code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public NucleotideCompound getAmbiguity(NucleotideCompound... compounds) { Set<NucleotideCompound> settedCompounds = new HashSet<NucleotideCompound>(); for(NucleotideCompound compound: compounds) { for(NucleotideCompound subCompound: compound.getConstituents()) { settedCompounds.add(getCompoundForString(subCompound.getBase().toUpperCase())); } } for(NucleotideCompound compound: getAllCompounds()) { if(compound.getConstituents().equals(settedCompounds)) { return compound; } } return null; } }
public class class_name { public NucleotideCompound getAmbiguity(NucleotideCompound... compounds) { Set<NucleotideCompound> settedCompounds = new HashSet<NucleotideCompound>(); for(NucleotideCompound compound: compounds) { for(NucleotideCompound subCompound: compound.getConstituents()) { settedCompounds.add(getCompoundForString(subCompound.getBase().toUpperCase())); // depends on control dependency: [for], data = [subCompound] } } for(NucleotideCompound compound: getAllCompounds()) { if(compound.getConstituents().equals(settedCompounds)) { return compound; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { private static final AbstractMessageParser createParser (final ProtocolDataUnit protocolDataUnit, final OperationCode operationCode) { switch (operationCode) { case LOGIN_REQUEST : return new LoginRequestParser(protocolDataUnit); case LOGIN_RESPONSE : return new LoginResponseParser(protocolDataUnit); case LOGOUT_REQUEST : return new LogoutRequestParser(protocolDataUnit); case LOGOUT_RESPONSE : return new LogoutResponseParser(protocolDataUnit); case TEXT_REQUEST : return new TextRequestParser(protocolDataUnit); case TEXT_RESPONSE : return new TextResponseParser(protocolDataUnit); case SCSI_DATA_OUT : return new DataOutParser(protocolDataUnit); case SCSI_DATA_IN : return new DataInParser(protocolDataUnit); case NOP_OUT : return new NOPOutParser(protocolDataUnit); case NOP_IN : return new NOPInParser(protocolDataUnit); case R2T : return new Ready2TransferParser(protocolDataUnit); case REJECT : return new RejectParser(protocolDataUnit); case SNACK_REQUEST : return new SNACKRequestParser(protocolDataUnit); case SCSI_TM_REQUEST : return new TaskManagementFunctionRequestParser(protocolDataUnit); case SCSI_TM_RESPONSE : return new TaskManagementFunctionResponseParser(protocolDataUnit); case SCSI_COMMAND : return new SCSICommandParser(protocolDataUnit); case SCSI_RESPONSE : return new SCSIResponseParser(protocolDataUnit); default : if (LOGGER.isErrorEnabled()) { LOGGER.error("Parser not supported with this operation code " + operationCode); } throw new NoSuchElementException(); } } }
public class class_name { private static final AbstractMessageParser createParser (final ProtocolDataUnit protocolDataUnit, final OperationCode operationCode) { switch (operationCode) { case LOGIN_REQUEST : return new LoginRequestParser(protocolDataUnit); case LOGIN_RESPONSE : return new LoginResponseParser(protocolDataUnit); case LOGOUT_REQUEST : return new LogoutRequestParser(protocolDataUnit); case LOGOUT_RESPONSE : return new LogoutResponseParser(protocolDataUnit); case TEXT_REQUEST : return new TextRequestParser(protocolDataUnit); case TEXT_RESPONSE : return new TextResponseParser(protocolDataUnit); case SCSI_DATA_OUT : return new DataOutParser(protocolDataUnit); case SCSI_DATA_IN : return new DataInParser(protocolDataUnit); case NOP_OUT : return new NOPOutParser(protocolDataUnit); case NOP_IN : return new NOPInParser(protocolDataUnit); case R2T : return new Ready2TransferParser(protocolDataUnit); case REJECT : return new RejectParser(protocolDataUnit); case SNACK_REQUEST : return new SNACKRequestParser(protocolDataUnit); case SCSI_TM_REQUEST : return new TaskManagementFunctionRequestParser(protocolDataUnit); case SCSI_TM_RESPONSE : return new TaskManagementFunctionResponseParser(protocolDataUnit); case SCSI_COMMAND : return new SCSICommandParser(protocolDataUnit); case SCSI_RESPONSE : return new SCSIResponseParser(protocolDataUnit); default : if (LOGGER.isErrorEnabled()) { LOGGER.error("Parser not supported with this operation code " + operationCode); // depends on control dependency: [if], data = [none] } throw new NoSuchElementException(); } } }
public class class_name { public final EObject ruleXBooleanLiteral() throws RecognitionException { EObject current = null; Token otherlv_1=null; Token lv_isTrue_2_0=null; enterRule(); try { // InternalXbase.g:4670:2: ( ( () (otherlv_1= 'false' | ( (lv_isTrue_2_0= 'true' ) ) ) ) ) // InternalXbase.g:4671:2: ( () (otherlv_1= 'false' | ( (lv_isTrue_2_0= 'true' ) ) ) ) { // InternalXbase.g:4671:2: ( () (otherlv_1= 'false' | ( (lv_isTrue_2_0= 'true' ) ) ) ) // InternalXbase.g:4672:3: () (otherlv_1= 'false' | ( (lv_isTrue_2_0= 'true' ) ) ) { // InternalXbase.g:4672:3: () // InternalXbase.g:4673:4: { if ( state.backtracking==0 ) { current = forceCreateModelElement( grammarAccess.getXBooleanLiteralAccess().getXBooleanLiteralAction_0(), current); } } // InternalXbase.g:4679:3: (otherlv_1= 'false' | ( (lv_isTrue_2_0= 'true' ) ) ) int alt81=2; int LA81_0 = input.LA(1); if ( (LA81_0==75) ) { alt81=1; } else if ( (LA81_0==76) ) { alt81=2; } else { if (state.backtracking>0) {state.failed=true; return current;} NoViableAltException nvae = new NoViableAltException("", 81, 0, input); throw nvae; } switch (alt81) { case 1 : // InternalXbase.g:4680:4: otherlv_1= 'false' { otherlv_1=(Token)match(input,75,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_1, grammarAccess.getXBooleanLiteralAccess().getFalseKeyword_1_0()); } } break; case 2 : // InternalXbase.g:4685:4: ( (lv_isTrue_2_0= 'true' ) ) { // InternalXbase.g:4685:4: ( (lv_isTrue_2_0= 'true' ) ) // InternalXbase.g:4686:5: (lv_isTrue_2_0= 'true' ) { // InternalXbase.g:4686:5: (lv_isTrue_2_0= 'true' ) // InternalXbase.g:4687:6: lv_isTrue_2_0= 'true' { lv_isTrue_2_0=(Token)match(input,76,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_isTrue_2_0, grammarAccess.getXBooleanLiteralAccess().getIsTrueTrueKeyword_1_1_0()); } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXBooleanLiteralRule()); } setWithLastConsumed(current, "isTrue", true, "true"); } } } } break; } } } if ( state.backtracking==0 ) { leaveRule(); } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } }
public class class_name { public final EObject ruleXBooleanLiteral() throws RecognitionException { EObject current = null; Token otherlv_1=null; Token lv_isTrue_2_0=null; enterRule(); try { // InternalXbase.g:4670:2: ( ( () (otherlv_1= 'false' | ( (lv_isTrue_2_0= 'true' ) ) ) ) ) // InternalXbase.g:4671:2: ( () (otherlv_1= 'false' | ( (lv_isTrue_2_0= 'true' ) ) ) ) { // InternalXbase.g:4671:2: ( () (otherlv_1= 'false' | ( (lv_isTrue_2_0= 'true' ) ) ) ) // InternalXbase.g:4672:3: () (otherlv_1= 'false' | ( (lv_isTrue_2_0= 'true' ) ) ) { // InternalXbase.g:4672:3: () // InternalXbase.g:4673:4: { if ( state.backtracking==0 ) { current = forceCreateModelElement( grammarAccess.getXBooleanLiteralAccess().getXBooleanLiteralAction_0(), current); // depends on control dependency: [if], data = [none] } } // InternalXbase.g:4679:3: (otherlv_1= 'false' | ( (lv_isTrue_2_0= 'true' ) ) ) int alt81=2; int LA81_0 = input.LA(1); if ( (LA81_0==75) ) { alt81=1; // depends on control dependency: [if], data = [none] } else if ( (LA81_0==76) ) { alt81=2; // depends on control dependency: [if], data = [none] } else { if (state.backtracking>0) {state.failed=true; return current;} // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none] NoViableAltException nvae = new NoViableAltException("", 81, 0, input); throw nvae; } switch (alt81) { case 1 : // InternalXbase.g:4680:4: otherlv_1= 'false' { otherlv_1=(Token)match(input,75,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(otherlv_1, grammarAccess.getXBooleanLiteralAccess().getFalseKeyword_1_0()); // depends on control dependency: [if], data = [none] } } break; case 2 : // InternalXbase.g:4685:4: ( (lv_isTrue_2_0= 'true' ) ) { // InternalXbase.g:4685:4: ( (lv_isTrue_2_0= 'true' ) ) // InternalXbase.g:4686:5: (lv_isTrue_2_0= 'true' ) { // InternalXbase.g:4686:5: (lv_isTrue_2_0= 'true' ) // InternalXbase.g:4687:6: lv_isTrue_2_0= 'true' { lv_isTrue_2_0=(Token)match(input,76,FOLLOW_2); if (state.failed) return current; if ( state.backtracking==0 ) { newLeafNode(lv_isTrue_2_0, grammarAccess.getXBooleanLiteralAccess().getIsTrueTrueKeyword_1_1_0()); // depends on control dependency: [if], data = [none] } if ( state.backtracking==0 ) { if (current==null) { current = createModelElement(grammarAccess.getXBooleanLiteralRule()); // depends on control dependency: [if], data = [none] } setWithLastConsumed(current, "isTrue", true, "true"); // depends on control dependency: [if], data = [none] } } } } break; } } } if ( state.backtracking==0 ) { leaveRule(); // depends on control dependency: [if], data = [none] } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } }
public class class_name { public static String tryToTrimToSize(String s, int length, boolean trimSuffix) { if (s == null || s.isEmpty()) { return s; } else if (s.length() <= length) { return s; } else if (s.contains(File.separator)) { String before = s.substring(0, s.lastIndexOf(File.separator)); String after = s.substring(s.lastIndexOf(File.separator)); if (!trimSuffix && length - after.length() > 4) { return Strings.tryToTrimToSize(before, length - after.length(), true) + after; } else { return Strings.tryToTrimToSize(before, length - 3, true) + File.separator + ".."; } } else { return ".."; } } }
public class class_name { public static String tryToTrimToSize(String s, int length, boolean trimSuffix) { if (s == null || s.isEmpty()) { return s; // depends on control dependency: [if], data = [none] } else if (s.length() <= length) { return s; // depends on control dependency: [if], data = [none] } else if (s.contains(File.separator)) { String before = s.substring(0, s.lastIndexOf(File.separator)); String after = s.substring(s.lastIndexOf(File.separator)); if (!trimSuffix && length - after.length() > 4) { return Strings.tryToTrimToSize(before, length - after.length(), true) + after; // depends on control dependency: [if], data = [none] } else { return Strings.tryToTrimToSize(before, length - 3, true) + File.separator + ".."; // depends on control dependency: [if], data = [none] } } else { return ".."; // depends on control dependency: [if], data = [none] } } }
public class class_name { public String convert(final String value, final boolean is4YearTerm) { final Matcher matcher = PATTERN_NUM.matcher(value); if(!matcher.matches()) { // 一致しない場合は、単純に数値の変換 return replaceSimple(value); } final String before = matcher.group(1); final String num = matcher.group(2); final String after = matcher.group(3); if(is4YearTerm && num.length() == 4) { // 年の桁は、単純に数値変換する return replaceSimple(before) + replaceSimple(num) + replaceSimple(after); } else { return replaceSimple(before) + replaceDisits(num) + replaceSimple(after); } } }
public class class_name { public String convert(final String value, final boolean is4YearTerm) { final Matcher matcher = PATTERN_NUM.matcher(value); if(!matcher.matches()) { // 一致しない場合は、単純に数値の変換 return replaceSimple(value); // depends on control dependency: [if], data = [none] } final String before = matcher.group(1); final String num = matcher.group(2); final String after = matcher.group(3); if(is4YearTerm && num.length() == 4) { // 年の桁は、単純に数値変換する return replaceSimple(before) + replaceSimple(num) + replaceSimple(after); // depends on control dependency: [if], data = [none] } else { return replaceSimple(before) + replaceDisits(num) + replaceSimple(after); // depends on control dependency: [if], data = [none] } } }
public class class_name { synchronized boolean updateKeystoreConfig(Dictionary<String, Object> props) { properties = props; if (id != null) { properties.put(Constants.SSLPROP_ALIAS, id); } String location = (String) properties.get(LibertyConstants.KEY_KEYSTORE_LOCATION); if (location != null) { properties.put(Constants.SSLPROP_KEY_STORE, locSvc.getServiceWithException().resolveString(location)); } try { // Try modifying the properties.. // This may throw if arguments are bad wsKeyStore = new WSKeyStore(id, properties, this); KeyStoreManager.getInstance().addKeyStoreToMap(id, wsKeyStore); KeyStoreManager.getInstance().addKeyStoreToMap(pid, wsKeyStore); return true; } catch (Exception e) { wsKeyStore = null; return false; } } }
public class class_name { synchronized boolean updateKeystoreConfig(Dictionary<String, Object> props) { properties = props; if (id != null) { properties.put(Constants.SSLPROP_ALIAS, id); // depends on control dependency: [if], data = [none] } String location = (String) properties.get(LibertyConstants.KEY_KEYSTORE_LOCATION); if (location != null) { properties.put(Constants.SSLPROP_KEY_STORE, locSvc.getServiceWithException().resolveString(location)); // depends on control dependency: [if], data = [(location] } try { // Try modifying the properties.. // This may throw if arguments are bad wsKeyStore = new WSKeyStore(id, properties, this); // depends on control dependency: [try], data = [none] KeyStoreManager.getInstance().addKeyStoreToMap(id, wsKeyStore); // depends on control dependency: [try], data = [none] KeyStoreManager.getInstance().addKeyStoreToMap(pid, wsKeyStore); // depends on control dependency: [try], data = [none] return true; // depends on control dependency: [try], data = [none] } catch (Exception e) { wsKeyStore = null; return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Internal private static void pushAnnotationAttributes(Type declaringType, ClassVisitor declaringClassWriter, GeneratorAdapter generatorAdapter, Map<? extends CharSequence, Object> annotationData, Map<String, GeneratorAdapter> loadTypeMethods) { int totalSize = annotationData.size() * 2; // start a new array pushNewArray(generatorAdapter, Object.class, totalSize); int i = 0; for (Map.Entry<? extends CharSequence, Object> entry : annotationData.entrySet()) { // use the property name as the key String memberName = entry.getKey().toString(); pushStoreStringInArray(generatorAdapter, i++, totalSize, memberName); // use the property type as the value Object value = entry.getValue(); pushStoreInArray(generatorAdapter, i++, totalSize, () -> pushValue(declaringType, declaringClassWriter, generatorAdapter, value, loadTypeMethods) ); } // invoke the AbstractBeanDefinition.createMap method generatorAdapter.invokeStatic(Type.getType(AnnotationUtil.class), METHOD_MAP_OF); } }
public class class_name { @Internal private static void pushAnnotationAttributes(Type declaringType, ClassVisitor declaringClassWriter, GeneratorAdapter generatorAdapter, Map<? extends CharSequence, Object> annotationData, Map<String, GeneratorAdapter> loadTypeMethods) { int totalSize = annotationData.size() * 2; // start a new array pushNewArray(generatorAdapter, Object.class, totalSize); int i = 0; for (Map.Entry<? extends CharSequence, Object> entry : annotationData.entrySet()) { // use the property name as the key String memberName = entry.getKey().toString(); pushStoreStringInArray(generatorAdapter, i++, totalSize, memberName); // depends on control dependency: [for], data = [none] // use the property type as the value Object value = entry.getValue(); pushStoreInArray(generatorAdapter, i++, totalSize, () -> pushValue(declaringType, declaringClassWriter, generatorAdapter, value, loadTypeMethods) ); // depends on control dependency: [for], data = [none] } // invoke the AbstractBeanDefinition.createMap method generatorAdapter.invokeStatic(Type.getType(AnnotationUtil.class), METHOD_MAP_OF); } }
public class class_name { @SuppressWarnings("unchecked") private void updateXmlContents( I_CmsReport report, String resourcePath, boolean inclSubFolder, CmsObject cmsObject) { // write parameters to report report.println(Messages.get().container(Messages.RPT_UPDATEXML_BEGIN_UPDATE_0), I_CmsReport.FORMAT_NOTE); report.println(Messages.get().container(Messages.RPT_UPDATEXML_PARAMETERS_0), I_CmsReport.FORMAT_HEADLINE); report.println( Messages.get().container(Messages.RPT_UPDATEXML_PARAMETERS_RESOURCE_PATH_1, resourcePath), I_CmsReport.FORMAT_NOTE); report.println( Messages.get().container( Messages.RPT_UPDATEXML_PARAMETERS_INC_SUBFOLDERS_1, new Boolean(inclSubFolder).toString()), I_CmsReport.FORMAT_NOTE); // check for valid parameters (vfs folder) if (CmsStringUtil.isEmpty(resourcePath)) { report.println(Messages.get().container(Messages.RPT_UPDATEXML_NO_VFS_FOLDER_0), I_CmsReport.FORMAT_ERROR); return; } // read all files in the vfs folder report.println(Messages.get().container(Messages.RPT_UPDATEXML_START_SEARCHING_0), I_CmsReport.FORMAT_HEADLINE); List<CmsResource> allFiles = null; try { allFiles = cmsObject.readResources(resourcePath, CmsResourceFilter.DEFAULT, inclSubFolder); } catch (CmsException e) { m_errorUpdate += 1; report.println(Messages.get().container(Messages.RPT_UPDATEXML_SEARCH_ERROR_0), I_CmsReport.FORMAT_ERROR); if (LOG.isErrorEnabled()) { LOG.error(e.getMessageContainer(), e); } report.println(Messages.get().container(Messages.RPT_UPDATEXML_END_UPDATE_0), I_CmsReport.FORMAT_NOTE); return; } // get the files to update List<CmsResource> files2Update = new ArrayList<CmsResource>(); Iterator<CmsResource> iter = allFiles.iterator(); while (iter.hasNext()) { CmsResource cmsResource = iter.next(); // only update Xml contents if (cmsResource.isFile() && (CmsResourceTypeXmlContent.isXmlContent(cmsResource) || CmsResourceTypeXmlPage.isXmlPage(cmsResource))) { files2Update.add(cmsResource); } } // number of files to update int nrOfFiles = files2Update.size(); report.println( Messages.get().container(Messages.RPT_UPDATEXML_FILES_TO_UPDATE_1, new Integer(nrOfFiles).toString()), I_CmsReport.FORMAT_NOTE); // the file counter int fileCounter = 0; // update the files if (nrOfFiles > 0) { // report entry report.println( Messages.get().container(Messages.RPT_UPDATEXML_START_UPDATING_0), I_CmsReport.FORMAT_HEADLINE); // loop over all files iter = files2Update.iterator(); while (iter.hasNext()) { CmsResource cmsResource = iter.next(); fileCounter += 1; // report entries report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_SUCCESSION_2, String.valueOf(fileCounter), String.valueOf(nrOfFiles)), I_CmsReport.FORMAT_NOTE); report.print(Messages.get().container(Messages.RPT_UPDATEXML_CURRENT_FILE_0), I_CmsReport.FORMAT_NOTE); report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_ARGUMENT_1, report.removeSiteRoot(cmsResource.getRootPath()))); report.print( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0), I_CmsReport.FORMAT_DEFAULT); // get current lock from file try { // try to lock the resource if (!lockResource(cmsObject, cmsResource, report)) { report.println( Messages.get().container( Messages.RPT_UPDATEXML_LOCKED_FILE_0, cmsObject.getSitePath(cmsResource)), I_CmsReport.FORMAT_ERROR); continue; } } catch (CmsException e) { report.println( Messages.get().container( Messages.RPT_UPDATEXML_LOCKED_FILE_0, cmsObject.getSitePath(cmsResource)), I_CmsReport.FORMAT_ERROR); if (LOG.isErrorEnabled()) { LOG.error(e.getMessageContainer(), e); } continue; } // write the resource try { // do not change the date last modified long lastModified = cmsResource.getDateLastModified(); CmsFile cmsFile = cmsObject.readFile(cmsResource); cmsFile.setDateLastModified(lastModified); cmsObject.writeFile(cmsFile); } catch (Exception e) { m_errorUpdate += 1; report.println( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_FAILED_0), I_CmsReport.FORMAT_ERROR); if (LOG.isErrorEnabled()) { LOG.error(e.toString()); } continue; } // unlock the resource try { cmsObject.unlockResource(cmsObject.getSitePath(cmsResource)); } catch (CmsException e) { m_errorUpdate += 1; report.println( Messages.get().container(Messages.RPT_UPDATEXML_UNLOCK_FILE_0), I_CmsReport.FORMAT_WARNING); if (LOG.isErrorEnabled()) { LOG.error(e.getMessageContainer(), e); } continue; } // successfully updated report.println( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0), I_CmsReport.FORMAT_OK); } } else { // no files to update report.println(Messages.get().container(Messages.RPT_UPDATEXML_NO_FILES_FOUND_0), I_CmsReport.FORMAT_NOTE); } // the results are written in the report report.println(Messages.get().container(Messages.RPT_UPDATEXML_RESULT_0), I_CmsReport.FORMAT_HEADLINE); report.println( Messages.get().container(Messages.RPT_UPDATEXML_FILES_TO_UPDATE_1, new Integer(nrOfFiles).toString()), I_CmsReport.FORMAT_NOTE); report.println( Messages.get().container( Messages.RPT_UPDATEXML_UPDATE_NUMBER_ERRORS_1, new Integer(m_errorUpdate).toString()), I_CmsReport.FORMAT_NOTE); report.println( Messages.get().container(Messages.RPT_UPDATEXML_LOCKED_FILES_1, new Integer(m_lockedFiles).toString()), I_CmsReport.FORMAT_NOTE); if (m_lockedFiles > 0) { report.println(Messages.get().container(Messages.RPT_UPDATEXML_UPDATE_FAILED_0), I_CmsReport.FORMAT_ERROR); } else { report.println(Messages.get().container(Messages.RPT_UPDATEXML_UPDATE_SUCCESS_0), I_CmsReport.FORMAT_OK); } report.println(Messages.get().container(Messages.RPT_UPDATEXML_END_UPDATE_0), I_CmsReport.FORMAT_NOTE); } }
public class class_name { @SuppressWarnings("unchecked") private void updateXmlContents( I_CmsReport report, String resourcePath, boolean inclSubFolder, CmsObject cmsObject) { // write parameters to report report.println(Messages.get().container(Messages.RPT_UPDATEXML_BEGIN_UPDATE_0), I_CmsReport.FORMAT_NOTE); report.println(Messages.get().container(Messages.RPT_UPDATEXML_PARAMETERS_0), I_CmsReport.FORMAT_HEADLINE); report.println( Messages.get().container(Messages.RPT_UPDATEXML_PARAMETERS_RESOURCE_PATH_1, resourcePath), I_CmsReport.FORMAT_NOTE); report.println( Messages.get().container( Messages.RPT_UPDATEXML_PARAMETERS_INC_SUBFOLDERS_1, new Boolean(inclSubFolder).toString()), I_CmsReport.FORMAT_NOTE); // check for valid parameters (vfs folder) if (CmsStringUtil.isEmpty(resourcePath)) { report.println(Messages.get().container(Messages.RPT_UPDATEXML_NO_VFS_FOLDER_0), I_CmsReport.FORMAT_ERROR); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } // read all files in the vfs folder report.println(Messages.get().container(Messages.RPT_UPDATEXML_START_SEARCHING_0), I_CmsReport.FORMAT_HEADLINE); List<CmsResource> allFiles = null; try { allFiles = cmsObject.readResources(resourcePath, CmsResourceFilter.DEFAULT, inclSubFolder); // depends on control dependency: [try], data = [none] } catch (CmsException e) { m_errorUpdate += 1; report.println(Messages.get().container(Messages.RPT_UPDATEXML_SEARCH_ERROR_0), I_CmsReport.FORMAT_ERROR); if (LOG.isErrorEnabled()) { LOG.error(e.getMessageContainer(), e); // depends on control dependency: [if], data = [none] } report.println(Messages.get().container(Messages.RPT_UPDATEXML_END_UPDATE_0), I_CmsReport.FORMAT_NOTE); return; } // depends on control dependency: [catch], data = [none] // get the files to update List<CmsResource> files2Update = new ArrayList<CmsResource>(); Iterator<CmsResource> iter = allFiles.iterator(); while (iter.hasNext()) { CmsResource cmsResource = iter.next(); // only update Xml contents if (cmsResource.isFile() && (CmsResourceTypeXmlContent.isXmlContent(cmsResource) || CmsResourceTypeXmlPage.isXmlPage(cmsResource))) { files2Update.add(cmsResource); // depends on control dependency: [if], data = [none] } } // number of files to update int nrOfFiles = files2Update.size(); report.println( Messages.get().container(Messages.RPT_UPDATEXML_FILES_TO_UPDATE_1, new Integer(nrOfFiles).toString()), I_CmsReport.FORMAT_NOTE); // the file counter int fileCounter = 0; // update the files if (nrOfFiles > 0) { // report entry report.println( Messages.get().container(Messages.RPT_UPDATEXML_START_UPDATING_0), I_CmsReport.FORMAT_HEADLINE); // depends on control dependency: [if], data = [none] // loop over all files iter = files2Update.iterator(); // depends on control dependency: [if], data = [none] while (iter.hasNext()) { CmsResource cmsResource = iter.next(); fileCounter += 1; // depends on control dependency: [while], data = [none] // report entries report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_SUCCESSION_2, String.valueOf(fileCounter), String.valueOf(nrOfFiles)), I_CmsReport.FORMAT_NOTE); // depends on control dependency: [while], data = [none] report.print(Messages.get().container(Messages.RPT_UPDATEXML_CURRENT_FILE_0), I_CmsReport.FORMAT_NOTE); // depends on control dependency: [while], data = [none] report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_ARGUMENT_1, report.removeSiteRoot(cmsResource.getRootPath()))); // depends on control dependency: [while], data = [none] report.print( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0), I_CmsReport.FORMAT_DEFAULT); // depends on control dependency: [while], data = [none] // get current lock from file try { // try to lock the resource if (!lockResource(cmsObject, cmsResource, report)) { report.println( Messages.get().container( Messages.RPT_UPDATEXML_LOCKED_FILE_0, cmsObject.getSitePath(cmsResource)), I_CmsReport.FORMAT_ERROR); // depends on control dependency: [if], data = [none] continue; } } catch (CmsException e) { report.println( Messages.get().container( Messages.RPT_UPDATEXML_LOCKED_FILE_0, cmsObject.getSitePath(cmsResource)), I_CmsReport.FORMAT_ERROR); if (LOG.isErrorEnabled()) { LOG.error(e.getMessageContainer(), e); // depends on control dependency: [if], data = [none] } continue; } // depends on control dependency: [catch], data = [none] // write the resource try { // do not change the date last modified long lastModified = cmsResource.getDateLastModified(); CmsFile cmsFile = cmsObject.readFile(cmsResource); cmsFile.setDateLastModified(lastModified); // depends on control dependency: [try], data = [none] cmsObject.writeFile(cmsFile); // depends on control dependency: [try], data = [none] } catch (Exception e) { m_errorUpdate += 1; report.println( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_FAILED_0), I_CmsReport.FORMAT_ERROR); if (LOG.isErrorEnabled()) { LOG.error(e.toString()); // depends on control dependency: [if], data = [none] } continue; } // depends on control dependency: [catch], data = [none] // unlock the resource try { cmsObject.unlockResource(cmsObject.getSitePath(cmsResource)); // depends on control dependency: [try], data = [none] } catch (CmsException e) { m_errorUpdate += 1; report.println( Messages.get().container(Messages.RPT_UPDATEXML_UNLOCK_FILE_0), I_CmsReport.FORMAT_WARNING); if (LOG.isErrorEnabled()) { LOG.error(e.getMessageContainer(), e); // depends on control dependency: [if], data = [none] } continue; } // depends on control dependency: [catch], data = [none] // successfully updated report.println( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0), I_CmsReport.FORMAT_OK); // depends on control dependency: [while], data = [none] } } else { // no files to update report.println(Messages.get().container(Messages.RPT_UPDATEXML_NO_FILES_FOUND_0), I_CmsReport.FORMAT_NOTE); // depends on control dependency: [if], data = [0)] } // the results are written in the report report.println(Messages.get().container(Messages.RPT_UPDATEXML_RESULT_0), I_CmsReport.FORMAT_HEADLINE); report.println( Messages.get().container(Messages.RPT_UPDATEXML_FILES_TO_UPDATE_1, new Integer(nrOfFiles).toString()), I_CmsReport.FORMAT_NOTE); report.println( Messages.get().container( Messages.RPT_UPDATEXML_UPDATE_NUMBER_ERRORS_1, new Integer(m_errorUpdate).toString()), I_CmsReport.FORMAT_NOTE); report.println( Messages.get().container(Messages.RPT_UPDATEXML_LOCKED_FILES_1, new Integer(m_lockedFiles).toString()), I_CmsReport.FORMAT_NOTE); if (m_lockedFiles > 0) { report.println(Messages.get().container(Messages.RPT_UPDATEXML_UPDATE_FAILED_0), I_CmsReport.FORMAT_ERROR); // depends on control dependency: [if], data = [0)] } else { report.println(Messages.get().container(Messages.RPT_UPDATEXML_UPDATE_SUCCESS_0), I_CmsReport.FORMAT_OK); // depends on control dependency: [if], data = [0)] } report.println(Messages.get().container(Messages.RPT_UPDATEXML_END_UPDATE_0), I_CmsReport.FORMAT_NOTE); } }
public class class_name { public EClass getIfcFaceBasedSurfaceModel() { if (ifcFaceBasedSurfaceModelEClass == null) { ifcFaceBasedSurfaceModelEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(221); } return ifcFaceBasedSurfaceModelEClass; } }
public class class_name { public EClass getIfcFaceBasedSurfaceModel() { if (ifcFaceBasedSurfaceModelEClass == null) { ifcFaceBasedSurfaceModelEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(221); // depends on control dependency: [if], data = [none] } return ifcFaceBasedSurfaceModelEClass; } }
public class class_name { public CreatePhoneNumberOrderRequest withE164PhoneNumbers(String... e164PhoneNumbers) { if (this.e164PhoneNumbers == null) { setE164PhoneNumbers(new java.util.ArrayList<String>(e164PhoneNumbers.length)); } for (String ele : e164PhoneNumbers) { this.e164PhoneNumbers.add(ele); } return this; } }
public class class_name { public CreatePhoneNumberOrderRequest withE164PhoneNumbers(String... e164PhoneNumbers) { if (this.e164PhoneNumbers == null) { setE164PhoneNumbers(new java.util.ArrayList<String>(e164PhoneNumbers.length)); // depends on control dependency: [if], data = [none] } for (String ele : e164PhoneNumbers) { this.e164PhoneNumbers.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { void close(boolean closeFromWebUI, boolean remoteJTFailure) throws IOException, InterruptedException { synchronized (closeLock) { checkJTEnd1FailureEvent(); if (!running) { return; } running = false; if (job != null) { job.close(); } reportJobStats(); int jobState = 0; if (sessionDriver != null) { if (job == null) { if (remoteJTFailure) { // There will be no feedback from remote JT because it died. sessionDriver.stop(SessionStatus.FAILED_JOBTRACKER); } else { // The remote JT will have the real status. jobState = JobStatus.SUCCEEDED; sessionDriver.stop(getSessionEndStatus(jobState)); } } else { jobState = job.getStatus().getRunState(); if (jobState != JobStatus.SUCCEEDED) { // We will report task failure counts only if the job succeeded. trackerStats.resetFailedCount(); } sessionDriver.stop( getSessionEndStatus(jobState), ResourceTracker.resourceTypes(), trackerStats.getNodeUsageReports()); } } if (stateFetcher != null) { clearJobHistoryCache(); stateFetcher.close(); } if (commitPermissionClient != null) { commitPermissionClient.close(); } if (localJTSubmitter != null) { localJTSubmitter.close(); } // Close parent client after closing submitter if (parentClient != null) { RPC.stopProxy(parentClient); } if (expireTasks != null) { expireTasks.shutdown(); expireTasks.interrupt(); expireTasks.join(); } if (resourceUpdaterThread != null) { resourceUpdaterThread.interrupt(); resourceUpdaterThread.join(); } if (assignTasksThread != null) { assignTasksThread.interrupt(); assignTasksThread.join(); } if (sessionDriver != null) { sessionDriver.join(); } if (commitTasksThread != null) { commitTasksThread.interrupt(); commitTasksThread.join(); } if (taskLauncher != null && (jobState == JobStatus.SUCCEEDED || closeFromWebUI || this.isPurgingJob || isLastTryForFailover())) { // We only kill the job when it succeeded or killed by user from // webUI or it is the last retry for failover // when StateRestoring enabled for job tracker failover. // In other case, we want to keep it and do fail over for // finished tasks LOG.info("call taskLauncher.killJob for job: " + jobId); taskLauncher.killJob(jobId, resourceTracker.allTrackers()); } if (infoServer != null) { if (closeFromWebUI) { // If we are being called from the web UI, this function is executing // in a web-server thread. Give some time to the web-server to // clean up. infoServer.setGracefulShutdown(1000); } try { // Unavoidable catch-all because of AbstractLifeCycle.stop(). infoServer.stop(); LOG.info("InfoServer stopped."); } catch (Exception ex) { LOG.warn("Exception shutting down web server ", ex); } } if (jobHistory != null) { try { LOG.info("mark job history done"); jobHistory.markCompleted(); } catch (IOException ioe) { LOG.warn("Failed to mark job " + jobId + " as completed!", ioe); } jobHistory.shutdown(); checkJTEnd2FailureEvent(); } closePJTClient(); // Stop RPC server. This is done near the end of the function // since this could be called through a RPC heartbeat call. // If (standalone == true) // - dont stop the RPC server at all. When this cannot talk to the parent, // it will exit the process. // if (standalone == false) // - if there is no remote JT, close right away // - if there is a remote JT, close after 1min. if (interTrackerServer != null) { if (!isStandalone) { if (remoteJT == null) { interTrackerServer.stop(); } else { final int timeout = conf.getInt(RPC_SERVER_STOP_TIMEOUT, 0); if (timeout > 0) { LOG.info("Starting async thread to stop RPC server for " + jobId); Thread async = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(timeout); LOG.info("Stopping RPC server for " + jobId); interTrackerServer.stop(); remoteJT.close(); } catch (InterruptedException e) { LOG.warn( "Interrupted during wait before stopping RPC server"); } } }); async.setDaemon(true); async.start(); } } } } synchronized (lockObject) { closed = true; lockObject.notifyAll(); } } } }
public class class_name { void close(boolean closeFromWebUI, boolean remoteJTFailure) throws IOException, InterruptedException { synchronized (closeLock) { checkJTEnd1FailureEvent(); if (!running) { return; } running = false; if (job != null) { job.close(); } reportJobStats(); int jobState = 0; if (sessionDriver != null) { if (job == null) { if (remoteJTFailure) { // There will be no feedback from remote JT because it died. sessionDriver.stop(SessionStatus.FAILED_JOBTRACKER); // depends on control dependency: [if], data = [none] } else { // The remote JT will have the real status. jobState = JobStatus.SUCCEEDED; // depends on control dependency: [if], data = [none] sessionDriver.stop(getSessionEndStatus(jobState)); // depends on control dependency: [if], data = [none] } } else { jobState = job.getStatus().getRunState(); if (jobState != JobStatus.SUCCEEDED) { // We will report task failure counts only if the job succeeded. trackerStats.resetFailedCount(); // depends on control dependency: [if], data = [none] } sessionDriver.stop( getSessionEndStatus(jobState), ResourceTracker.resourceTypes(), trackerStats.getNodeUsageReports()); } } if (stateFetcher != null) { clearJobHistoryCache(); stateFetcher.close(); } if (commitPermissionClient != null) { commitPermissionClient.close(); } if (localJTSubmitter != null) { localJTSubmitter.close(); } // Close parent client after closing submitter if (parentClient != null) { RPC.stopProxy(parentClient); } if (expireTasks != null) { expireTasks.shutdown(); expireTasks.interrupt(); expireTasks.join(); } if (resourceUpdaterThread != null) { resourceUpdaterThread.interrupt(); resourceUpdaterThread.join(); } if (assignTasksThread != null) { assignTasksThread.interrupt(); assignTasksThread.join(); } if (sessionDriver != null) { sessionDriver.join(); } if (commitTasksThread != null) { commitTasksThread.interrupt(); commitTasksThread.join(); } if (taskLauncher != null && (jobState == JobStatus.SUCCEEDED || closeFromWebUI || this.isPurgingJob || isLastTryForFailover())) { // We only kill the job when it succeeded or killed by user from // webUI or it is the last retry for failover // when StateRestoring enabled for job tracker failover. // In other case, we want to keep it and do fail over for // finished tasks LOG.info("call taskLauncher.killJob for job: " + jobId); taskLauncher.killJob(jobId, resourceTracker.allTrackers()); } if (infoServer != null) { if (closeFromWebUI) { // If we are being called from the web UI, this function is executing // in a web-server thread. Give some time to the web-server to // clean up. infoServer.setGracefulShutdown(1000); } try { // Unavoidable catch-all because of AbstractLifeCycle.stop(). infoServer.stop(); LOG.info("InfoServer stopped."); } catch (Exception ex) { LOG.warn("Exception shutting down web server ", ex); } } if (jobHistory != null) { try { LOG.info("mark job history done"); jobHistory.markCompleted(); } catch (IOException ioe) { LOG.warn("Failed to mark job " + jobId + " as completed!", ioe); } jobHistory.shutdown(); checkJTEnd2FailureEvent(); } closePJTClient(); // Stop RPC server. This is done near the end of the function // since this could be called through a RPC heartbeat call. // If (standalone == true) // - dont stop the RPC server at all. When this cannot talk to the parent, // it will exit the process. // if (standalone == false) // - if there is no remote JT, close right away // - if there is a remote JT, close after 1min. if (interTrackerServer != null) { if (!isStandalone) { if (remoteJT == null) { interTrackerServer.stop(); } else { final int timeout = conf.getInt(RPC_SERVER_STOP_TIMEOUT, 0); if (timeout > 0) { LOG.info("Starting async thread to stop RPC server for " + jobId); Thread async = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(timeout); LOG.info("Stopping RPC server for " + jobId); interTrackerServer.stop(); remoteJT.close(); } catch (InterruptedException e) { LOG.warn( "Interrupted during wait before stopping RPC server"); } } }); async.setDaemon(true); async.start(); } } } } synchronized (lockObject) { closed = true; lockObject.notifyAll(); } } } }
public class class_name { public static String getLocalizedMessage(ResourceBundle bundle, String key, Object... args) { String pattern; try { pattern = bundle.getString(key); } catch (MissingResourceException e) { pattern = key; } if (ArrayUtils.isNotEmpty(args)) { return MessageFormat.format(pattern, args); } else { return pattern; } } }
public class class_name { public static String getLocalizedMessage(ResourceBundle bundle, String key, Object... args) { String pattern; try { pattern = bundle.getString(key); // depends on control dependency: [try], data = [none] } catch (MissingResourceException e) { pattern = key; } // depends on control dependency: [catch], data = [none] if (ArrayUtils.isNotEmpty(args)) { return MessageFormat.format(pattern, args); // depends on control dependency: [if], data = [none] } else { return pattern; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void formatDecimal(BigDecimal n, StringBuilder destination, DecimalFormatOptions options) { DigitBuffer dbuf = new DigitBuffer(); DecimalFormatStyle style = options.style(); boolean grouping = orDefault(options.grouping(), false); boolean currency = false; NumberFormatMode formatMode = orDefault(options.formatMode(), NumberFormatMode.DEFAULT); switch (style) { case DECIMAL: { NumberFormatContext ctx = new NumberFormatContext(options, NumberFormatMode.DEFAULT); NumberPattern pattern = select(n, decimalStandard); ctx.set(pattern); BigDecimal q = ctx.adjust(n); DigitBuffer number = new DigitBuffer(); NumberFormattingUtils.format(q, number, params, currency, grouping, ctx.minIntDigits(), pattern.format.primaryGroupingSize(), pattern.format.secondaryGroupingSize()); format(pattern, number, dbuf, null, null); dbuf.appendTo(destination); break; } case LONG: case SHORT: { NumberFormatContext ctx = new NumberFormatContext(options, NumberFormatMode.SIGNIFICANT); int nDigits = integerDigits(n); int nDivisor = getDivisor_DECIMAL_LONG(nDigits); // Q1 is the number divided by the divisor (if any). BigDecimal q1 = n; if (nDivisor > 0) { q1 = n.movePointLeft(nDivisor).stripTrailingZeros(); } int q1Digits = integerDigits(q1); // Select an initial pattern using the OTHER plural category. NumberPattern pattern; if (style == DecimalFormatStyle.LONG) { pattern = select(n, getPattern_DECIMAL_LONG(nDigits, PluralCategory.OTHER)); } else { pattern = select(n, getPattern_DECIMAL_SHORT(nDigits, PluralCategory.OTHER)); } // Q2 is the number adjusted using the pattern and options. ctx.setCompact(pattern, q1Digits, nDivisor); BigDecimal q2 = ctx.adjust(q1); int q2Digits = integerDigits(q2); // Number rounded up, we need to select a new divisor and pattern. if (q2Digits > q1Digits) { // Bump the number of digits by 1 to select the next divisor/pattern. nDigits++; int divisor = getDivisor_DECIMAL_LONG(nDigits); if (style == DecimalFormatStyle.LONG) { pattern = select(n, getPattern_DECIMAL_LONG(nDigits, PluralCategory.OTHER)); } else { pattern = select(n, getPattern_DECIMAL_SHORT(nDigits, PluralCategory.OTHER)); } // If divisor changed, we need to divide and adjust again. // Otherwise we just use Q2 as-is. if (divisor > nDivisor) { q1 = n.movePointLeft(divisor).stripTrailingZeros(); ctx.setCompact(pattern, integerDigits(q1), divisor); q2 = ctx.adjust(q1); } } // Compute the plural category. NumberOperands operands = new NumberOperands(q2.toPlainString()); PluralCategory category = PLURAL_RULES.evalCardinal(bundleId.language(), operands); // Select the final pluralized pattern. if (style == DecimalFormatStyle.LONG) { pattern = select(n, getPattern_DECIMAL_LONG(nDigits, category)); } else { pattern = select(n, getPattern_DECIMAL_SHORT(nDigits, category)); } // Format the number into the buffer. DigitBuffer number = new DigitBuffer(); NumberFormattingUtils.format(q2, number, params, false, grouping, pattern.format.minimumIntegerDigits, decimalStandard[0].format.primaryGroupingSize, decimalStandard[0].format.secondaryGroupingSize); // Format the entire pattern and append to destination. format(pattern, number, dbuf, null, null); dbuf.appendTo(destination); break; } case PERCENT: case PERCENT_SCALED: case PERMILLE: case PERMILLE_SCALED: { // In default modes, scale the number. Otherwise assume it is already scaled // appropriately. if (style == PERCENT || style == PERMILLE) { n = n.movePointRight(style == PERCENT ? 2 : 3); } String symbol = (style == PERCENT) || (style == PERCENT_SCALED) ? params.percent : params.perMille; NumberPattern pattern = select(n, percentStandard); DigitBuffer number = new DigitBuffer(); setup(params, pattern, n, number, options, null, formatMode, grouping, -1, -1, -1); format(pattern, number, dbuf, null, symbol); dbuf.appendTo(destination); break; } } } }
public class class_name { public void formatDecimal(BigDecimal n, StringBuilder destination, DecimalFormatOptions options) { DigitBuffer dbuf = new DigitBuffer(); DecimalFormatStyle style = options.style(); boolean grouping = orDefault(options.grouping(), false); boolean currency = false; NumberFormatMode formatMode = orDefault(options.formatMode(), NumberFormatMode.DEFAULT); switch (style) { case DECIMAL: { NumberFormatContext ctx = new NumberFormatContext(options, NumberFormatMode.DEFAULT); NumberPattern pattern = select(n, decimalStandard); ctx.set(pattern); BigDecimal q = ctx.adjust(n); DigitBuffer number = new DigitBuffer(); NumberFormattingUtils.format(q, number, params, currency, grouping, ctx.minIntDigits(), pattern.format.primaryGroupingSize(), pattern.format.secondaryGroupingSize()); format(pattern, number, dbuf, null, null); dbuf.appendTo(destination); break; } case LONG: case SHORT: { NumberFormatContext ctx = new NumberFormatContext(options, NumberFormatMode.SIGNIFICANT); int nDigits = integerDigits(n); int nDivisor = getDivisor_DECIMAL_LONG(nDigits); // Q1 is the number divided by the divisor (if any). BigDecimal q1 = n; if (nDivisor > 0) { q1 = n.movePointLeft(nDivisor).stripTrailingZeros(); // depends on control dependency: [if], data = [(nDivisor] } int q1Digits = integerDigits(q1); // Select an initial pattern using the OTHER plural category. NumberPattern pattern; if (style == DecimalFormatStyle.LONG) { pattern = select(n, getPattern_DECIMAL_LONG(nDigits, PluralCategory.OTHER)); // depends on control dependency: [if], data = [none] } else { pattern = select(n, getPattern_DECIMAL_SHORT(nDigits, PluralCategory.OTHER)); // depends on control dependency: [if], data = [none] } // Q2 is the number adjusted using the pattern and options. ctx.setCompact(pattern, q1Digits, nDivisor); BigDecimal q2 = ctx.adjust(q1); int q2Digits = integerDigits(q2); // Number rounded up, we need to select a new divisor and pattern. if (q2Digits > q1Digits) { // Bump the number of digits by 1 to select the next divisor/pattern. nDigits++; // depends on control dependency: [if], data = [none] int divisor = getDivisor_DECIMAL_LONG(nDigits); if (style == DecimalFormatStyle.LONG) { pattern = select(n, getPattern_DECIMAL_LONG(nDigits, PluralCategory.OTHER)); // depends on control dependency: [if], data = [none] } else { pattern = select(n, getPattern_DECIMAL_SHORT(nDigits, PluralCategory.OTHER)); // depends on control dependency: [if], data = [none] } // If divisor changed, we need to divide and adjust again. // Otherwise we just use Q2 as-is. if (divisor > nDivisor) { q1 = n.movePointLeft(divisor).stripTrailingZeros(); // depends on control dependency: [if], data = [(divisor] ctx.setCompact(pattern, integerDigits(q1), divisor); // depends on control dependency: [if], data = [none] q2 = ctx.adjust(q1); // depends on control dependency: [if], data = [none] } } // Compute the plural category. NumberOperands operands = new NumberOperands(q2.toPlainString()); PluralCategory category = PLURAL_RULES.evalCardinal(bundleId.language(), operands); // Select the final pluralized pattern. if (style == DecimalFormatStyle.LONG) { pattern = select(n, getPattern_DECIMAL_LONG(nDigits, category)); // depends on control dependency: [if], data = [none] } else { pattern = select(n, getPattern_DECIMAL_SHORT(nDigits, category)); // depends on control dependency: [if], data = [none] } // Format the number into the buffer. DigitBuffer number = new DigitBuffer(); NumberFormattingUtils.format(q2, number, params, false, grouping, pattern.format.minimumIntegerDigits, decimalStandard[0].format.primaryGroupingSize, decimalStandard[0].format.secondaryGroupingSize); // Format the entire pattern and append to destination. format(pattern, number, dbuf, null, null); dbuf.appendTo(destination); break; } case PERCENT: case PERCENT_SCALED: case PERMILLE: case PERMILLE_SCALED: { // In default modes, scale the number. Otherwise assume it is already scaled // appropriately. if (style == PERCENT || style == PERMILLE) { n = n.movePointRight(style == PERCENT ? 2 : 3); // depends on control dependency: [if], data = [(style] } String symbol = (style == PERCENT) || (style == PERCENT_SCALED) ? params.percent : params.perMille; NumberPattern pattern = select(n, percentStandard); DigitBuffer number = new DigitBuffer(); setup(params, pattern, n, number, options, null, formatMode, grouping, -1, -1, -1); format(pattern, number, dbuf, null, symbol); dbuf.appendTo(destination); break; } } } }
public class class_name { public static String instructionListToString(InstructionList il, ConstantPoolGen pool) { StringBuilder out = new StringBuilder(); for (Iterator<InstructionHandle> i = il.iterator(); i.hasNext(); ) { InstructionHandle handle = i.next(); out.append(handle.getInstruction().toString(pool.getConstantPool()) + "\n"); } return out.toString(); } }
public class class_name { public static String instructionListToString(InstructionList il, ConstantPoolGen pool) { StringBuilder out = new StringBuilder(); for (Iterator<InstructionHandle> i = il.iterator(); i.hasNext(); ) { InstructionHandle handle = i.next(); out.append(handle.getInstruction().toString(pool.getConstantPool()) + "\n"); // depends on control dependency: [for], data = [none] } return out.toString(); } }
public class class_name { public Integer getInt(String name) { Object o = get(name); if (o instanceof Number) { return ((Number)o).intValue(); } if (o != null) { try { String string = o.toString(); if (string != null) { return Integer.parseInt(string); } } catch (NumberFormatException e) {} } return null; } }
public class class_name { public Integer getInt(String name) { Object o = get(name); if (o instanceof Number) { return ((Number)o).intValue(); // depends on control dependency: [if], data = [none] } if (o != null) { try { String string = o.toString(); if (string != null) { return Integer.parseInt(string); // depends on control dependency: [if], data = [(string] } } catch (NumberFormatException e) {} // depends on control dependency: [catch], data = [none] } return null; } }
public class class_name { public static void closeContext(Context ctx) { if (ctx instanceof DirContextAdapter) { return; } try { if (ctx != null) { ctx.close(); } } catch (NamingException e) { logger.error("Failed to close context.", e); } } }
public class class_name { public static void closeContext(Context ctx) { if (ctx instanceof DirContextAdapter) { return; // depends on control dependency: [if], data = [none] } try { if (ctx != null) { ctx.close(); // depends on control dependency: [if], data = [none] } } catch (NamingException e) { logger.error("Failed to close context.", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @SuppressWarnings("unchecked") public OGraphEdge link(final OGraphVertex iTargetVertex, final String iClassName) { if (iTargetVertex == null) throw new IllegalArgumentException("Missed the target vertex"); // CREATE THE EDGE BETWEEN ME AND THE TARGET final OGraphEdge edge = new OGraphEdge(database, iClassName, this, iTargetVertex); getOutEdges().add(edge); Set<ODocument> recordEdges = ((Set<ODocument>) document.field(OGraphDatabase.VERTEX_FIELD_OUT)); if (recordEdges == null) { recordEdges = new HashSet<ODocument>(); document.field(OGraphDatabase.VERTEX_FIELD_OUT, recordEdges); } recordEdges.add(edge.getDocument()); document.setDirty(); // INSERT INTO THE INGOING EDGES OF TARGET iTargetVertex.getInEdges().add(edge); recordEdges = ((Set<ODocument>) iTargetVertex.getDocument().field(OGraphDatabase.VERTEX_FIELD_IN)); if (recordEdges == null) { recordEdges = new HashSet<ODocument>(); iTargetVertex.getDocument().field(OGraphDatabase.VERTEX_FIELD_IN, recordEdges); } recordEdges.add(edge.getDocument()); iTargetVertex.getDocument().setDirty(); return edge; } }
public class class_name { @SuppressWarnings("unchecked") public OGraphEdge link(final OGraphVertex iTargetVertex, final String iClassName) { if (iTargetVertex == null) throw new IllegalArgumentException("Missed the target vertex"); // CREATE THE EDGE BETWEEN ME AND THE TARGET final OGraphEdge edge = new OGraphEdge(database, iClassName, this, iTargetVertex); getOutEdges().add(edge); Set<ODocument> recordEdges = ((Set<ODocument>) document.field(OGraphDatabase.VERTEX_FIELD_OUT)); if (recordEdges == null) { recordEdges = new HashSet<ODocument>(); // depends on control dependency: [if], data = [none] document.field(OGraphDatabase.VERTEX_FIELD_OUT, recordEdges); // depends on control dependency: [if], data = [none] } recordEdges.add(edge.getDocument()); document.setDirty(); // INSERT INTO THE INGOING EDGES OF TARGET iTargetVertex.getInEdges().add(edge); recordEdges = ((Set<ODocument>) iTargetVertex.getDocument().field(OGraphDatabase.VERTEX_FIELD_IN)); if (recordEdges == null) { recordEdges = new HashSet<ODocument>(); // depends on control dependency: [if], data = [none] iTargetVertex.getDocument().field(OGraphDatabase.VERTEX_FIELD_IN, recordEdges); // depends on control dependency: [if], data = [none] } recordEdges.add(edge.getDocument()); iTargetVertex.getDocument().setDirty(); return edge; } }
public class class_name { @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static void restartActivity(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { activity.recreate(); } else { Intent intent = activity.getIntent(); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); activity.finish(); activity.overridePendingTransition(0, 0); activity.startActivity(intent); activity.overridePendingTransition(0, 0); } } }
public class class_name { @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static void restartActivity(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { activity.recreate(); // depends on control dependency: [if], data = [none] } else { Intent intent = activity.getIntent(); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); // depends on control dependency: [if], data = [none] activity.finish(); // depends on control dependency: [if], data = [none] activity.overridePendingTransition(0, 0); // depends on control dependency: [if], data = [none] activity.startActivity(intent); // depends on control dependency: [if], data = [none] activity.overridePendingTransition(0, 0); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String getCellFontStyle(final Workbook wb, final Cell poiCell) { CellStyle cellStyle = poiCell.getCellStyle(); StringBuilder webStyle = new StringBuilder(); if (cellStyle != null) { short fontIdx = cellStyle.getFontIndex(); Font font = wb.getFontAt(fontIdx); if (font.getItalic()) { webStyle.append("font-style: italic;"); } if (font.getBold()) { webStyle.append("font-weight: bold;"); } webStyle.append( "font-size: " + font.getFontHeightInPoints() + "pt;"); String decoration = getCellFontDecoration(font); if (decoration.length() > 0) { webStyle.append("text-decoration:" + decoration + ";"); } webStyle.append(getCellFontColor(font)); } return webStyle.toString(); } }
public class class_name { public static String getCellFontStyle(final Workbook wb, final Cell poiCell) { CellStyle cellStyle = poiCell.getCellStyle(); StringBuilder webStyle = new StringBuilder(); if (cellStyle != null) { short fontIdx = cellStyle.getFontIndex(); Font font = wb.getFontAt(fontIdx); if (font.getItalic()) { webStyle.append("font-style: italic;"); // depends on control dependency: [if], data = [none] } if (font.getBold()) { webStyle.append("font-weight: bold;"); // depends on control dependency: [if], data = [none] } webStyle.append( "font-size: " + font.getFontHeightInPoints() + "pt;"); // depends on control dependency: [if], data = [none] String decoration = getCellFontDecoration(font); if (decoration.length() > 0) { webStyle.append("text-decoration:" + decoration + ";"); // depends on control dependency: [if], data = [none] } webStyle.append(getCellFontColor(font)); // depends on control dependency: [if], data = [none] } return webStyle.toString(); } }
public class class_name { @Override public EClass getIfcPropertySet() { if (ifcPropertySetEClass == null) { ifcPropertySetEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(473); } return ifcPropertySetEClass; } }
public class class_name { @Override public EClass getIfcPropertySet() { if (ifcPropertySetEClass == null) { ifcPropertySetEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(473); // depends on control dependency: [if], data = [none] } return ifcPropertySetEClass; } }
public class class_name { public int onePhaseCommitRemoteTransaction(GlobalTransaction gtx, List<WriteCommand> modifications) { RpcManager rpcManager = cache.getRpcManager(); CommandsFactory factory = cache.getComponentRegistry().getCommandsFactory(); try { //only pessimistic tx are committed in 1PC and it doesn't use versions. PrepareCommand command = factory.buildPrepareCommand(gtx, modifications, true); CompletionStage<Void> cs = rpcManager.invokeCommandOnAll(command, validOnly(), rpcManager.getSyncRpcOptions()); factory.initializeReplicableCommand(command, false); command.invokeAsync().join(); cs.toCompletableFuture().join(); forgetTransaction(gtx, rpcManager, factory); return loggingCompleted(true) == Status.OK ? XAResource.XA_OK : XAException.XAER_RMERR; } catch (Throwable throwable) { //transaction should commit but we still can have exceptions (timeouts or similar) return XAException.XAER_RMERR; } } }
public class class_name { public int onePhaseCommitRemoteTransaction(GlobalTransaction gtx, List<WriteCommand> modifications) { RpcManager rpcManager = cache.getRpcManager(); CommandsFactory factory = cache.getComponentRegistry().getCommandsFactory(); try { //only pessimistic tx are committed in 1PC and it doesn't use versions. PrepareCommand command = factory.buildPrepareCommand(gtx, modifications, true); CompletionStage<Void> cs = rpcManager.invokeCommandOnAll(command, validOnly(), rpcManager.getSyncRpcOptions()); factory.initializeReplicableCommand(command, false); // depends on control dependency: [try], data = [none] command.invokeAsync().join(); // depends on control dependency: [try], data = [none] cs.toCompletableFuture().join(); // depends on control dependency: [try], data = [none] forgetTransaction(gtx, rpcManager, factory); // depends on control dependency: [try], data = [none] return loggingCompleted(true) == Status.OK ? XAResource.XA_OK : XAException.XAER_RMERR; // depends on control dependency: [try], data = [none] } catch (Throwable throwable) { //transaction should commit but we still can have exceptions (timeouts or similar) return XAException.XAER_RMERR; } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public boolean clientSelectByExampleWithoutBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { // 方法生成 selectOneByExample Method selectOneMethod = JavaElementGeneratorTools.generateMethod( METHOD_SELECT_ONE_BY_EXAMPLE, JavaVisibility.DEFAULT, JavaElementGeneratorTools.getModelTypeWithoutBLOBs(introspectedTable), new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example") ); commentGenerator.addGeneralMethodComment(selectOneMethod, introspectedTable); // hook if (PluginTools.getHook(ISelectOneByExamplePluginHook.class).clientSelectOneByExampleWithoutBLOBsMethodGenerated(selectOneMethod, interfaze, introspectedTable)) { // interface 增加方法 FormatTools.addMethodWithBestPosition(interfaze, selectOneMethod); logger.debug("itfsw(查询单条数据插件):" + interfaze.getType().getShortName() + "增加selectOneByExample方法。"); } return super.clientSelectByExampleWithoutBLOBsMethodGenerated(selectOneMethod, interfaze, introspectedTable); } }
public class class_name { @Override public boolean clientSelectByExampleWithoutBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { // 方法生成 selectOneByExample Method selectOneMethod = JavaElementGeneratorTools.generateMethod( METHOD_SELECT_ONE_BY_EXAMPLE, JavaVisibility.DEFAULT, JavaElementGeneratorTools.getModelTypeWithoutBLOBs(introspectedTable), new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example") ); commentGenerator.addGeneralMethodComment(selectOneMethod, introspectedTable); // hook if (PluginTools.getHook(ISelectOneByExamplePluginHook.class).clientSelectOneByExampleWithoutBLOBsMethodGenerated(selectOneMethod, interfaze, introspectedTable)) { // interface 增加方法 FormatTools.addMethodWithBestPosition(interfaze, selectOneMethod); // depends on control dependency: [if], data = [none] logger.debug("itfsw(查询单条数据插件):" + interfaze.getType().getShortName() + "增加selectOneByExample方法。"); // depends on control dependency: [if], data = [none] } return super.clientSelectByExampleWithoutBLOBsMethodGenerated(selectOneMethod, interfaze, introspectedTable); } }
public class class_name { protected void deliverSpeak (ChatChannel channel, UserMessage message, int[] bodyIds) { channel = intern(channel); for (int bodyId : bodyIds) { BodyObject bobj = getBodyObject(bodyId); if (bobj != null && shouldDeliverSpeak(channel, message, bobj)) { _chatHistory.record(channel, bobj.getChatIdentifier(message), message, bobj.getVisibleName()); bobj.postMessage(ChatCodes.CHAT_CHANNEL_NOTIFICATION, channel, message); } } } }
public class class_name { protected void deliverSpeak (ChatChannel channel, UserMessage message, int[] bodyIds) { channel = intern(channel); for (int bodyId : bodyIds) { BodyObject bobj = getBodyObject(bodyId); if (bobj != null && shouldDeliverSpeak(channel, message, bobj)) { _chatHistory.record(channel, bobj.getChatIdentifier(message), message, bobj.getVisibleName()); // depends on control dependency: [if], data = [none] bobj.postMessage(ChatCodes.CHAT_CHANNEL_NOTIFICATION, channel, message); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public void clearPages(ClassLoader cl) { Iterator<PageSource> it = this.pageSources.values().iterator(); PageSourceImpl entry; while (it.hasNext()) { entry = (PageSourceImpl) it.next(); if (cl != null) entry.clear(cl); else entry.clear(); } } }
public class class_name { public void clearPages(ClassLoader cl) { Iterator<PageSource> it = this.pageSources.values().iterator(); PageSourceImpl entry; while (it.hasNext()) { entry = (PageSourceImpl) it.next(); // depends on control dependency: [while], data = [none] if (cl != null) entry.clear(cl); else entry.clear(); } } }
public class class_name { protected FluentModelTImpl prepareForFutureCommitOrPostRun(FluentModelTImpl childResource) { if (this.isPostRunMode) { if (!childResource.taskGroup().dependsOn(this.parentTaskGroup)) { this.parentTaskGroup.addPostRunDependentTaskGroup(childResource.taskGroup()); } return childResource; } else { return childResource; } } }
public class class_name { protected FluentModelTImpl prepareForFutureCommitOrPostRun(FluentModelTImpl childResource) { if (this.isPostRunMode) { if (!childResource.taskGroup().dependsOn(this.parentTaskGroup)) { this.parentTaskGroup.addPostRunDependentTaskGroup(childResource.taskGroup()); // depends on control dependency: [if], data = [none] } return childResource; // depends on control dependency: [if], data = [none] } else { return childResource; // depends on control dependency: [if], data = [none] } } }
public class class_name { public ObjectName build() { final String name = nameStrBuilder.substring(0, nameStrBuilder.length() - 1); try { return new ObjectName(name); } catch (MalformedObjectNameException e) { LOG.warn("Invalid ObjectName provided: " + name); throw Throwables.propagate(e); } } }
public class class_name { public ObjectName build() { final String name = nameStrBuilder.substring(0, nameStrBuilder.length() - 1); try { return new ObjectName(name); // depends on control dependency: [try], data = [none] } catch (MalformedObjectNameException e) { LOG.warn("Invalid ObjectName provided: " + name); throw Throwables.propagate(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static void setOutputForms( ActionMapping mapping, ActionForm[] outputForms, HttpServletRequest request, boolean overwrite ) { try { // // Now set any output forms in the request or session, as appropriate. // assert mapping.getScope() == null || mapping.getScope().equals( "request" ) || mapping.getScope().equals( "session" ) : mapping.getScope(); for ( int i = 0; i < outputForms.length; ++i ) { setOutputForm( mapping, outputForms[i], request, overwrite ); } } catch ( Exception e ) { _log.error( "Error while setting Struts form-beans", e ); } } }
public class class_name { public static void setOutputForms( ActionMapping mapping, ActionForm[] outputForms, HttpServletRequest request, boolean overwrite ) { try { // // Now set any output forms in the request or session, as appropriate. // assert mapping.getScope() == null || mapping.getScope().equals( "request" ) || mapping.getScope().equals( "session" ) : mapping.getScope(); // depends on control dependency: [try], data = [none] for ( int i = 0; i < outputForms.length; ++i ) { setOutputForm( mapping, outputForms[i], request, overwrite ); // depends on control dependency: [for], data = [i] } } catch ( Exception e ) { _log.error( "Error while setting Struts form-beans", e ); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private void copyToOffset(int offset) { final int minCapacity = 2 * (offset + nbrruns); if (valueslength.capacity() < minCapacity) { // expensive case where we need to reallocate int newCapacity = valueslength.capacity(); while (newCapacity < minCapacity) { newCapacity = (newCapacity == 0) ? DEFAULT_INIT_SIZE : newCapacity < 64 ? newCapacity * 2 : newCapacity < 1024 ? newCapacity * 3 / 2 : newCapacity * 5 / 4; } ShortBuffer newvalueslength = ShortBuffer.allocate(newCapacity); copyValuesLength(this.valueslength, 0, newvalueslength, offset, nbrruns); this.valueslength = newvalueslength; } else { // efficient case where we just copy copyValuesLength(this.valueslength, 0, this.valueslength, offset, nbrruns); } } }
public class class_name { private void copyToOffset(int offset) { final int minCapacity = 2 * (offset + nbrruns); if (valueslength.capacity() < minCapacity) { // expensive case where we need to reallocate int newCapacity = valueslength.capacity(); while (newCapacity < minCapacity) { newCapacity = (newCapacity == 0) ? DEFAULT_INIT_SIZE : newCapacity < 64 ? newCapacity * 2 : newCapacity < 1024 ? newCapacity * 3 / 2 : newCapacity * 5 / 4; // depends on control dependency: [while], data = [(newCapacity] } ShortBuffer newvalueslength = ShortBuffer.allocate(newCapacity); copyValuesLength(this.valueslength, 0, newvalueslength, offset, nbrruns); // depends on control dependency: [if], data = [none] this.valueslength = newvalueslength; // depends on control dependency: [if], data = [none] } else { // efficient case where we just copy copyValuesLength(this.valueslength, 0, this.valueslength, offset, nbrruns); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String trimString(String string, int maxMessageLength) { if (string == null) { return null; } else if (string.length() > maxMessageLength) { // CHECKSTYLE.OFF: MagicNumber return string.substring(0, maxMessageLength - 3) + "..."; // CHECKSTYLE.ON: MagicNumber } else { return string; } } }
public class class_name { public static String trimString(String string, int maxMessageLength) { if (string == null) { return null; // depends on control dependency: [if], data = [none] } else if (string.length() > maxMessageLength) { // CHECKSTYLE.OFF: MagicNumber return string.substring(0, maxMessageLength - 3) + "..."; // depends on control dependency: [if], data = [none] // CHECKSTYLE.ON: MagicNumber } else { return string; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static ISREInstall getDefaultSREInstall() { final ISREInstall install = getSREFromId(getDefaultSREId()); if (install != null && install.getValidity().isOK()) { return install; } // if the default SRE goes missing, re-detect LOCK.lock(); try { //defaultSREId = null; initializeSREs(); } finally { LOCK.unlock(); } return getSREFromId(getDefaultSREId()); } }
public class class_name { public static ISREInstall getDefaultSREInstall() { final ISREInstall install = getSREFromId(getDefaultSREId()); if (install != null && install.getValidity().isOK()) { return install; // depends on control dependency: [if], data = [none] } // if the default SRE goes missing, re-detect LOCK.lock(); try { //defaultSREId = null; initializeSREs(); // depends on control dependency: [try], data = [none] } finally { LOCK.unlock(); } return getSREFromId(getDefaultSREId()); } }
public class class_name { public static By getLocator(String applicationKey, String code, Object... args) { By locator = null; logger.debug("getLocator with this application key : {}", applicationKey); logger.debug("getLocator with this locator file : {}", Context.iniFiles.get(applicationKey)); final Ini ini = Context.iniFiles.get(applicationKey); final Map<String, String> section = ini.get(code); if (section != null) { final Entry<String, String> entry = section.entrySet().iterator().next(); final String selector = String.format(entry.getValue(), args); if ("css".equals(entry.getKey())) { locator = By.cssSelector(selector); } else if ("link".equals(entry.getKey())) { locator = By.linkText(selector); } else if ("id".equals(entry.getKey())) { locator = By.id(selector); } else if ("name".equals(entry.getKey())) { locator = By.name(selector); } else if ("xpath".equals(entry.getKey())) { locator = By.xpath(selector); } else if ("class".equals(entry.getKey())) { locator = By.className(selector); } else { Assert.fail(entry.getKey() + " NOT implemented!"); } } else { Assert.fail(code + " NOT implemented in ini file " + Context.iniFiles.get(applicationKey) + "!"); } return locator; } }
public class class_name { public static By getLocator(String applicationKey, String code, Object... args) { By locator = null; logger.debug("getLocator with this application key : {}", applicationKey); logger.debug("getLocator with this locator file : {}", Context.iniFiles.get(applicationKey)); final Ini ini = Context.iniFiles.get(applicationKey); final Map<String, String> section = ini.get(code); if (section != null) { final Entry<String, String> entry = section.entrySet().iterator().next(); final String selector = String.format(entry.getValue(), args); if ("css".equals(entry.getKey())) { locator = By.cssSelector(selector); // depends on control dependency: [if], data = [none] } else if ("link".equals(entry.getKey())) { locator = By.linkText(selector); // depends on control dependency: [if], data = [none] } else if ("id".equals(entry.getKey())) { locator = By.id(selector); // depends on control dependency: [if], data = [none] } else if ("name".equals(entry.getKey())) { locator = By.name(selector); // depends on control dependency: [if], data = [none] } else if ("xpath".equals(entry.getKey())) { locator = By.xpath(selector); // depends on control dependency: [if], data = [none] } else if ("class".equals(entry.getKey())) { locator = By.className(selector); // depends on control dependency: [if], data = [none] } else { Assert.fail(entry.getKey() + " NOT implemented!"); // depends on control dependency: [if], data = [none] } } else { Assert.fail(code + " NOT implemented in ini file " + Context.iniFiles.get(applicationKey) + "!"); // depends on control dependency: [if], data = [none] } return locator; } }
public class class_name { protected boolean validateRuntimeManage( SchedulerStateManagerAdaptor adaptor, String topologyName) throws TopologyRuntimeManagementException { // Check whether the topology has already been running Boolean isTopologyRunning = adaptor.isTopologyRunning(topologyName); boolean hasExecutionData = isTopologyRunning != null && isTopologyRunning.equals(Boolean.TRUE); if (!hasExecutionData) { if (command == Command.KILL) { LOG.warning(String.format("Topology '%s' is not found or not running", topologyName)); } else { throw new TopologyRuntimeManagementException( String.format("Topology '%s' does not exist", topologyName)); } } // Check whether cluster/role/environ matched if execution state data is available. ExecutionEnvironment.ExecutionState executionState = adaptor.getExecutionState(topologyName); if (executionState == null) { if (command == Command.KILL) { LOG.warning(String.format("Topology execution state for '%s' is not found", topologyName)); } else { throw new TopologyRuntimeManagementException( String.format("Failed to get execution state for topology %s", topologyName)); } } else { // Execution state is available, validate configurations. validateExecutionState(topologyName, executionState); } return hasExecutionData; } }
public class class_name { protected boolean validateRuntimeManage( SchedulerStateManagerAdaptor adaptor, String topologyName) throws TopologyRuntimeManagementException { // Check whether the topology has already been running Boolean isTopologyRunning = adaptor.isTopologyRunning(topologyName); boolean hasExecutionData = isTopologyRunning != null && isTopologyRunning.equals(Boolean.TRUE); if (!hasExecutionData) { if (command == Command.KILL) { LOG.warning(String.format("Topology '%s' is not found or not running", topologyName)); // depends on control dependency: [if], data = [none] } else { throw new TopologyRuntimeManagementException( String.format("Topology '%s' does not exist", topologyName)); } } // Check whether cluster/role/environ matched if execution state data is available. ExecutionEnvironment.ExecutionState executionState = adaptor.getExecutionState(topologyName); if (executionState == null) { if (command == Command.KILL) { LOG.warning(String.format("Topology execution state for '%s' is not found", topologyName)); } else { throw new TopologyRuntimeManagementException( String.format("Failed to get execution state for topology %s", topologyName)); } } else { // Execution state is available, validate configurations. validateExecutionState(topologyName, executionState); } return hasExecutionData; } }
public class class_name { public static InputStream asBufferedInputStream(InputStream is) { if (is instanceof BufferedInputStream || is instanceof ByteArrayInputStream) { return is; } return new BufferedInputStream(is); } }
public class class_name { public static InputStream asBufferedInputStream(InputStream is) { if (is instanceof BufferedInputStream || is instanceof ByteArrayInputStream) { return is; // depends on control dependency: [if], data = [none] } return new BufferedInputStream(is); } }
public class class_name { Object asJSON() { final List<Object> json = new ArrayList<>(); json.add(limit.asJSON()); if (offset != null) { json.add(offset.asJSON()); } return json; } }
public class class_name { Object asJSON() { final List<Object> json = new ArrayList<>(); json.add(limit.asJSON()); if (offset != null) { json.add(offset.asJSON()); } // depends on control dependency: [if], data = [(offset] return json; } }
public class class_name { public void enableUniformSize(final boolean enable) { if (mUniformSize != enable) { mUniformSize = enable; if (mContainer != null) { mContainer.onLayoutChanged(this); } } } }
public class class_name { public void enableUniformSize(final boolean enable) { if (mUniformSize != enable) { mUniformSize = enable; // depends on control dependency: [if], data = [none] if (mContainer != null) { mContainer.onLayoutChanged(this); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static String removeLeadingZeros(final String str) { String result = str; if (str != null && str.length() != 0) { int startIndex = 0; while (startIndex < str.length() - 1) { final char ch = str.charAt(startIndex); if (ch != '0') { break; } startIndex++; } if (startIndex > 0) { result = str.substring(startIndex); } } return result; } }
public class class_name { public static String removeLeadingZeros(final String str) { String result = str; if (str != null && str.length() != 0) { int startIndex = 0; while (startIndex < str.length() - 1) { final char ch = str.charAt(startIndex); if (ch != '0') { break; } startIndex++; // depends on control dependency: [while], data = [none] } if (startIndex > 0) { result = str.substring(startIndex); // depends on control dependency: [if], data = [(startIndex] } } return result; } }
public class class_name { protected List<User> executePaginatedQuery(UserQuery query, Integer firstResult, Integer maxResults) { if (firstResult == null) { firstResult = 0; } if (maxResults == null) { maxResults = Integer.MAX_VALUE; } return query.listPage(firstResult, maxResults); } }
public class class_name { protected List<User> executePaginatedQuery(UserQuery query, Integer firstResult, Integer maxResults) { if (firstResult == null) { firstResult = 0; // depends on control dependency: [if], data = [none] } if (maxResults == null) { maxResults = Integer.MAX_VALUE; // depends on control dependency: [if], data = [none] } return query.listPage(firstResult, maxResults); } }
public class class_name { public static void splitBySize(final File file, final long sizeOfPart, final File destDir) throws UncheckedIOException { final int numOfParts = (int) ((file.length() % sizeOfPart) == 0 ? (file.length() / sizeOfPart) : (file.length() / sizeOfPart) + 1); final String fileName = file.getName(); final long fileLength = file.length(); int fileSerNum = 1; final byte[] buf = Objectory.createByteArrayBuffer(); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(file); for (int i = 0; i < numOfParts; i++) { String subFileNmae = destDir.getAbsolutePath() + IOUtil.FILE_SEPARATOR + fileName + "_" + StringUtil.padStart(N.stringOf(fileSerNum++), 4, '0'); output = new FileOutputStream(new File(subFileNmae)); long partLength = sizeOfPart; if (i == numOfParts - 1) { partLength += fileLength % numOfParts; } int count = 0; try { while (partLength > 0 && EOF != (count = read(input, buf, 0, (int) Math.min(buf.length, partLength)))) { output.write(buf, 0, count); partLength = partLength - count; } output.flush(); } finally { close(output); } } } catch (IOException e) { throw new UncheckedIOException(e); } finally { Objectory.recycle(buf); closeQuietly(input); } } }
public class class_name { public static void splitBySize(final File file, final long sizeOfPart, final File destDir) throws UncheckedIOException { final int numOfParts = (int) ((file.length() % sizeOfPart) == 0 ? (file.length() / sizeOfPart) : (file.length() / sizeOfPart) + 1); final String fileName = file.getName(); final long fileLength = file.length(); int fileSerNum = 1; final byte[] buf = Objectory.createByteArrayBuffer(); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(file); for (int i = 0; i < numOfParts; i++) { String subFileNmae = destDir.getAbsolutePath() + IOUtil.FILE_SEPARATOR + fileName + "_" + StringUtil.padStart(N.stringOf(fileSerNum++), 4, '0'); output = new FileOutputStream(new File(subFileNmae)); // depends on control dependency: [for], data = [none] long partLength = sizeOfPart; if (i == numOfParts - 1) { partLength += fileLength % numOfParts; // depends on control dependency: [if], data = [none] } int count = 0; try { while (partLength > 0 && EOF != (count = read(input, buf, 0, (int) Math.min(buf.length, partLength)))) { output.write(buf, 0, count); // depends on control dependency: [while], data = [none] partLength = partLength - count; // depends on control dependency: [while], data = [none] } output.flush(); // depends on control dependency: [try], data = [none] } finally { close(output); } } } catch (IOException e) { throw new UncheckedIOException(e); } finally { Objectory.recycle(buf); closeQuietly(input); } } }
public class class_name { protected U convertAttributesToProfile(final List<Map<String, Object>> listStorageAttributes, final String username) { if (listStorageAttributes == null || listStorageAttributes.size() == 0) { return null; } final Map<String, Object> storageAttributes = listStorageAttributes.get(0); final String linkedId = (String) storageAttributes.get(LINKEDID); // legacy mode: only read the defined attributes if (isLegacyMode()) { final U profile = getProfileDefinition().newProfile(); for (final String attributeName : attributeNames) { getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, attributeName, storageAttributes.get(attributeName)); } final Object retrievedUsername = storageAttributes.get(getUsernameAttribute()); if (retrievedUsername != null) { profile.setId(ProfileHelper.sanitizeIdentifier(profile, retrievedUsername)); } else { profile.setId(username); } if (isNotBlank(linkedId)) { profile.setLinkedId(linkedId); } return profile; } else { // new behaviour (>= v2.0): read the serialized profile final String serializedProfile = (String) storageAttributes.get(SERIALIZED_PROFILE); if (serializedProfile == null) { throw new TechnicalException("No serialized profile found. You should certainly define the explicit attribute names you " + "want to retrieve"); } final U profile = (U) javaSerializationHelper.deserializeFromBase64(serializedProfile); if (profile == null) { throw new TechnicalException("No deserialized profile available. You should certainly define the explicit attribute " + "names you want to retrieve"); } final Object id = storageAttributes.get(getIdAttribute()); if (isBlank(profile.getId()) && id != null) { profile.setId(ProfileHelper.sanitizeIdentifier(profile, id)); } if (isBlank(profile.getLinkedId()) && isNotBlank(linkedId)) { profile.setLinkedId(linkedId); } return profile; } } }
public class class_name { protected U convertAttributesToProfile(final List<Map<String, Object>> listStorageAttributes, final String username) { if (listStorageAttributes == null || listStorageAttributes.size() == 0) { return null; // depends on control dependency: [if], data = [none] } final Map<String, Object> storageAttributes = listStorageAttributes.get(0); final String linkedId = (String) storageAttributes.get(LINKEDID); // legacy mode: only read the defined attributes if (isLegacyMode()) { final U profile = getProfileDefinition().newProfile(); for (final String attributeName : attributeNames) { getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, attributeName, storageAttributes.get(attributeName)); // depends on control dependency: [for], data = [attributeName] } final Object retrievedUsername = storageAttributes.get(getUsernameAttribute()); if (retrievedUsername != null) { profile.setId(ProfileHelper.sanitizeIdentifier(profile, retrievedUsername)); // depends on control dependency: [if], data = [none] } else { profile.setId(username); // depends on control dependency: [if], data = [none] } if (isNotBlank(linkedId)) { profile.setLinkedId(linkedId); // depends on control dependency: [if], data = [none] } return profile; // depends on control dependency: [if], data = [none] } else { // new behaviour (>= v2.0): read the serialized profile final String serializedProfile = (String) storageAttributes.get(SERIALIZED_PROFILE); if (serializedProfile == null) { throw new TechnicalException("No serialized profile found. You should certainly define the explicit attribute names you " + "want to retrieve"); } final U profile = (U) javaSerializationHelper.deserializeFromBase64(serializedProfile); if (profile == null) { throw new TechnicalException("No deserialized profile available. You should certainly define the explicit attribute " + "names you want to retrieve"); } final Object id = storageAttributes.get(getIdAttribute()); if (isBlank(profile.getId()) && id != null) { profile.setId(ProfileHelper.sanitizeIdentifier(profile, id)); // depends on control dependency: [if], data = [none] } if (isBlank(profile.getLinkedId()) && isNotBlank(linkedId)) { profile.setLinkedId(linkedId); // depends on control dependency: [if], data = [none] } return profile; // depends on control dependency: [if], data = [none] } } }
public class class_name { public String getConfigBrowserBasedAuthentication() { if (m_useBrowserBasedHttpAuthentication) { return Boolean.TRUE.toString(); } else if (m_browserBasedAuthenticationMechanism != null) { return m_browserBasedAuthenticationMechanism; } else { return Boolean.FALSE.toString(); } } }
public class class_name { public String getConfigBrowserBasedAuthentication() { if (m_useBrowserBasedHttpAuthentication) { return Boolean.TRUE.toString(); // depends on control dependency: [if], data = [none] } else if (m_browserBasedAuthenticationMechanism != null) { return m_browserBasedAuthenticationMechanism; // depends on control dependency: [if], data = [none] } else { return Boolean.FALSE.toString(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void initRemoteStub(ObjectOutputStream daOut) { try { daOut.writeUTF(startFieldName != null ? startFieldName : ProxyConstants.NULL); daOut.writeUTF(endFieldName != null ? endFieldName : ProxyConstants.NULL); this.writeField(daOut, m_fldStart); this.writeField(daOut, m_fldEnd); daOut.writeInt(m_iPadfldEnd); } catch (IOException ex) { ex.printStackTrace(); } } }
public class class_name { public void initRemoteStub(ObjectOutputStream daOut) { try { daOut.writeUTF(startFieldName != null ? startFieldName : ProxyConstants.NULL); // depends on control dependency: [try], data = [none] daOut.writeUTF(endFieldName != null ? endFieldName : ProxyConstants.NULL); // depends on control dependency: [try], data = [none] this.writeField(daOut, m_fldStart); // depends on control dependency: [try], data = [none] this.writeField(daOut, m_fldEnd); // depends on control dependency: [try], data = [none] daOut.writeInt(m_iPadfldEnd); // depends on control dependency: [try], data = [none] } catch (IOException ex) { ex.printStackTrace(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void visitLdcInsn(final Object value) { if (api < Opcodes.ASM5 && (value instanceof Handle || (value instanceof Type && ((Type) value).getSort() == Type.METHOD))) { throw new UnsupportedOperationException(REQUIRES_ASM5); } if (mv != null) { mv.visitLdcInsn(value); } } }
public class class_name { public void visitLdcInsn(final Object value) { if (api < Opcodes.ASM5 && (value instanceof Handle || (value instanceof Type && ((Type) value).getSort() == Type.METHOD))) { throw new UnsupportedOperationException(REQUIRES_ASM5); } if (mv != null) { mv.visitLdcInsn(value); // depends on control dependency: [if], data = [none] } } }
public class class_name { private Object filterValue(Object value) { if (value instanceof Boolean && !((Boolean) value).booleanValue()) { value = null; } if (value instanceof String && ((String) value).isEmpty()) { value = null; } if (value instanceof Double && ((Double) value).doubleValue() == 0.0) { value = null; } if (value instanceof Integer && ((Integer) value).intValue() == 0) { value = null; } if (value instanceof Duration && ((Duration) value).getDuration() == 0.0) { value = null; } return value; } }
public class class_name { private Object filterValue(Object value) { if (value instanceof Boolean && !((Boolean) value).booleanValue()) { value = null; // depends on control dependency: [if], data = [none] } if (value instanceof String && ((String) value).isEmpty()) { value = null; // depends on control dependency: [if], data = [none] } if (value instanceof Double && ((Double) value).doubleValue() == 0.0) { value = null; // depends on control dependency: [if], data = [none] } if (value instanceof Integer && ((Integer) value).intValue() == 0) { value = null; // depends on control dependency: [if], data = [none] } if (value instanceof Duration && ((Duration) value).getDuration() == 0.0) { value = null; // depends on control dependency: [if], data = [none] } return value; } }
public class class_name { public WireFeed build(Reader reader) throws IllegalArgumentException, FeedException { final SAXBuilder saxBuilder = createSAXBuilder(); try { if (xmlHealerOn) { reader = new XmlFixerReader(reader); } final Document document = saxBuilder.build(reader); return this.build(document); } catch (final JDOMParseException ex) { throw new ParsingFeedException("Invalid XML: " + ex.getMessage(), ex); } catch (final IllegalArgumentException ex) { throw ex; } catch (final Exception ex) { throw new ParsingFeedException("Invalid XML", ex); } } }
public class class_name { public WireFeed build(Reader reader) throws IllegalArgumentException, FeedException { final SAXBuilder saxBuilder = createSAXBuilder(); try { if (xmlHealerOn) { reader = new XmlFixerReader(reader); // depends on control dependency: [if], data = [none] } final Document document = saxBuilder.build(reader); return this.build(document); } catch (final JDOMParseException ex) { throw new ParsingFeedException("Invalid XML: " + ex.getMessage(), ex); } catch (final IllegalArgumentException ex) { throw ex; } catch (final Exception ex) { throw new ParsingFeedException("Invalid XML", ex); } } }
public class class_name { private void configureHandlerMappings() { Map<String, HandlerMapping> handlerMappings = this.factory.getBeansOfType(HandlerMapping.class); if (handlerMappings.isEmpty()) { defineBean(BeanNameUrlHandlerMapping.class); defineBean(RequestMappingHandlerMapping.class); } } }
public class class_name { private void configureHandlerMappings() { Map<String, HandlerMapping> handlerMappings = this.factory.getBeansOfType(HandlerMapping.class); if (handlerMappings.isEmpty()) { defineBean(BeanNameUrlHandlerMapping.class); // depends on control dependency: [if], data = [none] defineBean(RequestMappingHandlerMapping.class); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void marshall(CloudWatchLogsConfig cloudWatchLogsConfig, ProtocolMarshaller protocolMarshaller) { if (cloudWatchLogsConfig == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(cloudWatchLogsConfig.getStatus(), STATUS_BINDING); protocolMarshaller.marshall(cloudWatchLogsConfig.getGroupName(), GROUPNAME_BINDING); protocolMarshaller.marshall(cloudWatchLogsConfig.getStreamName(), STREAMNAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(CloudWatchLogsConfig cloudWatchLogsConfig, ProtocolMarshaller protocolMarshaller) { if (cloudWatchLogsConfig == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(cloudWatchLogsConfig.getStatus(), STATUS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(cloudWatchLogsConfig.getGroupName(), GROUPNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(cloudWatchLogsConfig.getStreamName(), STREAMNAME_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public int[] mergeAllChunks() { int[] merged = new int[chunkSize*numChunks]; int filledChunks = Math.min(numChunks,getFilledChunks()+1); for (int i = 0; i < filledChunks ; i++) { if (chunks[i]!=null) { System.arraycopy(chunks[i],0,merged,i*chunkSize,chunkSize); } } if (defaultValue!=0) Arrays.fill(merged, size(),merged.length,defaultValue); return merged; } }
public class class_name { public int[] mergeAllChunks() { int[] merged = new int[chunkSize*numChunks]; int filledChunks = Math.min(numChunks,getFilledChunks()+1); for (int i = 0; i < filledChunks ; i++) { if (chunks[i]!=null) { System.arraycopy(chunks[i],0,merged,i*chunkSize,chunkSize); // depends on control dependency: [if], data = [(chunks[i]] } } if (defaultValue!=0) Arrays.fill(merged, size(),merged.length,defaultValue); return merged; } }
public class class_name { public String stem(String word) { String ret = null; try { ret = getActualStemmer().getWordStem(word); } catch (PTStemmerException e) { e.printStackTrace(); } return ret; } }
public class class_name { public String stem(String word) { String ret = null; try { ret = getActualStemmer().getWordStem(word); // depends on control dependency: [try], data = [none] } catch (PTStemmerException e) { e.printStackTrace(); } // depends on control dependency: [catch], data = [none] return ret; } }
public class class_name { public TerminalSize withColumns(int columns) { if(this.columns == columns) { return this; } if(columns == 0 && this.rows == 0) { return ZERO; } return new TerminalSize(columns, this.rows); } }
public class class_name { public TerminalSize withColumns(int columns) { if(this.columns == columns) { return this; // depends on control dependency: [if], data = [none] } if(columns == 0 && this.rows == 0) { return ZERO; // depends on control dependency: [if], data = [none] } return new TerminalSize(columns, this.rows); } }
public class class_name { public static void setMultiSelectEditorValue( CmsObject cms, Map<String, String[]> formParameters, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) { String[] values = formParameters.get(param.getId()); if ((values != null) && (values.length > 0)) { StringBuffer value = new StringBuffer(128); for (int i = 0; i < values.length; i++) { if (i > 0) { value.append(','); } value.append(values[i]); } // set the value param.setStringValue(cms, value.toString()); } else { // erase: param.setStringValue(cms, ""); } } }
public class class_name { public static void setMultiSelectEditorValue( CmsObject cms, Map<String, String[]> formParameters, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) { String[] values = formParameters.get(param.getId()); if ((values != null) && (values.length > 0)) { StringBuffer value = new StringBuffer(128); for (int i = 0; i < values.length; i++) { if (i > 0) { value.append(','); // depends on control dependency: [if], data = [none] } value.append(values[i]); // depends on control dependency: [for], data = [i] } // set the value param.setStringValue(cms, value.toString()); // depends on control dependency: [if], data = [none] } else { // erase: param.setStringValue(cms, ""); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static void substituteDeprecatedConfigPrefix( Configuration config, String deprecatedPrefix, String designatedPrefix) { // set the designated key only if it is not set already final int prefixLen = deprecatedPrefix.length(); Configuration replacement = new Configuration(); for (String key : config.keySet()) { if (key.startsWith(deprecatedPrefix)) { String newKey = designatedPrefix + key.substring(prefixLen); if (!config.containsKey(newKey)) { replacement.setString(newKey, config.getString(key, null)); } } } config.addAll(replacement); } }
public class class_name { public static void substituteDeprecatedConfigPrefix( Configuration config, String deprecatedPrefix, String designatedPrefix) { // set the designated key only if it is not set already final int prefixLen = deprecatedPrefix.length(); Configuration replacement = new Configuration(); for (String key : config.keySet()) { if (key.startsWith(deprecatedPrefix)) { String newKey = designatedPrefix + key.substring(prefixLen); if (!config.containsKey(newKey)) { replacement.setString(newKey, config.getString(key, null)); // depends on control dependency: [if], data = [none] } } } config.addAll(replacement); } }
public class class_name { private void configureSessionManager(final ServletContextHandler context, final Integer minutes, final String cookie, String domain, String path, final String url, final Boolean cookieHttpOnly, final Boolean secure, final String workerName, final Boolean lazy, final String directory, final int maxAge) { LOG.debug("configureSessionManager for context [" + context + "] using - timeout:" + minutes + ", cookie:" + cookie + ", url:" + url + ", cookieHttpOnly:" + cookieHttpOnly + ", workerName:" + workerName + ", lazyLoad:" + lazy + ", storeDirectory: " + directory); final SessionHandler sessionHandler = context.getSessionHandler(); if (sessionHandler != null) { if (minutes != null) { sessionHandler.setMaxInactiveInterval(minutes * 60); LOG.debug("Session timeout set to {} minutes for context [{}]", minutes, context); } if (cookie != null && !"none".equals(cookie)) { sessionHandler.getSessionCookieConfig().setName(cookie); LOG.debug("Session cookie set to {} for context [{}]", cookie, context); sessionHandler.getSessionCookieConfig().setHttpOnly(cookieHttpOnly); LOG.debug("Session cookieHttpOnly set to {} for context [{}]", cookieHttpOnly, context); } if (domain != null && domain.length() > 0) { sessionHandler.getSessionCookieConfig().setDomain(domain); LOG.debug("Session cookie domain set to {} for context [{]]", domain, context); } if (path != null && path.length() > 0) { sessionHandler.getSessionCookieConfig().setPath(path); LOG.debug("Session cookie path set to {} for context [{}]", path, context); } if (secure != null) { sessionHandler.getSessionCookieConfig().setSecure(secure); LOG.debug("Session cookie secure set to {} for context [{]}]", secure, context); } if (url != null) { sessionHandler.setSessionIdPathParameterName(url); LOG.debug("Session URL set to {} for context [{}]", url, context); } if (workerName != null && sessionHandler.getSessionIdManager() != null) { ((DefaultSessionIdManager) sessionHandler.getSessionIdManager()).setWorkerName(workerName); LOG.debug("Worker name set to {} for context [{}]", workerName, context); } } } }
public class class_name { private void configureSessionManager(final ServletContextHandler context, final Integer minutes, final String cookie, String domain, String path, final String url, final Boolean cookieHttpOnly, final Boolean secure, final String workerName, final Boolean lazy, final String directory, final int maxAge) { LOG.debug("configureSessionManager for context [" + context + "] using - timeout:" + minutes + ", cookie:" + cookie + ", url:" + url + ", cookieHttpOnly:" + cookieHttpOnly + ", workerName:" + workerName + ", lazyLoad:" + lazy + ", storeDirectory: " + directory); final SessionHandler sessionHandler = context.getSessionHandler(); if (sessionHandler != null) { if (minutes != null) { sessionHandler.setMaxInactiveInterval(minutes * 60); // depends on control dependency: [if], data = [(minutes] LOG.debug("Session timeout set to {} minutes for context [{}]", minutes, context); // depends on control dependency: [if], data = [none] } if (cookie != null && !"none".equals(cookie)) { sessionHandler.getSessionCookieConfig().setName(cookie); LOG.debug("Session cookie set to {} for context [{}]", cookie, context); sessionHandler.getSessionCookieConfig().setHttpOnly(cookieHttpOnly); LOG.debug("Session cookieHttpOnly set to {} for context [{}]", cookieHttpOnly, context); } if (domain != null && domain.length() > 0) { sessionHandler.getSessionCookieConfig().setDomain(domain); LOG.debug("Session cookie domain set to {} for context [{]]", domain, context); } if (path != null && path.length() > 0) { sessionHandler.getSessionCookieConfig().setPath(path); LOG.debug("Session cookie path set to {} for context [{}]", path, context); } if (secure != null) { sessionHandler.getSessionCookieConfig().setSecure(secure); LOG.debug("Session cookie secure set to {} for context [{]}]", secure, context); } if (url != null) { sessionHandler.setSessionIdPathParameterName(url); LOG.debug("Session URL set to {} for context [{}]", url, context); } if (workerName != null && sessionHandler.getSessionIdManager() != null) { ((DefaultSessionIdManager) sessionHandler.getSessionIdManager()).setWorkerName(workerName); LOG.debug("Worker name set to {} for context [{}]", workerName, context); } } } }
public class class_name { public void init(Object env, Map<String,Object> properties, Object applet) { if (properties == null) properties = new Hashtable<String,Object>(); if (m_properties == null) m_properties = properties; else m_properties.putAll(properties); m_mapTasks = new HashMap<Task,RemoteTask>(); if (applet != null) m_sApplet = applet; try { Class.forName("javax.jnlp.PersistenceService"); // Test if this exists this.setMuffinManager(new MuffinManager(this)); if (this.getMuffinManager().isServiceAvailable()) if ((this.getProperty(Params.REMOTE_HOST) == null) || (this.getProperty(Params.REMOTE_HOST).length() == 0)) this.setProperty(Params.REMOTE_HOST, this.getAppServerName()); } catch (Exception ex) { // Test for JNLP } String strUser = this.getProperty(Params.USER_ID); if (strUser == null) // if (strUser.length() == 0) then you don't want the current sys username if (this.getProperty(Params.USER_NAME) == null) if (this.getMuffinManager() != null) { strUser = this.getMuffinManager().getMuffin(Params.USER_ID); this.setProperty(Params.USER_ID, strUser); // User name is required } if (strUser == null) // if (strUser.length() == 0) then you don't want the current sys username if (this.getProperty(Params.USER_NAME) == null) { try { strUser = System.getProperties().getProperty("user.name"); this.setProperty(Params.USER_NAME, strUser); // User name is required } catch (java.security.AccessControlException ex) { // Ignore this, I'm probably running in an Applet } } try { // Since I send this over the wire, make sure I'm using the default dom implementation System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); } catch (Exception e) { // Ignore this error } if (Util.getPortableImageUtil() == null) { PortableImageUtil portableImageUtil = null; try { Class.forName("javax.swing.ImageIcon"); // Test if swing exists portableImageUtil = (PortableImageUtil)ClassServiceUtility.getClassService().makeObjectFromClassName(SWING_IMAGE_UTIL); } catch (Exception ex) { // Android portableImageUtil = (PortableImageUtil)ClassServiceUtility.getClassService().makeObjectFromClassName(ANDROID_IMAGE_UTIL); } if (portableImageUtil == null) // Sometime OSGi has a hard time finding javax portableImageUtil = (PortableImageUtil)ClassServiceUtility.getClassService().makeObjectFromClassName(SWING_IMAGE_UTIL); Util.setPortableImageUtil(portableImageUtil); } } }
public class class_name { public void init(Object env, Map<String,Object> properties, Object applet) { if (properties == null) properties = new Hashtable<String,Object>(); if (m_properties == null) m_properties = properties; else m_properties.putAll(properties); m_mapTasks = new HashMap<Task,RemoteTask>(); if (applet != null) m_sApplet = applet; try { Class.forName("javax.jnlp.PersistenceService"); // Test if this exists this.setMuffinManager(new MuffinManager(this)); // depends on control dependency: [try], data = [none] if (this.getMuffinManager().isServiceAvailable()) if ((this.getProperty(Params.REMOTE_HOST) == null) || (this.getProperty(Params.REMOTE_HOST).length() == 0)) this.setProperty(Params.REMOTE_HOST, this.getAppServerName()); } catch (Exception ex) { // Test for JNLP } // depends on control dependency: [catch], data = [none] String strUser = this.getProperty(Params.USER_ID); if (strUser == null) // if (strUser.length() == 0) then you don't want the current sys username if (this.getProperty(Params.USER_NAME) == null) if (this.getMuffinManager() != null) { strUser = this.getMuffinManager().getMuffin(Params.USER_ID); // depends on control dependency: [if], data = [none] this.setProperty(Params.USER_ID, strUser); // User name is required // depends on control dependency: [if], data = [none] } if (strUser == null) // if (strUser.length() == 0) then you don't want the current sys username if (this.getProperty(Params.USER_NAME) == null) { try { strUser = System.getProperties().getProperty("user.name"); this.setProperty(Params.USER_NAME, strUser); // User name is required // depends on control dependency: [try], data = [none] } catch (java.security.AccessControlException ex) { // Ignore this, I'm probably running in an Applet } // depends on control dependency: [catch], data = [none] } try { // Since I send this over the wire, make sure I'm using the default dom implementation System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); // depends on control dependency: [try], data = [none] } catch (Exception e) { // Ignore this error } // depends on control dependency: [catch], data = [none] if (Util.getPortableImageUtil() == null) { PortableImageUtil portableImageUtil = null; try { Class.forName("javax.swing.ImageIcon"); // Test if swing exists portableImageUtil = (PortableImageUtil)ClassServiceUtility.getClassService().makeObjectFromClassName(SWING_IMAGE_UTIL); // depends on control dependency: [try], data = [none] } catch (Exception ex) { // Android portableImageUtil = (PortableImageUtil)ClassServiceUtility.getClassService().makeObjectFromClassName(ANDROID_IMAGE_UTIL); } // depends on control dependency: [catch], data = [none] if (portableImageUtil == null) // Sometime OSGi has a hard time finding javax portableImageUtil = (PortableImageUtil)ClassServiceUtility.getClassService().makeObjectFromClassName(SWING_IMAGE_UTIL); Util.setPortableImageUtil(portableImageUtil); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void marshall(DeliveryChannel deliveryChannel, ProtocolMarshaller protocolMarshaller) { if (deliveryChannel == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deliveryChannel.getName(), NAME_BINDING); protocolMarshaller.marshall(deliveryChannel.getS3BucketName(), S3BUCKETNAME_BINDING); protocolMarshaller.marshall(deliveryChannel.getS3KeyPrefix(), S3KEYPREFIX_BINDING); protocolMarshaller.marshall(deliveryChannel.getSnsTopicARN(), SNSTOPICARN_BINDING); protocolMarshaller.marshall(deliveryChannel.getConfigSnapshotDeliveryProperties(), CONFIGSNAPSHOTDELIVERYPROPERTIES_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DeliveryChannel deliveryChannel, ProtocolMarshaller protocolMarshaller) { if (deliveryChannel == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deliveryChannel.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(deliveryChannel.getS3BucketName(), S3BUCKETNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(deliveryChannel.getS3KeyPrefix(), S3KEYPREFIX_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(deliveryChannel.getSnsTopicARN(), SNSTOPICARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(deliveryChannel.getConfigSnapshotDeliveryProperties(), CONFIGSNAPSHOTDELIVERYPROPERTIES_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @SuppressWarnings("unchecked") public A replace(Property property) { Data data = getData(); Data replaced = data.replace(property); if (!replaced.isEmpty()) { return copy(delegate.put("data", Property.toArrayNode(replaced))); } return (A)this; } }
public class class_name { @SuppressWarnings("unchecked") public A replace(Property property) { Data data = getData(); Data replaced = data.replace(property); if (!replaced.isEmpty()) { return copy(delegate.put("data", Property.toArrayNode(replaced))); // depends on control dependency: [if], data = [none] } return (A)this; } }
public class class_name { public static ColorConverter newInstance(Configuration config, String[] options) { if (options.length < 1) { LOGGER.error("Incorrect number of options on style. " + "Expected at least 1, received {}", options.length); return null; } if (options[0] == null) { LOGGER.error("No pattern supplied on style"); return null; } PatternParser parser = PatternLayout.createPatternParser(config); List<PatternFormatter> formatters = parser.parse(options[0]); AnsiElement element = (options.length != 1) ? ELEMENTS.get(options[1]) : null; return new ColorConverter(formatters, element); } }
public class class_name { public static ColorConverter newInstance(Configuration config, String[] options) { if (options.length < 1) { LOGGER.error("Incorrect number of options on style. " + "Expected at least 1, received {}", options.length); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } if (options[0] == null) { LOGGER.error("No pattern supplied on style"); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } PatternParser parser = PatternLayout.createPatternParser(config); List<PatternFormatter> formatters = parser.parse(options[0]); AnsiElement element = (options.length != 1) ? ELEMENTS.get(options[1]) : null; return new ColorConverter(formatters, element); } }
public class class_name { public void marshall(DescribeClusterRequest describeClusterRequest, ProtocolMarshaller protocolMarshaller) { if (describeClusterRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeClusterRequest.getClusterArn(), CLUSTERARN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DescribeClusterRequest describeClusterRequest, ProtocolMarshaller protocolMarshaller) { if (describeClusterRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeClusterRequest.getClusterArn(), CLUSTERARN_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void resetDimensions() { if (immutable) throw new IllegalStateException("Cant modify"); ArrayList<Dimension> newDimensions = new ArrayList<>(); for (Dimension dim : dimensions) { if (dim.isShared()) { Dimension newD = getParentGroup().findDimension(dim.getShortName()); if (newD == null) throw new IllegalArgumentException("Variable " + getFullName() + " resetDimensions FAILED, dim doesnt exist in parent group=" + dim); newDimensions.add(newD); } else { newDimensions.add(dim); } } this.dimensions = newDimensions; resetShape(); } }
public class class_name { public void resetDimensions() { if (immutable) throw new IllegalStateException("Cant modify"); ArrayList<Dimension> newDimensions = new ArrayList<>(); for (Dimension dim : dimensions) { if (dim.isShared()) { Dimension newD = getParentGroup().findDimension(dim.getShortName()); if (newD == null) throw new IllegalArgumentException("Variable " + getFullName() + " resetDimensions FAILED, dim doesnt exist in parent group=" + dim); newDimensions.add(newD); // depends on control dependency: [if], data = [none] } else { newDimensions.add(dim); // depends on control dependency: [if], data = [none] } } this.dimensions = newDimensions; resetShape(); } }
public class class_name { private static String getPoliciesDocType(PolicyType type) { String docType = "planPolicies"; //$NON-NLS-1$ if (type == PolicyType.Api) { docType = "apiPolicies"; //$NON-NLS-1$ } else if (type == PolicyType.Client) { docType = "clientPolicies"; //$NON-NLS-1$ } return docType; } }
public class class_name { private static String getPoliciesDocType(PolicyType type) { String docType = "planPolicies"; //$NON-NLS-1$ if (type == PolicyType.Api) { docType = "apiPolicies"; //$NON-NLS-1$ // depends on control dependency: [if], data = [none] } else if (type == PolicyType.Client) { docType = "clientPolicies"; //$NON-NLS-1$ // depends on control dependency: [if], data = [none] } return docType; } }
public class class_name { public void marshall(CopyBackupToRegionRequest copyBackupToRegionRequest, ProtocolMarshaller protocolMarshaller) { if (copyBackupToRegionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(copyBackupToRegionRequest.getDestinationRegion(), DESTINATIONREGION_BINDING); protocolMarshaller.marshall(copyBackupToRegionRequest.getBackupId(), BACKUPID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(CopyBackupToRegionRequest copyBackupToRegionRequest, ProtocolMarshaller protocolMarshaller) { if (copyBackupToRegionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(copyBackupToRegionRequest.getDestinationRegion(), DESTINATIONREGION_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(copyBackupToRegionRequest.getBackupId(), BACKUPID_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public final String entryRuleOpOr() throws RecognitionException { String current = null; AntlrDatatypeRuleToken iv_ruleOpOr = null; try { // InternalXbase.g:425:44: (iv_ruleOpOr= ruleOpOr EOF ) // InternalXbase.g:426:2: iv_ruleOpOr= ruleOpOr EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getOpOrRule()); } pushFollow(FOLLOW_1); iv_ruleOpOr=ruleOpOr(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleOpOr.getText(); } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } }
public class class_name { public final String entryRuleOpOr() throws RecognitionException { String current = null; AntlrDatatypeRuleToken iv_ruleOpOr = null; try { // InternalXbase.g:425:44: (iv_ruleOpOr= ruleOpOr EOF ) // InternalXbase.g:426:2: iv_ruleOpOr= ruleOpOr EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getOpOrRule()); // depends on control dependency: [if], data = [none] } pushFollow(FOLLOW_1); iv_ruleOpOr=ruleOpOr(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleOpOr.getText(); // depends on control dependency: [if], data = [none] } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } }
public class class_name { protected void updateRepositoryBase(RepositoryBase value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; Element root = updateElement(counter, element, xmlTag, shouldExist); if (shouldExist) { Counter innerCount = new Counter(counter.getDepth() + 1); findAndReplaceSimpleElement(innerCount, root, "id", value.getId(), null); findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); findAndReplaceSimpleElement(innerCount, root, "layout", value.getLayout(), "default"); } } }
public class class_name { protected void updateRepositoryBase(RepositoryBase value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; Element root = updateElement(counter, element, xmlTag, shouldExist); if (shouldExist) { Counter innerCount = new Counter(counter.getDepth() + 1); findAndReplaceSimpleElement(innerCount, root, "id", value.getId(), null); // depends on control dependency: [if], data = [none] findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); // depends on control dependency: [if], data = [none] findAndReplaceSimpleElement(innerCount, root, "url", value.getUrl(), null); // depends on control dependency: [if], data = [none] findAndReplaceSimpleElement(innerCount, root, "layout", value.getLayout(), "default"); // depends on control dependency: [if], data = [none] } } }
public class class_name { final boolean isExpired() throws SevereMessageStoreException { // 182086 if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "isExpired"); if (isAvailable() && internalCanExpire()) { // we can only expire if we are available long expiryTime = _tuple.getExpiryTime(); if (expiryTime != 0 && expiryTime <= Expirer.timeNow()) { // we are due to expire boolean hasBecomeNonReleasable = false; synchronized (this) { if (ItemLinkState.STATE_AVAILABLE == _itemLinkState) { // force item to be present AbstractItem item = _getItemNoRestore(); if (null == item) { item = _restoreItem(); } ListStatistics stats = getParentStatistics(); synchronized (stats) { stats.incrementExpiring(); stats.decrementAvailable(); } _lockID = AbstractItemLink.EXPIRY_LOCK_ID; hasBecomeNonReleasable = _declareNotDiscardable(item); _itemLinkState = ItemLinkState.STATE_LOCKED_FOR_EXPIRY; } } if (hasBecomeNonReleasable) { _declareNotReleasable(); } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "isExpired", Boolean.valueOf(isExpiring())); return isExpiring(); } }
public class class_name { final boolean isExpired() throws SevereMessageStoreException { // 182086 if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "isExpired"); if (isAvailable() && internalCanExpire()) { // we can only expire if we are available long expiryTime = _tuple.getExpiryTime(); if (expiryTime != 0 && expiryTime <= Expirer.timeNow()) { // we are due to expire boolean hasBecomeNonReleasable = false; synchronized (this) // depends on control dependency: [if], data = [none] { if (ItemLinkState.STATE_AVAILABLE == _itemLinkState) { // force item to be present AbstractItem item = _getItemNoRestore(); if (null == item) { item = _restoreItem(); // depends on control dependency: [if], data = [none] } ListStatistics stats = getParentStatistics(); synchronized (stats) // depends on control dependency: [if], data = [none] { stats.incrementExpiring(); stats.decrementAvailable(); } _lockID = AbstractItemLink.EXPIRY_LOCK_ID; // depends on control dependency: [if], data = [none] hasBecomeNonReleasable = _declareNotDiscardable(item); // depends on control dependency: [if], data = [none] _itemLinkState = ItemLinkState.STATE_LOCKED_FOR_EXPIRY; // depends on control dependency: [if], data = [none] } } if (hasBecomeNonReleasable) { _declareNotReleasable(); // depends on control dependency: [if], data = [none] } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "isExpired", Boolean.valueOf(isExpiring())); return isExpiring(); } }
public class class_name { public Observable<ServiceResponse<Page<JobResponseInner>>> listJobsWithServiceResponseAsync(final String resourceGroupName, final String resourceName) { return listJobsSinglePageAsync(resourceGroupName, resourceName) .concatMap(new Func1<ServiceResponse<Page<JobResponseInner>>, Observable<ServiceResponse<Page<JobResponseInner>>>>() { @Override public Observable<ServiceResponse<Page<JobResponseInner>>> call(ServiceResponse<Page<JobResponseInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listJobsNextWithServiceResponseAsync(nextPageLink)); } }); } }
public class class_name { public Observable<ServiceResponse<Page<JobResponseInner>>> listJobsWithServiceResponseAsync(final String resourceGroupName, final String resourceName) { return listJobsSinglePageAsync(resourceGroupName, resourceName) .concatMap(new Func1<ServiceResponse<Page<JobResponseInner>>, Observable<ServiceResponse<Page<JobResponseInner>>>>() { @Override public Observable<ServiceResponse<Page<JobResponseInner>>> call(ServiceResponse<Page<JobResponseInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); // depends on control dependency: [if], data = [none] } return Observable.just(page).concatWith(listJobsNextWithServiceResponseAsync(nextPageLink)); } }); } }
public class class_name { public boolean removeBuddy(Request req, long timeout) { initErrorInfo(); if (parent.retireBuddy(targetUri) == null) { setReturnCode(SipSession.INVALID_ARGUMENT); setErrorMessage("Buddy removal for URI " + targetUri + " failed, not found in buddy list."); return false; } if (endSubscription(req, timeout, parent.getProxyHost() != null, "Buddy removed from contact list") == true) { return true; } // unsubscribe failed return false; } }
public class class_name { public boolean removeBuddy(Request req, long timeout) { initErrorInfo(); if (parent.retireBuddy(targetUri) == null) { setReturnCode(SipSession.INVALID_ARGUMENT); // depends on control dependency: [if], data = [none] setErrorMessage("Buddy removal for URI " + targetUri + " failed, not found in buddy list."); // depends on control dependency: [if], data = [none] return false; // depends on control dependency: [if], data = [none] } if (endSubscription(req, timeout, parent.getProxyHost() != null, "Buddy removed from contact list") == true) { return true; // depends on control dependency: [if], data = [none] } // unsubscribe failed return false; } }
public class class_name { public String formatReduced( IsoDateStyle dateStyle, IsoDecimalStyle decimalStyle, ClockUnit precision, InfinityStyle infinityStyle ) { TimestampInterval interval = this.toCanonical(); PlainTimestamp start = interval.getStartAsTimestamp(); PlainTimestamp end = interval.getEndAsTimestamp(); StringBuilder buffer = new StringBuilder(60); ChronoPrinter<PlainTime> timePrinter = ( dateStyle.isExtended() ? Iso8601Format.ofExtendedTime(decimalStyle, precision) : Iso8601Format.ofBasicTime(decimalStyle, precision)); ChronoPrinter<PlainTimestamp> printer = null; if (interval.getStart().isInfinite()) { printer = Iso8601Format.ofTimestamp(dateStyle, decimalStyle, precision); buffer.append(infinityStyle.displayPast(printer, PlainTimestamp.axis())); } else { Iso8601Format.ofDate(dateStyle).print(start.getCalendarDate(), buffer); buffer.append('T'); timePrinter.print(start.getWallTime(), buffer); } buffer.append('/'); if (interval.isFinite()) { PlainDate d1 = start.getCalendarDate(); PlainDate d2 = end.getCalendarDate(); if (!d1.equals(d2)) { DateInterval.getEndPrinter(dateStyle, d1, d2).print(d2, buffer); } buffer.append('T'); timePrinter.print(end.getWallTime(), buffer); } else if (interval.getEnd().isInfinite()) { if (printer == null) { printer = Iso8601Format.ofTimestamp(dateStyle, decimalStyle, precision); } buffer.append(infinityStyle.displayFuture(printer, PlainTimestamp.axis())); } else { if (printer == null) { printer = Iso8601Format.ofTimestamp(dateStyle, decimalStyle, precision); } printer.print(end, buffer); } return buffer.toString(); } }
public class class_name { public String formatReduced( IsoDateStyle dateStyle, IsoDecimalStyle decimalStyle, ClockUnit precision, InfinityStyle infinityStyle ) { TimestampInterval interval = this.toCanonical(); PlainTimestamp start = interval.getStartAsTimestamp(); PlainTimestamp end = interval.getEndAsTimestamp(); StringBuilder buffer = new StringBuilder(60); ChronoPrinter<PlainTime> timePrinter = ( dateStyle.isExtended() ? Iso8601Format.ofExtendedTime(decimalStyle, precision) : Iso8601Format.ofBasicTime(decimalStyle, precision)); ChronoPrinter<PlainTimestamp> printer = null; if (interval.getStart().isInfinite()) { printer = Iso8601Format.ofTimestamp(dateStyle, decimalStyle, precision); // depends on control dependency: [if], data = [none] buffer.append(infinityStyle.displayPast(printer, PlainTimestamp.axis())); // depends on control dependency: [if], data = [none] } else { Iso8601Format.ofDate(dateStyle).print(start.getCalendarDate(), buffer); // depends on control dependency: [if], data = [none] buffer.append('T'); // depends on control dependency: [if], data = [none] timePrinter.print(start.getWallTime(), buffer); // depends on control dependency: [if], data = [none] } buffer.append('/'); if (interval.isFinite()) { PlainDate d1 = start.getCalendarDate(); PlainDate d2 = end.getCalendarDate(); if (!d1.equals(d2)) { DateInterval.getEndPrinter(dateStyle, d1, d2).print(d2, buffer); // depends on control dependency: [if], data = [none] } buffer.append('T'); // depends on control dependency: [if], data = [none] timePrinter.print(end.getWallTime(), buffer); // depends on control dependency: [if], data = [none] } else if (interval.getEnd().isInfinite()) { if (printer == null) { printer = Iso8601Format.ofTimestamp(dateStyle, decimalStyle, precision); // depends on control dependency: [if], data = [none] } buffer.append(infinityStyle.displayFuture(printer, PlainTimestamp.axis())); // depends on control dependency: [if], data = [none] } else { if (printer == null) { printer = Iso8601Format.ofTimestamp(dateStyle, decimalStyle, precision); // depends on control dependency: [if], data = [none] } printer.print(end, buffer); // depends on control dependency: [if], data = [none] } return buffer.toString(); } }
public class class_name { public boolean isConsumerSuspended(int suspendFlag) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "isConsumerSuspended", Integer.valueOf(suspendFlag)); boolean suspended; this.lock(); try { if (suspendFlag == 0) { // the passed in suspend flag was 0 this means the caller wants to know if the consumer // is suspended for any reason suspended = _consumerSuspended; } else if (_suspendFlags == 0) // No flags set so it must not be suspended { suspended = false; } else if ((_suspendFlags & suspendFlag) == suspendFlag) { //We were asked about certain type of suspended and we are suspended for that reason suspended = true; } else { suspended = false; } } finally { this.unlock(); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "isConsumerSuspended", Boolean.valueOf(suspended)); return suspended; } }
public class class_name { public boolean isConsumerSuspended(int suspendFlag) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "isConsumerSuspended", Integer.valueOf(suspendFlag)); boolean suspended; this.lock(); try { if (suspendFlag == 0) { // the passed in suspend flag was 0 this means the caller wants to know if the consumer // is suspended for any reason suspended = _consumerSuspended; // depends on control dependency: [if], data = [none] } else if (_suspendFlags == 0) // No flags set so it must not be suspended { suspended = false; // depends on control dependency: [if], data = [none] } else if ((_suspendFlags & suspendFlag) == suspendFlag) { //We were asked about certain type of suspended and we are suspended for that reason suspended = true; // depends on control dependency: [if], data = [none] } else { suspended = false; // depends on control dependency: [if], data = [none] } } finally { this.unlock(); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "isConsumerSuspended", Boolean.valueOf(suspended)); return suspended; } }
public class class_name { public boolean isEmbedLinkUrlExpired(){ Long urlCreationTime = getUrlCreationTime(); if (urlCreationTime == null){ return true; } return (System.currentTimeMillis() - urlCreationTime) < (60 * 1000); } }
public class class_name { public boolean isEmbedLinkUrlExpired(){ Long urlCreationTime = getUrlCreationTime(); if (urlCreationTime == null){ return true; // depends on control dependency: [if], data = [none] } return (System.currentTimeMillis() - urlCreationTime) < (60 * 1000); } }
public class class_name { private Collection<String> getFileDirectory(String path) throws Exception { // If the crawler is being closed, we return if (closed) { return Collections.emptyList(); } logger.trace("Querying elasticsearch for files in dir [{}:{}]", PATH_ROOT, SignTool.sign(path)); Collection<String> files = new ArrayList<>(); ESSearchResponse response = esClient.search( new ESSearchRequest() .withIndex(fsSettings.getElasticsearch().getIndex()) .withSize(REQUEST_SIZE) .addField(FILE_FILENAME) .withESQuery(new ESTermQuery(PATH_ROOT, SignTool.sign(path)))); logger.trace("Response [{}]", response.toString()); if (response.getHits() != null) { for (ESSearchHit hit : response.getHits()) { String name; if (hit.getFields() != null && hit.getFields().get(FILE_FILENAME) != null) { // In case someone disabled _source which is not recommended name = hit.getFields().get(FILE_FILENAME).getValue(); } else { // Houston, we have a problem ! We can't get the old files from ES logger.warn("Can't find stored field name to check existing filenames in path [{}]. " + "Please set store: true on field [{}]", path, FILE_FILENAME); throw new RuntimeException("Mapping is incorrect: please set stored: true on field [" + FILE_FILENAME + "]."); } files.add(name); } } logger.trace("We found: {}", files); return files; } }
public class class_name { private Collection<String> getFileDirectory(String path) throws Exception { // If the crawler is being closed, we return if (closed) { return Collections.emptyList(); } logger.trace("Querying elasticsearch for files in dir [{}:{}]", PATH_ROOT, SignTool.sign(path)); Collection<String> files = new ArrayList<>(); ESSearchResponse response = esClient.search( new ESSearchRequest() .withIndex(fsSettings.getElasticsearch().getIndex()) .withSize(REQUEST_SIZE) .addField(FILE_FILENAME) .withESQuery(new ESTermQuery(PATH_ROOT, SignTool.sign(path)))); logger.trace("Response [{}]", response.toString()); if (response.getHits() != null) { for (ESSearchHit hit : response.getHits()) { String name; if (hit.getFields() != null && hit.getFields().get(FILE_FILENAME) != null) { // In case someone disabled _source which is not recommended name = hit.getFields().get(FILE_FILENAME).getValue(); // depends on control dependency: [if], data = [none] } else { // Houston, we have a problem ! We can't get the old files from ES logger.warn("Can't find stored field name to check existing filenames in path [{}]. " + "Please set store: true on field [{}]", path, FILE_FILENAME); // depends on control dependency: [if], data = [none] throw new RuntimeException("Mapping is incorrect: please set stored: true on field [" + FILE_FILENAME + "]."); } files.add(name); } } logger.trace("We found: {}", files); return files; } }
public class class_name { public void setGroupId(final String groupId) { if (groupId == null && this.groupId == null) { return; } else if (groupId == null) { removeChild(this.groupId); this.groupId = null; } else if (this.groupId == null) { this.groupId = new KeyValueNode<String>(CommonConstants.CS_MAVEN_GROUP_ID_TITLE, groupId); appendChild(this.groupId, false); } else { this.groupId.setValue(groupId); } } }
public class class_name { public void setGroupId(final String groupId) { if (groupId == null && this.groupId == null) { return; // depends on control dependency: [if], data = [none] } else if (groupId == null) { removeChild(this.groupId); // depends on control dependency: [if], data = [none] this.groupId = null; // depends on control dependency: [if], data = [none] } else if (this.groupId == null) { this.groupId = new KeyValueNode<String>(CommonConstants.CS_MAVEN_GROUP_ID_TITLE, groupId); // depends on control dependency: [if], data = [none] appendChild(this.groupId, false); // depends on control dependency: [if], data = [(this.groupId] } else { this.groupId.setValue(groupId); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static <T> T[] join(final T[] base, final T... add) { if (add == null) { return base; } else if (base == null) { return add; } if (add.length == 0) { return base; } final T[] result = Arrays.copyOf(base, base.length + add.length); System.arraycopy(add, 0, result, base.length, add.length); return result; } }
public class class_name { public static <T> T[] join(final T[] base, final T... add) { if (add == null) { return base; // depends on control dependency: [if], data = [none] } else if (base == null) { return add; // depends on control dependency: [if], data = [none] } if (add.length == 0) { return base; // depends on control dependency: [if], data = [none] } final T[] result = Arrays.copyOf(base, base.length + add.length); System.arraycopy(add, 0, result, base.length, add.length); return result; } }
public class class_name { protected void reschedule(long minTimeoutAt) { if (minTimeoutAt == Long.MAX_VALUE) { for (PendingPromise pending : promises.values()) { if (pending.timeoutAt > 0 && pending.timeoutAt < minTimeoutAt) { minTimeoutAt = pending.timeoutAt; } } long timeoutAt; requestStreamReadLock.lock(); try { for (IncomingStream stream : requestStreams.values()) { timeoutAt = stream.getTimeoutAt(); if (timeoutAt > 0 && timeoutAt < minTimeoutAt) { minTimeoutAt = timeoutAt; } } } finally { requestStreamReadLock.unlock(); } responseStreamReadLock.lock(); try { for (IncomingStream stream : responseStreams.values()) { timeoutAt = stream.getTimeoutAt(); if (timeoutAt > 0 && timeoutAt < minTimeoutAt) { minTimeoutAt = timeoutAt; } } } finally { responseStreamReadLock.unlock(); } } long now = System.currentTimeMillis(); if (minTimeoutAt == Long.MAX_VALUE) { ScheduledFuture<?> t = callTimeoutTimer.get(); if (t != null) { if (prevTimeoutAt.get() > now) { t.cancel(false); prevTimeoutAt.set(0); } else { callTimeoutTimer.set(null); prevTimeoutAt.set(0); } } } else { minTimeoutAt = (minTimeoutAt / 100 * 100) + 100; long prev = prevTimeoutAt.getAndSet(minTimeoutAt); if (prev == minTimeoutAt) { // Next when not changed return; } // Stop previous timer ScheduledFuture<?> t = callTimeoutTimer.get(); if (t != null) { t.cancel(false); } // Schedule next timeout timer long delay = Math.max(10, minTimeoutAt - now); callTimeoutTimer.set(scheduler.schedule(this::checkTimeouts, delay, TimeUnit.MILLISECONDS)); } } }
public class class_name { protected void reschedule(long minTimeoutAt) { if (minTimeoutAt == Long.MAX_VALUE) { for (PendingPromise pending : promises.values()) { if (pending.timeoutAt > 0 && pending.timeoutAt < minTimeoutAt) { minTimeoutAt = pending.timeoutAt; // depends on control dependency: [if], data = [none] } } long timeoutAt; requestStreamReadLock.lock(); // depends on control dependency: [if], data = [none] try { for (IncomingStream stream : requestStreams.values()) { timeoutAt = stream.getTimeoutAt(); // depends on control dependency: [for], data = [stream] if (timeoutAt > 0 && timeoutAt < minTimeoutAt) { minTimeoutAt = timeoutAt; // depends on control dependency: [if], data = [none] } } } finally { requestStreamReadLock.unlock(); } responseStreamReadLock.lock(); // depends on control dependency: [if], data = [none] try { for (IncomingStream stream : responseStreams.values()) { timeoutAt = stream.getTimeoutAt(); // depends on control dependency: [for], data = [stream] if (timeoutAt > 0 && timeoutAt < minTimeoutAt) { minTimeoutAt = timeoutAt; // depends on control dependency: [if], data = [none] } } } finally { responseStreamReadLock.unlock(); } } long now = System.currentTimeMillis(); if (minTimeoutAt == Long.MAX_VALUE) { ScheduledFuture<?> t = callTimeoutTimer.get(); if (t != null) { if (prevTimeoutAt.get() > now) { t.cancel(false); // depends on control dependency: [if], data = [none] prevTimeoutAt.set(0); // depends on control dependency: [if], data = [none] } else { callTimeoutTimer.set(null); // depends on control dependency: [if], data = [none] prevTimeoutAt.set(0); // depends on control dependency: [if], data = [none] } } } else { minTimeoutAt = (minTimeoutAt / 100 * 100) + 100; // depends on control dependency: [if], data = [(minTimeoutAt] long prev = prevTimeoutAt.getAndSet(minTimeoutAt); if (prev == minTimeoutAt) { // Next when not changed return; // depends on control dependency: [if], data = [none] } // Stop previous timer ScheduledFuture<?> t = callTimeoutTimer.get(); if (t != null) { t.cancel(false); // depends on control dependency: [if], data = [none] } // Schedule next timeout timer long delay = Math.max(10, minTimeoutAt - now); callTimeoutTimer.set(scheduler.schedule(this::checkTimeouts, delay, TimeUnit.MILLISECONDS)); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void marshall(ParallelismConfigurationUpdate parallelismConfigurationUpdate, ProtocolMarshaller protocolMarshaller) { if (parallelismConfigurationUpdate == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(parallelismConfigurationUpdate.getConfigurationTypeUpdate(), CONFIGURATIONTYPEUPDATE_BINDING); protocolMarshaller.marshall(parallelismConfigurationUpdate.getParallelismUpdate(), PARALLELISMUPDATE_BINDING); protocolMarshaller.marshall(parallelismConfigurationUpdate.getParallelismPerKPUUpdate(), PARALLELISMPERKPUUPDATE_BINDING); protocolMarshaller.marshall(parallelismConfigurationUpdate.getAutoScalingEnabledUpdate(), AUTOSCALINGENABLEDUPDATE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ParallelismConfigurationUpdate parallelismConfigurationUpdate, ProtocolMarshaller protocolMarshaller) { if (parallelismConfigurationUpdate == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(parallelismConfigurationUpdate.getConfigurationTypeUpdate(), CONFIGURATIONTYPEUPDATE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(parallelismConfigurationUpdate.getParallelismUpdate(), PARALLELISMUPDATE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(parallelismConfigurationUpdate.getParallelismPerKPUUpdate(), PARALLELISMPERKPUUPDATE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(parallelismConfigurationUpdate.getAutoScalingEnabledUpdate(), AUTOSCALINGENABLEDUPDATE_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @RequestMapping(value = "/getThumbnail.action", method = RequestMethod.GET) public ResponseEntity<?> getThumbnail(@RequestParam Integer id) { final HttpHeaders responseHeaders = new HttpHeaders(); Map<String, Object> responseMap; try { // try to get the image ImageFile image = service.findById(id); if (image == null) { throw new Exception("Could not find the image with id " + id); } byte[] imageBytes = null; imageBytes = image.getThumbnail(); responseHeaders.setContentType( MediaType.parseMediaType(image.getFileType())); LOG.info("Successfully got the image thumbnail " + image.getFileName()); return new ResponseEntity<byte[]>( imageBytes, responseHeaders, HttpStatus.OK); } catch (Exception e) { final String errorMessage = "Could not get the image thumbnail: " + e.getMessage(); LOG.error(errorMessage); responseMap = ResultSet.error(errorMessage); responseHeaders.setContentType(MediaType.APPLICATION_JSON); return new ResponseEntity<Map<String, Object>>( responseMap, responseHeaders, HttpStatus.OK); } } }
public class class_name { @RequestMapping(value = "/getThumbnail.action", method = RequestMethod.GET) public ResponseEntity<?> getThumbnail(@RequestParam Integer id) { final HttpHeaders responseHeaders = new HttpHeaders(); Map<String, Object> responseMap; try { // try to get the image ImageFile image = service.findById(id); if (image == null) { throw new Exception("Could not find the image with id " + id); } byte[] imageBytes = null; imageBytes = image.getThumbnail(); // depends on control dependency: [try], data = [none] responseHeaders.setContentType( MediaType.parseMediaType(image.getFileType())); // depends on control dependency: [try], data = [none] LOG.info("Successfully got the image thumbnail " + image.getFileName()); // depends on control dependency: [try], data = [none] return new ResponseEntity<byte[]>( imageBytes, responseHeaders, HttpStatus.OK); // depends on control dependency: [try], data = [none] } catch (Exception e) { final String errorMessage = "Could not get the image thumbnail: " + e.getMessage(); LOG.error(errorMessage); responseMap = ResultSet.error(errorMessage); responseHeaders.setContentType(MediaType.APPLICATION_JSON); return new ResponseEntity<Map<String, Object>>( responseMap, responseHeaders, HttpStatus.OK); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void setDescriptionColor(final Color COLOR) { if (null == descriptionColor) { _descriptionColor = COLOR; fireTileEvent(REDRAW_EVENT); } else { descriptionColor.set(COLOR); } } }
public class class_name { public void setDescriptionColor(final Color COLOR) { if (null == descriptionColor) { _descriptionColor = COLOR; // depends on control dependency: [if], data = [none] fireTileEvent(REDRAW_EVENT); // depends on control dependency: [if], data = [none] } else { descriptionColor.set(COLOR); // depends on control dependency: [if], data = [none] } } }
public class class_name { @NonNull private static List<Point> coordAll(@NonNull List<Point> coords, @NonNull MultiPolygon multiPolygon, boolean excludeWrapCoord) { int wrapShrink = excludeWrapCoord ? 1 : 0; for (int i = 0; i < multiPolygon.coordinates().size(); i++) { for (int j = 0; j < multiPolygon.coordinates().get(i).size(); j++) { for (int k = 0; k < multiPolygon.coordinates().get(i).get(j).size() - wrapShrink; k++) { coords.add(multiPolygon.coordinates().get(i).get(j).get(k)); } } } return coords; } }
public class class_name { @NonNull private static List<Point> coordAll(@NonNull List<Point> coords, @NonNull MultiPolygon multiPolygon, boolean excludeWrapCoord) { int wrapShrink = excludeWrapCoord ? 1 : 0; for (int i = 0; i < multiPolygon.coordinates().size(); i++) { for (int j = 0; j < multiPolygon.coordinates().get(i).size(); j++) { for (int k = 0; k < multiPolygon.coordinates().get(i).get(j).size() - wrapShrink; k++) { coords.add(multiPolygon.coordinates().get(i).get(j).get(k)); // depends on control dependency: [for], data = [k] } } } return coords; } }
public class class_name { public void addSecureMethod(Class<?> javaType, String mappedName, List<ConfigAttribute> attr) { String name = javaType.getName() + '.' + mappedName; if (logger.isDebugEnabled()) { logger.debug("Request to add secure method [" + name + "] with attributes [" + attr + "]"); } Method[] methods = javaType.getMethods(); List<Method> matchingMethods = new ArrayList<>(); for (Method m : methods) { if (m.getName().equals(mappedName) || isMatch(m.getName(), mappedName)) { matchingMethods.add(m); } } if (matchingMethods.isEmpty()) { throw new IllegalArgumentException("Couldn't find method '" + mappedName + "' on '" + javaType + "'"); } // register all matching methods for (Method method : matchingMethods) { RegisteredMethod registeredMethod = new RegisteredMethod(method, javaType); String regMethodName = (String) this.nameMap.get(registeredMethod); if ((regMethodName == null) || (!regMethodName.equals(name) && (regMethodName.length() <= name .length()))) { // no already registered method name, or more specific // method name specification now -> (re-)register method if (regMethodName != null) { logger.debug("Replacing attributes for secure method [" + method + "]: current name [" + name + "] is more specific than [" + regMethodName + "]"); } this.nameMap.put(registeredMethod, name); addSecureMethod(registeredMethod, attr); } else { logger.debug("Keeping attributes for secure method [" + method + "]: current name [" + name + "] is not more specific than [" + regMethodName + "]"); } } } }
public class class_name { public void addSecureMethod(Class<?> javaType, String mappedName, List<ConfigAttribute> attr) { String name = javaType.getName() + '.' + mappedName; if (logger.isDebugEnabled()) { logger.debug("Request to add secure method [" + name + "] with attributes [" + attr + "]"); // depends on control dependency: [if], data = [none] } Method[] methods = javaType.getMethods(); List<Method> matchingMethods = new ArrayList<>(); for (Method m : methods) { if (m.getName().equals(mappedName) || isMatch(m.getName(), mappedName)) { matchingMethods.add(m); // depends on control dependency: [if], data = [none] } } if (matchingMethods.isEmpty()) { throw new IllegalArgumentException("Couldn't find method '" + mappedName + "' on '" + javaType + "'"); } // register all matching methods for (Method method : matchingMethods) { RegisteredMethod registeredMethod = new RegisteredMethod(method, javaType); String regMethodName = (String) this.nameMap.get(registeredMethod); if ((regMethodName == null) || (!regMethodName.equals(name) && (regMethodName.length() <= name .length()))) { // no already registered method name, or more specific // method name specification now -> (re-)register method if (regMethodName != null) { logger.debug("Replacing attributes for secure method [" + method + "]: current name [" + name + "] is more specific than [" + regMethodName + "]"); // depends on control dependency: [if], data = [none] } this.nameMap.put(registeredMethod, name); // depends on control dependency: [if], data = [none] addSecureMethod(registeredMethod, attr); // depends on control dependency: [if], data = [none] } else { logger.debug("Keeping attributes for secure method [" + method + "]: current name [" + name + "] is not more specific than [" + regMethodName + "]"); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public Class<?> getNestedParameterType() { if (this.nestingLevel > 1) { Type type = getGenericParameterType(); for (int i = 2; i <= this.nestingLevel; i++) { if (type instanceof ParameterizedType) { Type[] args = ((ParameterizedType) type).getActualTypeArguments(); Integer index = getTypeIndexForLevel(i); type = args[index != null ? index : args.length - 1]; } } if (type instanceof Class) { return (Class<?>) type; } else if (type instanceof ParameterizedType) { Type arg = ((ParameterizedType) type).getRawType(); if (arg instanceof Class) { return (Class<?>) arg; } } return Object.class; } else { return getParameterType(); } } }
public class class_name { public Class<?> getNestedParameterType() { if (this.nestingLevel > 1) { Type type = getGenericParameterType(); for (int i = 2; i <= this.nestingLevel; i++) { if (type instanceof ParameterizedType) { Type[] args = ((ParameterizedType) type).getActualTypeArguments(); Integer index = getTypeIndexForLevel(i); type = args[index != null ? index : args.length - 1]; // depends on control dependency: [if], data = [none] } } if (type instanceof Class) { return (Class<?>) type; // depends on control dependency: [if], data = [none] } else if (type instanceof ParameterizedType) { Type arg = ((ParameterizedType) type).getRawType(); if (arg instanceof Class) { return (Class<?>) arg; // depends on control dependency: [if], data = [none] } } return Object.class; } else { return getParameterType(); } } }
public class class_name { ProjectionRect latLonToProjBB2(LatLonRect latlonRect) { double minx, maxx, miny, maxy; LatLonPointImpl llpt = latlonRect.getLowerLeftPoint(); LatLonPointImpl urpt = latlonRect.getUpperRightPoint(); LatLonPointImpl lrpt = latlonRect.getLowerRightPoint(); LatLonPointImpl ulpt = latlonRect.getUpperLeftPoint(); if (isLatLon()) { minx = getMinOrMaxLon(llpt.getLongitude(), ulpt.getLongitude(), true); miny = Math.min(llpt.getLatitude(), lrpt.getLatitude()); maxx = getMinOrMaxLon(urpt.getLongitude(), lrpt.getLongitude(), false); maxy = Math.min(ulpt.getLatitude(), urpt.getLatitude()); } else { ProjectionPoint ll = latLonToProj(llpt, new ProjectionPointImpl()); ProjectionPoint ur = latLonToProj(urpt, new ProjectionPointImpl()); ProjectionPoint lr = latLonToProj(lrpt, new ProjectionPointImpl()); ProjectionPoint ul = latLonToProj(ulpt, new ProjectionPointImpl()); minx = Math.min(ll.getX(), ul.getX()); miny = Math.min(ll.getY(), lr.getY()); maxx = Math.max(ur.getX(), lr.getX()); maxy = Math.max(ul.getY(), ur.getY()); } return new ProjectionRect(minx, miny, maxx, maxy); } }
public class class_name { ProjectionRect latLonToProjBB2(LatLonRect latlonRect) { double minx, maxx, miny, maxy; LatLonPointImpl llpt = latlonRect.getLowerLeftPoint(); LatLonPointImpl urpt = latlonRect.getUpperRightPoint(); LatLonPointImpl lrpt = latlonRect.getLowerRightPoint(); LatLonPointImpl ulpt = latlonRect.getUpperLeftPoint(); if (isLatLon()) { minx = getMinOrMaxLon(llpt.getLongitude(), ulpt.getLongitude(), true); // depends on control dependency: [if], data = [none] miny = Math.min(llpt.getLatitude(), lrpt.getLatitude()); // depends on control dependency: [if], data = [none] maxx = getMinOrMaxLon(urpt.getLongitude(), lrpt.getLongitude(), false); // depends on control dependency: [if], data = [none] maxy = Math.min(ulpt.getLatitude(), urpt.getLatitude()); // depends on control dependency: [if], data = [none] } else { ProjectionPoint ll = latLonToProj(llpt, new ProjectionPointImpl()); ProjectionPoint ur = latLonToProj(urpt, new ProjectionPointImpl()); ProjectionPoint lr = latLonToProj(lrpt, new ProjectionPointImpl()); ProjectionPoint ul = latLonToProj(ulpt, new ProjectionPointImpl()); minx = Math.min(ll.getX(), ul.getX()); // depends on control dependency: [if], data = [none] miny = Math.min(ll.getY(), lr.getY()); // depends on control dependency: [if], data = [none] maxx = Math.max(ur.getX(), lr.getX()); // depends on control dependency: [if], data = [none] maxy = Math.max(ul.getY(), ur.getY()); // depends on control dependency: [if], data = [none] } return new ProjectionRect(minx, miny, maxx, maxy); } }
public class class_name { @SuppressWarnings("deprecation") public static String urlEscape(String s) { try { return URLEncoder.encode(s,"UTF8"); } catch (UnsupportedEncodingException e) { // should be impossible; all JVMs must support UTF8 // but have a fallback just in case return URLEncoder.encode(s); } } }
public class class_name { @SuppressWarnings("deprecation") public static String urlEscape(String s) { try { return URLEncoder.encode(s,"UTF8"); // depends on control dependency: [try], data = [none] } catch (UnsupportedEncodingException e) { // should be impossible; all JVMs must support UTF8 // but have a fallback just in case return URLEncoder.encode(s); } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected Map<Method, Object> getConsoleMethods() { // search for declared command collections final Iterator<OConsoleCommandCollection> ite = ServiceRegistry.lookupProviders(OConsoleCommandCollection.class); final Collection<Object> candidates = new ArrayList<Object>(); candidates.add(this); while (ite.hasNext()) { try { // make a copy and set it's context final OConsoleCommandCollection cc = ite.next().getClass().newInstance(); cc.setContext(this); candidates.add(cc); } catch (InstantiationException ex) { Logger.getLogger(OConsoleApplication.class.getName()).log(Level.WARNING, ex.getMessage()); } catch (IllegalAccessException ex) { Logger.getLogger(OConsoleApplication.class.getName()).log(Level.WARNING, ex.getMessage()); } } final Map<Method, Object> consoleMethods = new TreeMap<Method, Object>(new Comparator<Method>() { public int compare(Method o1, Method o2) { return o1.getName().compareTo(o2.getName()); } }); for (final Object candidate : candidates) { final Method[] methods = candidate.getClass().getMethods(); for (Method m : methods) { if (Modifier.isAbstract(m.getModifiers()) || Modifier.isStatic(m.getModifiers()) || !Modifier.isPublic(m.getModifiers())) { continue; } if (m.getReturnType() != Void.TYPE) { continue; } consoleMethods.put(m, candidate); } } return consoleMethods; } }
public class class_name { protected Map<Method, Object> getConsoleMethods() { // search for declared command collections final Iterator<OConsoleCommandCollection> ite = ServiceRegistry.lookupProviders(OConsoleCommandCollection.class); final Collection<Object> candidates = new ArrayList<Object>(); candidates.add(this); while (ite.hasNext()) { try { // make a copy and set it's context final OConsoleCommandCollection cc = ite.next().getClass().newInstance(); cc.setContext(this); // depends on control dependency: [try], data = [none] candidates.add(cc); // depends on control dependency: [try], data = [none] } catch (InstantiationException ex) { Logger.getLogger(OConsoleApplication.class.getName()).log(Level.WARNING, ex.getMessage()); } catch (IllegalAccessException ex) { // depends on control dependency: [catch], data = [none] Logger.getLogger(OConsoleApplication.class.getName()).log(Level.WARNING, ex.getMessage()); } // depends on control dependency: [catch], data = [none] } final Map<Method, Object> consoleMethods = new TreeMap<Method, Object>(new Comparator<Method>() { public int compare(Method o1, Method o2) { return o1.getName().compareTo(o2.getName()); } }); for (final Object candidate : candidates) { final Method[] methods = candidate.getClass().getMethods(); for (Method m : methods) { if (Modifier.isAbstract(m.getModifiers()) || Modifier.isStatic(m.getModifiers()) || !Modifier.isPublic(m.getModifiers())) { continue; } if (m.getReturnType() != Void.TYPE) { continue; } consoleMethods.put(m, candidate); // depends on control dependency: [for], data = [m] } } return consoleMethods; } }
public class class_name { private void refreshPartitionKeys(boolean topologyUpdate) { long interval = System.currentTimeMillis() - m_lastPartitionKeyFetched.get(); if (!m_useClientAffinity && interval < PARTITION_KEYS_INFO_REFRESH_FREQUENCY) { return; } try { ProcedureInvocation invocation = new ProcedureInvocation(m_sysHandle.getAndDecrement(), "@GetPartitionKeys", "INTEGER"); CountDownLatch latch = null; if (!topologyUpdate) { latch = new CountDownLatch(1); } PartitionUpdateCallback cb = new PartitionUpdateCallback(latch); if (!queue(invocation, cb, true, System.nanoTime(), USE_DEFAULT_CLIENT_TIMEOUT)) { m_partitionUpdateStatus.set(new ClientResponseImpl(ClientResponseImpl.SERVER_UNAVAILABLE, new VoltTable[0], "Fails to queue the partition update query, please try later.")); } if (!topologyUpdate) { latch.await(); } m_lastPartitionKeyFetched.set(System.currentTimeMillis()); } catch (InterruptedException | IOException e) { m_partitionUpdateStatus.set(new ClientResponseImpl(ClientResponseImpl.SERVER_UNAVAILABLE, new VoltTable[0], "Fails to fetch partition keys from server:" + e.getMessage())); } } }
public class class_name { private void refreshPartitionKeys(boolean topologyUpdate) { long interval = System.currentTimeMillis() - m_lastPartitionKeyFetched.get(); if (!m_useClientAffinity && interval < PARTITION_KEYS_INFO_REFRESH_FREQUENCY) { return; // depends on control dependency: [if], data = [none] } try { ProcedureInvocation invocation = new ProcedureInvocation(m_sysHandle.getAndDecrement(), "@GetPartitionKeys", "INTEGER"); CountDownLatch latch = null; if (!topologyUpdate) { latch = new CountDownLatch(1); // depends on control dependency: [if], data = [none] } PartitionUpdateCallback cb = new PartitionUpdateCallback(latch); if (!queue(invocation, cb, true, System.nanoTime(), USE_DEFAULT_CLIENT_TIMEOUT)) { m_partitionUpdateStatus.set(new ClientResponseImpl(ClientResponseImpl.SERVER_UNAVAILABLE, new VoltTable[0], "Fails to queue the partition update query, please try later.")); // depends on control dependency: [if], data = [none] } if (!topologyUpdate) { latch.await(); // depends on control dependency: [if], data = [none] } m_lastPartitionKeyFetched.set(System.currentTimeMillis()); // depends on control dependency: [try], data = [none] } catch (InterruptedException | IOException e) { m_partitionUpdateStatus.set(new ClientResponseImpl(ClientResponseImpl.SERVER_UNAVAILABLE, new VoltTable[0], "Fails to fetch partition keys from server:" + e.getMessage())); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void startAsync() { Thread thread = new Thread(new Runnable() { @Override public void run() { try { start(); } catch (Exception e) { LOG.error("Failed to connect to kubernetes: " + e, e); } } }, "Jenkins X PipelineClient Thread"); thread.start(); } }
public class class_name { public void startAsync() { Thread thread = new Thread(new Runnable() { @Override public void run() { try { start(); // depends on control dependency: [try], data = [none] } catch (Exception e) { LOG.error("Failed to connect to kubernetes: " + e, e); } // depends on control dependency: [catch], data = [none] } }, "Jenkins X PipelineClient Thread"); thread.start(); } }
public class class_name { public static void fireFirstDeclared(Throwable t, Class... declaredTypes) { Throwable cause = t; while (cause != null) { cause = cause.getCause(); if (cause == null) { break; } if (declaredTypes != null) { for (Class declaredType : declaredTypes) { if (declaredType.isInstance(cause)) { fire(cause); } } } if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } if (cause instanceof Error) { throw (Error) cause; } } throw new UndeclaredThrowableException(t); } }
public class class_name { public static void fireFirstDeclared(Throwable t, Class... declaredTypes) { Throwable cause = t; while (cause != null) { cause = cause.getCause(); // depends on control dependency: [while], data = [none] if (cause == null) { break; } if (declaredTypes != null) { for (Class declaredType : declaredTypes) { if (declaredType.isInstance(cause)) { fire(cause); // depends on control dependency: [if], data = [none] } } } if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } if (cause instanceof Error) { throw (Error) cause; } } throw new UndeclaredThrowableException(t); } }
public class class_name { @Override public void perform(final Wave wave) { final JRebirthEvent event = wave.get(EditorWaves.EVENT); LOGGER.trace("Process " + event.eventType() + " of type " + event.target()); final EditorModel editorModel = getModel(EditorModel.class); final BallModel targetBallModel = getModel(BallModel.class, event); editorModel.registerBall(targetBallModel); if (editorModel.retrieveBall(targetBallModel.getEventModel().source()) == null) { // it's the application node, we shall center it !!! minus 70 because it's the globalFacade node that resides in the center targetBallModel.view().node().layoutXProperty().bind(editorModel.view().node().widthProperty().divide(2).subtract(70).subtract(24)); targetBallModel.view().node().layoutYProperty().bind(editorModel.view().node().heightProperty().divide(2).subtract(24)); } else { final BallModel sourceBallModel = editorModel.retrieveBall(targetBallModel.getEventModel().source()); // All other nodes shall be positionned relatively to their parent /* * System.out.println("Create " + targetBallModel.getEventModel().getTarget().getSimpleName() + " From : " + targetBallModel.getEventModel().getSource().getSimpleName() + " x=" + * sourceBallModel.getView().getRootNode().getCenterX() + " trX=" + sourceBallModel.getView().getRootNode().getTranslateX() + " y=" + sourceBallModel.getView().getRootNode().getCenterY() + * " trY=" + sourceBallModel.getView().getRootNode().getTranslateY()); */ targetBallModel.view().node() .layoutXProperty().bind(sourceBallModel.view().node().layoutXProperty().add(sourceBallModel.view().node().translateXProperty())); targetBallModel.view().node() .layoutYProperty().bind(sourceBallModel.view().node().layoutYProperty().add(sourceBallModel.view().node().translateYProperty())); } targetBallModel.show(); } }
public class class_name { @Override public void perform(final Wave wave) { final JRebirthEvent event = wave.get(EditorWaves.EVENT); LOGGER.trace("Process " + event.eventType() + " of type " + event.target()); final EditorModel editorModel = getModel(EditorModel.class); final BallModel targetBallModel = getModel(BallModel.class, event); editorModel.registerBall(targetBallModel); if (editorModel.retrieveBall(targetBallModel.getEventModel().source()) == null) { // it's the application node, we shall center it !!! minus 70 because it's the globalFacade node that resides in the center targetBallModel.view().node().layoutXProperty().bind(editorModel.view().node().widthProperty().divide(2).subtract(70).subtract(24)); // depends on control dependency: [if], data = [none] targetBallModel.view().node().layoutYProperty().bind(editorModel.view().node().heightProperty().divide(2).subtract(24)); // depends on control dependency: [if], data = [none] } else { final BallModel sourceBallModel = editorModel.retrieveBall(targetBallModel.getEventModel().source()); // All other nodes shall be positionned relatively to their parent /* * System.out.println("Create " + targetBallModel.getEventModel().getTarget().getSimpleName() + " From : " + targetBallModel.getEventModel().getSource().getSimpleName() + " x=" + * sourceBallModel.getView().getRootNode().getCenterX() + " trX=" + sourceBallModel.getView().getRootNode().getTranslateX() + " y=" + sourceBallModel.getView().getRootNode().getCenterY() + * " trY=" + sourceBallModel.getView().getRootNode().getTranslateY()); */ targetBallModel.view().node() .layoutXProperty().bind(sourceBallModel.view().node().layoutXProperty().add(sourceBallModel.view().node().translateXProperty())); // depends on control dependency: [if], data = [none] targetBallModel.view().node() .layoutYProperty().bind(sourceBallModel.view().node().layoutYProperty().add(sourceBallModel.view().node().translateYProperty())); // depends on control dependency: [if], data = [none] } targetBallModel.show(); } }
public class class_name { private void process() { if (hasExternsRoot()) { sourceKind = SourceKind.EXTERN; NodeTraversal.traverse(compiler, externsRoot, new BuildGlobalNamespace()); } sourceKind = SourceKind.CODE; NodeTraversal.traverse(compiler, root, new BuildGlobalNamespace()); generated = true; externsScope = null; } }
public class class_name { private void process() { if (hasExternsRoot()) { sourceKind = SourceKind.EXTERN; // depends on control dependency: [if], data = [none] NodeTraversal.traverse(compiler, externsRoot, new BuildGlobalNamespace()); // depends on control dependency: [if], data = [none] } sourceKind = SourceKind.CODE; NodeTraversal.traverse(compiler, root, new BuildGlobalNamespace()); generated = true; externsScope = null; } }
public class class_name { @Override public String format(LogRecord log) { StringBuilder sb = new StringBuilder(); int mark = 0; for (FormatItem item : _formatList) { item.format(sb, log, mark); if (item instanceof PrettyPrintMarkItem) { mark = sb.length(); } } return sb.toString(); } }
public class class_name { @Override public String format(LogRecord log) { StringBuilder sb = new StringBuilder(); int mark = 0; for (FormatItem item : _formatList) { item.format(sb, log, mark); // depends on control dependency: [for], data = [item] if (item instanceof PrettyPrintMarkItem) { mark = sb.length(); // depends on control dependency: [if], data = [none] } } return sb.toString(); } }
public class class_name { @Override protected int writeBytesWireFormat ( byte[] dst, int dstIndex ) { int start = dstIndex; if ( log.isDebugEnabled() ) { log.debug("Opening " + this.name); } SMBUtil.writeInt2(57, dst, dstIndex); dst[ dstIndex + 2 ] = this.securityFlags; dst[ dstIndex + 3 ] = this.requestedOplockLevel; dstIndex += 4; SMBUtil.writeInt4(this.impersonationLevel, dst, dstIndex); dstIndex += 4; SMBUtil.writeInt8(this.smbCreateFlags, dst, dstIndex); dstIndex += 8; dstIndex += 8; // Reserved SMBUtil.writeInt4(this.desiredAccess, dst, dstIndex); dstIndex += 4; SMBUtil.writeInt4(this.fileAttributes, dst, dstIndex); dstIndex += 4; SMBUtil.writeInt4(this.shareAccess, dst, dstIndex); dstIndex += 4; SMBUtil.writeInt4(this.createDisposition, dst, dstIndex); dstIndex += 4; SMBUtil.writeInt4(this.createOptions, dst, dstIndex); dstIndex += 4; int nameOffsetOffset = dstIndex; byte[] nameBytes = this.name.getBytes(StandardCharsets.UTF_16LE); SMBUtil.writeInt2(nameBytes.length, dst, dstIndex + 2); dstIndex += 4; int createContextOffsetOffset = dstIndex; dstIndex += 4; // createContextOffset int createContextLengthOffset = dstIndex; dstIndex += 4; // createContextLength SMBUtil.writeInt2(dstIndex - getHeaderStart(), dst, nameOffsetOffset); System.arraycopy(nameBytes, 0, dst, dstIndex, nameBytes.length); if ( nameBytes.length == 0 ) { // buffer must contain at least one byte dstIndex++; } else { dstIndex += nameBytes.length; } dstIndex += pad8(dstIndex); if ( this.createContexts == null || this.createContexts.length == 0 ) { SMBUtil.writeInt4(0, dst, createContextOffsetOffset); } else { SMBUtil.writeInt4(dstIndex - getHeaderStart(), dst, createContextOffsetOffset); } int totalCreateContextLength = 0; if ( this.createContexts != null ) { int lastStart = -1; for ( CreateContextRequest createContext : this.createContexts ) { int structStart = dstIndex; SMBUtil.writeInt4(0, dst, structStart); // Next if ( lastStart > 0 ) { // set next pointer of previous CREATE_CONTEXT SMBUtil.writeInt4(structStart - dstIndex, dst, lastStart); } dstIndex += 4; byte[] cnBytes = createContext.getName(); int cnOffsetOffset = dstIndex; SMBUtil.writeInt2(cnBytes.length, dst, dstIndex + 2); dstIndex += 4; int dataOffsetOffset = dstIndex + 2; dstIndex += 4; int dataLengthOffset = dstIndex; dstIndex += 4; SMBUtil.writeInt2(dstIndex - structStart, dst, cnOffsetOffset); System.arraycopy(cnBytes, 0, dst, dstIndex, cnBytes.length); dstIndex += cnBytes.length; dstIndex += pad8(dstIndex); SMBUtil.writeInt2(dstIndex - structStart, dst, dataOffsetOffset); int len = createContext.encode(dst, dstIndex); SMBUtil.writeInt4(len, dst, dataLengthOffset); dstIndex += len; int pad = pad8(dstIndex); totalCreateContextLength += len + pad; dstIndex += pad; lastStart = structStart; } } SMBUtil.writeInt4(totalCreateContextLength, dst, createContextLengthOffset); return dstIndex - start; } }
public class class_name { @Override protected int writeBytesWireFormat ( byte[] dst, int dstIndex ) { int start = dstIndex; if ( log.isDebugEnabled() ) { log.debug("Opening " + this.name); // depends on control dependency: [if], data = [none] } SMBUtil.writeInt2(57, dst, dstIndex); dst[ dstIndex + 2 ] = this.securityFlags; dst[ dstIndex + 3 ] = this.requestedOplockLevel; dstIndex += 4; SMBUtil.writeInt4(this.impersonationLevel, dst, dstIndex); dstIndex += 4; SMBUtil.writeInt8(this.smbCreateFlags, dst, dstIndex); dstIndex += 8; dstIndex += 8; // Reserved SMBUtil.writeInt4(this.desiredAccess, dst, dstIndex); dstIndex += 4; SMBUtil.writeInt4(this.fileAttributes, dst, dstIndex); dstIndex += 4; SMBUtil.writeInt4(this.shareAccess, dst, dstIndex); dstIndex += 4; SMBUtil.writeInt4(this.createDisposition, dst, dstIndex); dstIndex += 4; SMBUtil.writeInt4(this.createOptions, dst, dstIndex); dstIndex += 4; int nameOffsetOffset = dstIndex; byte[] nameBytes = this.name.getBytes(StandardCharsets.UTF_16LE); SMBUtil.writeInt2(nameBytes.length, dst, dstIndex + 2); dstIndex += 4; int createContextOffsetOffset = dstIndex; dstIndex += 4; // createContextOffset int createContextLengthOffset = dstIndex; dstIndex += 4; // createContextLength SMBUtil.writeInt2(dstIndex - getHeaderStart(), dst, nameOffsetOffset); System.arraycopy(nameBytes, 0, dst, dstIndex, nameBytes.length); if ( nameBytes.length == 0 ) { // buffer must contain at least one byte dstIndex++; // depends on control dependency: [if], data = [none] } else { dstIndex += nameBytes.length; // depends on control dependency: [if], data = [none] } dstIndex += pad8(dstIndex); if ( this.createContexts == null || this.createContexts.length == 0 ) { SMBUtil.writeInt4(0, dst, createContextOffsetOffset); // depends on control dependency: [if], data = [none] } else { SMBUtil.writeInt4(dstIndex - getHeaderStart(), dst, createContextOffsetOffset); // depends on control dependency: [if], data = [none] } int totalCreateContextLength = 0; if ( this.createContexts != null ) { int lastStart = -1; for ( CreateContextRequest createContext : this.createContexts ) { int structStart = dstIndex; SMBUtil.writeInt4(0, dst, structStart); // Next // depends on control dependency: [for], data = [none] if ( lastStart > 0 ) { // set next pointer of previous CREATE_CONTEXT SMBUtil.writeInt4(structStart - dstIndex, dst, lastStart); // depends on control dependency: [if], data = [none] } dstIndex += 4; // depends on control dependency: [for], data = [none] byte[] cnBytes = createContext.getName(); int cnOffsetOffset = dstIndex; SMBUtil.writeInt2(cnBytes.length, dst, dstIndex + 2); // depends on control dependency: [for], data = [none] dstIndex += 4; // depends on control dependency: [for], data = [none] int dataOffsetOffset = dstIndex + 2; dstIndex += 4; // depends on control dependency: [for], data = [none] int dataLengthOffset = dstIndex; dstIndex += 4; // depends on control dependency: [for], data = [none] SMBUtil.writeInt2(dstIndex - structStart, dst, cnOffsetOffset); // depends on control dependency: [for], data = [none] System.arraycopy(cnBytes, 0, dst, dstIndex, cnBytes.length); // depends on control dependency: [for], data = [none] dstIndex += cnBytes.length; // depends on control dependency: [for], data = [none] dstIndex += pad8(dstIndex); // depends on control dependency: [for], data = [none] SMBUtil.writeInt2(dstIndex - structStart, dst, dataOffsetOffset); // depends on control dependency: [for], data = [none] int len = createContext.encode(dst, dstIndex); SMBUtil.writeInt4(len, dst, dataLengthOffset); // depends on control dependency: [for], data = [none] dstIndex += len; // depends on control dependency: [for], data = [none] int pad = pad8(dstIndex); totalCreateContextLength += len + pad; // depends on control dependency: [for], data = [none] dstIndex += pad; // depends on control dependency: [for], data = [none] lastStart = structStart; // depends on control dependency: [for], data = [none] } } SMBUtil.writeInt4(totalCreateContextLength, dst, createContextLengthOffset); return dstIndex - start; } }
public class class_name { public void createAccumulator(final OnDemandStatsProducer producer, final A annotation, final Method method) { if (producer != null && annotation != null) { final String statsName = (method == null) ? OnDemandStatsProducer.CUMULATED_STATS_NAME : method.getName(); String accumulatorName = getName(annotation); if (StringUtils.isEmpty(accumulatorName)) accumulatorName = method == null ? formAccumulatorNameForClass(producer, annotation) : formAccumulatorNameForMethod(producer, annotation, method); createAccumulator( producer.getProducerId(), annotation, accumulatorName, statsName ); } } }
public class class_name { public void createAccumulator(final OnDemandStatsProducer producer, final A annotation, final Method method) { if (producer != null && annotation != null) { final String statsName = (method == null) ? OnDemandStatsProducer.CUMULATED_STATS_NAME : method.getName(); String accumulatorName = getName(annotation); if (StringUtils.isEmpty(accumulatorName)) accumulatorName = method == null ? formAccumulatorNameForClass(producer, annotation) : formAccumulatorNameForMethod(producer, annotation, method); createAccumulator( producer.getProducerId(), annotation, accumulatorName, statsName ); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void marshall(DescribeAggregationAuthorizationsRequest describeAggregationAuthorizationsRequest, ProtocolMarshaller protocolMarshaller) { if (describeAggregationAuthorizationsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeAggregationAuthorizationsRequest.getLimit(), LIMIT_BINDING); protocolMarshaller.marshall(describeAggregationAuthorizationsRequest.getNextToken(), NEXTTOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DescribeAggregationAuthorizationsRequest describeAggregationAuthorizationsRequest, ProtocolMarshaller protocolMarshaller) { if (describeAggregationAuthorizationsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeAggregationAuthorizationsRequest.getLimit(), LIMIT_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(describeAggregationAuthorizationsRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static void validateKeysInDataFile(List<String> keysToValidate, String dataFileName, TestPlatform currentPlatform) { for (String currentKey : keysToValidate) { // For case: Invalid element inside a container, the key inside a container is split using delimiter. // It will be assigned to the currentKey to proceed with the validation. if (currentKey.contains(DELIMITER)) { String[] keyInContainer = currentKey.split(DELIMITER); // assigning the key to the current key to proceed with the validation currentKey = keyInContainer[1]; } if (!validForWebPlatform(currentPlatform, currentKey) || !validForMobilePlatforms(currentPlatform, currentKey)) { throw new IllegalArgumentException(String.format( "Detected an invalid key [%s] in data file %s for Platform %s", currentKey, dataFileName, currentPlatform.getPlatformName())); } } } }
public class class_name { public static void validateKeysInDataFile(List<String> keysToValidate, String dataFileName, TestPlatform currentPlatform) { for (String currentKey : keysToValidate) { // For case: Invalid element inside a container, the key inside a container is split using delimiter. // It will be assigned to the currentKey to proceed with the validation. if (currentKey.contains(DELIMITER)) { String[] keyInContainer = currentKey.split(DELIMITER); // assigning the key to the current key to proceed with the validation currentKey = keyInContainer[1]; // depends on control dependency: [if], data = [none] } if (!validForWebPlatform(currentPlatform, currentKey) || !validForMobilePlatforms(currentPlatform, currentKey)) { throw new IllegalArgumentException(String.format( "Detected an invalid key [%s] in data file %s for Platform %s", currentKey, dataFileName, currentPlatform.getPlatformName())); } } } }
public class class_name { public void open() { if (log.isTraceEnabled()) { // dump memory stats log.trace("Memory at open - free: {}K total: {}K", Runtime.getRuntime().freeMemory() / 1024, Runtime.getRuntime().totalMemory() / 1024); } } }
public class class_name { public void open() { if (log.isTraceEnabled()) { // dump memory stats log.trace("Memory at open - free: {}K total: {}K", Runtime.getRuntime().freeMemory() / 1024, Runtime.getRuntime().totalMemory() / 1024); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String getDescriptiveName( IDevice device ) { // if any of this logic changes update javadoc for // AbstractInstrumentationMojo#testCreateReport StringBuilder identfier = new StringBuilder().append( device.getSerialNumber() ); if ( device.getAvdName() != null ) { identfier.append( SEPARATOR ).append( device.getAvdName() ); } String manufacturer = getManufacturer( device ); if ( StringUtils.isNotBlank( manufacturer ) ) { identfier.append( SEPARATOR ).append( manufacturer ); } String model = getModel( device ); if ( StringUtils.isNotBlank( model ) ) { identfier.append( SEPARATOR ).append( model ); } return FileNameHelper.fixFileName( identfier.toString() ); } }
public class class_name { public static String getDescriptiveName( IDevice device ) { // if any of this logic changes update javadoc for // AbstractInstrumentationMojo#testCreateReport StringBuilder identfier = new StringBuilder().append( device.getSerialNumber() ); if ( device.getAvdName() != null ) { identfier.append( SEPARATOR ).append( device.getAvdName() ); // depends on control dependency: [if], data = [( device.getAvdName()] } String manufacturer = getManufacturer( device ); if ( StringUtils.isNotBlank( manufacturer ) ) { identfier.append( SEPARATOR ).append( manufacturer ); // depends on control dependency: [if], data = [none] } String model = getModel( device ); if ( StringUtils.isNotBlank( model ) ) { identfier.append( SEPARATOR ).append( model ); // depends on control dependency: [if], data = [none] } return FileNameHelper.fixFileName( identfier.toString() ); } }
public class class_name { protected boolean i_recordScannedClassName(String i_className) { boolean didPlaceClass = annotationTargets.i_placeClass(i_getClassSourceName(), i_className); if (!didPlaceClass) { return false; } boolean didAddClass = annotationTargets.i_addScannedClassName(i_className, getScanPolicy()); return didAddClass; } }
public class class_name { protected boolean i_recordScannedClassName(String i_className) { boolean didPlaceClass = annotationTargets.i_placeClass(i_getClassSourceName(), i_className); if (!didPlaceClass) { return false; // depends on control dependency: [if], data = [none] } boolean didAddClass = annotationTargets.i_addScannedClassName(i_className, getScanPolicy()); return didAddClass; } }
public class class_name { private InputStream httpCopyFromStream(String url, String post) { HttpPost httpPost = new HttpPost(url); if (post != null) { StringEntity entity = new StringEntity(post, Consts.UTF_8); httpPost.setEntity(entity); } try (CloseableHttpResponse response = httpClient.execute(httpPost)) { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { EntityUtils.consume(entity); throw new WxRuntimeException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } else { InputStream inputStream = entity.getContent(); byte[] binaryContent = IOUtils.toByteArray(inputStream); String content = new String(binaryContent, "UTF-8"); if (content.contains("errcode")) { WxError wxError = WxError.fromJson(content); throw new WxRuntimeException(wxError); } else { return new ByteArrayInputStream(binaryContent); } } } catch (IOException e) { logger.error("http download: {} failed.", url, e); throw new WxRuntimeException(999, e.getMessage()); } } }
public class class_name { private InputStream httpCopyFromStream(String url, String post) { HttpPost httpPost = new HttpPost(url); if (post != null) { StringEntity entity = new StringEntity(post, Consts.UTF_8); httpPost.setEntity(entity); // depends on control dependency: [if], data = [none] } try (CloseableHttpResponse response = httpClient.execute(httpPost)) { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { EntityUtils.consume(entity); // depends on control dependency: [if], data = [none] throw new WxRuntimeException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } else { InputStream inputStream = entity.getContent(); byte[] binaryContent = IOUtils.toByteArray(inputStream); String content = new String(binaryContent, "UTF-8"); if (content.contains("errcode")) { WxError wxError = WxError.fromJson(content); throw new WxRuntimeException(wxError); } else { return new ByteArrayInputStream(binaryContent); // depends on control dependency: [if], data = [none] } } } catch (IOException e) { logger.error("http download: {} failed.", url, e); throw new WxRuntimeException(999, e.getMessage()); } } }
public class class_name { public ArrayList<String> getColumns() { ArrayList<String> columns = new ArrayList<String>(); for (String col : columnLookup.keySet()) { HeaderInfo hi = columnLookup.get(col); if (!hi.isHide()) { columns.add(col); } } return columns; } }
public class class_name { public ArrayList<String> getColumns() { ArrayList<String> columns = new ArrayList<String>(); for (String col : columnLookup.keySet()) { HeaderInfo hi = columnLookup.get(col); if (!hi.isHide()) { columns.add(col); // depends on control dependency: [if], data = [none] } } return columns; } }
public class class_name { private String[] getStringArray(final List<CharSequence> charSeqList) { final int length = charSeqList.size(); final String[] stringArray = new String[length]; for (int i = 0; i < length; i++) { stringArray[i] = getString(charSeqList.get(i)); } return stringArray; } }
public class class_name { private String[] getStringArray(final List<CharSequence> charSeqList) { final int length = charSeqList.size(); final String[] stringArray = new String[length]; for (int i = 0; i < length; i++) { stringArray[i] = getString(charSeqList.get(i)); // depends on control dependency: [for], data = [i] } return stringArray; } }
public class class_name { @SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity", "checkstyle:nestedifdepth"}) protected void checkSuperConstructor( XtendTypeDeclaration container, EStructuralFeature feature, Collection<ActionParameterTypes> defaultSignatures) { final JvmDeclaredType jvmElement = this.associations.getInferredType(container); if (jvmElement != null) { final Map<ActionParameterTypes, JvmConstructor> superConstructors = CollectionLiterals.newTreeMap((Comparator<ActionParameterTypes>) null); final JvmTypeReference typeRef = jvmElement.getExtendedClass(); final JvmType supertype = (typeRef == null) ? null : typeRef.getType(); if (supertype instanceof JvmGenericType) { final JvmGenericType jvmSuperElement = (JvmGenericType) supertype; for (final JvmConstructor superConstructor : jvmSuperElement.getDeclaredConstructors()) { final ActionParameterTypes sig = this.sarlActionSignatures.createParameterTypesFromJvmModel( superConstructor.isVarArgs(), superConstructor.getParameters()); superConstructors.put(sig, superConstructor); } } final ActionParameterTypes voidKey = this.sarlActionSignatures.createParameterTypesForVoid(); //boolean hasDeclaredConstructor = false; for (final XtendMember member : container.getMembers()) { if (member instanceof SarlConstructor) { final SarlConstructor constructor = (SarlConstructor) member; //hasDeclaredConstructor = true; boolean invokeDefaultConstructor = true; final XExpression body = constructor.getExpression(); if (body instanceof XBlockExpression) { final XBlockExpression block = (XBlockExpression) body; if (!block.getExpressions().isEmpty()) { final XExpression firstStatement = block.getExpressions().get(0); if (firstStatement instanceof XConstructorCall || isDelegateConstructorCall(firstStatement)) { invokeDefaultConstructor = false; } } } else if (body instanceof XConstructorCall || isDelegateConstructorCall(body)) { invokeDefaultConstructor = false; } if (invokeDefaultConstructor && !superConstructors.containsKey(voidKey)) { final List<String> issueData = new ArrayList<>(); for (final ActionParameterTypes defaultSignature : defaultSignatures) { issueData.add(defaultSignature.toString()); } error(Messages.SARLValidator_33, member, null, ValidationMessageAcceptor.INSIGNIFICANT_INDEX, MUST_INVOKE_SUPER_CONSTRUCTOR, toArray(issueData, String.class)); } } } // The following code is no more needed because of the constructor inheritance mechanism which // is implemented into the JVM model inferrer. /*if (!hasDeclaredConstructor) { for (final ActionParameterTypes defaultSignature : defaultSignatures) { if (!superConstructors.containsKey(defaultSignature)) { final List<String> issueData = new ArrayList<>(); for (final JvmConstructor superConstructor : superConstructors.values()) { issueData.add(EcoreUtil.getURI(superConstructor).toString()); issueData.add(doGetReadableSignature(container.getName(), superConstructor.getParameters())); } error(Messages.SARLValidator_33, container, feature, MISSING_CONSTRUCTOR, toArray(issueData, String.class)); } } }*/ } } }
public class class_name { @SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity", "checkstyle:nestedifdepth"}) protected void checkSuperConstructor( XtendTypeDeclaration container, EStructuralFeature feature, Collection<ActionParameterTypes> defaultSignatures) { final JvmDeclaredType jvmElement = this.associations.getInferredType(container); if (jvmElement != null) { final Map<ActionParameterTypes, JvmConstructor> superConstructors = CollectionLiterals.newTreeMap((Comparator<ActionParameterTypes>) null); final JvmTypeReference typeRef = jvmElement.getExtendedClass(); final JvmType supertype = (typeRef == null) ? null : typeRef.getType(); if (supertype instanceof JvmGenericType) { final JvmGenericType jvmSuperElement = (JvmGenericType) supertype; for (final JvmConstructor superConstructor : jvmSuperElement.getDeclaredConstructors()) { final ActionParameterTypes sig = this.sarlActionSignatures.createParameterTypesFromJvmModel( superConstructor.isVarArgs(), superConstructor.getParameters()); superConstructors.put(sig, superConstructor); // depends on control dependency: [for], data = [superConstructor] } } final ActionParameterTypes voidKey = this.sarlActionSignatures.createParameterTypesForVoid(); //boolean hasDeclaredConstructor = false; for (final XtendMember member : container.getMembers()) { if (member instanceof SarlConstructor) { final SarlConstructor constructor = (SarlConstructor) member; //hasDeclaredConstructor = true; boolean invokeDefaultConstructor = true; final XExpression body = constructor.getExpression(); if (body instanceof XBlockExpression) { final XBlockExpression block = (XBlockExpression) body; if (!block.getExpressions().isEmpty()) { final XExpression firstStatement = block.getExpressions().get(0); if (firstStatement instanceof XConstructorCall || isDelegateConstructorCall(firstStatement)) { invokeDefaultConstructor = false; // depends on control dependency: [if], data = [none] } } } else if (body instanceof XConstructorCall || isDelegateConstructorCall(body)) { invokeDefaultConstructor = false; // depends on control dependency: [if], data = [none] } if (invokeDefaultConstructor && !superConstructors.containsKey(voidKey)) { final List<String> issueData = new ArrayList<>(); for (final ActionParameterTypes defaultSignature : defaultSignatures) { issueData.add(defaultSignature.toString()); // depends on control dependency: [for], data = [defaultSignature] } error(Messages.SARLValidator_33, member, null, ValidationMessageAcceptor.INSIGNIFICANT_INDEX, MUST_INVOKE_SUPER_CONSTRUCTOR, toArray(issueData, String.class)); // depends on control dependency: [if], data = [none] } } } // The following code is no more needed because of the constructor inheritance mechanism which // is implemented into the JVM model inferrer. /*if (!hasDeclaredConstructor) { for (final ActionParameterTypes defaultSignature : defaultSignatures) { if (!superConstructors.containsKey(defaultSignature)) { final List<String> issueData = new ArrayList<>(); for (final JvmConstructor superConstructor : superConstructors.values()) { issueData.add(EcoreUtil.getURI(superConstructor).toString()); issueData.add(doGetReadableSignature(container.getName(), superConstructor.getParameters())); } error(Messages.SARLValidator_33, container, feature, MISSING_CONSTRUCTOR, toArray(issueData, String.class)); } } }*/ } } }
public class class_name { @Override public CommerceShipmentItem fetchByCommerceShipment_Last( long commerceShipmentId, OrderByComparator<CommerceShipmentItem> orderByComparator) { int count = countByCommerceShipment(commerceShipmentId); if (count == 0) { return null; } List<CommerceShipmentItem> list = findByCommerceShipment(commerceShipmentId, count - 1, count, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; } }
public class class_name { @Override public CommerceShipmentItem fetchByCommerceShipment_Last( long commerceShipmentId, OrderByComparator<CommerceShipmentItem> orderByComparator) { int count = countByCommerceShipment(commerceShipmentId); if (count == 0) { return null; // depends on control dependency: [if], data = [none] } List<CommerceShipmentItem> list = findByCommerceShipment(commerceShipmentId, count - 1, count, orderByComparator); if (!list.isEmpty()) { return list.get(0); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { protected boolean shouldReuseId(HttpServletRequest _request, SessionAffinityContext sac) { boolean reuseId = sac.isResponseIdSet() || sac.isRequestedSessionIDFromSSL(); if (!reuseId) { if (_smc.getEnableUrlRewriting()) { boolean useCookies = _smc.getEnableCookies() && _request.getHeader("Cookie") != null; if (!useCookies) { // Either the server doesn't support cookies, or we didn't get // any cookies from the client, so we have to assume url-rewriting. // Note that the client may indeed support cookies but we have no // way to know for sure. Object objSacHashtable = ((IExtendedRequest) _request).getSessionAffinityContext(); Hashtable sacHashtable = (Hashtable) objSacHashtable; if (sacHashtable.size() > 1) { // multiple sacs on request -- can only happen if one or more apps // in dispatch // chain support cookies. Enumeration sacEnum = sacHashtable.elements(); SessionAffinityContext otherSac; String otherResponseId; // look through sacs and take the first response id we find while (sacEnum.hasMoreElements()) { otherSac = (SessionAffinityContext) sacEnum.nextElement(); otherResponseId = otherSac.getResponseSessionID(); if (otherResponseId != null) { sac.setResponseSessionID(otherResponseId); reuseId = true; break; } } } } } } // We must check SessionManagerConfig.isIdReuse() at the end to ensure the // response id is // properly set in the current sac. return (reuseId || SessionManagerConfig.isIdReuse()); } }
public class class_name { protected boolean shouldReuseId(HttpServletRequest _request, SessionAffinityContext sac) { boolean reuseId = sac.isResponseIdSet() || sac.isRequestedSessionIDFromSSL(); if (!reuseId) { if (_smc.getEnableUrlRewriting()) { boolean useCookies = _smc.getEnableCookies() && _request.getHeader("Cookie") != null; if (!useCookies) { // Either the server doesn't support cookies, or we didn't get // any cookies from the client, so we have to assume url-rewriting. // Note that the client may indeed support cookies but we have no // way to know for sure. Object objSacHashtable = ((IExtendedRequest) _request).getSessionAffinityContext(); Hashtable sacHashtable = (Hashtable) objSacHashtable; if (sacHashtable.size() > 1) { // multiple sacs on request -- can only happen if one or more apps // in dispatch // chain support cookies. Enumeration sacEnum = sacHashtable.elements(); SessionAffinityContext otherSac; String otherResponseId; // look through sacs and take the first response id we find while (sacEnum.hasMoreElements()) { otherSac = (SessionAffinityContext) sacEnum.nextElement(); // depends on control dependency: [while], data = [none] otherResponseId = otherSac.getResponseSessionID(); // depends on control dependency: [while], data = [none] if (otherResponseId != null) { sac.setResponseSessionID(otherResponseId); // depends on control dependency: [if], data = [(otherResponseId] reuseId = true; // depends on control dependency: [if], data = [none] break; } } } } } } // We must check SessionManagerConfig.isIdReuse() at the end to ensure the // response id is // properly set in the current sac. return (reuseId || SessionManagerConfig.isIdReuse()); } }