code
stringlengths
12
2.05k
label_name
stringlengths
6
8
label
int64
0
95
public void setEntityResolver(EntityResolver entityResolver) { this.entityResolver = entityResolver; }
CWE-611
13
private TextBlock getTitleBlock(IGroup g) { final Display label = g.getDisplay(); if (label == null) return TextBlockUtils.empty(0, 0); final ISkinParam skinParam = dotData.getSkinParam(); final FontConfiguration fontConfiguration; if (UseStyle.useBetaStyle()) { final SName sname = dotData.getUmlDiagramType().getStyleName(); final StyleSignatureBasic signature; final USymbol uSymbol = g.getUSymbol(); if (uSymbol == USymbols.RECTANGLE) signature = StyleSignatureBasic.of(SName.root, SName.element, sname, uSymbol.getSName(), SName.title); else signature = StyleSignatureBasic.of(SName.root, SName.element, sname, SName.title); final Style style = signature // .withTOBECHANGED(g.getStereotype()) // .with(g.getStereostyles()) // .getMergedStyle(skinParam.getCurrentStyleBuilder()); fontConfiguration = style.getFontConfiguration(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); } else fontConfiguration = g.getFontConfigurationForTitle(skinParam); final HorizontalAlignment alignment = HorizontalAlignment.CENTER; return label.create(fontConfiguration, alignment, dotData.getSkinParam()); }
CWE-918
16
private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { String oldName = request.getParameter("groupName"); String newName = request.getParameter("newName"); if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) { m_groupRepository.renameGroup(oldName, newName); } return listGroups(request, response); }
CWE-79
1
private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { String oldName = request.getParameter("groupName"); String newName = request.getParameter("newName"); if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) { m_groupRepository.renameGroup(oldName, newName); } return listGroups(request, response); }
CWE-79
1
public <T> T toBean(Class<T> beanClass) { setTag(new Tag(beanClass)); if (getVersion() != null) { try { MigrationHelper.migrate(getVersion(), beanClass.newInstance(), this); removeVersion(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } return (T) new OneYaml().construct(this); }
CWE-502
15
private static String getOrderClause(Set<String> joinAliases, String alias, Order order) { String property = order.getProperty(); boolean qualifyReference = !property.contains("("); // ( indicates a function for (String joinAlias : joinAliases) { if (property.startsWith(joinAlias.concat("."))) { qualifyReference = false; break; } } String reference = qualifyReference && StringUtils.hasText(alias) ? String.format("%s.%s", alias, property) : property; String wrapped = order.isIgnoreCase() ? String.format("lower(%s)", reference) : reference; return String.format("%s %s", wrapped, toJpaDirection(order)); }
CWE-89
0
private void parse(UserRequest ureq) { String[] sFiles = ureq.getHttpReq().getParameterValues(FORM_ID); if (sFiles == null || sFiles.length == 0) return; files = Arrays.asList(sFiles); }
CWE-22
2
public void spliceToFile() throws Throwable { EventLoopGroup group = new EpollEventLoopGroup(1); File file = File.createTempFile("netty-splice", null); file.deleteOnExit(); SpliceHandler sh = new SpliceHandler(file); ServerBootstrap bs = new ServerBootstrap(); bs.channel(EpollServerSocketChannel.class); bs.group(group).childHandler(sh); bs.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); Channel sc = bs.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel(); Bootstrap cb = new Bootstrap(); cb.group(group); cb.channel(EpollSocketChannel.class); cb.handler(new ChannelInboundHandlerAdapter()); Channel cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel(); for (int i = 0; i < data.length;) { int length = Math.min(random.nextInt(1024 * 64), data.length - i); ByteBuf buf = Unpooled.wrappedBuffer(data, i, length); cc.writeAndFlush(buf); i += length; } while (sh.future2 == null || !sh.future2.isDone() || !sh.future.isDone()) { if (sh.exception.get() != null) { break; } try { Thread.sleep(50); } catch (InterruptedException e) { // Ignore. } } sc.close().sync(); cc.close().sync(); if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) { throw sh.exception.get(); } byte[] written = new byte[data.length]; FileInputStream in = new FileInputStream(file); try { Assert.assertEquals(written.length, in.read(written)); Assert.assertArrayEquals(data, written); } finally { in.close(); group.shutdownGracefully(); } }
CWE-378
80
public EfficiencyStatement getUserEfficiencyStatementByCourseRepositoryEntry(RepositoryEntry courseRepoEntry, Identity identity){ UserEfficiencyStatementImpl s = getUserEfficiencyStatementFull(courseRepoEntry, identity); if(s == null || s.getStatementXml() == null) { return null; } return (EfficiencyStatement)xstream.fromXML(s.getStatementXml()); }
CWE-91
78
public String getExecutable() { if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { return super.getExecutable(); } return unifyQuotes( super.getExecutable()); }
CWE-78
6
public XssHttpServletRequestWrapper(HttpServletRequest request) { super(request); }
CWE-79
1
protected int addFileNames(List<String> list) { // This appears to only be used by unit tests and the copy // constructor for (String file : list) { workUnitList.add(new WorkUnit(file)); } return size(); }
CWE-502
15
private void ondata(String data) { try { this.decoder.add(data); } catch (DecodingException e) { this.onerror(e); } }
CWE-476
46
final protected SymbolContext getContext() { if (UseStyle.useBetaStyle() == false) return getContextLegacy(); final Style style = getStyleSignature().getMergedStyle(skinParam.getCurrentStyleBuilder()); final HColor lineColor = style.value(PName.LineColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); final HColor backgroundColor = style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); return new SymbolContext(backgroundColor, lineColor).withStroke(getStroke()); }
CWE-918
16
void requestResetPasswordUnexistingUser() { when(this.userReference.toString()).thenReturn("user:Foobar"); when(this.userManager.exists(this.userReference)).thenReturn(false); String exceptionMessage = "User [user:Foobar] doesn't exist"; when(this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.noUser", "user:Foobar")).thenReturn(exceptionMessage); ResetPasswordException resetPasswordException = assertThrows(ResetPasswordException.class, () -> this.resetPasswordManager.requestResetPassword(this.userReference)); assertEquals(exceptionMessage, resetPasswordException.getMessage()); }
CWE-640
20
public Claims validateToken(String token) throws AuthenticationException { try { RsaKeyUtil rsaKeyUtil = new RsaKeyUtil(); PublicKey publicKey = rsaKeyUtil.fromPemEncoded(keycloakPublicKey); return Jwts.parser().setSigningKey(publicKey).parseJws(token.replace("Bearer ", "")).getBody(); } catch (Exception e){ throw new AuthenticationException(String.format("Failed to check user authorization for token: %s", token), e); } }
CWE-290
85
public void doFilter(ServletRequest srequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { /* HttpServletRequest request = (HttpServletRequest) srequest; //final String realIp = request.getHeader(X_FORWARDED_FOR); //if (realIp != null) { filterChain.doFilter(new XssHttpServletRequestWrapper(request) { *//** public String getRemoteAddr() { return realIp; } public String getRemoteHost() { return realIp; } **//* }, response); return; //} */ }
CWE-79
1
private Runnable getDiscoveryRequestSetup(final String url) { return new Runnable() { public void run() { expect(request.getHeader("Origin")).andStubReturn(null); expect(request.getHeader("Referer")).andStubReturn(null); expect(request.getRemoteHost()).andReturn("localhost"); expect(request.getRemoteAddr()).andReturn("127.0.0.1"); expect(request.getRequestURI()).andReturn("/jolokia/"); expect(request.getParameterMap()).andReturn(null); expect(request.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE)).andReturn(null); expect(request.getPathInfo()).andReturn(HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getParameter(ConfigKey.MIME_TYPE.getKeyValue())).andReturn("text/plain"); StringBuffer buf = new StringBuffer(); buf.append(url).append(HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getRequestURL()).andReturn(buf); expect(request.getRequestURI()).andReturn("/jolokia" + HttpTestUtil.HEAP_MEMORY_GET_REQUEST); expect(request.getContextPath()).andReturn("/jolokia"); expect(request.getAuthType()).andReturn("BASIC"); expect(request.getAttribute("subject")).andReturn(null); expect(request.getParameter(ConfigKey.STREAMING.getKeyValue())).andReturn(null); } }; }
CWE-79
1
protected SAXContentHandler createContentHandler(XMLReader reader) { return new SAXContentHandler(getDocumentFactory(), dispatchHandler); }
CWE-611
13
final protected CommandExecutionResult executeArg(TimingDiagram diagram, LineLocation location, RegexResult arg) { final String compact = arg.get("COMPACT", 0); final String code = arg.get("CODE", 0); String full = arg.get("FULL", 0); if (full == null) { full = code; } final TimingStyle type = TimingStyle.valueOf(arg.get("TYPE", 0).toUpperCase()); return diagram.createRobustConcise(code, full, type, compact != null); }
CWE-918
16
public static String printFormattedMetadata(final IBaseDataObject payload) { final StringBuilder out = new StringBuilder(); out.append(LS); for (final Map.Entry<String, Collection<Object>> entry : payload.getParameters().entrySet()) { out.append(entry.getKey() + SEP + entry.getValue() + LS); } return out.toString(); }
CWE-502
15
public static void closeSubsequentFS(Path path) { if(path != null && FileSystems.getDefault() != path.getFileSystem()) { IOUtils.closeQuietly(path.getFileSystem()); } }
CWE-22
2
public Document read(Reader reader) throws DocumentException { InputSource source = new InputSource(reader); if (this.encoding != null) { source.setEncoding(this.encoding); } return read(source); }
CWE-611
13
final protected Style getStyle() { return getStyleSignature().getMergedStyle(skinParam.getCurrentStyleBuilder()); }
CWE-918
16
protected final boolean loadMore() throws IOException { if (_inputStream != null) { _currInputProcessed += _inputEnd; int count = _inputStream.read(_inputBuffer, 0, _inputBuffer.length); if (count > 0) { _inputPtr = 0; _inputEnd = count; return true; } // End of input _closeInput(); // Should never return 0, so let's fail if (count == 0) { throw new IOException("InputStream.read() returned 0 characters when trying to read "+_inputBuffer.length+" bytes"); } } return false; }
CWE-770
37
void sendResetPasswordEmailRequest() throws Exception { when(this.referenceSerializer.serialize(this.userReference)).thenReturn("user:Foobar"); when(this.userProperties.getFirstName()).thenReturn("Foo"); when(this.userProperties.getLastName()).thenReturn("Bar"); AuthenticationResourceReference resourceReference = new AuthenticationResourceReference(AuthenticationAction.RESET_PASSWORD); String verificationCode = "foobar4242"; resourceReference.addParameter("u", "user:Foobar"); resourceReference.addParameter("v", verificationCode); ExtendedURL firstExtendedURL = new ExtendedURL(Arrays.asList("authenticate", "reset"), resourceReference.getParameters()); when(this.resourceReferenceSerializer.serialize(resourceReference)).thenReturn(firstExtendedURL); when(this.urlNormalizer.normalize(firstExtendedURL)).thenReturn( new ExtendedURL(Arrays.asList("xwiki", "authenticate", "reset"), resourceReference.getParameters()) ); XWikiURLFactory urlFactory = mock(XWikiURLFactory.class); when(this.context.getURLFactory()).thenReturn(urlFactory); when(urlFactory.getServerURL(this.context)).thenReturn(new URL("http://xwiki.org")); InternetAddress email = new InternetAddress("[email protected]"); DefaultResetPasswordRequestResponse requestResponse = new DefaultResetPasswordRequestResponse(this.userReference, email, verificationCode); this.resetPasswordManager.sendResetPasswordEmailRequest(requestResponse); verify(this.resetPasswordMailSender).sendResetPasswordEmail("Foo Bar", email, new URL("http://xwiki.org/xwiki/authenticate/reset?u=user%3AFoobar&v=foobar4242")); }
CWE-640
20
void allReservedCharacters() { final PathAndQuery res = PathAndQuery.parse("/#/:[]@!$&'()*+,;=?a=/#/:[]@!$&'()*+,;="); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/#/:[]@!$&'()*+,;="); assertThat(res.query()).isEqualTo("a=/#/:[]@!$&'()*+,;="); final PathAndQuery res2 = PathAndQuery.parse("/%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F" + "?a=%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F"); assertThat(res2).isNotNull(); assertThat(res2.path()).isEqualTo("/#%2F:[]@!$&'()*+,;=?"); assertThat(res2.query()).isEqualTo("a=%23%2F%3A%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%3F"); }
CWE-22
2
public void testBourneShellQuotingCharacters() throws Exception { // { ' ', '$', ';', '&', '|', '<', '>', '*', '?', '(', ')' }; // test with values http://steve-parker.org/sh/bourne.shtml Appendix B - Meta-characters and Reserved Words Commandline commandline = new Commandline( newShell() ); commandline.setExecutable( "chmod" ); commandline.getShell().setQuotedArgumentsEnabled( true ); commandline.createArg().setValue( " " ); commandline.createArg().setValue( "|" ); commandline.createArg().setValue( "&&" ); commandline.createArg().setValue( "||" ); commandline.createArg().setValue( ";" ); commandline.createArg().setValue( ";;" ); commandline.createArg().setValue( "&" ); commandline.createArg().setValue( "()" ); commandline.createArg().setValue( "<" ); commandline.createArg().setValue( "<<" ); commandline.createArg().setValue( ">" ); commandline.createArg().setValue( ">>" ); commandline.createArg().setValue( "*" ); commandline.createArg().setValue( "?" ); commandline.createArg().setValue( "[" ); commandline.createArg().setValue( "]" ); commandline.createArg().setValue( "{" ); commandline.createArg().setValue( "}" ); commandline.createArg().setValue( "`" ); String[] lines = commandline.getShellCommandline(); System.out.println( Arrays.asList( lines ) ); assertEquals( "/bin/sh", lines[0] ); assertEquals( "-c", lines[1] ); assertEquals( "chmod ' ' '|' '&&' '||' ';' ';;' '&' '()' '<' '<<' '>' '>>' '*' '?' '[' ']' '{' '}' '`'", lines[2] ); }
CWE-78
6
private ModelAndView renameGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { String oldName = request.getParameter("groupName"); String newName = request.getParameter("newName"); if (StringUtils.hasText(oldName) && StringUtils.hasText(newName)) { m_groupRepository.renameGroup(oldName, newName); } return listGroups(request, response); }
CWE-79
1
private void testKeyFactory(ECPublicKey pub, ECPrivateKey priv) throws Exception { KeyFactory ecFact = KeyFactory.getInstance("ECDSA"); ECPublicKeySpec pubSpec = (ECPublicKeySpec)ecFact.getKeySpec(pub, ECPublicKeySpec.class); ECPrivateKeySpec privSpec = (ECPrivateKeySpec)ecFact.getKeySpec(priv, ECPrivateKeySpec.class); if (!pubSpec.getW().equals(pub.getW()) || !pubSpec.getParams().getCurve().equals(pub.getParams().getCurve())) { fail("pubSpec not correct"); } if (!privSpec.getS().equals(priv.getS()) || !privSpec.getParams().getCurve().equals(priv.getParams().getCurve())) { fail("privSpec not correct"); } ECPublicKey pubKey = (ECPublicKey)ecFact.translateKey(pub); ECPrivateKey privKey = (ECPrivateKey)ecFact.translateKey(priv); if (!pubKey.getW().equals(pub.getW()) || !pubKey.getParams().getCurve().equals(pub.getParams().getCurve())) { fail("pubKey not correct"); } if (!privKey.getS().equals(priv.getS()) || !privKey.getParams().getCurve().equals(priv.getParams().getCurve())) { fail("privKey not correct"); } }
CWE-347
25
private Template getClassloaderTemplate(ClassLoader classloader, String suffixPath, String templateName) { String templatePath = suffixPath + templateName; URL url = classloader.getResource(templatePath); return url != null ? new ClassloaderTemplate(new ClassloaderResource(url, templateName)) : null; }
CWE-22
2
void requestResetPasswordNoEmail() throws Exception { when(this.userManager.exists(this.userReference)).thenReturn(true); String exceptionMessage = "User has no email address."; when(this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.noEmail")) .thenReturn(exceptionMessage); ResetPasswordException resetPasswordException = assertThrows(ResetPasswordException.class, () -> this.resetPasswordManager.requestResetPassword(this.userReference)); assertEquals(exceptionMessage, resetPasswordException.getMessage()); }
CWE-640
20
private static boolean pathContainsDoubleDots(Bytes path) { final int length = path.length; byte b0 = 0; byte b1 = 0; byte b2 = '/'; for (int i = 1; i < length; i++) { final byte b3 = path.data[i]; if (b3 == '/' && b2 == '.' && b1 == '.' && b0 == '/') { return true; } b0 = b1; b1 = b2; b2 = b3; } return b0 == '/' && b1 == '.' && b2 == '.'; }
CWE-22
2
public void testWrapMemoryMapped() throws Exception { File file = File.createTempFile("netty-test", "tmp"); FileChannel output = null; FileChannel input = null; ByteBuf b1 = null; ByteBuf b2 = null; try { output = new RandomAccessFile(file, "rw").getChannel(); byte[] bytes = new byte[1024]; PlatformDependent.threadLocalRandom().nextBytes(bytes); output.write(ByteBuffer.wrap(bytes)); input = new RandomAccessFile(file, "r").getChannel(); ByteBuffer m = input.map(FileChannel.MapMode.READ_ONLY, 0, input.size()); b1 = buffer(m); ByteBuffer dup = m.duplicate(); dup.position(2); dup.limit(4); b2 = buffer(dup); Assert.assertEquals(b2, b1.slice(2, 2)); } finally { if (b1 != null) { b1.release(); } if (b2 != null) { b2.release(); } if (output != null) { output.close(); } if (input != null) { input.close(); } file.delete(); } }
CWE-379
83
public static Document toXml(final List<IBaseDataObject> list) { final Element root = new Element("payload-list"); for (final IBaseDataObject d : list) { final Document doc = toXml(d); root.addContent(doc.detachRootElement()); logger.debug("Adding xml content for " + d.shortName() + " to document"); } final Document doc = new Document(root); return doc; }
CWE-502
15
private Document parseXml(String xmlContent) { try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(xmlContent))); document.getDocumentElement().normalize(); return document; } catch (Exception e) { throw new JadxRuntimeException("Can not parse xml content", e); } }
CWE-611
13
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultResetPasswordRequestResponse that = (DefaultResetPasswordRequestResponse) o; return new EqualsBuilder() .append(userReference, that.userReference) .append(userEmail, that.userEmail) .append(verificationCode, that.verificationCode) .isEquals(); }
CWE-640
20
public void initWithcustomAccessRestrictor() throws ServletException { prepareStandardInitialisation(); servlet.destroy(); }
CWE-79
1
private static File newFile() throws IOException { File file = File.createTempFile("netty-", ".tmp"); file.deleteOnExit(); final FileOutputStream out = new FileOutputStream(file); out.write(data); out.close(); return file; }
CWE-378
80
public void clientIdChanged(ClientModel client, String newClientId) { logger.debugf("Updating clientId from '%s' to '%s'", client.getClientId(), newClientId); UserModel serviceAccountUser = realmManager.getSession().users().getServiceAccount(client); if (serviceAccountUser != null) { String username = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + newClientId; serviceAccountUser.setUsername(username); serviceAccountUser.setEmail(username + "@placeholder.org"); } }
CWE-798
18
public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (keySpec == null) { // The key is not set yet - return the plaintext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); return length; } if (space < 16 || length > (space - 16)) throw new ShortBufferException(); try { setup(ad); int result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset); cipher.doFinal(ciphertext, ciphertextOffset + result); } catch (InvalidKeyException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (InvalidAlgorithmParameterException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (IllegalBlockSizeException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (BadPaddingException e) { // Shouldn't happen. throw new IllegalStateException(e); } ghash.update(ciphertext, ciphertextOffset, length); ghash.pad(ad != null ? ad.length : 0, length); ghash.finish(ciphertext, ciphertextOffset + length, 16); for (int index = 0; index < 16; ++index) ciphertext[ciphertextOffset + length + index] ^= hashKey[index]; return length + 16; }
CWE-125
47
public static byte[] serializeToBytes(final Object payload) throws IOException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); serializeToStream(bos, payload); return bos.toByteArray(); }
CWE-502
15
public boolean importWiki(File file, String filename, File targetDirectory) { try { Path path = FileResource.getResource(file, filename); if(path == null) { return false; } Path destDir = targetDirectory.toPath(); Files.walkFileTree(path, new ImportVisitor(destDir)); PathUtils.closeSubsequentFS(path); return true; } catch (IOException e) { log.error("", e); return false; } }
CWE-22
2
public XMLReader getXMLReader() throws SAXException { if (xmlReader == null) { xmlReader = createXMLReader(); } return xmlReader; }
CWE-611
13
public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (keySpec == null) { // The key is not set yet - return the plaintext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); return length; } if (space < 16 || length > (space - 16)) throw new ShortBufferException(); try { setup(ad); int result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset); cipher.doFinal(ciphertext, ciphertextOffset + result); } catch (InvalidKeyException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (InvalidAlgorithmParameterException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (IllegalBlockSizeException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (BadPaddingException e) { // Shouldn't happen. throw new IllegalStateException(e); } ghash.update(ciphertext, ciphertextOffset, length); ghash.pad(ad != null ? ad.length : 0, length); ghash.finish(ciphertext, ciphertextOffset + length, 16); for (int index = 0; index < 16; ++index) ciphertext[ciphertextOffset + length + index] ^= hashKey[index]; return length + 16; }
CWE-787
24
protected BigDecimal bcdToBigDecimal() { if (usingBytes) { // Converting to a string here is faster than doing BigInteger/BigDecimal arithmetic. BigDecimal result = new BigDecimal(toNumberString()); if (isNegative()) { result = result.negate(); } return result; } else { long tempLong = 0L; for (int shift = (precision - 1); shift >= 0; shift--) { tempLong = tempLong * 10 + getDigitPos(shift); } BigDecimal result = BigDecimal.valueOf(tempLong); result = result.scaleByPowerOfTen(scale); if (isNegative()) result = result.negate(); return result; } }
CWE-190
19
public PersistentTask updateTask(Task task, Serializable runnableTask, Identity modifier, Date scheduledDate) { PersistentTask ptask = dbInstance.getCurrentEntityManager() .find(PersistentTask.class, task.getKey(), LockModeType.PESSIMISTIC_WRITE); if(ptask != null) { ptask.setLastModified(new Date()); ptask.setScheduledDate(scheduledDate); ptask.setStatus(TaskStatus.newTask); ptask.setStatusBeforeEditStr(null); ptask.setTask(xstream.toXML(runnableTask)); ptask = dbInstance.getCurrentEntityManager().merge(ptask); if(modifier != null) { //add to the list of modifier PersistentTaskModifier mod = new PersistentTaskModifier(); mod.setCreationDate(new Date()); mod.setModifier(modifier); mod.setTask(ptask); dbInstance.getCurrentEntityManager().persist(mod); } dbInstance.commit(); } return ptask; }
CWE-91
78
public SAXReader(DocumentFactory factory, boolean validating) { this.factory = factory; this.validating = validating; }
CWE-611
13
private final HColor getBackColor(UmlDiagramType umlDiagramType, Style style) { if (EntityUtils.groupRoot(group)) return null; final HColor result = group.getColors().getColor(ColorType.BACK); if (result != null) return result; final Stereotype stereo = group.getStereotype(); if (UseStyle.useBetaStyle()) return style.value(PName.BackGroundColor).asColor(skinParam.getThemeStyle(), skinParam.getIHtmlColorSet()); final USymbol sym = group.getUSymbol() == null ? USymbols.PACKAGE : group.getUSymbol(); final ColorParam backparam = umlDiagramType == UmlDiagramType.ACTIVITY ? ColorParam.partitionBackground : sym.getColorParamBack(); final HColor c1 = skinParam.getHtmlColor(backparam, stereo, false); if (c1 != null) return c1; if (parentCluster == null) return null; return parentCluster.getBackColor(umlDiagramType, style); }
CWE-918
16
public XssHttpServletRequestWrapper(HttpServletRequest request) { super(request); }
CWE-79
1
public static String decodePath(String path) { if (path.indexOf('%') < 0) { // No need to decoded; not percent-encoded return path; } // Decode percent-encoded characters. // An invalid character is replaced with 0xFF, which will be replaced into '�' by UTF-8 decoder. final int len = path.length(); try (TemporaryThreadLocals tempThreadLocals = TemporaryThreadLocals.acquire()) { final byte[] buf = tempThreadLocals.byteArray(len); int dstLen = 0; for (int i = 0; i < len; i++) { final char ch = path.charAt(i); if (ch != '%') { buf[dstLen++] = (byte) ((ch & 0xFF80) == 0 ? ch : 0xFF); continue; } // Decode a percent-encoded character. final int hexEnd = i + 3; if (hexEnd > len) { // '%' or '%x' (must be followed by two hexadigits) buf[dstLen++] = (byte) 0xFF; break; } final int digit1 = decodeHexNibble(path.charAt(++i)); final int digit2 = decodeHexNibble(path.charAt(++i)); if (digit1 < 0 || digit2 < 0) { // The first or second digit is not hexadecimal. buf[dstLen++] = (byte) 0xFF; } else { buf[dstLen++] = (byte) ((digit1 << 4) | digit2); } } return new String(buf, 0, dstLen, StandardCharsets.UTF_8); } }
CWE-22
2
public void saveCustomConfigAndCompileCSS(Map<String, Map<String, Object>> customConfig, CourseEnvironment courseEnvironment){ VFSContainer themeBase = null; VFSContainer base = null; base = (VFSContainer) courseEnvironment.getCourseBaseContainer().resolve(CourseLayoutHelper.LAYOUT_COURSE_SUBFOLDER); if (base == null) { base = courseEnvironment.getCourseBaseContainer().createChildContainer(CourseLayoutHelper.LAYOUT_COURSE_SUBFOLDER); } themeBase = (VFSContainer) base.resolve("/" + CourseLayoutHelper.CONFIG_KEY_CUSTOM); if (themeBase == null) { themeBase = base.createChildContainer(CourseLayoutHelper.CONFIG_KEY_CUSTOM); } VFSLeaf configTarget = (VFSLeaf) themeBase.resolve(CUSTOM_CONFIG_XML); if (configTarget == null) { configTarget = themeBase.createChildLeaf(CUSTOM_CONFIG_XML); } XStream xStream = XStreamHelper.createXStreamInstance(); xStream.toXML(customConfig, configTarget.getOutputStream(false)); // compile the css-files StringBuilder sbMain = new StringBuilder(); StringBuilder sbIFrame = new StringBuilder(); for (Entry<String, Map<String, Object>> iterator : customConfig.entrySet()) { String type = iterator.getKey(); Map<String, Object> elementConfig = iterator.getValue(); AbstractLayoutElement configuredLayEl = createLayoutElementByType(type, elementConfig); sbIFrame.append(configuredLayEl.getCSSForIFrame()); sbMain.append(configuredLayEl.getCSSForMain()); } // attach line for logo, if there is any to cssForMain: appendLogoPart(sbMain, themeBase); VFSLeaf mainFile = (VFSLeaf) themeBase.resolve(MAIN_CSS); if (mainFile == null) mainFile = themeBase.createChildLeaf(MAIN_CSS); VFSLeaf iFrameFile = (VFSLeaf) themeBase.resolve(IFRAME_CSS); if (iFrameFile == null) iFrameFile = themeBase.createChildLeaf(IFRAME_CSS); FileUtils.save(mainFile.getOutputStream(false), sbMain.toString(), "utf-8"); FileUtils.save(iFrameFile.getOutputStream(false), sbIFrame.toString(), "utf-8"); }
CWE-91
78
setStringInputSource(ThreadContext context, IRubyObject data, IRubyObject url) { source = new InputSource(); ParserContext.setUrl(context, source, url); Ruby ruby = context.getRuntime(); if (!(data instanceof RubyString)) { throw ruby.newArgumentError("must be kind_of String"); } RubyString stringData = (RubyString) data; if (stringData.encoding(context) != null) { RubyString stringEncoding = stringData.encoding(context).asString(); String encName = NokogiriHelpers.getValidEncodingOrNull(stringEncoding); if (encName != null) { java_encoding = encName; } } ByteList bytes = stringData.getByteList(); stringDataSize = bytes.length() - bytes.begin(); ByteArrayInputStream stream = new ByteArrayInputStream(bytes.unsafeBytes(), bytes.begin(), bytes.length()); source.setByteStream(stream); source.setEncoding(java_encoding); }
CWE-241
68
public TMap readMapBegin() throws TException { int size = readVarint32(); byte keyAndValueType = size == 0 ? 0 : readByte(); return new TMap( getTType((byte) (keyAndValueType >> 4)), getTType((byte) (keyAndValueType & 0xf)), size); }
CWE-770
37
public Response attachTaskFile(@PathParam("courseId") Long courseId, @PathParam("nodeId") String nodeId, @Context HttpServletRequest request) { ICourse course = CoursesWebService.loadCourse(courseId); CourseEditorTreeNode parentNode = getParentNode(course, nodeId); if(course == null) { return Response.serverError().status(Status.NOT_FOUND).build(); } if(parentNode == null) { return Response.serverError().status(Status.NOT_FOUND).build(); } else if(!(parentNode.getCourseNode() instanceof TACourseNode)) { return Response.serverError().status(Status.NOT_ACCEPTABLE).build(); } if (!isAuthorEditor(course, request)) { return Response.serverError().status(Status.UNAUTHORIZED).build(); } InputStream in = null; MultipartReader reader = null; try { reader = new MultipartReader(request); String filename = reader.getValue("filename", "task"); String taskFolderPath = TACourseNode.getTaskFolderPathRelToFolderRoot(course, parentNode.getCourseNode()); VFSContainer taskFolder = VFSManager.olatRootContainer(taskFolderPath, null); VFSLeaf singleFile = (VFSLeaf) taskFolder.resolve("/" + filename); if (singleFile == null) { singleFile = taskFolder.createChildLeaf("/" + filename); } File file = reader.getFile(); if(file != null) { in = new FileInputStream(file); OutputStream out = singleFile.getOutputStream(false); IOUtils.copy(in, out); IOUtils.closeQuietly(out); } else { return Response.status(Status.NOT_ACCEPTABLE).build(); } } catch (Exception e) { log.error("", e); return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); } finally { MultipartReader.closeQuietly(reader); IOUtils.closeQuietly(in); } return Response.ok().build(); }
CWE-22
2
void plus() { final PathAndQuery res = PathAndQuery.parse("/+?a+b=c+d"); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/+"); assertThat(res.query()).isEqualTo("a+b=c+d"); final PathAndQuery res2 = PathAndQuery.parse("/%2b?a%2bb=c%2bd"); assertThat(res2).isNotNull(); assertThat(res2.path()).isEqualTo("/+"); assertThat(res2.query()).isEqualTo("a%2Bb=c%2Bd"); }
CWE-22
2
public TSet readSetBegin() throws TException { return new TSet(readByte(), readI32()); }
CWE-770
37
private Template getClassloaderTemplate(String suffixPath, String templateName) { return getClassloaderTemplate(Thread.currentThread().getContextClassLoader(), suffixPath, templateName); }
CWE-22
2
final protected CommandExecutionResult executeArg(TimingDiagram diagram, LineLocation location, RegexResult arg) { final String compact = arg.get("COMPACT", 0); final String code = arg.get("CODE", 0); final String full = arg.get("FULL", 0); return diagram.createBinary(code, full, compact != null); }
CWE-918
16
public void configure(ICourse course, CourseNode newNode, ModuleConfiguration moduleConfig) { if(displayType != null && (STCourseNodeEditController.CONFIG_VALUE_DISPLAY_TOC.equals(displayType) || STCourseNodeEditController.CONFIG_VALUE_DISPLAY_PEEKVIEW.equals(displayType) || STCourseNodeEditController.CONFIG_VALUE_DISPLAY_FILE.equals(displayType))) { moduleConfig.setStringValue(STCourseNodeEditController.CONFIG_KEY_DISPLAY_TYPE, displayType); } if(STCourseNodeEditController.CONFIG_VALUE_DISPLAY_FILE.equals(moduleConfig.getStringValue(STCourseNodeEditController.CONFIG_KEY_DISPLAY_TYPE))) { if(in != null && StringHelper.containsNonWhitespace(filename)) { VFSContainer rootContainer = course.getCourseFolderContainer(); VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve("/" + filename); if (singleFile == null) { singleFile = rootContainer.createChildLeaf("/" + filename); } moduleConfig.set(STCourseNodeEditController.CONFIG_KEY_FILE, "/" + filename); OutputStream out = singleFile.getOutputStream(false); FileUtils.copy(in, out); FileUtils.closeSafely(out); FileUtils.closeSafely(in); } else if (StringHelper.containsNonWhitespace(filename)) { VFSContainer rootContainer = course.getCourseFolderContainer(); VFSLeaf singleFile = (VFSLeaf) rootContainer.resolve("/" + filename); if(singleFile != null) { moduleConfig.set(STCourseNodeEditController.CONFIG_KEY_FILE, "/" + filename); } } } }
CWE-22
2
public static final void testClosedArray() { // Discovered by fuzzer with seed -Dfuzz.seed=df3b4778ce54d00a assertSanitized("-1742461140214282", "\ufeff-01742461140214282]"); }
CWE-611
13
void semicolon() { final PathAndQuery res = PathAndQuery.parse("/;?a=b;c=d"); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo("/;"); assertThat(res.query()).isEqualTo("a=b;c=d"); // '%3B' in a query string should never be decoded into ';'. final PathAndQuery res2 = PathAndQuery.parse("/%3b?a=b%3Bc=d"); assertThat(res2).isNotNull(); assertThat(res2.path()).isEqualTo("/;"); assertThat(res2.query()).isEqualTo("a=b%3Bc=d"); }
CWE-22
2
public RefUpdated uploadFiles(Collection<FileUpload> uploads, String directory, String commitMessage) { Map<String, BlobContent> newBlobs = new HashMap<>(); String parentPath = getDirectory(); if (directory != null) { if (parentPath != null) parentPath += "/" + directory; else parentPath = directory; } User user = Preconditions.checkNotNull(SecurityUtils.getUser()); BlobIdent blobIdent = getBlobIdent(); for (FileUpload upload: uploads) { String blobPath = upload.getClientFileName(); if (parentPath != null) blobPath = parentPath + "/" + blobPath; if (getProject().isReviewRequiredForModification(user, blobIdent.revision, blobPath)) throw new BlobEditException("Review required for this change. Please submit pull request instead"); else if (getProject().isBuildRequiredForModification(user, blobIdent.revision, blobPath)) throw new BlobEditException("Build required for this change. Please submit pull request instead"); BlobContent blobContent = new BlobContent.Immutable(upload.getBytes(), FileMode.REGULAR_FILE); newBlobs.put(blobPath, blobContent); } BlobEdits blobEdits = new BlobEdits(Sets.newHashSet(), newBlobs); String refName = blobIdent.revision!=null?GitUtils.branch2ref(blobIdent.revision):"refs/heads/master"; ObjectId prevCommitId; if (blobIdent.revision != null) prevCommitId = getProject().getRevCommit(blobIdent.revision, true).copy(); else prevCommitId = ObjectId.zeroId(); while (true) { try { ObjectId newCommitId = blobEdits.commit(getProject().getRepository(), refName, prevCommitId, prevCommitId, user.asPerson(), commitMessage); return new RefUpdated(getProject(), refName, prevCommitId, newCommitId); } catch (ObjectAlreadyExistsException|NotTreeException e) { throw new BlobEditException(e.getMessage()); } catch (ObsoleteCommitException e) { prevCommitId = e.getOldCommitId(); } } }
CWE-434
5
public boolean isStringInternEnabled() { return stringInternEnabled; }
CWE-611
13
protected void onStart() { super.onStart(); Intent intent = getIntent(); intent.putExtra( SettingsActivity.SP_FEED_LIST_LAYOUT, mPrefs.getString(SettingsActivity.SP_FEED_LIST_LAYOUT, "0") ); setResult(RESULT_OK,intent); }
CWE-829
86
public void testReadBytesAndWriteBytesWithFileChannel() throws IOException { File file = File.createTempFile("file-channel", ".tmp"); RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(file, "rw"); FileChannel channel = randomAccessFile.getChannel(); // channelPosition should never be changed long channelPosition = channel.position(); byte[] bytes = {'a', 'b', 'c', 'd'}; int len = bytes.length; ByteBuf buffer = newBuffer(len); buffer.resetReaderIndex(); buffer.resetWriterIndex(); buffer.writeBytes(bytes); int oldReaderIndex = buffer.readerIndex(); assertEquals(len, buffer.readBytes(channel, 10, len)); assertEquals(oldReaderIndex + len, buffer.readerIndex()); assertEquals(channelPosition, channel.position()); ByteBuf buffer2 = newBuffer(len); buffer2.resetReaderIndex(); buffer2.resetWriterIndex(); int oldWriterIndex = buffer2.writerIndex(); assertEquals(len, buffer2.writeBytes(channel, 10, len)); assertEquals(channelPosition, channel.position()); assertEquals(oldWriterIndex + len, buffer2.writerIndex()); assertEquals('a', buffer2.getByte(0)); assertEquals('b', buffer2.getByte(1)); assertEquals('c', buffer2.getByte(2)); assertEquals('d', buffer2.getByte(3)); buffer.release(); buffer2.release(); } finally { if (randomAccessFile != null) { randomAccessFile.close(); } file.delete(); } }
CWE-378
80
public void testMatchTwoTypes() { JWKMatcher matcher = new JWKMatcher.Builder().keyTypes(KeyType.RSA, KeyType.EC).build(); assertTrue(matcher.matches(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").build())); assertTrue(matcher.matches(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build())); assertEquals("kty=[RSA, EC]", matcher.toString()); }
CWE-347
25
public int decryptWithAd(byte[] ad, byte[] ciphertext, int ciphertextOffset, byte[] plaintext, int plaintextOffset, int length) throws ShortBufferException, BadPaddingException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (length > space) throw new ShortBufferException(); if (plaintextOffset > plaintext.length) space = 0; else space = plaintext.length - plaintextOffset; if (!haskey) { // The key is not set yet - return the ciphertext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length); return length; } if (length < 16) Noise.throwBadTagException(); int dataLen = length - 16; if (dataLen > space) throw new ShortBufferException(); setup(ad); ghash.update(ciphertext, ciphertextOffset, dataLen); ghash.pad(ad != null ? ad.length : 0, dataLen); ghash.finish(enciv, 0, 16); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (hashKey[index] ^ enciv[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); encryptCTR(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen); return dataLen; }
CWE-125
47
public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (!haskey) { // The key is not set yet - return the plaintext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); return length; } if (space < 16 || length > (space - 16)) throw new ShortBufferException(); setup(ad); encrypt(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); poly.update(ciphertext, ciphertextOffset, length); finish(ad, length); System.arraycopy(polyKey, 0, ciphertext, ciphertextOffset + length, 16); return length + 16; }
CWE-125
47
public void testGetBytesAndSetBytesWithFileChannel() throws IOException { File file = File.createTempFile("file-channel", ".tmp"); RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(file, "rw"); FileChannel channel = randomAccessFile.getChannel(); // channelPosition should never be changed long channelPosition = channel.position(); byte[] bytes = {'a', 'b', 'c', 'd'}; int len = bytes.length; ByteBuf buffer = newBuffer(len); buffer.resetReaderIndex(); buffer.resetWriterIndex(); buffer.writeBytes(bytes); int oldReaderIndex = buffer.readerIndex(); assertEquals(len, buffer.getBytes(oldReaderIndex, channel, 10, len)); assertEquals(oldReaderIndex, buffer.readerIndex()); assertEquals(channelPosition, channel.position()); ByteBuf buffer2 = newBuffer(len); buffer2.resetReaderIndex(); buffer2.resetWriterIndex(); int oldWriterIndex = buffer2.writerIndex(); assertEquals(buffer2.setBytes(oldWriterIndex, channel, 10, len), len); assertEquals(channelPosition, channel.position()); assertEquals(oldWriterIndex, buffer2.writerIndex()); assertEquals('a', buffer2.getByte(oldWriterIndex)); assertEquals('b', buffer2.getByte(oldWriterIndex + 1)); assertEquals('c', buffer2.getByte(oldWriterIndex + 2)); assertEquals('d', buffer2.getByte(oldWriterIndex + 3)); buffer.release(); buffer2.release(); } finally { if (randomAccessFile != null) { randomAccessFile.close(); } file.delete(); } }
CWE-379
83
private void saveToFile(VFSLeaf glossaryFile, List<GlossaryItem> glossaryItemArr) { // cdata-tags should be used instead of strings, overwrite writer. glossaryItemArr = removeEmptyGlossaryItems(glossaryItemArr); XStreamHelper.writeObject(xstreamWriter, glossaryFile, glossaryItemArr); }
CWE-91
78
private XMLGregorianCalendar toXMLGregorianCalendar(ZonedDateTime instant) { if (instant == null) { return null; } return new XMLGregorianCalendarImpl(GregorianCalendar.from(instant)); }
CWE-611
13
public int addFileName(String file) { workUnitList.add(new WorkUnit(file)); return size(); }
CWE-502
15
public OutputStream getOutputStream(boolean append) { return null; }
CWE-91
78
public void testGetShellCommandLineBash() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( "/bin/echo" ); cmd.addArguments( new String[] { "hello world" } ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( "Command line size", 3, shellCommandline.length ); assertEquals( "/bin/sh", shellCommandline[0] ); assertEquals( "-c", shellCommandline[1] ); String expectedShellCmd = "/bin/echo \'hello world\'"; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { expectedShellCmd = "\\bin\\echo \'hello world\'"; } assertEquals( expectedShellCmd, shellCommandline[2] ); }
CWE-78
6
public static File createTempFile(String prefix, String suffix, File directory) throws IOException { if (javaVersion() >= 7) { if (directory == null) { return Files.createTempFile(prefix, suffix).toFile(); } return Files.createTempFile(directory.toPath(), prefix, suffix).toFile(); } if (directory == null) { return File.createTempFile(prefix, suffix); } File file = File.createTempFile(prefix, suffix, directory); // Try to adjust the perms, if this fails there is not much else we can do... file.setReadable(false, false); file.setReadable(true, true); return file; }
CWE-379
83
public void testSelectByType() { JWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyType(KeyType.RSA).build()); List<JWK> keyList = new ArrayList<>(); keyList.add(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").build()); keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()); JWKSet jwkSet = new JWKSet(keyList); List<JWK> matches = selector.select(jwkSet); RSAKey key1 = (RSAKey)matches.get(0); assertEquals(KeyType.RSA, key1.getKeyType()); assertEquals("1", key1.getKeyID()); assertEquals(1, matches.size()); }
CWE-347
25
protected SymbolContext getContextLegacy() { return new SymbolContext(HColorUtils.COL_D7E0F2, HColorUtils.COL_038048).withStroke(new UStroke(1.5)); }
CWE-918
16
protected StyleSignatureBasic getStyleSignature() { if (type == TimingStyle.CONCISE) return StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram, SName.concise); if (type == TimingStyle.ROBUST) return StyleSignatureBasic.of(SName.root, SName.element, SName.timingDiagram, SName.robust); throw new IllegalStateException(); }
CWE-918
16
private ZonedDateTime toZonedDateTime(XMLGregorianCalendar instant) { if (instant == null) { return null; } return instant.toGregorianCalendar().toZonedDateTime(); }
CWE-611
13
private List<GlossaryItem> loadGlossaryItemListFromFile(VFSLeaf glossaryFile) { List<GlossaryItem> glossaryItemList = new ArrayList<>(); if (glossaryFile == null) { return new ArrayList<>(); } Object glossObj = XStreamHelper.readObject(xstreamReader, glossaryFile); if (glossObj instanceof ArrayList) { ArrayList<GlossaryItem> glossItemsFromFile = (ArrayList<GlossaryItem>) glossObj; glossaryItemList.addAll(glossItemsFromFile); } else { log.error("The Glossary-XML-File " + glossaryFile.toString() + " seems not to be correct!"); } Collections.sort(glossaryItemList); return glossaryItemList; }
CWE-91
78
public boolean isIgnoreComments() { return ignoreComments; }
CWE-611
13
public String getOrderBy() { return orderBy; }
CWE-89
0
public void create_withNullThreadPool() throws Exception { final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(100,10,10000)).thenReturn(new Server()); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(null); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 8080, null, 100,10,10000); verify(jettyServerFactory, times(1)).create(100,10,10000); verifyNoMoreInteractions(jettyServerFactory); }
CWE-22
2
private static ECPrivateKey generateECPrivateKey(final ECKey.Curve curve) throws Exception { final ECParameterSpec ecParameterSpec = curve.toECParameterSpec(); KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); generator.initialize(ecParameterSpec); KeyPair keyPair = generator.generateKeyPair(); return (ECPrivateKey) keyPair.getPrivate(); }
CWE-347
25
public static void unzipFilesToPath(String jarPath, String destinationDir) throws IOException { File file = new File(jarPath); try (JarFile jar = new JarFile(file)) { // fist get all directories, // then make those directory on the destination Path /*for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements(); ) { JarEntry entry = (JarEntry) enums.nextElement(); String fileName = destinationDir + File.separator + entry.getName(); File f = new File(fileName); if (fileName.endsWith("/")) { f.mkdirs(); } }*/ //now create all files for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements(); ) { JarEntry entry = enums.nextElement(); String fileName = destinationDir + File.separator + entry.getName(); File f = new File(fileName); if (!f.getCanonicalPath().startsWith(destinationDir)) { System.out.println("Zip Slip exploit detected. Skipping entry " + entry.getName()); continue; } File parent = f.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } if (!fileName.endsWith("/")) { try (InputStream is = jar.getInputStream(entry); FileOutputStream fos = new FileOutputStream(f)) { // write contents of 'is' to 'fos' while (is.available() > 0) { fos.write(is.read()); } } } } } }
CWE-22
2
public SAXReader(XMLReader xmlReader) { this.xmlReader = xmlReader; }
CWE-611
13
void relative() { assertThat(PathAndQuery.parse("foo")).isNull(); }
CWE-22
2
public <T extends JiffleRuntime> T getRuntimeInstance(Class<T> baseClass) throws it.geosolutions.jaiext.jiffle.JiffleException { RuntimeModel model = RuntimeModel.get(baseClass); if (model == null) { throw new it.geosolutions.jaiext.jiffle.JiffleException(baseClass.getName() + " does not implement a required Jiffle runtime interface"); } return (T) createRuntimeInstance(model, baseClass, false); }
CWE-94
14
public void testSelectByTwoTypes() { JWKSelector selector = new JWKSelector(new JWKMatcher.Builder().keyTypes(KeyType.RSA, KeyType.EC).build()); List<JWK> keyList = new ArrayList<>(); keyList.add(new RSAKey.Builder(new Base64URL("n"), new Base64URL("e")).keyID("1").build()); keyList.add(new ECKey.Builder(ECKey.Curve.P_256, new Base64URL("x"), new Base64URL("y")).keyID("2").build()); JWKSet jwkSet = new JWKSet(keyList); List<JWK> matches = selector.select(jwkSet); RSAKey key1 = (RSAKey)matches.get(0); assertEquals(KeyType.RSA, key1.getKeyType()); assertEquals("1", key1.getKeyID()); ECKey key2 = (ECKey)matches.get(1); assertEquals(KeyType.EC, key2.getKeyType()); assertEquals("2", key2.getKeyID()); assertEquals(2, matches.size()); }
CWE-347
25
private void parseAttributesForKnownElements(Map<String, List<Entry>> subdirs, Node desc) { // NOTE: NamedNodeMap does not have any particular order... NamedNodeMap attributes = desc.getAttributes(); for (Node attr : asIterable(attributes)) { if (!XMP.ELEMENTS.contains(attr.getNamespaceURI())) { continue; } List<Entry> dir = subdirs.get(attr.getNamespaceURI()); if (dir == null) { dir = new ArrayList<Entry>(); subdirs.put(attr.getNamespaceURI(), dir); } dir.add(new XMPEntry(attr.getNamespaceURI() + attr.getLocalName(), attr.getLocalName(), attr.getNodeValue())); } }
CWE-611
13
public void create_withThreadPool() throws Exception { final QueuedThreadPool threadPool = new QueuedThreadPool(100); final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class); final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class); final Routes routes = mock(Routes.class); when(jettyServerFactory.create(threadPool)).thenReturn(new Server(threadPool)); final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(threadPool); embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false); embeddedServer.ignite("localhost", 8080, null, 0,0,0); verify(jettyServerFactory, times(1)).create(threadPool); verifyNoMoreInteractions(jettyServerFactory); }
CWE-22
2
public int decryptWithAd(byte[] ad, byte[] ciphertext, int ciphertextOffset, byte[] plaintext, int plaintextOffset, int length) throws ShortBufferException, BadPaddingException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (length > space) throw new ShortBufferException(); if (plaintextOffset > plaintext.length) space = 0; else space = plaintext.length - plaintextOffset; if (keySpec == null) { // The key is not set yet - return the ciphertext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length); return length; } if (length < 16) Noise.throwBadTagException(); int dataLen = length - 16; if (dataLen > space) throw new ShortBufferException(); try { setup(ad); } catch (InvalidKeyException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (InvalidAlgorithmParameterException e) { // Shouldn't happen. throw new IllegalStateException(e); } ghash.update(ciphertext, ciphertextOffset, dataLen); ghash.pad(ad != null ? ad.length : 0, dataLen); ghash.finish(iv, 0, 16); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (hashKey[index] ^ iv[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); try { int result = cipher.update(ciphertext, ciphertextOffset, dataLen, plaintext, plaintextOffset); cipher.doFinal(plaintext, plaintextOffset + result); } catch (IllegalBlockSizeException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (BadPaddingException e) { // Shouldn't happen. throw new IllegalStateException(e); } return dataLen; }
CWE-787
24
protected String getCorsDomain(String referer, String userAgent) { String dom = null; if (referer != null && referer.toLowerCase() .matches("https?://([a-z0-9,-]+[.])*draw[.]io/.*")) { dom = referer.toLowerCase().substring(0, referer.indexOf(".draw.io/") + 8); } else if (referer != null && referer.toLowerCase() .matches("https?://([a-z0-9,-]+[.])*diagrams[.]net/.*")) { dom = referer.toLowerCase().substring(0, referer.indexOf(".diagrams.net/") + 13); } else if (referer != null && referer.toLowerCase() .matches("https?://([a-z0-9,-]+[.])*quipelements[.]com/.*")) { dom = referer.toLowerCase().substring(0, referer.indexOf(".quipelements.com/") + 17); } // Enables Confluence/Jira proxy via referer or hardcoded user-agent (for old versions) // UA refers to old FF on macOS so low risk and fixes requests from existing servers else if ((referer != null && referer.equals("draw.io Proxy Confluence Server")) || (userAgent != null && userAgent.equals( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:50.0) Gecko/20100101 Firefox/50.0"))) { dom = ""; } return dom; }
CWE-918
16
public void setXMLReader(XMLReader reader) { this.xmlReader = reader; }
CWE-611
13
private Path getFilePath(String path) { return baseDirPath.map(dir -> dir.resolve(path)).orElseGet(() -> Paths.get(path)); }
CWE-22
2
void requestResetPassword() throws Exception { when(this.userManager.exists(this.userReference)).thenReturn(true); InternetAddress email = new InternetAddress("[email protected]"); when(this.userProperties.getEmail()).thenReturn(email); BaseObject xObject = mock(BaseObject.class); when(this.userDocument .getXObject(DefaultResetPasswordManager.RESET_PASSWORD_REQUEST_CLASS_REFERENCE, true, this.context)) .thenReturn(xObject); String verificationCode = "abcde1234"; when(this.xWiki.generateRandomString(30)).thenReturn(verificationCode); when(this.localizationManager.getTranslationPlain("xe.admin.passwordReset.versionComment")) .thenReturn("Save verification code 42"); ResetPasswordRequestResponse expectedResult = new DefaultResetPasswordRequestResponse(this.userReference, email, verificationCode); assertEquals(expectedResult, this.resetPasswordManager.requestResetPassword(this.userReference)); verify(xObject).set(DefaultResetPasswordManager.VERIFICATION_PROPERTY, verificationCode, context); verify(this.xWiki).saveDocument(this.userDocument, "Save verification code 42", true, this.context); }
CWE-640
20
public void setXMLFilter(XMLFilter filter) { this.xmlFilter = filter; }
CWE-611
13
void checkVerificationCodeUnexistingUser() { when(this.userReference.toString()).thenReturn("user:Foobar"); when(this.userManager.exists(this.userReference)).thenReturn(false); String exceptionMessage = "User [user:Foobar] doesn't exist"; when(this.localizationManager.getTranslationPlain("xe.admin.passwordReset.error.noUser", "user:Foobar")).thenReturn(exceptionMessage); ResetPasswordException resetPasswordException = assertThrows(ResetPasswordException.class, () -> this.resetPasswordManager.checkVerificationCode(this.userReference, "some code")); assertEquals(exceptionMessage, resetPasswordException.getMessage()); }
CWE-640
20
public String toString() { if (query == null) { return path; } return path + "?" + query; }
CWE-22
2