code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public Map<String, Map<String, List<String>>> grantResourcePermission(String subjectid, String resourcePath, EnumSet<App.AllowedMethods> permission, boolean allowGuestAccess) { if (StringUtils.isBlank(subjectid) || StringUtils.isBlank(resourcePath) || permission == null) { return Collections.emptyMap(); } if (allowGuestAccess && App.ALLOW_ALL.equals(subjectid)) { permission.add(App.AllowedMethods.GUEST); } resourcePath = Utils.urlEncode(resourcePath); return getEntity(invokePut(Utils.formatMessage("_permissions/{0}/{1}", subjectid, resourcePath), Entity.json(permission)), Map.class); } }
public class class_name { public Map<String, Map<String, List<String>>> grantResourcePermission(String subjectid, String resourcePath, EnumSet<App.AllowedMethods> permission, boolean allowGuestAccess) { if (StringUtils.isBlank(subjectid) || StringUtils.isBlank(resourcePath) || permission == null) { return Collections.emptyMap(); // depends on control dependency: [if], data = [none] } if (allowGuestAccess && App.ALLOW_ALL.equals(subjectid)) { permission.add(App.AllowedMethods.GUEST); // depends on control dependency: [if], data = [none] } resourcePath = Utils.urlEncode(resourcePath); return getEntity(invokePut(Utils.formatMessage("_permissions/{0}/{1}", subjectid, resourcePath), Entity.json(permission)), Map.class); } }
public class class_name { private void obtainStyledAttributes(@Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle, @StyleRes final int defaultStyleResource) { TypedArray typedArray = getContext() .obtainStyledAttributes(attributeSet, R.styleable.ElevationShadowView, defaultStyle, defaultStyleResource); try { obtainShadowElevation(typedArray); obtainShadowOrientation(typedArray); obtainEmulateParallelLight(typedArray); } finally { typedArray.recycle(); } } }
public class class_name { private void obtainStyledAttributes(@Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle, @StyleRes final int defaultStyleResource) { TypedArray typedArray = getContext() .obtainStyledAttributes(attributeSet, R.styleable.ElevationShadowView, defaultStyle, defaultStyleResource); try { obtainShadowElevation(typedArray); // depends on control dependency: [try], data = [none] obtainShadowOrientation(typedArray); // depends on control dependency: [try], data = [none] obtainEmulateParallelLight(typedArray); // depends on control dependency: [try], data = [none] } finally { typedArray.recycle(); } } }
public class class_name { protected PExp makeAnd(PExp root, PExp e) { if (root != null) { AAndBooleanBinaryExp a = new AAndBooleanBinaryExp(); a.setLeft(root.clone()); a.setOp(new LexKeywordToken(VDMToken.AND, null)); a.setType(new ABooleanBasicType()); a.setRight(e.clone()); return a; } else { return e; } } }
public class class_name { protected PExp makeAnd(PExp root, PExp e) { if (root != null) { AAndBooleanBinaryExp a = new AAndBooleanBinaryExp(); a.setLeft(root.clone()); // depends on control dependency: [if], data = [(root] a.setOp(new LexKeywordToken(VDMToken.AND, null)); // depends on control dependency: [if], data = [null)] a.setType(new ABooleanBasicType()); // depends on control dependency: [if], data = [none] a.setRight(e.clone()); // depends on control dependency: [if], data = [none] return a; // depends on control dependency: [if], data = [none] } else { return e; // depends on control dependency: [if], data = [none] } } }
public class class_name { protected void initOrdinal(int defaultOrdinal) { ordinal = defaultOrdinal; String configuredOrdinalString = getValue(CONFIG_ORDINAL); try { if (configuredOrdinalString != null) { ordinal = Integer.parseInt(configuredOrdinalString.trim()); } } catch (NumberFormatException e) { log.log(Level.WARNING, "The configured config-ordinal isn't a valid integer. Invalid value: " + configuredOrdinalString); } } }
public class class_name { protected void initOrdinal(int defaultOrdinal) { ordinal = defaultOrdinal; String configuredOrdinalString = getValue(CONFIG_ORDINAL); try { if (configuredOrdinalString != null) { ordinal = Integer.parseInt(configuredOrdinalString.trim()); // depends on control dependency: [if], data = [(configuredOrdinalString] } } catch (NumberFormatException e) { log.log(Level.WARNING, "The configured config-ordinal isn't a valid integer. Invalid value: " + configuredOrdinalString); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void write(String uri, String contentType, String hostIP, long fetchBeginTimeStamp, long recordLength, InputStream in, boolean enforceLength) throws IOException { preWriteRecordTasks(); try { write(getMetaLine(uri, contentType, hostIP, fetchBeginTimeStamp, recordLength).getBytes(UTF8)); copyFrom(in, recordLength, enforceLength); if (in instanceof ReplayInputStream) { // check for consumption of entire recorded material long remaining = ((ReplayInputStream) in).remaining(); // Should be zero at this stage. If not, something is // wrong. if (remaining != 0) { String message = "Gap between expected and actual: " + remaining + LINE_SEPARATOR + DevUtils.extraInfo() + " writing arc " + this.getFile().getAbsolutePath(); DevUtils.warnHandle(new Throwable(message), message); throw new IOException(message); } } write(LINE_SEPARATOR); } finally { postWriteRecordTasks(); } } }
public class class_name { public void write(String uri, String contentType, String hostIP, long fetchBeginTimeStamp, long recordLength, InputStream in, boolean enforceLength) throws IOException { preWriteRecordTasks(); try { write(getMetaLine(uri, contentType, hostIP, fetchBeginTimeStamp, recordLength).getBytes(UTF8)); copyFrom(in, recordLength, enforceLength); if (in instanceof ReplayInputStream) { // check for consumption of entire recorded material long remaining = ((ReplayInputStream) in).remaining(); // Should be zero at this stage. If not, something is // wrong. if (remaining != 0) { String message = "Gap between expected and actual: " + remaining + LINE_SEPARATOR + DevUtils.extraInfo() + " writing arc " + this.getFile().getAbsolutePath(); // depends on control dependency: [if], data = [none] DevUtils.warnHandle(new Throwable(message), message); // depends on control dependency: [if], data = [none] throw new IOException(message); } } write(LINE_SEPARATOR); } finally { postWriteRecordTasks(); } } }
public class class_name { @Override public void onLoadFinished(final Loader<SortedList<T>> loader, final SortedList<T> data) { isLoading = false; mCheckedItems.clear(); mCheckedVisibleViewHolders.clear(); mFiles = data; mAdapter.setList(data); if (mCurrentDirView != null) { mCurrentDirView.setText(getFullPath(mCurrentPath)); } // Stop loading now to avoid a refresh clearing the user's selections getLoaderManager().destroyLoader( 0 ); } }
public class class_name { @Override public void onLoadFinished(final Loader<SortedList<T>> loader, final SortedList<T> data) { isLoading = false; mCheckedItems.clear(); mCheckedVisibleViewHolders.clear(); mFiles = data; mAdapter.setList(data); if (mCurrentDirView != null) { mCurrentDirView.setText(getFullPath(mCurrentPath)); // depends on control dependency: [if], data = [none] } // Stop loading now to avoid a refresh clearing the user's selections getLoaderManager().destroyLoader( 0 ); } }
public class class_name { @Override public void export(ExportFormat format, int maxRows, ExportCallback callback) { if (dataSetHandler == null) { callback.noData(); } else { Map<String,String> columnNameMap = new HashMap<>(); displayerSettings.getColumnSettingsList().forEach(cs -> columnNameMap.put(cs.getColumnId(), cs.getColumnName())); dataSetHandler.exportCurrentDataSetLookup(format, maxRows, callback, columnNameMap); } } }
public class class_name { @Override public void export(ExportFormat format, int maxRows, ExportCallback callback) { if (dataSetHandler == null) { callback.noData(); // depends on control dependency: [if], data = [none] } else { Map<String,String> columnNameMap = new HashMap<>(); displayerSettings.getColumnSettingsList().forEach(cs -> columnNameMap.put(cs.getColumnId(), cs.getColumnName())); // depends on control dependency: [if], data = [none] dataSetHandler.exportCurrentDataSetLookup(format, maxRows, callback, columnNameMap); // depends on control dependency: [if], data = [none] } } }
public class class_name { @SuppressWarnings({ "unchecked", "rawtypes", "unused" }) private void commitToVoldemort(List<String> storeNamesToCommit) { if(logger.isDebugEnabled()) { logger.debug("Trying to commit to Voldemort"); } boolean hasError = false; if(nodesToStream == null || nodesToStream.size() == 0) { if(logger.isDebugEnabled()) { logger.debug("No nodes to stream to. Returning."); } return; } for(Node node: nodesToStream) { for(String store: storeNamesToCommit) { if(!nodeIdStoreInitialized.get(new Pair(store, node.getId()))) continue; nodeIdStoreInitialized.put(new Pair(store, node.getId()), false); DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair(store, node.getId())); try { ProtoUtils.writeEndOfStream(outputStream); outputStream.flush(); DataInputStream inputStream = nodeIdStoreToInputStreamRequest.get(new Pair(store, node.getId())); VAdminProto.UpdatePartitionEntriesResponse.Builder updateResponse = ProtoUtils.readToBuilder(inputStream, VAdminProto.UpdatePartitionEntriesResponse.newBuilder()); if(updateResponse.hasError()) { hasError = true; } } catch(IOException e) { logger.error("Exception during commit", e); hasError = true; if(!faultyNodes.contains(node.getId())) faultyNodes.add(node.getId()); } } } if(streamingresults == null) { logger.warn("StreamingSession may not have been initialized since Variable streamingresults is null. Skipping callback "); return; } // remove redundant callbacks if(hasError) { logger.info("Invoking the Recovery Callback"); Future future = streamingresults.submit(recoveryCallback); try { future.get(); } catch(InterruptedException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed", e1); throw new VoldemortException("Recovery Callback failed"); } catch(ExecutionException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed during execution", e1); throw new VoldemortException("Recovery Callback failed during execution"); } } else { if(logger.isDebugEnabled()) { logger.debug("Commit successful"); logger.debug("calling checkpoint callback"); } Future future = streamingresults.submit(checkpointCallback); try { future.get(); } catch(InterruptedException e1) { logger.warn("Checkpoint callback failed!", e1); } catch(ExecutionException e1) { logger.warn("Checkpoint callback failed during execution!", e1); } } } }
public class class_name { @SuppressWarnings({ "unchecked", "rawtypes", "unused" }) private void commitToVoldemort(List<String> storeNamesToCommit) { if(logger.isDebugEnabled()) { logger.debug("Trying to commit to Voldemort"); // depends on control dependency: [if], data = [none] } boolean hasError = false; if(nodesToStream == null || nodesToStream.size() == 0) { if(logger.isDebugEnabled()) { logger.debug("No nodes to stream to. Returning."); // depends on control dependency: [if], data = [none] } return; // depends on control dependency: [if], data = [none] } for(Node node: nodesToStream) { for(String store: storeNamesToCommit) { if(!nodeIdStoreInitialized.get(new Pair(store, node.getId()))) continue; nodeIdStoreInitialized.put(new Pair(store, node.getId()), false); // depends on control dependency: [for], data = [store] DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair(store, node.getId())); try { ProtoUtils.writeEndOfStream(outputStream); // depends on control dependency: [try], data = [none] outputStream.flush(); // depends on control dependency: [try], data = [none] DataInputStream inputStream = nodeIdStoreToInputStreamRequest.get(new Pair(store, node.getId())); VAdminProto.UpdatePartitionEntriesResponse.Builder updateResponse = ProtoUtils.readToBuilder(inputStream, VAdminProto.UpdatePartitionEntriesResponse.newBuilder()); if(updateResponse.hasError()) { hasError = true; // depends on control dependency: [if], data = [none] } } catch(IOException e) { logger.error("Exception during commit", e); hasError = true; if(!faultyNodes.contains(node.getId())) faultyNodes.add(node.getId()); } // depends on control dependency: [catch], data = [none] } } if(streamingresults == null) { logger.warn("StreamingSession may not have been initialized since Variable streamingresults is null. Skipping callback "); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } // remove redundant callbacks if(hasError) { logger.info("Invoking the Recovery Callback"); // depends on control dependency: [if], data = [none] Future future = streamingresults.submit(recoveryCallback); try { future.get(); // depends on control dependency: [try], data = [none] } catch(InterruptedException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed", e1); throw new VoldemortException("Recovery Callback failed"); } catch(ExecutionException e1) { // depends on control dependency: [catch], data = [none] MARKED_BAD = true; logger.error("Recovery Callback failed during execution", e1); throw new VoldemortException("Recovery Callback failed during execution"); } // depends on control dependency: [catch], data = [none] } else { if(logger.isDebugEnabled()) { logger.debug("Commit successful"); // depends on control dependency: [if], data = [none] logger.debug("calling checkpoint callback"); // depends on control dependency: [if], data = [none] } Future future = streamingresults.submit(checkpointCallback); try { future.get(); // depends on control dependency: [try], data = [none] } catch(InterruptedException e1) { logger.warn("Checkpoint callback failed!", e1); } catch(ExecutionException e1) { // depends on control dependency: [catch], data = [none] logger.warn("Checkpoint callback failed during execution!", e1); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public void setNetworkAclIds(java.util.Collection<String> networkAclIds) { if (networkAclIds == null) { this.networkAclIds = null; return; } this.networkAclIds = new com.amazonaws.internal.SdkInternalList<String>(networkAclIds); } }
public class class_name { public void setNetworkAclIds(java.util.Collection<String> networkAclIds) { if (networkAclIds == null) { this.networkAclIds = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.networkAclIds = new com.amazonaws.internal.SdkInternalList<String>(networkAclIds); } }
public class class_name { public String getAccessToken() { if (System.currentTimeMillis() > getExpireTime()) { try { synchronized (this) { if (System.currentTimeMillis() > getExpireTime()) { accessToken = fetchAccessToken(); if (accessToken != null && !accessToken.isEmpty()) { expires = (System.currentTimeMillis() + expires); } } } } catch (Exception e) { LOG.debug("Error in fetching the access token: {} ", e); } } return accessToken; } }
public class class_name { public String getAccessToken() { if (System.currentTimeMillis() > getExpireTime()) { try { synchronized (this) { // depends on control dependency: [try], data = [none] if (System.currentTimeMillis() > getExpireTime()) { accessToken = fetchAccessToken(); // depends on control dependency: [if], data = [none] if (accessToken != null && !accessToken.isEmpty()) { expires = (System.currentTimeMillis() + expires); // depends on control dependency: [if], data = [none] } } } } catch (Exception e) { LOG.debug("Error in fetching the access token: {} ", e); } // depends on control dependency: [catch], data = [none] } return accessToken; } }
public class class_name { public List<AdministeredObjectType<InterceptorType<T>>> getAllAdministeredObject() { List<AdministeredObjectType<InterceptorType<T>>> list = new ArrayList<AdministeredObjectType<InterceptorType<T>>>(); List<Node> nodeList = childNode.get("administered-object"); for(Node node: nodeList) { AdministeredObjectType<InterceptorType<T>> type = new AdministeredObjectTypeImpl<InterceptorType<T>>(this, "administered-object", childNode, node); list.add(type); } return list; } }
public class class_name { public List<AdministeredObjectType<InterceptorType<T>>> getAllAdministeredObject() { List<AdministeredObjectType<InterceptorType<T>>> list = new ArrayList<AdministeredObjectType<InterceptorType<T>>>(); List<Node> nodeList = childNode.get("administered-object"); for(Node node: nodeList) { AdministeredObjectType<InterceptorType<T>> type = new AdministeredObjectTypeImpl<InterceptorType<T>>(this, "administered-object", childNode, node); list.add(type); // depends on control dependency: [for], data = [none] } return list; } }
public class class_name { public static void createFieldDebugInfo(FacesContext facesContext, final String field, Object oldValue, Object newValue, String clientId) { if ((oldValue == null && newValue == null) || (oldValue != null && oldValue.equals(newValue))) { // nothing changed - NOTE that this is a difference to the method in // UIInput, because in UIInput every call to this method comes from // setSubmittedValue or setLocalValue and here every call comes // from the VisitCallback of the PhaseListener. return; } // convert Array values into a more readable format if (oldValue != null && oldValue.getClass().isArray()) { oldValue = Arrays.deepToString((Object[]) oldValue); } if (newValue != null && newValue.getClass().isArray()) { newValue = Arrays.deepToString((Object[]) newValue); } // NOTE that the call stack does not make much sence here // create the debug-info array // structure: // - 0: phase // - 1: old value // - 2: new value // - 3: StackTraceElement List // NOTE that we cannot create a class here to encapsulate this data, // because this is not on the spec and the class would not be available in impl. Object[] debugInfo = new Object[4]; debugInfo[0] = facesContext.getCurrentPhaseId(); debugInfo[1] = oldValue; debugInfo[2] = newValue; debugInfo[3] = null; // here we have no call stack (only in UIInput) // add the debug info getFieldDebugInfos(field, clientId).add(debugInfo); } }
public class class_name { public static void createFieldDebugInfo(FacesContext facesContext, final String field, Object oldValue, Object newValue, String clientId) { if ((oldValue == null && newValue == null) || (oldValue != null && oldValue.equals(newValue))) { // nothing changed - NOTE that this is a difference to the method in // UIInput, because in UIInput every call to this method comes from // setSubmittedValue or setLocalValue and here every call comes // from the VisitCallback of the PhaseListener. return; // depends on control dependency: [if], data = [none] } // convert Array values into a more readable format if (oldValue != null && oldValue.getClass().isArray()) { oldValue = Arrays.deepToString((Object[]) oldValue); // depends on control dependency: [if], data = [none] } if (newValue != null && newValue.getClass().isArray()) { newValue = Arrays.deepToString((Object[]) newValue); // depends on control dependency: [if], data = [none] } // NOTE that the call stack does not make much sence here // create the debug-info array // structure: // - 0: phase // - 1: old value // - 2: new value // - 3: StackTraceElement List // NOTE that we cannot create a class here to encapsulate this data, // because this is not on the spec and the class would not be available in impl. Object[] debugInfo = new Object[4]; debugInfo[0] = facesContext.getCurrentPhaseId(); debugInfo[1] = oldValue; debugInfo[2] = newValue; debugInfo[3] = null; // here we have no call stack (only in UIInput) // add the debug info getFieldDebugInfos(field, clientId).add(debugInfo); } }
public class class_name { public void marshall(ProjectArtifacts projectArtifacts, ProtocolMarshaller protocolMarshaller) { if (projectArtifacts == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(projectArtifacts.getType(), TYPE_BINDING); protocolMarshaller.marshall(projectArtifacts.getLocation(), LOCATION_BINDING); protocolMarshaller.marshall(projectArtifacts.getPath(), PATH_BINDING); protocolMarshaller.marshall(projectArtifacts.getNamespaceType(), NAMESPACETYPE_BINDING); protocolMarshaller.marshall(projectArtifacts.getName(), NAME_BINDING); protocolMarshaller.marshall(projectArtifacts.getPackaging(), PACKAGING_BINDING); protocolMarshaller.marshall(projectArtifacts.getOverrideArtifactName(), OVERRIDEARTIFACTNAME_BINDING); protocolMarshaller.marshall(projectArtifacts.getEncryptionDisabled(), ENCRYPTIONDISABLED_BINDING); protocolMarshaller.marshall(projectArtifacts.getArtifactIdentifier(), ARTIFACTIDENTIFIER_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ProjectArtifacts projectArtifacts, ProtocolMarshaller protocolMarshaller) { if (projectArtifacts == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(projectArtifacts.getType(), TYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(projectArtifacts.getLocation(), LOCATION_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(projectArtifacts.getPath(), PATH_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(projectArtifacts.getNamespaceType(), NAMESPACETYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(projectArtifacts.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(projectArtifacts.getPackaging(), PACKAGING_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(projectArtifacts.getOverrideArtifactName(), OVERRIDEARTIFACTNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(projectArtifacts.getEncryptionDisabled(), ENCRYPTIONDISABLED_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(projectArtifacts.getArtifactIdentifier(), ARTIFACTIDENTIFIER_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 { private String getErrorForUnknownService(String id) { StringBuffer error = new StringBuffer(); error.append("Services path: " + ServiceConfigurationManager.CONFIGURATION_DIR); error.append("The service with id: " + id + " is not registered"); error.append("\n Available services are: "); Set<String> keys = serviceManager.getRegisteredConfigurations().keySet(); Iterator<String> it = keys.iterator(); while (it.hasNext()) { error.append(it.next()).append(" "); } return error.toString(); } }
public class class_name { private String getErrorForUnknownService(String id) { StringBuffer error = new StringBuffer(); error.append("Services path: " + ServiceConfigurationManager.CONFIGURATION_DIR); error.append("The service with id: " + id + " is not registered"); error.append("\n Available services are: "); Set<String> keys = serviceManager.getRegisteredConfigurations().keySet(); Iterator<String> it = keys.iterator(); while (it.hasNext()) { error.append(it.next()).append(" "); // depends on control dependency: [while], data = [none] } return error.toString(); } }
public class class_name { protected final void setCliOption(Option option){ if(option!=null){ this.cliOption = option; } if(this.cliOption.getDescription()!=null){ this.descr = this.cliOption.getDescription(); } else{ this.cliOption.setDescription(this.descr); } } }
public class class_name { protected final void setCliOption(Option option){ if(option!=null){ this.cliOption = option; // depends on control dependency: [if], data = [none] } if(this.cliOption.getDescription()!=null){ this.descr = this.cliOption.getDescription(); // depends on control dependency: [if], data = [none] } else{ this.cliOption.setDescription(this.descr); // depends on control dependency: [if], data = [none] } } }
public class class_name { public List<JAXBElement<Object>> get_GenericApplicationPropertyOfBuilding() { if (_GenericApplicationPropertyOfBuilding == null) { _GenericApplicationPropertyOfBuilding = new ArrayList<JAXBElement<Object>>(); } return this._GenericApplicationPropertyOfBuilding; } }
public class class_name { public List<JAXBElement<Object>> get_GenericApplicationPropertyOfBuilding() { if (_GenericApplicationPropertyOfBuilding == null) { _GenericApplicationPropertyOfBuilding = new ArrayList<JAXBElement<Object>>(); // depends on control dependency: [if], data = [none] } return this._GenericApplicationPropertyOfBuilding; } }
public class class_name { public void addItem(final InvoiceItem invoiceItem) { Preconditions.checkState(!isBuilt, "Tree already built, unable to add new invoiceItem=%s", invoiceItem); switch (invoiceItem.getInvoiceItemType()) { case RECURRING: if (invoiceItem.getAmount().compareTo(BigDecimal.ZERO) == 0) { // Nothing to repair -- https://github.com/killbill/killbill/issues/783 existingIgnoredItems.add(invoiceItem); } else { root.addExistingItem(new ItemsNodeInterval(root, new Item(invoiceItem, targetInvoiceId, ItemAction.ADD))); } break; case REPAIR_ADJ: root.addExistingItem(new ItemsNodeInterval(root, new Item(invoiceItem, targetInvoiceId, ItemAction.CANCEL))); break; case FIXED: existingIgnoredItems.add(invoiceItem); break; case ITEM_ADJ: pendingItemAdj.add(invoiceItem); break; default: break; } } }
public class class_name { public void addItem(final InvoiceItem invoiceItem) { Preconditions.checkState(!isBuilt, "Tree already built, unable to add new invoiceItem=%s", invoiceItem); switch (invoiceItem.getInvoiceItemType()) { case RECURRING: if (invoiceItem.getAmount().compareTo(BigDecimal.ZERO) == 0) { // Nothing to repair -- https://github.com/killbill/killbill/issues/783 existingIgnoredItems.add(invoiceItem); // depends on control dependency: [if], data = [none] } else { root.addExistingItem(new ItemsNodeInterval(root, new Item(invoiceItem, targetInvoiceId, ItemAction.ADD))); // depends on control dependency: [if], data = [none] } break; case REPAIR_ADJ: root.addExistingItem(new ItemsNodeInterval(root, new Item(invoiceItem, targetInvoiceId, ItemAction.CANCEL))); break; case FIXED: existingIgnoredItems.add(invoiceItem); break; case ITEM_ADJ: pendingItemAdj.add(invoiceItem); break; default: break; } } }
public class class_name { public void marshall(GetCampaignVersionsRequest getCampaignVersionsRequest, ProtocolMarshaller protocolMarshaller) { if (getCampaignVersionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getCampaignVersionsRequest.getApplicationId(), APPLICATIONID_BINDING); protocolMarshaller.marshall(getCampaignVersionsRequest.getCampaignId(), CAMPAIGNID_BINDING); protocolMarshaller.marshall(getCampaignVersionsRequest.getPageSize(), PAGESIZE_BINDING); protocolMarshaller.marshall(getCampaignVersionsRequest.getToken(), TOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(GetCampaignVersionsRequest getCampaignVersionsRequest, ProtocolMarshaller protocolMarshaller) { if (getCampaignVersionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getCampaignVersionsRequest.getApplicationId(), APPLICATIONID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(getCampaignVersionsRequest.getCampaignId(), CAMPAIGNID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(getCampaignVersionsRequest.getPageSize(), PAGESIZE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(getCampaignVersionsRequest.getToken(), TOKEN_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static Document getDocument(File file) { InputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (FileNotFoundException ex) { throw new MjdbcRuntimeException(ex); } return XmlRepositoryFactory.getDocument(inputStream); } }
public class class_name { public static Document getDocument(File file) { InputStream inputStream = null; try { inputStream = new FileInputStream(file); // depends on control dependency: [try], data = [none] } catch (FileNotFoundException ex) { throw new MjdbcRuntimeException(ex); } // depends on control dependency: [catch], data = [none] return XmlRepositoryFactory.getDocument(inputStream); } }
public class class_name { private boolean hmmBreak(Map<S, Double> message) { for (double logProbability : message.values()) { if (logProbability != Double.NEGATIVE_INFINITY) { return false; } } return true; } }
public class class_name { private boolean hmmBreak(Map<S, Double> message) { for (double logProbability : message.values()) { if (logProbability != Double.NEGATIVE_INFINITY) { return false; // depends on control dependency: [if], data = [none] } } return true; } }
public class class_name { static boolean getBooleanValFromVMArg(String vmArgValue, boolean defaultStateWhenNotDefined) { String sysProperty = System.getProperty(vmArgValue); boolean flag = defaultStateWhenNotDefined; if ((sysProperty != null) && (!sysProperty.isEmpty())) { flag = Boolean.parseBoolean(sysProperty); } return flag; } }
public class class_name { static boolean getBooleanValFromVMArg(String vmArgValue, boolean defaultStateWhenNotDefined) { String sysProperty = System.getProperty(vmArgValue); boolean flag = defaultStateWhenNotDefined; if ((sysProperty != null) && (!sysProperty.isEmpty())) { flag = Boolean.parseBoolean(sysProperty); // depends on control dependency: [if], data = [none] } return flag; } }
public class class_name { public void setXYZ(Point3D pt) { _touch(); boolean bHasZ = hasAttribute(Semantics.Z); if (!bHasZ && !VertexDescription.isDefaultValue(Semantics.Z, pt.z)) {// add // Z // only // if // pt.z // is // not // a // default // value. addAttribute(Semantics.Z); bHasZ = true; } if (m_attributes == null) _setToDefault(); m_attributes[0] = pt.x; m_attributes[1] = pt.y; if (bHasZ) m_attributes[2] = pt.z; } }
public class class_name { public void setXYZ(Point3D pt) { _touch(); boolean bHasZ = hasAttribute(Semantics.Z); if (!bHasZ && !VertexDescription.isDefaultValue(Semantics.Z, pt.z)) {// add // Z // only // if // pt.z // is // not // a // default // value. addAttribute(Semantics.Z); // depends on control dependency: [if], data = [none] bHasZ = true; // depends on control dependency: [if], data = [none] } if (m_attributes == null) _setToDefault(); m_attributes[0] = pt.x; m_attributes[1] = pt.y; if (bHasZ) m_attributes[2] = pt.z; } }
public class class_name { public AST process(AST t) { // first visit List l = new ArrayList(); traverse((GroovySourceAST)t,l,null); //System.out.println("l:" + l); // second visit Iterator itr = l.iterator(); if (itr.hasNext()) { itr.next(); /* discard first */ } traverse((GroovySourceAST)t,null,itr); return t; } }
public class class_name { public AST process(AST t) { // first visit List l = new ArrayList(); traverse((GroovySourceAST)t,l,null); //System.out.println("l:" + l); // second visit Iterator itr = l.iterator(); if (itr.hasNext()) { itr.next(); /* discard first */ } // depends on control dependency: [if], data = [none] traverse((GroovySourceAST)t,null,itr); return t; } }
public class class_name { @Override public WebPage run(WebPage initialPage) { if(getUser() == null) throw new IllegalStateException("the user set is null"); WebPage currentPage = initialPage; for(WebTask task : this) { logger.info("BEGIN subtask " + task.getClass().getSimpleName()); // before running the subtask, set the user task.setUser(getUser()); currentPage = task.run(currentPage); logger.info("END subtask " + task.getClass().getSimpleName()); } return currentPage; } }
public class class_name { @Override public WebPage run(WebPage initialPage) { if(getUser() == null) throw new IllegalStateException("the user set is null"); WebPage currentPage = initialPage; for(WebTask task : this) { logger.info("BEGIN subtask " + task.getClass().getSimpleName()); // depends on control dependency: [for], data = [task] // before running the subtask, set the user task.setUser(getUser()); // depends on control dependency: [for], data = [task] currentPage = task.run(currentPage); // depends on control dependency: [for], data = [task] logger.info("END subtask " + task.getClass().getSimpleName()); // depends on control dependency: [for], data = [task] } return currentPage; } }
public class class_name { public static Set<String> namesOf(AdminsConfig adminsConfig, Map<String, Collection<String>> rolesToUsers) { List<AdminUser> admins = adminsConfig.getUsers(); Set<String> adminNames = new HashSet<>(); for (AdminUser admin : admins) { adminNames.add(admin.getName().toLower()); } for (AdminRole adminRole : adminsConfig.getRoles()) { adminNames.addAll(emptyIfNull(rolesToUsers.get(adminRole.getName().toLower()))); } return adminNames; } }
public class class_name { public static Set<String> namesOf(AdminsConfig adminsConfig, Map<String, Collection<String>> rolesToUsers) { List<AdminUser> admins = adminsConfig.getUsers(); Set<String> adminNames = new HashSet<>(); for (AdminUser admin : admins) { adminNames.add(admin.getName().toLower()); // depends on control dependency: [for], data = [admin] } for (AdminRole adminRole : adminsConfig.getRoles()) { adminNames.addAll(emptyIfNull(rolesToUsers.get(adminRole.getName().toLower()))); // depends on control dependency: [for], data = [adminRole] } return adminNames; } }
public class class_name { private void extractCharacterFilesFromJar(URL urlCharacters) throws IOException { JarURLConnection connection = (JarURLConnection)urlCharacters.openConnection(); ZipInputStream in = null; ZipEntry zipEntry = null; String basePath = connection.getJarEntry().getName(); byte[] buff = new byte[1024 * 1024]; int size; try { in = new ZipInputStream(new FileInputStream(connection.getJarFile().getName())); while ((zipEntry = in.getNextEntry()) != null) { if ((!zipEntry.getName().startsWith(basePath)) || (zipEntry.getName().length() <= basePath.length())) { continue; } FileOutputStream out = null; String fileName = zipEntry.getName().substring(basePath.length()); try { out = new FileOutputStream("characters/" + fileName); while (0 < (size = in.read(buff))) { out.write(buff, 0, size); } } catch (Exception e) { continue; } finally { try { in.closeEntry(); } catch (IOException e2) {} if (out != null) { try { out.close(); } catch (IOException e2) {} } } } } finally { if (in != null) { try { in.close(); } catch (IOException e) {} } } } }
public class class_name { private void extractCharacterFilesFromJar(URL urlCharacters) throws IOException { JarURLConnection connection = (JarURLConnection)urlCharacters.openConnection(); ZipInputStream in = null; ZipEntry zipEntry = null; String basePath = connection.getJarEntry().getName(); byte[] buff = new byte[1024 * 1024]; int size; try { in = new ZipInputStream(new FileInputStream(connection.getJarFile().getName())); while ((zipEntry = in.getNextEntry()) != null) { if ((!zipEntry.getName().startsWith(basePath)) || (zipEntry.getName().length() <= basePath.length())) { continue; } FileOutputStream out = null; String fileName = zipEntry.getName().substring(basePath.length()); try { out = new FileOutputStream("characters/" + fileName); // depends on control dependency: [try], data = [none] while (0 < (size = in.read(buff))) { out.write(buff, 0, size); // depends on control dependency: [while], data = [none] } } catch (Exception e) { continue; } finally { // depends on control dependency: [catch], data = [none] try { in.closeEntry(); // depends on control dependency: [try], data = [none] } catch (IOException e2) {} // depends on control dependency: [catch], data = [none] if (out != null) { try { out.close(); // depends on control dependency: [try], data = [none] } catch (IOException e2) {} // depends on control dependency: [catch], data = [none] } } } } finally { if (in != null) { try { in.close(); // depends on control dependency: [try], data = [none] } catch (IOException e) {} // depends on control dependency: [catch], data = [none] } } } }
public class class_name { public static void logV(String localTag, String msg) { if (getConfig().debugMode) { Log.v(getConfig().logTag, "[" + localTag + "] " + msg); } } }
public class class_name { public static void logV(String localTag, String msg) { if (getConfig().debugMode) { Log.v(getConfig().logTag, "[" + localTag + "] " + msg); // depends on control dependency: [if], data = [none] } } }
public class class_name { private ImmutableList<Require> getAllRequiresInDeclaration() { Node rhs = nameDeclaration.getFirstChild().isDestructuringLhs() ? nameDeclaration.getFirstChild().getSecondChild() : nameDeclaration.getFirstFirstChild(); String namespace = rhs.getSecondChild().getString(); if (nameDeclaration.getFirstChild().isName()) { // const modA = goog.require('modA'); Node lhs = nameDeclaration.getFirstChild(); return ImmutableList.of( Require.create( lhs.getString(), Import.builder() .moduleRequest(namespace) .localName(lhs.getString()) .importName(Export.NAMESPACE) .importNode(nameDeclaration) .nameNode(lhs) .build(), requireKind)); } else { // const {x, y} = goog.require('modA'); Node objectPattern = nameDeclaration.getFirstFirstChild(); if (!objectPattern.isObjectPattern()) { // bad JS, ignore return ImmutableList.of(); } return getAllRequiresFromDestructuring(objectPattern, namespace); } } }
public class class_name { private ImmutableList<Require> getAllRequiresInDeclaration() { Node rhs = nameDeclaration.getFirstChild().isDestructuringLhs() ? nameDeclaration.getFirstChild().getSecondChild() : nameDeclaration.getFirstFirstChild(); String namespace = rhs.getSecondChild().getString(); if (nameDeclaration.getFirstChild().isName()) { // const modA = goog.require('modA'); Node lhs = nameDeclaration.getFirstChild(); return ImmutableList.of( Require.create( lhs.getString(), Import.builder() .moduleRequest(namespace) .localName(lhs.getString()) .importName(Export.NAMESPACE) .importNode(nameDeclaration) .nameNode(lhs) .build(), requireKind)); // depends on control dependency: [if], data = [none] } else { // const {x, y} = goog.require('modA'); Node objectPattern = nameDeclaration.getFirstFirstChild(); if (!objectPattern.isObjectPattern()) { // bad JS, ignore return ImmutableList.of(); // depends on control dependency: [if], data = [none] } return getAllRequiresFromDestructuring(objectPattern, namespace); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void setDeploymentGroupsInfo(java.util.Collection<DeploymentGroupInfo> deploymentGroupsInfo) { if (deploymentGroupsInfo == null) { this.deploymentGroupsInfo = null; return; } this.deploymentGroupsInfo = new com.amazonaws.internal.SdkInternalList<DeploymentGroupInfo>(deploymentGroupsInfo); } }
public class class_name { public void setDeploymentGroupsInfo(java.util.Collection<DeploymentGroupInfo> deploymentGroupsInfo) { if (deploymentGroupsInfo == null) { this.deploymentGroupsInfo = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.deploymentGroupsInfo = new com.amazonaws.internal.SdkInternalList<DeploymentGroupInfo>(deploymentGroupsInfo); } }
public class class_name { @Deprecated public AndroidChannelBuilder transportExecutor(@Nullable Executor transportExecutor) { try { OKHTTP_CHANNEL_BUILDER_CLASS .getMethod("transportExecutor", Executor.class) .invoke(delegateBuilder, transportExecutor); return this; } catch (Exception e) { throw new RuntimeException("Failed to invoke transportExecutor on delegate builder", e); } } }
public class class_name { @Deprecated public AndroidChannelBuilder transportExecutor(@Nullable Executor transportExecutor) { try { OKHTTP_CHANNEL_BUILDER_CLASS .getMethod("transportExecutor", Executor.class) .invoke(delegateBuilder, transportExecutor); // depends on control dependency: [try], data = [none] return this; // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new RuntimeException("Failed to invoke transportExecutor on delegate builder", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public List<T> createSpec(Map<String, Object> rawSpec) { List<T> result = new ArrayList<>(); Set<String> actualKeys = new HashSet<>(); for ( String rawLhsStr : rawSpec.keySet() ) { Object rawRhs = rawSpec.get( rawLhsStr ); String[] keyStrings = rawLhsStr.split( "\\|" ); // unwrap the syntactic sugar of the OR for ( String keyString : keyStrings ) { T childSpec = createSpec( keyString, rawRhs ); String childCanonicalString = childSpec.getPathElement().getCanonicalForm(); if ( actualKeys.contains( childCanonicalString ) ) { throw new IllegalArgumentException( "Duplicate canonical key found : " + childCanonicalString ); } actualKeys.add( childCanonicalString ); result.add(childSpec); } } return result; } }
public class class_name { public List<T> createSpec(Map<String, Object> rawSpec) { List<T> result = new ArrayList<>(); Set<String> actualKeys = new HashSet<>(); for ( String rawLhsStr : rawSpec.keySet() ) { Object rawRhs = rawSpec.get( rawLhsStr ); String[] keyStrings = rawLhsStr.split( "\\|" ); // unwrap the syntactic sugar of the OR for ( String keyString : keyStrings ) { T childSpec = createSpec( keyString, rawRhs ); String childCanonicalString = childSpec.getPathElement().getCanonicalForm(); if ( actualKeys.contains( childCanonicalString ) ) { throw new IllegalArgumentException( "Duplicate canonical key found : " + childCanonicalString ); } actualKeys.add( childCanonicalString ); // depends on control dependency: [for], data = [none] result.add(childSpec); // depends on control dependency: [for], data = [none] } } return result; } }
public class class_name { public MessageMgr build(){ if(this.messageHandlers.size()==0){ this.buildErrors.addError("no message handlers set"); return null; } return new MessageMgr(this.appID, this.messageHandlers, this.doCollectMessages); } }
public class class_name { public MessageMgr build(){ if(this.messageHandlers.size()==0){ this.buildErrors.addError("no message handlers set"); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } return new MessageMgr(this.appID, this.messageHandlers, this.doCollectMessages); } }
public class class_name { public static int getThemeAttributeDimensionSize(Context context, int attr) { TypedArray a = null; try { a = context.getTheme().obtainStyledAttributes(new int[]{attr}); return a.getDimensionPixelSize(0, 0); } finally { if (a != null) { a.recycle(); } } } }
public class class_name { public static int getThemeAttributeDimensionSize(Context context, int attr) { TypedArray a = null; try { a = context.getTheme().obtainStyledAttributes(new int[]{attr}); // depends on control dependency: [try], data = [none] return a.getDimensionPixelSize(0, 0); // depends on control dependency: [try], data = [none] } finally { if (a != null) { a.recycle(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static void startProfileActivity(Context context, int uid) { // Ignore call if context is empty, simple work-around when fragment was disconnected from // activity if (context == null) { return; } Bundle b = new Bundle(); b.putInt(Intents.EXTRA_UID, uid); startActivity(context, b, ProfileActivity.class); } }
public class class_name { public static void startProfileActivity(Context context, int uid) { // Ignore call if context is empty, simple work-around when fragment was disconnected from // activity if (context == null) { return; // depends on control dependency: [if], data = [none] } Bundle b = new Bundle(); b.putInt(Intents.EXTRA_UID, uid); startActivity(context, b, ProfileActivity.class); } }
public class class_name { public ArrayList getProperties(){ ArrayList properties = new ArrayList(); if (configEntry.properties != null){ Iterator it = configEntry.properties.values().iterator(); while (it.hasNext()){ Property property = new Property((com.ibm.ws.cache.config.Property)it.next()); properties.add(property); } } return properties; } }
public class class_name { public ArrayList getProperties(){ ArrayList properties = new ArrayList(); if (configEntry.properties != null){ Iterator it = configEntry.properties.values().iterator(); while (it.hasNext()){ Property property = new Property((com.ibm.ws.cache.config.Property)it.next()); properties.add(property); // depends on control dependency: [while], data = [none] } } return properties; } }
public class class_name { protected boolean isNavigationKey(int keyCode) { for (int i = 0; i < NAVIGATION_CODES.length; i++) { if (NAVIGATION_CODES[i] == keyCode) { return true; } } return false; } }
public class class_name { protected boolean isNavigationKey(int keyCode) { for (int i = 0; i < NAVIGATION_CODES.length; i++) { if (NAVIGATION_CODES[i] == keyCode) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { public static String encodeURIAttribute(final String string, final String characterEncoding) throws IOException { StringBuilder sb = null; //create later on demand String app; char c; boolean endLoop = false; int length = string.length(); for (int i = 0; i < length; ++i) { app = null; c = string.charAt(i); // This are the guidelines to be taken into account by this algorithm to encode: // RFC 2396 Section 2.4.3 Excluded US-ASCII Characters // // control = <US-ASCII coded characters 00-1F and 7F hexadecimal> // space = <US-ASCII coded character 20 hexadecimal> // delims = "<" | ">" | "#" | "%" | <"> // %3C %3E %23 %25 %22 // unwise = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`" // %7D %7B %7C %5C %5E %5B %5D %60 // // ".... Data corresponding to excluded characters must be escaped in order to // be properly represented within a URI....." // RFC 3986 Section 3. Syntax Components // // "... The generic URI syntax consists of a hierarchical sequence of // components referred to as the scheme, authority, path, query, and // fragment. // // URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] // // hier-part = "//" authority path-abempty // / path-absolute // / path-rootless // / path-empty // ...." // RFC 3986 Section 2.2: // Reserved characters (should not be percent-encoded) // reserved = gen-delims / sub-delims // gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" // %3A %2F %3F %23 %5B %5D %40 // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" // %21 %24 %26 %27 %28 %29 %2A %2B %2C %3B %3D // Note than chars "[" and "]" are mentioned as they should be escaped on RFC 2396, // but on the part D. Changes from RFC 2396 says about this chars (used on IPv6) // "...those rules were redefined to directly specify the characters allowed...." // There is also other characters moved from excluded list to reserved: // "[" / "]" / "#" // RFC 3986 Section 2.3: // "... for consistency, percent-encoded octets in the ranges of ALPHA // (%41-%5A and %61-%7A), DIGIT (%30-%39), hyphen (%2D), period (%2E), // underscore (%5F), or tilde (%7E) should not be created by URI // producers...." // RFC 3986 Section 3.2.2. Host // host = IP-literal / IPv4address / reg-name // The reg-name syntax allows percent-encoded octets in order to // represent non-ASCII registered names in a uniform way that is // independent of the underlying name resolution technology. Non-ASCII // characters must first be encoded according to UTF-8 [STD63], and then // each octet of the corresponding UTF-8 sequence must be percent- // encoded to be represented as URI characters. URI producing // applications must not use percent-encoding in host unless it is used // to represent a UTF-8 character sequence. // RFC 3986 Section 3.4 Query // query = *( pchar / "/" / "?" ) // // "... However, as query components are often used to carry identifying information // in the form of "key=value" pairs and one frequently used value is a reference to // another URI, it is sometimes better for usability to avoid percent-encoding those characters....." // // RFC 3986 Section 2.5 Identifying Data (Apply to query section) // // When a new URI scheme defines a component that represents textual // data consisting of characters from the Universal Character Set [UCS], // the data should first be encoded as octets according to the UTF-8 // character encoding [STD63]; then only those octets that do not // correspond to characters in the unreserved set should be percent- // encoded. For example, the character A would be represented as "A", // the character LATIN CAPITAL LETTER A WITH GRAVE would be represented // as "%C3%80", and the character KATAKANA LETTER A would be represented // as "%E3%82%A2". // // RFC 3986 Section 3.5 Fragment // fragment = *( pchar / "/" / "?" ) // // Note that follows the same as query // Based on the extracts the strategy to apply on this method is: // // On scheme ":" hier-part // // Escape or percent encode chars inside : // // - From %00 to %20, // - <"> %22, "%" %25 (If there is encode of "%", there is a risk of // duplicate encoding, encode it when we are sure // that there are not encoded twice) // - "<" %3C, ">" %3E // - "\" %5C, "^" %5E, "`" %60 // - "{" %7B, "|" %7C, "}" %7D // - From %7F ad infinitum (characters from %100 to infinitum should not be used in this // part of an URI, but it is preferred to encode it that omit it). // // The remaining characters must not be encoded // // Characters after ? or # should be percent encoding but only the necessary ones: // // - From %00 to %20 (' ' %20 could encode as +, but %20 also works, so we keep %20) // - <"> %22, "%" %25 (If there is encode of "%", there is a risk of // duplicate encoding, encode it when we are sure // that there are not encoded twice) // - "<" %3C, ">" %3E, // - "\" %5C, "^" %5E, "`" %60 // - "{" %7B, "|" %7C, "}" %7D // - From %7F ad infinitum (each character as many bytes as necessary but take into account // that a single char should contain 2,3 or more bytes!. This data should be encoded // translating from the document character encoding to percent encoding, because this values // could be retrieved from httpRequest.getParameter() and it uses the current character encoding // for decode values) // // "&" should be encoded as "&amp;" because this link is inside an html page, and // put only & is invalid in this context. if ( (c <= (char)0x20) || (c >= (char)0x7F) || c == '"' || c == '<' || c == '>' || c == '\\' || c == '^' || c == '`' || c == '{' || c == '|' || c == '}') { // The percent encoding on this part should be done using UTF-8 charset // as RFC 3986 Section 3.2.2 says. // Also there is a reference on // http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars // that recommend use of UTF-8 instead the document character encoding. // Jetty set by default UTF-8 (see http://jira.codehaus.org/browse/JETTY-113) app = percentEncode(c, "UTF-8"); } else if (c == '%') { if (i + 2 < length) { char c1 = string.charAt(i+1); char c2 = string.charAt(i+2); if ((( c1 >= '0' && c1 <='9') || (c1 >='A' && c1 <='Z') || (c1 >='a' && c1 <='z')) && (( c2 >= '0' && c2 <='9') || (c2 >='A' && c2 <='Z') || (c2 >='a' && c2 <='z'))) { // do not percent encode, because it could be already encoded // and we don't want encode it twice } else { app = percentEncode(c, UTF8); } } else { app = percentEncode(c, UTF8); } } else if (c == '?' || c == '#') { if (i+1 < length) { // The remaining part of the URI are data that should be encoded // using the document character encoding. app = c + encodeURIQuery(string.substring(i+1), characterEncoding); endLoop = true; } } else { //No encoding, just do nothing, char will be added later. } if (app != null) { if (sb == null) { sb = new StringBuilder(string.substring(0, i)); } sb.append(app); } else { if (sb != null) { sb.append(c); } } if (endLoop) { break; } } if (sb == null) { return string; } else { return sb.toString(); } } }
public class class_name { public static String encodeURIAttribute(final String string, final String characterEncoding) throws IOException { StringBuilder sb = null; //create later on demand String app; char c; boolean endLoop = false; int length = string.length(); for (int i = 0; i < length; ++i) { app = null; c = string.charAt(i); // This are the guidelines to be taken into account by this algorithm to encode: // RFC 2396 Section 2.4.3 Excluded US-ASCII Characters // // control = <US-ASCII coded characters 00-1F and 7F hexadecimal> // space = <US-ASCII coded character 20 hexadecimal> // delims = "<" | ">" | "#" | "%" | <"> // %3C %3E %23 %25 %22 // unwise = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`" // %7D %7B %7C %5C %5E %5B %5D %60 // // ".... Data corresponding to excluded characters must be escaped in order to // be properly represented within a URI....." // RFC 3986 Section 3. Syntax Components // // "... The generic URI syntax consists of a hierarchical sequence of // components referred to as the scheme, authority, path, query, and // fragment. // // URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] // // hier-part = "//" authority path-abempty // / path-absolute // / path-rootless // / path-empty // ...." // RFC 3986 Section 2.2: // Reserved characters (should not be percent-encoded) // reserved = gen-delims / sub-delims // gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" // %3A %2F %3F %23 %5B %5D %40 // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" // %21 %24 %26 %27 %28 %29 %2A %2B %2C %3B %3D // Note than chars "[" and "]" are mentioned as they should be escaped on RFC 2396, // but on the part D. Changes from RFC 2396 says about this chars (used on IPv6) // "...those rules were redefined to directly specify the characters allowed...." // There is also other characters moved from excluded list to reserved: // "[" / "]" / "#" // RFC 3986 Section 2.3: // "... for consistency, percent-encoded octets in the ranges of ALPHA // (%41-%5A and %61-%7A), DIGIT (%30-%39), hyphen (%2D), period (%2E), // underscore (%5F), or tilde (%7E) should not be created by URI // producers...." // RFC 3986 Section 3.2.2. Host // host = IP-literal / IPv4address / reg-name // The reg-name syntax allows percent-encoded octets in order to // represent non-ASCII registered names in a uniform way that is // independent of the underlying name resolution technology. Non-ASCII // characters must first be encoded according to UTF-8 [STD63], and then // each octet of the corresponding UTF-8 sequence must be percent- // encoded to be represented as URI characters. URI producing // applications must not use percent-encoding in host unless it is used // to represent a UTF-8 character sequence. // RFC 3986 Section 3.4 Query // query = *( pchar / "/" / "?" ) // // "... However, as query components are often used to carry identifying information // in the form of "key=value" pairs and one frequently used value is a reference to // another URI, it is sometimes better for usability to avoid percent-encoding those characters....." // // RFC 3986 Section 2.5 Identifying Data (Apply to query section) // // When a new URI scheme defines a component that represents textual // data consisting of characters from the Universal Character Set [UCS], // the data should first be encoded as octets according to the UTF-8 // character encoding [STD63]; then only those octets that do not // correspond to characters in the unreserved set should be percent- // encoded. For example, the character A would be represented as "A", // the character LATIN CAPITAL LETTER A WITH GRAVE would be represented // as "%C3%80", and the character KATAKANA LETTER A would be represented // as "%E3%82%A2". // // RFC 3986 Section 3.5 Fragment // fragment = *( pchar / "/" / "?" ) // // Note that follows the same as query // Based on the extracts the strategy to apply on this method is: // // On scheme ":" hier-part // // Escape or percent encode chars inside : // // - From %00 to %20, // - <"> %22, "%" %25 (If there is encode of "%", there is a risk of // duplicate encoding, encode it when we are sure // that there are not encoded twice) // - "<" %3C, ">" %3E // - "\" %5C, "^" %5E, "`" %60 // - "{" %7B, "|" %7C, "}" %7D // - From %7F ad infinitum (characters from %100 to infinitum should not be used in this // part of an URI, but it is preferred to encode it that omit it). // // The remaining characters must not be encoded // // Characters after ? or # should be percent encoding but only the necessary ones: // // - From %00 to %20 (' ' %20 could encode as +, but %20 also works, so we keep %20) // - <"> %22, "%" %25 (If there is encode of "%", there is a risk of // duplicate encoding, encode it when we are sure // that there are not encoded twice) // - "<" %3C, ">" %3E, // - "\" %5C, "^" %5E, "`" %60 // - "{" %7B, "|" %7C, "}" %7D // - From %7F ad infinitum (each character as many bytes as necessary but take into account // that a single char should contain 2,3 or more bytes!. This data should be encoded // translating from the document character encoding to percent encoding, because this values // could be retrieved from httpRequest.getParameter() and it uses the current character encoding // for decode values) // // "&" should be encoded as "&amp;" because this link is inside an html page, and // put only & is invalid in this context. if ( (c <= (char)0x20) || (c >= (char)0x7F) || c == '"' || c == '<' || c == '>' || c == '\\' || c == '^' || c == '`' || c == '{' || c == '|' || c == '}') { // The percent encoding on this part should be done using UTF-8 charset // as RFC 3986 Section 3.2.2 says. // Also there is a reference on // http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars // that recommend use of UTF-8 instead the document character encoding. // Jetty set by default UTF-8 (see http://jira.codehaus.org/browse/JETTY-113) app = percentEncode(c, "UTF-8"); } else if (c == '%') { if (i + 2 < length) { char c1 = string.charAt(i+1); char c2 = string.charAt(i+2); if ((( c1 >= '0' && c1 <='9') || (c1 >='A' && c1 <='Z') || (c1 >='a' && c1 <='z')) && (( c2 >= '0' && c2 <='9') || (c2 >='A' && c2 <='Z') || (c2 >='a' && c2 <='z'))) { // do not percent encode, because it could be already encoded // and we don't want encode it twice } else { app = percentEncode(c, UTF8); // depends on control dependency: [if], data = [none] } } else { app = percentEncode(c, UTF8); // depends on control dependency: [if], data = [none] } } else if (c == '?' || c == '#') { if (i+1 < length) { // The remaining part of the URI are data that should be encoded // using the document character encoding. app = c + encodeURIQuery(string.substring(i+1), characterEncoding); // depends on control dependency: [if], data = [(i+1] endLoop = true; // depends on control dependency: [if], data = [none] } } else { //No encoding, just do nothing, char will be added later. } if (app != null) { if (sb == null) { sb = new StringBuilder(string.substring(0, i)); // depends on control dependency: [if], data = [none] } sb.append(app); // depends on control dependency: [if], data = [(app] } else { if (sb != null) { sb.append(c); // depends on control dependency: [if], data = [none] } } if (endLoop) { break; } } if (sb == null) { return string; } else { return sb.toString(); } } }
public class class_name { public void setMinuteTickMarksVisible(final boolean VISIBLE) { if (null == minuteTickMarksVisible) { _minuteTickMarksVisible = VISIBLE; fireUpdateEvent(REDRAW_EVENT); } else { minuteTickMarksVisible.set(VISIBLE); } } }
public class class_name { public void setMinuteTickMarksVisible(final boolean VISIBLE) { if (null == minuteTickMarksVisible) { _minuteTickMarksVisible = VISIBLE; // depends on control dependency: [if], data = [none] fireUpdateEvent(REDRAW_EVENT); // depends on control dependency: [if], data = [none] } else { minuteTickMarksVisible.set(VISIBLE); // depends on control dependency: [if], data = [none] } } }
public class class_name { public final boolean add(final Period period) { if (isUtc()) { period.setUtc(true); } else { period.setTimeZone(timezone); } return periods.add(period); } }
public class class_name { public final boolean add(final Period period) { if (isUtc()) { period.setUtc(true); // depends on control dependency: [if], data = [none] } else { period.setTimeZone(timezone); // depends on control dependency: [if], data = [none] } return periods.add(period); } }
public class class_name { Map buildFilterParamMap(List filters) { if(filters == null || filters.size() == 0) return null; String encoded = encodeFilters(filters); if(encoded == null) return null; else { HashMap params = new HashMap(); params.put(PARAM_KEY_FILTER, new String[]{encoded}); return params; } } }
public class class_name { Map buildFilterParamMap(List filters) { if(filters == null || filters.size() == 0) return null; String encoded = encodeFilters(filters); if(encoded == null) return null; else { HashMap params = new HashMap(); params.put(PARAM_KEY_FILTER, new String[]{encoded}); // depends on control dependency: [if], data = [none] return params; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static BigDecimal inverse(final BigDecimal value, final int scale, final int rounding) { if (isNotZero(value)) { return BigDecimal.ONE.divide(value, scale, rounding); } return null; } }
public class class_name { public static BigDecimal inverse(final BigDecimal value, final int scale, final int rounding) { if (isNotZero(value)) { return BigDecimal.ONE.divide(value, scale, rounding); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { public void getAllObjects (ArrayList<ObjectInfo> list) { for (Iterator<Section> iter = getSections(); iter.hasNext(); ) { iter.next().getAllObjects(list); } } }
public class class_name { public void getAllObjects (ArrayList<ObjectInfo> list) { for (Iterator<Section> iter = getSections(); iter.hasNext(); ) { iter.next().getAllObjects(list); // depends on control dependency: [for], data = [iter] } } }
public class class_name { public void marshall(UsageInstruction usageInstruction, ProtocolMarshaller protocolMarshaller) { if (usageInstruction == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(usageInstruction.getType(), TYPE_BINDING); protocolMarshaller.marshall(usageInstruction.getValue(), VALUE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(UsageInstruction usageInstruction, ProtocolMarshaller protocolMarshaller) { if (usageInstruction == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(usageInstruction.getType(), TYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(usageInstruction.getValue(), VALUE_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void each(Consumer<T> operation) { for (T component : components) { operation.accept(component); } } }
public class class_name { public void each(Consumer<T> operation) { for (T component : components) { operation.accept(component); // depends on control dependency: [for], data = [component] } } }
public class class_name { public void marshall(EnvironmentPropertyDescriptions environmentPropertyDescriptions, ProtocolMarshaller protocolMarshaller) { if (environmentPropertyDescriptions == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(environmentPropertyDescriptions.getPropertyGroupDescriptions(), PROPERTYGROUPDESCRIPTIONS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(EnvironmentPropertyDescriptions environmentPropertyDescriptions, ProtocolMarshaller protocolMarshaller) { if (environmentPropertyDescriptions == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(environmentPropertyDescriptions.getPropertyGroupDescriptions(), PROPERTYGROUPDESCRIPTIONS_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static String renameIfExists(String path) { File file = new File(path); if (file.exists() && file.isFile()) { int index = file.getName().lastIndexOf("."); String name = file.getName().substring(0, index); String suffix = index == -1 ? "" : file.getName().substring(index); int i = 1; String newName; do { newName = name + "(" + i + ")" + suffix; i++; } while (existsFile(file.getParent() + File.separator + newName)); return newName; } return file.getName(); } }
public class class_name { public static String renameIfExists(String path) { File file = new File(path); if (file.exists() && file.isFile()) { int index = file.getName().lastIndexOf("."); String name = file.getName().substring(0, index); String suffix = index == -1 ? "" : file.getName().substring(index); int i = 1; String newName; do { newName = name + "(" + i + ")" + suffix; i++; } while (existsFile(file.getParent() + File.separator + newName)); return newName; // depends on control dependency: [if], data = [none] } return file.getName(); } }
public class class_name { public File getCompiled(AssetInfo asset, File starter) throws IOException, ServiceException { File file; synchronized(WebpackCache.class) { file = webpackAssets.get(asset); if (file == null || !file.exists() || file.lastModified() < asset.getFile().lastModified() || (starter != null && file.lastModified() < starter.lastModified())) { file = getOutput(asset); compile(asset, starter, file); return file; } } return file; } }
public class class_name { public File getCompiled(AssetInfo asset, File starter) throws IOException, ServiceException { File file; synchronized(WebpackCache.class) { file = webpackAssets.get(asset); if (file == null || !file.exists() || file.lastModified() < asset.getFile().lastModified() || (starter != null && file.lastModified() < starter.lastModified())) { file = getOutput(asset); // depends on control dependency: [if], data = [none] compile(asset, starter, file); // depends on control dependency: [if], data = [none] return file; // depends on control dependency: [if], data = [none] } } return file; } }
public class class_name { final int writeToPreallocated(StorageChannelOutput out, Map<AbstractIndexPage, Integer> map) { if (!isDirty()) { return pageId; } Integer pageIdpre = map.get(this); if (pageIdpre == null) { throw DBLogger.newFatalInternal("Page not preallocated: " + pageId + " / " + this); } if (isLeaf) { //Page was already reported to FSM during map build-up out.seekPageForWrite(ind.getDataType(), pageId); out.writeShort((short) 0); writeData(out); } else { //now write the sub pages for (int i = 0; i < getNKeys()+1; i++) { AbstractIndexPage p = subPages[i]; if (p == null) { //This can happen if pages are not loaded yet continue; } subPageIds[i] = p.writeToPreallocated(out, map); } //now write the page index out.seekPageForWrite(ind.getDataType(), pageId); out.writeShort((short) subPages.length); out.noCheckWrite(subPageIds); writeKeys(out); } out.flush(); setDirty( false ); ind.statNWrittenPages++; return pageId; } }
public class class_name { final int writeToPreallocated(StorageChannelOutput out, Map<AbstractIndexPage, Integer> map) { if (!isDirty()) { return pageId; // depends on control dependency: [if], data = [none] } Integer pageIdpre = map.get(this); if (pageIdpre == null) { throw DBLogger.newFatalInternal("Page not preallocated: " + pageId + " / " + this); } if (isLeaf) { //Page was already reported to FSM during map build-up out.seekPageForWrite(ind.getDataType(), pageId); // depends on control dependency: [if], data = [none] out.writeShort((short) 0); // depends on control dependency: [if], data = [none] writeData(out); // depends on control dependency: [if], data = [none] } else { //now write the sub pages for (int i = 0; i < getNKeys()+1; i++) { AbstractIndexPage p = subPages[i]; if (p == null) { //This can happen if pages are not loaded yet continue; } subPageIds[i] = p.writeToPreallocated(out, map); // depends on control dependency: [for], data = [i] } //now write the page index out.seekPageForWrite(ind.getDataType(), pageId); // depends on control dependency: [if], data = [none] out.writeShort((short) subPages.length); // depends on control dependency: [if], data = [none] out.noCheckWrite(subPageIds); // depends on control dependency: [if], data = [none] writeKeys(out); // depends on control dependency: [if], data = [none] } out.flush(); setDirty( false ); ind.statNWrittenPages++; return pageId; } }
public class class_name { public static void setField( final Object target, final String name, final Object value ) { final Field field = findField(target.getClass(), name) .orElseThrow(() -> new IllegalArgumentException(name + " not found.")); try { field.setAccessible(true); field.set(target, value); } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } } }
public class class_name { public static void setField( final Object target, final String name, final Object value ) { final Field field = findField(target.getClass(), name) .orElseThrow(() -> new IllegalArgumentException(name + " not found.")); try { field.setAccessible(true); // depends on control dependency: [try], data = [none] field.set(target, value); // depends on control dependency: [try], data = [none] } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void stop() { if (mBackup != null) { mBackup.cancel(true); mBackup = null; } LOG.info("Daily metadata backup stopped"); mScheduledExecutor.shutdownNow(); String waitForMessage = "waiting for daily metadata backup executor service to shut down"; try { if (!mScheduledExecutor.awaitTermination(SHUTDOWN_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { LOG.warn("Timed out " + waitForMessage); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOG.warn("Interrupted while " + waitForMessage); } } }
public class class_name { public void stop() { if (mBackup != null) { mBackup.cancel(true); // depends on control dependency: [if], data = [none] mBackup = null; // depends on control dependency: [if], data = [none] } LOG.info("Daily metadata backup stopped"); mScheduledExecutor.shutdownNow(); String waitForMessage = "waiting for daily metadata backup executor service to shut down"; try { if (!mScheduledExecutor.awaitTermination(SHUTDOWN_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { LOG.warn("Timed out " + waitForMessage); // depends on control dependency: [if], data = [none] } } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOG.warn("Interrupted while " + waitForMessage); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void shuffleFromTo(int from, int to) { if (size == 0) return; checkRangeFromTo(from, to, size); //cern.jet.random.Uniform gen = new cern.jet.random.Uniform(new cern.jet.random.engine.DRand(new java.util.Date())); java.util.Random gen = new java.util.Random(); Object tmpElement; Object[] theElements = elements; int random; for (int i = from; i < to; i++) { //random = gen.nextIntFromTo(i, to); int rp = gen.nextInt(to-i); random = rp + i; //swap(i, random) tmpElement = theElements[random]; theElements[random] = theElements[i]; theElements[i] = tmpElement; } } }
public class class_name { public void shuffleFromTo(int from, int to) { if (size == 0) return; checkRangeFromTo(from, to, size); //cern.jet.random.Uniform gen = new cern.jet.random.Uniform(new cern.jet.random.engine.DRand(new java.util.Date())); java.util.Random gen = new java.util.Random(); Object tmpElement; Object[] theElements = elements; int random; for (int i = from; i < to; i++) { //random = gen.nextIntFromTo(i, to); int rp = gen.nextInt(to-i); random = rp + i; // depends on control dependency: [for], data = [i] //swap(i, random) tmpElement = theElements[random]; // depends on control dependency: [for], data = [none] theElements[random] = theElements[i]; // depends on control dependency: [for], data = [i] theElements[i] = tmpElement; // depends on control dependency: [for], data = [i] } } }
public class class_name { @InService(PageServiceSync.class) public void afterDataFlush(Page newPage, int sequenceFlush) { Page page = _pages.get(newPage.getId()); if (page == newPage) { page.afterDataFlush(this, sequenceFlush); } else { System.out.println("AfterDataFlush mismatch: " + page + " " + newPage); } } }
public class class_name { @InService(PageServiceSync.class) public void afterDataFlush(Page newPage, int sequenceFlush) { Page page = _pages.get(newPage.getId()); if (page == newPage) { page.afterDataFlush(this, sequenceFlush); // depends on control dependency: [if], data = [none] } else { System.out.println("AfterDataFlush mismatch: " + page + " " + newPage); // depends on control dependency: [if], data = [newPage)] } } }
public class class_name { @SuppressWarnings("unused") public void setCronExpression(String cronExpression) { checkFrozen(); try { // check if the cron expression is valid new CronExpression(cronExpression); } catch (Exception e) { throw new CmsIllegalArgumentException( Messages.get().container(Messages.ERR_BAD_CRON_EXPRESSION_2, getJobName(), cronExpression)); } m_cronExpression = cronExpression; } }
public class class_name { @SuppressWarnings("unused") public void setCronExpression(String cronExpression) { checkFrozen(); try { // check if the cron expression is valid new CronExpression(cronExpression); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new CmsIllegalArgumentException( Messages.get().container(Messages.ERR_BAD_CRON_EXPRESSION_2, getJobName(), cronExpression)); } // depends on control dependency: [catch], data = [none] m_cronExpression = cronExpression; } }
public class class_name { public boolean isDeleted(String identifier) { ItemState lastState = changesLog.getItemState(identifier); if (lastState != null && lastState.isDeleted()) { return true; } return false; } }
public class class_name { public boolean isDeleted(String identifier) { ItemState lastState = changesLog.getItemState(identifier); if (lastState != null && lastState.isDeleted()) { return true; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { public UploadResponse upload(File photo, String title, String description, List<String> tags, Boolean isPublic, Boolean isFriend, Boolean isFamily, JinxConstants.SafetyLevel safetyLevel, JinxConstants.ContentType contentType, Boolean hidden, Boolean async) throws JinxException { JinxUtils.validateParams(photo); byte[] photoData = new byte[(int) photo.length()]; FileInputStream in = null; try { in = new FileInputStream(photo); in.read(photoData); if (JinxUtils.isNullOrEmpty(title)) { int index = photo.getName().indexOf('.'); if (index > 0) { title = photo.getName().substring(0, index); } else { title = photo.getName(); } } } catch (Exception e) { throw new JinxException("Unable to load data from photo " + photo.getAbsolutePath(), e); } finally { JinxUtils.close(in); } return upload(photoData, title, description, tags, isPublic, isFriend, isFamily, safetyLevel, contentType, hidden, async); } }
public class class_name { public UploadResponse upload(File photo, String title, String description, List<String> tags, Boolean isPublic, Boolean isFriend, Boolean isFamily, JinxConstants.SafetyLevel safetyLevel, JinxConstants.ContentType contentType, Boolean hidden, Boolean async) throws JinxException { JinxUtils.validateParams(photo); byte[] photoData = new byte[(int) photo.length()]; FileInputStream in = null; try { in = new FileInputStream(photo); in.read(photoData); if (JinxUtils.isNullOrEmpty(title)) { int index = photo.getName().indexOf('.'); if (index > 0) { title = photo.getName().substring(0, index); // depends on control dependency: [if], data = [none] } else { title = photo.getName(); // depends on control dependency: [if], data = [none] } } } catch (Exception e) { throw new JinxException("Unable to load data from photo " + photo.getAbsolutePath(), e); } finally { JinxUtils.close(in); } return upload(photoData, title, description, tags, isPublic, isFriend, isFamily, safetyLevel, contentType, hidden, async); } }
public class class_name { public Pattern getPattern(String name, Pattern defaultValue) { String valString = get(name); if (null == valString || valString.isEmpty()) { return defaultValue; } try { return Pattern.compile(valString); } catch (PatternSyntaxException pse) { LOG.warn("Regular expression '" + valString + "' for property '" + name + "' not valid. Using default", pse); return defaultValue; } } }
public class class_name { public Pattern getPattern(String name, Pattern defaultValue) { String valString = get(name); if (null == valString || valString.isEmpty()) { return defaultValue; // depends on control dependency: [if], data = [none] } try { return Pattern.compile(valString); // depends on control dependency: [try], data = [none] } catch (PatternSyntaxException pse) { LOG.warn("Regular expression '" + valString + "' for property '" + name + "' not valid. Using default", pse); return defaultValue; } // depends on control dependency: [catch], data = [none] } }
public class class_name { private String normalizeText(String text) { String[] tokens = StringUtils.split(text, "\n"); for (int i = 0; i < tokens.length; i++) { tokens[i] = tokens[i].trim(); } return StringUtils.join(tokens, " ").trim(); } }
public class class_name { private String normalizeText(String text) { String[] tokens = StringUtils.split(text, "\n"); for (int i = 0; i < tokens.length; i++) { tokens[i] = tokens[i].trim(); // depends on control dependency: [for], data = [i] } return StringUtils.join(tokens, " ").trim(); } }
public class class_name { protected boolean hasKey() { boolean result = false; String requestURI = this.request.getUri(); parseKeys(requestURI); if(this.parsedKeys != null) { result = true; } else { logger.error("Error when validating request. No key specified."); RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Error: No key specified !"); } return result; } }
public class class_name { protected boolean hasKey() { boolean result = false; String requestURI = this.request.getUri(); parseKeys(requestURI); if(this.parsedKeys != null) { result = true; // depends on control dependency: [if], data = [none] } else { logger.error("Error when validating request. No key specified."); // depends on control dependency: [if], data = [none] RestErrorHandler.writeErrorResponse(this.messageEvent, HttpResponseStatus.BAD_REQUEST, "Error: No key specified !"); // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { String partialEncode() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "partialEncode()"); String encoded = null; // If we have a cached version of the string, use it. if (cachedPartialEncodedString != null) { encoded = cachedPartialEncodedString; } else { // Get a copy of the properties which make up this Destination. We need a // copy since we remove the jms name before iterating over the other // properties, and encoding them. Map<String, Object> destProps = getCopyOfProperties(); // Remove the props that are stored in the reply header. // NB. The deliveryMode is used in the creation of the reply header, // but must still be carried. destProps.remove(JmsInternalConstants.DEST_NAME); destProps.remove(JmsInternalConstants.DEST_DISCRIM); destProps.remove(JmsInternalConstants.PRIORITY); destProps.remove(JmsInternalConstants.TIME_TO_LIVE); destProps.remove(JmsInternalConstants.FORWARD_ROUTING_PATH); destProps.remove(JmsInternalConstants.REVERSE_ROUTING_PATH); // Pass off to a common helper method (between full and partial encodings). encoded = encodeMap(destProps); // Now store this string in the cache in case we need it later. cachedPartialEncodedString = encoded; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "partialEncode", encoded); return encoded; } }
public class class_name { String partialEncode() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "partialEncode()"); String encoded = null; // If we have a cached version of the string, use it. if (cachedPartialEncodedString != null) { encoded = cachedPartialEncodedString; // depends on control dependency: [if], data = [none] } else { // Get a copy of the properties which make up this Destination. We need a // copy since we remove the jms name before iterating over the other // properties, and encoding them. Map<String, Object> destProps = getCopyOfProperties(); // Remove the props that are stored in the reply header. // NB. The deliveryMode is used in the creation of the reply header, // but must still be carried. destProps.remove(JmsInternalConstants.DEST_NAME); // depends on control dependency: [if], data = [none] destProps.remove(JmsInternalConstants.DEST_DISCRIM); // depends on control dependency: [if], data = [none] destProps.remove(JmsInternalConstants.PRIORITY); // depends on control dependency: [if], data = [none] destProps.remove(JmsInternalConstants.TIME_TO_LIVE); // depends on control dependency: [if], data = [none] destProps.remove(JmsInternalConstants.FORWARD_ROUTING_PATH); // depends on control dependency: [if], data = [none] destProps.remove(JmsInternalConstants.REVERSE_ROUTING_PATH); // depends on control dependency: [if], data = [none] // Pass off to a common helper method (between full and partial encodings). encoded = encodeMap(destProps); // depends on control dependency: [if], data = [none] // Now store this string in the cache in case we need it later. cachedPartialEncodedString = encoded; // depends on control dependency: [if], data = [none] } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "partialEncode", encoded); return encoded; } }
public class class_name { private ImmutableNode mapToNode(final Builder builder, final Map<String, Object> map) { for (final Map.Entry<String, Object> entry : map.entrySet()) { final String key = entry.getKey(); final Object value = entry.getValue(); if (value instanceof List) { // For a list, add each list item as a child of this node. for (final Object item : (List)value) { addChildNode(builder, key, item); } } else { // Otherwise, add the value as a child of this node. addChildNode(builder, key, value); } } return builder.create(); } }
public class class_name { private ImmutableNode mapToNode(final Builder builder, final Map<String, Object> map) { for (final Map.Entry<String, Object> entry : map.entrySet()) { final String key = entry.getKey(); final Object value = entry.getValue(); if (value instanceof List) { // For a list, add each list item as a child of this node. for (final Object item : (List)value) { addChildNode(builder, key, item); // depends on control dependency: [for], data = [item] } } else { // Otherwise, add the value as a child of this node. addChildNode(builder, key, value); // depends on control dependency: [if], data = [none] } } return builder.create(); } }
public class class_name { public static DoubleStreamEx iterate(double seed, DoublePredicate predicate, DoubleUnaryOperator f) { Objects.requireNonNull(f); Objects.requireNonNull(predicate); Spliterator.OfDouble spliterator = new Spliterators.AbstractDoubleSpliterator(Long.MAX_VALUE, Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL) { double prev; boolean started, finished; @Override public boolean tryAdvance(DoubleConsumer action) { Objects.requireNonNull(action); if (finished) return false; double t; if (started) t = f.applyAsDouble(prev); else { t = seed; started = true; } if (!predicate.test(t)) { finished = true; return false; } action.accept(prev = t); return true; } @Override public void forEachRemaining(DoubleConsumer action) { Objects.requireNonNull(action); if (finished) return; finished = true; double t = started ? f.applyAsDouble(prev) : seed; while (predicate.test(t)) { action.accept(t); t = f.applyAsDouble(t); } } }; return of(spliterator); } }
public class class_name { public static DoubleStreamEx iterate(double seed, DoublePredicate predicate, DoubleUnaryOperator f) { Objects.requireNonNull(f); Objects.requireNonNull(predicate); Spliterator.OfDouble spliterator = new Spliterators.AbstractDoubleSpliterator(Long.MAX_VALUE, Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL) { double prev; boolean started, finished; @Override public boolean tryAdvance(DoubleConsumer action) { Objects.requireNonNull(action); if (finished) return false; double t; if (started) t = f.applyAsDouble(prev); else { t = seed; // depends on control dependency: [if], data = [none] started = true; // depends on control dependency: [if], data = [none] } if (!predicate.test(t)) { finished = true; // depends on control dependency: [if], data = [none] return false; // depends on control dependency: [if], data = [none] } action.accept(prev = t); return true; } @Override public void forEachRemaining(DoubleConsumer action) { Objects.requireNonNull(action); if (finished) return; finished = true; double t = started ? f.applyAsDouble(prev) : seed; while (predicate.test(t)) { action.accept(t); // depends on control dependency: [while], data = [none] t = f.applyAsDouble(t); // depends on control dependency: [while], data = [none] } } }; return of(spliterator); } }
public class class_name { private int getTargetPort() { int port = getVirtualPort(); if (NOTSET == port) { port = (isIncoming()) ? getServiceContext().getLocalPort() : getServiceContext().getRemotePort(); } return port; } }
public class class_name { private int getTargetPort() { int port = getVirtualPort(); if (NOTSET == port) { port = (isIncoming()) ? getServiceContext().getLocalPort() : getServiceContext().getRemotePort(); // depends on control dependency: [if], data = [none] } return port; } }
public class class_name { public static void fire(final HasSummernoteKeyDownHandlers source, NativeEvent nativeEvent) { if (TYPE != null) { SummernoteKeyDownEvent event = new SummernoteKeyDownEvent(nativeEvent); source.fireEvent(event); } } }
public class class_name { public static void fire(final HasSummernoteKeyDownHandlers source, NativeEvent nativeEvent) { if (TYPE != null) { SummernoteKeyDownEvent event = new SummernoteKeyDownEvent(nativeEvent); source.fireEvent(event); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void unpack() throws InstallationFailedException { System.out.println("Preparing FEDORA_HOME..."); if (!_installDir.exists() && !_installDir.mkdirs()) { throw new InstallationFailedException( "Unable to create FEDORA_HOME: " + _installDir.getAbsolutePath()); } if (!_installDir.isDirectory()) { throw new InstallationFailedException(_installDir.getAbsolutePath() + " is not a directory"); } try { Zip.unzip(_dist.get(Distribution.FEDORA_HOME), _installDir); setScriptsExecutable(new File(_installDir, "client" + File.separator + "bin")); File serverDir = new File(_installDir, "server"); if (_clientOnlyInstall) { FileUtils.delete(serverDir); } else { setScriptsExecutable(new File(serverDir, "bin")); } } catch (IOException e) { throw new InstallationFailedException(e.getMessage(), e); } } }
public class class_name { private void unpack() throws InstallationFailedException { System.out.println("Preparing FEDORA_HOME..."); if (!_installDir.exists() && !_installDir.mkdirs()) { throw new InstallationFailedException( "Unable to create FEDORA_HOME: " + _installDir.getAbsolutePath()); } if (!_installDir.isDirectory()) { throw new InstallationFailedException(_installDir.getAbsolutePath() + " is not a directory"); } try { Zip.unzip(_dist.get(Distribution.FEDORA_HOME), _installDir); setScriptsExecutable(new File(_installDir, "client" + File.separator + "bin")); File serverDir = new File(_installDir, "server"); if (_clientOnlyInstall) { FileUtils.delete(serverDir); // depends on control dependency: [if], data = [none] } else { setScriptsExecutable(new File(serverDir, "bin")); // depends on control dependency: [if], data = [none] } } catch (IOException e) { throw new InstallationFailedException(e.getMessage(), e); } } }
public class class_name { public List<String> listEscapeJava(final List<?> target) { if (target == null) { return null; } final List<String> result = new ArrayList<String>(target.size() + 2); for (final Object element : target) { result.add(escapeJava(element)); } return result; } }
public class class_name { public List<String> listEscapeJava(final List<?> target) { if (target == null) { return null; // depends on control dependency: [if], data = [none] } final List<String> result = new ArrayList<String>(target.size() + 2); for (final Object element : target) { result.add(escapeJava(element)); // depends on control dependency: [for], data = [element] } return result; } }
public class class_name { public void removeMap(String mapId) { IndexInformation info = cache.remove(mapId); if (info != null) { totalMemoryUsed.addAndGet(-info.getSize()); if (!queue.remove(mapId)) { LOG.warn("Map ID" + mapId + " not found in queue!!"); } } else { LOG.info("Map ID " + mapId + " not found in cache"); } } }
public class class_name { public void removeMap(String mapId) { IndexInformation info = cache.remove(mapId); if (info != null) { totalMemoryUsed.addAndGet(-info.getSize()); // depends on control dependency: [if], data = [none] if (!queue.remove(mapId)) { LOG.warn("Map ID" + mapId + " not found in queue!!"); // depends on control dependency: [if], data = [none] } } else { LOG.info("Map ID " + mapId + " not found in cache"); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static void warn(String msg) { if (loggedMessages.contains(msg)) { return; } Log.w(TAG, msg); loggedMessages.add(msg); } }
public class class_name { public static void warn(String msg) { if (loggedMessages.contains(msg)) { return; // depends on control dependency: [if], data = [none] } Log.w(TAG, msg); loggedMessages.add(msg); } }
public class class_name { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (TypeElement dataSource : dataSets) { SQLiteDatabaseSchema currentSchema = createDataSource(dataSource); // Analyze beans BEFORE daos, because beans are needed for DAO // definition for (String daoName : currentSchema.getDaoNameSet()) { // check dao into bean definition createSQLEntityFromDao(currentSchema, dataSource, daoName); } // end foreach bean // sort table by its name, BEFORE inject generated tables and entities Collections.sort(currentSchema.getCollection(), new Comparator<SQLiteDaoDefinition>() { @Override public int compare(SQLiteDaoDefinition o1, SQLiteDaoDefinition o2) { return o1.getTableName().compareTo(o2.getTableName()); } }); // DAO analysis // Get all generated dao definitions for (String generatedDaoItem : currentSchema.getDaoNameSet()) { createSQLDaoDefinition(currentSchema, globalBeanElements, globalDaoElements, generatedDaoItem); } analyzeForeignKey(currentSchema); // Relation must be done AFTER foreign key building!!! analyzeRelations(currentSchema); // Analyze custom bean analyzeCustomBeanForSelect(currentSchema); if (currentSchema.getCollection().size() == 0) { AssertKripton.fail("DataSource class %s with @%s annotation has no defined DAOs", currentSchema.getElement().getSimpleName().toString(), BindDataSource.class.getSimpleName(), BindDao.class.getSimpleName() ); // info(msg); return true; } // for each dao definition, we define its uid int uid = 0; for (SQLiteDaoDefinition daoDefinition : currentSchema.getCollection()) { String daoFieldName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, daoDefinition.getName()) + "_UID"; daoDefinition.daoUidName = daoFieldName; daoDefinition.daoUidValue = uid; uid++; } schemas.add(currentSchema); } // end foreach dataSource return true; } }
public class class_name { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (TypeElement dataSource : dataSets) { SQLiteDatabaseSchema currentSchema = createDataSource(dataSource); // Analyze beans BEFORE daos, because beans are needed for DAO // definition for (String daoName : currentSchema.getDaoNameSet()) { // check dao into bean definition createSQLEntityFromDao(currentSchema, dataSource, daoName); // depends on control dependency: [for], data = [daoName] } // end foreach bean // sort table by its name, BEFORE inject generated tables and entities Collections.sort(currentSchema.getCollection(), new Comparator<SQLiteDaoDefinition>() { @Override public int compare(SQLiteDaoDefinition o1, SQLiteDaoDefinition o2) { return o1.getTableName().compareTo(o2.getTableName()); } }); // depends on control dependency: [for], data = [none] // DAO analysis // Get all generated dao definitions for (String generatedDaoItem : currentSchema.getDaoNameSet()) { createSQLDaoDefinition(currentSchema, globalBeanElements, globalDaoElements, generatedDaoItem); // depends on control dependency: [for], data = [generatedDaoItem] } analyzeForeignKey(currentSchema); // depends on control dependency: [for], data = [none] // Relation must be done AFTER foreign key building!!! analyzeRelations(currentSchema); // depends on control dependency: [for], data = [none] // Analyze custom bean analyzeCustomBeanForSelect(currentSchema); // depends on control dependency: [for], data = [none] if (currentSchema.getCollection().size() == 0) { AssertKripton.fail("DataSource class %s with @%s annotation has no defined DAOs", currentSchema.getElement().getSimpleName().toString(), BindDataSource.class.getSimpleName(), BindDao.class.getSimpleName() ); // depends on control dependency: [if], data = [none] // info(msg); return true; // depends on control dependency: [if], data = [none] } // for each dao definition, we define its uid int uid = 0; for (SQLiteDaoDefinition daoDefinition : currentSchema.getCollection()) { String daoFieldName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, daoDefinition.getName()) + "_UID"; daoDefinition.daoUidName = daoFieldName; // depends on control dependency: [for], data = [daoDefinition] daoDefinition.daoUidValue = uid; // depends on control dependency: [for], data = [daoDefinition] uid++; // depends on control dependency: [for], data = [none] } schemas.add(currentSchema); // depends on control dependency: [for], data = [none] } // end foreach dataSource return true; } }
public class class_name { public String createRunner(Vector<Object> runnerParams) { try { Runner runner = XmlRpcDataMarshaller.toRunner(runnerParams); service.createRunner(runner); log.debug( "Created Runner: " + runner.getName() ); return SUCCESS; } catch (Exception e) { return errorAsString( e, RUNNER_CREATE_FAILED ); } } }
public class class_name { public String createRunner(Vector<Object> runnerParams) { try { Runner runner = XmlRpcDataMarshaller.toRunner(runnerParams); service.createRunner(runner); // depends on control dependency: [try], data = [none] log.debug( "Created Runner: " + runner.getName() ); // depends on control dependency: [try], data = [none] return SUCCESS; // depends on control dependency: [try], data = [none] } catch (Exception e) { return errorAsString( e, RUNNER_CREATE_FAILED ); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @RequirePOST public HttpResponse doStop() { lock.writeLock().lock(); // need write lock as interrupt will change the field try { if (executable != null) { getParentOf(executable).getOwnerTask().checkAbortPermission(); interrupt(); } } finally { lock.writeLock().unlock(); } return HttpResponses.forwardToPreviousPage(); } }
public class class_name { @RequirePOST public HttpResponse doStop() { lock.writeLock().lock(); // need write lock as interrupt will change the field try { if (executable != null) { getParentOf(executable).getOwnerTask().checkAbortPermission(); // depends on control dependency: [if], data = [(executable] interrupt(); // depends on control dependency: [if], data = [none] } } finally { lock.writeLock().unlock(); } return HttpResponses.forwardToPreviousPage(); } }
public class class_name { public static SecretKeyFactory getSecretKeyFactory(String algorithm) { final Provider provider = GlobalBouncyCastleProvider.INSTANCE.getProvider(); SecretKeyFactory keyFactory; try { keyFactory = (null == provider) // ? SecretKeyFactory.getInstance(getMainAlgorithm(algorithm)) // : SecretKeyFactory.getInstance(getMainAlgorithm(algorithm), provider); } catch (NoSuchAlgorithmException e) { throw new CryptoException(e); } return keyFactory; } }
public class class_name { public static SecretKeyFactory getSecretKeyFactory(String algorithm) { final Provider provider = GlobalBouncyCastleProvider.INSTANCE.getProvider(); SecretKeyFactory keyFactory; try { keyFactory = (null == provider) // ? SecretKeyFactory.getInstance(getMainAlgorithm(algorithm)) // : SecretKeyFactory.getInstance(getMainAlgorithm(algorithm), provider); // depends on control dependency: [try], data = [none] } catch (NoSuchAlgorithmException e) { throw new CryptoException(e); } // depends on control dependency: [catch], data = [none] return keyFactory; } }
public class class_name { @SuppressWarnings({ "squid:S1166", "squid:S2221" }) boolean isValidDragSource(final VDragEvent drag, final UIDL configuration) { try { final String dragSource = drag.getTransferable().getDragSource().getWidget().getElement().getId(); final String dragSourcePrefix = configuration.getStringAttribute(DRAG_SOURCE); if (dragSource.startsWith(dragSourcePrefix)) { return true; } } catch (final Exception e) { // log and continue LOGGER.log(Level.SEVERE, "Error verifying drag source: " + e.getLocalizedMessage()); } return false; } }
public class class_name { @SuppressWarnings({ "squid:S1166", "squid:S2221" }) boolean isValidDragSource(final VDragEvent drag, final UIDL configuration) { try { final String dragSource = drag.getTransferable().getDragSource().getWidget().getElement().getId(); final String dragSourcePrefix = configuration.getStringAttribute(DRAG_SOURCE); if (dragSource.startsWith(dragSourcePrefix)) { return true; // depends on control dependency: [if], data = [none] } } catch (final Exception e) { // log and continue LOGGER.log(Level.SEVERE, "Error verifying drag source: " + e.getLocalizedMessage()); } // depends on control dependency: [catch], data = [none] return false; } }
public class class_name { protected void statusInfoMessage(final String tag) { if(logger.isInfoEnabled()) { logger.info(tag + " : [partition: " + currentPartition + ", partitionFetched: " + currentPartitionFetched + "] for store " + storageEngine.getName()); } } }
public class class_name { protected void statusInfoMessage(final String tag) { if(logger.isInfoEnabled()) { logger.info(tag + " : [partition: " + currentPartition + ", partitionFetched: " + currentPartitionFetched + "] for store " + storageEngine.getName()); // depends on control dependency: [if], data = [none] } } }
public class class_name { private int updateProgress(int checkedTiles, int tilesNumber, int oldPercent, Collection<ImageBuffer> tiles) { final int percent = getProgressPercent(checkedTiles, tilesNumber); if (percent != oldPercent) { for (final ProgressListener listener : listeners) { listener.notifyProgress(percent, tiles); } } return percent; } }
public class class_name { private int updateProgress(int checkedTiles, int tilesNumber, int oldPercent, Collection<ImageBuffer> tiles) { final int percent = getProgressPercent(checkedTiles, tilesNumber); if (percent != oldPercent) { for (final ProgressListener listener : listeners) { listener.notifyProgress(percent, tiles); // depends on control dependency: [for], data = [listener] } } return percent; } }
public class class_name { public static CmsPositionBean getEditablePosition(Element editable) { CmsPositionBean result = new CmsPositionBean(); int dummy = -999; // setting minimum height result.setHeight(20); result.setWidth(60); result.setLeft(dummy); result.setTop(dummy); Element sibling = editable.getNextSiblingElement(); while ((sibling != null) && !CmsDomUtil.hasClass(CmsGwtConstants.CLASS_EDITABLE, sibling) && !CmsDomUtil.hasClass(CmsGwtConstants.CLASS_EDITABLE_END, sibling)) { // only consider element nodes if ((sibling.getNodeType() == Node.ELEMENT_NODE) && !sibling.getTagName().equalsIgnoreCase(Tag.script.name())) { if (!CmsDomUtil.hasClass(CmsGwtConstants.CLASS_EDITABLE_SKIP, sibling)) { CmsPositionBean siblingPos = CmsPositionBean.generatePositionInfo(sibling); result.setLeft( ((result.getLeft() == dummy) || (siblingPos.getLeft() < result.getLeft())) ? siblingPos.getLeft() : result.getLeft()); result.setTop( ((result.getTop() == dummy) || (siblingPos.getTop() < result.getTop())) ? siblingPos.getTop() : result.getTop()); result.setHeight( ((result.getTop() + result.getHeight()) > (siblingPos.getTop() + siblingPos.getHeight())) ? result.getHeight() : (siblingPos.getTop() + siblingPos.getHeight()) - result.getTop()); result.setWidth( ((result.getLeft() + result.getWidth()) > (siblingPos.getLeft() + siblingPos.getWidth())) ? result.getWidth() : (siblingPos.getLeft() + siblingPos.getWidth()) - result.getLeft()); } } sibling = sibling.getNextSiblingElement(); } if ((result.getTop() == dummy) && (result.getLeft() == dummy)) { result = CmsPositionBean.generatePositionInfo(editable); } if (result.getHeight() == -1) { // in case no height was set result = CmsPositionBean.generatePositionInfo(editable); result.setHeight(20); result.setWidth((result.getWidth() < 60) ? 60 : result.getWidth()); } return result; } }
public class class_name { public static CmsPositionBean getEditablePosition(Element editable) { CmsPositionBean result = new CmsPositionBean(); int dummy = -999; // setting minimum height result.setHeight(20); result.setWidth(60); result.setLeft(dummy); result.setTop(dummy); Element sibling = editable.getNextSiblingElement(); while ((sibling != null) && !CmsDomUtil.hasClass(CmsGwtConstants.CLASS_EDITABLE, sibling) && !CmsDomUtil.hasClass(CmsGwtConstants.CLASS_EDITABLE_END, sibling)) { // only consider element nodes if ((sibling.getNodeType() == Node.ELEMENT_NODE) && !sibling.getTagName().equalsIgnoreCase(Tag.script.name())) { if (!CmsDomUtil.hasClass(CmsGwtConstants.CLASS_EDITABLE_SKIP, sibling)) { CmsPositionBean siblingPos = CmsPositionBean.generatePositionInfo(sibling); result.setLeft( ((result.getLeft() == dummy) || (siblingPos.getLeft() < result.getLeft())) ? siblingPos.getLeft() : result.getLeft()); // depends on control dependency: [if], data = [none] result.setTop( ((result.getTop() == dummy) || (siblingPos.getTop() < result.getTop())) ? siblingPos.getTop() : result.getTop()); // depends on control dependency: [if], data = [none] result.setHeight( ((result.getTop() + result.getHeight()) > (siblingPos.getTop() + siblingPos.getHeight())) ? result.getHeight() : (siblingPos.getTop() + siblingPos.getHeight()) - result.getTop()); // depends on control dependency: [if], data = [none] result.setWidth( ((result.getLeft() + result.getWidth()) > (siblingPos.getLeft() + siblingPos.getWidth())) ? result.getWidth() : (siblingPos.getLeft() + siblingPos.getWidth()) - result.getLeft()); // depends on control dependency: [if], data = [none] } } sibling = sibling.getNextSiblingElement(); // depends on control dependency: [while], data = [none] } if ((result.getTop() == dummy) && (result.getLeft() == dummy)) { result = CmsPositionBean.generatePositionInfo(editable); // depends on control dependency: [if], data = [none] } if (result.getHeight() == -1) { // in case no height was set result = CmsPositionBean.generatePositionInfo(editable); // depends on control dependency: [if], data = [none] result.setHeight(20); // depends on control dependency: [if], data = [none] result.setWidth((result.getWidth() < 60) ? 60 : result.getWidth()); // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { @Override public boolean accept(Stanza message) { if (!message.hasStanzaIdSet()) { return false; } if (super.accept(message)) { ExtensionElement extension = message.getExtension(ChatStateManager.NAMESPACE); String chatStateElementName = extension.getElementName(); ChatState state; try { state = ChatState.valueOf(chatStateElementName); return (state == ChatState.active); } catch (Exception ex) { return false; } } return true; } }
public class class_name { @Override public boolean accept(Stanza message) { if (!message.hasStanzaIdSet()) { return false; // depends on control dependency: [if], data = [none] } if (super.accept(message)) { ExtensionElement extension = message.getExtension(ChatStateManager.NAMESPACE); String chatStateElementName = extension.getElementName(); ChatState state; try { state = ChatState.valueOf(chatStateElementName); // depends on control dependency: [try], data = [none] return (state == ChatState.active); // depends on control dependency: [try], data = [none] } catch (Exception ex) { return false; } // depends on control dependency: [catch], data = [none] } return true; } }
public class class_name { private void constructFailureStates() { Queue<State> queue = new LinkedBlockingDeque<State>(); // 第一步,将深度为1的节点的failure设为根节点 for (State depthOneState : this.rootState.getStates()) { depthOneState.setFailure(this.rootState); queue.add(depthOneState); } this.failureStatesConstructed = true; // 第二步,为深度 > 1 的节点建立failure表,这是一个bfs while (!queue.isEmpty()) { State currentState = queue.remove(); for (Character transition : currentState.getTransitions()) { State targetState = currentState.nextState(transition); queue.add(targetState); State traceFailureState = currentState.failure(); while (traceFailureState.nextState(transition) == null) { traceFailureState = traceFailureState.failure(); } State newFailureState = traceFailureState.nextState(transition); targetState.setFailure(newFailureState); targetState.addEmit(newFailureState.emit()); } } } }
public class class_name { private void constructFailureStates() { Queue<State> queue = new LinkedBlockingDeque<State>(); // 第一步,将深度为1的节点的failure设为根节点 for (State depthOneState : this.rootState.getStates()) { depthOneState.setFailure(this.rootState); // depends on control dependency: [for], data = [depthOneState] queue.add(depthOneState); // depends on control dependency: [for], data = [depthOneState] } this.failureStatesConstructed = true; // 第二步,为深度 > 1 的节点建立failure表,这是一个bfs while (!queue.isEmpty()) { State currentState = queue.remove(); for (Character transition : currentState.getTransitions()) { State targetState = currentState.nextState(transition); queue.add(targetState); // depends on control dependency: [for], data = [none] State traceFailureState = currentState.failure(); while (traceFailureState.nextState(transition) == null) { traceFailureState = traceFailureState.failure(); // depends on control dependency: [while], data = [none] } State newFailureState = traceFailureState.nextState(transition); targetState.setFailure(newFailureState); // depends on control dependency: [for], data = [none] targetState.addEmit(newFailureState.emit()); // depends on control dependency: [for], data = [none] } } } }
public class class_name { private String[] parseLine(String nextLine, boolean multi) { if (!multi && pending != null) { pending = null; } if (nextLine == null) { if (pending != null) { String s = pending; pending = null; return new String[] { s }; } else { return null; } } List<String> tokensOnThisLine = new ArrayList<String>(); StringBuilder sb = new StringBuilder(INITIAL_READ_SIZE); boolean inQuotes = false; if (pending != null) { sb.append(pending); pending = null; inQuotes = true; } for (int i = 0; i < nextLine.length(); i++) { char c = nextLine.charAt(i); if (format.isEscape(c)) { if (isNextCharacterEscapable(nextLine, inQuotes || inField, i)) { sb.append(nextLine.charAt(i + 1)); i++; } } else if (c == format.getDelimiter()) { if (isNextCharacterEscapedQuote(nextLine, inQuotes || inField, i)) { sb.append(nextLine.charAt(i + 1)); i++; } else { inQuotes = !inQuotes; // the tricky case of an embedded quote in the middle: // a,bc"d"ef,g if (!format.isStrictQuotes()) { if (i > 2 // not on the beginning of the line // not at the beginning of an escape // sequence && !format.isSeparator(nextLine.charAt(i - 1)) && nextLine.length() > (i + 1) // not at the end of an escape sequence && !format.isSeparator(nextLine.charAt(i + 1)) // not ) { // discard white space leading up to quote if (ignoreLeadingWhiteSpace && sb.length() > 0 && isAllWhiteSpace(sb)) { sb = new StringBuilder(INITIAL_READ_SIZE); } else { sb.append(c); } } } } inField = !inField; } else if (format.isSeparator(c) && !inQuotes) { tokensOnThisLine.add(sb.toString()); sb = new StringBuilder(INITIAL_READ_SIZE); // start work on next // token inField = false; } else { if (!format.isStrictQuotes() || inQuotes) { sb.append(c); inField = true; } } } // line is done - check status if (inQuotes) { if (multi) { // continuing a quoted section, re-append newline sb.append("\n"); pending = sb.toString(); sb = null; // this partial content is not to be added to field // list yet } else { throw new RuntimeException("Un-terminated quoted field at end of CSV line"); } } if (sb != null) { tokensOnThisLine.add(sb.toString()); } return tokensOnThisLine.toArray(new String[tokensOnThisLine.size()]); } }
public class class_name { private String[] parseLine(String nextLine, boolean multi) { if (!multi && pending != null) { pending = null; // depends on control dependency: [if], data = [none] } if (nextLine == null) { if (pending != null) { String s = pending; pending = null; // depends on control dependency: [if], data = [none] return new String[] { s }; // depends on control dependency: [if], data = [none] } else { return null; // depends on control dependency: [if], data = [none] } } List<String> tokensOnThisLine = new ArrayList<String>(); StringBuilder sb = new StringBuilder(INITIAL_READ_SIZE); boolean inQuotes = false; if (pending != null) { sb.append(pending); // depends on control dependency: [if], data = [(pending] pending = null; // depends on control dependency: [if], data = [none] inQuotes = true; // depends on control dependency: [if], data = [none] } for (int i = 0; i < nextLine.length(); i++) { char c = nextLine.charAt(i); if (format.isEscape(c)) { if (isNextCharacterEscapable(nextLine, inQuotes || inField, i)) { sb.append(nextLine.charAt(i + 1)); // depends on control dependency: [if], data = [none] i++; // depends on control dependency: [if], data = [none] } } else if (c == format.getDelimiter()) { if (isNextCharacterEscapedQuote(nextLine, inQuotes || inField, i)) { sb.append(nextLine.charAt(i + 1)); // depends on control dependency: [if], data = [none] i++; // depends on control dependency: [if], data = [none] } else { inQuotes = !inQuotes; // depends on control dependency: [if], data = [none] // the tricky case of an embedded quote in the middle: // a,bc"d"ef,g if (!format.isStrictQuotes()) { if (i > 2 // not on the beginning of the line // not at the beginning of an escape // sequence && !format.isSeparator(nextLine.charAt(i - 1)) && nextLine.length() > (i + 1) // not at the end of an escape sequence && !format.isSeparator(nextLine.charAt(i + 1)) // not ) { // discard white space leading up to quote if (ignoreLeadingWhiteSpace && sb.length() > 0 && isAllWhiteSpace(sb)) { sb = new StringBuilder(INITIAL_READ_SIZE); // depends on control dependency: [if], data = [none] } else { sb.append(c); // depends on control dependency: [if], data = [none] } } } } inField = !inField; // depends on control dependency: [if], data = [none] } else if (format.isSeparator(c) && !inQuotes) { tokensOnThisLine.add(sb.toString()); // depends on control dependency: [if], data = [none] sb = new StringBuilder(INITIAL_READ_SIZE); // start work on next // depends on control dependency: [if], data = [none] // token inField = false; // depends on control dependency: [if], data = [none] } else { if (!format.isStrictQuotes() || inQuotes) { sb.append(c); // depends on control dependency: [if], data = [none] inField = true; // depends on control dependency: [if], data = [none] } } } // line is done - check status if (inQuotes) { if (multi) { // continuing a quoted section, re-append newline sb.append("\n"); // depends on control dependency: [if], data = [none] pending = sb.toString(); // depends on control dependency: [if], data = [none] sb = null; // this partial content is not to be added to field // depends on control dependency: [if], data = [none] // list yet } else { throw new RuntimeException("Un-terminated quoted field at end of CSV line"); } } if (sb != null) { tokensOnThisLine.add(sb.toString()); // depends on control dependency: [if], data = [(sb] } return tokensOnThisLine.toArray(new String[tokensOnThisLine.size()]); } }
public class class_name { public void setSupportedPlatforms(java.util.Collection<String> supportedPlatforms) { if (supportedPlatforms == null) { this.supportedPlatforms = null; return; } this.supportedPlatforms = new java.util.ArrayList<String>(supportedPlatforms); } }
public class class_name { public void setSupportedPlatforms(java.util.Collection<String> supportedPlatforms) { if (supportedPlatforms == null) { this.supportedPlatforms = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.supportedPlatforms = new java.util.ArrayList<String>(supportedPlatforms); } }
public class class_name { @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T> void notEmpty(final boolean condition, @Nonnull final T reference, final boolean expression, @Nullable final String name) { if (condition) { Check.notEmpty(reference, expression, name); } } }
public class class_name { @ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class }) public static <T> void notEmpty(final boolean condition, @Nonnull final T reference, final boolean expression, @Nullable final String name) { if (condition) { Check.notEmpty(reference, expression, name); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void start(@NonNull Activity activity, @NonNull String connection, @Nullable Map<String, Object> extraAuthParameters, @NonNull AuthCallback callback, int requestCode) { HashMap<String, Object> parameters; if (extraAuthParameters == null) { parameters = options.getAuthenticationParameters(); } else { parameters = new HashMap<>(options.getAuthenticationParameters()); parameters.putAll(extraAuthParameters); } WebAuthProvider.Builder builder = WebAuthProvider.init(options.getAccount()) .useBrowser(options.useBrowser()) .withParameters(parameters) .withConnection(connection); final String connectionScope = options.getConnectionsScope().get(connection); if (connectionScope != null) { builder.withConnectionScope(connectionScope); } final String scope = options.getScope(); if (scope != null) { builder.withScope(scope); } final String audience = options.getAudience(); if (audience != null && options.getAccount().isOIDCConformant()) { builder.withAudience(audience); } final String scheme = options.getScheme(); if (scheme != null) { builder.withScheme(scheme); } builder.start(activity, callback, requestCode); } }
public class class_name { public void start(@NonNull Activity activity, @NonNull String connection, @Nullable Map<String, Object> extraAuthParameters, @NonNull AuthCallback callback, int requestCode) { HashMap<String, Object> parameters; if (extraAuthParameters == null) { parameters = options.getAuthenticationParameters(); // depends on control dependency: [if], data = [none] } else { parameters = new HashMap<>(options.getAuthenticationParameters()); // depends on control dependency: [if], data = [none] parameters.putAll(extraAuthParameters); // depends on control dependency: [if], data = [(extraAuthParameters] } WebAuthProvider.Builder builder = WebAuthProvider.init(options.getAccount()) .useBrowser(options.useBrowser()) .withParameters(parameters) .withConnection(connection); final String connectionScope = options.getConnectionsScope().get(connection); if (connectionScope != null) { builder.withConnectionScope(connectionScope); // depends on control dependency: [if], data = [(connectionScope] } final String scope = options.getScope(); if (scope != null) { builder.withScope(scope); // depends on control dependency: [if], data = [(scope] } final String audience = options.getAudience(); if (audience != null && options.getAccount().isOIDCConformant()) { builder.withAudience(audience); // depends on control dependency: [if], data = [(audience] } final String scheme = options.getScheme(); if (scheme != null) { builder.withScheme(scheme); // depends on control dependency: [if], data = [(scheme] } builder.start(activity, callback, requestCode); } }
public class class_name { public void close() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "close"); synchronized(this) { if (closed) { idToProxyQueueMap.clear(); factory.groupCloseNotification(conversation, this); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "close"); } }
public class class_name { public void close() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "close"); synchronized(this) { if (closed) { idToProxyQueueMap.clear(); // depends on control dependency: [if], data = [none] factory.groupCloseNotification(conversation, this); // depends on control dependency: [if], data = [none] } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "close"); } }
public class class_name { public static void initUBL22 (@Nonnull final ValidationExecutorSetRegistry aRegistry) { ValueEnforcer.notNull (aRegistry, "Registry"); // For better error messages LocationBeautifierSPI.addMappings (UBL22NamespaceContext.getInstance ()); final boolean bNotDeprecated = false; for (final EUBL22DocumentType e : EUBL22DocumentType.values ()) { final String sName = e.getLocalName (); final VESID aVESID = new VESID (GROUP_ID, sName.toLowerCase (Locale.US), VERSION_22); // No Schematrons here aRegistry.registerValidationExecutorSet (ValidationExecutorSet.create (aVESID, "UBL " + sName + " " + VERSION_22, bNotDeprecated, ValidationExecutorXSD.create (e))); } } }
public class class_name { public static void initUBL22 (@Nonnull final ValidationExecutorSetRegistry aRegistry) { ValueEnforcer.notNull (aRegistry, "Registry"); // For better error messages LocationBeautifierSPI.addMappings (UBL22NamespaceContext.getInstance ()); final boolean bNotDeprecated = false; for (final EUBL22DocumentType e : EUBL22DocumentType.values ()) { final String sName = e.getLocalName (); final VESID aVESID = new VESID (GROUP_ID, sName.toLowerCase (Locale.US), VERSION_22); // No Schematrons here aRegistry.registerValidationExecutorSet (ValidationExecutorSet.create (aVESID, "UBL " + sName + " " + VERSION_22, bNotDeprecated, ValidationExecutorXSD.create (e))); // depends on control dependency: [for], data = [e] } } }
public class class_name { protected synchronized void activate(ComponentContext context) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(this, tc, "Activating"); } bContext = context.getBundleContext(); instance.set(this); sslConfigs.activate(context); cfwBundle.getFramework().registerFactories(this); } }
public class class_name { protected synchronized void activate(ComponentContext context) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(this, tc, "Activating"); // depends on control dependency: [if], data = [none] } bContext = context.getBundleContext(); instance.set(this); sslConfigs.activate(context); cfwBundle.getFramework().registerFactories(this); } }
public class class_name { public void marshall(CompatibleImage compatibleImage, ProtocolMarshaller protocolMarshaller) { if (compatibleImage == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(compatibleImage.getAmiId(), AMIID_BINDING); protocolMarshaller.marshall(compatibleImage.getName(), NAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(CompatibleImage compatibleImage, ProtocolMarshaller protocolMarshaller) { if (compatibleImage == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(compatibleImage.getAmiId(), AMIID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(compatibleImage.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public List<Feature> parseJsonFiles(List<String> jsonFiles) { if (jsonFiles.isEmpty()) { throw new ValidationException("None report file was added!"); } List<Feature> featureResults = new ArrayList<>(); for (int i = 0; i < jsonFiles.size(); i++) { String jsonFile = jsonFiles.get(i); // if file is empty (is not valid JSON report), check if should be skipped or not if (new File(jsonFile).length() == 0 && configuration.containsReducingMethod(ReducingMethod.SKIP_EMPTY_JSON_FILES)) { continue; } Feature[] features = parseForFeature(jsonFile); LOG.log(Level.INFO, String.format("File '%s' contains %d features", jsonFile, features.length)); featureResults.addAll(Arrays.asList(features)); } // report that has no features seems to be not valid if (featureResults.isEmpty()) { throw new ValidationException("Passed files have no features!"); } return featureResults; } }
public class class_name { public List<Feature> parseJsonFiles(List<String> jsonFiles) { if (jsonFiles.isEmpty()) { throw new ValidationException("None report file was added!"); } List<Feature> featureResults = new ArrayList<>(); for (int i = 0; i < jsonFiles.size(); i++) { String jsonFile = jsonFiles.get(i); // if file is empty (is not valid JSON report), check if should be skipped or not if (new File(jsonFile).length() == 0 && configuration.containsReducingMethod(ReducingMethod.SKIP_EMPTY_JSON_FILES)) { continue; } Feature[] features = parseForFeature(jsonFile); LOG.log(Level.INFO, String.format("File '%s' contains %d features", jsonFile, features.length)); // depends on control dependency: [for], data = [none] featureResults.addAll(Arrays.asList(features)); // depends on control dependency: [for], data = [none] } // report that has no features seems to be not valid if (featureResults.isEmpty()) { throw new ValidationException("Passed files have no features!"); } return featureResults; } }
public class class_name { private int[][] createStationBasinsMatrix( double[] statValues, int[] activeStationsPerBasin ) { int[][] stationsBasins = new int[stationCoordinates.size()][basinBaricenterCoordinates.size()]; Set<Integer> bandsIdSet = bin2StationsListMap.keySet(); Integer[] bandsIdArray = (Integer[]) bandsIdSet.toArray(new Integer[bandsIdSet.size()]); // for every basin for( int i = 0; i < basinBaricenterCoordinates.size(); i++ ) { Coordinate basinBaricenterCoordinate = basinBaricenterCoordinates.get(i); // for every stations band int activeStationsForThisBasin = 0; for( int j = 0; j < bandsIdArray.length; j++ ) { int bandId = bandsIdArray[j]; List<Integer> stationIdsForBand = bin2StationsListMap.get(bandId); /* * search for the nearest stations that have values. */ List<Integer> stationsToUse = extractStationsToUse(basinBaricenterCoordinate, stationIdsForBand, stationId2CoordinateMap, statValues, stationid2StationindexMap); if (stationsToUse.size() < pNum) { pm.message("Found only " + stationsToUse.size() + " for basin " + basinindex2basinidMap.get(i) + " and bandid " + bandId + "."); } /* * now we have the list of stations to use. With this list we * need to enable (1) the proper matrix positions inside the * stations-basins matrix. */ // i is the column (basin) index // the station id index can be taken from the idStationIndexMap // System.out.print("STATIONS for basin " + basinindex2basinidMap.get(i) + ": "); for( Integer stationIdToEnable : stationsToUse ) { int stIndex = stationid2StationindexMap.get(stationIdToEnable); stationsBasins[stIndex][i] = 1; // System.out.print(stationIdToEnable + ", "); } // System.out.println(); activeStationsForThisBasin = activeStationsForThisBasin + stationsToUse.size(); } activeStationsPerBasin[i] = activeStationsForThisBasin; } return stationsBasins; } }
public class class_name { private int[][] createStationBasinsMatrix( double[] statValues, int[] activeStationsPerBasin ) { int[][] stationsBasins = new int[stationCoordinates.size()][basinBaricenterCoordinates.size()]; Set<Integer> bandsIdSet = bin2StationsListMap.keySet(); Integer[] bandsIdArray = (Integer[]) bandsIdSet.toArray(new Integer[bandsIdSet.size()]); // for every basin for( int i = 0; i < basinBaricenterCoordinates.size(); i++ ) { Coordinate basinBaricenterCoordinate = basinBaricenterCoordinates.get(i); // for every stations band int activeStationsForThisBasin = 0; for( int j = 0; j < bandsIdArray.length; j++ ) { int bandId = bandsIdArray[j]; List<Integer> stationIdsForBand = bin2StationsListMap.get(bandId); /* * search for the nearest stations that have values. */ List<Integer> stationsToUse = extractStationsToUse(basinBaricenterCoordinate, stationIdsForBand, stationId2CoordinateMap, statValues, stationid2StationindexMap); if (stationsToUse.size() < pNum) { pm.message("Found only " + stationsToUse.size() + " for basin " + basinindex2basinidMap.get(i) + " and bandid " + bandId + "."); // depends on control dependency: [if], data = [none] } /* * now we have the list of stations to use. With this list we * need to enable (1) the proper matrix positions inside the * stations-basins matrix. */ // i is the column (basin) index // the station id index can be taken from the idStationIndexMap // System.out.print("STATIONS for basin " + basinindex2basinidMap.get(i) + ": "); for( Integer stationIdToEnable : stationsToUse ) { int stIndex = stationid2StationindexMap.get(stationIdToEnable); stationsBasins[stIndex][i] = 1; // depends on control dependency: [for], data = [none] // System.out.print(stationIdToEnable + ", "); } // System.out.println(); activeStationsForThisBasin = activeStationsForThisBasin + stationsToUse.size(); // depends on control dependency: [for], data = [none] } activeStationsPerBasin[i] = activeStationsForThisBasin; // depends on control dependency: [for], data = [i] } return stationsBasins; } }
public class class_name { public void eventUnreferenced(ActivityHandle handle, FireableEventType eventType, Object event, Address arg3, ReceivableService arg4, int arg5) { if(tracer.isFineEnabled()) { tracer.fine("Event Unreferenced. Handle = "+handle+", type = "+eventType.getEventType()+", event = "+event); } if(event instanceof ResponseEventWrapper) { final ResponseEventWrapper rew = (ResponseEventWrapper) event; processResponseEventUnreferenced(rew); } else if(event instanceof RequestEventWrapper) { final RequestEventWrapper rew = (RequestEventWrapper) event; final ServerTransactionWrapper stw = (ServerTransactionWrapper) rew.getServerTransaction(); if (stw.isAckTransaction()) { processTransactionTerminated(stw); } else { final Request r = rew.getRequest(); if (r.getMethod().equals(Request.CANCEL)) { // lets be a good citizen and reply if no sbb has done if (stw.getState() != TransactionState.TERMINATED) { processCancelNotHandled(stw,r); } } } } } }
public class class_name { public void eventUnreferenced(ActivityHandle handle, FireableEventType eventType, Object event, Address arg3, ReceivableService arg4, int arg5) { if(tracer.isFineEnabled()) { tracer.fine("Event Unreferenced. Handle = "+handle+", type = "+eventType.getEventType()+", event = "+event); // depends on control dependency: [if], data = [none] } if(event instanceof ResponseEventWrapper) { final ResponseEventWrapper rew = (ResponseEventWrapper) event; processResponseEventUnreferenced(rew); // depends on control dependency: [if], data = [none] } else if(event instanceof RequestEventWrapper) { final RequestEventWrapper rew = (RequestEventWrapper) event; final ServerTransactionWrapper stw = (ServerTransactionWrapper) rew.getServerTransaction(); if (stw.isAckTransaction()) { processTransactionTerminated(stw); // depends on control dependency: [if], data = [none] } else { final Request r = rew.getRequest(); if (r.getMethod().equals(Request.CANCEL)) { // lets be a good citizen and reply if no sbb has done if (stw.getState() != TransactionState.TERMINATED) { processCancelNotHandled(stw,r); // depends on control dependency: [if], data = [none] } } } } } }
public class class_name { protected boolean isMatch(IPListConfig config, String remoteAddr) { if (config.getIpList().contains(remoteAddr)) { return true; } try { String [] remoteAddrSplit = remoteAddr.split("\\."); //$NON-NLS-1$ for (String ip : config.getIpList()) { String [] ipSplit = ip.split("\\."); //$NON-NLS-1$ if (remoteAddrSplit.length == ipSplit.length) { int numParts = ipSplit.length; boolean matches = true; for (int idx = 0; idx < numParts; idx++) { if (ipSplit[idx].equals("*") || ipSplit[idx].equals(remoteAddrSplit[idx])) { //$NON-NLS-1$ // This component matches! } else { matches = false; break; } } if (matches) { return true; } } } } catch (Throwable t) { // eat it } return false; } }
public class class_name { protected boolean isMatch(IPListConfig config, String remoteAddr) { if (config.getIpList().contains(remoteAddr)) { return true; // depends on control dependency: [if], data = [none] } try { String [] remoteAddrSplit = remoteAddr.split("\\."); //$NON-NLS-1$ for (String ip : config.getIpList()) { String [] ipSplit = ip.split("\\."); //$NON-NLS-1$ if (remoteAddrSplit.length == ipSplit.length) { int numParts = ipSplit.length; boolean matches = true; for (int idx = 0; idx < numParts; idx++) { if (ipSplit[idx].equals("*") || ipSplit[idx].equals(remoteAddrSplit[idx])) { //$NON-NLS-1$ // This component matches! } else { matches = false; // depends on control dependency: [if], data = [none] break; } } if (matches) { return true; // depends on control dependency: [if], data = [none] } } } } catch (Throwable t) { // eat it } // depends on control dependency: [catch], data = [none] return false; } }
public class class_name { public synchronized void close() throws IOException { // // Kill running tasks. Do this in a 2nd vector, called 'tasksToClose', // because calling jobHasFinished() may result in an edit to 'tasks'. // TreeMap<TaskAttemptID, TaskInProgress> tasksToClose = new TreeMap<TaskAttemptID, TaskInProgress>(); tasksToClose.putAll(tasks); for (TaskInProgress tip : tasksToClose.values()) { tip.jobHasFinished(false); } this.running = false; if (pulseChecker != null) { pulseChecker.shutdown(); } if (versionBeanName != null) { MBeanUtil.unregisterMBean(versionBeanName); } // Clear local storage if (asyncDiskService != null) { // Clear local storage asyncDiskService.cleanupAllVolumes(); // Shutdown all async deletion threads with up to 10 seconds of delay asyncDiskService.shutdown(); try { if (!asyncDiskService.awaitTermination(10000)) { asyncDiskService.shutdownNow(); asyncDiskService = null; } } catch (InterruptedException e) { asyncDiskService.shutdownNow(); asyncDiskService = null; } } // Shutdown the fetcher thread if (this.mapEventsFetcher != null) { this.mapEventsFetcher.interrupt(); } // Stop the launchers this.mapLauncher.interrupt(); this.reduceLauncher.interrupt(); if (this.heartbeatMonitor != null) { this.heartbeatMonitor.interrupt(); } // Stop memory manager thread if (this.taskMemoryManager != null) { this.taskMemoryManager.shutdown(); } // Stop cgroup memory watcher this.cgroupMemoryWatcher.shutdown(); // All tasks are killed. So, they are removed from TaskLog monitoring also. // Interrupt the monitor. getTaskLogsMonitor().interrupt(); jvmManager.stop(); // shutdown RPC connections RPC.stopProxy(jobClient); // wait for the fetcher thread to exit for (boolean done = false; !done; ) { try { if (this.mapEventsFetcher != null) { this.mapEventsFetcher.join(); } done = true; } catch (InterruptedException e) { } } if (taskReportServer != null) { taskReportServer.stop(); taskReportServer = null; } if (healthChecker != null) { //stop node health checker service healthChecker.stop(); healthChecker = null; } if (this.server != null) { try { LOG.info("Shutting down StatusHttpServer"); this.server.stop(); LOG.info("Shutting down Netty MapOutput Server"); if (this.nettyMapOutputServer != null) { this.nettyMapOutputServer.stop(); } } catch (Exception e) { LOG.warn("Exception shutting down TaskTracker", e); } } } }
public class class_name { public synchronized void close() throws IOException { // // Kill running tasks. Do this in a 2nd vector, called 'tasksToClose', // because calling jobHasFinished() may result in an edit to 'tasks'. // TreeMap<TaskAttemptID, TaskInProgress> tasksToClose = new TreeMap<TaskAttemptID, TaskInProgress>(); tasksToClose.putAll(tasks); for (TaskInProgress tip : tasksToClose.values()) { tip.jobHasFinished(false); } this.running = false; if (pulseChecker != null) { pulseChecker.shutdown(); } if (versionBeanName != null) { MBeanUtil.unregisterMBean(versionBeanName); } // Clear local storage if (asyncDiskService != null) { // Clear local storage asyncDiskService.cleanupAllVolumes(); // Shutdown all async deletion threads with up to 10 seconds of delay asyncDiskService.shutdown(); try { if (!asyncDiskService.awaitTermination(10000)) { asyncDiskService.shutdownNow(); // depends on control dependency: [if], data = [none] asyncDiskService = null; // depends on control dependency: [if], data = [none] } } catch (InterruptedException e) { asyncDiskService.shutdownNow(); asyncDiskService = null; } } // Shutdown the fetcher thread if (this.mapEventsFetcher != null) { this.mapEventsFetcher.interrupt(); } // Stop the launchers this.mapLauncher.interrupt(); this.reduceLauncher.interrupt(); if (this.heartbeatMonitor != null) { this.heartbeatMonitor.interrupt(); } // Stop memory manager thread if (this.taskMemoryManager != null) { this.taskMemoryManager.shutdown(); } // Stop cgroup memory watcher this.cgroupMemoryWatcher.shutdown(); // All tasks are killed. So, they are removed from TaskLog monitoring also. // Interrupt the monitor. getTaskLogsMonitor().interrupt(); jvmManager.stop(); // shutdown RPC connections RPC.stopProxy(jobClient); // wait for the fetcher thread to exit for (boolean done = false; !done; ) { try { if (this.mapEventsFetcher != null) { this.mapEventsFetcher.join(); } done = true; } catch (InterruptedException e) { } } if (taskReportServer != null) { taskReportServer.stop(); taskReportServer = null; } if (healthChecker != null) { //stop node health checker service healthChecker.stop(); healthChecker = null; } if (this.server != null) { try { LOG.info("Shutting down StatusHttpServer"); this.server.stop(); LOG.info("Shutting down Netty MapOutput Server"); if (this.nettyMapOutputServer != null) { this.nettyMapOutputServer.stop(); } } catch (Exception e) { LOG.warn("Exception shutting down TaskTracker", e); } } } }
public class class_name { public static void probeObject(Object o) { Class c = o.getClass(); Class interfaces[] = c.getInterfaces(); Class parent = c.getSuperclass(); Method m[] = c.getMethods(); System.out.println("********* OBJECT PROBE *********"); System.out.println("Class Name: " + c.getName()); System.out.println("Super Class: " + parent.getName()); System.out.println("Interfaces: "); for (int i = 0; i < interfaces.length; i++) { System.out.println(" " + interfaces[i].getName()); } System.out.println("Methods:"); for (int i = 0; i < m.length; i++) { Class params[] = m[i].getParameterTypes(); Class excepts[] = m[i].getExceptionTypes(); Class ret = m[i].getReturnType(); System.out.print(" " + ret.getName() + " " + m[i].getName() + "("); for (int j = 0; j < params.length; j++) { if (j > 0) System.out.print(", "); System.out.print(params[j].getName()); } System.out.print(") throws "); for (int j = 0; j < excepts.length; j++) { if (j > 0) System.out.print(", "); System.out.print(excepts[j].getName()); } System.out.println(""); } System.out.println("******************"); } }
public class class_name { public static void probeObject(Object o) { Class c = o.getClass(); Class interfaces[] = c.getInterfaces(); Class parent = c.getSuperclass(); Method m[] = c.getMethods(); System.out.println("********* OBJECT PROBE *********"); System.out.println("Class Name: " + c.getName()); System.out.println("Super Class: " + parent.getName()); System.out.println("Interfaces: "); for (int i = 0; i < interfaces.length; i++) { System.out.println(" " + interfaces[i].getName()); } System.out.println("Methods:"); for (int i = 0; i < m.length; i++) { Class params[] = m[i].getParameterTypes(); Class excepts[] = m[i].getExceptionTypes(); Class ret = m[i].getReturnType(); System.out.print(" " + ret.getName() + " " + m[i].getName() + "("); for (int j = 0; j < params.length; j++) { if (j > 0) System.out.print(", "); System.out.print(params[j].getName()); // depends on control dependency: [for], data = [j] } System.out.print(") throws "); // depends on control dependency: [for], data = [none] for (int j = 0; j < excepts.length; j++) { if (j > 0) System.out.print(", "); System.out.print(excepts[j].getName()); // depends on control dependency: [for], data = [j] } System.out.println(""); // depends on control dependency: [for], data = [none] } System.out.println("******************"); } }
public class class_name { public static <T, E extends Exception> IntList mapToInt(final Collection<? extends T> c, final int fromIndex, final int toIndex, final Try.ToIntFunction<? super T, E> func) throws E { checkFromToIndex(fromIndex, toIndex, size(c)); N.checkArgNotNull(func); if (N.isNullOrEmpty(c) && fromIndex == 0 && toIndex == 0) { return new IntList(); } final IntList result = new IntList(toIndex - fromIndex); if (c instanceof List && c instanceof RandomAccess) { final List<T> list = (List<T>) c; for (int i = fromIndex; i < toIndex; i++) { result.add(func.applyAsInt(list.get(i))); } } else { int idx = 0; for (T e : c) { if (idx++ < fromIndex) { continue; } result.add(func.applyAsInt(e)); if (idx >= toIndex) { break; } } } return result; } }
public class class_name { public static <T, E extends Exception> IntList mapToInt(final Collection<? extends T> c, final int fromIndex, final int toIndex, final Try.ToIntFunction<? super T, E> func) throws E { checkFromToIndex(fromIndex, toIndex, size(c)); N.checkArgNotNull(func); if (N.isNullOrEmpty(c) && fromIndex == 0 && toIndex == 0) { return new IntList(); } final IntList result = new IntList(toIndex - fromIndex); if (c instanceof List && c instanceof RandomAccess) { final List<T> list = (List<T>) c; for (int i = fromIndex; i < toIndex; i++) { result.add(func.applyAsInt(list.get(i))); // depends on control dependency: [for], data = [i] } } else { int idx = 0; for (T e : c) { if (idx++ < fromIndex) { continue; } result.add(func.applyAsInt(e)); // depends on control dependency: [for], data = [e] if (idx >= toIndex) { break; } } } return result; } }
public class class_name { public void validateUpdateFile(Long configId, String fileName) { // // config // Config config = valideConfigExist(configId); // // value // try { if (!config.getName().equals(fileName)) { throw new Exception(); } } catch (Exception e) { throw new FieldException("value", "conf.file.name.not.equal", e); } } }
public class class_name { public void validateUpdateFile(Long configId, String fileName) { // // config // Config config = valideConfigExist(configId); // // value // try { if (!config.getName().equals(fileName)) { throw new Exception(); } } catch (Exception e) { throw new FieldException("value", "conf.file.name.not.equal", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public final Mono<T> reduce(BiFunction<T, T, T> aggregator) { if (this instanceof Callable){ @SuppressWarnings("unchecked") Callable<T> thiz = (Callable<T>)this; return convertToMono(thiz); } return Mono.onAssembly(new MonoReduce<>(this, aggregator)); } }
public class class_name { public final Mono<T> reduce(BiFunction<T, T, T> aggregator) { if (this instanceof Callable){ @SuppressWarnings("unchecked") Callable<T> thiz = (Callable<T>)this; return convertToMono(thiz); // depends on control dependency: [if], data = [none] } return Mono.onAssembly(new MonoReduce<>(this, aggregator)); } }
public class class_name { public boolean handlePopBox(String deviceBrand) { pushHandleGps2Device(); CommandLine exeCommand = null; if (deviceBrand.contains("HTC")) { exeCommand = adbCommand("shell", "uiautomator", "runtest", "/data/local/tmp/handlePopBox.jar", "-c", "com.test.device.gps.HTCGPSTest"); } else if (deviceBrand.contains("Meizu")) { exeCommand = adbCommand("shell", "uiautomator", "runtest", "/data/local/tmp/handlePopBox.jar", "-c", "com.test.device.gps.MeizuGPSTest"); } String output = executeCommandQuietly(exeCommand); log.debug("run test {}", output); try { // give it a second to recover from the activity start Thread.sleep(1000); } catch (InterruptedException ie) { throw new RuntimeException(ie); } return output.contains("OK"); } }
public class class_name { public boolean handlePopBox(String deviceBrand) { pushHandleGps2Device(); CommandLine exeCommand = null; if (deviceBrand.contains("HTC")) { exeCommand = adbCommand("shell", "uiautomator", "runtest", "/data/local/tmp/handlePopBox.jar", "-c", "com.test.device.gps.HTCGPSTest"); } else if (deviceBrand.contains("Meizu")) { exeCommand = adbCommand("shell", "uiautomator", "runtest", "/data/local/tmp/handlePopBox.jar", "-c", "com.test.device.gps.MeizuGPSTest"); // depends on control dependency: [if], data = [none] } String output = executeCommandQuietly(exeCommand); log.debug("run test {}", output); try { // give it a second to recover from the activity start Thread.sleep(1000); // depends on control dependency: [try], data = [none] } catch (InterruptedException ie) { throw new RuntimeException(ie); } // depends on control dependency: [catch], data = [none] return output.contains("OK"); } }
public class class_name { public void marshall(DvbNitSettings dvbNitSettings, ProtocolMarshaller protocolMarshaller) { if (dvbNitSettings == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(dvbNitSettings.getNetworkId(), NETWORKID_BINDING); protocolMarshaller.marshall(dvbNitSettings.getNetworkName(), NETWORKNAME_BINDING); protocolMarshaller.marshall(dvbNitSettings.getNitInterval(), NITINTERVAL_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DvbNitSettings dvbNitSettings, ProtocolMarshaller protocolMarshaller) { if (dvbNitSettings == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(dvbNitSettings.getNetworkId(), NETWORKID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(dvbNitSettings.getNetworkName(), NETWORKNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(dvbNitSettings.getNitInterval(), NITINTERVAL_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 { private static String readResource(String name) { try { return IOUtils.toString(AmazonKinesisFirehoseToRedshiftSample.class.getResourceAsStream(name)); } catch (IOException e) { throw new RuntimeException("Failed to read document resource: " + name, e); } } }
public class class_name { private static String readResource(String name) { try { return IOUtils.toString(AmazonKinesisFirehoseToRedshiftSample.class.getResourceAsStream(name)); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new RuntimeException("Failed to read document resource: " + name, e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public long handleNodeTags(ReaderNode node) { long flags = 0; for (AbstractFlagEncoder encoder : edgeEncoders) { flags |= encoder.handleNodeTags(node); } return flags; } }
public class class_name { public long handleNodeTags(ReaderNode node) { long flags = 0; for (AbstractFlagEncoder encoder : edgeEncoders) { flags |= encoder.handleNodeTags(node); // depends on control dependency: [for], data = [encoder] } return flags; } }
public class class_name { public final String toShortString() { StringBuffer buffer = new StringBuffer(); buffer.append(defaultAlignment.abbreviation()); buffer.append(":"); buffer.append(size.toString()); buffer.append(':'); if (resizeWeight == NO_GROW) { buffer.append("n"); } else if (resizeWeight == DEFAULT_GROW) { buffer.append("g"); } else { buffer.append("g("); buffer.append(resizeWeight); buffer.append(')'); } return buffer.toString(); } }
public class class_name { public final String toShortString() { StringBuffer buffer = new StringBuffer(); buffer.append(defaultAlignment.abbreviation()); buffer.append(":"); buffer.append(size.toString()); buffer.append(':'); if (resizeWeight == NO_GROW) { buffer.append("n"); // depends on control dependency: [if], data = [none] } else if (resizeWeight == DEFAULT_GROW) { buffer.append("g"); // depends on control dependency: [if], data = [none] } else { buffer.append("g("); buffer.append(resizeWeight); buffer.append(')'); // depends on control dependency: [if], data = [none] } return buffer.toString(); } }
public class class_name { @Deprecated public Collection<MaterialRevision> computeRevisionsForReporting(CaseInsensitiveString pipelineName, PipelineTimeline pipelineTimeline) { Pair<List<RootFanInNode>, List<DependencyFanInNode>> scmAndDepMaterialsChildren = getScmAndDepMaterialsChildren(); List<RootFanInNode> scmChildren = scmAndDepMaterialsChildren.first(); List<DependencyFanInNode> depChildren = scmAndDepMaterialsChildren.last(); if (depChildren.isEmpty()) { //No fanin required all are SCMs return null; } FanInGraphContext context = buildContext(pipelineTimeline); root.initialize(context); initChildren(depChildren, pipelineName, context); iterateAndMakeAllUniqueScmRevisionsForChildrenSame(depChildren, pipelineName, context); List<MaterialRevision> finalRevisionsForScmChildren = createFinalRevisionsForScmChildren(root.latestPipelineTimelineEntry(context), scmChildren, depChildren); List<MaterialRevision> finalRevisionsForDepChildren = createFinalRevisionsForDepChildren(depChildren); return CollectionUtils.union(finalRevisionsForScmChildren, finalRevisionsForDepChildren); } }
public class class_name { @Deprecated public Collection<MaterialRevision> computeRevisionsForReporting(CaseInsensitiveString pipelineName, PipelineTimeline pipelineTimeline) { Pair<List<RootFanInNode>, List<DependencyFanInNode>> scmAndDepMaterialsChildren = getScmAndDepMaterialsChildren(); List<RootFanInNode> scmChildren = scmAndDepMaterialsChildren.first(); List<DependencyFanInNode> depChildren = scmAndDepMaterialsChildren.last(); if (depChildren.isEmpty()) { //No fanin required all are SCMs return null; // depends on control dependency: [if], data = [none] } FanInGraphContext context = buildContext(pipelineTimeline); root.initialize(context); initChildren(depChildren, pipelineName, context); iterateAndMakeAllUniqueScmRevisionsForChildrenSame(depChildren, pipelineName, context); List<MaterialRevision> finalRevisionsForScmChildren = createFinalRevisionsForScmChildren(root.latestPipelineTimelineEntry(context), scmChildren, depChildren); List<MaterialRevision> finalRevisionsForDepChildren = createFinalRevisionsForDepChildren(depChildren); return CollectionUtils.union(finalRevisionsForScmChildren, finalRevisionsForDepChildren); } }