code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { ByteVector put12(final int b, final int s) { int length = this.length; if (length + 3 > data.length) { enlarge(3); } byte[] data = this.data; data[length++] = (byte) b; data[length++] = (byte) (s >>> 8); data[length++] = (byte) s; this.length = length; return this; } }
public class class_name { ByteVector put12(final int b, final int s) { int length = this.length; if (length + 3 > data.length) { enlarge(3); // depends on control dependency: [if], data = [none] } byte[] data = this.data; data[length++] = (byte) b; data[length++] = (byte) (s >>> 8); data[length++] = (byte) s; this.length = length; return this; } }
public class class_name { @Deprecated public ArrayList<ItemHistory> getAllItemHistory( EpcFormat epcFormat, String epcPrefix, String jobId, String fromZone, String toZone, String fromFacility, String toFacility, PresenceConfidence presenceConfidence, String facility, String pageMarker) { ItemHistoryResponse response; String nextPageMarker = ""; int pageSize = 1000; ArrayList<ItemHistory> items = new ArrayList<>(); do { response = this.getItemHistory( epcFormat, epcPrefix, jobId, fromZone, toZone, fromFacility, toFacility, presenceConfidence, facility, pageSize, nextPageMarker); if (response.getHistory() != null) { Collections.addAll(items, response.getHistory()); } nextPageMarker = response.getNextPageMarker(); } while (nextPageMarker != null && !nextPageMarker.isEmpty()); return items; } }
public class class_name { @Deprecated public ArrayList<ItemHistory> getAllItemHistory( EpcFormat epcFormat, String epcPrefix, String jobId, String fromZone, String toZone, String fromFacility, String toFacility, PresenceConfidence presenceConfidence, String facility, String pageMarker) { ItemHistoryResponse response; String nextPageMarker = ""; int pageSize = 1000; ArrayList<ItemHistory> items = new ArrayList<>(); do { response = this.getItemHistory( epcFormat, epcPrefix, jobId, fromZone, toZone, fromFacility, toFacility, presenceConfidence, facility, pageSize, nextPageMarker); if (response.getHistory() != null) { Collections.addAll(items, response.getHistory()); // depends on control dependency: [if], data = [none] } nextPageMarker = response.getNextPageMarker(); } while (nextPageMarker != null && !nextPageMarker.isEmpty()); return items; } }
public class class_name { public static String toHexString(byte[] b) { if (b == null) return null; StringBuilder sb = new StringBuilder(b.length * 2); for (int i = 0; i < b.length; i++) { int v = b[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { sb.append(0); } sb.append(hv); } return sb.toString(); } }
public class class_name { public static String toHexString(byte[] b) { if (b == null) return null; StringBuilder sb = new StringBuilder(b.length * 2); for (int i = 0; i < b.length; i++) { int v = b[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { sb.append(0); // depends on control dependency: [if], data = [none] } sb.append(hv); // depends on control dependency: [for], data = [none] } return sb.toString(); } }
public class class_name { public EClass getBOG() { if (bogEClass == null) { bogEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(215); } return bogEClass; } }
public class class_name { public EClass getBOG() { if (bogEClass == null) { bogEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(215); // depends on control dependency: [if], data = [none] } return bogEClass; } }
public class class_name { @Override public FacesConfig getMetaInfServicesFacesConfig(ExternalContext ectx) { try { org.apache.myfaces.config.impl.digester.elements.FacesConfigImpl facesConfig = new org.apache.myfaces.config.impl.digester.elements.FacesConfigImpl(); org.apache.myfaces.config.impl.digester.elements.FactoryImpl factory = new org.apache.myfaces.config.impl.digester.elements.FactoryImpl(); facesConfig.addFactory(factory); for (String factoryName : FACTORY_NAMES) { List<String> classList = ServiceProviderFinderFactory.getServiceProviderFinder(ectx) .getServiceProviderList(factoryName); for (String className : classList) { if (log.isLoggable(Level.INFO)) { log.info("Found " + factoryName + " factory implementation: " + className); } if (factoryName.equals(FactoryFinder.APPLICATION_FACTORY)) { factory.addApplicationFactory(className); } else if(factoryName.equals(FactoryFinder.EXCEPTION_HANDLER_FACTORY)) { factory.addExceptionHandlerFactory(className); } else if (factoryName.equals(FactoryFinder.EXTERNAL_CONTEXT_FACTORY)) { factory.addExternalContextFactory(className); } else if (factoryName.equals(FactoryFinder.FACES_CONTEXT_FACTORY)) { factory.addFacesContextFactory(className); } else if (factoryName.equals(FactoryFinder.LIFECYCLE_FACTORY)) { factory.addLifecycleFactory(className); } else if (factoryName.equals(FactoryFinder.RENDER_KIT_FACTORY)) { factory.addRenderkitFactory(className); } else if(factoryName.equals(FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY)) { factory.addTagHandlerDelegateFactory(className); } else if (factoryName.equals(FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY)) { factory.addPartialViewContextFactory(className); } else if(factoryName.equals(FactoryFinder.VISIT_CONTEXT_FACTORY)) { factory.addVisitContextFactory(className); } else if(factoryName.equals(FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY)) { factory.addViewDeclarationLanguageFactory(className); } else if(factoryName.equals(FactoryFinder.FLASH_FACTORY)) { factory.addFlashFactory(className); } else if(factoryName.equals(FactoryFinder.FLOW_HANDLER_FACTORY)) { factory.addFlowHandlerFactory(className); } else if(factoryName.equals(FactoryFinder.CLIENT_WINDOW_FACTORY)) { factory.addClientWindowFactory(className); } else if(factoryName.equals(FactoryFinder.FACELET_CACHE_FACTORY)) { factory.addFaceletCacheFactory(className); } else { throw new IllegalStateException("Unexpected factory name " + factoryName); } } } return facesConfig; } catch (Throwable e) { throw new FacesException(e); } } }
public class class_name { @Override public FacesConfig getMetaInfServicesFacesConfig(ExternalContext ectx) { try { org.apache.myfaces.config.impl.digester.elements.FacesConfigImpl facesConfig = new org.apache.myfaces.config.impl.digester.elements.FacesConfigImpl(); org.apache.myfaces.config.impl.digester.elements.FactoryImpl factory = new org.apache.myfaces.config.impl.digester.elements.FactoryImpl(); facesConfig.addFactory(factory); // depends on control dependency: [try], data = [none] for (String factoryName : FACTORY_NAMES) { List<String> classList = ServiceProviderFinderFactory.getServiceProviderFinder(ectx) .getServiceProviderList(factoryName); for (String className : classList) { if (log.isLoggable(Level.INFO)) { log.info("Found " + factoryName + " factory implementation: " + className); // depends on control dependency: [if], data = [none] } if (factoryName.equals(FactoryFinder.APPLICATION_FACTORY)) { factory.addApplicationFactory(className); // depends on control dependency: [if], data = [none] } else if(factoryName.equals(FactoryFinder.EXCEPTION_HANDLER_FACTORY)) { factory.addExceptionHandlerFactory(className); // depends on control dependency: [if], data = [none] } else if (factoryName.equals(FactoryFinder.EXTERNAL_CONTEXT_FACTORY)) { factory.addExternalContextFactory(className); // depends on control dependency: [if], data = [none] } else if (factoryName.equals(FactoryFinder.FACES_CONTEXT_FACTORY)) { factory.addFacesContextFactory(className); // depends on control dependency: [if], data = [none] } else if (factoryName.equals(FactoryFinder.LIFECYCLE_FACTORY)) { factory.addLifecycleFactory(className); // depends on control dependency: [if], data = [none] } else if (factoryName.equals(FactoryFinder.RENDER_KIT_FACTORY)) { factory.addRenderkitFactory(className); // depends on control dependency: [if], data = [none] } else if(factoryName.equals(FactoryFinder.TAG_HANDLER_DELEGATE_FACTORY)) { factory.addTagHandlerDelegateFactory(className); // depends on control dependency: [if], data = [none] } else if (factoryName.equals(FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY)) { factory.addPartialViewContextFactory(className); // depends on control dependency: [if], data = [none] } else if(factoryName.equals(FactoryFinder.VISIT_CONTEXT_FACTORY)) { factory.addVisitContextFactory(className); // depends on control dependency: [if], data = [none] } else if(factoryName.equals(FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY)) { factory.addViewDeclarationLanguageFactory(className); // depends on control dependency: [if], data = [none] } else if(factoryName.equals(FactoryFinder.FLASH_FACTORY)) { factory.addFlashFactory(className); // depends on control dependency: [if], data = [none] } else if(factoryName.equals(FactoryFinder.FLOW_HANDLER_FACTORY)) { factory.addFlowHandlerFactory(className); // depends on control dependency: [if], data = [none] } else if(factoryName.equals(FactoryFinder.CLIENT_WINDOW_FACTORY)) { factory.addClientWindowFactory(className); // depends on control dependency: [if], data = [none] } else if(factoryName.equals(FactoryFinder.FACELET_CACHE_FACTORY)) { factory.addFaceletCacheFactory(className); // depends on control dependency: [if], data = [none] } else { throw new IllegalStateException("Unexpected factory name " + factoryName); } } } return facesConfig; // depends on control dependency: [try], data = [none] } catch (Throwable e) { throw new FacesException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public Double hincrByFloat(Object key, Object field, double value) { Jedis jedis = getJedis(); try { return jedis.hincrByFloat(keyToBytes(key), fieldToBytes(field), value); } finally {close(jedis);} } }
public class class_name { public Double hincrByFloat(Object key, Object field, double value) { Jedis jedis = getJedis(); try { return jedis.hincrByFloat(keyToBytes(key), fieldToBytes(field), value); // depends on control dependency: [try], data = [none] } finally {close(jedis);} } }
public class class_name { public static Reader createReader(InputStream inputStream,String encoding) { //get encoding String updatedEncoding=IOHelper.getEncodingToUse(encoding); //create reader Reader reader=null; try { reader=new InputStreamReader(inputStream,updatedEncoding); } catch(UnsupportedEncodingException exception) { throw new FaxException("Unable to create reader, unsupported encoding: "+encoding,exception); } return reader; } }
public class class_name { public static Reader createReader(InputStream inputStream,String encoding) { //get encoding String updatedEncoding=IOHelper.getEncodingToUse(encoding); //create reader Reader reader=null; try { reader=new InputStreamReader(inputStream,updatedEncoding); // depends on control dependency: [try], data = [none] } catch(UnsupportedEncodingException exception) { throw new FaxException("Unable to create reader, unsupported encoding: "+encoding,exception); } // depends on control dependency: [catch], data = [none] return reader; } }
public class class_name { protected void zSetData(MithraDataObject data) { this.currentData = data; this.persistenceState = PersistenceState.PERSISTED; MithraTransaction currentTransaction = MithraManagerProvider.getMithraManager().getCurrentTransaction(); if (currentTransaction != null && zGetPortal().getTxParticipationMode(currentTransaction).mustParticipateInTxOnRead()) { this.transactionalState = currentTransaction.getReadLockedTransactionalState(null, PersistenceState.PERSISTED); } } }
public class class_name { protected void zSetData(MithraDataObject data) { this.currentData = data; this.persistenceState = PersistenceState.PERSISTED; MithraTransaction currentTransaction = MithraManagerProvider.getMithraManager().getCurrentTransaction(); if (currentTransaction != null && zGetPortal().getTxParticipationMode(currentTransaction).mustParticipateInTxOnRead()) { this.transactionalState = currentTransaction.getReadLockedTransactionalState(null, PersistenceState.PERSISTED); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Restricted(NoExternalUse.class) public static void skip(@Nonnull Iterator<?> iterator, int count) { if (count < 0) { throw new IllegalArgumentException(); } while (iterator.hasNext() && count-- > 0) { iterator.next(); } } }
public class class_name { @Restricted(NoExternalUse.class) public static void skip(@Nonnull Iterator<?> iterator, int count) { if (count < 0) { throw new IllegalArgumentException(); } while (iterator.hasNext() && count-- > 0) { iterator.next(); // depends on control dependency: [while], data = [none] } } }
public class class_name { public void addRotation(int axis1, int axis2, double angle) { if(trans == null) { trans = new AffineTransformation(dim); } trans.addRotation(axis1, axis2, angle); } }
public class class_name { public void addRotation(int axis1, int axis2, double angle) { if(trans == null) { trans = new AffineTransformation(dim); // depends on control dependency: [if], data = [none] } trans.addRotation(axis1, axis2, angle); } }
public class class_name { public synchronized FilteredBlock applyAndUpdate(Block block) { List<Transaction> txns = block.getTransactions(); List<Sha256Hash> txHashes = new ArrayList<>(txns.size()); List<Transaction> matched = Lists.newArrayList(); byte[] bits = new byte[(int) Math.ceil(txns.size() / 8.0)]; for (int i = 0; i < txns.size(); i++) { Transaction tx = txns.get(i); txHashes.add(tx.getTxId()); if (applyAndUpdate(tx)) { Utils.setBitLE(bits, i); matched.add(tx); } } PartialMerkleTree pmt = PartialMerkleTree.buildFromLeaves(block.getParams(), bits, txHashes); FilteredBlock filteredBlock = new FilteredBlock(block.getParams(), block.cloneAsHeader(), pmt); for (Transaction transaction : matched) filteredBlock.provideTransaction(transaction); return filteredBlock; } }
public class class_name { public synchronized FilteredBlock applyAndUpdate(Block block) { List<Transaction> txns = block.getTransactions(); List<Sha256Hash> txHashes = new ArrayList<>(txns.size()); List<Transaction> matched = Lists.newArrayList(); byte[] bits = new byte[(int) Math.ceil(txns.size() / 8.0)]; for (int i = 0; i < txns.size(); i++) { Transaction tx = txns.get(i); txHashes.add(tx.getTxId()); // depends on control dependency: [for], data = [none] if (applyAndUpdate(tx)) { Utils.setBitLE(bits, i); // depends on control dependency: [if], data = [none] matched.add(tx); // depends on control dependency: [if], data = [none] } } PartialMerkleTree pmt = PartialMerkleTree.buildFromLeaves(block.getParams(), bits, txHashes); FilteredBlock filteredBlock = new FilteredBlock(block.getParams(), block.cloneAsHeader(), pmt); for (Transaction transaction : matched) filteredBlock.provideTransaction(transaction); return filteredBlock; } }
public class class_name { public void setEnable7Zip(final boolean enable7Zip) { this.enable7Zip = enable7Zip; if (!this.enable7Zip) { if (outputCompression == OutputCompressionEnum.SevenZip) { outputCompression = OutputCompressionEnum.None; } } } }
public class class_name { public void setEnable7Zip(final boolean enable7Zip) { this.enable7Zip = enable7Zip; if (!this.enable7Zip) { if (outputCompression == OutputCompressionEnum.SevenZip) { outputCompression = OutputCompressionEnum.None; // depends on control dependency: [if], data = [none] } } } }
public class class_name { private int validateFiles() { List<ValidationPlanResult> planResults = new ArrayList<ValidationPlanResult>(); int parseErrorCount = 0; try { long timeIn = System.currentTimeMillis(); if (filterMode && filterPrefix != null) { goodFilesWriter = new PrintWriter(filterPrefix + "_good.txt","UTF-8"); badFilesWriter = new PrintWriter(filterPrefix + "_bad.txt","UTF-8"); } for (File file : entryFiles) { List<ValidationPlanResult> results = validateFile( file,errorWriter); planResults.addAll(results); } infoWriter.flush(); errorWriter.flush(); reportWriter.flush(); fixWriter.flush(); infoWriter.close(); errorWriter.close(); reportWriter.close(); fixWriter.close(); if (filterMode && filterPrefix != null) { badFilesWriter.flush(); badFilesWriter.close(); goodFilesWriter.flush(); goodFilesWriter.close(); } List<ValidationMessage<Origin>> messages = new ArrayList<ValidationMessage<Origin>>(); for (ValidationPlanResult planResult : planResults) { messages.addAll(planResult.getMessages()); } for (ValidationResult parseResult : parseResults) { messages.addAll(parseResult.getMessages()); for (ValidationMessage message : parseResult.getMessages()) { parseErrorCount++; } } /** * will be built up to form the summary for the whole run */ String summaryLine = ""; if (!planResults.isEmpty()) { FlattenedMessageResult results = Utils.flattenMessages(messages,MESSAGE_FLATTEN_THRESHOLD); List<ValidationMessage> flattenedMessages = results.getFlattenedMessages(); List<ValidationMessage> unFlattenedMessages = results.getUnFlattenedMessages(); Collections.sort( flattenedMessages,new ValidationMessageComparator()); Collections.sort( unFlattenedMessages,new ValidationMessageComparator()); if (!flattenedMessages.isEmpty()) { summaryLine = summaryLine.concat("\n\n***MESSAGES SUMMARY***"); summaryLine = summaryLine.concat("\nCompressed messages (occurring more than "+ MESSAGE_FLATTEN_THRESHOLD + " times)"); for (ValidationMessage message : flattenedMessages) { summaryLine = summaryLine.concat("\n"+ message.getSeverity()); summaryLine = summaryLine.concat(": "); summaryLine = summaryLine.concat(message.getMessage()); summaryLine = summaryLine.concat(" ("+ message.getMessageKey() + ") "); } } if (!unFlattenedMessages.isEmpty()) { summaryLine = summaryLine.concat("\n\nMessages"); for (ValidationMessage message : unFlattenedMessages) { summaryLine = summaryLine.concat("\n"+ message.getSeverity()); summaryLine = summaryLine.concat(": "); summaryLine = summaryLine.concat(message.getMessage()); summaryLine = summaryLine.concat(" ("+ message.getMessageKey() + ") "); for (Object origin : message.getOrigins()) { StringWriter writer = new StringWriter(); String text = ((Origin) origin).getOriginText(); writer.write(text); summaryLine = summaryLine.concat(writer.toString()); writer.close(); } } } summaryLine = summaryLine.concat("\n\n***FILE SUMMARY***\n"); List<FlattenedValidationPlanResult> flattenedPlanResults = Utils.flattenValidationPlans(planResults); for (FlattenedValidationPlanResult flattenedResult : flattenedPlanResults) { summaryLine = summaryLine.concat(flattenedResult.getFileName() + " - "); summaryLine = summaryLine.concat(flattenedResult.getEntryCount() + " entries, "); summaryLine = summaryLine.concat(flattenedResult.getFailedEntryCount() + " failed entries, "); summaryLine = summaryLine.concat((flattenedResult.getErrorCount() + parseErrorCount) + " errors, "); summaryLine = summaryLine.concat(flattenedResult.getFixCount() + " fixes, "); summaryLine = summaryLine.concat(flattenedResult.getWarningInfoCount() + " warnings & info"); summaryLine = summaryLine.concat("\n"); } } summaryLine = summaryLine.concat("\n*** SUMMARY***\n"); summaryLine = summaryLine.concat("Parsing error:" + parseErrorCount+ "\n"); summaryLine = summaryLine.concat("Fixed Entries:" + fixCount + "\n"); summaryLine = summaryLine.concat("Failed Entries:" + failCount+ "\n"); summaryLine = summaryLine.concat("Checked Entries:"+ totalEntryCount + "\n"); summaryLine = summaryLine.concat("Unchanged Entries:"+ unchangedCount + "\n"); long timeOut = System.currentTimeMillis(); long timeToRun = (timeOut - timeIn) / 1000; summaryLine = summaryLine.concat("\n\nProcessed " + totalEntryCount+ " entries in " + timeToRun + " seconds.\n\n"); printMessage( summaryLine,LOG_LEVEL_SUMMARY); summaryWriter.write(summaryLine); summaryWriter.flush(); summaryWriter.close(); } catch (IOException e) { e.printStackTrace(); } return failCount; } }
public class class_name { private int validateFiles() { List<ValidationPlanResult> planResults = new ArrayList<ValidationPlanResult>(); int parseErrorCount = 0; try { long timeIn = System.currentTimeMillis(); if (filterMode && filterPrefix != null) { goodFilesWriter = new PrintWriter(filterPrefix + "_good.txt","UTF-8"); // depends on control dependency: [if], data = [none] badFilesWriter = new PrintWriter(filterPrefix + "_bad.txt","UTF-8"); // depends on control dependency: [if], data = [none] } for (File file : entryFiles) { List<ValidationPlanResult> results = validateFile( file,errorWriter); planResults.addAll(results); // depends on control dependency: [for], data = [none] } infoWriter.flush(); errorWriter.flush(); reportWriter.flush(); fixWriter.flush(); infoWriter.close(); errorWriter.close(); reportWriter.close(); fixWriter.close(); if (filterMode && filterPrefix != null) { badFilesWriter.flush(); // depends on control dependency: [if], data = [none] badFilesWriter.close(); // depends on control dependency: [if], data = [none] goodFilesWriter.flush(); // depends on control dependency: [if], data = [none] goodFilesWriter.close(); // depends on control dependency: [if], data = [none] } List<ValidationMessage<Origin>> messages = new ArrayList<ValidationMessage<Origin>>(); for (ValidationPlanResult planResult : planResults) { messages.addAll(planResult.getMessages()); // depends on control dependency: [for], data = [planResult] } for (ValidationResult parseResult : parseResults) { messages.addAll(parseResult.getMessages()); // depends on control dependency: [for], data = [parseResult] for (ValidationMessage message : parseResult.getMessages()) { parseErrorCount++; // depends on control dependency: [for], data = [none] } } /** * will be built up to form the summary for the whole run */ String summaryLine = ""; if (!planResults.isEmpty()) { FlattenedMessageResult results = Utils.flattenMessages(messages,MESSAGE_FLATTEN_THRESHOLD); List<ValidationMessage> flattenedMessages = results.getFlattenedMessages(); List<ValidationMessage> unFlattenedMessages = results.getUnFlattenedMessages(); Collections.sort( flattenedMessages,new ValidationMessageComparator()); // depends on control dependency: [if], data = [none] Collections.sort( unFlattenedMessages,new ValidationMessageComparator()); // depends on control dependency: [if], data = [none] if (!flattenedMessages.isEmpty()) { summaryLine = summaryLine.concat("\n\n***MESSAGES SUMMARY***"); // depends on control dependency: [if], data = [none] summaryLine = summaryLine.concat("\nCompressed messages (occurring more than "+ MESSAGE_FLATTEN_THRESHOLD + " times)"); // depends on control dependency: [if], data = [none] for (ValidationMessage message : flattenedMessages) { summaryLine = summaryLine.concat("\n"+ message.getSeverity()); // depends on control dependency: [for], data = [message] summaryLine = summaryLine.concat(": "); // depends on control dependency: [for], data = [none] summaryLine = summaryLine.concat(message.getMessage()); // depends on control dependency: [for], data = [message] summaryLine = summaryLine.concat(" ("+ message.getMessageKey() + ") "); // depends on control dependency: [for], data = [message] } } if (!unFlattenedMessages.isEmpty()) { summaryLine = summaryLine.concat("\n\nMessages"); // depends on control dependency: [if], data = [none] for (ValidationMessage message : unFlattenedMessages) { summaryLine = summaryLine.concat("\n"+ message.getSeverity()); // depends on control dependency: [for], data = [message] summaryLine = summaryLine.concat(": "); // depends on control dependency: [for], data = [none] summaryLine = summaryLine.concat(message.getMessage()); // depends on control dependency: [for], data = [message] summaryLine = summaryLine.concat(" ("+ message.getMessageKey() + ") "); for (Object origin : message.getOrigins()) { StringWriter writer = new StringWriter(); String text = ((Origin) origin).getOriginText(); writer.write(text); summaryLine = summaryLine.concat(writer.toString()); writer.close(); // depends on control dependency: [for], data = [none] } } } summaryLine = summaryLine.concat("\n\n***FILE SUMMARY***\n"); List<FlattenedValidationPlanResult> flattenedPlanResults = Utils.flattenValidationPlans(planResults); for (FlattenedValidationPlanResult flattenedResult : flattenedPlanResults) { summaryLine = summaryLine.concat(flattenedResult.getFileName() + " - "); summaryLine = summaryLine.concat(flattenedResult.getEntryCount() + " entries, "); summaryLine = summaryLine.concat(flattenedResult.getFailedEntryCount() + " failed entries, "); summaryLine = summaryLine.concat((flattenedResult.getErrorCount() + parseErrorCount) + " errors, "); summaryLine = summaryLine.concat(flattenedResult.getFixCount() + " fixes, "); summaryLine = summaryLine.concat(flattenedResult.getWarningInfoCount() + " warnings & info"); summaryLine = summaryLine.concat("\n"); } } summaryLine = summaryLine.concat("\n*** SUMMARY***\n"); summaryLine = summaryLine.concat("Parsing error:" + parseErrorCount+ "\n"); summaryLine = summaryLine.concat("Fixed Entries:" + fixCount + "\n"); summaryLine = summaryLine.concat("Failed Entries:" + failCount+ "\n"); summaryLine = summaryLine.concat("Checked Entries:"+ totalEntryCount + "\n"); summaryLine = summaryLine.concat("Unchanged Entries:"+ unchangedCount + "\n"); long timeOut = System.currentTimeMillis(); long timeToRun = (timeOut - timeIn) / 1000; summaryLine = summaryLine.concat("\n\nProcessed " + totalEntryCount+ " entries in " + timeToRun + " seconds.\n\n"); printMessage( summaryLine,LOG_LEVEL_SUMMARY); summaryWriter.write(summaryLine); summaryWriter.flush(); summaryWriter.close(); } catch (IOException e) { e.printStackTrace(); } return failCount; } }
public class class_name { private double getAngle(ServletRequest pRequest) { // Get angle double angle = ServletUtil.getDoubleParameter(pRequest, PARAM_TEXT_ROTATION, 0.0); // Convert to radians, if needed String units = pRequest.getParameter(PARAM_TEXT_ROTATION_UNITS); if (!StringUtil.isEmpty(units) && ROTATION_DEGREES.equalsIgnoreCase(units)) { angle = Math.toRadians(angle); } return angle; } }
public class class_name { private double getAngle(ServletRequest pRequest) { // Get angle double angle = ServletUtil.getDoubleParameter(pRequest, PARAM_TEXT_ROTATION, 0.0); // Convert to radians, if needed String units = pRequest.getParameter(PARAM_TEXT_ROTATION_UNITS); if (!StringUtil.isEmpty(units) && ROTATION_DEGREES.equalsIgnoreCase(units)) { angle = Math.toRadians(angle); // depends on control dependency: [if], data = [none] } return angle; } }
public class class_name { @SuppressWarnings("unchecked") public void setSwitchers(Switcher<T>[] switchers) { if (switchers != null && switchers.length > 0 && this.switchers != null && this.switchers.length > 0) { Switcher<T>[] oldSwitchers = this.switchers; this.switchers = new Switcher[oldSwitchers.length + switchers.length]; System.arraycopy(oldSwitchers, 0, this.switchers, 0, oldSwitchers.length); System.arraycopy(switchers, 0, this.switchers, oldSwitchers.length, switchers.length); } else { this.switchers = switchers; } } }
public class class_name { @SuppressWarnings("unchecked") public void setSwitchers(Switcher<T>[] switchers) { if (switchers != null && switchers.length > 0 && this.switchers != null && this.switchers.length > 0) { Switcher<T>[] oldSwitchers = this.switchers; this.switchers = new Switcher[oldSwitchers.length + switchers.length]; // depends on control dependency: [if], data = [none] System.arraycopy(oldSwitchers, 0, this.switchers, 0, oldSwitchers.length); // depends on control dependency: [if], data = [none] System.arraycopy(switchers, 0, this.switchers, oldSwitchers.length, switchers.length); // depends on control dependency: [if], data = [(switchers] } else { this.switchers = switchers; // depends on control dependency: [if], data = [none] } } }
public class class_name { void loadCategories(CmsObject cms, String contextPath) { m_checkboxes.clear(); m_container.removeAllItems(); List<CmsCategory> categories; Locale wpLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); CmsCategoryService catService = CmsCategoryService.getInstance(); // get the categories try { categories = catService.readCategories(cms, "", true, contextPath); categories = catService.localizeCategories(cms, categories, wpLocale); setCategories(categories); } catch (CmsException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public class class_name { void loadCategories(CmsObject cms, String contextPath) { m_checkboxes.clear(); m_container.removeAllItems(); List<CmsCategory> categories; Locale wpLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms); CmsCategoryService catService = CmsCategoryService.getInstance(); // get the categories try { categories = catService.readCategories(cms, "", true, contextPath); // depends on control dependency: [try], data = [none] categories = catService.localizeCategories(cms, categories, wpLocale); // depends on control dependency: [try], data = [none] setCategories(categories); // depends on control dependency: [try], data = [none] } catch (CmsException e) { // TODO Auto-generated catch block e.printStackTrace(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { void load() throws StartException { FileInputStream fis = null; try { KeyStore loadedKeystore = KeyStore.getInstance(provider); if (new File(path).exists()) { fis = new FileInputStream(path); loadedKeystore.load(fis, keystorePassword); } else if (isKeyStore) { throw DomainManagementLogger.ROOT_LOGGER.keyStoreNotFound(path); } else { loadedKeystore.load(null); } if (isKeyStore) { assertContainsKey(loadedKeystore); } if (alias == null) { this.setKeyStore(loadedKeystore); } else { KeyStore newKeystore = KeyStore.getInstance(provider); newKeystore.load(null); KeyStore.ProtectionParameter passParam = new KeyStore.PasswordProtection(keyPassword == null ? keystorePassword : keyPassword); if (loadedKeystore.containsAlias(alias)) { if (loadedKeystore.isKeyEntry(alias)) { KeyStore.Entry entry = loadedKeystore.getEntry(this.alias, passParam); newKeystore.setEntry(alias, entry, passParam); } else { throw DomainManagementLogger.ROOT_LOGGER.aliasNotKey(alias, validAliasList(loadedKeystore)); } } else { throw DomainManagementLogger.ROOT_LOGGER.aliasNotFound(alias, validAliasList(loadedKeystore)); } this.setKeyStore(newKeystore); } this.lastModificationTime = new File(path).lastModified(); } catch (KeyStoreException e) { throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e); } catch (NoSuchAlgorithmException e) { throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e); } catch (CertificateException e) { throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e); } catch (IOException e) { throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e); } catch (UnrecoverableEntryException e) { throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e); } finally { safeClose(fis); } } }
public class class_name { void load() throws StartException { FileInputStream fis = null; try { KeyStore loadedKeystore = KeyStore.getInstance(provider); if (new File(path).exists()) { fis = new FileInputStream(path); // depends on control dependency: [if], data = [none] loadedKeystore.load(fis, keystorePassword); // depends on control dependency: [if], data = [none] } else if (isKeyStore) { throw DomainManagementLogger.ROOT_LOGGER.keyStoreNotFound(path); } else { loadedKeystore.load(null); // depends on control dependency: [if], data = [none] } if (isKeyStore) { assertContainsKey(loadedKeystore); // depends on control dependency: [if], data = [none] } if (alias == null) { this.setKeyStore(loadedKeystore); // depends on control dependency: [if], data = [none] } else { KeyStore newKeystore = KeyStore.getInstance(provider); newKeystore.load(null); // depends on control dependency: [if], data = [null)] KeyStore.ProtectionParameter passParam = new KeyStore.PasswordProtection(keyPassword == null ? keystorePassword : keyPassword); if (loadedKeystore.containsAlias(alias)) { if (loadedKeystore.isKeyEntry(alias)) { KeyStore.Entry entry = loadedKeystore.getEntry(this.alias, passParam); newKeystore.setEntry(alias, entry, passParam); // depends on control dependency: [if], data = [none] } else { throw DomainManagementLogger.ROOT_LOGGER.aliasNotKey(alias, validAliasList(loadedKeystore)); } } else { throw DomainManagementLogger.ROOT_LOGGER.aliasNotFound(alias, validAliasList(loadedKeystore)); } this.setKeyStore(newKeystore); // depends on control dependency: [if], data = [none] } this.lastModificationTime = new File(path).lastModified(); } catch (KeyStoreException e) { throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e); } catch (NoSuchAlgorithmException e) { throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e); } catch (CertificateException e) { throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e); } catch (IOException e) { throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e); } catch (UnrecoverableEntryException e) { throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e); } finally { safeClose(fis); } } }
public class class_name { public static double[] cumsum (double[] vector) { // Initialize the return value: final double[] retval = new double[vector.length]; // Iterate and cumulate: retval[0] = vector[0]; for (int i = 1; i < retval.length; i++) { retval[i] = vector[i] + retval[i - 1]; } // Done, return: return retval; } }
public class class_name { public static double[] cumsum (double[] vector) { // Initialize the return value: final double[] retval = new double[vector.length]; // Iterate and cumulate: retval[0] = vector[0]; for (int i = 1; i < retval.length; i++) { retval[i] = vector[i] + retval[i - 1]; // depends on control dependency: [for], data = [i] } // Done, return: return retval; } }
public class class_name { @Override public PathImpl schemeWalk(String userPath, Map<String,Object> attributes, String filePath, int offset) { if (! isWindows()) { return super.schemeWalk(userPath, attributes, filePath, offset); } String canonicalPath; if (filePath.length() < offset + 2) { return super.schemeWalk(userPath, attributes, filePath, offset); } char ch1 = filePath.charAt(offset + 1); char ch2 = filePath.charAt(offset); if ((ch2 == '/' || ch2 == _separatorChar) && (ch1 == '/' || ch1 == _separatorChar)) return super.schemeWalk(userPath, attributes, convertFromWindowsPath(filePath.substring(offset)), 0); else return super.schemeWalk(userPath, attributes, filePath, offset); } }
public class class_name { @Override public PathImpl schemeWalk(String userPath, Map<String,Object> attributes, String filePath, int offset) { if (! isWindows()) { return super.schemeWalk(userPath, attributes, filePath, offset); // depends on control dependency: [if], data = [none] } String canonicalPath; if (filePath.length() < offset + 2) { return super.schemeWalk(userPath, attributes, filePath, offset); // depends on control dependency: [if], data = [none] } char ch1 = filePath.charAt(offset + 1); char ch2 = filePath.charAt(offset); if ((ch2 == '/' || ch2 == _separatorChar) && (ch1 == '/' || ch1 == _separatorChar)) return super.schemeWalk(userPath, attributes, convertFromWindowsPath(filePath.substring(offset)), 0); else return super.schemeWalk(userPath, attributes, filePath, offset); } }
public class class_name { @Override public void visit(Field aField) { if (aField.isPrivate()) { /* * private fields are harmless, as long as they are used correctly * inside their own class. This should be something the rest of this * detector can find out, so do not report them, they might be false * positives. */ return; } String superclassName = getSuperclassName(); if (!aField.isStatic() && !"java/lang/Enum".equals(superclassName)) { return; } if (!aField.isPublic() && !aField.isProtected()) { return; } ClassDescriptor classOfField = DescriptorFactory.createClassDescriptorFromFieldSignature(aField.getSignature()); String tBugType = null; int priority = aField.isPublic() && aField.isFinal() && aField.getName().equals(aField.getName().toUpperCase()) && getThisClass().isPublic() ? HIGH_PRIORITY : NORMAL_PRIORITY; if (classOfField != null) { try { if (subtypes2.isSubtype(classOfField, calendarType)) { tBugType = "STCAL_STATIC_CALENDAR_INSTANCE"; priority++; } else if (subtypes2.isSubtype(classOfField, dateFormatType)) { tBugType = "STCAL_STATIC_SIMPLE_DATE_FORMAT_INSTANCE"; } if (getClassContext().getXClass().usesConcurrency()) { priority--; } if (tBugType != null) { pendingBugs.put(getXField(), new BugInstance(this, tBugType, priority).addClass(currentClass).addField(this)); } } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); } } } }
public class class_name { @Override public void visit(Field aField) { if (aField.isPrivate()) { /* * private fields are harmless, as long as they are used correctly * inside their own class. This should be something the rest of this * detector can find out, so do not report them, they might be false * positives. */ return; // depends on control dependency: [if], data = [none] } String superclassName = getSuperclassName(); if (!aField.isStatic() && !"java/lang/Enum".equals(superclassName)) { return; // depends on control dependency: [if], data = [none] } if (!aField.isPublic() && !aField.isProtected()) { return; // depends on control dependency: [if], data = [none] } ClassDescriptor classOfField = DescriptorFactory.createClassDescriptorFromFieldSignature(aField.getSignature()); String tBugType = null; int priority = aField.isPublic() && aField.isFinal() && aField.getName().equals(aField.getName().toUpperCase()) && getThisClass().isPublic() ? HIGH_PRIORITY : NORMAL_PRIORITY; if (classOfField != null) { try { if (subtypes2.isSubtype(classOfField, calendarType)) { tBugType = "STCAL_STATIC_CALENDAR_INSTANCE"; // depends on control dependency: [if], data = [none] priority++; // depends on control dependency: [if], data = [none] } else if (subtypes2.isSubtype(classOfField, dateFormatType)) { tBugType = "STCAL_STATIC_SIMPLE_DATE_FORMAT_INSTANCE"; // depends on control dependency: [if], data = [none] } if (getClassContext().getXClass().usesConcurrency()) { priority--; // depends on control dependency: [if], data = [none] } if (tBugType != null) { pendingBugs.put(getXField(), new BugInstance(this, tBugType, priority).addClass(currentClass).addField(this)); // depends on control dependency: [if], data = [none] } } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { currentRequest.set(req); try { // check to OpenCms runlevel int runlevel = OpenCmsCore.getInstance().getRunLevel(); // write OpenCms server identification in the response header res.setHeader(CmsRequestUtil.HEADER_SERVER, OpenCmsCore.getInstance().getSystemInfo().getVersion()); if (runlevel != OpenCms.RUNLEVEL_4_SERVLET_ACCESS) { // not the "normal" servlet runlevel if (runlevel == OpenCms.RUNLEVEL_3_SHELL_ACCESS) { // we have shell runlevel only, upgrade to servlet runlevel (required after setup wizard) init(getServletConfig()); } else { // illegal runlevel, we can't process requests // sending status code 403, indicating the server understood the request but refused to fulfill it res.sendError(HttpServletResponse.SC_FORBIDDEN); // goodbye return; } } String path = OpenCmsCore.getInstance().getPathInfo(req); if (path.startsWith(HANDLE_PATH)) { // this is a request to an OpenCms handler URI invokeHandler(req, res); } else if (path.endsWith(HANDLE_GWT)) { // handle GWT rpc services String serviceName = CmsResource.getName(path); serviceName = serviceName.substring(0, serviceName.length() - HANDLE_GWT.length()); OpenCmsCore.getInstance().invokeGwtService(serviceName, req, res, getServletConfig()); } else { // standard request to a URI in the OpenCms VFS OpenCmsCore.getInstance().showResource(req, res); } } finally { currentRequest.remove(); } } }
public class class_name { @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { currentRequest.set(req); try { // check to OpenCms runlevel int runlevel = OpenCmsCore.getInstance().getRunLevel(); // write OpenCms server identification in the response header res.setHeader(CmsRequestUtil.HEADER_SERVER, OpenCmsCore.getInstance().getSystemInfo().getVersion()); if (runlevel != OpenCms.RUNLEVEL_4_SERVLET_ACCESS) { // not the "normal" servlet runlevel if (runlevel == OpenCms.RUNLEVEL_3_SHELL_ACCESS) { // we have shell runlevel only, upgrade to servlet runlevel (required after setup wizard) init(getServletConfig()); // depends on control dependency: [if], data = [none] } else { // illegal runlevel, we can't process requests // sending status code 403, indicating the server understood the request but refused to fulfill it res.sendError(HttpServletResponse.SC_FORBIDDEN); // depends on control dependency: [if], data = [none] // goodbye return; // depends on control dependency: [if], data = [none] } } String path = OpenCmsCore.getInstance().getPathInfo(req); if (path.startsWith(HANDLE_PATH)) { // this is a request to an OpenCms handler URI invokeHandler(req, res); } else if (path.endsWith(HANDLE_GWT)) { // handle GWT rpc services String serviceName = CmsResource.getName(path); serviceName = serviceName.substring(0, serviceName.length() - HANDLE_GWT.length()); OpenCmsCore.getInstance().invokeGwtService(serviceName, req, res, getServletConfig()); } else { // standard request to a URI in the OpenCms VFS OpenCmsCore.getInstance().showResource(req, res); } } finally { currentRequest.remove(); } } }
public class class_name { public GeneralizedCounter<K> conditionalize(List<K> l) { int n = l.size(); if (n >= depth()) { throw new RuntimeException("Error -- attempted to conditionalize a GeneralizedCounter of depth " + depth() + " on a vector of length " + n); } else { GeneralizedCounter<K> next = this; for (K o: l) { next = next.conditionalizeHelper(o); } return next; } } }
public class class_name { public GeneralizedCounter<K> conditionalize(List<K> l) { int n = l.size(); if (n >= depth()) { throw new RuntimeException("Error -- attempted to conditionalize a GeneralizedCounter of depth " + depth() + " on a vector of length " + n); } else { GeneralizedCounter<K> next = this; for (K o: l) { next = next.conditionalizeHelper(o); // depends on control dependency: [for], data = [o] } return next; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static List<ColumnMetaData> buildMDFromSQLTable(final Connection con, final String dataDefinition, final Parser parser) throws SQLException { final List<ColumnMetaData> cmds = new ArrayList<>(); final String dfTbl = parser != null ? parser.getDataFileTable() : "DATAFILE"; final String dsTbl = parser != null ? parser.getDataStructureTable() : "DATASTRUCTURE"; final StringBuilder sqlSb = new StringBuilder(); sqlSb.append("SELECT * FROM ").append(dfTbl).append(" INNER JOIN ").append(dsTbl).append(" ON ").append(dfTbl).append(".DATAFILE_NO = ") .append(dsTbl).append(".DATAFILE_NO " + "WHERE DATAFILE_DESC = ? ORDER BY DATASTRUCTURE_COL_ORDER"); try (PreparedStatement stmt = con.prepareStatement(sqlSb.toString())) { // always use PreparedStatement // as the DB can do clever things. stmt.setString(1, dataDefinition); try (ResultSet rs = stmt.executeQuery()) { int recPosition = 1; // put array of columns together. These will be used to put together // the dataset when reading in the file while (rs.next()) { final ColumnMetaData column = new ColumnMetaData(); column.setColName(rs.getString("DATASTRUCTURE_COLUMN")); column.setColLength(rs.getInt(DATASTRUCTURE_LENGTH)); column.setStartPosition(recPosition); column.setEndPosition(recPosition + rs.getInt(DATASTRUCTURE_LENGTH) - 1); recPosition += rs.getInt(DATASTRUCTURE_LENGTH); cmds.add(column); } } if (cmds.isEmpty()) { throw new FPException("Data File Key [" + dataDefinition + "] Is Not In The database OR No Columns Specified In Table"); } } return cmds; } }
public class class_name { public static List<ColumnMetaData> buildMDFromSQLTable(final Connection con, final String dataDefinition, final Parser parser) throws SQLException { final List<ColumnMetaData> cmds = new ArrayList<>(); final String dfTbl = parser != null ? parser.getDataFileTable() : "DATAFILE"; final String dsTbl = parser != null ? parser.getDataStructureTable() : "DATASTRUCTURE"; final StringBuilder sqlSb = new StringBuilder(); sqlSb.append("SELECT * FROM ").append(dfTbl).append(" INNER JOIN ").append(dsTbl).append(" ON ").append(dfTbl).append(".DATAFILE_NO = ") .append(dsTbl).append(".DATAFILE_NO " + "WHERE DATAFILE_DESC = ? ORDER BY DATASTRUCTURE_COL_ORDER"); try (PreparedStatement stmt = con.prepareStatement(sqlSb.toString())) { // always use PreparedStatement // as the DB can do clever things. stmt.setString(1, dataDefinition); try (ResultSet rs = stmt.executeQuery()) { int recPosition = 1; // put array of columns together. These will be used to put together // the dataset when reading in the file while (rs.next()) { final ColumnMetaData column = new ColumnMetaData(); column.setColName(rs.getString("DATASTRUCTURE_COLUMN")); // depends on control dependency: [while], data = [none] column.setColLength(rs.getInt(DATASTRUCTURE_LENGTH)); // depends on control dependency: [while], data = [none] column.setStartPosition(recPosition); // depends on control dependency: [while], data = [none] column.setEndPosition(recPosition + rs.getInt(DATASTRUCTURE_LENGTH) - 1); // depends on control dependency: [while], data = [none] recPosition += rs.getInt(DATASTRUCTURE_LENGTH); // depends on control dependency: [while], data = [none] cmds.add(column); // depends on control dependency: [while], data = [none] } } if (cmds.isEmpty()) { throw new FPException("Data File Key [" + dataDefinition + "] Is Not In The database OR No Columns Specified In Table"); } } return cmds; } }
public class class_name { @Override public void renewToken() { CreateTokenRequest createTokenRequest = new CreateTokenRequest(); createTokenRequest.setUser(credentials.getUserName()); createTokenRequest.setPassword(credentials.getPassword()); CreateTokenResponse createTokenResponse; try { createTokenResponse = send(createTokenRequest); } catch (ValidationConstraintViolationException vcve) { throw new AuthorizationException(vcve); } HttpStatus status = HttpStatus.getStatus(createTokenResponse.getStatusCode()); if (status.isError()) { if (status.equals(HttpStatus.Unauthorized)) { throw new AuthorizationException(HttpStatus.Unauthorized.toString()); } else { throw new CommunicationErrorException(status); } } String newToken = createTokenResponse.getToken(); tokenStore.setToken(newToken); } }
public class class_name { @Override public void renewToken() { CreateTokenRequest createTokenRequest = new CreateTokenRequest(); createTokenRequest.setUser(credentials.getUserName()); createTokenRequest.setPassword(credentials.getPassword()); CreateTokenResponse createTokenResponse; try { createTokenResponse = send(createTokenRequest); // depends on control dependency: [try], data = [none] } catch (ValidationConstraintViolationException vcve) { throw new AuthorizationException(vcve); } // depends on control dependency: [catch], data = [none] HttpStatus status = HttpStatus.getStatus(createTokenResponse.getStatusCode()); if (status.isError()) { if (status.equals(HttpStatus.Unauthorized)) { throw new AuthorizationException(HttpStatus.Unauthorized.toString()); } else { throw new CommunicationErrorException(status); } } String newToken = createTokenResponse.getToken(); tokenStore.setToken(newToken); } }
public class class_name { protected void closeJobManagerConnection(JobID jobId, Exception cause) { JobManagerRegistration jobManagerRegistration = jobManagerRegistrations.remove(jobId); if (jobManagerRegistration != null) { final ResourceID jobManagerResourceId = jobManagerRegistration.getJobManagerResourceID(); final JobMasterGateway jobMasterGateway = jobManagerRegistration.getJobManagerGateway(); final JobMasterId jobMasterId = jobManagerRegistration.getJobMasterId(); log.info("Disconnect job manager {}@{} for job {} from the resource manager.", jobMasterId, jobMasterGateway.getAddress(), jobId); jobManagerHeartbeatManager.unmonitorTarget(jobManagerResourceId); jmResourceIdRegistrations.remove(jobManagerResourceId); // tell the job manager about the disconnect jobMasterGateway.disconnectResourceManager(getFencingToken(), cause); } else { log.debug("There was no registered job manager for job {}.", jobId); } } }
public class class_name { protected void closeJobManagerConnection(JobID jobId, Exception cause) { JobManagerRegistration jobManagerRegistration = jobManagerRegistrations.remove(jobId); if (jobManagerRegistration != null) { final ResourceID jobManagerResourceId = jobManagerRegistration.getJobManagerResourceID(); final JobMasterGateway jobMasterGateway = jobManagerRegistration.getJobManagerGateway(); final JobMasterId jobMasterId = jobManagerRegistration.getJobMasterId(); log.info("Disconnect job manager {}@{} for job {} from the resource manager.", jobMasterId, jobMasterGateway.getAddress(), jobId); // depends on control dependency: [if], data = [none] jobManagerHeartbeatManager.unmonitorTarget(jobManagerResourceId); // depends on control dependency: [if], data = [none] jmResourceIdRegistrations.remove(jobManagerResourceId); // depends on control dependency: [if], data = [none] // tell the job manager about the disconnect jobMasterGateway.disconnectResourceManager(getFencingToken(), cause); // depends on control dependency: [if], data = [none] } else { log.debug("There was no registered job manager for job {}.", jobId); // depends on control dependency: [if], data = [none] } } }
public class class_name { @POST @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public Response createEnforcementJob(@Context HttpHeaders hh, String payload){ logger.debug("StartOf createEnforcementJob - REQUEST Insert /enforcement"); EnforcementJobHelper enforcementJobService = getHelper(); String location; try { location = enforcementJobService.createEnforcementJob( hh, _uriInfo.getAbsolutePath().toString(), payload); } catch (HelperException e) { logger.info("createEnforcementJob exception", e); return buildResponse(e); } logger.debug("EndOf createEnforcementJob"); return buildResponsePOST( HttpStatus.CREATED, printMessage( HttpStatus.CREATED, "The enforcementJob has been stored successfully in the SLA Repository Database"), location); } }
public class class_name { @POST @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public Response createEnforcementJob(@Context HttpHeaders hh, String payload){ logger.debug("StartOf createEnforcementJob - REQUEST Insert /enforcement"); EnforcementJobHelper enforcementJobService = getHelper(); String location; try { location = enforcementJobService.createEnforcementJob( hh, _uriInfo.getAbsolutePath().toString(), payload); // depends on control dependency: [try], data = [none] } catch (HelperException e) { logger.info("createEnforcementJob exception", e); return buildResponse(e); } // depends on control dependency: [catch], data = [none] logger.debug("EndOf createEnforcementJob"); return buildResponsePOST( HttpStatus.CREATED, printMessage( HttpStatus.CREATED, "The enforcementJob has been stored successfully in the SLA Repository Database"), location); } }
public class class_name { @Override public void scan(String xmlLocations) { if (StringHelper.isBlank(xmlLocations)) { return; } // 对配置的xml路径按逗号分割的规则来解析,如果是XML文件则直接将该xml文件存放到xmlPaths的Set集合中, // 否则就代表是xml资源目录,并解析目录下所有的xml文件,将这些xml文件存放到xmlPaths的Set集合中, String[] xmlLocationArr = xmlLocations.split(ZealotConst.COMMA); for (String xmlLocation: xmlLocationArr) { if (StringHelper.isBlank(xmlLocation)) { continue; } String cleanXmlLocation = xmlLocation.trim(); if (StringHelper.isXmlFile(cleanXmlLocation)) { xmlPaths.add(cleanXmlLocation); } else { this.scanXmlsByPackage(cleanXmlLocation.replace('.', '/')); } } // 从xmlPath的Set集合中获取的如果是zealot的xml文件的话,则将其添加到XmlContext上下文中. this.addZealotXmlInContext(); } }
public class class_name { @Override public void scan(String xmlLocations) { if (StringHelper.isBlank(xmlLocations)) { return; // depends on control dependency: [if], data = [none] } // 对配置的xml路径按逗号分割的规则来解析,如果是XML文件则直接将该xml文件存放到xmlPaths的Set集合中, // 否则就代表是xml资源目录,并解析目录下所有的xml文件,将这些xml文件存放到xmlPaths的Set集合中, String[] xmlLocationArr = xmlLocations.split(ZealotConst.COMMA); for (String xmlLocation: xmlLocationArr) { if (StringHelper.isBlank(xmlLocation)) { continue; } String cleanXmlLocation = xmlLocation.trim(); if (StringHelper.isXmlFile(cleanXmlLocation)) { xmlPaths.add(cleanXmlLocation); // depends on control dependency: [if], data = [none] } else { this.scanXmlsByPackage(cleanXmlLocation.replace('.', '/')); // depends on control dependency: [if], data = [none] } } // 从xmlPath的Set集合中获取的如果是zealot的xml文件的话,则将其添加到XmlContext上下文中. this.addZealotXmlInContext(); } }
public class class_name { protected void bitcoinSerializeToStream(OutputStream stream, boolean useSegwit) throws IOException { // version uint32ToByteStreamLE(version, stream); // marker, flag if (useSegwit) { stream.write(0); stream.write(1); } // txin_count, txins stream.write(new VarInt(inputs.size()).encode()); for (TransactionInput in : inputs) in.bitcoinSerialize(stream); // txout_count, txouts stream.write(new VarInt(outputs.size()).encode()); for (TransactionOutput out : outputs) out.bitcoinSerialize(stream); // script_witnisses if (useSegwit) { for (TransactionInput in : inputs) { in.getWitness().bitcoinSerializeToStream(stream); } } // lock_time uint32ToByteStreamLE(lockTime, stream); } }
public class class_name { protected void bitcoinSerializeToStream(OutputStream stream, boolean useSegwit) throws IOException { // version uint32ToByteStreamLE(version, stream); // marker, flag if (useSegwit) { stream.write(0); stream.write(1); } // txin_count, txins stream.write(new VarInt(inputs.size()).encode()); for (TransactionInput in : inputs) in.bitcoinSerialize(stream); // txout_count, txouts stream.write(new VarInt(outputs.size()).encode()); for (TransactionOutput out : outputs) out.bitcoinSerialize(stream); // script_witnisses if (useSegwit) { for (TransactionInput in : inputs) { in.getWitness().bitcoinSerializeToStream(stream); // depends on control dependency: [for], data = [in] } } // lock_time uint32ToByteStreamLE(lockTime, stream); } }
public class class_name { public TreeElement getChild(int index) { TreeElement childNode = null; if (_children == null) return null; Object child = _children.get(index); if (child != null) { childNode = (TreeElement) child; } return childNode; } }
public class class_name { public TreeElement getChild(int index) { TreeElement childNode = null; if (_children == null) return null; Object child = _children.get(index); if (child != null) { childNode = (TreeElement) child; // depends on control dependency: [if], data = [none] } return childNode; } }
public class class_name { Long getCounterValueAsLong(final CounterMap counters, final String counterGroupName, final String counterName) { Counter c1 = counters.getCounter(counterGroupName, counterName); if (c1 != null) { return c1.getValue(); } else { return 0L; } } }
public class class_name { Long getCounterValueAsLong(final CounterMap counters, final String counterGroupName, final String counterName) { Counter c1 = counters.getCounter(counterGroupName, counterName); if (c1 != null) { return c1.getValue(); // depends on control dependency: [if], data = [none] } else { return 0L; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static INDArray[] covarianceMatrix(INDArray in) { long dlength = in.rows(); long vlength = in.columns(); INDArray sum = Nd4j.create(vlength); INDArray product = Nd4j.create(vlength, vlength); for (int i = 0; i < vlength; i++) sum.getColumn(i).assign(in.getColumn(i).sumNumber().doubleValue() / dlength); for (int i = 0; i < dlength; i++) { INDArray dx1 = in.getRow(i).sub(sum); product.addi(dx1.reshape(vlength, 1).mmul(dx1.reshape(1, vlength))); } product.divi(dlength); return new INDArray[] {product, sum}; } }
public class class_name { public static INDArray[] covarianceMatrix(INDArray in) { long dlength = in.rows(); long vlength = in.columns(); INDArray sum = Nd4j.create(vlength); INDArray product = Nd4j.create(vlength, vlength); for (int i = 0; i < vlength; i++) sum.getColumn(i).assign(in.getColumn(i).sumNumber().doubleValue() / dlength); for (int i = 0; i < dlength; i++) { INDArray dx1 = in.getRow(i).sub(sum); product.addi(dx1.reshape(vlength, 1).mmul(dx1.reshape(1, vlength))); // depends on control dependency: [for], data = [none] } product.divi(dlength); return new INDArray[] {product, sum}; } }
public class class_name { @Override public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) { final String valueAsString = Objects.toString(pvalue, null); if (StringUtils.isEmpty(valueAsString)) { return true; } if (valueAsString.length() != ISIN_LENGTH) { // ISIN size is wrong, but that's handled by size annotation return true; } // calculate and check checksum (ISIN) return CHECK_ISIN.isValid(valueAsString); } }
public class class_name { @Override public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) { final String valueAsString = Objects.toString(pvalue, null); if (StringUtils.isEmpty(valueAsString)) { return true; // depends on control dependency: [if], data = [none] } if (valueAsString.length() != ISIN_LENGTH) { // ISIN size is wrong, but that's handled by size annotation return true; // depends on control dependency: [if], data = [none] } // calculate and check checksum (ISIN) return CHECK_ISIN.isValid(valueAsString); } }
public class class_name { protected void handleTCPSrvRqst(SrvRqst srvRqst, Socket socket) { // Match scopes if (!getScopes().weakMatch(srvRqst.getScopes())) { if (logger.isLoggable(Level.FINE)) logger.fine("ServiceAgent server " + this + " dropping message " + srvRqst + ": no scopes match among agent scopes " + getScopes() + " and message scopes " + srvRqst.getScopes()); return; } List<ServiceInfo> matchingServices = matchServices(srvRqst.getServiceType(), srvRqst.getLanguage(), srvRqst.getScopes(), srvRqst.getFilter()); if (logger.isLoggable(Level.FINE)) logger.fine("ServiceAgent server " + this + " returning " + matchingServices.size() + " services of type " + srvRqst.getServiceType()); tcpSrvRply.perform(socket, srvRqst, matchingServices); } }
public class class_name { protected void handleTCPSrvRqst(SrvRqst srvRqst, Socket socket) { // Match scopes if (!getScopes().weakMatch(srvRqst.getScopes())) { if (logger.isLoggable(Level.FINE)) logger.fine("ServiceAgent server " + this + " dropping message " + srvRqst + ": no scopes match among agent scopes " + getScopes() + " and message scopes " + srvRqst.getScopes()); return; // depends on control dependency: [if], data = [none] } List<ServiceInfo> matchingServices = matchServices(srvRqst.getServiceType(), srvRqst.getLanguage(), srvRqst.getScopes(), srvRqst.getFilter()); if (logger.isLoggable(Level.FINE)) logger.fine("ServiceAgent server " + this + " returning " + matchingServices.size() + " services of type " + srvRqst.getServiceType()); tcpSrvRply.perform(socket, srvRqst, matchingServices); } }
public class class_name { private void fireFieldChangeEvent(AssignmentField field, Object oldValue, Object newValue) { // // Internal event handling // switch (field) { case START: case BASELINE_START: { m_array[AssignmentField.START_VARIANCE.getValue()] = null; break; } case FINISH: case BASELINE_FINISH: { m_array[AssignmentField.FINISH_VARIANCE.getValue()] = null; break; } case BCWP: case ACWP: { m_array[AssignmentField.CV.getValue()] = null; m_array[AssignmentField.SV.getValue()] = null; break; } case COST: case BASELINE_COST: { m_array[AssignmentField.COST_VARIANCE.getValue()] = null; break; } case WORK: case BASELINE_WORK: { m_array[AssignmentField.WORK_VARIANCE.getValue()] = null; break; } case ACTUAL_OVERTIME_COST: case REMAINING_OVERTIME_COST: { m_array[AssignmentField.OVERTIME_COST.getValue()] = null; break; } default: { break; } } // // External event handling // if (m_listeners != null) { for (FieldListener listener : m_listeners) { listener.fieldChange(this, field, oldValue, newValue); } } } }
public class class_name { private void fireFieldChangeEvent(AssignmentField field, Object oldValue, Object newValue) { // // Internal event handling // switch (field) { case START: case BASELINE_START: { m_array[AssignmentField.START_VARIANCE.getValue()] = null; break; } case FINISH: case BASELINE_FINISH: { m_array[AssignmentField.FINISH_VARIANCE.getValue()] = null; break; } case BCWP: case ACWP: { m_array[AssignmentField.CV.getValue()] = null; m_array[AssignmentField.SV.getValue()] = null; break; } case COST: case BASELINE_COST: { m_array[AssignmentField.COST_VARIANCE.getValue()] = null; break; } case WORK: case BASELINE_WORK: { m_array[AssignmentField.WORK_VARIANCE.getValue()] = null; break; } case ACTUAL_OVERTIME_COST: case REMAINING_OVERTIME_COST: { m_array[AssignmentField.OVERTIME_COST.getValue()] = null; break; } default: { break; } } // // External event handling // if (m_listeners != null) { for (FieldListener listener : m_listeners) { listener.fieldChange(this, field, oldValue, newValue); // depends on control dependency: [for], data = [listener] } } } }
public class class_name { public void addCameraListener(CameraListener lis) { if (listeners == null) { listeners = new ArrayList<>(5); } listeners.add(lis); } }
public class class_name { public void addCameraListener(CameraListener lis) { if (listeners == null) { listeners = new ArrayList<>(5); // depends on control dependency: [if], data = [none] } listeners.add(lis); } }
public class class_name { public static StringUtil getInstance() { if (instance == null) { synchronized (StringUtilImpl.class) { if (instance == null) { instance = new StringUtilImpl(); } } } return instance; } }
public class class_name { public static StringUtil getInstance() { if (instance == null) { synchronized (StringUtilImpl.class) { // depends on control dependency: [if], data = [none] if (instance == null) { instance = new StringUtilImpl(); // depends on control dependency: [if], data = [none] } } } return instance; } }
public class class_name { @Nonnull public static <T extends Comparable<T>> List<T> sortOptionallyComparables(@Nonnull Collection<T> toReturn) { List<T> list = new ArrayList<>(toReturn); try { Collections.sort(list); } catch (IllegalArgumentException e) { // catch possible sorting misbehaviour if (!e.getMessage().contains("Comparison method violates its general contract!")) { throw e; } // otherwise print a warning and leave the list unsorted } return list; } }
public class class_name { @Nonnull public static <T extends Comparable<T>> List<T> sortOptionallyComparables(@Nonnull Collection<T> toReturn) { List<T> list = new ArrayList<>(toReturn); try { Collections.sort(list); // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException e) { // catch possible sorting misbehaviour if (!e.getMessage().contains("Comparison method violates its general contract!")) { throw e; } // otherwise print a warning and leave the list unsorted } // depends on control dependency: [catch], data = [none] return list; } }
public class class_name { private void insertOrUpdateToken(io.motown.ocpi.dto.Token tokenUpdate, Integer subscriptionId) { Token token = ocpiRepository.findTokenByUidAndIssuingCompany(tokenUpdate.uid, tokenUpdate.issuer); if (token == null) { token = new Token(); token.setUid(tokenUpdate.uid); token.setSubscriptionId(subscriptionId); token.setDateCreated(new Date()); } token.setTokenType(tokenUpdate.type); token.setAuthId(tokenUpdate.auth_id); token.setVisualNumber(tokenUpdate.visual_number); token.setIssuingCompany(tokenUpdate.issuer); token.setValid(tokenUpdate.valid); token.setWhitelist(tokenUpdate.whitelist); token.setLanguageCode(tokenUpdate.languageCode); try { token.setLastUpdated(AppConfig.DATE_FORMAT.parse(tokenUpdate.last_updated)); } catch (ParseException e) { throw new RuntimeException(e); } ocpiRepository.insertOrUpdate(token); } }
public class class_name { private void insertOrUpdateToken(io.motown.ocpi.dto.Token tokenUpdate, Integer subscriptionId) { Token token = ocpiRepository.findTokenByUidAndIssuingCompany(tokenUpdate.uid, tokenUpdate.issuer); if (token == null) { token = new Token(); // depends on control dependency: [if], data = [none] token.setUid(tokenUpdate.uid); // depends on control dependency: [if], data = [(token] token.setSubscriptionId(subscriptionId); // depends on control dependency: [if], data = [none] token.setDateCreated(new Date()); // depends on control dependency: [if], data = [none] } token.setTokenType(tokenUpdate.type); token.setAuthId(tokenUpdate.auth_id); token.setVisualNumber(tokenUpdate.visual_number); token.setIssuingCompany(tokenUpdate.issuer); token.setValid(tokenUpdate.valid); token.setWhitelist(tokenUpdate.whitelist); token.setLanguageCode(tokenUpdate.languageCode); try { token.setLastUpdated(AppConfig.DATE_FORMAT.parse(tokenUpdate.last_updated)); // depends on control dependency: [try], data = [none] } catch (ParseException e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] ocpiRepository.insertOrUpdate(token); } }
public class class_name { public NodeType[] getSupertypes() { Set<InternalQName> supers = nodeTypeDataManager.getSupertypes(nodeTypeData.getName()); NodeType[] superTypes = new NodeType[supers.size()]; int i = 0; for (InternalQName nodeTypeName : supers) { try { superTypes[i++] = nodeTypeManager.findNodeType(nodeTypeName); } catch (NoSuchNodeTypeException e) { LOG.error(e.getLocalizedMessage(), e); } catch (RepositoryException e) { LOG.error(e.getLocalizedMessage(), e); } } return superTypes; } }
public class class_name { public NodeType[] getSupertypes() { Set<InternalQName> supers = nodeTypeDataManager.getSupertypes(nodeTypeData.getName()); NodeType[] superTypes = new NodeType[supers.size()]; int i = 0; for (InternalQName nodeTypeName : supers) { try { superTypes[i++] = nodeTypeManager.findNodeType(nodeTypeName); // depends on control dependency: [try], data = [none] } catch (NoSuchNodeTypeException e) { LOG.error(e.getLocalizedMessage(), e); } // depends on control dependency: [catch], data = [none] catch (RepositoryException e) { LOG.error(e.getLocalizedMessage(), e); } // depends on control dependency: [catch], data = [none] } return superTypes; } }
public class class_name { public static PermutationMatrix fromPartialPivots(int[] pivots) { int[] permutations = new int[pivots.length]; for (int i = 0; i < pivots.length; i++) { permutations[i] = i; } for (int i = 0; i < pivots.length; i++) { int j = pivots[i] - 1; if (j == i) continue; int tmp = permutations[i]; permutations[i] = permutations[j]; permutations[j] = tmp; } return new PermutationMatrix(permutations, pivots); } }
public class class_name { public static PermutationMatrix fromPartialPivots(int[] pivots) { int[] permutations = new int[pivots.length]; for (int i = 0; i < pivots.length; i++) { permutations[i] = i; // depends on control dependency: [for], data = [i] } for (int i = 0; i < pivots.length; i++) { int j = pivots[i] - 1; if (j == i) continue; int tmp = permutations[i]; permutations[i] = permutations[j]; // depends on control dependency: [for], data = [i] permutations[j] = tmp; // depends on control dependency: [for], data = [none] } return new PermutationMatrix(permutations, pivots); } }
public class class_name { private String buildInternalForm() { StringBuffer result = new StringBuffer(128); CmsResource resource = null; boolean internal = false; // try to read the internal flag from the resource try { resource = getCms().readResource(getParamResource(), CmsResourceFilter.ALL); internal = resource.isInternal(); } catch (CmsException e) { // an error occurred reading the resource LOG.error(e.getLocalizedMessage()); } if ((resource != null) && (resource.isFile())) { // only show internal check box on files result.append("<form action=\"").append(getDialogUri()).append( "\" method=\"post\" name=\"internal\" class=\"nomargin\">\n"); result.append("<table border=\"0\" width=\"100%\">\n"); result.append("<tr>\n"); result.append("\t<td class=\"dialogpermissioncell\">").append(key(Messages.GUI_PERMISSION_INTERNAL_0)); result.append(" <input type=\"checkbox\" name=\""); result.append(PARAM_INTERNAL); result.append("\" value=\"true\""); if (internal) { result.append(" checked=\"checked\""); } if (!getEditable()) { result.append(" disabled=\"disabled\""); } result.append(" ></td>\n"); if (getEditable()) { result.append("<td><input type=\"submit\" class=\"dialogbutton\" value=\"").append( key(Messages.GUI_LABEL_SET_0)).append("\">"); } result.append("</td>\n"); result.append("</tr>\n"); result.append("</table>\n"); setParamAction(DIALOG_INTERNALUSE); setParamType(null); setParamName(null); result.append(paramsAsHidden()); result.append("</form>\n"); } return result.toString(); } }
public class class_name { private String buildInternalForm() { StringBuffer result = new StringBuffer(128); CmsResource resource = null; boolean internal = false; // try to read the internal flag from the resource try { resource = getCms().readResource(getParamResource(), CmsResourceFilter.ALL); // depends on control dependency: [try], data = [none] internal = resource.isInternal(); // depends on control dependency: [try], data = [none] } catch (CmsException e) { // an error occurred reading the resource LOG.error(e.getLocalizedMessage()); } // depends on control dependency: [catch], data = [none] if ((resource != null) && (resource.isFile())) { // only show internal check box on files result.append("<form action=\"").append(getDialogUri()).append( "\" method=\"post\" name=\"internal\" class=\"nomargin\">\n"); // depends on control dependency: [if], data = [none] result.append("<table border=\"0\" width=\"100%\">\n"); // depends on control dependency: [if], data = [none] result.append("<tr>\n"); // depends on control dependency: [if], data = [none] result.append("\t<td class=\"dialogpermissioncell\">").append(key(Messages.GUI_PERMISSION_INTERNAL_0)); result.append(" <input type=\"checkbox\" name=\""); // depends on control dependency: [if], data = [none] result.append(PARAM_INTERNAL); // depends on control dependency: [if], data = [none] result.append("\" value=\"true\""); // depends on control dependency: [if], data = [none] if (internal) { result.append(" checked=\"checked\""); // depends on control dependency: [if], data = [none] } if (!getEditable()) { result.append(" disabled=\"disabled\""); // depends on control dependency: [if], data = [none] } result.append(" ></td>\n"); // depends on control dependency: [if], data = [none] if (getEditable()) { result.append("<td><input type=\"submit\" class=\"dialogbutton\" value=\"").append( key(Messages.GUI_LABEL_SET_0)).append("\">"); // depends on control dependency: [if], data = [none] } result.append("</td>\n"); // depends on control dependency: [if], data = [none] result.append("</tr>\n"); // depends on control dependency: [if], data = [none] result.append("</table>\n"); // depends on control dependency: [if], data = [none] setParamAction(DIALOG_INTERNALUSE); // depends on control dependency: [if], data = [none] setParamType(null); // depends on control dependency: [if], data = [none] setParamName(null); // depends on control dependency: [if], data = [none] result.append(paramsAsHidden()); // depends on control dependency: [if], data = [none] result.append("</form>\n"); // depends on control dependency: [if], data = [none] } return result.toString(); } }
public class class_name { public void match(ByteBuffer data, int size, IMtrieHandler func, XPub pub) { assert (data != null); assert (func != null); assert (pub != null); Mtrie current = this; int idx = 0; while (true) { // Signal the pipes attached to this node. if (current.pipes != null) { for (Pipe it : current.pipes) { func.invoke(it, null, 0, pub); } } // If we are at the end of the message, there's nothing more to match. if (size == 0) { break; } // If there are no subnodes in the trie, return. if (current.count == 0) { break; } byte c = data.get(idx); // If there's one subnode (optimisation). if (current.count == 1) { if (c != current.min) { break; } current = current.next[0]; idx++; size--; continue; } // If there are multiple subnodes. if (c < current.min || c >= current.min + current.count) { break; } if (current.next[c - current.min] == null) { break; } current = current.next[c - current.min]; idx++; size--; } } }
public class class_name { public void match(ByteBuffer data, int size, IMtrieHandler func, XPub pub) { assert (data != null); assert (func != null); assert (pub != null); Mtrie current = this; int idx = 0; while (true) { // Signal the pipes attached to this node. if (current.pipes != null) { for (Pipe it : current.pipes) { func.invoke(it, null, 0, pub); // depends on control dependency: [for], data = [it] } } // If we are at the end of the message, there's nothing more to match. if (size == 0) { break; } // If there are no subnodes in the trie, return. if (current.count == 0) { break; } byte c = data.get(idx); // If there's one subnode (optimisation). if (current.count == 1) { if (c != current.min) { break; } current = current.next[0]; // depends on control dependency: [if], data = [none] idx++; // depends on control dependency: [if], data = [none] size--; // depends on control dependency: [if], data = [none] continue; } // If there are multiple subnodes. if (c < current.min || c >= current.min + current.count) { break; } if (current.next[c - current.min] == null) { break; } current = current.next[c - current.min]; // depends on control dependency: [while], data = [none] idx++; // depends on control dependency: [while], data = [none] size--; // depends on control dependency: [while], data = [none] } } }
public class class_name { public static boolean hasDirectAnnotationWithSimpleName(Symbol sym, String simpleName) { for (AnnotationMirror annotation : sym.getAnnotationMirrors()) { if (annotation.getAnnotationType().asElement().getSimpleName().contentEquals(simpleName)) { return true; } } return false; } }
public class class_name { public static boolean hasDirectAnnotationWithSimpleName(Symbol sym, String simpleName) { for (AnnotationMirror annotation : sym.getAnnotationMirrors()) { if (annotation.getAnnotationType().asElement().getSimpleName().contentEquals(simpleName)) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { private static boolean statisticsObjectCheck(final ExecutorInfo statisticsObj1, final ExecutorInfo statisticsObj2, final String caller) { // both doesn't expose the info if (null == statisticsObj1 && null == statisticsObj2) { logger.debug(String.format("%s : neither of the executors exposed statistics info.", caller)); return true; } //right side doesn't expose the info. if (null == statisticsObj2) { logger.debug(String.format( "%s : choosing left side and the right side executor doesn't expose statistics info", caller)); return true; } //left side doesn't expose the info. if (null == statisticsObj1) { logger.debug(String.format( "%s : choosing right side and the left side executor doesn't expose statistics info", caller)); return true; } // both not null return false; } }
public class class_name { private static boolean statisticsObjectCheck(final ExecutorInfo statisticsObj1, final ExecutorInfo statisticsObj2, final String caller) { // both doesn't expose the info if (null == statisticsObj1 && null == statisticsObj2) { logger.debug(String.format("%s : neither of the executors exposed statistics info.", caller)); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } //right side doesn't expose the info. if (null == statisticsObj2) { logger.debug(String.format( "%s : choosing left side and the right side executor doesn't expose statistics info", caller)); return true; } //left side doesn't expose the info. if (null == statisticsObj1) { logger.debug(String.format( "%s : choosing right side and the left side executor doesn't expose statistics info", caller)); return true; } // both not null return false; } }
public class class_name { private void processMethodAnnotations(Method method, String[] classMappingIds) { // is there a @URLAction annotation on the class? URLAction actionAnnotation = method.getAnnotation(URLAction.class); if (actionAnnotation != null) { processPrettyActionAnnotation(actionAnnotation, method, classMappingIds); } // is there a @URLAction container annotation on the class? URLActions actionsAnnotation = method.getAnnotation(URLActions.class); if (actionsAnnotation != null) { // process all @URLAction annotations for (URLAction child : actionsAnnotation.actions()) { processPrettyActionAnnotation(child, method, classMappingIds); } } } }
public class class_name { private void processMethodAnnotations(Method method, String[] classMappingIds) { // is there a @URLAction annotation on the class? URLAction actionAnnotation = method.getAnnotation(URLAction.class); if (actionAnnotation != null) { processPrettyActionAnnotation(actionAnnotation, method, classMappingIds); // depends on control dependency: [if], data = [(actionAnnotation] } // is there a @URLAction container annotation on the class? URLActions actionsAnnotation = method.getAnnotation(URLActions.class); if (actionsAnnotation != null) { // process all @URLAction annotations for (URLAction child : actionsAnnotation.actions()) { processPrettyActionAnnotation(child, method, classMappingIds); // depends on control dependency: [for], data = [child] } } } }
public class class_name { public static Type[] getTypeArguments(Type type) { if (null == type) { return null; } final ParameterizedType parameterizedType = toParameterizedType(type); return (null == parameterizedType) ? null : parameterizedType.getActualTypeArguments(); } }
public class class_name { public static Type[] getTypeArguments(Type type) { if (null == type) { return null; // depends on control dependency: [if], data = [none] } final ParameterizedType parameterizedType = toParameterizedType(type); return (null == parameterizedType) ? null : parameterizedType.getActualTypeArguments(); } }
public class class_name { void build(String namespace, String name, String nameAlias, XSLTElementDef[] elements, XSLTAttributeDef[] attributes, XSLTElementProcessor contentHandler, Class classObject) { this.m_namespace = namespace; this.m_name = name; this.m_nameAlias = nameAlias; this.m_elements = elements; this.m_attributes = attributes; setElementProcessor(contentHandler); this.m_classObject = classObject; if (hasRequired() && m_elements != null) { int n = m_elements.length; for (int i = 0; i < n; i++) { XSLTElementDef def = m_elements[i]; if (def != null && def.getRequired()) { if (m_requiredFound == null) m_requiredFound = new Hashtable(); m_requiredFound.put(def.getName(), "xsl:" +def.getName()); } } } } }
public class class_name { void build(String namespace, String name, String nameAlias, XSLTElementDef[] elements, XSLTAttributeDef[] attributes, XSLTElementProcessor contentHandler, Class classObject) { this.m_namespace = namespace; this.m_name = name; this.m_nameAlias = nameAlias; this.m_elements = elements; this.m_attributes = attributes; setElementProcessor(contentHandler); this.m_classObject = classObject; if (hasRequired() && m_elements != null) { int n = m_elements.length; for (int i = 0; i < n; i++) { XSLTElementDef def = m_elements[i]; if (def != null && def.getRequired()) { if (m_requiredFound == null) m_requiredFound = new Hashtable(); m_requiredFound.put(def.getName(), "xsl:" +def.getName()); // depends on control dependency: [if], data = [(def] } } } } }
public class class_name { protected void printDeadClassConstant(VariableDeclarationFragment fragment) { VariableElement var = fragment.getVariableElement(); Object value = var.getConstantValue(); assert value != null; String declType = getDeclarationType(var); declType += (declType.endsWith("*") ? "" : " "); String name = nameTable.getVariableShortName(var); if (ElementUtil.isPrimitiveConstant(var)) { printf("#define %s_%s %s\n", typeName, name, LiteralGenerator.generate(value)); } else { println("FOUNDATION_EXPORT " + UnicodeUtils.format("%s%s_%s", declType, typeName, name) + ";"); } } }
public class class_name { protected void printDeadClassConstant(VariableDeclarationFragment fragment) { VariableElement var = fragment.getVariableElement(); Object value = var.getConstantValue(); assert value != null; String declType = getDeclarationType(var); declType += (declType.endsWith("*") ? "" : " "); String name = nameTable.getVariableShortName(var); if (ElementUtil.isPrimitiveConstant(var)) { printf("#define %s_%s %s\n", typeName, name, LiteralGenerator.generate(value)); // depends on control dependency: [if], data = [none] } else { println("FOUNDATION_EXPORT " + UnicodeUtils.format("%s%s_%s", declType, typeName, name) + ";"); // depends on control dependency: [if], data = [none] } } }
public class class_name { private MultiValueMap<String, String> buildFormParameters(OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest) { ClientRegistration clientRegistration = clientCredentialsGrantRequest.getClientRegistration(); MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>(); formParameters.add(OAuth2ParameterNames.GRANT_TYPE, clientCredentialsGrantRequest.getGrantType().getValue()); if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) { formParameters.add(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(clientRegistration.getScopes(), " ")); } if (ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod())) { formParameters.add(OAuth2ParameterNames.CLIENT_ID, clientRegistration.getClientId()); formParameters.add(OAuth2ParameterNames.CLIENT_SECRET, clientRegistration.getClientSecret()); } return formParameters; } }
public class class_name { private MultiValueMap<String, String> buildFormParameters(OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest) { ClientRegistration clientRegistration = clientCredentialsGrantRequest.getClientRegistration(); MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>(); formParameters.add(OAuth2ParameterNames.GRANT_TYPE, clientCredentialsGrantRequest.getGrantType().getValue()); if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) { formParameters.add(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(clientRegistration.getScopes(), " ")); // depends on control dependency: [if], data = [none] } if (ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod())) { formParameters.add(OAuth2ParameterNames.CLIENT_ID, clientRegistration.getClientId()); // depends on control dependency: [if], data = [none] formParameters.add(OAuth2ParameterNames.CLIENT_SECRET, clientRegistration.getClientSecret()); // depends on control dependency: [if], data = [none] } return formParameters; } }
public class class_name { public ClassNode extractStaticReceiver(MethodCall call) { if (call instanceof StaticMethodCallExpression) { return ((StaticMethodCallExpression) call).getOwnerType(); } else if (call instanceof MethodCallExpression) { Expression objectExpr = ((MethodCallExpression) call).getObjectExpression(); if (objectExpr instanceof ClassExpression && ClassHelper.CLASS_Type.equals(objectExpr.getType())) { GenericsType[] genericsTypes = objectExpr.getType().getGenericsTypes(); if (genericsTypes!=null && genericsTypes.length==1) { return genericsTypes[0].getType(); } } if (objectExpr instanceof ClassExpression) { return objectExpr.getType(); } } return null; } }
public class class_name { public ClassNode extractStaticReceiver(MethodCall call) { if (call instanceof StaticMethodCallExpression) { return ((StaticMethodCallExpression) call).getOwnerType(); // depends on control dependency: [if], data = [none] } else if (call instanceof MethodCallExpression) { Expression objectExpr = ((MethodCallExpression) call).getObjectExpression(); if (objectExpr instanceof ClassExpression && ClassHelper.CLASS_Type.equals(objectExpr.getType())) { GenericsType[] genericsTypes = objectExpr.getType().getGenericsTypes(); if (genericsTypes!=null && genericsTypes.length==1) { return genericsTypes[0].getType(); // depends on control dependency: [if], data = [none] } } if (objectExpr instanceof ClassExpression) { return objectExpr.getType(); // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public void passivate() { // Notify ActivationListeners SipApplicationSessionEvent event = null; if(this.sipApplicationSessionAttributeMap != null) { Set<String> keySet = getAttributeMap().keySet(); for (String key : keySet) { Object attribute = getAttributeMap().get(key); if (attribute instanceof SipApplicationSessionActivationListener) { if (event == null) event = new SipApplicationSessionActivationEvent(this, SessionActivationNotificationCause.PASSIVATION); try { ((SipApplicationSessionActivationListener)attribute) .sessionWillPassivate(event); } catch (Throwable t) { logger.error("SipApplicationSessionActivationListener threw exception", t); } } } } } }
public class class_name { public void passivate() { // Notify ActivationListeners SipApplicationSessionEvent event = null; if(this.sipApplicationSessionAttributeMap != null) { Set<String> keySet = getAttributeMap().keySet(); for (String key : keySet) { Object attribute = getAttributeMap().get(key); if (attribute instanceof SipApplicationSessionActivationListener) { if (event == null) event = new SipApplicationSessionActivationEvent(this, SessionActivationNotificationCause.PASSIVATION); try { ((SipApplicationSessionActivationListener)attribute) .sessionWillPassivate(event); // depends on control dependency: [try], data = [none] } catch (Throwable t) { logger.error("SipApplicationSessionActivationListener threw exception", t); } // depends on control dependency: [catch], data = [none] } } } } }
public class class_name { private String extractIPV6Brackets(String host) { String ret = host; // IPv6 here, remove square brackets if (host.indexOf(':') != -1) { int startPoint = host.indexOf('['); int endPoint = host.indexOf(']'); if (endPoint == -1) endPoint = host.length(); if (startPoint != -1) { ret = host.substring(startPoint + 1, endPoint); } else { ret = host.substring(0, endPoint); } } return ret; } }
public class class_name { private String extractIPV6Brackets(String host) { String ret = host; // IPv6 here, remove square brackets if (host.indexOf(':') != -1) { int startPoint = host.indexOf('['); int endPoint = host.indexOf(']'); if (endPoint == -1) endPoint = host.length(); if (startPoint != -1) { ret = host.substring(startPoint + 1, endPoint); // depends on control dependency: [if], data = [(startPoint] } else { ret = host.substring(0, endPoint); // depends on control dependency: [if], data = [none] } } return ret; } }
public class class_name { public void beforeSuite(String suiteName, String ... testGroups) { testSuiteListener.onStart(); if (!CollectionUtils.isEmpty(beforeSuite)) { for (SequenceBeforeSuite sequenceBeforeSuite : beforeSuite) { try { if (sequenceBeforeSuite.shouldExecute(suiteName, testGroups)) { sequenceBeforeSuite.execute(createTestContext()); } } catch (Exception e) { testSuiteListener.onStartFailure(e); afterSuite(suiteName, testGroups); throw new AssertionError("Before suite failed with errors", e); } } testSuiteListener.onStartSuccess(); } else { testSuiteListener.onStartSuccess(); } } }
public class class_name { public void beforeSuite(String suiteName, String ... testGroups) { testSuiteListener.onStart(); if (!CollectionUtils.isEmpty(beforeSuite)) { for (SequenceBeforeSuite sequenceBeforeSuite : beforeSuite) { try { if (sequenceBeforeSuite.shouldExecute(suiteName, testGroups)) { sequenceBeforeSuite.execute(createTestContext()); // depends on control dependency: [if], data = [none] } } catch (Exception e) { testSuiteListener.onStartFailure(e); afterSuite(suiteName, testGroups); throw new AssertionError("Before suite failed with errors", e); } // depends on control dependency: [catch], data = [none] } testSuiteListener.onStartSuccess(); // depends on control dependency: [if], data = [none] } else { testSuiteListener.onStartSuccess(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void executeJob(String jobName) throws MangooSchedulerException { Objects.requireNonNull(this.quartzScheduler, Required.SCHEDULER.toString()); Objects.requireNonNull(jobName, Required.JOB_NAME.toString()); try { for (JobKey jobKey : getAllJobKeys()) { if (jobKey.getName().equalsIgnoreCase(jobName)) { this.quartzScheduler.triggerJob(jobKey); } } } catch (SchedulerException | MangooSchedulerException e) { throw new MangooSchedulerException(e); } } }
public class class_name { public void executeJob(String jobName) throws MangooSchedulerException { Objects.requireNonNull(this.quartzScheduler, Required.SCHEDULER.toString()); Objects.requireNonNull(jobName, Required.JOB_NAME.toString()); try { for (JobKey jobKey : getAllJobKeys()) { if (jobKey.getName().equalsIgnoreCase(jobName)) { this.quartzScheduler.triggerJob(jobKey); // depends on control dependency: [if], data = [none] } } } catch (SchedulerException | MangooSchedulerException e) { throw new MangooSchedulerException(e); } } }
public class class_name { public Observable<ServiceResponse<List<Domain>>> getDomainsWithServiceResponseAsync() { if (this.client.apiKey() == null) { throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null."); } return service.getDomains(this.client.apiKey(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<Domain>>>>() { @Override public Observable<ServiceResponse<List<Domain>>> call(Response<ResponseBody> response) { try { ServiceResponse<List<Domain>> clientResponse = getDomainsDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } }
public class class_name { public Observable<ServiceResponse<List<Domain>>> getDomainsWithServiceResponseAsync() { if (this.client.apiKey() == null) { throw new IllegalArgumentException("Parameter this.client.apiKey() is required and cannot be null."); } return service.getDomains(this.client.apiKey(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<Domain>>>>() { @Override public Observable<ServiceResponse<List<Domain>>> call(Response<ResponseBody> response) { try { ServiceResponse<List<Domain>> clientResponse = getDomainsDelegate(response); return Observable.just(clientResponse); // depends on control dependency: [try], data = [none] } catch (Throwable t) { return Observable.error(t); } // depends on control dependency: [catch], data = [none] } }); } }
public class class_name { private RPCBatchRequestSender getBatchRequestSender() { RPCBatchRequestSender sender = null; // test the last sender we have in the list if( !batchRequestSenders.isEmpty() ) { sender = batchRequestSenders.get( batchRequestSenders.size() - 1 ); if( sender.canAddRequest() ) return sender; } // otherwise, create a new one sender = new RPCBatchRequestSender(); sender.init( baseUrl, batchSenderCallback ); batchRequestSenders.add( sender ); return sender; } }
public class class_name { private RPCBatchRequestSender getBatchRequestSender() { RPCBatchRequestSender sender = null; // test the last sender we have in the list if( !batchRequestSenders.isEmpty() ) { sender = batchRequestSenders.get( batchRequestSenders.size() - 1 ); // depends on control dependency: [if], data = [none] if( sender.canAddRequest() ) return sender; } // otherwise, create a new one sender = new RPCBatchRequestSender(); sender.init( baseUrl, batchSenderCallback ); batchRequestSenders.add( sender ); return sender; } }
public class class_name { public LdapSearcher search(String context, String filterExpr, Object... filterArgs) { searchResults.clear(); LdapContext ldapContext = null; NamingEnumeration<SearchResult> ldapResult = null; try { ldapContext = buildLdapContext(); ldapResult = ldapContext.search(context, filterExpr, filterArgs, createSearchControls()); while (ldapResult.hasMore()) { searchResults.add(ldapResult.next()); } } catch (NamingException ex) { throw new RuntimeException("LDAP search has failed", ex); } finally { if (ldapResult != null) { try { ldapResult.close(); } catch (NamingException ex) { log.error("Failed to close LDAP results enumeration", ex); } } if (ldapContext != null) { try { ldapContext.close(); } catch (NamingException ex) { log.error("Failed to close LDAP context", ex); } } } return this; } }
public class class_name { public LdapSearcher search(String context, String filterExpr, Object... filterArgs) { searchResults.clear(); LdapContext ldapContext = null; NamingEnumeration<SearchResult> ldapResult = null; try { ldapContext = buildLdapContext(); // depends on control dependency: [try], data = [none] ldapResult = ldapContext.search(context, filterExpr, filterArgs, createSearchControls()); // depends on control dependency: [try], data = [none] while (ldapResult.hasMore()) { searchResults.add(ldapResult.next()); // depends on control dependency: [while], data = [none] } } catch (NamingException ex) { throw new RuntimeException("LDAP search has failed", ex); } finally { // depends on control dependency: [catch], data = [none] if (ldapResult != null) { try { ldapResult.close(); // depends on control dependency: [try], data = [none] } catch (NamingException ex) { log.error("Failed to close LDAP results enumeration", ex); } // depends on control dependency: [catch], data = [none] } if (ldapContext != null) { try { ldapContext.close(); // depends on control dependency: [try], data = [none] } catch (NamingException ex) { log.error("Failed to close LDAP context", ex); } // depends on control dependency: [catch], data = [none] } } return this; } }
public class class_name { public Object createInstanceQuietly() { try { return clazz.newInstance(); } catch (InstantiationException e) { log.finest(e); return null; } catch (IllegalAccessException e) { log.finest(e); return null; } } }
public class class_name { public Object createInstanceQuietly() { try { return clazz.newInstance(); // depends on control dependency: [try], data = [none] } catch (InstantiationException e) { log.finest(e); return null; } catch (IllegalAccessException e) { // depends on control dependency: [catch], data = [none] log.finest(e); return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public void cacheResult( List<CommerceUserSegmentEntry> commerceUserSegmentEntries) { for (CommerceUserSegmentEntry commerceUserSegmentEntry : commerceUserSegmentEntries) { if (entityCache.getResult( CommerceUserSegmentEntryModelImpl.ENTITY_CACHE_ENABLED, CommerceUserSegmentEntryImpl.class, commerceUserSegmentEntry.getPrimaryKey()) == null) { cacheResult(commerceUserSegmentEntry); } else { commerceUserSegmentEntry.resetOriginalValues(); } } } }
public class class_name { @Override public void cacheResult( List<CommerceUserSegmentEntry> commerceUserSegmentEntries) { for (CommerceUserSegmentEntry commerceUserSegmentEntry : commerceUserSegmentEntries) { if (entityCache.getResult( CommerceUserSegmentEntryModelImpl.ENTITY_CACHE_ENABLED, CommerceUserSegmentEntryImpl.class, commerceUserSegmentEntry.getPrimaryKey()) == null) { cacheResult(commerceUserSegmentEntry); // depends on control dependency: [if], data = [none] } else { commerceUserSegmentEntry.resetOriginalValues(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { @SuppressWarnings("unchecked") private void loadListRelation(List<?> obj, String path) { if(obj.size() <= 0){ return; } if(obj.get(0) instanceof String){ relation.put(path, (List<String>) obj); return; } loadRelation(obj.get(0), path + "[]"); } }
public class class_name { @SuppressWarnings("unchecked") private void loadListRelation(List<?> obj, String path) { if(obj.size() <= 0){ return; // depends on control dependency: [if], data = [none] } if(obj.get(0) instanceof String){ relation.put(path, (List<String>) obj); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } loadRelation(obj.get(0), path + "[]"); } }
public class class_name { static long getDateHeader(final String pHeaderValue) { long date = -1L; if (pHeaderValue != null) { date = HTTPUtil.parseHTTPDate(pHeaderValue); } return date; } }
public class class_name { static long getDateHeader(final String pHeaderValue) { long date = -1L; if (pHeaderValue != null) { date = HTTPUtil.parseHTTPDate(pHeaderValue); // depends on control dependency: [if], data = [(pHeaderValue] } return date; } }
public class class_name { public static Iterable<MutableIntTuple> mooreNeighborhoodIterable( IntTuple center, final int radius, IntTuple min, IntTuple max, Order order) { Objects.requireNonNull(order, "The order is null"); if (min != null) { Utils.checkForEqualSize(center, min); } if (max != null) { Utils.checkForEqualSize(center, max); } final IntTuple localCenter = IntTuples.copy(center); final IntTuple localMin = min == null ? null : IntTuples.copy(min); final IntTuple localMax = max == null ? null : IntTuples.copy(max); return () -> IntTupleNeighborhoodIterators.mooreNeighborhoodIterator( localCenter, radius, localMin, localMax, order); } }
public class class_name { public static Iterable<MutableIntTuple> mooreNeighborhoodIterable( IntTuple center, final int radius, IntTuple min, IntTuple max, Order order) { Objects.requireNonNull(order, "The order is null"); if (min != null) { Utils.checkForEqualSize(center, min); // depends on control dependency: [if], data = [none] } if (max != null) { Utils.checkForEqualSize(center, max); // depends on control dependency: [if], data = [none] } final IntTuple localCenter = IntTuples.copy(center); final IntTuple localMin = min == null ? null : IntTuples.copy(min); final IntTuple localMax = max == null ? null : IntTuples.copy(max); return () -> IntTupleNeighborhoodIterators.mooreNeighborhoodIterator( localCenter, radius, localMin, localMax, order); } }
public class class_name { public static String getSignatureHexCode(Context context, String targetPackageName) { if (TextUtils.isEmpty(targetPackageName)) { return null; } try { PackageInfo info = PackageManagerUtils.getSignaturePackageInfo(context, targetPackageName); if (info.signatures.length != 1) { // multiple signature would not treated return null; } Signature sig = info.signatures[0]; byte[] sha256 = MessageDigestUtils.computeSha256(sig.toByteArray()); return StringUtils.byteToHex(sha256); } catch (NameNotFoundException e) { Log.e(TAG, "target package not found: ", e); return null; } } }
public class class_name { public static String getSignatureHexCode(Context context, String targetPackageName) { if (TextUtils.isEmpty(targetPackageName)) { return null; // depends on control dependency: [if], data = [none] } try { PackageInfo info = PackageManagerUtils.getSignaturePackageInfo(context, targetPackageName); if (info.signatures.length != 1) { // multiple signature would not treated return null; // depends on control dependency: [if], data = [none] } Signature sig = info.signatures[0]; byte[] sha256 = MessageDigestUtils.computeSha256(sig.toByteArray()); return StringUtils.byteToHex(sha256); // depends on control dependency: [try], data = [none] } catch (NameNotFoundException e) { Log.e(TAG, "target package not found: ", e); return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public String getRemoteDirForNode( final INodeEntry node, final IRundeckProject project, final IFramework framework ) { String pathSeparator = "/"; String remotedir = "/tmp/"; String osfamily = null != node.getOsFamily() ? node.getOsFamily().trim().toLowerCase() : "unix"; if ("windows".equalsIgnoreCase(osfamily)) { pathSeparator = "\\"; remotedir = "C:\\WINDOWS\\TEMP\\"; } //node specific if (null != node.getAttributes() && null != node.getAttributes().get(FILE_COPY_DESTINATION_DIR)) { String s = node.getAttributes().get(FILE_COPY_DESTINATION_DIR); return s.endsWith(pathSeparator) ? s : s + pathSeparator; } //project, os-specific if (null != project && project.hasProperty(PROJECT_FILE_COPY_DESTINATION_DIR + "." + osfamily)) { String s = project.getProperty(PROJECT_FILE_COPY_DESTINATION_DIR + "." + osfamily); return s.endsWith(pathSeparator) ? s : s + pathSeparator; } //project specific if (null != project && project.hasProperty(PROJECT_FILE_COPY_DESTINATION_DIR)) { String s = project.getProperty(PROJECT_FILE_COPY_DESTINATION_DIR); return s.endsWith(pathSeparator) ? s : s + pathSeparator; } //framework, os-specific if (null != framework && framework.getPropertyLookup().hasProperty( FRAMEWORK_FILE_COPY_DESTINATION_DIR + "." + osfamily )) { String s = framework.getPropertyLookup().getProperty(FRAMEWORK_FILE_COPY_DESTINATION_DIR + "." + osfamily); return s.endsWith(pathSeparator) ? s : s + pathSeparator; } //framework specific if (null != framework && framework.getPropertyLookup().hasProperty(FRAMEWORK_FILE_COPY_DESTINATION_DIR)) { String s = framework.getPropertyLookup().getProperty(FRAMEWORK_FILE_COPY_DESTINATION_DIR); return s.endsWith(pathSeparator) ? s : s + pathSeparator; } //default return remotedir; } }
public class class_name { @Override public String getRemoteDirForNode( final INodeEntry node, final IRundeckProject project, final IFramework framework ) { String pathSeparator = "/"; String remotedir = "/tmp/"; String osfamily = null != node.getOsFamily() ? node.getOsFamily().trim().toLowerCase() : "unix"; if ("windows".equalsIgnoreCase(osfamily)) { pathSeparator = "\\"; remotedir = "C:\\WINDOWS\\TEMP\\"; // depends on control dependency: [if], data = [none] } //node specific if (null != node.getAttributes() && null != node.getAttributes().get(FILE_COPY_DESTINATION_DIR)) { String s = node.getAttributes().get(FILE_COPY_DESTINATION_DIR); return s.endsWith(pathSeparator) ? s : s + pathSeparator; // depends on control dependency: [if], data = [none] } //project, os-specific if (null != project && project.hasProperty(PROJECT_FILE_COPY_DESTINATION_DIR + "." + osfamily)) { String s = project.getProperty(PROJECT_FILE_COPY_DESTINATION_DIR + "." + osfamily); return s.endsWith(pathSeparator) ? s : s + pathSeparator; // depends on control dependency: [if], data = [none] } //project specific if (null != project && project.hasProperty(PROJECT_FILE_COPY_DESTINATION_DIR)) { String s = project.getProperty(PROJECT_FILE_COPY_DESTINATION_DIR); return s.endsWith(pathSeparator) ? s : s + pathSeparator; // depends on control dependency: [if], data = [none] } //framework, os-specific if (null != framework && framework.getPropertyLookup().hasProperty( FRAMEWORK_FILE_COPY_DESTINATION_DIR + "." + osfamily )) { String s = framework.getPropertyLookup().getProperty(FRAMEWORK_FILE_COPY_DESTINATION_DIR + "." + osfamily); return s.endsWith(pathSeparator) ? s : s + pathSeparator; // depends on control dependency: [if], data = [] } //framework specific if (null != framework && framework.getPropertyLookup().hasProperty(FRAMEWORK_FILE_COPY_DESTINATION_DIR)) { String s = framework.getPropertyLookup().getProperty(FRAMEWORK_FILE_COPY_DESTINATION_DIR); return s.endsWith(pathSeparator) ? s : s + pathSeparator; // depends on control dependency: [if], data = [none] } //default return remotedir; } }
public class class_name { public void setInfo(String info) { m_info = info; if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_SET_INFO_1, info)); } } }
public class class_name { public void setInfo(String info) { m_info = info; if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_SET_INFO_1, info)); // depends on control dependency: [if], data = [none] } } }
public class class_name { protected double computeDelta(Evaluation currentEvaluation, Evaluation previousEvaluation){ if(problem.isMinimizing()){ // minimization: return decrease return previousEvaluation.getValue() - currentEvaluation.getValue(); } else { // maximization: return increase return currentEvaluation.getValue() - previousEvaluation.getValue(); } } }
public class class_name { protected double computeDelta(Evaluation currentEvaluation, Evaluation previousEvaluation){ if(problem.isMinimizing()){ // minimization: return decrease return previousEvaluation.getValue() - currentEvaluation.getValue(); // depends on control dependency: [if], data = [none] } else { // maximization: return increase return currentEvaluation.getValue() - previousEvaluation.getValue(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static void vertical(GrayF32 input, GrayF32 output, int radius, @Nullable FWorkArrays work) { InputSanityCheck.checkSameShape(input , output ); Kernel1D_F32 kernel = FactoryKernel.table1D_F32(radius,false); ConvolveJustBorder_General_SB.vertical(kernel,ImageBorderValue.wrap(input,0),output); if(BoofConcurrency.USE_CONCURRENT ) { ImplConvolveBox_MT.vertical(input, output, radius, work); } else { ImplConvolveBox.vertical(input, output, radius,work); } } }
public class class_name { public static void vertical(GrayF32 input, GrayF32 output, int radius, @Nullable FWorkArrays work) { InputSanityCheck.checkSameShape(input , output ); Kernel1D_F32 kernel = FactoryKernel.table1D_F32(radius,false); ConvolveJustBorder_General_SB.vertical(kernel,ImageBorderValue.wrap(input,0),output); if(BoofConcurrency.USE_CONCURRENT ) { ImplConvolveBox_MT.vertical(input, output, radius, work); // depends on control dependency: [if], data = [none] } else { ImplConvolveBox.vertical(input, output, radius,work); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void marshall(ListTargetsForPolicyRequest listTargetsForPolicyRequest, ProtocolMarshaller protocolMarshaller) { if (listTargetsForPolicyRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listTargetsForPolicyRequest.getPolicyId(), POLICYID_BINDING); protocolMarshaller.marshall(listTargetsForPolicyRequest.getNextToken(), NEXTTOKEN_BINDING); protocolMarshaller.marshall(listTargetsForPolicyRequest.getMaxResults(), MAXRESULTS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ListTargetsForPolicyRequest listTargetsForPolicyRequest, ProtocolMarshaller protocolMarshaller) { if (listTargetsForPolicyRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listTargetsForPolicyRequest.getPolicyId(), POLICYID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(listTargetsForPolicyRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(listTargetsForPolicyRequest.getMaxResults(), MAXRESULTS_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 { @Override public void onMessageRead(MessageReadEvent event) { for (IMessagingListener listener : messagingListeners) { try { listener.onMessageRead(event); } catch (Exception e) { logError(e, "message read "+event.getMessageId()); } } } }
public class class_name { @Override public void onMessageRead(MessageReadEvent event) { for (IMessagingListener listener : messagingListeners) { try { listener.onMessageRead(event); // depends on control dependency: [try], data = [none] } catch (Exception e) { logError(e, "message read "+event.getMessageId()); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { final void setInputFrameFromDescriptor( final SymbolTable symbolTable, final int access, final String descriptor, final int maxLocals) { inputLocals = new int[maxLocals]; inputStack = new int[0]; int inputLocalIndex = 0; if ((access & Opcodes.ACC_STATIC) == 0) { if ((access & Constants.ACC_CONSTRUCTOR) == 0) { inputLocals[inputLocalIndex++] = REFERENCE_KIND | symbolTable.addType(symbolTable.getClassName()); } else { inputLocals[inputLocalIndex++] = UNINITIALIZED_THIS; } } for (Type argumentType : Type.getArgumentTypes(descriptor)) { int abstractType = getAbstractTypeFromDescriptor(symbolTable, argumentType.getDescriptor(), 0); inputLocals[inputLocalIndex++] = abstractType; if (abstractType == LONG || abstractType == DOUBLE) { inputLocals[inputLocalIndex++] = TOP; } } while (inputLocalIndex < maxLocals) { inputLocals[inputLocalIndex++] = TOP; } } }
public class class_name { final void setInputFrameFromDescriptor( final SymbolTable symbolTable, final int access, final String descriptor, final int maxLocals) { inputLocals = new int[maxLocals]; inputStack = new int[0]; int inputLocalIndex = 0; if ((access & Opcodes.ACC_STATIC) == 0) { if ((access & Constants.ACC_CONSTRUCTOR) == 0) { inputLocals[inputLocalIndex++] = REFERENCE_KIND | symbolTable.addType(symbolTable.getClassName()); // depends on control dependency: [if], data = [none] } else { inputLocals[inputLocalIndex++] = UNINITIALIZED_THIS; // depends on control dependency: [if], data = [none] } } for (Type argumentType : Type.getArgumentTypes(descriptor)) { int abstractType = getAbstractTypeFromDescriptor(symbolTable, argumentType.getDescriptor(), 0); inputLocals[inputLocalIndex++] = abstractType; // depends on control dependency: [for], data = [none] if (abstractType == LONG || abstractType == DOUBLE) { inputLocals[inputLocalIndex++] = TOP; // depends on control dependency: [if], data = [none] } } while (inputLocalIndex < maxLocals) { inputLocals[inputLocalIndex++] = TOP; // depends on control dependency: [while], data = [none] } } }
public class class_name { private void validate(final WildcardContext wildcardContext) throws IOException { notNull(wildcardContext); final String uri = wildcardContext.getUri(); final File folder = wildcardContext.getFolder(); if (uri == null || folder == null || !folder.isDirectory()) { final StringBuffer message = new StringBuffer("Invalid folder provided"); if (folder != null) { message.append(", with path: ").append(folder.getPath()); } message.append(", with fileNameWithWildcard: ").append(uri); throw new IOException(message.toString()); } if (!hasWildcard(uri)) { throw new IOException("No wildcard detected for the uri: " + uri); } LOG.debug("uri: {}", uri); LOG.debug("folder: {}", folder.getPath()); LOG.debug("wildcard: {}", wildcardContext.getWildcard()); } }
public class class_name { private void validate(final WildcardContext wildcardContext) throws IOException { notNull(wildcardContext); final String uri = wildcardContext.getUri(); final File folder = wildcardContext.getFolder(); if (uri == null || folder == null || !folder.isDirectory()) { final StringBuffer message = new StringBuffer("Invalid folder provided"); if (folder != null) { message.append(", with path: ").append(folder.getPath()); // depends on control dependency: [if], data = [(folder] } message.append(", with fileNameWithWildcard: ").append(uri); throw new IOException(message.toString()); } if (!hasWildcard(uri)) { throw new IOException("No wildcard detected for the uri: " + uri); } LOG.debug("uri: {}", uri); LOG.debug("folder: {}", folder.getPath()); LOG.debug("wildcard: {}", wildcardContext.getWildcard()); } }
public class class_name { public void setVpcSecurityGroups(java.util.Collection<VpcSecurityGroupMembership> vpcSecurityGroups) { if (vpcSecurityGroups == null) { this.vpcSecurityGroups = null; return; } this.vpcSecurityGroups = new java.util.ArrayList<VpcSecurityGroupMembership>(vpcSecurityGroups); } }
public class class_name { public void setVpcSecurityGroups(java.util.Collection<VpcSecurityGroupMembership> vpcSecurityGroups) { if (vpcSecurityGroups == null) { this.vpcSecurityGroups = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.vpcSecurityGroups = new java.util.ArrayList<VpcSecurityGroupMembership>(vpcSecurityGroups); } }
public class class_name { public FEELFnResult<Object> evaluate(EvaluationContext ctx, Object[] params) { if ( decisionRules.isEmpty() ) { return FEELFnResult.ofError(new FEELEventBase(Severity.WARN, "Decision table is empty", null)); } Object[] actualInputs = resolveActualInputs( ctx, feel ); Either<FEELEvent, Object> actualInputMatch = actualInputsMatchInputValues( ctx, actualInputs ); if ( actualInputMatch.isLeft() ) { return actualInputMatch.cata( e -> FEELFnResult.ofError(e), e -> FEELFnResult.ofError(null) ); } List<DTDecisionRule> matches = findMatches( ctx, actualInputs ); if( !matches.isEmpty() ) { List<Object> results = evaluateResults( ctx, feel, actualInputs, matches ); Map<Integer, String> msgs = checkResults( ctx, matches, results ); if( msgs.isEmpty() ) { Object result = hitPolicy.getDti().dti( ctx, this, matches, results ); return FEELFnResult.ofResult( result ); } else { List<Integer> offending = msgs.keySet().stream().collect( Collectors.toList()); return FEELFnResult.ofError( new HitPolicyViolationEvent( Severity.ERROR, "Errors found evaluating decision table '"+getName()+"': \n"+(msgs.values().stream().collect( Collectors.joining( "\n" ) )), name, offending ) ); } } else { // check if there is a default value set for the outputs if( hasDefaultValues ) { Object result = defaultToOutput( ctx, feel ); return FEELFnResult.ofResult( result ); } else { if( hitPolicy.getDefaultValue() != null ) { return FEELFnResult.ofResult( hitPolicy.getDefaultValue() ); } return FEELFnResult.ofError( new HitPolicyViolationEvent( Severity.WARN, "No rule matched for decision table '" + name + "' and no default values were defined. Setting result to null.", name, Collections.EMPTY_LIST ) ); } } } }
public class class_name { public FEELFnResult<Object> evaluate(EvaluationContext ctx, Object[] params) { if ( decisionRules.isEmpty() ) { return FEELFnResult.ofError(new FEELEventBase(Severity.WARN, "Decision table is empty", null)); // depends on control dependency: [if], data = [none] } Object[] actualInputs = resolveActualInputs( ctx, feel ); Either<FEELEvent, Object> actualInputMatch = actualInputsMatchInputValues( ctx, actualInputs ); if ( actualInputMatch.isLeft() ) { return actualInputMatch.cata( e -> FEELFnResult.ofError(e), e -> FEELFnResult.ofError(null) ); // depends on control dependency: [if], data = [none] } List<DTDecisionRule> matches = findMatches( ctx, actualInputs ); if( !matches.isEmpty() ) { List<Object> results = evaluateResults( ctx, feel, actualInputs, matches ); Map<Integer, String> msgs = checkResults( ctx, matches, results ); if( msgs.isEmpty() ) { Object result = hitPolicy.getDti().dti( ctx, this, matches, results ); return FEELFnResult.ofResult( result ); // depends on control dependency: [if], data = [none] } else { List<Integer> offending = msgs.keySet().stream().collect( Collectors.toList()); return FEELFnResult.ofError( new HitPolicyViolationEvent( Severity.ERROR, "Errors found evaluating decision table '"+getName()+"': \n"+(msgs.values().stream().collect( Collectors.joining( "\n" ) )), name, offending ) ); // depends on control dependency: [if], data = [none] } } else { // check if there is a default value set for the outputs if( hasDefaultValues ) { Object result = defaultToOutput( ctx, feel ); return FEELFnResult.ofResult( result ); // depends on control dependency: [if], data = [none] } else { if( hitPolicy.getDefaultValue() != null ) { return FEELFnResult.ofResult( hitPolicy.getDefaultValue() ); // depends on control dependency: [if], data = [( hitPolicy.getDefaultValue()] } return FEELFnResult.ofError( new HitPolicyViolationEvent( Severity.WARN, "No rule matched for decision table '" + name + "' and no default values were defined. Setting result to null.", name, Collections.EMPTY_LIST ) ); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public void pairsMatching(final IntDoubleProcedure condition, final IntArrayList keyList, final DoubleArrayList valueList) { keyList.clear(); valueList.clear(); for (int i = table.length ; i-- > 0 ;) { if (state[i]==FULL && condition.apply(table[i],values[i])) { keyList.add(table[i]); valueList.add(values[i]); } } } }
public class class_name { public void pairsMatching(final IntDoubleProcedure condition, final IntArrayList keyList, final DoubleArrayList valueList) { keyList.clear(); valueList.clear(); for (int i = table.length ; i-- > 0 ;) { if (state[i]==FULL && condition.apply(table[i],values[i])) { keyList.add(table[i]); // depends on control dependency: [if], data = [none] valueList.add(values[i]); // depends on control dependency: [if], data = [none] } } } }
public class class_name { protected void registerSuperClassMultipleJoinedTables(ClassDescriptor cld) { /* arminw: Sadly, we can't map to sub class-descriptor, because it's not guaranteed that they exist when this method is called. Thus we map the class instance instead of the class-descriptor. */ if(cld.getBaseClass() != null) { try { Class superClass = ClassHelper.getClass(cld.getBaseClass()); Class currentClass = cld.getClassOfObject(); synchronized(descriptorTable) { List subClasses = (List) superClassMultipleJoinedTablesMap.get(superClass); if(subClasses == null) { subClasses = new ArrayList(); superClassMultipleJoinedTablesMap.put(superClass, subClasses); } if(!subClasses.contains(currentClass)) { if(log.isDebugEnabled()) { log.debug("(MultipleJoinedTables): Register sub-class '" + currentClass + "' for class '" + superClass); } subClasses.add(currentClass); } } } catch(Exception e) { throw new MetadataException("Can't register super class '" + cld.getBaseClass() + "' for class-descriptor: " + cld, e); } } } }
public class class_name { protected void registerSuperClassMultipleJoinedTables(ClassDescriptor cld) { /* arminw: Sadly, we can't map to sub class-descriptor, because it's not guaranteed that they exist when this method is called. Thus we map the class instance instead of the class-descriptor. */ if(cld.getBaseClass() != null) { try { Class superClass = ClassHelper.getClass(cld.getBaseClass()); Class currentClass = cld.getClassOfObject(); synchronized(descriptorTable) { List subClasses = (List) superClassMultipleJoinedTablesMap.get(superClass); if(subClasses == null) { subClasses = new ArrayList(); superClassMultipleJoinedTablesMap.put(superClass, subClasses); } if(!subClasses.contains(currentClass)) { if(log.isDebugEnabled()) { log.debug("(MultipleJoinedTables): Register sub-class '" + currentClass + "' for class '" + superClass); // depends on control dependency: [if], data = [none] } subClasses.add(currentClass); // depends on control dependency: [if], data = [none] } } } catch(Exception e) { throw new MetadataException("Can't register super class '" + cld.getBaseClass() + "' for class-descriptor: " + cld, e); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public ExceptionHandlerImpl getHandler(Class<? extends Exception> exceptionClass) { // If the exception map does not contain the provided exception class, it might // still be that a superclass of the exception class is. if (!this.exceptionMap.containsKey(exceptionClass)) { Class<?> superclass = exceptionClass.getSuperclass(); do { // Is the superclass mapped? if (this.exceptionMap.containsKey(superclass)) { // Use the handler for the mapped superclass, and cache handler // for this exception class ExceptionHandlerImpl handler = this.exceptionMap.get(superclass); this.exceptionMap.put(exceptionClass, handler); return handler; } // Iteratively walk through the exception class's superclasses superclass = superclass.getSuperclass(); } while (superclass != null); // No handler found either for the superclasses of the exception class // We cache the null value to prevent future this.exceptionMap.put(exceptionClass, null); return null; } // Direct map return this.exceptionMap.get(exceptionClass); } }
public class class_name { public ExceptionHandlerImpl getHandler(Class<? extends Exception> exceptionClass) { // If the exception map does not contain the provided exception class, it might // still be that a superclass of the exception class is. if (!this.exceptionMap.containsKey(exceptionClass)) { Class<?> superclass = exceptionClass.getSuperclass(); do { // Is the superclass mapped? if (this.exceptionMap.containsKey(superclass)) { // Use the handler for the mapped superclass, and cache handler // for this exception class ExceptionHandlerImpl handler = this.exceptionMap.get(superclass); this.exceptionMap.put(exceptionClass, handler); // depends on control dependency: [if], data = [none] return handler; // depends on control dependency: [if], data = [none] } // Iteratively walk through the exception class's superclasses superclass = superclass.getSuperclass(); } while (superclass != null); // No handler found either for the superclasses of the exception class // We cache the null value to prevent future this.exceptionMap.put(exceptionClass, null); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } // Direct map return this.exceptionMap.get(exceptionClass); } }
public class class_name { @Override protected synchronized String issueCrumb(ServletRequest request, String salt) { if (request instanceof HttpServletRequest) { if (md != null) { HttpServletRequest req = (HttpServletRequest) request; StringBuilder buffer = new StringBuilder(); Authentication a = Jenkins.getAuthentication(); if (a != null) { buffer.append(a.getName()); } buffer.append(';'); if (!isExcludeClientIPFromCrumb()) { buffer.append(getClientIP(req)); } md.update(buffer.toString().getBytes()); return Util.toHexString(md.digest(salt.getBytes())); } } return null; } }
public class class_name { @Override protected synchronized String issueCrumb(ServletRequest request, String salt) { if (request instanceof HttpServletRequest) { if (md != null) { HttpServletRequest req = (HttpServletRequest) request; StringBuilder buffer = new StringBuilder(); Authentication a = Jenkins.getAuthentication(); if (a != null) { buffer.append(a.getName()); // depends on control dependency: [if], data = [(a] } buffer.append(';'); // depends on control dependency: [if], data = [none] if (!isExcludeClientIPFromCrumb()) { buffer.append(getClientIP(req)); // depends on control dependency: [if], data = [none] } md.update(buffer.toString().getBytes()); // depends on control dependency: [if], data = [none] return Util.toHexString(md.digest(salt.getBytes())); // depends on control dependency: [if], data = [(md] } } return null; } }
public class class_name { @SuppressWarnings("unchecked") public void processEvent(final SystemEvent event) { if (event instanceof PreDestroyViewMapEvent) { Map<Contextual<?>, Object> componentInstanceMap = getComponentInstanceMap(); Map<Contextual<?>, CreationalContext<?>> creationalContextMap = getCreationalInstanceMap(); if (componentInstanceMap != null) { for (Entry<Contextual<?>, Object> componentEntry : componentInstanceMap.entrySet()) { /* * No way to inform the compiler of type <T> information, so it has to be abandoned here :( */ Contextual contextual = componentEntry.getKey(); Object instance = componentEntry.getValue(); CreationalContext creational = creationalContextMap.get(contextual); contextual.destroy(instance, creational); } } } } }
public class class_name { @SuppressWarnings("unchecked") public void processEvent(final SystemEvent event) { if (event instanceof PreDestroyViewMapEvent) { Map<Contextual<?>, Object> componentInstanceMap = getComponentInstanceMap(); Map<Contextual<?>, CreationalContext<?>> creationalContextMap = getCreationalInstanceMap(); // depends on control dependency: [if], data = [none] if (componentInstanceMap != null) { for (Entry<Contextual<?>, Object> componentEntry : componentInstanceMap.entrySet()) { /* * No way to inform the compiler of type <T> information, so it has to be abandoned here :( */ Contextual contextual = componentEntry.getKey(); Object instance = componentEntry.getValue(); CreationalContext creational = creationalContextMap.get(contextual); contextual.destroy(instance, creational); // depends on control dependency: [for], data = [none] } } } } }
public class class_name { public static boolean booleanValue(String s) { boolean b = false; if (s != null) { if (s.equalsIgnoreCase("yes")) { b = true; } else { b = Boolean.valueOf(s).booleanValue(); } } return b; } }
public class class_name { public static boolean booleanValue(String s) { boolean b = false; if (s != null) { if (s.equalsIgnoreCase("yes")) { b = true; // depends on control dependency: [if], data = [none] } else { b = Boolean.valueOf(s).booleanValue(); // depends on control dependency: [if], data = [none] } } return b; } }
public class class_name { @VisibleForTesting @NonNull static List<MarkwonPlugin> ensureImplicitCoreIfHasDependents(@NonNull List<MarkwonPlugin> plugins) { // loop over plugins -> if CorePlugin is found -> break; // iterate over all plugins and check if CorePlugin is requested boolean hasCore = false; boolean hasCoreDependents = false; for (MarkwonPlugin plugin : plugins) { // here we do not check for exact match (a user could've subclasses CorePlugin // and supplied it. In this case we DO NOT implicitly add CorePlugin // // if core is present already we do not need to iterate anymore -> as nothing // will be changed (and we actually do not care if there are any dependents of Core // as it's present anyway) if (CorePlugin.class.isAssignableFrom(plugin.getClass())) { hasCore = true; break; } // if plugin has CorePlugin in dependencies -> mark for addition if (!hasCoreDependents) { // here we check for direct CorePlugin, if it's not CorePlugin (exact, not a subclass // or something -> ignore) if (plugin.priority().after().contains(CorePlugin.class)) { hasCoreDependents = true; } } } // important thing here is to check if corePlugin is added // add it _only_ if it's not present if (hasCoreDependents && !hasCore) { final List<MarkwonPlugin> out = new ArrayList<>(plugins.size() + 1); // add default instance of CorePlugin out.add(CorePlugin.create()); out.addAll(plugins); return out; } return plugins; } }
public class class_name { @VisibleForTesting @NonNull static List<MarkwonPlugin> ensureImplicitCoreIfHasDependents(@NonNull List<MarkwonPlugin> plugins) { // loop over plugins -> if CorePlugin is found -> break; // iterate over all plugins and check if CorePlugin is requested boolean hasCore = false; boolean hasCoreDependents = false; for (MarkwonPlugin plugin : plugins) { // here we do not check for exact match (a user could've subclasses CorePlugin // and supplied it. In this case we DO NOT implicitly add CorePlugin // // if core is present already we do not need to iterate anymore -> as nothing // will be changed (and we actually do not care if there are any dependents of Core // as it's present anyway) if (CorePlugin.class.isAssignableFrom(plugin.getClass())) { hasCore = true; // depends on control dependency: [if], data = [none] break; } // if plugin has CorePlugin in dependencies -> mark for addition if (!hasCoreDependents) { // here we check for direct CorePlugin, if it's not CorePlugin (exact, not a subclass // or something -> ignore) if (plugin.priority().after().contains(CorePlugin.class)) { hasCoreDependents = true; // depends on control dependency: [if], data = [none] } } } // important thing here is to check if corePlugin is added // add it _only_ if it's not present if (hasCoreDependents && !hasCore) { final List<MarkwonPlugin> out = new ArrayList<>(plugins.size() + 1); // add default instance of CorePlugin out.add(CorePlugin.create()); // depends on control dependency: [if], data = [none] out.addAll(plugins); // depends on control dependency: [if], data = [none] return out; // depends on control dependency: [if], data = [none] } return plugins; } }
public class class_name { public PoolDisableAutoScaleOptions withOcpDate(DateTime ocpDate) { if (ocpDate == null) { this.ocpDate = null; } else { this.ocpDate = new DateTimeRfc1123(ocpDate); } return this; } }
public class class_name { public PoolDisableAutoScaleOptions withOcpDate(DateTime ocpDate) { if (ocpDate == null) { this.ocpDate = null; // depends on control dependency: [if], data = [none] } else { this.ocpDate = new DateTimeRfc1123(ocpDate); // depends on control dependency: [if], data = [(ocpDate] } return this; } }
public class class_name { public void executePropertyChanges(@NonNull ViewGroup container, @Nullable View from, @Nullable View to, @Nullable Transition transition, boolean isPush) { if (from != null && (removesFromViewOnPush() || !isPush) && from.getParent() == container) { container.removeView(from); } if (to != null && to.getParent() == null) { container.addView(to); } } }
public class class_name { public void executePropertyChanges(@NonNull ViewGroup container, @Nullable View from, @Nullable View to, @Nullable Transition transition, boolean isPush) { if (from != null && (removesFromViewOnPush() || !isPush) && from.getParent() == container) { container.removeView(from); // depends on control dependency: [if], data = [none] } if (to != null && to.getParent() == null) { container.addView(to); // depends on control dependency: [if], data = [none] } } }
public class class_name { public final Mono<T> doFinally(Consumer<SignalType> onFinally) { Objects.requireNonNull(onFinally, "onFinally"); if (this instanceof Fuseable) { return onAssembly(new MonoDoFinallyFuseable<>(this, onFinally)); } return onAssembly(new MonoDoFinally<>(this, onFinally)); } }
public class class_name { public final Mono<T> doFinally(Consumer<SignalType> onFinally) { Objects.requireNonNull(onFinally, "onFinally"); if (this instanceof Fuseable) { return onAssembly(new MonoDoFinallyFuseable<>(this, onFinally)); // depends on control dependency: [if], data = [none] } return onAssembly(new MonoDoFinally<>(this, onFinally)); } }
public class class_name { @Override public Set<Principal> getPrincipals(final HttpServletRequest request) { LOGGER.debug("Checking for principals using {}", HttpHeaderPrincipalProvider.class.getSimpleName()); if (headerName == null || separator == null) { LOGGER.debug("headerName or separator not initialized"); return emptySet(); } LOGGER.debug("Trying to get principals from header: {}; separator: {}", headerName, separator); if (request == null) { LOGGER.debug("Servlet request from servletCredentials was null"); return emptySet(); } final String value = request.getHeader(headerName); if (value == null) { LOGGER.debug("Value for header {} is null", headerName); return emptySet(); } final String[] names = value.split(separator); final Set<Principal> principals = new HashSet<>(); for (final String name : names) { LOGGER.debug("Adding HTTP header-provided principal: {}", name.trim()); principals.add(createPrincipal(name)); } return principals; } }
public class class_name { @Override public Set<Principal> getPrincipals(final HttpServletRequest request) { LOGGER.debug("Checking for principals using {}", HttpHeaderPrincipalProvider.class.getSimpleName()); if (headerName == null || separator == null) { LOGGER.debug("headerName or separator not initialized"); // depends on control dependency: [if], data = [none] return emptySet(); // depends on control dependency: [if], data = [none] } LOGGER.debug("Trying to get principals from header: {}; separator: {}", headerName, separator); if (request == null) { LOGGER.debug("Servlet request from servletCredentials was null"); // depends on control dependency: [if], data = [none] return emptySet(); // depends on control dependency: [if], data = [none] } final String value = request.getHeader(headerName); if (value == null) { LOGGER.debug("Value for header {} is null", headerName); // depends on control dependency: [if], data = [none] return emptySet(); // depends on control dependency: [if], data = [none] } final String[] names = value.split(separator); final Set<Principal> principals = new HashSet<>(); for (final String name : names) { LOGGER.debug("Adding HTTP header-provided principal: {}", name.trim()); // depends on control dependency: [for], data = [name] principals.add(createPrincipal(name)); // depends on control dependency: [for], data = [name] } return principals; } }
public class class_name { protected void bicoUpdate(double[] x) { assert (!this.bufferPhase && this.numDimensions == x.length); // Starts with the global root node as the current root node ClusteringTreeNode r = this.root; int i = 1; while (true) { ClusteringTreeNode y = r.nearestChild(x); // Checks if the point can not be added to the current level if (r.hasNoChildren() || y == null || Metric.distanceSquared(x, y.getCenter()) > calcRSquared(i)) { // Creates a new node for the point and adds it to the current // root node r.addChild(new ClusteringTreeNode(x, new ClusteringFeature(x, calcR(i)))); this.rootCount++; break; } else { // Checks if the point can be added to the nearest node without // exceeding the global threshold if (y.getClusteringFeature().calcKMeansCosts(y.getCenter(), x) <= this.T) { // Adds the point to the ClusteringFeature y.getClusteringFeature().add(1, x, Metric.distanceSquared(x)); break; } else { // Navigates one level down in the tree r = y; i++; } } } // Checks if the number of nodes in the tree exceeds the maximum number if (this.rootCount > this.maxNumClusterFeatures) { rebuild(); } } }
public class class_name { protected void bicoUpdate(double[] x) { assert (!this.bufferPhase && this.numDimensions == x.length); // Starts with the global root node as the current root node ClusteringTreeNode r = this.root; int i = 1; while (true) { ClusteringTreeNode y = r.nearestChild(x); // Checks if the point can not be added to the current level if (r.hasNoChildren() || y == null || Metric.distanceSquared(x, y.getCenter()) > calcRSquared(i)) { // Creates a new node for the point and adds it to the current // root node r.addChild(new ClusteringTreeNode(x, new ClusteringFeature(x, calcR(i)))); // depends on control dependency: [if], data = [none] this.rootCount++; // depends on control dependency: [if], data = [none] break; } else { // Checks if the point can be added to the nearest node without // exceeding the global threshold if (y.getClusteringFeature().calcKMeansCosts(y.getCenter(), x) <= this.T) { // Adds the point to the ClusteringFeature y.getClusteringFeature().add(1, x, Metric.distanceSquared(x)); // depends on control dependency: [if], data = [none] break; } else { // Navigates one level down in the tree r = y; // depends on control dependency: [if], data = [none] i++; // depends on control dependency: [if], data = [none] } } } // Checks if the number of nodes in the tree exceeds the maximum number if (this.rootCount > this.maxNumClusterFeatures) { rebuild(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static Class<?> getGenericClass(Class<?> cls, int i) { try { ParameterizedType parameterizedType; if (cls.getGenericInterfaces().length > 0 && cls.getGenericInterfaces()[0] instanceof ParameterizedType) { parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]); } else if (cls.getGenericSuperclass() instanceof ParameterizedType) { parameterizedType = (ParameterizedType) cls.getGenericSuperclass(); } else { parameterizedType = null; } if (parameterizedType != null) { Object genericClass = parameterizedType.getActualTypeArguments()[i]; if (genericClass instanceof ParameterizedType) { // 处理多级泛型 return (Class<?>) ((ParameterizedType) genericClass).getRawType(); } else if (genericClass instanceof GenericArrayType) { // 处理数组泛型 Class<?> componentType = (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType(); if (componentType.isArray()) { return componentType; } else { return Array.newInstance(componentType, 0).getClass(); } } else if (genericClass instanceof Class) { return (Class<?>) genericClass; } } } catch (Exception e) { } if (cls.getSuperclass() != null && cls.getSuperclass() != Object.class) { return getGenericClass(cls.getSuperclass(), i); } else { throw new IllegalArgumentException(cls.getName() + " generic type undefined!"); } } }
public class class_name { public static Class<?> getGenericClass(Class<?> cls, int i) { try { ParameterizedType parameterizedType; if (cls.getGenericInterfaces().length > 0 && cls.getGenericInterfaces()[0] instanceof ParameterizedType) { parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]); // depends on control dependency: [if], data = [0] } else if (cls.getGenericSuperclass() instanceof ParameterizedType) { parameterizedType = (ParameterizedType) cls.getGenericSuperclass(); // depends on control dependency: [if], data = [none] } else { parameterizedType = null; // depends on control dependency: [if], data = [none] } if (parameterizedType != null) { Object genericClass = parameterizedType.getActualTypeArguments()[i]; if (genericClass instanceof ParameterizedType) { // 处理多级泛型 return (Class<?>) ((ParameterizedType) genericClass).getRawType(); // depends on control dependency: [if], data = [none] } else if (genericClass instanceof GenericArrayType) { // 处理数组泛型 Class<?> componentType = (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType(); if (componentType.isArray()) { return componentType; } else { // depends on control dependency: [if], data = [none] return Array.newInstance(componentType, 0).getClass(); } } else if (genericClass instanceof Class) { return (Class<?>) genericClass; // depends on control dependency: [if], data = [none] } } } catch (Exception e) { } if (cls.getSuperclass() != null && cls.getSuperclass() != Object.class) { return getGenericClass(cls.getSuperclass(), i); } else { throw new IllegalArgumentException(cls.getName() + " generic type undefined!"); } } }
public class class_name { private void initOrderedIterator() { if (orderedNodes != null) { return; } long time = 0; if (LOG.isDebugEnabled()) { time = System.currentTimeMillis(); } ScoreNode[][] nodes = (ScoreNode[][])scoreNodes.toArray(new ScoreNode[scoreNodes.size()][]); final Set<String> invalidIDs = new HashSet<String>(2); /** Cache for Nodes obtainer during the order (comparator work) */ final Map<String, NodeData> lcache = new HashMap<String, NodeData>(); do { if (invalidIDs.size() > 0) { // previous sort run was not successful -> remove failed uuids List<ScoreNode[]> tmp = new ArrayList<ScoreNode[]>(); for (int i = 0; i < nodes.length; i++) { if (!invalidIDs.contains(nodes[i][selectorIndex].getNodeId())) { tmp.add(nodes[i]); } } nodes = (ScoreNode[][])tmp.toArray(new ScoreNode[tmp.size()][]); invalidIDs.clear(); } try { // sort the uuids Arrays.sort(nodes, new ScoreNodeComparator(lcache, invalidIDs)); } catch (SortFailedException e) { if (LOG.isTraceEnabled()) { LOG.trace("An exception occurred: " + e.getMessage()); } } } while (invalidIDs.size() > 0); if (LOG.isDebugEnabled()) { LOG.debug("" + nodes.length + " node(s) ordered in " + (System.currentTimeMillis() - time) + " ms"); } orderedNodes = new ScoreNodeIteratorImpl(nodes); } }
public class class_name { private void initOrderedIterator() { if (orderedNodes != null) { return; // depends on control dependency: [if], data = [none] } long time = 0; if (LOG.isDebugEnabled()) { time = System.currentTimeMillis(); // depends on control dependency: [if], data = [none] } ScoreNode[][] nodes = (ScoreNode[][])scoreNodes.toArray(new ScoreNode[scoreNodes.size()][]); final Set<String> invalidIDs = new HashSet<String>(2); /** Cache for Nodes obtainer during the order (comparator work) */ final Map<String, NodeData> lcache = new HashMap<String, NodeData>(); do { if (invalidIDs.size() > 0) { // previous sort run was not successful -> remove failed uuids List<ScoreNode[]> tmp = new ArrayList<ScoreNode[]>(); for (int i = 0; i < nodes.length; i++) { if (!invalidIDs.contains(nodes[i][selectorIndex].getNodeId())) { tmp.add(nodes[i]); // depends on control dependency: [if], data = [none] } } nodes = (ScoreNode[][])tmp.toArray(new ScoreNode[tmp.size()][]); // depends on control dependency: [if], data = [none] invalidIDs.clear(); // depends on control dependency: [if], data = [none] } try { // sort the uuids Arrays.sort(nodes, new ScoreNodeComparator(lcache, invalidIDs)); // depends on control dependency: [try], data = [none] } catch (SortFailedException e) { if (LOG.isTraceEnabled()) { LOG.trace("An exception occurred: " + e.getMessage()); // depends on control dependency: [if], data = [none] } } // depends on control dependency: [catch], data = [none] } while (invalidIDs.size() > 0); if (LOG.isDebugEnabled()) { LOG.debug("" + nodes.length + " node(s) ordered in " + (System.currentTimeMillis() - time) + " ms"); } orderedNodes = new ScoreNodeIteratorImpl(nodes); } }
public class class_name { private static PropertyDescriptor getMatchPropertyDescriptor(PropertyDescriptor[] srcPds, String property) { for (PropertyDescriptor srcPd : srcPds) { if (srcPd.getName().equals(property)) { return srcPd; } } return null; } }
public class class_name { private static PropertyDescriptor getMatchPropertyDescriptor(PropertyDescriptor[] srcPds, String property) { for (PropertyDescriptor srcPd : srcPds) { if (srcPd.getName().equals(property)) { return srcPd; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { private void parseMsgLargeBuffer(Map<Object, Object> props) { if (!areMessagesLimited()) { // if there isn't a standard size limit, ignore this extension to // that config option return; } String value = (String) props.get(HttpConfigConstants.PROPNAME_MSG_SIZE_LARGEBUFFER); if (null != value) { try { long limit = Long.parseLong(value); if (limit < getMessageSize() || HttpConfigConstants.UNLIMITED > limit) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Config: Invalid large buffer limit: " + limit); } limit = getMessageSize(); } this.msgSizeLargeBuffer = limit; } catch (NumberFormatException e) { // no FFDC required if (tc.isEventEnabled()) { Tr.event(tc, "Config: Non-numeric large buffer size; " + value); } } } } }
public class class_name { private void parseMsgLargeBuffer(Map<Object, Object> props) { if (!areMessagesLimited()) { // if there isn't a standard size limit, ignore this extension to // that config option return; // depends on control dependency: [if], data = [none] } String value = (String) props.get(HttpConfigConstants.PROPNAME_MSG_SIZE_LARGEBUFFER); if (null != value) { try { long limit = Long.parseLong(value); if (limit < getMessageSize() || HttpConfigConstants.UNLIMITED > limit) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Config: Invalid large buffer limit: " + limit); // depends on control dependency: [if], data = [none] } limit = getMessageSize(); // depends on control dependency: [if], data = [none] } this.msgSizeLargeBuffer = limit; // depends on control dependency: [try], data = [none] } catch (NumberFormatException e) { // no FFDC required if (tc.isEventEnabled()) { Tr.event(tc, "Config: Non-numeric large buffer size; " + value); // depends on control dependency: [if], data = [none] } } // depends on control dependency: [catch], data = [none] } } }
public class class_name { protected void checkShrink () { if ((_buckets.length > DEFAULT_BUCKETS) && (_size < (int) (_buckets.length * _loadFactor * .125))) { resizeBuckets(Math.max(DEFAULT_BUCKETS, _buckets.length >> 1)); } } }
public class class_name { protected void checkShrink () { if ((_buckets.length > DEFAULT_BUCKETS) && (_size < (int) (_buckets.length * _loadFactor * .125))) { resizeBuckets(Math.max(DEFAULT_BUCKETS, _buckets.length >> 1)); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void close() { lock(); try { if (this.evictionTask != null) { this.evictionTask.cancel(); } for (Entry<String, OReentrantResourcePool<String, DB>> pool : pools.entrySet()) { for (DB db : pool.getValue().getResources()) { pool.getValue().close(); try { OLogManager.instance().debug(this, "Closing pooled database '%s'...", db.getName()); ((ODatabasePooled) db).forceClose(); OLogManager.instance().debug(this, "OK", db.getName()); } catch (Exception e) { OLogManager.instance().debug(this, "Error: %d", e.toString()); } } } } finally { unlock(); } } }
public class class_name { public void close() { lock(); try { if (this.evictionTask != null) { this.evictionTask.cancel(); // depends on control dependency: [if], data = [none] } for (Entry<String, OReentrantResourcePool<String, DB>> pool : pools.entrySet()) { for (DB db : pool.getValue().getResources()) { pool.getValue().close(); // depends on control dependency: [for], data = [none] try { OLogManager.instance().debug(this, "Closing pooled database '%s'...", db.getName()); // depends on control dependency: [try], data = [none] ((ODatabasePooled) db).forceClose(); // depends on control dependency: [try], data = [none] OLogManager.instance().debug(this, "OK", db.getName()); // depends on control dependency: [try], data = [none] } catch (Exception e) { OLogManager.instance().debug(this, "Error: %d", e.toString()); } // depends on control dependency: [catch], data = [none] } } } finally { unlock(); } } }
public class class_name { protected void addNoCacheHeaders(HttpServletResponse response) { String cacheControlValue = response.getHeader(WebConstants.HEADER_CACHE_CONTROL); if (cacheControlValue != null && !cacheControlValue.isEmpty()) { cacheControlValue = cacheControlValue + ", " + WebConstants.CACHE_CONTROL_NO_STORE; } else { cacheControlValue = WebConstants.CACHE_CONTROL_NO_STORE; } response.setHeader(WebConstants.HEADER_CACHE_CONTROL, cacheControlValue); response.setHeader(WebConstants.HEADER_PRAGMA, WebConstants.PRAGMA_NO_CACHE); } }
public class class_name { protected void addNoCacheHeaders(HttpServletResponse response) { String cacheControlValue = response.getHeader(WebConstants.HEADER_CACHE_CONTROL); if (cacheControlValue != null && !cacheControlValue.isEmpty()) { cacheControlValue = cacheControlValue + ", " + WebConstants.CACHE_CONTROL_NO_STORE; // depends on control dependency: [if], data = [none] } else { cacheControlValue = WebConstants.CACHE_CONTROL_NO_STORE; // depends on control dependency: [if], data = [none] } response.setHeader(WebConstants.HEADER_CACHE_CONTROL, cacheControlValue); response.setHeader(WebConstants.HEADER_PRAGMA, WebConstants.PRAGMA_NO_CACHE); } }
public class class_name { public static Configuration forCurrentPlatform() { String os = System.getProperty("os.name"); if (os.contains("Windows")) { return windows(); } else if (os.contains("OS X")) { return osX(); } else { return unix(); } } }
public class class_name { public static Configuration forCurrentPlatform() { String os = System.getProperty("os.name"); if (os.contains("Windows")) { return windows(); // depends on control dependency: [if], data = [none] } else if (os.contains("OS X")) { return osX(); // depends on control dependency: [if], data = [none] } else { return unix(); // depends on control dependency: [if], data = [none] } } }
public class class_name { protected void beforeMarkup() { int soFar = stack[depth]; if ((soFar & WROTE_DATA) == 0 // no data in this scope && (depth > 0 || soFar != 0)) { try { writeNewLine(depth); if (depth > 0 && getIndent().length() > 0) { afterMarkup(); // indentation was written } } catch (Exception e) { e.printStackTrace(); } } } }
public class class_name { protected void beforeMarkup() { int soFar = stack[depth]; if ((soFar & WROTE_DATA) == 0 // no data in this scope && (depth > 0 || soFar != 0)) { try { writeNewLine(depth); // depends on control dependency: [try], data = [none] if (depth > 0 && getIndent().length() > 0) { afterMarkup(); // indentation was written // depends on control dependency: [if], data = [none] } } catch (Exception e) { e.printStackTrace(); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { static ConnectionSpec convertSpec(com.squareup.okhttp.ConnectionSpec spec) { Preconditions.checkArgument(spec.isTls(), "plaintext ConnectionSpec is not accepted"); List<com.squareup.okhttp.TlsVersion> tlsVersionList = spec.tlsVersions(); String[] tlsVersions = new String[tlsVersionList.size()]; for (int i = 0; i < tlsVersions.length; i++) { tlsVersions[i] = tlsVersionList.get(i).javaName(); } List<com.squareup.okhttp.CipherSuite> cipherSuiteList = spec.cipherSuites(); CipherSuite[] cipherSuites = new CipherSuite[cipherSuiteList.size()]; for (int i = 0; i < cipherSuites.length; i++) { cipherSuites[i] = CipherSuite.valueOf(cipherSuiteList.get(i).name()); } return new ConnectionSpec.Builder(spec.isTls()) .supportsTlsExtensions(spec.supportsTlsExtensions()) .tlsVersions(tlsVersions) .cipherSuites(cipherSuites) .build(); } }
public class class_name { static ConnectionSpec convertSpec(com.squareup.okhttp.ConnectionSpec spec) { Preconditions.checkArgument(spec.isTls(), "plaintext ConnectionSpec is not accepted"); List<com.squareup.okhttp.TlsVersion> tlsVersionList = spec.tlsVersions(); String[] tlsVersions = new String[tlsVersionList.size()]; for (int i = 0; i < tlsVersions.length; i++) { tlsVersions[i] = tlsVersionList.get(i).javaName(); // depends on control dependency: [for], data = [i] } List<com.squareup.okhttp.CipherSuite> cipherSuiteList = spec.cipherSuites(); CipherSuite[] cipherSuites = new CipherSuite[cipherSuiteList.size()]; for (int i = 0; i < cipherSuites.length; i++) { cipherSuites[i] = CipherSuite.valueOf(cipherSuiteList.get(i).name()); // depends on control dependency: [for], data = [i] } return new ConnectionSpec.Builder(spec.isTls()) .supportsTlsExtensions(spec.supportsTlsExtensions()) .tlsVersions(tlsVersions) .cipherSuites(cipherSuites) .build(); } }
public class class_name { public static void executeWithSystemPermissions(Runnable task) { ContextAwareRunnable contextAwaretask = new ContextAwareRunnable(task); Subject newsubject = new Subject.Builder().buildSubject(); newsubject.login(new RootAuthenticationToken()); try { newsubject.execute(contextAwaretask); } finally { newsubject.logout(); } } }
public class class_name { public static void executeWithSystemPermissions(Runnable task) { ContextAwareRunnable contextAwaretask = new ContextAwareRunnable(task); Subject newsubject = new Subject.Builder().buildSubject(); newsubject.login(new RootAuthenticationToken()); try { newsubject.execute(contextAwaretask); // depends on control dependency: [try], data = [none] } finally { newsubject.logout(); } } }
public class class_name { @SuppressWarnings("checkstyle:ParameterNumber") private static void trackType(final Map<String, Type> resolved, final Map<String, Type> rawRootGenerics, final String genericName, final Type actualGeneric, final Type knownGeneric, final Class<?> root, final Class<?> known, final LinkedHashMap<String, Type> knownGenerics) { final Class<?> knownGenericType = GenericsUtils.resolveClass(knownGeneric, knownGenerics); if (actualGeneric instanceof ExplicitTypeVariable) { final ExplicitTypeVariable variable = (ExplicitTypeVariable) actualGeneric; // look what minimal type is acceptable according to root class declaration // Available if root class use wildcard ({@code <T extends Something>}) checkTypesCompatibility( // use wildcard to check possible multiple bounds definition WildcardTypeImpl.upper(GenericsUtils.resolveTypeVariables(variable.getBounds(), rawRootGenerics)), knownGenericType, genericName, root, known); resolved.put(variable.getName(), knownGeneric); } else if (actualGeneric instanceof ParameterizedType) { final Class<?> exactActualType = (Class) ((ParameterizedType) actualGeneric).getRawType(); // look raw compatibility checkTypesCompatibility(exactActualType, knownGenericType, genericName, root, known); // if generic is not parameterized, but types compatible then simply types not declared properly - // nothing to do if (knownGeneric instanceof ParameterizedType) { // matching parametrization arguments, for example: // Root<A> extends Base<List<A>>, List<A> and known, for example, List<String> final Type[] actualArguments = ((ParameterizedType) actualGeneric).getActualTypeArguments(); final Type[] knownArguments = alignParametrizationArguments( exactActualType, knownGenericType, (ParameterizedType) knownGeneric, knownGenerics); for (int i = 0; i < actualArguments.length; i++) { // matching parametrization of actual type and known generic (already aligned to same type) trackType(resolved, rawRootGenerics, genericName, actualArguments[i], knownArguments[i], root, known, knownGenerics); } } } else if (actualGeneric instanceof GenericArrayType) { // compare base array types, for example: Root<A> extends Base<A[]> final Type actualComponentType = ((GenericArrayType) actualGeneric).getGenericComponentType(); if (knownGeneric instanceof Class && ((Class) knownGeneric).isArray()) { trackType(resolved, rawRootGenerics, genericName, actualComponentType, ((Class) knownGeneric).getComponentType(), root, known, knownGenerics); } } else if (actualGeneric instanceof Class) { // If generic was resolved to class then it's directly declared in the root class hierarchy // (Root extends Base<Something>).. tracking impossible // We only need to check that class not contradicts with known (declared) generic type. final Class exactActualType = (Class) actualGeneric; checkTypesCompatibility(exactActualType, knownGenericType, genericName, root, known); } // otherwise, in case of different type (possible?).. do nothing (give up) } }
public class class_name { @SuppressWarnings("checkstyle:ParameterNumber") private static void trackType(final Map<String, Type> resolved, final Map<String, Type> rawRootGenerics, final String genericName, final Type actualGeneric, final Type knownGeneric, final Class<?> root, final Class<?> known, final LinkedHashMap<String, Type> knownGenerics) { final Class<?> knownGenericType = GenericsUtils.resolveClass(knownGeneric, knownGenerics); if (actualGeneric instanceof ExplicitTypeVariable) { final ExplicitTypeVariable variable = (ExplicitTypeVariable) actualGeneric; // look what minimal type is acceptable according to root class declaration // Available if root class use wildcard ({@code <T extends Something>}) checkTypesCompatibility( // use wildcard to check possible multiple bounds definition WildcardTypeImpl.upper(GenericsUtils.resolveTypeVariables(variable.getBounds(), rawRootGenerics)), knownGenericType, genericName, root, known); // depends on control dependency: [if], data = [none] resolved.put(variable.getName(), knownGeneric); // depends on control dependency: [if], data = [none] } else if (actualGeneric instanceof ParameterizedType) { final Class<?> exactActualType = (Class) ((ParameterizedType) actualGeneric).getRawType(); // depends on control dependency: [if], data = [none] // look raw compatibility checkTypesCompatibility(exactActualType, knownGenericType, genericName, root, known); // depends on control dependency: [if], data = [none] // if generic is not parameterized, but types compatible then simply types not declared properly - // nothing to do if (knownGeneric instanceof ParameterizedType) { // matching parametrization arguments, for example: // Root<A> extends Base<List<A>>, List<A> and known, for example, List<String> final Type[] actualArguments = ((ParameterizedType) actualGeneric).getActualTypeArguments(); final Type[] knownArguments = alignParametrizationArguments( exactActualType, knownGenericType, (ParameterizedType) knownGeneric, knownGenerics); for (int i = 0; i < actualArguments.length; i++) { // matching parametrization of actual type and known generic (already aligned to same type) trackType(resolved, rawRootGenerics, genericName, actualArguments[i], knownArguments[i], root, known, knownGenerics); // depends on control dependency: [for], data = [none] } } } else if (actualGeneric instanceof GenericArrayType) { // compare base array types, for example: Root<A> extends Base<A[]> final Type actualComponentType = ((GenericArrayType) actualGeneric).getGenericComponentType(); if (knownGeneric instanceof Class && ((Class) knownGeneric).isArray()) { trackType(resolved, rawRootGenerics, genericName, actualComponentType, ((Class) knownGeneric).getComponentType(), root, known, knownGenerics); // depends on control dependency: [if], data = [none] } } else if (actualGeneric instanceof Class) { // If generic was resolved to class then it's directly declared in the root class hierarchy // (Root extends Base<Something>).. tracking impossible // We only need to check that class not contradicts with known (declared) generic type. final Class exactActualType = (Class) actualGeneric; // depends on control dependency: [if], data = [none] checkTypesCompatibility(exactActualType, knownGenericType, genericName, root, known); // depends on control dependency: [if], data = [none] } // otherwise, in case of different type (possible?).. do nothing (give up) } }
public class class_name { public static String replace(final Object source, final Properties valueProperties) { if (valueProperties == null) { return source.toString(); } final Map<String,String> valueMap = new HashMap<>(); final Enumeration<?> propNames = valueProperties.propertyNames(); while (propNames.hasMoreElements()) { final String propName = (String)propNames.nextElement(); final String propValue = valueProperties.getProperty(propName); valueMap.put(propName, propValue); } return StrSubstitutor.replace(source, valueMap); } }
public class class_name { public static String replace(final Object source, final Properties valueProperties) { if (valueProperties == null) { return source.toString(); // depends on control dependency: [if], data = [none] } final Map<String,String> valueMap = new HashMap<>(); final Enumeration<?> propNames = valueProperties.propertyNames(); while (propNames.hasMoreElements()) { final String propName = (String)propNames.nextElement(); final String propValue = valueProperties.getProperty(propName); valueMap.put(propName, propValue); // depends on control dependency: [while], data = [none] } return StrSubstitutor.replace(source, valueMap); } }
public class class_name { private String evaluatorToString(final String streamName, final int offsetInBlock, final JBBPIntegerValueEvaluator evaluator, final AtomicInteger detectedFlagsSet, final boolean doResultPostprocessing) { final StringBuilder buffer = new StringBuilder(); final ExpressionEvaluatorVisitor visitor = new ExpressionEvaluatorVisitor() { private final List<Object> stack = new ArrayList<>(); @Override public ExpressionEvaluatorVisitor visitStart() { this.stack.clear(); return this; } @Override public ExpressionEvaluatorVisitor visitSpecial(final Special specialField) { this.stack.add(specialField); return this; } @Override public ExpressionEvaluatorVisitor visitField(final JBBPNamedFieldInfo nullableNameFieldInfo, final String nullableExternalFieldName) { if (nullableNameFieldInfo != null) { this.stack.add(nullableNameFieldInfo); } else if (nullableExternalFieldName != null) { detectedFlagsSet.set(detectedFlagsSet.get() | FLAG_DETECTED_EXTERNAL_FIELDS); this.stack.add(nullableExternalFieldName); } return this; } @Override public ExpressionEvaluatorVisitor visitOperator(final Operator operator) { this.stack.add(operator); return this; } @Override public ExpressionEvaluatorVisitor visitConstant(final int value) { this.stack.add(value); return this; } private String arg2str(final Object obj) { if (obj instanceof ExprTreeItem) { return obj.toString(); } else if (obj instanceof Special) { if (obj == Special.STREAM_COUNTER) { return "(int)" + streamName + ".getCounter()"; } throw new Error("Unexpected special"); } else if (obj instanceof Integer) { if ((Integer) obj < 0) { return '(' + obj.toString() + ')'; } else { return obj.toString(); } } else if (obj instanceof String) { return String.format("%s.getNamedValue(this, \"%s\")", (getCurrentStruct().isRoot() ? "this" : "this." + NAME_ROOT_STRUCT), obj.toString()); } else if (obj instanceof JBBPNamedFieldInfo) { final NamedFieldInfo namedFieldInfo = foundNamedFields.get(obj); final String fieldPath = namedFieldInfo.makeSrcPath(getCurrentStruct()); String result; switch (namedFieldInfo.fieldType) { case BOOL: { result = '(' + fieldPath + "?1:0)"; } break; case CUSTOM: case VAR: { result = "((JBBPNumericField)" + fieldPath + ").getAsInt()"; } break; default: { result = "(int)" + fieldPath; } break; } return result; } else { return null; } } @Override public ExpressionEvaluatorVisitor visitEnd() { buffer.setLength(0); for (int i = 0; i < this.stack.size(); i++) { if (this.stack.get(i) instanceof Operator) { final Operator op = (Operator) this.stack.remove(i); i--; ExprTreeItem newItem = new ExprTreeItem(op); for (int j = 0; j < op.argsNumber; j++) { final Object val = this.stack.remove(i); i--; if (newItem.right == null) { newItem.right = val; } else { newItem.left = val; } } i++; this.stack.add(i, newItem); } } if (this.stack.size() != 1) { throw new IllegalStateException("Stack must have only element"); } final Object result = this.stack.remove(0); if (result instanceof ExprTreeItem) { buffer.append('(').append(result.toString()).append(')'); } else { buffer.append(arg2str(result)); } return this; } class ExprTreeItem { Operator op; Object left; Object right; ExprTreeItem(Operator op) { this.op = op; } boolean doesNeedBrackets(Object obj) { if (!(obj instanceof ExprTreeItem)) { return false; } final ExprTreeItem that = (ExprTreeItem) obj; return that.op.priority <= this.op.priority || ((that.op == Operator.LSHIFT || that.op == Operator.RSHIFT || that.op == Operator.URSHIFT) && (this.op == Operator.LSHIFT || this.op == Operator.RSHIFT || this.op == Operator.URSHIFT)); } @Override public String toString() { String leftStr = arg2str(this.left); String rightStr = arg2str(this.right); if (doesNeedBrackets(this.left)) { leftStr = '(' + leftStr + ')'; } if (doesNeedBrackets(this.right)) { rightStr = '(' + rightStr + ')'; } return (leftStr == null ? "" : leftStr) + this.op.text + (rightStr == null ? "" : rightStr); } } }; evaluator.visitItems(this.compiledBlock, offsetInBlock, visitor); String result = buffer.toString(); if (result.startsWith("(") && result.endsWith(")")) { try { result = Integer.toString(Integer.parseInt(result.substring(1, result.length() - 1).trim())); } catch (NumberFormatException ex) { // ignore the excepton because it is checking exception } } if (!(evaluator instanceof IntConstValueEvaluator)) { if (doResultPostprocessing) { if ((this.parserFlags & JBBPParser.FLAG_NEGATIVE_EXPRESSION_RESULT_AS_ZERO) != 0) { result = "java.lang.Math.max(0," + result + ')'; } else { detectedFlagsSet.set(detectedFlagsSet.get() | FLAG_ADD_ASSERT_NOT_NEGATIVE_EXPR); result = "assrtExprNotNeg(" + result + ')'; } } } return result; } }
public class class_name { private String evaluatorToString(final String streamName, final int offsetInBlock, final JBBPIntegerValueEvaluator evaluator, final AtomicInteger detectedFlagsSet, final boolean doResultPostprocessing) { final StringBuilder buffer = new StringBuilder(); final ExpressionEvaluatorVisitor visitor = new ExpressionEvaluatorVisitor() { private final List<Object> stack = new ArrayList<>(); @Override public ExpressionEvaluatorVisitor visitStart() { this.stack.clear(); return this; } @Override public ExpressionEvaluatorVisitor visitSpecial(final Special specialField) { this.stack.add(specialField); return this; } @Override public ExpressionEvaluatorVisitor visitField(final JBBPNamedFieldInfo nullableNameFieldInfo, final String nullableExternalFieldName) { if (nullableNameFieldInfo != null) { this.stack.add(nullableNameFieldInfo); // depends on control dependency: [if], data = [(nullableNameFieldInfo] } else if (nullableExternalFieldName != null) { detectedFlagsSet.set(detectedFlagsSet.get() | FLAG_DETECTED_EXTERNAL_FIELDS); // depends on control dependency: [if], data = [none] this.stack.add(nullableExternalFieldName); // depends on control dependency: [if], data = [(nullableExternalFieldName] } return this; } @Override public ExpressionEvaluatorVisitor visitOperator(final Operator operator) { this.stack.add(operator); return this; } @Override public ExpressionEvaluatorVisitor visitConstant(final int value) { this.stack.add(value); return this; } private String arg2str(final Object obj) { if (obj instanceof ExprTreeItem) { return obj.toString(); // depends on control dependency: [if], data = [none] } else if (obj instanceof Special) { if (obj == Special.STREAM_COUNTER) { return "(int)" + streamName + ".getCounter()"; // depends on control dependency: [if], data = [none] } throw new Error("Unexpected special"); } else if (obj instanceof Integer) { if ((Integer) obj < 0) { return '(' + obj.toString() + ')'; // depends on control dependency: [if], data = [none] } else { return obj.toString(); // depends on control dependency: [if], data = [none] } } else if (obj instanceof String) { return String.format("%s.getNamedValue(this, \"%s\")", (getCurrentStruct().isRoot() ? "this" : "this." + NAME_ROOT_STRUCT), obj.toString()); // depends on control dependency: [if], data = [none] } else if (obj instanceof JBBPNamedFieldInfo) { final NamedFieldInfo namedFieldInfo = foundNamedFields.get(obj); final String fieldPath = namedFieldInfo.makeSrcPath(getCurrentStruct()); String result; switch (namedFieldInfo.fieldType) { case BOOL: { result = '(' + fieldPath + "?1:0)"; } break; case CUSTOM: case VAR: { result = "((JBBPNumericField)" + fieldPath + ").getAsInt()"; } break; default: { result = "(int)" + fieldPath; } break; } return result; } else { return null; } } @Override public ExpressionEvaluatorVisitor visitEnd() { buffer.setLength(0); for (int i = 0; i < this.stack.size(); i++) { if (this.stack.get(i) instanceof Operator) { final Operator op = (Operator) this.stack.remove(i); i--; // depends on control dependency: [if], data = [none] ExprTreeItem newItem = new ExprTreeItem(op); for (int j = 0; j < op.argsNumber; j++) { final Object val = this.stack.remove(i); i--; // depends on control dependency: [for], data = [none] if (newItem.right == null) { newItem.right = val; // depends on control dependency: [if], data = [none] } else { newItem.left = val; // depends on control dependency: [if], data = [none] } } i++; // depends on control dependency: [if], data = [none] this.stack.add(i, newItem); // depends on control dependency: [if], data = [none] } } if (this.stack.size() != 1) { throw new IllegalStateException("Stack must have only element"); } final Object result = this.stack.remove(0); if (result instanceof ExprTreeItem) { buffer.append('(').append(result.toString()).append(')'); // depends on control dependency: [if], data = [none] } else { buffer.append(arg2str(result)); // depends on control dependency: [if], data = [none] } return this; } class ExprTreeItem { Operator op; Object left; Object right; ExprTreeItem(Operator op) { this.op = op; } boolean doesNeedBrackets(Object obj) { if (!(obj instanceof ExprTreeItem)) { return false; // depends on control dependency: [if], data = [none] } final ExprTreeItem that = (ExprTreeItem) obj; return that.op.priority <= this.op.priority || ((that.op == Operator.LSHIFT || that.op == Operator.RSHIFT || that.op == Operator.URSHIFT) && (this.op == Operator.LSHIFT || this.op == Operator.RSHIFT || this.op == Operator.URSHIFT)); } @Override public String toString() { String leftStr = arg2str(this.left); String rightStr = arg2str(this.right); if (doesNeedBrackets(this.left)) { leftStr = '(' + leftStr + ')'; // depends on control dependency: [if], data = [none] } if (doesNeedBrackets(this.right)) { rightStr = '(' + rightStr + ')'; // depends on control dependency: [if], data = [none] } return (leftStr == null ? "" : leftStr) + this.op.text + (rightStr == null ? "" : rightStr); } } }; evaluator.visitItems(this.compiledBlock, offsetInBlock, visitor); String result = buffer.toString(); if (result.startsWith("(") && result.endsWith(")")) { try { result = Integer.toString(Integer.parseInt(result.substring(1, result.length() - 1).trim())); } catch (NumberFormatException ex) { // ignore the excepton because it is checking exception } } if (!(evaluator instanceof IntConstValueEvaluator)) { if (doResultPostprocessing) { if ((this.parserFlags & JBBPParser.FLAG_NEGATIVE_EXPRESSION_RESULT_AS_ZERO) != 0) { result = "java.lang.Math.max(0," + result + ')'; } else { detectedFlagsSet.set(detectedFlagsSet.get() | FLAG_ADD_ASSERT_NOT_NEGATIVE_EXPR); result = "assrtExprNotNeg(" + result + ')'; } } } return result; } }
public class class_name { private void moveToPrevious() { if (controller != null) { currentItemIndex = controller.previousItem(this, currentItemIndex); } else { currentItemIndex = defaultController.previousItem(this, currentItemIndex); } } }
public class class_name { private void moveToPrevious() { if (controller != null) { currentItemIndex = controller.previousItem(this, currentItemIndex); // depends on control dependency: [if], data = [none] } else { currentItemIndex = defaultController.previousItem(this, currentItemIndex); // depends on control dependency: [if], data = [none] } } }