_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q15900
Comparables.nullSafeCompare
train
public static <Value extends Comparable<Value>> int nullSafeCompare(final Value first, final Value second) { if (first == null) { return second == null ? EQUAL_COMPARE_RESULT : LOWER_THAN_COMPARE_RESULT; } return second == null ? GREATER_THAN_COMPARE_RESULT : first.compareTo(second); }
java
{ "resource": "" }
q15901
SnomedClient.call
train
public Collection<Utterance> call(final AnalysisRequest request) { ClientResponse response = null; try { response = service.type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(ClientResponse.class, request); return response.getEntity(new GenericType<Collection<Utterance>>() {}); } finally { // belt and braces if (response != null) { //noinspection OverlyBroadCatchBlock try { response.close(); } catch (final Throwable ignored) { /* do nothing */ } } } }
java
{ "resource": "" }
q15902
GoXServletHandler.getURLForNonExistingItem
train
@Nonnull @OverrideOnDemand protected SimpleURL getURLForNonExistingItem (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final String sKey) { return new SimpleURL (aRequestScope.getFullContextPath ()); }
java
{ "resource": "" }
q15903
PhotonSessionState.state
train
@Nonnull public PhotonSessionStatePerApp state (@Nonnull @Nonempty final String sAppID) { ValueEnforcer.notEmpty (sAppID, "AppID"); return m_aStateMap.computeIfAbsent (sAppID, k -> new PhotonSessionStatePerApp ()); }
java
{ "resource": "" }
q15904
AbstractHCScriptInline.setMode
train
@Nonnull public final IMPLTYPE setMode (@Nonnull final EHCScriptInlineMode eMode) { m_eScriptMode = ValueEnforcer.notNull (eMode, "Mode"); return thisAsT (); }
java
{ "resource": "" }
q15905
JSCommentPart.format
train
protected void format (@Nonnull final JSFormatter aFormatter, @Nonnull final String sIndent) { if (!isEmpty ()) aFormatter.plain (sIndent); final Iterator <Object> aIter = iterator (); while (aIter.hasNext ()) { final Object aValue = aIter.next (); if (aValue instanceof String) { int nIdx; String sValue = (String) aValue; while ((nIdx = sValue.indexOf ('\n')) != -1) { final String sLine = sValue.substring (0, nIdx); if (sLine.length () > 0) aFormatter.plain (_escape (sLine)); sValue = sValue.substring (nIdx + 1); aFormatter.nlFix ().plain (sIndent); } if (sValue.length () != 0) aFormatter.plain (_escape (sValue)); } else if (aValue instanceof AbstractJSClass) { ((AbstractJSClass) aValue).printLink (aFormatter); } else if (aValue instanceof AbstractJSType) { aFormatter.generatable ((AbstractJSType) aValue); } else throw new IllegalStateException ("Unsupported value: " + aValue); } if (!isEmpty ()) aFormatter.nlFix (); }
java
{ "resource": "" }
q15906
JSCommentPart._escape
train
@Nonnull private static String _escape (@Nonnull final String sStr) { String ret = sStr; while (true) { final int idx = ret.indexOf ("*/"); if (idx < 0) return ret; ret = ret.substring (0, idx + 1) + "<!-- -->" + ret.substring (idx + 1); } }
java
{ "resource": "" }
q15907
Line.skipSpaces
train
public boolean skipSpaces () { while (m_nPos < m_sValue.length () && m_sValue.charAt (m_nPos) == ' ') m_nPos++; return m_nPos < m_sValue.length (); }
java
{ "resource": "" }
q15908
Line.readUntil
train
public String readUntil (final char... aEndChars) { final StringBuilder aSB = new StringBuilder (); int nPos = m_nPos; while (nPos < m_sValue.length ()) { final char ch = m_sValue.charAt (nPos); if (ch == '\\' && nPos + 1 < m_sValue.length ()) { final char c = m_sValue.charAt (nPos + 1); if (MarkdownHelper.isEscapeChar (c)) { aSB.append (c); nPos++; } else aSB.append (ch); } else { boolean bEndReached = false; for (final char cElement : aEndChars) if (ch == cElement) { bEndReached = true; break; } if (bEndReached) break; aSB.append (ch); } nPos++; } final char ch = nPos < m_sValue.length () ? m_sValue.charAt (nPos) : '\n'; for (final char cElement : aEndChars) if (ch == cElement) { m_nPos = nPos; return aSB.toString (); } return null; }
java
{ "resource": "" }
q15909
Line._countCharsStart
train
private int _countCharsStart (final char ch) { int nCount = 0; for (int i = 0; i < m_sValue.length (); i++) { final char c = m_sValue.charAt (i); if (c == ' ') continue; if (c != ch) break; nCount++; } return nCount; }
java
{ "resource": "" }
q15910
EndProcessor.assertThatEndMethodCheckFileExists
train
public static void assertThatEndMethodCheckFileExists(String uniqueFileName) throws IOException { Enumeration<URL> resources = ClassLoader.getSystemResources(uniqueFileName); if(!resources.hasMoreElements()) { throw new AssertionError("End method check uniqueFileName named: " + uniqueFileName + " doesn't exist.\n" + "Either you didn't use anywhere the annotation @EndMethodCheckFile(\"" + uniqueFileName + "\")\n" + "or the annotation processor wasn't invoked by the compiler and you have to check it's configuration.\n" + "For more about annotation processor configuration and possible issues see:\n" + "https://github.com/c0stra/fluent-api-end-check"); } URL url = resources.nextElement(); if(resources.hasMoreElements()) { throw new IllegalArgumentException("Too many files with the same name: " + uniqueFileName + " found on class-path.\n" + "Chosen end method check file name is not unique.\n" + "Files found:\n" + url + "\n" + resources.nextElement()); } }
java
{ "resource": "" }
q15911
FineUploader5Resume.setRecordsExpireIn
train
@Nonnull public FineUploader5Resume setRecordsExpireIn (@Nonnegative final int nRecordsExpireIn) { ValueEnforcer.isGE0 (nRecordsExpireIn, "RecordsExpireIn"); m_nResumeRecordsExpireIn = nRecordsExpireIn; return this; }
java
{ "resource": "" }
q15912
FineUploader5Resume.setParamNameResuming
train
@Nonnull public FineUploader5Resume setParamNameResuming (@Nonnull @Nonempty final String sParamNameResuming) { ValueEnforcer.notEmpty (sParamNameResuming, "ParamNameResuming"); m_sResumeParamNamesResuming = sParamNameResuming; return this; }
java
{ "resource": "" }
q15913
JavaCCParserImpl.badIdentifier
train
@Override protected String badIdentifier(String expected) { error(expected); final String id = "@" + (nextId++); if (!peekPunctuation()) { final Token token = getNextToken(); return "BAD_IDENTIFIER" + "_" + friendlyName(token) + id; } else { return "NO_IDENTIFIER" + id; } }
java
{ "resource": "" }
q15914
JavaCCParserImpl.error
train
private void error(String expected, String actual) { if (!recovering) { recovering = true; final String outputString = (EOF_STRING.equals(actual) || UNTERMINATED_COMMENT_STRING.equals(actual) || COMMENT_NOT_ALLOWED.equals(actual)) ? actual : "'" + actual + "'"; errors.add(SyntaxError._UnexpectedToken(expected, outputString, lookahead(1).beginLine)); } }
java
{ "resource": "" }
q15915
JavaCCParserImpl.friendlyName
train
private String friendlyName(Token token) { return token.kind == EOF ? EOF_STRING : token.kind == UNTERMINATED_COMMENT ? UNTERMINATED_COMMENT_STRING : token.image; }
java
{ "resource": "" }
q15916
JavaCCParserImpl.lookahead
train
private Token lookahead(int n) { Token current = token; for (int i = 0; i < n; i++) { if (current.next == null) { current.next = token_source.getNextToken(); } current = current.next; } return current; }
java
{ "resource": "" }
q15917
RoleManager.createNewRole
train
@Nonnull public IRole createNewRole (@Nonnull @Nonempty final String sName, @Nullable final String sDescription, @Nullable final Map <String, String> aCustomAttrs) { // Create role final Role aRole = new Role (sName, sDescription, aCustomAttrs); m_aRWLock.writeLocked ( () -> { // Store internalCreateItem (aRole); }); AuditHelper.onAuditCreateSuccess (Role.OT, aRole.getID (), sName); // Execute callback as the very last action m_aCallbacks.forEach (aCB -> aCB.onRoleCreated (aRole, false)); return aRole; }
java
{ "resource": "" }
q15918
RoleManager.createPredefinedRole
train
@Nonnull public IRole createPredefinedRole (@Nonnull @Nonempty final String sID, @Nonnull @Nonempty final String sName, @Nullable final String sDescription, @Nullable final Map <String, String> aCustomAttrs) { // Create role final Role aRole = new Role (StubObject.createForCurrentUserAndID (sID, aCustomAttrs), sName, sDescription); m_aRWLock.writeLocked ( () -> { // Store internalCreateItem (aRole); }); AuditHelper.onAuditCreateSuccess (Role.OT, aRole.getID (), "predefind-role", sName); // Execute callback as the very last action m_aCallbacks.forEach (aCB -> aCB.onRoleCreated (aRole, true)); return aRole; }
java
{ "resource": "" }
q15919
RoleManager.deleteRole
train
@Nonnull public EChange deleteRole (@Nullable final String sRoleID) { Role aDeletedRole; m_aRWLock.writeLock ().lock (); try { aDeletedRole = internalDeleteItem (sRoleID); if (aDeletedRole == null) { AuditHelper.onAuditDeleteFailure (Role.OT, "no-such-role-id", sRoleID); return EChange.UNCHANGED; } BusinessObjectHelper.setDeletionNow (aDeletedRole); } finally { m_aRWLock.writeLock ().unlock (); } AuditHelper.onAuditDeleteSuccess (Role.OT, sRoleID); // Execute callback as the very last action m_aCallbacks.forEach (aCB -> aCB.onRoleDeleted (aDeletedRole)); return EChange.CHANGED; }
java
{ "resource": "" }
q15920
RoleManager.renameRole
train
@Nonnull public EChange renameRole (@Nullable final String sRoleID, @Nonnull @Nonempty final String sNewName) { // Resolve user group final Role aRole = getOfID (sRoleID); if (aRole == null) { AuditHelper.onAuditModifyFailure (Role.OT, sRoleID, "no-such-id"); return EChange.UNCHANGED; } m_aRWLock.writeLock ().lock (); try { if (aRole.setName (sNewName).isUnchanged ()) return EChange.UNCHANGED; BusinessObjectHelper.setLastModificationNow (aRole); internalUpdateItem (aRole); } finally { m_aRWLock.writeLock ().unlock (); } AuditHelper.onAuditModifySuccess (Role.OT, "name", sRoleID, sNewName); // Execute callback as the very last action m_aCallbacks.forEach (aCB -> aCB.onRoleRenamed (aRole)); return EChange.CHANGED; }
java
{ "resource": "" }
q15921
FieldVisitor.visitAnnotation
train
public AnnotationVisitor visitAnnotation(String desc, boolean visible) { if (fv != null) { return fv.visitAnnotation(desc, visible); } return null; }
java
{ "resource": "" }
q15922
HCHelper.getFirstChildElement
train
@Nullable public static IMicroElement getFirstChildElement (@Nonnull final IMicroElement aElement, @Nonnull final EHTMLElement eHTMLElement) { ValueEnforcer.notNull (aElement, "element"); ValueEnforcer.notNull (eHTMLElement, "HTMLElement"); // First try with lower case name IMicroElement aChild = aElement.getFirstChildElement (eHTMLElement.getElementName ()); if (aChild == null) { // Fallback: try with upper case name aChild = aElement.getFirstChildElement (eHTMLElement.getElementNameUpperCase ()); } return aChild; }
java
{ "resource": "" }
q15923
HCHelper.getChildElements
train
@Nonnull @ReturnsMutableCopy public static ICommonsList <IMicroElement> getChildElements (@Nonnull final IMicroElement aElement, @Nonnull final EHTMLElement eHTMLElement) { ValueEnforcer.notNull (aElement, "element"); ValueEnforcer.notNull (eHTMLElement, "HTMLElement"); final ICommonsList <IMicroElement> ret = new CommonsArrayList <> (); ret.addAll (aElement.getAllChildElements (eHTMLElement.getElementName ())); ret.addAll (aElement.getAllChildElements (eHTMLElement.getElementNameUpperCase ())); return ret; }
java
{ "resource": "" }
q15924
HCHelper.getAsHTMLID
train
@Nonnull public static String getAsHTMLID (@Nullable final String sSrc) { String ret = StringHelper.getNotNull (sSrc, "").trim (); ret = StringHelper.removeMultiple (ret, ID_REMOVE_CHARS); return ret.isEmpty () ? "_" : ret; }
java
{ "resource": "" }
q15925
Hasher.hashSystemEnv
train
public String hashSystemEnv() { List<String> system = new ArrayList<String>(); for (Entry<Object, Object> el : System.getProperties().entrySet()) { system.add(el.getKey() + " " + el.getValue()); } Map<String, String> env = System.getenv(); for (Entry<String, String> el : env.entrySet()) { system.add(el.getKey() + " " + el.getValue()); } Collections.sort(system); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { DataOutputStream dos = new DataOutputStream(baos); for (String s : system) { dos.write(s.getBytes()); } } catch (IOException ex) { // never } return hashByteArray(baos.toByteArray()); }
java
{ "resource": "" }
q15926
Hasher.hashURL
train
protected String hashURL(URL url, String externalForm) { if (url == null) return ERR_HASH; String hash = path2Hash.get(externalForm); if (hash != null) { return hash; } if (mIsSemanticHashing) { byte[] bytes = FileUtil.loadBytes(url); if (bytes == null) return ERR_HASH; // Remove debug info from classfiles. bytes = BytecodeCleaner.removeDebugInfo(bytes); hash = hashByteArray(bytes); } else { // http://www.oracle.com/technetwork/articles/java/compress-1565076.html Checksum cksum = new Adler32(); byte[] bytes = FileUtil.loadBytes(url, cksum); if (bytes == null) return ERR_HASH; hash = Long.toString(cksum.getValue()); } path2Hash.put(externalForm, hash); return hash; }
java
{ "resource": "" }
q15927
Hasher.hashByteArray
train
protected String hashByteArray(byte[] data) { if (mCRC32 != null) { return hashCRC32(data); } else if (mHashAlgorithm != null) { return messageDigest(data); } else { // Default. return hashCRC32(data); } }
java
{ "resource": "" }
q15928
Types.isIgnorable
train
public static boolean isIgnorable(Class<?> clz) { return clz.isArray() || clz.isPrimitive() || isIgnorableBinName(clz.getName()); }
java
{ "resource": "" }
q15929
Types.isRetransformIgnorable
train
@Research public static boolean isRetransformIgnorable(Class<?> clz) { String className = clz.getName(); return (isIgnorableBinName(className) || className.startsWith(Names.ORG_APACHE_MAVEN_BIN, 0) || className.startsWith(Names.ORG_JUNIT_PACKAGE_BIN, 0) || className.startsWith(Names.JUNIT_FRAMEWORK_PACKAGE_BIN, 0)); }
java
{ "resource": "" }
q15930
Types.extractJarURL
train
public static URL extractJarURL(URL url) throws IOException { JarURLConnection connection = (JarURLConnection) url.openConnection(); return connection.getJarFileURL(); }
java
{ "resource": "" }
q15931
Types.isPrimitiveDesc
train
public static boolean isPrimitiveDesc(String desc) { if (desc.length() > 1) return false; char c = desc.charAt(0); return c == 'Z' || c == 'B' || c == 'C' || c == 'D' || c == 'F' || c == 'I' || c == 'J' || c == 'S'; }
java
{ "resource": "" }
q15932
BasePageShowChildrenRenderer.beforeAddRenderedMenuItem
train
@OverrideOnDemand public void beforeAddRenderedMenuItem (@Nonnull final IWebPageExecutionContext aWPEC, @Nonnull final IMenuObject aMenuObj, @Nullable final IHCElement <?> aPreviousLI) { if (aMenuObj.getMenuObjectType () == EMenuObjectType.SEPARATOR && aPreviousLI != null) aPreviousLI.addStyle (CCSSProperties.MARGIN_BOTTOM.newValue ("1em")); }
java
{ "resource": "" }
q15933
BasePageShowChildrenRenderer.renderMenuSeparator
train
@Nullable @OverrideOnDemand public IHCNode renderMenuSeparator (@Nonnull final IWebPageExecutionContext aWPEC, @Nonnull final IMenuSeparator aMenuSeparator) { return null; }
java
{ "resource": "" }
q15934
BasePageShowChildrenRenderer.renderMenuItemPage
train
@Nullable @OverrideOnDemand public IHCNode renderMenuItemPage (@Nonnull final IWebPageExecutionContext aWPEC, @Nonnull final IMenuItemPage aMenuItemPage) { if (!aMenuItemPage.matchesDisplayFilter ()) return null; final Locale aDisplayLocale = aWPEC.getDisplayLocale (); final HCA ret = new HCA (aWPEC.getLinkToMenuItem (aMenuItemPage.getID ())); // Set window target (if defined) if (aMenuItemPage.hasTarget ()) ret.setTarget (new HC_Target (aMenuItemPage.getTarget ())); ret.addChild (aMenuItemPage.getDisplayText (aDisplayLocale)); return ret; }
java
{ "resource": "" }
q15935
BasePageShowChildrenRenderer.renderMenuItemExternal
train
@Nullable @OverrideOnDemand public IHCNode renderMenuItemExternal (@Nonnull final IWebPageExecutionContext aWPEC, @Nonnull final IMenuItemExternal aMenuItemExternal) { if (!aMenuItemExternal.matchesDisplayFilter ()) return null; final Locale aDisplayLocale = aWPEC.getDisplayLocale (); final HCA ret = new HCA (aMenuItemExternal.getURL ()); // Set window target (if defined) if (aMenuItemExternal.hasTarget ()) ret.setTarget (new HC_Target (aMenuItemExternal.getTarget ())); ret.addChild (aMenuItemExternal.getDisplayText (aDisplayLocale)); return ret; }
java
{ "resource": "" }
q15936
AbstractJSBlock.removeByName
train
@Nonnull public EChange removeByName (final String sName) { final IJSDeclaration aDecl = m_aDecls.remove (sName); if (aDecl == null) return EChange.UNCHANGED; m_aObjs.remove (aDecl); return EChange.CHANGED; }
java
{ "resource": "" }
q15937
AbstractJSBlock.pos
train
@Nonnegative public int pos (@Nonnegative final int nNewPos) { ValueEnforcer.isBetweenInclusive (nNewPos, "NewPos", 0, m_aObjs.size ()); final int nOldPos = m_nPos; m_nPos = nNewPos; return nOldPos; }
java
{ "resource": "" }
q15938
AbstractJSBlock._class
train
@Nonnull public JSDefinedClass _class (@Nonnull @Nonempty final String sName) throws JSNameAlreadyExistsException { final JSDefinedClass aDefinedClass = new JSDefinedClass (sName); return addDeclaration (aDefinedClass); }
java
{ "resource": "" }
q15939
AbstractJSBlock._throw
train
@Nonnull public IMPLTYPE _throw (@Nonnull final IJSExpression aExpr) { addStatement (new JSThrow (aExpr)); return thisAsT (); }
java
{ "resource": "" }
q15940
AbstractJSBlock._if
train
@Nonnull public JSConditional _if (@Nonnull final IJSExpression aTest, @Nullable final IHasJSCode aThen) { return addStatement (new JSConditional (aTest, aThen)); }
java
{ "resource": "" }
q15941
AbstractJSBlock._return
train
@Nonnull public IMPLTYPE _return (@Nullable final IJSExpression aExpr) { addStatement (new JSReturn (aExpr)); return thisAsT (); }
java
{ "resource": "" }
q15942
InternalErrorBuilder.setDuplicateEliminiationCounter
train
@Nonnull public final InternalErrorBuilder setDuplicateEliminiationCounter (@Nonnegative final int nDuplicateEliminiationCounter) { ValueEnforcer.isGE0 (nDuplicateEliminiationCounter, "DuplicateEliminiationCounter"); m_nDuplicateEliminiationCounter = nDuplicateEliminiationCounter; return this; }
java
{ "resource": "" }
q15943
InternalErrorBuilder.setFromWebExecutionContext
train
@Nonnull public final InternalErrorBuilder setFromWebExecutionContext (@Nonnull final ISimpleWebExecutionContext aSWEC) { setDisplayLocale (aSWEC.getDisplayLocale ()); setRequestScope (aSWEC.getRequestScope ()); return this; }
java
{ "resource": "" }
q15944
InternalErrorBuilder.handle
train
@Nonnull @Nonempty public String handle () { return InternalErrorHandler.handleInternalError (m_bSendEmail, m_bSaveAsXML, m_aUIErrorHandler, m_aThrowable, m_aRequestScope, m_aCustomData, m_aEmailAttachments, m_aDisplayLocale, m_bInvokeCustomExceptionHandler, m_bAddClassPath, m_nDuplicateEliminiationCounter); }
java
{ "resource": "" }
q15945
BootstrapBorderBuilder.type
train
@Nonnull public BootstrapBorderBuilder type (@Nonnull final EBootstrapBorderType eType) { ValueEnforcer.notNull (eType, "Type"); m_eType = eType; return this; }
java
{ "resource": "" }
q15946
BootstrapBorderBuilder.radius
train
@Nonnull public BootstrapBorderBuilder radius (@Nonnull final EBootstrapBorderRadiusType eRadius) { ValueEnforcer.notNull (eRadius, "Radius"); m_eRadius = eRadius; return this; }
java
{ "resource": "" }
q15947
DataTablesHelper.createFunctionPrintSum
train
@Nonnull public static JSAnonymousFunction createFunctionPrintSum (@Nullable final String sPrefix, @Nullable final String sSuffix, @Nullable final String sBothPrefix, @Nullable final String sBothSep, @Nullable final String sBothSuffix) { final JSAnonymousFunction aFuncPrintSum = new JSAnonymousFunction (); IJSExpression aTotal = aFuncPrintSum.param ("t"); IJSExpression aPageTotal = aFuncPrintSum.param ("pt"); if (StringHelper.hasText (sPrefix)) { aTotal = JSExpr.lit (sPrefix).plus (aTotal); aPageTotal = JSExpr.lit (sPrefix).plus (aPageTotal); } if (StringHelper.hasText (sSuffix)) { aTotal = aTotal.plus (sSuffix); aPageTotal = aPageTotal.plus (sSuffix); } IJSExpression aBoth; if (StringHelper.hasText (sBothPrefix)) aBoth = JSExpr.lit (sBothPrefix).plus (aPageTotal); else aBoth = aPageTotal; if (StringHelper.hasText (sBothSep)) aBoth = aBoth.plus (sBothSep); aBoth = aBoth.plus (aTotal); if (StringHelper.hasText (sBothSuffix)) aBoth = aBoth.plus (sBothSuffix); aFuncPrintSum.body ()._return (JSOp.cond (aTotal.eq (aPageTotal), aTotal, aBoth)); return aFuncPrintSum; }
java
{ "resource": "" }
q15948
DataTablesHelper.createClearFilterCode
train
@Nonnull public static JSInvocation createClearFilterCode (@Nonnull final IJSExpression aDTSelect) { return aDTSelect.invoke ("DataTable") .invoke ("search") .arg ("") .invoke ("columns") .invoke ("search") .arg ("") .invoke ("draw"); }
java
{ "resource": "" }
q15949
DefaultBootstrapFormGroupRenderer.createSingleErrorNode
train
@Nullable @OverrideOnDemand protected IHCElement <?> createSingleErrorNode (@Nonnull final IError aError, @Nonnull final Locale aContentLocale) { return BootstrapFormHelper.createDefaultErrorNode (aError, aContentLocale); }
java
{ "resource": "" }
q15950
InvokableAPIDescriptor.canExecute
train
public boolean canExecute (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final MutableInt aStatusCode) { if (aRequestScope == null) return false; // Note: HTTP method was already checked in APIDescriptorList // Check required headers for (final String sRequiredHeader : m_aDescriptor.requiredHeaders ()) if (aRequestScope.headers ().getFirstHeaderValue (sRequiredHeader) == null) { LOGGER.warn ("Request '" + m_sPath + "' is missing required HTTP header '" + sRequiredHeader + "'"); return false; } // Check required parameters for (final String sRequiredParam : m_aDescriptor.requiredParams ()) if (!aRequestScope.params ().containsKey (sRequiredParam)) { LOGGER.warn ("Request '" + m_sPath + "' is missing required HTTP parameter '" + sRequiredParam + "'"); return false; } // Check explicit filter if (m_aDescriptor.hasExecutionFilter ()) if (!m_aDescriptor.getExecutionFilter ().canExecute (aRequestScope)) { LOGGER.warn ("Request '" + m_sPath + "' cannot be executed because of ExecutionFilter"); return false; } if (m_aDescriptor.allowedMimeTypes ().isNotEmpty ()) { final String sContentType = aRequestScope.getContentType (); // Parse to extract any parameters etc. final MimeType aMT = MimeTypeParser.safeParseMimeType (sContentType); // If parsing fails, use the provided String final String sMimeTypeToCheck = aMT == null ? sContentType : aMT.getAsStringWithoutParameters (); if (!m_aDescriptor.allowedMimeTypes ().contains (sMimeTypeToCheck) && !m_aDescriptor.allowedMimeTypes ().contains (sMimeTypeToCheck.toLowerCase (CGlobal.DEFAULT_LOCALE))) { LOGGER.warn ("Request '" + m_sPath + "' contains the Content-Type '" + sContentType + "' which is not in the allowed list of " + m_aDescriptor.allowedMimeTypes ()); // Special error code HTTP 415 aStatusCode.set (HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); return false; } } return true; }
java
{ "resource": "" }
q15951
PhotonHTMLHelper.getMimeType
train
@Nonnull public static IMimeType getMimeType (@Nullable final IRequestWebScopeWithoutResponse aRequestScope) { // Add the charset to the MIME type return new MimeType (CMimeType.TEXT_HTML).addParameter (CMimeType.PARAMETER_NAME_CHARSET, HCSettings.getHTMLCharset ().name ()); }
java
{ "resource": "" }
q15952
PhotonHTMLHelper.mergeExternalCSSAndJSNodes
train
public static void mergeExternalCSSAndJSNodes (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final HCHead aHead, final boolean bMergeCSS, final boolean bMergeJS, @Nonnull final IWebSiteResourceBundleProvider aWSRBMgr) { if (!bMergeCSS && !bMergeJS) { // Nothing to do return; } final boolean bRegular = HCSettings.isUseRegularResources (); if (bMergeCSS) { // Extract all CSS nodes for merging final ICommonsList <IHCNode> aCSSNodes = new CommonsArrayList <> (); aHead.getAllAndRemoveAllCSSNodes (aCSSNodes); final ICommonsList <WebSiteResourceWithCondition> aCSSs = new CommonsArrayList <> (); for (final IHCNode aNode : aCSSNodes) { boolean bStartMerge = true; if (HCCSSNodeDetector.isDirectCSSFileNode (aNode)) { final ICSSPathProvider aPathProvider = ((HCLink) aNode).getPathProvider (); if (aPathProvider != null) { aCSSs.add (WebSiteResourceWithCondition.createForCSS (aPathProvider, bRegular)); bStartMerge = false; } } if (bStartMerge) { if (!aCSSs.isEmpty ()) { for (final WebSiteResourceBundleSerialized aBundle : aWSRBMgr.getResourceBundles (aCSSs, bRegular)) aHead.addCSS (aBundle.createNode (aRequestScope)); aCSSs.clear (); } // Add the current (non-mergable) node again to head after merging aHead.addCSS (aNode); } } // Add the remaining nodes (if any) if (!aCSSs.isEmpty ()) for (final WebSiteResourceBundleSerialized aBundle : aWSRBMgr.getResourceBundles (aCSSs, bRegular)) aHead.addCSS (aBundle.createNode (aRequestScope)); } if (bMergeJS) { // Extract all JS nodes for merging final ICommonsList <IHCNode> aJSNodes = new CommonsArrayList <> (); aHead.getAllAndRemoveAllJSNodes (aJSNodes); final ICommonsList <WebSiteResourceWithCondition> aJSs = new CommonsArrayList <> (); for (final IHCNode aNode : aJSNodes) { boolean bStartMerge = true; if (HCJSNodeDetector.isDirectJSFileNode (aNode)) { final IJSPathProvider aPathProvider = ((HCScriptFile) aNode).getPathProvider (); if (aPathProvider != null) { aJSs.add (WebSiteResourceWithCondition.createForJS (aPathProvider, bRegular)); bStartMerge = false; } } if (bStartMerge) { if (!aJSs.isEmpty ()) { for (final WebSiteResourceBundleSerialized aBundle : aWSRBMgr.getResourceBundles (aJSs, bRegular)) aHead.addJS (aBundle.createNode (aRequestScope)); aJSs.clear (); } // Add the current (non-mergable) node again to head after merging aHead.addJS (aNode); } } // Add the remaining nodes (if any) if (!aJSs.isEmpty ()) for (final WebSiteResourceBundleSerialized aBundle : aWSRBMgr.getResourceBundles (aJSs, bRegular)) aHead.addJS (aBundle.createNode (aRequestScope)); } }
java
{ "resource": "" }
q15953
UserTokenManager.isAccessTokenUsed
train
public boolean isAccessTokenUsed (@Nullable final String sTokenString) { if (StringHelper.hasNoText (sTokenString)) return false; return containsAny (x -> x.findFirstAccessToken (y -> y.getTokenString ().equals (sTokenString)) != null); }
java
{ "resource": "" }
q15954
SurefireMojoInterceptor.execute
train
public static void execute(Object mojo) throws Exception { // Note that the object can be an instance of // AbstractSurefireMojo. if (!(isSurefirePlugin(mojo) || isFailsafePlugin(mojo))) { return; } // Check if the same object is already invoked. This may // happen (in the future) if execute method is in both // AbstractSurefire and SurefirePlugin classes. if (isAlreadyInvoked(mojo)) { return; } // Check if surefire version is supported. checkSurefireVersion(mojo); // Check surefire configuration. checkSurefireConfiguration(mojo); try { // Update argLine. updateArgLine(mojo); // Update excludes. updateExcludes(mojo); // Update parallel. updateParallel(mojo); } catch (Exception ex) { // This exception should not happen in theory. throwMojoExecutionException(mojo, "Unsupported surefire version", ex); } }
java
{ "resource": "" }
q15955
SurefireMojoInterceptor.checkSurefireVersion
train
private static void checkSurefireVersion(Object mojo) throws Exception { try { // Check version specific methods/fields. // mojo.getClass().getMethod(GET_RUN_ORDER); getField(SKIP_TESTS_FIELD, mojo); getField(FORK_MODE_FIELD, mojo); // We will always require the following. getField(ARGLINE_FIELD, mojo); getField(EXCLUDES_FIELD, mojo); } catch (NoSuchMethodException ex) { throwMojoExecutionException(mojo, "Unsupported surefire version. An alternative is to use select/restore goals.", ex); } }
java
{ "resource": "" }
q15956
SurefireMojoInterceptor.checkSurefireConfiguration
train
private static void checkSurefireConfiguration(Object mojo) throws Exception { String forkCount = null; try { forkCount = invokeAndGetString(GET_FORK_COUNT, mojo); } catch (NoSuchMethodException ex) { // Nothing: earlier versions (before 2.14) of surefire did // not have forkCount. } String forkMode = null; try { forkMode = getStringField(FORK_MODE_FIELD, mojo); } catch (NoSuchMethodException ex) { // Nothing: earlier versions (before 2.1) of surefire did // not have forkMode. } if ((forkCount != null && forkCount.equals("0")) || (forkMode != null && (forkMode.equals("never") || forkMode.equals("none")))) { throwMojoExecutionException(mojo, "Fork has to be enabled when running tests with Ekstazi; check forkMode and forkCount parameters.", null); } }
java
{ "resource": "" }
q15957
SurefireMojoInterceptor.updateParallel
train
private static void updateParallel(Object mojo) throws Exception { try { String currentParallel = getStringField(PARALLEL_FIELD, mojo); if (currentParallel != null) { warn(mojo, "Ekstazi does not support parallel parameter. This parameter will be set to null for this run."); setField(PARALLEL_FIELD, mojo, null); } } catch (NoSuchMethodException ex) { // "parallel" was introduced in Surefire 2.2, so methods // may not exist, but we do not fail because default is // sequential execution. } }
java
{ "resource": "" }
q15958
SurefireMojoInterceptor.isOneVMPerClass
train
private static boolean isOneVMPerClass(Object mojo) throws Exception { // We already know that we fork process (checked in // precondition). Threfore if we see reuseForks=false, we know // that one class will be run in one VM. try { return !invokeAndGetBoolean(IS_REUSE_FORKS, mojo); } catch (NoSuchMethodException ex) { // Nothing: earlier versions (before 2.13) of surefire did // not have reuseForks. return false; } }
java
{ "resource": "" }
q15959
ArrayObjectProvider.getProvider
train
public static <Type> ArrayObjectProvider<Type> getProvider(final Class<Type> arrayType) { return new ArrayObjectProvider<Type>(arrayType); }
java
{ "resource": "" }
q15960
FineUploader5Request.addCustomHeaders
train
@Nonnull public FineUploader5Request addCustomHeaders (@Nullable final Map <String, String> aCustomHeaders) { m_aRequestCustomHeaders.addAll (aCustomHeaders); return this; }
java
{ "resource": "" }
q15961
FineUploader5Request.setEndpoint
train
@Nonnull public FineUploader5Request setEndpoint (@Nonnull final ISimpleURL aRequestEndpoint) { ValueEnforcer.notNull (aRequestEndpoint, "RequestEndpoint"); m_aRequestEndpoint = aRequestEndpoint; return this; }
java
{ "resource": "" }
q15962
FineUploader5Request.setFilenameParam
train
@Nonnull public FineUploader5Request setFilenameParam (@Nonnull @Nonempty final String sFilenameParam) { ValueEnforcer.notEmpty (sFilenameParam, "FilenameParam"); m_sRequestFilenameParam = sFilenameParam; return this; }
java
{ "resource": "" }
q15963
FineUploader5Request.setUUIDName
train
@Nonnull public FineUploader5Request setUUIDName (@Nonnull @Nonempty final String sUUIDName) { ValueEnforcer.notEmpty (sUUIDName, "UUIDName"); m_sRequestUUIDName = sUUIDName; return this; }
java
{ "resource": "" }
q15964
FineUploader5Request.setTotalFileSizeName
train
@Nonnull public FineUploader5Request setTotalFileSizeName (@Nonnull @Nonempty final String sTotalFileSizeName) { ValueEnforcer.notEmpty (sTotalFileSizeName, "TotalFileSizeName"); m_sRequestTotalFileSizeName = sTotalFileSizeName; return this; }
java
{ "resource": "" }
q15965
WebSiteResourceWithCondition.canBeBundledWith
train
public boolean canBeBundledWith (@Nonnull final WebSiteResourceWithCondition aOther) { ValueEnforcer.notNull (aOther, "Other"); // Resource cannot be bundled at all if (!m_bIsBundlable || !aOther.isBundlable ()) return false; // Can only bundle resources of the same type if (!m_aResource.getResourceType ().equals (aOther.m_aResource.getResourceType ())) return false; // If the conditional comment is different, items cannot be bundled! if (!EqualsHelper.equals (m_sConditionalComment, aOther.m_sConditionalComment)) return false; // If the CSS media list is different, items cannot be bundled! if (!EqualsHelper.equals (m_aMediaList, aOther.m_aMediaList)) return false; // Can be bundled! return true; }
java
{ "resource": "" }
q15966
WebSiteResourceWithCondition.createForJS
train
@Nonnull public static WebSiteResourceWithCondition createForJS (@Nonnull final IJSPathProvider aPP, final boolean bRegular) { return createForJS (aPP.getJSItemPath (bRegular), aPP.getConditionalComment (), aPP.isBundlable ()); }
java
{ "resource": "" }
q15967
WebSiteResourceWithCondition.createForCSS
train
@Nonnull public static WebSiteResourceWithCondition createForCSS (@Nonnull final ICSSPathProvider aPP, final boolean bRegular) { return createForCSS (aPP.getCSSItemPath (bRegular), aPP.getConditionalComment (), aPP.isBundlable (), aPP.getMediaList ()); }
java
{ "resource": "" }
q15968
SecurityUIHelper.canBeDeleted
train
public static boolean canBeDeleted (@Nullable final IUser aUser) { return aUser != null && !aUser.isDeleted () && !aUser.isAdministrator (); }
java
{ "resource": "" }
q15969
DataTablesServerData.createConversionSettings
train
@Nonnull public static IHCConversionSettings createConversionSettings () { // Create HTML without namespaces final HCConversionSettings aRealCS = HCSettings.getMutableConversionSettings ().getClone (); aRealCS.getMutableXMLWriterSettings ().setEmitNamespaces (false); // Remove any "HCCustomizerAutoFocusFirstCtrl" customizer for AJAX calls on // DataTables final IHCCustomizer aCustomizer = aRealCS.getCustomizer (); if (aCustomizer instanceof HCCustomizerAutoFocusFirstCtrl) aRealCS.setCustomizer (null); else if (aCustomizer instanceof HCCustomizerList) ((HCCustomizerList) aCustomizer).removeAllCustomizersOfClass (HCCustomizerAutoFocusFirstCtrl.class); return aRealCS; }
java
{ "resource": "" }
q15970
PhotonCSS.unregisterCSSIncludeFromThisRequest
train
public static void unregisterCSSIncludeFromThisRequest (@Nonnull final ICSSPathProvider aCSSPathProvider) { final CSSResourceSet aSet = _getPerRequestSet (false); if (aSet != null) aSet.removeItem (aCSSPathProvider); }
java
{ "resource": "" }
q15971
HCOutput.setFor
train
@Nonnull public final HCOutput setFor (@Nullable final IHCHasID <?> aFor) { if (aFor == null) m_sFor = null; else m_sFor = aFor.ensureID ().getID (); return this; }
java
{ "resource": "" }
q15972
CoverageMethodVisitor.visitLdcInsn
train
@Override public void visitLdcInsn(Object cst) { // We use this method to support accesses to .class. if (cst instanceof Type) { int sort = ((Type) cst).getSort(); if (sort == Type.OBJECT) { String className = Types.descToInternalName(((Type) cst).getDescriptor()); insertTInvocation0(className, mProbeCounter.incrementAndGet()); } } mv.visitLdcInsn(cst); }
java
{ "resource": "" }
q15973
CoverageMethodVisitor.insertTInvocation0
train
private void insertTInvocation0(String className, int probeId) { // Check if class name has been seen since the last label. if (!mSeenClasses.add(className)) return; // Check if this class name should be ignored. if (Types.isIgnorableInternalName(className)) return; // x. (we tried). Surround invocation of monitor with // try/finally. This approach did not work in some cases as I // was using local variables to save exception exception that // has to be thrown; however, the same local variable may be // used in finally block, so I would override. // NOTE: The following is deprecated and excluded from code // (see monitor for new approach and accesses to fields): // We check if class contains "$" in which case we assume (without // consequences) that the class is inner and we invoke coverage method // that takes string as input. The reason for this special treatment is // access policy, as the inner class may be private and we cannot load // its .class. (See 57f5365935d26d2e6c47ec368612c6b003a2da79 for the // test that is throwing an exception without this.) However, note // that this slows down the execution a lot. // boolean isNonInnerClass = !className.contains("$"); boolean isNonInnerClass = true; // See the class visitor; currently we override // the version number to 49 for all classes that have lower version // number (so else branch should not be executed for this reason any // more). Earlier comment: Note that we have to use class name in case // of classes that have classfiles with major version of 48 or lower // as ldc could not load .class prior to version 49 (in theory we // could generate a method that does it for us, as the compiler // would do, but then we would change bytecode too much). if (isNonInnerClass && mIsNewerThanJava4) { insertTInvocation(className, probeId); } else { // DEPRECATED: This part is deprecated and should never be executed. // Using Class.forName(className) was very slow. mv.visitLdcInsn(className.replaceAll("/", ".")); mv.visitMethodInsn(Opcodes.INVOKESTATIC, Names.COVERAGE_MONITOR_VM, Instr.COVERAGE_MONITOR_MNAME, Instr.STRING_V_DESC, false); } }
java
{ "resource": "" }
q15974
AbstractEkstaziMojo.lookupPlugin
train
protected Plugin lookupPlugin(String key) { List<Plugin> plugins = project.getBuildPlugins(); for (Iterator<Plugin> iterator = plugins.iterator(); iterator.hasNext();) { Plugin plugin = iterator.next(); if(key.equalsIgnoreCase(plugin.getKey())) { return plugin; } } return null; }
java
{ "resource": "" }
q15975
AbstractEkstaziMojo.isRestoreGoalPresent
train
protected boolean isRestoreGoalPresent() { Plugin ekstaziPlugin = lookupPlugin(EKSTAZI_PLUGIN_KEY); if (ekstaziPlugin == null) { return false; } for (Object execution : ekstaziPlugin.getExecutions()) { for (Object goal : ((PluginExecution) execution).getGoals()) { if (((String) goal).equals("restore")) { return true; } } } return false; }
java
{ "resource": "" }
q15976
AbstractEkstaziMojo.restoreExcludesFile
train
private void restoreExcludesFile(File excludesFileFile) throws MojoExecutionException { if (!excludesFileFile.exists()) { return; } try { String[] lines = FileUtil.readLines(excludesFileFile); List<String> newLines = new ArrayList<String>(); for (String line : lines) { if (line.equals(EKSTAZI_LINE_MARKER)) break; newLines.add(line); } FileUtil.writeLines(excludesFileFile, newLines); } catch (IOException ex) { throw new MojoExecutionException("Could not restore 'excludesFile'", ex); } }
java
{ "resource": "" }
q15977
TraditionalKeyParser.parsePrivateKeyASN1
train
private static List<byte[]> parsePrivateKeyASN1(ByteBuffer byteBuffer) { final List<byte[]> collection = new ArrayList<byte[]>(); while (byteBuffer.hasRemaining()) { byte type = byteBuffer.get(); int length = UnsignedBytes.toInt(byteBuffer.get()); if ((length & 0x80) != 0) { int numberOfOctets = length ^ 0x80; length = 0; for (int i = 0; i < numberOfOctets; ++i) { int lengthChunk = UnsignedBytes.toInt(byteBuffer.get()); length += lengthChunk << (numberOfOctets - i - 1) * 8; } } if (length < 0) { throw new IllegalArgumentException(); } if (type == 0x30) { int position = byteBuffer.position(); byte[] data = Arrays.copyOfRange(byteBuffer.array(), position, position + length); return parsePrivateKeyASN1(ByteBuffer.wrap(data)); } if (type == 0x02) { byte[] segment = new byte[length]; byteBuffer.get(segment); collection.add(segment); } } return collection; }
java
{ "resource": "" }
q15978
PathDescriptorHelper.getCleanPathParts
train
@Nonnull @ReturnsMutableCopy public static ICommonsList <String> getCleanPathParts (@Nonnull final String sPath) { // Remove leading and trailing whitespaces and slashes String sRealPath = StringHelper.trimStartAndEnd (sPath.trim (), "/", "/"); // Remove obscure path parts sRealPath = FilenameHelper.getCleanPath (sRealPath); // Split into pieces final ICommonsList <String> aPathParts = StringHelper.getExploded ('/', sRealPath); return aPathParts; }
java
{ "resource": "" }
q15979
FineUploader5Paste.setDefaultName
train
@Nonnull public FineUploader5Paste setDefaultName (@Nonnull @Nonempty final String sDefaultName) { ValueEnforcer.notEmpty (sDefaultName, "DefaultName"); m_sPasteDefaultName = sDefaultName; return this; }
java
{ "resource": "" }
q15980
Inflector.ordinalize
train
public String ordinalize(int number) { String numberStr = Integer.toString(number); if (11 <= number && number <= 13) return numberStr + "th"; int remainder = number % 10; if (remainder == 1) return numberStr + "st"; if (remainder == 2) return numberStr + "nd"; if (remainder == 3) return numberStr + "rd"; return numberStr + "th"; }
java
{ "resource": "" }
q15981
AbstractLoginManager.isLoginInProgress
train
@OverrideOnDemand protected boolean isLoginInProgress (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope) { return CLogin.REQUEST_ACTION_VALIDATE_LOGIN_CREDENTIALS.equals (aRequestScope.params () .getAsString (CLogin.REQUEST_PARAM_ACTION)); }
java
{ "resource": "" }
q15982
AbstractLoginManager.getLoginName
train
@Nullable @OverrideOnDemand protected String getLoginName (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope) { return aRequestScope.params ().getAsString (CLogin.REQUEST_ATTR_USERID); }
java
{ "resource": "" }
q15983
AbstractLoginManager.getPassword
train
@Nullable @OverrideOnDemand protected String getPassword (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope) { return aRequestScope.params ().getAsString (CLogin.REQUEST_ATTR_PASSWORD); }
java
{ "resource": "" }
q15984
AbstractLoginManager.checkUserAndShowLogin
train
@Nonnull public final EContinue checkUserAndShowLogin (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final UnifiedResponse aUnifiedResponse) { final LoggedInUserManager aLoggedInUserManager = LoggedInUserManager.getInstance (); String sSessionUserID = aLoggedInUserManager.getCurrentUserID (); boolean bLoggedInInThisRequest = false; if (sSessionUserID == null) { // No user currently logged in -> start login boolean bLoginError = false; ICredentialValidationResult aLoginResult = ELoginResult.SUCCESS; // Is the special login-check action present? if (isLoginInProgress (aRequestScope)) { // Login screen was already shown // -> Check request parameters final String sLoginName = getLoginName (aRequestScope); final String sPassword = getPassword (aRequestScope); // Resolve user - may be null final IUser aUser = getUserOfLoginName (sLoginName); // Try main login aLoginResult = aLoggedInUserManager.loginUser (aUser, sPassword, m_aRequiredRoleIDs); if (aLoginResult.isSuccess ()) { // Credentials are valid - implies that the user was resolved // correctly sSessionUserID = aUser.getID (); bLoggedInInThisRequest = true; } else { // Credentials are invalid if (GlobalDebug.isDebugMode ()) LOGGER.warn ("Login of '" + sLoginName + "' failed because " + aLoginResult); // Anyway show the error message only if at least some credential // values are passed bLoginError = StringHelper.hasText (sLoginName) || StringHelper.hasText (sPassword); } } if (sSessionUserID == null) { // Show login screen as no user is in the session final IHTMLProvider aLoginScreenProvider = createLoginScreen (bLoginError, aLoginResult); PhotonHTMLHelper.createHTMLResponse (aRequestScope, aUnifiedResponse, aLoginScreenProvider); } } // Update details final LoginInfo aLoginInfo = aLoggedInUserManager.getLoginInfo (sSessionUserID); if (aLoginInfo != null) { // Update last login info aLoginInfo.setLastAccessDTNow (); // Set custom attributes modifyLoginInfo (aLoginInfo, aRequestScope, bLoggedInInThisRequest); } else { // Internal inconsistency if (sSessionUserID != null) LOGGER.error ("Failed to resolve LoginInfo of user ID '" + sSessionUserID + "'"); } if (bLoggedInInThisRequest) { // Avoid double submit by simply redirecting to the desired destination // URL without the login parameters aUnifiedResponse.setRedirect (aRequestScope.getURL ()); return EContinue.BREAK; } // Continue only, if a valid user ID is present return EContinue.valueOf (sSessionUserID != null); }
java
{ "resource": "" }
q15985
JSFormHelper.setSelectOptions
train
@Nonnull public static JSInvocation setSelectOptions (@Nonnull final IJSExpression aSelector, @Nonnull final IJSExpression aValueList) { return getFormHelper ().invoke ("setSelectOptions").arg (aSelector).arg (aValueList); }
java
{ "resource": "" }
q15986
TxtStorer.isMagicCorrect
train
protected boolean isMagicCorrect(BufferedReader br) throws IOException { if (mCheckMagicSequence) { String magicLine = br.readLine(); return (magicLine != null && magicLine.equals(mMode.getMagicSequence())); } else { return true; } }
java
{ "resource": "" }
q15987
TxtStorer.parseLine
train
protected RegData parseLine(State state, String line) { // Note. Initial this method was using String.split, but that method // seems to be much more expensive than playing with indexOf and // substring. int sepIndex = line.indexOf(SEPARATOR); String urlExternalForm = line.substring(0, sepIndex); String hash = line.substring(sepIndex + SEPARATOR_LEN); return new RegData(urlExternalForm, hash); }
java
{ "resource": "" }
q15988
TxtStorer.printLine
train
protected void printLine(State state, Writer pw, String externalForm, String hash) throws IOException { pw.write(externalForm); pw.write(SEPARATOR); pw.write(hash); pw.write('\n'); }
java
{ "resource": "" }
q15989
FloatRange.update
train
public void update(final float delta) { if (transitionInProgress) { currentValue += (targetValue - initialValue) * delta / transitionLength; if (isInitialGreater) { if (currentValue <= targetValue) { finalizeTransition(); } } else { if (currentValue >= targetValue) { finalizeTransition(); } } } }
java
{ "resource": "" }
q15990
FloatRange.setCurrentValue
train
public void setCurrentValue(final float currentValue) { this.currentValue = currentValue; initialValue = currentValue; targetValue = currentValue; transitionInProgress = false; }
java
{ "resource": "" }
q15991
UITextFormatter.markdown
train
@Nonnull public static IHCNode markdown (@Nullable final String sMD) { try { final HCNodeList aNL = MARKDOWN_PROC.process (sMD).getNodeList (); // Replace a single <p> element with its contents if (aNL.getChildCount () == 1 && aNL.getChildAtIndex (0) instanceof HCP) return ((HCP) aNL.getChildAtIndex (0)).getAllChildrenAsNodeList (); return aNL; } catch (final Exception ex) { LOGGER.warn ("Failed to markdown '" + sMD + "': " + ex.getMessage ()); return new HCTextNode (sMD); } }
java
{ "resource": "" }
q15992
AbstractWebPage.getContent
train
public final void getContent (@Nonnull final WPECTYPE aWPEC) { if (isValidToDisplayPage (aWPEC).isValid ()) { // "before"-callback beforeFillContent (aWPEC); // Create the main page content fillContent (aWPEC); // "after"-callback afterFillContent (aWPEC); } else { // Invalid to display page onInvalidToDisplayPage (aWPEC); } }
java
{ "resource": "" }
q15993
AbstractWebPage.addAjax
train
@Nonnull public static final AjaxFunctionDeclaration addAjax (@Nullable final String sPrefix, @Nonnull final IAjaxExecutor aExecutor) { // null means random name final String sFuncName = StringHelper.hasText (sPrefix) ? sPrefix + AjaxFunctionDeclaration.getUniqueFunctionID () : null; final AjaxFunctionDeclaration aFunction = AjaxFunctionDeclaration.builder (sFuncName) .withExecutor (aExecutor) .build (); GlobalAjaxInvoker.getInstance ().getRegistry ().registerFunction (aFunction); return aFunction; }
java
{ "resource": "" }
q15994
QRSCT.reference
train
public QRSCT reference(String reference) { if (reference != null && reference.length() <= 35) { this.text = ""; //$NON-NLS-1$ this.reference = checkValidSigns(reference); return this; } throw new IllegalArgumentException("supplied reference [" + reference //$NON-NLS-1$ + "] not valid: has to be not null and of max length 35"); //$NON-NLS-1$ }
java
{ "resource": "" }
q15995
QRSCT.text
train
public QRSCT text(String text) { if (text != null && text.length() <= 140) { this.reference = ""; //$NON-NLS-1$ this.text = checkValidSigns(text); return this; } throw new IllegalArgumentException("supplied text [" + text //$NON-NLS-1$ + "] not valid: has to be not null and of max length 140"); //$NON-NLS-1$ }
java
{ "resource": "" }
q15996
ProcessDomainMojo.processClasspath
train
private void processClasspath(String classpathElement) throws ResourceNotFoundException, ParseErrorException, Exception { // getLog().info("Classpath is " + classpathElement); if (classpathElement.endsWith(".jar")) { // TODO: implement JAR scanning } else { final File dir = new File(classpathElement); processPackage(dir, dir); } }
java
{ "resource": "" }
q15997
ProcessDomainMojo.processPackage
train
private void processPackage(File root, File dir) { getLog().debug("- package: " + dir); if (null != dir && dir.isDirectory()) { for (File f : dir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory() || pathname.getName().endsWith(".class"); } })) { if (f.isDirectory()) { processPackage(root, f); } else if (f.getParentFile().getAbsolutePath().replace(File.separatorChar, '.').endsWith(basePackage + '.' + domainPackageName)) { final String simpleName = f.getName().substring(0, f.getName().lastIndexOf(".class")); final String className = String.format("%s.%s.%s", basePackage, domainPackageName, simpleName); getLog().debug(String.format("--- class %s", className)); try { Class clazz = loader.loadClass(className); if (!Modifier.isAbstract(clazz.getModifiers()) && isEntity(clazz)) { getLog().debug("@Entity " + clazz.getName()); final Entity entity = new Entity(); entity.setClazz(clazz); final String packageName = clazz.getPackage().getName(); Group group = packages.get(packageName); if (null == group) { group = new Group(); group.setName(packageName); packages.put(packageName, group); } group.getEntities().put(simpleName, entity); entities.put(entity.getClassName(), entity); } } catch (ClassNotFoundException ex) { Logger.getLogger(ProcessDomainMojo.class.getName()).log(Level.SEVERE, null, ex); } } } } }
java
{ "resource": "" }
q15998
XMLHolidayManager._getHolidays
train
@Nonnull @ReturnsMutableCopy private HolidayMap _getHolidays (final int nYear, @Nonnull final Configuration aConfig, @Nullable final String... aArgs) { if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Adding holidays for " + aConfig.getDescription ()); final HolidayMap aHolidayMap = new HolidayMap (); for (final IHolidayParser aParser : _getParsers (aConfig.getHolidays ())) aParser.parse (nYear, aHolidayMap, aConfig.getHolidays ()); if (ArrayHelper.isNotEmpty (aArgs)) { final String sHierarchy = aArgs[0]; for (final Configuration aSubConfig : aConfig.getSubConfigurations ()) { if (sHierarchy.equalsIgnoreCase (aSubConfig.getHierarchy ())) { // Recursive call final HolidayMap aSubHolidays = _getHolidays (nYear, aSubConfig, ArrayHelper.getCopy (aArgs, 1, aArgs.length - 1)); aHolidayMap.addAll (aSubHolidays); break; } } } return aHolidayMap; }
java
{ "resource": "" }
q15999
XMLHolidayManager._validateConfigurationHierarchy
train
private static void _validateConfigurationHierarchy (@Nonnull final Configuration aConfig) { final ICommonsSet <String> aHierarchySet = new CommonsHashSet <> (); for (final Configuration aSubConfig : aConfig.getSubConfigurations ()) { final String sHierarchy = aSubConfig.getHierarchy (); if (!aHierarchySet.add (sHierarchy)) throw new IllegalArgumentException ("Configuration for " + aConfig.getHierarchy () + " contains multiple SubConfigurations with the same hierarchy id '" + sHierarchy + "'. "); } for (final Configuration aSubConfig : aConfig.getSubConfigurations ()) _validateConfigurationHierarchy (aSubConfig); }
java
{ "resource": "" }