_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q15500
AbstractGlobalWebSingleton.getGlobalSingleton
train
@Nonnull public static final <T extends AbstractGlobalWebSingleton> T getGlobalSingleton (@Nonnull final Class <T> aClass) { return getSingleton (_getStaticScope (true), aClass); }
java
{ "resource": "" }
q15501
DNSHelper.setDNSCacheTime
train
public static void setDNSCacheTime (final int nSeconds) { final String sValue = Integer.toString (nSeconds); Security.setProperty ("networkaddress.cache.ttl", sValue); Security.setProperty ("networkaddress.cache.negative.ttl", sValue); SystemProperties.setPropertyValue ("disableWSAddressCaching", nSeconds == 0); }
java
{ "resource": "" }
q15502
AcceptCharsetList.getQValueOfCharset
train
@Nonnull public QValue getQValueOfCharset (@Nonnull final String sCharset) { ValueEnforcer.notNull (sCharset, "Charset"); // Find charset direct QValue aQuality = m_aMap.get (_unify (sCharset)); if (aQuality == null) { // If not explicitly given, check for "*" aQuality = m_aMap.get (AcceptCharsetHandler.ANY_CHARSET); if (aQuality == null) { // Neither charset nor "*" is present return sCharset.equals (AcceptCharsetHandler.DEFAULT_CHARSET) ? QValue.MAX_QVALUE : QValue.MIN_QVALUE; } } return aQuality; }
java
{ "resource": "" }
q15503
LWJGLUtil.checkForGLError
train
public static void checkForGLError() { if (CausticUtil.isDebugEnabled()) { final int errorValue = GL11.glGetError(); if (errorValue != GL11.GL_NO_ERROR) { throw new GLException("GL ERROR: " + GLU.gluErrorString(errorValue)); } } }
java
{ "resource": "" }
q15504
PemObjectReader.getPemObject
train
public static PemObject getPemObject(final File file) throws IOException { PemObject pemObject; try (PemReader pemReader = new PemReader(new InputStreamReader(new FileInputStream(file)))) { pemObject = pemReader.readPemObject(); } return pemObject; }
java
{ "resource": "" }
q15505
MockHttpSession.clearAttributes
train
public void clearAttributes () { for (final Map.Entry <String, Object> entry : m_aAttributes.entrySet ()) { final String sName = entry.getKey (); final Object aValue = entry.getValue (); if (aValue instanceof HttpSessionBindingListener) ((HttpSessionBindingListener) aValue).valueUnbound (new HttpSessionBindingEvent (this, sName, aValue)); } m_aAttributes.clear (); }
java
{ "resource": "" }
q15506
MockHttpSession.serializeState
train
@Nonnull public Serializable serializeState () { final ICommonsMap <String, Object> aState = new CommonsHashMap <> (); for (final Map.Entry <String, Object> entry : m_aAttributes.entrySet ()) { final String sName = entry.getKey (); final Object aValue = entry.getValue (); if (aValue instanceof Serializable) { aState.put (sName, aValue); } else { // Not serializable... Servlet containers usually automatically // unbind the attribute in this case. if (aValue instanceof HttpSessionBindingListener) { ((HttpSessionBindingListener) aValue).valueUnbound (new HttpSessionBindingEvent (this, sName, aValue)); } } } m_aAttributes.clear (); return aState; }
java
{ "resource": "" }
q15507
ResponseHelperSettings.setAll
train
@Nonnull public static EChange setAll (final boolean bResponseCompressionEnabled, final boolean bResponseGzipEnabled, final boolean bResponseDeflateEnabled) { return s_aRWLock.writeLocked ( () -> { EChange eChange = EChange.UNCHANGED; if (s_bResponseCompressionEnabled != bResponseCompressionEnabled) { s_bResponseCompressionEnabled = bResponseCompressionEnabled; eChange = EChange.CHANGED; LOGGER.info ("ResponseHelper responseCompressEnabled=" + bResponseCompressionEnabled); } if (s_bResponseGzipEnabled != bResponseGzipEnabled) { s_bResponseGzipEnabled = bResponseGzipEnabled; eChange = EChange.CHANGED; LOGGER.info ("ResponseHelper responseGzipEnabled=" + bResponseGzipEnabled); } if (s_bResponseDeflateEnabled != bResponseDeflateEnabled) { s_bResponseDeflateEnabled = bResponseDeflateEnabled; eChange = EChange.CHANGED; LOGGER.info ("ResponseHelper responseDeflateEnabled=" + bResponseDeflateEnabled); } return eChange; }); }
java
{ "resource": "" }
q15508
ResponseHelperSettings.setExpirationSeconds
train
@Nonnull public static EChange setExpirationSeconds (final int nExpirationSeconds) { return s_aRWLock.writeLocked ( () -> { if (s_nExpirationSeconds == nExpirationSeconds) return EChange.UNCHANGED; s_nExpirationSeconds = nExpirationSeconds; LOGGER.info ("ResponseHelper expirationSeconds=" + nExpirationSeconds); return EChange.CHANGED; }); }
java
{ "resource": "" }
q15509
FileItemStream.openStream
train
@Nonnull public InputStream openStream () throws IOException { if (m_aIS instanceof ICloseable && ((ICloseable) m_aIS).isClosed ()) throw new MultipartItemSkippedException (); return m_aIS; }
java
{ "resource": "" }
q15510
XQuery.text
train
public @Nonnull String text() { return new NodeListSpliterator(node.getChildNodes()).stream() .filter(it -> it instanceof Text) .map(it -> ((Text) it).getNodeValue()) .collect(joining()); }
java
{ "resource": "" }
q15511
XQuery.attr
train
public @Nonnull Map<String, String> attr() { synchronized (this) { if (attrMap.get() == null) { attrMap.set( Optional.ofNullable(node.getAttributes()) .map(XQuery::attributesToMap) .map(Collections::unmodifiableMap) .orElseGet(Collections::emptyMap) ); } } return attrMap.get(); }
java
{ "resource": "" }
q15512
XQuery.evaluate
train
private @Nonnull NodeList evaluate(String xpath) { try { XPathExpression expr = xpf.newXPath().compile(xpath); return (NodeList) expr.evaluate(node, XPathConstants.NODESET); } catch (XPathExpressionException ex) { throw new IllegalArgumentException("Invalid XPath '" + xpath + "'", ex); } }
java
{ "resource": "" }
q15513
XQuery.findElement
train
private @Nonnull Optional<XQuery> findElement(Function<Node, Node> iterator) { Node it = node; do { it = iterator.apply(it); } while (it != null && !(it instanceof Element)); return Optional.ofNullable(it).map(XQuery::new); }
java
{ "resource": "" }
q15514
DigestAuthServerBuilder.setOpaque
train
@Nonnull public DigestAuthServerBuilder setOpaque (@Nonnull final String sOpaque) { if (!HttpStringHelper.isQuotedTextContent (sOpaque)) throw new IllegalArgumentException ("opaque is invalid: " + sOpaque); m_sOpaque = sOpaque; return this; }
java
{ "resource": "" }
q15515
ServletHelper.getRequestPathInfo
train
@Nonnull public static String getRequestPathInfo (@Nullable final HttpServletRequest aRequest) { String ret = null; if (aRequest != null) try { // They may return null! if (aRequest.isAsyncSupported () && aRequest.isAsyncStarted ()) ret = (String) aRequest.getAttribute (AsyncContext.ASYNC_PATH_INFO); else ret = aRequest.getPathInfo (); } catch (final UnsupportedOperationException ex) { // Offline request - fall through } catch (final Exception ex) { // fall through if (isLogExceptions ()) if (LOGGER.isWarnEnabled ()) LOGGER.warn ("[ServletHelper] Failed to determine path info of HTTP request", ex); } return ret == null ? "" : ret; }
java
{ "resource": "" }
q15516
ServletHelper.getRequestRequestURI
train
@Nonnull public static String getRequestRequestURI (@Nullable final HttpServletRequest aRequest) { String ret = ""; if (aRequest != null) try { if (aRequest.isAsyncSupported () && aRequest.isAsyncStarted ()) ret = (String) aRequest.getAttribute (AsyncContext.ASYNC_REQUEST_URI); else ret = aRequest.getRequestURI (); } catch (final Exception ex) { // fall through if (isLogExceptions ()) if (LOGGER.isWarnEnabled ()) LOGGER.warn ("[ServletHelper] Failed to determine request URI of HTTP request", ex); } return ret; }
java
{ "resource": "" }
q15517
ServletHelper.getRequestRequestURL
train
@Nonnull public static StringBuffer getRequestRequestURL (@Nullable final HttpServletRequest aRequest) { StringBuffer ret = null; if (aRequest != null) try { ret = aRequest.getRequestURL (); } catch (final Exception ex) { // fall through if (isLogExceptions ()) if (LOGGER.isWarnEnabled ()) LOGGER.warn ("[ServletHelper] Failed to determine request URL of HTTP request", ex); } return ret != null ? ret : new StringBuffer (); }
java
{ "resource": "" }
q15518
ServletHelper.getRequestServletPath
train
@Nonnull public static String getRequestServletPath (@Nullable final HttpServletRequest aRequest) { String ret = ""; if (aRequest != null) try { if (aRequest.isAsyncSupported () && aRequest.isAsyncStarted ()) ret = (String) aRequest.getAttribute (AsyncContext.ASYNC_SERVLET_PATH); else ret = aRequest.getServletPath (); } catch (final UnsupportedOperationException ex) { // Offline request - fall through } catch (final Exception ex) { // fall through if (isLogExceptions ()) if (LOGGER.isWarnEnabled ()) LOGGER.warn ("[ServletHelper] Failed to determine servlet path of HTTP request", ex); } return ret; }
java
{ "resource": "" }
q15519
BasicAuthServerBuilder.setRealm
train
@Nonnull public BasicAuthServerBuilder setRealm (@Nonnull final String sRealm) { ValueEnforcer.isTrue (HttpStringHelper.isQuotedTextContent (sRealm), () -> "Realm is invalid: " + sRealm); m_sRealm = sRealm; return this; }
java
{ "resource": "" }
q15520
Path.contains
train
public boolean contains(String path) { boolean result = false; FileName fn = new FileName(path); if (fn.getPath().startsWith(getPath())) { result = true; } return result; }
java
{ "resource": "" }
q15521
WordlistsProcessor.getCurrentAttempt
train
public String getCurrentAttempt() { if (currentIndex < words.size()) { final String currentAttempt = words.get(currentIndex); return currentAttempt; } return null; }
java
{ "resource": "" }
q15522
WordlistsProcessor.process
train
public boolean process() { boolean continueIterate = true; boolean found = false; String attempt = getCurrentAttempt(); while (continueIterate) { if (attempt.equals(toCheckAgainst)) { found = true; break; } attempt = getCurrentAttempt(); continueIterate = increment(); } return found; }
java
{ "resource": "" }
q15523
FailedMailQueue.remove
train
@Nullable public FailedMailData remove (@Nullable final String sID) { if (StringHelper.hasNoText (sID)) return null; return m_aRWLock.writeLocked ( () -> internalRemove (sID)); }
java
{ "resource": "" }
q15524
HttpBasicAuth.getBasicAuthClientCredentials
train
@Nullable public static BasicAuthClientCredentials getBasicAuthClientCredentials (@Nullable final String sAuthHeader) { final String sRealHeader = StringHelper.trim (sAuthHeader); if (StringHelper.hasNoText (sRealHeader)) return null; final String [] aElements = RegExHelper.getSplitToArray (sRealHeader, "\\s+", 2); if (aElements.length != 2) { if (LOGGER.isErrorEnabled ()) LOGGER.error ("String is not Basic Auth: " + sRealHeader); return null; } if (!aElements[0].equals (HEADER_VALUE_PREFIX_BASIC)) { if (LOGGER.isErrorEnabled ()) LOGGER.error ("String does not start with 'Basic': " + sRealHeader); return null; } // Apply Base64 decoding final String sEncodedCredentials = aElements[1]; final String sUsernamePassword = Base64.safeDecodeAsString (sEncodedCredentials, CHARSET); if (sUsernamePassword == null) { if (LOGGER.isErrorEnabled ()) LOGGER.error ("Illegal Base64 encoded value '" + sEncodedCredentials + "'"); return null; } // Do we have a username/password separator? final int nIndex = sUsernamePassword.indexOf (USERNAME_PASSWORD_SEPARATOR); if (nIndex >= 0) return new BasicAuthClientCredentials (sUsernamePassword.substring (0, nIndex), sUsernamePassword.substring (nIndex + 1)); return new BasicAuthClientCredentials (sUsernamePassword); }
java
{ "resource": "" }
q15525
ServletStatusManager.onServletInit
train
public void onServletInit (@Nonnull final Class <? extends GenericServlet> aServletClass) { if (LOGGER.isDebugEnabled ()) LOGGER.debug ("onServletInit: " + aServletClass); _updateStatus (aServletClass, EServletStatus.INITED); }
java
{ "resource": "" }
q15526
ServletStatusManager.onServletInvocation
train
public void onServletInvocation (@Nonnull final Class <? extends GenericServlet> aServletClass) { m_aRWLock.writeLocked ( () -> _getOrCreateServletStatus (aServletClass).internalIncrementInvocationCount ()); }
java
{ "resource": "" }
q15527
NetworkPortHelper.checkPortOpen
train
@Nonnull public static ENetworkPortStatus checkPortOpen (@Nonnull @Nonempty final String sHostName, @Nonnegative final int nPort, @Nonnegative final int nTimeoutMillisecs) { ValueEnforcer.notEmpty (sHostName, "Hostname"); ValueEnforcer.isGE0 (nPort, "Port"); ValueEnforcer.isGE0 (nTimeoutMillisecs, "TimeoutMillisecs"); LOGGER.info ("Checking TCP port status for " + sHostName + ":" + nPort + " with timeouf of " + nTimeoutMillisecs + " ms"); try (final Socket aSocket = new Socket ()) { aSocket.setReuseAddress (true); final SocketAddress aSocketAddr = new InetSocketAddress (sHostName, nPort); aSocket.connect (aSocketAddr, nTimeoutMillisecs); return ENetworkPortStatus.PORT_IS_OPEN; } catch (final IOException ex) { // Can also be: // Connection refused: connect if (ex.getMessage ().startsWith ("Connection refused")) return ENetworkPortStatus.PORT_IS_CLOSED; if (ex instanceof java.net.UnknownHostException) return ENetworkPortStatus.HOST_NOT_EXISTING; if (ex instanceof java.net.SocketTimeoutException) return ENetworkPortStatus.CONNECTION_TIMEOUT; if (ex instanceof java.net.ConnectException) { // E.g. for port 0 return ENetworkPortStatus.GENERIC_IO_ERROR; } LOGGER.error ("Other error checking TCP port status", ex); return ENetworkPortStatus.GENERIC_IO_ERROR; } }
java
{ "resource": "" }
q15528
UserAgentDecryptor._decryptUserAgent
train
@Nonnull private static UserAgentElementList _decryptUserAgent (@Nonnull final String sUserAgent) { final UserAgentElementList ret = new UserAgentElementList (); final StringScanner aSS = new StringScanner (sUserAgent.trim ()); while (true) { aSS.skipWhitespaces (); final int nIndex = aSS.findFirstIndex ('/', ' ', '[', '('); if (nIndex == -1) break; switch (aSS.getCharAtIndex (nIndex)) { case '/': { // e.g. "a/b" final String sKey = aSS.getUntilIndex (nIndex); final String sValue = aSS.skip (1).getUntilWhiteSpace (); final String sFullValue = sKey + "/" + sValue; // Special handling of URLs :) if (URLProtocolRegistry.getInstance ().hasKnownProtocol (sFullValue)) ret.add (sFullValue); else ret.add (Pair.create (sKey, sValue)); break; } case ' ': { // e.g. "Opera 6.03" // e.g. "HTC_P3700 Opera/9.50 (Windows NT 5.1; U; de)" final String sText = aSS.getUntilIndex (nIndex).trim (); final Matcher aMatcher = RegExHelper.getMatcher ("([^\\s]+)\\s+([0-9]+\\.[0-9]+)", sText); if (aMatcher.matches ()) ret.add (Pair.create (aMatcher.group (1), aMatcher.group (2))); else ret.add (sText); break; } case '[': { // e.g. "[en]" aSS.setIndex (nIndex).skip (1); // skip incl. "[" ret.add (aSS.getUntil (']')); aSS.skip (1); break; } case '(': { // e.g. "(compatible; MSIE 5.0; Windows 2000)" aSS.setIndex (nIndex).skip (1); // skip incl. "(" final String sParams = aSS.getUntilBalanced (1, '(', ')'); // convert to ";" separated list final ICommonsList <String> aParams = StringHelper.getExploded (';', sParams); ret.add (aParams.getAllMapped (String::trim)); break; } default: throw new IllegalStateException ("Invalid character: " + aSS.getCharAtIndex (nIndex)); } } // add all remaining parts as is final String sRest = aSS.getRest ().trim (); if (sRest.length () > 0) ret.add (sRest); return ret; }
java
{ "resource": "" }
q15529
UserAgentDecryptor.decryptUserAgentString
train
@Nonnull public static IUserAgent decryptUserAgentString (@Nonnull final String sUserAgent) { ValueEnforcer.notNull (sUserAgent, "UserAgent"); String sRealUserAgent = sUserAgent; // Check if surrounded with '"' or ''' if (sRealUserAgent.length () >= 2) { final char cFirst = sRealUserAgent.charAt (0); if ((cFirst == '\'' || cFirst == '"') && StringHelper.getLastChar (sRealUserAgent) == cFirst) sRealUserAgent = sRealUserAgent.substring (1, sRealUserAgent.length () - 1); } // Skip a certain prefix that is known to occur frequently if (sRealUserAgent.startsWith (SKIP_PREFIX)) sRealUserAgent = sRealUserAgent.substring (SKIP_PREFIX.length ()); return new UserAgent (sRealUserAgent, _decryptUserAgent (sRealUserAgent)); }
java
{ "resource": "" }
q15530
AuthenticatorProxySettingsManager.requestProxyPasswordAuthentication
train
@Nullable public static PasswordAuthentication requestProxyPasswordAuthentication (@Nullable final String sHostName, @Nullable final int nPort, @Nullable final String sProtocol) { return requestPasswordAuthentication (sHostName, (InetAddress) null, nPort, sProtocol, (String) null, (String) null, (URL) null, RequestorType.PROXY); }
java
{ "resource": "" }
q15531
Browser.get
train
public static <T> T get(final Class<T> pageClass, final String... params) { cryIfNotAnnotated(pageClass); try { final String pageUrl = pageClass.getAnnotation(Page.class).value(); return loadPage(pageUrl, pageClass, Arrays.asList(params)); } catch (final Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q15532
RequestParamMap._getChildMapExceptLast
train
@Nullable private ICommonsOrderedMap <String, RequestParamMapItem> _getChildMapExceptLast (@Nonnull @Nonempty final String... aPath) { ValueEnforcer.notEmpty (aPath, "Path"); ICommonsOrderedMap <String, RequestParamMapItem> aMap = m_aMap; // Until the second last object for (int i = 0; i < aPath.length - 1; ++i) { aMap = _getChildMap (aMap, aPath[i]); if (aMap == null) return null; } return aMap; }
java
{ "resource": "" }
q15533
RequestParamMap.getFieldName
train
@Nonnull @Nonempty @Deprecated public static String getFieldName (@Nonnull @Nonempty final String sBaseName) { ValueEnforcer.notEmpty (sBaseName, "BaseName"); return sBaseName; }
java
{ "resource": "" }
q15534
RequestParamMap.setSeparators
train
public static void setSeparators (final char cOpen, final char cClose) { ValueEnforcer.isFalse (cOpen == cClose, "Open and closing element may not be identical!"); s_sOpen = Character.toString (cOpen); s_sClose = Character.toString (cClose); }
java
{ "resource": "" }
q15535
RequestParamMap.setSeparators
train
public static void setSeparators (@Nonnull @Nonempty final String sOpen, @Nonnull @Nonempty final String sClose) { ValueEnforcer.notEmpty (sOpen, "Open"); ValueEnforcer.notEmpty (sClose, "Close"); ValueEnforcer.isFalse (sOpen.contains (sClose), "open may not contain close"); ValueEnforcer.isFalse (sClose.contains (sOpen), "close may not contain open"); s_sOpen = sOpen; s_sClose = sClose; }
java
{ "resource": "" }
q15536
RequestHelper.getWithoutSessionID
train
@Nonnull public static SimpleURL getWithoutSessionID (@Nonnull final ISimpleURL aURL) { ValueEnforcer.notNull (aURL, "URL"); // Strip the parameter from the path, but keep parameters and anchor intact! // Note: using URLData avoid parsing, since the data was already parsed! return new SimpleURL (new URLData (getWithoutSessionID (aURL.getPath ()), aURL.params (), aURL.getAnchor ())); }
java
{ "resource": "" }
q15537
RequestHelper.getPathWithinServletContext
train
@Nonnull public static String getPathWithinServletContext (@Nonnull final HttpServletRequest aHttpRequest) { ValueEnforcer.notNull (aHttpRequest, "HttpRequest"); final String sRequestURI = getRequestURI (aHttpRequest); if (StringHelper.hasNoText (sRequestURI)) { // Can e.g. happen for "Request(GET //localhost:90/)" if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Having empty request URI '" + sRequestURI + "' from request " + aHttpRequest); return "/"; } // Always use the context path final String sContextPath = ServletContextPathHolder.getContextPath (); if (StringHelper.hasNoText (sContextPath) || !sRequestURI.startsWith (sContextPath)) return sRequestURI; // Normal case: URI contains context path. final String sPath = sRequestURI.substring (sContextPath.length ()); return sPath.length () > 0 ? sPath : "/"; }
java
{ "resource": "" }
q15538
RequestHelper.getHttpVersion
train
@Nullable public static EHttpVersion getHttpVersion (@Nonnull final HttpServletRequest aHttpRequest) { ValueEnforcer.notNull (aHttpRequest, "HttpRequest"); final String sProtocol = aHttpRequest.getProtocol (); return EHttpVersion.getFromNameOrNull (sProtocol); }
java
{ "resource": "" }
q15539
RequestHelper.getHttpMethod
train
@Nullable public static EHttpMethod getHttpMethod (@Nonnull final HttpServletRequest aHttpRequest) { ValueEnforcer.notNull (aHttpRequest, "HttpRequest"); final String sMethod = aHttpRequest.getMethod (); return EHttpMethod.getFromNameOrNull (sMethod); }
java
{ "resource": "" }
q15540
RequestHelper.getRequestHeaderMap
train
@Nonnull @ReturnsMutableCopy public static HttpHeaderMap getRequestHeaderMap (@Nonnull final HttpServletRequest aHttpRequest) { ValueEnforcer.notNull (aHttpRequest, "HttpRequest"); final HttpHeaderMap ret = new HttpHeaderMap (); final Enumeration <String> aHeaders = aHttpRequest.getHeaderNames (); while (aHeaders.hasMoreElements ()) { final String sName = aHeaders.nextElement (); final Enumeration <String> eHeaderValues = aHttpRequest.getHeaders (sName); while (eHeaderValues.hasMoreElements ()) { final String sValue = eHeaderValues.nextElement (); ret.addHeader (sName, sValue); } } return ret; }
java
{ "resource": "" }
q15541
RequestHelper.getRequestClientCertificates
train
@Nullable public static X509Certificate [] getRequestClientCertificates (@Nonnull final HttpServletRequest aHttpRequest) { return _getRequestAttr (aHttpRequest, SERVLET_ATTR_CLIENT_CERTIFICATE, X509Certificate [].class); }
java
{ "resource": "" }
q15542
RequestHelper.getHttpUserAgentStringFromRequest
train
@Nullable public static String getHttpUserAgentStringFromRequest (@Nonnull final HttpServletRequest aHttpRequest) { // Use non-standard headers first String sUserAgent = aHttpRequest.getHeader (CHttpHeader.UA); if (sUserAgent == null) { sUserAgent = aHttpRequest.getHeader (CHttpHeader.X_DEVICE_USER_AGENT); if (sUserAgent == null) sUserAgent = aHttpRequest.getHeader (CHttpHeader.USER_AGENT); } return sUserAgent; }
java
{ "resource": "" }
q15543
RequestHelper.getCheckBoxHiddenFieldName
train
@Nonnull @Nonempty public static String getCheckBoxHiddenFieldName (@Nonnull @Nonempty final String sFieldName) { ValueEnforcer.notEmpty (sFieldName, "FieldName"); return DEFAULT_CHECKBOX_HIDDEN_FIELD_PREFIX + sFieldName; }
java
{ "resource": "" }
q15544
CookieHelper.createCookie
train
@Nonnull public static Cookie createCookie (@Nonnull final String sName, @Nullable final String sValue, final String sPath, final boolean bExpireWhenBrowserIsClosed) { final Cookie aCookie = new Cookie (sName, sValue); aCookie.setPath (sPath); if (bExpireWhenBrowserIsClosed) aCookie.setMaxAge (-1); else aCookie.setMaxAge (DEFAULT_MAX_AGE_SECONDS); return aCookie; }
java
{ "resource": "" }
q15545
CookieHelper.removeCookie
train
public static void removeCookie (@Nonnull final HttpServletResponse aHttpResponse, @Nonnull final Cookie aCookie) { ValueEnforcer.notNull (aHttpResponse, "HttpResponse"); ValueEnforcer.notNull (aCookie, "aCookie"); // expire the cookie! aCookie.setMaxAge (0); aHttpResponse.addCookie (aCookie); }
java
{ "resource": "" }
q15546
EncryptedPrivateKeyReader.readPasswordProtectedPrivateKey
train
public static PrivateKey readPasswordProtectedPrivateKey(final byte[] encryptedPrivateKeyBytes, final String password, final String algorithm) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException { final EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo( encryptedPrivateKeyBytes); final String algName = encryptedPrivateKeyInfo.getAlgName(); final Cipher cipher = CipherFactory.newCipher(algName); final KeySpec pbeKeySpec = KeySpecFactory.newPBEKeySpec(password); final SecretKeyFactory secretKeyFactory = SecretKeyFactoryExtensions .newSecretKeyFactory(algName); final Key pbeKey = secretKeyFactory.generateSecret(pbeKeySpec); final AlgorithmParameters algParameters = encryptedPrivateKeyInfo.getAlgParameters(); cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParameters); final KeySpec pkcs8KeySpec = encryptedPrivateKeyInfo.getKeySpec(cipher); final KeyFactory keyFactory = KeyFactory.getInstance(algorithm); return keyFactory.generatePrivate(pkcs8KeySpec); }
java
{ "resource": "" }
q15547
ServletAsyncSpec.createAsync
train
@Nonnull public static ServletAsyncSpec createAsync (@CheckForSigned final long nTimeoutMillis, @Nullable final Iterable <? extends AsyncListener> aAsyncListeners) { return new ServletAsyncSpec (true, nTimeoutMillis, aAsyncListeners); }
java
{ "resource": "" }
q15548
MergeMojo.initOutput
train
protected OutputStream initOutput(final File file) throws MojoExecutionException { // stream to return final OutputStream stream; // plenty of things can go wrong... try { // directory? if (file.isDirectory()) { throw new MojoExecutionException("File " + file.getAbsolutePath() + " is directory!"); } // already exists && can't remove it? if (file.exists() && !file.delete()) { throw new MojoExecutionException("Could not remove file: " + file.getAbsolutePath()); } // get directory above file file final File fileDirectory = file.getParentFile(); // does not exist && create it? if (!fileDirectory.exists() && !fileDirectory.mkdirs()) { throw new MojoExecutionException( "Could not create directory: " + fileDirectory.getAbsolutePath()); } // moar wtf: parent directory is no directory? if (!fileDirectory.isDirectory()) { throw new MojoExecutionException("Not a directory: " + fileDirectory.getAbsolutePath()); } // file file is for any reason not creatable? if (!file.createNewFile()) { throw new MojoExecutionException("Could not create file: " + file.getAbsolutePath()); } // finally create some file stream = new FileOutputStream(file); } catch (FileNotFoundException e) { throw new MojoExecutionException("Could not find file: " + file.getAbsolutePath(), e); } catch (IOException e) { throw new MojoExecutionException("Could not write to file: " + file.getAbsolutePath(), e); } // return return stream; }
java
{ "resource": "" }
q15549
MergeMojo.initInput
train
protected InputStream initInput(final File file) throws MojoExecutionException { InputStream stream = null; try { if (file.isDirectory()) { throw new MojoExecutionException("File " + file.getAbsolutePath() + " is directory!"); } if (!file.exists()) { throw new MojoExecutionException("File " + file.getAbsolutePath() + " does not exist!"); } stream = new FileInputStream(file); //append to outfile here } catch (FileNotFoundException e) { throw new MojoExecutionException("Could not find file: " + file.getAbsolutePath(), e); } return stream; }
java
{ "resource": "" }
q15550
MergeMojo.appendStream
train
protected void appendStream(final InputStream input, final OutputStream output) throws MojoExecutionException { // prebuffer int character; try { // get line seperator, based on system final String newLine = System.getProperty("line.separator"); // read & write while ((character = input.read()) != -1) { output.write(character); } // append newline output.write(newLine.getBytes()); // flush output.flush(); } catch (IOException e) { throw new MojoExecutionException("Error in buffering/writing " + e.getMessage(), e); } }
java
{ "resource": "" }
q15551
DeferredFileOutputStream.onThresholdReached
train
@Override protected void onThresholdReached () throws IOException { FileOutputStream aFOS = null; try { aFOS = new FileOutputStream (m_aOutputFile); m_aMemoryOS.writeTo (aFOS); m_aCurrentOS = aFOS; // Explicitly close the stream (even though this is a no-op) StreamHelper.close (m_aMemoryOS); m_aMemoryOS = null; } catch (final IOException ex) { StreamHelper.close (aFOS); throw ex; } }
java
{ "resource": "" }
q15552
DeferredFileOutputStream.writeTo
train
public void writeTo (@Nonnull @WillNotClose final OutputStream aOS) throws IOException { // we may only need to check if this is closed if we are working with a file // but we should force the habit of closing whether we are working with // a file or memory. if (!m_bClosed) throw new IOException ("This stream is not closed"); if (isInMemory ()) { m_aMemoryOS.writeTo (aOS); } else { final InputStream aIS = FileHelper.getInputStream (m_aOutputFile); StreamHelper.copyInputStreamToOutputStream (aIS, aOS); } }
java
{ "resource": "" }
q15553
MeshGenerator.generatePlane
train
public static VertexData generatePlane(Vector2f size) { final VertexData destination = new VertexData(); final VertexAttribute positionsAttribute = new VertexAttribute("positions", DataType.FLOAT, 3); destination.addAttribute(0, positionsAttribute); final TFloatList positions = new TFloatArrayList(); final VertexAttribute normalsAttribute = new VertexAttribute("normals", DataType.FLOAT, 3); destination.addAttribute(1, normalsAttribute); final TFloatList normals = new TFloatArrayList(); final VertexAttribute textureCoordsAttribute = new VertexAttribute("textureCoords", DataType.FLOAT, 2); destination.addAttribute(2, textureCoordsAttribute); final TFloatList textureCoords = new TFloatArrayList(); final TIntList indices = destination.getIndices(); // Generate the mesh generatePlane(positions, normals, textureCoords, indices, size); // Put the mesh in the vertex data positionsAttribute.setData(positions); normalsAttribute.setData(normals); textureCoordsAttribute.setData(textureCoords); return destination; }
java
{ "resource": "" }
q15554
MeshGenerator.generatePlane
train
public static void generatePlane(TFloatList positions, TFloatList normals, TFloatList textureCoords, TIntList indices, Vector2f size) { /* * 2-----3 * | | * | | * 0-----1 */ // Corner positions final Vector2f p = size.div(2); final Vector3f p3 = new Vector3f(p.getX(), p.getY(), 0); final Vector3f p2 = new Vector3f(-p.getX(), p.getY(), 0); final Vector3f p1 = new Vector3f(p.getX(), -p.getY(), 0); final Vector3f p0 = new Vector3f(-p.getX(), -p.getY(), 0); // Normal final Vector3f n = new Vector3f(0, 0, 1); // Face addVector(positions, p0); addVector(normals, n); addAll(textureCoords, 0, 0); addVector(positions, p1); addVector(normals, n); addAll(textureCoords, 1, 0); addVector(positions, p2); addVector(normals, n); addAll(textureCoords, 0, 1); addVector(positions, p3); addVector(normals, n); addAll(textureCoords, 1, 1); addAll(indices, 0, 3, 2, 0, 1, 3); }
java
{ "resource": "" }
q15555
MeshGenerator.generateCylinder
train
public static void generateCylinder(TFloatList positions, TFloatList normals, TIntList indices, float radius, float height) { // 0,0,0 will be halfway up the cylinder in the middle final float halfHeight = height / 2; // The positions at the rims of the cylinders final List<Vector3f> rims = new ArrayList<>(); for (int angle = 0; angle < 360; angle += 15) { final double angleRads = Math.toRadians(angle); rims.add(new Vector3f( radius * TrigMath.cos(angleRads), halfHeight, radius * -TrigMath.sin(angleRads))); } // The normals for the triangles of the top and bottom faces final Vector3f topNormal = new Vector3f(0, 1, 0); final Vector3f bottomNormal = new Vector3f(0, -1, 0); // Add the top and bottom face center vertices addVector(positions, new Vector3f(0, halfHeight, 0));// 0 addVector(normals, topNormal); addVector(positions, new Vector3f(0, -halfHeight, 0));// 1 addVector(normals, bottomNormal); // Add all the faces section by section, turning around the y axis final int rimsSize = rims.size(); for (int i = 0; i < rimsSize; i++) { // Get the top and bottom vertex positions and the side normal final Vector3f t = rims.get(i); final Vector3f b = new Vector3f(t.getX(), -t.getY(), t.getZ()); final Vector3f n = new Vector3f(t.getX(), 0, t.getZ()).normalize(); // Top face vertex addVector(positions, t);// index addVector(normals, topNormal); // Bottom face vertex addVector(positions, b);// index + 1 addVector(normals, bottomNormal); // Side top vertex addVector(positions, t);// index + 2 addVector(normals, n); // Side bottom vertex addVector(positions, b);// index + 3 addVector(normals, n); // Get the current index for our vertices final int currentIndex = i * 4 + 2; // Get the index for the next iteration, wrapping around at the end final int nextIndex = (i == rimsSize - 1 ? 0 : i + 1) * 4 + 2; // Add the 4 triangles (1 top, 1 bottom, 2 for the side) addAll(indices, 0, currentIndex, nextIndex); addAll(indices, 1, nextIndex + 1, currentIndex + 1); addAll(indices, currentIndex + 2, currentIndex + 3, nextIndex + 2); addAll(indices, currentIndex + 3, nextIndex + 3, nextIndex + 2); } }
java
{ "resource": "" }
q15556
MockEventListenerList.setFrom
train
@Nonnull public EChange setFrom (@Nonnull final MockEventListenerList aList) { ValueEnforcer.notNull (aList, "List"); // Assigning this to this? if (this == aList) return EChange.UNCHANGED; // Get all listeners to assign final ICommonsList <EventListener> aOtherListeners = aList.getAllListeners (); return m_aRWLock.writeLocked ( () -> { if (m_aListener.isEmpty () && aOtherListeners.isEmpty ()) return EChange.UNCHANGED; m_aListener.setAll (aOtherListeners); return EChange.CHANGED; }); }
java
{ "resource": "" }
q15557
MockEventListenerList.addListener
train
@Nonnull public EChange addListener (@Nonnull final EventListener aListener) { ValueEnforcer.notNull (aListener, "Listener"); // Small consistency check if (!(aListener instanceof ServletContextListener) && !(aListener instanceof HttpSessionListener) && !(aListener instanceof ServletRequestListener)) { LOGGER.warn ("Passed mock listener is none of ServletContextListener, HttpSessionListener or ServletRequestListener and therefore has no effect. The listener class is: " + aListener.getClass ()); } return m_aRWLock.writeLocked ( () -> EChange.valueOf (m_aListener.add (aListener))); }
java
{ "resource": "" }
q15558
XMLSitemapProvider.forEachURLSet
train
public static void forEachURLSet (@Nonnull final Consumer <? super XMLSitemapURLSet> aConsumer) { ValueEnforcer.notNull (aConsumer, "Consumer"); for (final IXMLSitemapProviderSPI aSPI : s_aProviders) { final XMLSitemapURLSet aURLSet = aSPI.createURLSet (); aConsumer.accept (aURLSet); } }
java
{ "resource": "" }
q15559
Camera.getViewMatrix
train
public Matrix4f getViewMatrix() { if (updateViewMatrix) { rotationMatrixInverse = Matrix4f.createRotation(rotation); final Matrix4f rotationMatrix = Matrix4f.createRotation(rotation.invert()); final Matrix4f positionMatrix = Matrix4f.createTranslation(position.negate()); viewMatrix = rotationMatrix.mul(positionMatrix); updateViewMatrix = false; } return viewMatrix; }
java
{ "resource": "" }
q15560
Camera.createPerspective
train
public static Camera createPerspective(float fieldOfView, int windowWidth, int windowHeight, float near, float far) { return new Camera(Matrix4f.createPerspective(fieldOfView, (float) windowWidth / windowHeight, near, far)); }
java
{ "resource": "" }
q15561
CertificateReader.readPemCertificate
train
public static X509Certificate readPemCertificate(final File file) throws IOException, CertificateException { final String privateKeyAsString = readPemFileAsBase64(file); final byte[] decoded = new Base64().decode(privateKeyAsString); return readCertificate(decoded); }
java
{ "resource": "" }
q15562
LoggingFilter.isLogRequest
train
@OverrideOnDemand protected boolean isLogRequest (@Nonnull final HttpServletRequest aHttpRequest, @Nonnull final HttpServletResponse aHttpResponse) { boolean bLog = isGloballyEnabled () && m_aLogger.isInfoEnabled (); if (bLog) { // Check for excluded path final String sRequestURI = ServletHelper.getRequestRequestURI (aHttpRequest); for (final String sExcludedPath : m_aExcludedPaths) if (sRequestURI.startsWith (sExcludedPath)) { bLog = false; break; } } return bLog; }
java
{ "resource": "" }
q15563
HttpClientManager.execute
train
@Nonnull public CloseableHttpResponse execute (@Nonnull final HttpUriRequest aRequest) throws IOException { return execute (aRequest, (HttpContext) null); }
java
{ "resource": "" }
q15564
HttpClientManager.execute
train
@Nonnull public CloseableHttpResponse execute (@Nonnull final HttpUriRequest aRequest, @Nullable final HttpContext aHttpContext) throws IOException { checkIfClosed (); HttpDebugger.beforeRequest (aRequest, aHttpContext); CloseableHttpResponse ret = null; Throwable aCaughtException = null; try { ret = m_aHttpClient.execute (aRequest, aHttpContext); return ret; } catch (final IOException ex) { aCaughtException = ex; throw ex; } finally { HttpDebugger.afterRequest (aRequest, ret, aCaughtException); } }
java
{ "resource": "" }
q15565
HttpClientManager.execute
train
@Nullable public <T> T execute (@Nonnull final HttpUriRequest aRequest, @Nonnull final ResponseHandler <T> aResponseHandler) throws IOException { return execute (aRequest, (HttpContext) null, aResponseHandler); }
java
{ "resource": "" }
q15566
EmailGlobalSettings.setMailQueueSize
train
@Nonnull public static EChange setMailQueueSize (@Nonnegative final int nMaxMailQueueLen, @Nonnegative final int nMaxMailSendCount) { ValueEnforcer.isGT0 (nMaxMailQueueLen, "MaxMailQueueLen"); ValueEnforcer.isGT0 (nMaxMailSendCount, "MaxMailSendCount"); ValueEnforcer.isTrue (nMaxMailQueueLen >= nMaxMailSendCount, () -> "MaxMailQueueLen (" + nMaxMailQueueLen + ") must be >= than MaxMailSendCount (" + nMaxMailSendCount + ")"); return s_aRWLock.writeLocked ( () -> { if (nMaxMailQueueLen == s_nMaxMailQueueLen && nMaxMailSendCount == s_nMaxMailSendCount) return EChange.UNCHANGED; s_nMaxMailQueueLen = nMaxMailQueueLen; s_nMaxMailSendCount = nMaxMailSendCount; return EChange.CHANGED; }); }
java
{ "resource": "" }
q15567
EmailGlobalSettings.setUseSSL
train
@Nonnull public static EChange setUseSSL (final boolean bUseSSL) { return s_aRWLock.writeLocked ( () -> { if (s_bUseSSL == bUseSSL) return EChange.UNCHANGED; s_bUseSSL = bUseSSL; return EChange.CHANGED; }); }
java
{ "resource": "" }
q15568
EmailGlobalSettings.setUseSTARTTLS
train
@Nonnull public static EChange setUseSTARTTLS (final boolean bUseSTARTTLS) { return s_aRWLock.writeLocked ( () -> { if (s_bUseSTARTTLS == bUseSTARTTLS) return EChange.UNCHANGED; s_bUseSTARTTLS = bUseSTARTTLS; return EChange.CHANGED; }); }
java
{ "resource": "" }
q15569
EmailGlobalSettings.setConnectionTimeoutMilliSecs
train
@Nonnull public static EChange setConnectionTimeoutMilliSecs (final long nMilliSecs) { return s_aRWLock.writeLocked ( () -> { if (s_nConnectionTimeoutMilliSecs == nMilliSecs) return EChange.UNCHANGED; if (nMilliSecs <= 0) LOGGER.warn ("You are setting an indefinite connection timeout for the mail transport api: " + nMilliSecs); s_nConnectionTimeoutMilliSecs = nMilliSecs; return EChange.CHANGED; }); }
java
{ "resource": "" }
q15570
EmailGlobalSettings.setTimeoutMilliSecs
train
@Nonnull public static EChange setTimeoutMilliSecs (final long nMilliSecs) { return s_aRWLock.writeLocked ( () -> { if (s_nTimeoutMilliSecs == nMilliSecs) return EChange.UNCHANGED; if (nMilliSecs <= 0) LOGGER.warn ("You are setting an indefinite socket timeout for the mail transport api: " + nMilliSecs); s_nTimeoutMilliSecs = nMilliSecs; return EChange.CHANGED; }); }
java
{ "resource": "" }
q15571
EmailGlobalSettings.addConnectionListener
train
public static void addConnectionListener (@Nonnull final ConnectionListener aConnectionListener) { ValueEnforcer.notNull (aConnectionListener, "ConnectionListener"); s_aRWLock.writeLocked ( () -> s_aConnectionListeners.add (aConnectionListener)); }
java
{ "resource": "" }
q15572
EmailGlobalSettings.removeConnectionListener
train
@Nonnull public static EChange removeConnectionListener (@Nullable final ConnectionListener aConnectionListener) { if (aConnectionListener == null) return EChange.UNCHANGED; return s_aRWLock.writeLocked ( () -> s_aConnectionListeners.removeObject (aConnectionListener)); }
java
{ "resource": "" }
q15573
EmailGlobalSettings.addEmailDataTransportListener
train
public static void addEmailDataTransportListener (@Nonnull final IEmailDataTransportListener aEmailDataTransportListener) { ValueEnforcer.notNull (aEmailDataTransportListener, "EmailDataTransportListener"); s_aRWLock.writeLocked ( () -> s_aEmailDataTransportListeners.add (aEmailDataTransportListener)); }
java
{ "resource": "" }
q15574
EmailGlobalSettings.removeEmailDataTransportListener
train
@Nonnull public static EChange removeEmailDataTransportListener (@Nullable final IEmailDataTransportListener aEmailDataTransportListener) { if (aEmailDataTransportListener == null) return EChange.UNCHANGED; return s_aRWLock.writeLocked ( () -> s_aEmailDataTransportListeners.removeObject (aEmailDataTransportListener)); }
java
{ "resource": "" }
q15575
EmailGlobalSettings.enableJavaxMailDebugging
train
@SuppressFBWarnings ("LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE") public static void enableJavaxMailDebugging (final boolean bDebug) { java.util.logging.Logger.getLogger ("com.sun.mail.smtp").setLevel (bDebug ? Level.FINEST : Level.INFO); java.util.logging.Logger.getLogger ("com.sun.mail.smtp.protocol").setLevel (bDebug ? Level.FINEST : Level.INFO); SystemProperties.setPropertyValue ("mail.socket.debug", bDebug); SystemProperties.setPropertyValue ("java.security.debug", bDebug ? "certpath" : null); SystemProperties.setPropertyValue ("javax.net.debug", bDebug ? "trustmanager" : null); }
java
{ "resource": "" }
q15576
EmailGlobalSettings.setToDefault
train
public static void setToDefault () { s_aRWLock.writeLocked ( () -> { s_nMaxMailQueueLen = DEFAULT_MAX_QUEUE_LENGTH; s_nMaxMailSendCount = DEFAULT_MAX_SEND_COUNT; s_bUseSSL = DEFAULT_USE_SSL; s_bUseSTARTTLS = DEFAULT_USE_STARTTLS; s_nConnectionTimeoutMilliSecs = DEFAULT_CONNECT_TIMEOUT_MILLISECS; s_nTimeoutMilliSecs = DEFAULT_TIMEOUT_MILLISECS; s_bDebugSMTP = GlobalDebug.isDebugMode (); s_aConnectionListeners.clear (); s_aEmailDataTransportListeners.clear (); }); }
java
{ "resource": "" }
q15577
GoogleMapsUrlSigner.convertToKeyByteArray
train
public static byte[] convertToKeyByteArray(String yourGooglePrivateKeyString) { yourGooglePrivateKeyString = yourGooglePrivateKeyString.replace('-', '+'); yourGooglePrivateKeyString = yourGooglePrivateKeyString.replace('_', '/'); return Base64.getDecoder().decode(yourGooglePrivateKeyString); }
java
{ "resource": "" }
q15578
GoogleMapsUrlSigner.signRequest
train
public static String signRequest(final String yourGooglePrivateKeyString, final String path, final String query) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException { // Retrieve the proper URL components to sign final String resource = path + '?' + query; // Get an HMAC-SHA1 signing key from the raw key bytes final SecretKeySpec sha1Key = new SecretKeySpec( convertToKeyByteArray(yourGooglePrivateKeyString), "HmacSHA1"); // Get an HMAC-SHA1 Mac instance and initialize it with the HMAC-SHA1 // key final Mac mac = Mac.getInstance("HmacSHA1"); mac.init(sha1Key); // compute the binary signature for the request final byte[] sigBytes = mac.doFinal(resource.getBytes()); // base 64 encode the binary signature // Base64 is JDK 1.8 only - older versions may need to use Apache // Commons or similar. String signature = Base64.getEncoder().encodeToString(sigBytes); // convert the signature to 'web safe' base 64 signature = signature.replace('+', '-'); signature = signature.replace('/', '_'); return resource + "&signature=" + signature; }
java
{ "resource": "" }
q15579
GoogleMapsUrlSigner.signRequest
train
public static String signRequest(final URL url, final String yourGooglePrivateKeyString) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException { // Retrieve the proper URL components to sign final String resource = url.getPath() + '?' + url.getQuery(); // Get an HMAC-SHA1 signing key from the raw key bytes final SecretKeySpec sha1Key = new SecretKeySpec( convertToKeyByteArray(yourGooglePrivateKeyString), "HmacSHA1"); // Get an HMAC-SHA1 Mac instance and initialize it with the HMAC-SHA1 // key final Mac mac = Mac.getInstance("HmacSHA1"); mac.init(sha1Key); // compute the binary signature for the request final byte[] sigBytes = mac.doFinal(resource.getBytes()); // base 64 encode the binary signature // Base64 is JDK 1.8 only - older versions may need to use Apache // Commons or similar. String signature = Base64.getEncoder().encodeToString(sigBytes); // convert the signature to 'web safe' base 64 signature = signature.replace('+', '-'); signature = signature.replace('/', '_'); final String signedRequestPath = resource + "&signature=" + signature; final String urlGoogleMapSignedRequest = url.getProtocol() + "://" + url.getHost() + signedRequestPath; return urlGoogleMapSignedRequest; }
java
{ "resource": "" }
q15580
UnifiedResponseDefaultSettings.setResponseHeader
train
public static void setResponseHeader (@Nonnull @Nonempty final String sName, @Nonnull @Nonempty final String sValue) { ValueEnforcer.notEmpty (sName, "Name"); ValueEnforcer.notEmpty (sValue, "Value"); s_aRWLock.writeLocked ( () -> s_aResponseHeaderMap.setHeader (sName, sValue)); }
java
{ "resource": "" }
q15581
UnifiedResponseDefaultSettings.addResponseHeader
train
public static void addResponseHeader (@Nonnull @Nonempty final String sName, @Nonnull @Nonempty final String sValue) { ValueEnforcer.notEmpty (sName, "Name"); ValueEnforcer.notEmpty (sValue, "Value"); s_aRWLock.writeLocked ( () -> s_aResponseHeaderMap.addHeader (sName, sValue)); }
java
{ "resource": "" }
q15582
MapHelper.merge
train
public static <S, T> Map<S, T> merge(Map<S, T> map, Map<S, T> toMerge) { Map<S, T> ret = new HashMap<S, T>(); ret.putAll(ensure(map)); ret.putAll(ensure(toMerge)); return ret; }
java
{ "resource": "" }
q15583
FileItemHeaders.addHeader
train
public void addHeader (@Nonnull final String sName, @Nullable final String sValue) { ValueEnforcer.notNull (sName, "HeaderName"); final String sNameLower = sName.toLowerCase (Locale.US); m_aRWLock.writeLocked ( () -> { ICommonsList <String> aHeaderValueList = m_aHeaderNameToValueListMap.get (sNameLower); if (aHeaderValueList == null) { aHeaderValueList = new CommonsArrayList <> (); m_aHeaderNameToValueListMap.put (sNameLower, aHeaderValueList); m_aHeaderNameList.add (sNameLower); } aHeaderValueList.add (sValue); }); }
java
{ "resource": "" }
q15584
CausticUtil.checkVersion
train
public static void checkVersion(GLVersioned required, GLVersioned object) { if (!debug) { return; } final GLVersion requiredVersion = required.getGLVersion(); final GLVersion objectVersion = object.getGLVersion(); if (objectVersion.getMajor() > requiredVersion.getMajor() && objectVersion.getMinor() > requiredVersion.getMinor()) { throw new IllegalStateException("Versions not compatible: expected " + requiredVersion + " or lower, got " + objectVersion); } }
java
{ "resource": "" }
q15585
CausticUtil.getPackedPixels
train
public static int[] getPackedPixels(ByteBuffer imageData, Format format, Rectangle size) { final int[] pixels = new int[size.getArea()]; final int width = size.getWidth(); final int height = size.getHeight(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { final int srcIndex = (x + y * width) * format.getComponentCount(); final int destIndex = x + (height - y - 1) * width; if (format.hasRed()) { pixels[destIndex] |= (imageData.get(srcIndex) & 0xff) << 16; } if (format.hasGreen()) { pixels[destIndex] |= (imageData.get(srcIndex + 1) & 0xff) << 8; } if (format.hasBlue()) { pixels[destIndex] |= imageData.get(srcIndex + 2) & 0xff; } if (format.hasAlpha()) { pixels[destIndex] |= (imageData.get(srcIndex + 3) & 0xff) << 24; } else { pixels[destIndex] |= 0xff000000; } } } return pixels; }
java
{ "resource": "" }
q15586
CausticUtil.getImage
train
public static BufferedImage getImage(ByteBuffer imageData, Format format, Rectangle size) { final int width = size.getWidth(); final int height = size.getHeight(); final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); final int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { final int srcIndex = (x + y * width) * format.getComponentCount(); final int destIndex = x + (height - y - 1) * width; if (format.hasRed()) { pixels[destIndex] |= (imageData.get(srcIndex) & 0xff) << 16; } if (format.hasGreen()) { pixels[destIndex] |= (imageData.get(srcIndex + 1) & 0xff) << 8; } if (format.hasBlue()) { pixels[destIndex] |= imageData.get(srcIndex + 2) & 0xff; } if (format.hasAlpha()) { pixels[destIndex] |= (imageData.get(srcIndex + 3) & 0xff) << 24; } else { pixels[destIndex] |= 0xff000000; } } } return image; }
java
{ "resource": "" }
q15587
CausticUtil.fromIntRGBA
train
public static Vector4f fromIntRGBA(int r, int g, int b, int a) { return new Vector4f((r & 0xff) / 255f, (g & 0xff) / 255f, (b & 0xff) / 255f, (a & 0xff) / 255f); }
java
{ "resource": "" }
q15588
CausticUtil.createByteBuffer
train
public static ByteBuffer createByteBuffer(int capacity) { return ByteBuffer.allocateDirect(capacity * DataType.BYTE.getByteSize()).order(ByteOrder.nativeOrder()); }
java
{ "resource": "" }
q15589
GenomicsDataSourceBase.getUnmappedMatesOfMappedReads
train
protected UnmappedReads<Read> getUnmappedMatesOfMappedReads(String readsetId) throws GeneralSecurityException, IOException { LOG.info("Collecting unmapped mates of mapped reads for injection"); final Iterable<Read> unmappedReadsIterable = getUnmappedReadsIterator(readsetId); final UnmappedReads<Read> unmappedReads = createUnmappedReads(); for (Read read : unmappedReadsIterable) { unmappedReads.maybeAddRead(read); } LOG.info("Finished collecting unmapped mates of mapped reads: " + unmappedReads.getReadCount() + " found."); return unmappedReads; }
java
{ "resource": "" }
q15590
Rectangle.set
train
public void set(Rectangle rectangle) { set(rectangle.getX(), rectangle.getY(), rectangle.getWidth(), rectangle.getHeight()); }
java
{ "resource": "" }
q15591
WebScopeSessionManager.getSessionWebScopeOfSession
train
@Nullable public static ISessionWebScope getSessionWebScopeOfSession (@Nullable final HttpSession aHttpSession) { return aHttpSession == null ? null : getSessionWebScopeOfID (aHttpSession.getId ()); }
java
{ "resource": "" }
q15592
WebScopeSessionManager.destroyAllWebSessions
train
public static void destroyAllWebSessions () { // destroy all session web scopes (make a copy, because we're invalidating // the sessions!) for (final ISessionWebScope aSessionScope : getAllSessionWebScopes ()) { // Unfortunately we need a special handling here if (aSessionScope.selfDestruct ().isContinue ()) { // Remove from map ScopeSessionManager.getInstance ().onScopeEnd (aSessionScope); } // Else the destruction was already started! } }
java
{ "resource": "" }
q15593
DiskFileItem.writeObject
train
private void writeObject (final ObjectOutputStream aOS) throws IOException { // Read the data if (m_aDFOS.isInMemory ()) { _ensureCachedContentIsPresent (); } else { m_aCachedContent = null; m_aDFOSFile = m_aDFOS.getFile (); } // write out values aOS.defaultWriteObject (); }
java
{ "resource": "" }
q15594
DiskFileItem.getSize
train
@Nonnegative public long getSize () { if (m_nSize >= 0) return m_nSize; if (m_aCachedContent != null) return m_aCachedContent.length; if (m_aDFOS.isInMemory ()) return m_aDFOS.getDataLength (); return m_aDFOS.getFile ().length (); }
java
{ "resource": "" }
q15595
DiskFileItem.directGet
train
@ReturnsMutableObject ("Speed") @SuppressFBWarnings ("EI_EXPOSE_REP") @Nullable public byte [] directGet () { if (isInMemory ()) { _ensureCachedContentIsPresent (); return m_aCachedContent; } return SimpleFileIO.getAllFileBytes (m_aDFOS.getFile ()); }
java
{ "resource": "" }
q15596
DiskFileItem.getStringWithFallback
train
@Nonnull public String getStringWithFallback (@Nonnull final Charset aFallbackCharset) { final String sCharset = getCharSet (); final Charset aCharset = CharsetHelper.getCharsetFromNameOrDefault (sCharset, aFallbackCharset); return getString (aCharset); }
java
{ "resource": "" }
q15597
GA4GHPicardRunner.run
train
public void run(String[] args) { LOG.info("Starting GA4GHPicardRunner"); try { parseCmdLine(args); buildPicardCommand(); startProcess(); pumpInputData(); waitForProcessEnd(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } }
java
{ "resource": "" }
q15598
GA4GHPicardRunner.parseCmdLine
train
void parseCmdLine(String[] args) { JCommander parser = new JCommander(this, args); parser.setProgramName("GA4GHPicardRunner"); LOG.info("Cmd line parsed"); }
java
{ "resource": "" }
q15599
GA4GHPicardRunner.buildPicardCommand
train
private void buildPicardCommand() throws IOException, GeneralSecurityException, URISyntaxException { File picardJarPath = new File(picardPath, "picard.jar"); if (!picardJarPath.exists()) { throw new IOException("Picard tool not found at " + picardJarPath.getAbsolutePath()); } command.add("java"); command.add(picardJVMArgs); command.add("-jar"); command.add(picardJarPath.getAbsolutePath()); command.add(picardTool); for (String picardArg : picardArgs) { if (picardArg.startsWith(INPUT_PREFIX)) { String inputPath = picardArg.substring(INPUT_PREFIX.length()); inputs.add(processInput(inputPath)); } else { command.add(picardArg); } } for (Input input : inputs) { command.add("INPUT=" + input.pipeName); } }
java
{ "resource": "" }