code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { private void ensureCapacity (int n) { if (n <= 0) { return; } int max; if (data == null || data.length == 0) { max = 25; } else if (data.length >= n * 5) { return; } else { max = data.length; } while (max < n * 5) { max *= 2; } String newData[] = new String[max]; if (length > 0) { System.arraycopy(data, 0, newData, 0, length*5); } data = newData; } }
public class class_name { private void ensureCapacity (int n) { if (n <= 0) { return; // depends on control dependency: [if], data = [none] } int max; if (data == null || data.length == 0) { max = 25; // depends on control dependency: [if], data = [none] } else if (data.length >= n * 5) { return; // depends on control dependency: [if], data = [none] } else { max = data.length; // depends on control dependency: [if], data = [none] } while (max < n * 5) { max *= 2; // depends on control dependency: [while], data = [none] } String newData[] = new String[max]; if (length > 0) { System.arraycopy(data, 0, newData, 0, length*5); // depends on control dependency: [if], data = [none] } data = newData; } }
public class class_name { public BitcoinAuxPOW parseAuxPow(ByteBuffer rawByteBuffer) { if (!this.readAuxPow) { return null; } // in case it does not contain auxpow we need to reset rawByteBuffer.mark(); int currentVersion=rawByteBuffer.getInt(); byte[] currentInCounterVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); byte[] currentTransactionInputPrevTransactionHash=new byte[32]; rawByteBuffer.get(currentTransactionInputPrevTransactionHash,0,32); byte[] prevTxOutIdx = new byte[4]; rawByteBuffer.get(prevTxOutIdx,0,4); // detect auxPow rawByteBuffer.reset(); byte[] expectedPrevTransactionHash=new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; byte[] expectedPrevOutIdx = new byte[] {(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF}; if ((!(Arrays.equals(prevTxOutIdx,expectedPrevOutIdx))||(!(Arrays.equals(currentTransactionInputPrevTransactionHash,expectedPrevTransactionHash))))) { return null; } // continue reading auxPow // txIn (for all of them) currentVersion=rawByteBuffer.getInt(); currentInCounterVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentNoOfInputs=BitcoinUtil.getVarInt(currentInCounterVarInt); List<BitcoinTransactionInput> currentTransactionInput = parseTransactionInputs(rawByteBuffer, currentNoOfInputs); // txOut (for all of them) byte[] currentOutCounterVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentNoOfOutput=BitcoinUtil.getVarInt(currentOutCounterVarInt); List<BitcoinTransactionOutput> currentTransactionOutput = parseTransactionOutputs(rawByteBuffer,currentNoOfOutput); int lockTime = rawByteBuffer.getInt(); BitcoinTransaction coinbaseTransaction= new BitcoinTransaction(currentVersion,currentInCounterVarInt,currentTransactionInput, currentOutCounterVarInt, currentTransactionOutput,lockTime); // read branches // coinbase branch byte[] coinbaseParentBlockHeaderHash=new byte[32]; rawByteBuffer.get(coinbaseParentBlockHeaderHash,0,32); BitcoinAuxPOWBranch coinbaseBranch = parseAuxPOWBranch(rawByteBuffer); // auxchain branch BitcoinAuxPOWBranch auxChainBranch = parseAuxPOWBranch(rawByteBuffer); // parent Block header byte[] parentBlockBits=new byte[4]; byte[] parentBlockHashMerkleRoot=new byte[32]; byte[] parentBlockHashPrevBlock=new byte[32]; // version int parentBlockVersion=rawByteBuffer.getInt(); // hashPrevBlock rawByteBuffer.get(parentBlockHashPrevBlock,0,32); // hashMerkleRoot rawByteBuffer.get(parentBlockHashMerkleRoot,0,32); // time int parentBlockTime=rawByteBuffer.getInt(); // bits/difficulty rawByteBuffer.get(parentBlockBits,0,4); // nonce int parentBlockNonce=rawByteBuffer.getInt(); BitcoinAuxPOWBlockHeader parentBlockheader = new BitcoinAuxPOWBlockHeader(parentBlockVersion, parentBlockHashPrevBlock, parentBlockHashMerkleRoot, parentBlockTime, parentBlockBits, parentBlockNonce); return new BitcoinAuxPOW(currentVersion, coinbaseTransaction, coinbaseParentBlockHeaderHash, coinbaseBranch, auxChainBranch, parentBlockheader); } }
public class class_name { public BitcoinAuxPOW parseAuxPow(ByteBuffer rawByteBuffer) { if (!this.readAuxPow) { return null; // depends on control dependency: [if], data = [none] } // in case it does not contain auxpow we need to reset rawByteBuffer.mark(); int currentVersion=rawByteBuffer.getInt(); byte[] currentInCounterVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); byte[] currentTransactionInputPrevTransactionHash=new byte[32]; rawByteBuffer.get(currentTransactionInputPrevTransactionHash,0,32); byte[] prevTxOutIdx = new byte[4]; rawByteBuffer.get(prevTxOutIdx,0,4); // detect auxPow rawByteBuffer.reset(); byte[] expectedPrevTransactionHash=new byte[]{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; byte[] expectedPrevOutIdx = new byte[] {(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF}; if ((!(Arrays.equals(prevTxOutIdx,expectedPrevOutIdx))||(!(Arrays.equals(currentTransactionInputPrevTransactionHash,expectedPrevTransactionHash))))) { return null; // depends on control dependency: [if], data = [none] } // continue reading auxPow // txIn (for all of them) currentVersion=rawByteBuffer.getInt(); currentInCounterVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentNoOfInputs=BitcoinUtil.getVarInt(currentInCounterVarInt); List<BitcoinTransactionInput> currentTransactionInput = parseTransactionInputs(rawByteBuffer, currentNoOfInputs); // txOut (for all of them) byte[] currentOutCounterVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentNoOfOutput=BitcoinUtil.getVarInt(currentOutCounterVarInt); List<BitcoinTransactionOutput> currentTransactionOutput = parseTransactionOutputs(rawByteBuffer,currentNoOfOutput); int lockTime = rawByteBuffer.getInt(); BitcoinTransaction coinbaseTransaction= new BitcoinTransaction(currentVersion,currentInCounterVarInt,currentTransactionInput, currentOutCounterVarInt, currentTransactionOutput,lockTime); // read branches // coinbase branch byte[] coinbaseParentBlockHeaderHash=new byte[32]; rawByteBuffer.get(coinbaseParentBlockHeaderHash,0,32); BitcoinAuxPOWBranch coinbaseBranch = parseAuxPOWBranch(rawByteBuffer); // auxchain branch BitcoinAuxPOWBranch auxChainBranch = parseAuxPOWBranch(rawByteBuffer); // parent Block header byte[] parentBlockBits=new byte[4]; byte[] parentBlockHashMerkleRoot=new byte[32]; byte[] parentBlockHashPrevBlock=new byte[32]; // version int parentBlockVersion=rawByteBuffer.getInt(); // hashPrevBlock rawByteBuffer.get(parentBlockHashPrevBlock,0,32); // hashMerkleRoot rawByteBuffer.get(parentBlockHashMerkleRoot,0,32); // time int parentBlockTime=rawByteBuffer.getInt(); // bits/difficulty rawByteBuffer.get(parentBlockBits,0,4); // nonce int parentBlockNonce=rawByteBuffer.getInt(); BitcoinAuxPOWBlockHeader parentBlockheader = new BitcoinAuxPOWBlockHeader(parentBlockVersion, parentBlockHashPrevBlock, parentBlockHashMerkleRoot, parentBlockTime, parentBlockBits, parentBlockNonce); return new BitcoinAuxPOW(currentVersion, coinbaseTransaction, coinbaseParentBlockHeaderHash, coinbaseBranch, auxChainBranch, parentBlockheader); } }
public class class_name { private static Type getAsynchronizedGenericType(Object targetObject) { if (targetObject instanceof java.util.Collection) { Class<? extends java.util.Collection> rawType = (Class<? extends Collection>) targetObject.getClass(); Class<?> actualType = Object.class; if (((java.util.Collection<?>) targetObject).size() > 0) { Object element = ((java.util.Collection<?>) targetObject).iterator().next(); actualType = element.getClass(); } return new ParameterizedType() { private Type actualType, rawType; public ParameterizedType setTypes(Type actualType, Type rawType) { this.actualType = actualType; this.rawType = rawType; return this; } @Override public Type[] getActualTypeArguments() { return new Type[] { actualType }; } @Override public Type getRawType() { return rawType; } @Override public Type getOwnerType() { return null; } }.setTypes(actualType, rawType); } else return targetObject.getClass(); } }
public class class_name { private static Type getAsynchronizedGenericType(Object targetObject) { if (targetObject instanceof java.util.Collection) { Class<? extends java.util.Collection> rawType = (Class<? extends Collection>) targetObject.getClass(); Class<?> actualType = Object.class; if (((java.util.Collection<?>) targetObject).size() > 0) { Object element = ((java.util.Collection<?>) targetObject).iterator().next(); actualType = element.getClass(); // depends on control dependency: [if], data = [none] } return new ParameterizedType() { private Type actualType, rawType; public ParameterizedType setTypes(Type actualType, Type rawType) { this.actualType = actualType; this.rawType = rawType; return this; } @Override public Type[] getActualTypeArguments() { return new Type[] { actualType }; } @Override public Type getRawType() { return rawType; } @Override public Type getOwnerType() { return null; } }.setTypes(actualType, rawType); // depends on control dependency: [if], data = [none] } else return targetObject.getClass(); } }
public class class_name { private Response serveOneOrAll(Map<String, Model> modelsMap) { // returns empty sets if !this.find_compatible_frames Pair<Map<String, Frame>, Map<String, Set<String>>> frames_info = fetchFrames(); Map<String, Frame> all_frames = frames_info.getFirst(); Map<String, Set<String>> all_frames_cols = frames_info.getSecond(); Map<String, ModelSummary> modelSummaries = Models.generateModelSummaries(null, modelsMap, find_compatible_frames, all_frames, all_frames_cols); Map resultsMap = new LinkedHashMap(); resultsMap.put("models", modelSummaries); // If find_compatible_frames then include a map of the Frame summaries. Should we put this on a separate switch? if (this.find_compatible_frames) { Set<String> all_referenced_frames = new TreeSet<String>(); for (Map.Entry<String, ModelSummary> entry: modelSummaries.entrySet()) { ModelSummary summary = entry.getValue(); all_referenced_frames.addAll(summary.compatible_frames); } Map<String, FrameSummary> frameSummaries = Frames.generateFrameSummaries(all_referenced_frames, all_frames, false, null, null); resultsMap.put("frames", frameSummaries); } // TODO: temporary hack to get things going String json = gson.toJson(resultsMap); JsonObject result = gson.fromJson(json, JsonElement.class).getAsJsonObject(); return Response.done(result); } }
public class class_name { private Response serveOneOrAll(Map<String, Model> modelsMap) { // returns empty sets if !this.find_compatible_frames Pair<Map<String, Frame>, Map<String, Set<String>>> frames_info = fetchFrames(); Map<String, Frame> all_frames = frames_info.getFirst(); Map<String, Set<String>> all_frames_cols = frames_info.getSecond(); Map<String, ModelSummary> modelSummaries = Models.generateModelSummaries(null, modelsMap, find_compatible_frames, all_frames, all_frames_cols); Map resultsMap = new LinkedHashMap(); resultsMap.put("models", modelSummaries); // If find_compatible_frames then include a map of the Frame summaries. Should we put this on a separate switch? if (this.find_compatible_frames) { Set<String> all_referenced_frames = new TreeSet<String>(); for (Map.Entry<String, ModelSummary> entry: modelSummaries.entrySet()) { ModelSummary summary = entry.getValue(); all_referenced_frames.addAll(summary.compatible_frames); // depends on control dependency: [for], data = [none] } Map<String, FrameSummary> frameSummaries = Frames.generateFrameSummaries(all_referenced_frames, all_frames, false, null, null); resultsMap.put("frames", frameSummaries); // depends on control dependency: [if], data = [none] } // TODO: temporary hack to get things going String json = gson.toJson(resultsMap); JsonObject result = gson.fromJson(json, JsonElement.class).getAsJsonObject(); return Response.done(result); } }
public class class_name { public static List<RepositoryConfigValidationResult> validateRepositoryPropertiesFile(Properties repoProperties) throws InstallException { List<RepositoryConfigValidationResult> validationResults = new ArrayList<RepositoryConfigValidationResult>(); // Retrieves the Repository Properties file File repoPropertiesFile = new File(getRepoPropertiesFileLocation()); Map<String, String> configMap = new HashMap<String, String>(); Map<String, Integer> lineMap = new HashMap<String, Integer>(); if (repoPropertiesFile.exists() && repoPropertiesFile.isFile()) { logger.log(Level.FINE, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("LOG_VALIDATING", getRepoPropertiesFileLocation())); //Load repository properties FileInputStream repoPropertiesInput = null; BufferedReader repoPropertiesReader = null; try { repoPropertiesInput = new FileInputStream(repoPropertiesFile); repoPropertiesReader = new BufferedReader(new InputStreamReader(repoPropertiesInput)); String line; int lineNum = 0; //Validate configurations in the repositories.properties file while ((line = repoPropertiesReader.readLine()) != null) { lineNum++; validateRepositoryPropertiesLine(repoProperties, line, lineNum, configMap, lineMap, validationResults); } //Missing Host if (configMap.containsKey(PROXY_HOST)) { int ln = lineMap.get(PROXY_HOST); if (!configMap.containsKey(PROXY_PORT)) { validationResults.add(new RepositoryConfigValidationResult(ln, ValidationFailedReason.MISSING_PORT, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("MSG_VALIDATION_MISSING_PORT_VALUE", configMap.get(PROXY_HOST)))); } else { /** * verify proxy host url along with the port number */ String proxyHost = repoProperties.getProperty(InstallConstants.REPO_PROPERTIES_PROXY_HOST); String proxyPort = repoProperties.getProperty(InstallConstants.REPO_PROPERTIES_PROXY_PORT); try { //Trim any trailing whitespaces proxyHost = proxyHost.trim(); proxyPort = proxyPort.trim(); URL proxyUrl = null; if (proxyHost.toLowerCase().contains("://")) { proxyUrl = new URL(proxyHost + ":" + proxyPort); if (!proxyUrl.getProtocol().toLowerCase().equals("http")) validationResults.add(new RepositoryConfigValidationResult(ln, ValidationFailedReason.INVALID_HOST, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("MSG_VALIDATION_INVALID_HOST", configMap.get(PROXY_HOST)))); } else { new URL("http://" + proxyHost + ":" + proxyPort); } } catch (MalformedURLException e) { validationResults.add(new RepositoryConfigValidationResult(ln, ValidationFailedReason.INVALID_HOST, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("MSG_VALIDATION_INVALID_HOST", configMap.get(PROXY_HOST)))); } } } else { if (configMap.containsKey(PROXY_PORT) || configMap.containsKey(PROXY_USER) || configMap.containsKey(PROXY_PASSWORD)) { int ln = 0; if (lineMap.containsKey(PROXY_PORT)) ln = lineMap.get(PROXY_PORT); else if (lineMap.containsKey(PROXY_USER)) ln = lineMap.get(PROXY_USER); else ln = lineMap.get(PROXY_PASSWORD); validationResults.add(new RepositoryConfigValidationResult(ln, ValidationFailedReason.MISSING_HOST, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("MSG_VALIDATION_MISSING_HOST"))); } } } catch (IOException e) { throw new InstallException(Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("ERROR_TOOL_REPOSITORY_PROPS_NOT_LOADED", getRepoPropertiesFileLocation()), InstallException.IO_FAILURE); } finally { InstallUtils.close(repoPropertiesInput); InstallUtils.close(repoPropertiesReader); } logger.log(Level.FINE, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("LOG_VALIDATION_DONE")); } return validationResults; } }
public class class_name { public static List<RepositoryConfigValidationResult> validateRepositoryPropertiesFile(Properties repoProperties) throws InstallException { List<RepositoryConfigValidationResult> validationResults = new ArrayList<RepositoryConfigValidationResult>(); // Retrieves the Repository Properties file File repoPropertiesFile = new File(getRepoPropertiesFileLocation()); Map<String, String> configMap = new HashMap<String, String>(); Map<String, Integer> lineMap = new HashMap<String, Integer>(); if (repoPropertiesFile.exists() && repoPropertiesFile.isFile()) { logger.log(Level.FINE, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("LOG_VALIDATING", getRepoPropertiesFileLocation())); //Load repository properties FileInputStream repoPropertiesInput = null; BufferedReader repoPropertiesReader = null; try { repoPropertiesInput = new FileInputStream(repoPropertiesFile); repoPropertiesReader = new BufferedReader(new InputStreamReader(repoPropertiesInput)); String line; int lineNum = 0; //Validate configurations in the repositories.properties file while ((line = repoPropertiesReader.readLine()) != null) { lineNum++; // depends on control dependency: [while], data = [none] validateRepositoryPropertiesLine(repoProperties, line, lineNum, configMap, lineMap, validationResults); // depends on control dependency: [while], data = [none] } //Missing Host if (configMap.containsKey(PROXY_HOST)) { int ln = lineMap.get(PROXY_HOST); if (!configMap.containsKey(PROXY_PORT)) { validationResults.add(new RepositoryConfigValidationResult(ln, ValidationFailedReason.MISSING_PORT, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("MSG_VALIDATION_MISSING_PORT_VALUE", configMap.get(PROXY_HOST)))); } else { /** * verify proxy host url along with the port number */ String proxyHost = repoProperties.getProperty(InstallConstants.REPO_PROPERTIES_PROXY_HOST); String proxyPort = repoProperties.getProperty(InstallConstants.REPO_PROPERTIES_PROXY_PORT); try { //Trim any trailing whitespaces proxyHost = proxyHost.trim(); proxyPort = proxyPort.trim(); URL proxyUrl = null; if (proxyHost.toLowerCase().contains("://")) { proxyUrl = new URL(proxyHost + ":" + proxyPort); if (!proxyUrl.getProtocol().toLowerCase().equals("http")) validationResults.add(new RepositoryConfigValidationResult(ln, ValidationFailedReason.INVALID_HOST, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("MSG_VALIDATION_INVALID_HOST", configMap.get(PROXY_HOST)))); } else { new URL("http://" + proxyHost + ":" + proxyPort); } } catch (MalformedURLException e) { validationResults.add(new RepositoryConfigValidationResult(ln, ValidationFailedReason.INVALID_HOST, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("MSG_VALIDATION_INVALID_HOST", configMap.get(PROXY_HOST)))); } } } else { if (configMap.containsKey(PROXY_PORT) || configMap.containsKey(PROXY_USER) || configMap.containsKey(PROXY_PASSWORD)) { int ln = 0; if (lineMap.containsKey(PROXY_PORT)) ln = lineMap.get(PROXY_PORT); else if (lineMap.containsKey(PROXY_USER)) ln = lineMap.get(PROXY_USER); else ln = lineMap.get(PROXY_PASSWORD); validationResults.add(new RepositoryConfigValidationResult(ln, ValidationFailedReason.MISSING_HOST, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("MSG_VALIDATION_MISSING_HOST"))); } } } catch (IOException e) { throw new InstallException(Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("ERROR_TOOL_REPOSITORY_PROPS_NOT_LOADED", getRepoPropertiesFileLocation()), InstallException.IO_FAILURE); } finally { InstallUtils.close(repoPropertiesInput); InstallUtils.close(repoPropertiesReader); } logger.log(Level.FINE, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("LOG_VALIDATION_DONE")); } return validationResults; } }
public class class_name { public static byte[] rowKeyFromTSUID(final TSDB tsdb, final byte[] tsuid, final long timestamp) { if (tsuid.length < tsdb.metrics.width()) { throw new IllegalArgumentException("TSUID appears to be missing the metric"); } final long base_time; if ((timestamp & Const.SECOND_MASK) != 0) { // drop the ms timestamp to seconds to calculate the base timestamp base_time = ((timestamp / 1000) - ((timestamp / 1000) % Const.MAX_TIMESPAN)); } else { base_time = (timestamp - (timestamp % Const.MAX_TIMESPAN)); } final byte[] row = new byte[Const.SALT_WIDTH() + tsuid.length + Const.TIMESTAMP_BYTES]; System.arraycopy(tsuid, 0, row, Const.SALT_WIDTH(), tsdb.metrics.width()); Bytes.setInt(row, (int) base_time, Const.SALT_WIDTH() + tsdb.metrics.width()); System.arraycopy(tsuid, tsdb.metrics.width(), row, Const.SALT_WIDTH() + tsdb.metrics.width() + Const.TIMESTAMP_BYTES, tsuid.length - tsdb.metrics.width()); RowKey.prefixKeyWithSalt(row); return row; } }
public class class_name { public static byte[] rowKeyFromTSUID(final TSDB tsdb, final byte[] tsuid, final long timestamp) { if (tsuid.length < tsdb.metrics.width()) { throw new IllegalArgumentException("TSUID appears to be missing the metric"); } final long base_time; if ((timestamp & Const.SECOND_MASK) != 0) { // drop the ms timestamp to seconds to calculate the base timestamp base_time = ((timestamp / 1000) - ((timestamp / 1000) % Const.MAX_TIMESPAN)); // depends on control dependency: [if], data = [0)] } else { base_time = (timestamp - (timestamp % Const.MAX_TIMESPAN)); // depends on control dependency: [if], data = [none] } final byte[] row = new byte[Const.SALT_WIDTH() + tsuid.length + Const.TIMESTAMP_BYTES]; System.arraycopy(tsuid, 0, row, Const.SALT_WIDTH(), tsdb.metrics.width()); Bytes.setInt(row, (int) base_time, Const.SALT_WIDTH() + tsdb.metrics.width()); System.arraycopy(tsuid, tsdb.metrics.width(), row, Const.SALT_WIDTH() + tsdb.metrics.width() + Const.TIMESTAMP_BYTES, tsuid.length - tsdb.metrics.width()); RowKey.prefixKeyWithSalt(row); return row; } }
public class class_name { private GenericQueryRequest createN1qlRequest(final N1qlQuery query, String bucket, String username, String password, InetAddress targetNode) { String rawQuery = query.n1ql().toString(); rawQuery = rawQuery.replaceAll( CouchbaseAsyncBucket.CURRENT_BUCKET_IDENTIFIER, "`" + bucket + "`" ); String statement = query.statement().toString(); if (targetNode != null) { return GenericQueryRequest.jsonQuery(rawQuery, bucket, username, password, targetNode, query.params().clientContextId(), statement); } else { return GenericQueryRequest.jsonQuery(rawQuery, bucket, username, password, query.params().clientContextId(), statement); } } }
public class class_name { private GenericQueryRequest createN1qlRequest(final N1qlQuery query, String bucket, String username, String password, InetAddress targetNode) { String rawQuery = query.n1ql().toString(); rawQuery = rawQuery.replaceAll( CouchbaseAsyncBucket.CURRENT_BUCKET_IDENTIFIER, "`" + bucket + "`" ); String statement = query.statement().toString(); if (targetNode != null) { return GenericQueryRequest.jsonQuery(rawQuery, bucket, username, password, targetNode, query.params().clientContextId(), statement); // depends on control dependency: [if], data = [none] } else { return GenericQueryRequest.jsonQuery(rawQuery, bucket, username, password, query.params().clientContextId(), statement); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public String toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) { StringBuilder buf = new StringBuilder(); synchronized (payloads) { if (payloads.size() > 0) { buf.append('<').append(getElementName()); buf.append(" xmlns=\"").append(getNamespace()).append("\" >"); Iterator<JinglePayloadType> pt = payloads.listIterator(); while (pt.hasNext()) { JinglePayloadType pte = pt.next(); buf.append(pte.toXML()); } buf.append("</").append(getElementName()).append('>'); } } return buf.toString(); } }
public class class_name { @Override public String toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) { StringBuilder buf = new StringBuilder(); synchronized (payloads) { if (payloads.size() > 0) { buf.append('<').append(getElementName()); // depends on control dependency: [if], data = [none] buf.append(" xmlns=\"").append(getNamespace()).append("\" >"); // depends on control dependency: [if], data = [none] Iterator<JinglePayloadType> pt = payloads.listIterator(); while (pt.hasNext()) { JinglePayloadType pte = pt.next(); buf.append(pte.toXML()); // depends on control dependency: [while], data = [none] } buf.append("</").append(getElementName()).append('>'); // depends on control dependency: [if], data = [none] } } return buf.toString(); } }
public class class_name { public TagLibraryInfo[] getTagLibraryInfos() { TagLibraryInfo[] taglibs = null; Collection c = pageInfo.getTaglibs(); if (c != null) { Object[] objs = c.toArray(); if (objs != null && objs.length > 0) { taglibs = new TagLibraryInfo[objs.length]; for (int i=0; i<objs.length; i++) { taglibs[i] = (TagLibraryInfo) objs[i]; } } } return taglibs; } }
public class class_name { public TagLibraryInfo[] getTagLibraryInfos() { TagLibraryInfo[] taglibs = null; Collection c = pageInfo.getTaglibs(); if (c != null) { Object[] objs = c.toArray(); if (objs != null && objs.length > 0) { taglibs = new TagLibraryInfo[objs.length]; // depends on control dependency: [if], data = [none] for (int i=0; i<objs.length; i++) { taglibs[i] = (TagLibraryInfo) objs[i]; // depends on control dependency: [for], data = [i] } } } return taglibs; } }
public class class_name { public void marshall(DescribeTaskExecutionRequest describeTaskExecutionRequest, ProtocolMarshaller protocolMarshaller) { if (describeTaskExecutionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeTaskExecutionRequest.getTaskExecutionArn(), TASKEXECUTIONARN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DescribeTaskExecutionRequest describeTaskExecutionRequest, ProtocolMarshaller protocolMarshaller) { if (describeTaskExecutionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeTaskExecutionRequest.getTaskExecutionArn(), TASKEXECUTIONARN_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 Node getNextSingleNode(final Node user, RelationshipType relationshipType) { // find an outgoing relation of the type specified Relationship rel = null; try { rel = user.getSingleRelationship(relationshipType, Direction.OUTGOING); } catch (final NonWritableChannelException e) { // TODO: why is this here? Bug for read-only databases in previous // version? } return (rel == null) ? (null) : (rel.getEndNode()); } }
public class class_name { public static Node getNextSingleNode(final Node user, RelationshipType relationshipType) { // find an outgoing relation of the type specified Relationship rel = null; try { rel = user.getSingleRelationship(relationshipType, Direction.OUTGOING); // depends on control dependency: [try], data = [none] } catch (final NonWritableChannelException e) { // TODO: why is this here? Bug for read-only databases in previous // version? } // depends on control dependency: [catch], data = [none] return (rel == null) ? (null) : (rel.getEndNode()); } }
public class class_name { public static RuntimeException handle(Throwable e) { if (e instanceof CRestException) { return handle((CRestException) e); }else if (e instanceof RequestException) { return handle((RequestException) e); } else if (e instanceof IllegalArgumentException) { return handle((IllegalArgumentException) e); } else if (e instanceof IllegalStateException) { return handle((IllegalStateException) e); } else if (e instanceof InvocationTargetException) { return handle((InvocationTargetException) e); } else { return new CRestException(e.getMessage(), e); } } }
public class class_name { public static RuntimeException handle(Throwable e) { if (e instanceof CRestException) { return handle((CRestException) e); // depends on control dependency: [if], data = [none] }else if (e instanceof RequestException) { return handle((RequestException) e); // depends on control dependency: [if], data = [none] } else if (e instanceof IllegalArgumentException) { return handle((IllegalArgumentException) e); // depends on control dependency: [if], data = [none] } else if (e instanceof IllegalStateException) { return handle((IllegalStateException) e); // depends on control dependency: [if], data = [none] } else if (e instanceof InvocationTargetException) { return handle((InvocationTargetException) e); // depends on control dependency: [if], data = [none] } else { return new CRestException(e.getMessage(), e); // depends on control dependency: [if], data = [none] } } }
public class class_name { @FFDCIgnore(Exception.class) //manually logged or is NoSuchElementException which we want to ignore private void processInvalidListeners() { final boolean trace = com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled(); String appName = getIStore().getId(); long start = System.currentTimeMillis(); if (trace && tc.isDebugEnabled()) tcInvoke(tcSessionMetaCache, "iterator"); @SuppressWarnings("rawtypes") Iterator<Cache.Entry<String, ArrayList>> it = sessionMetaCache.iterator(); if (trace && tc.isDebugEnabled()) tcReturn(tcSessionMetaCache, "iterator", it); while (it.hasNext()) { if (trace && tc.isDebugEnabled()) tcInvoke(tcSessionMetaCache, "_iterator.next"); @SuppressWarnings("rawtypes") Cache.Entry<String, ArrayList> entry; try { entry = it.next(); } catch (NoSuchElementException x) { // ignore - some JCache providers might raise this instead of returning null when modified during iterator entry = null; } String id = entry == null ? null : entry.getKey(); ArrayList<?> value = id == null ? null : entry.getValue(); if (trace && tc.isDebugEnabled()) tcReturn(tcSessionMetaCache, "_iterator.next", id, value); if (id != null && !INVAL_KEY.equals(id)) { SessionInfo sessionInfo = new SessionInfo(value); long lastAccess = sessionInfo.getLastAccess(); short listenerTypes = sessionInfo.getListenerTypes(); int maxInactive = sessionInfo.getMaxInactiveTime(); if ((listenerTypes & BackedSession.HTTP_SESSION_BINDING_LISTENER) != 0 // sessions that DO have binding listeners && maxInactive >= 0 && maxInactive < (start - lastAccess) / 1000) { if (trace && tc.isDebugEnabled()) Tr.debug(this, tc, "processInvalidListeners for sessionID=" + id); CacheSession session = new CacheSession(this, id, _iStore.getStoreCallback()); session.initSession(_iStore); session.setIsValid(true); session.setIsNew(false); session.updateLastAccessTime(lastAccess); session.setCreationTime(sessionInfo.getCreationTime()); session.internalSetMaxInactive(maxInactive); session.internalSetUser(sessionInfo.getUser()); session.setListenerFlag(listenerTypes); long now = System.currentTimeMillis(); //handle the subset of session listeners lastAccess = session.getCurrentAccessTime(); // try using lastTouch again.. try { // get the session ready and read in any listeners session.setIsNew(false); session.getSwappableListeners(BackedSession.HTTP_SESSION_BINDING_LISTENER); sessionInfo = sessionInfo.clone(); sessionInfo.setLastAccess(lastAccess); // only invalidate those which have not been accessed since // check in computeInvalidList ArrayList<Object> list = sessionInfo.getArrayList(); if (trace && tc.isDebugEnabled()) tcInvoke(tcSessionMetaCache, "remove", id, list); boolean removed = sessionMetaCache.remove(id, list); if (trace && tc.isDebugEnabled()) tcReturn(tcSessionMetaCache, "remove", removed); if (removed) { // return of session done as a result of this call session.internalInvalidate(true); Set<String> propIds = sessionInfo.getSessionPropertyIds(); if (propIds != null && !propIds.isEmpty()) { HashSet<String> propKeys = new HashSet<String>(); for (String propId : propIds) propKeys.add(createSessionAttributeKey(id, propId)); if (trace && tc.isDebugEnabled()) tcInvoke(tcSessionAttrCache, "removeAll", propKeys); sessionAttributeCache.removeAll(propKeys); if (trace && tc.isDebugEnabled()) tcReturn(tcSessionAttrCache, "removeAll"); } } /* * we don't want to update this on every invalidation with a listener that is processed. * We'll only update this if we're getting close. * * Processing Invalidation Listeners could take a long time. We should update the * NukerTimeStamp so that another server in this cluster doesn't kick off invalidation * while we are still processing. We only want to update the time stamp if we are getting * close to the time when it will expire. Therefore, we are going to do it after we're 1/2 way there. */ if ((now + _smc.getInvalidationCheckInterval() * (1000 / 2)) < System.currentTimeMillis()) { updateNukerTimeStamp(appName); now = System.currentTimeMillis(); } } catch (Exception e) { FFDCFilter.processException(e, getClass().getName(), "652", this, new Object[] { session }); throw e; } } } } } }
public class class_name { @FFDCIgnore(Exception.class) //manually logged or is NoSuchElementException which we want to ignore private void processInvalidListeners() { final boolean trace = com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled(); String appName = getIStore().getId(); long start = System.currentTimeMillis(); if (trace && tc.isDebugEnabled()) tcInvoke(tcSessionMetaCache, "iterator"); @SuppressWarnings("rawtypes") Iterator<Cache.Entry<String, ArrayList>> it = sessionMetaCache.iterator(); if (trace && tc.isDebugEnabled()) tcReturn(tcSessionMetaCache, "iterator", it); while (it.hasNext()) { if (trace && tc.isDebugEnabled()) tcInvoke(tcSessionMetaCache, "_iterator.next"); @SuppressWarnings("rawtypes") Cache.Entry<String, ArrayList> entry; try { entry = it.next(); // depends on control dependency: [try], data = [none] } catch (NoSuchElementException x) { // ignore - some JCache providers might raise this instead of returning null when modified during iterator entry = null; } // depends on control dependency: [catch], data = [none] String id = entry == null ? null : entry.getKey(); ArrayList<?> value = id == null ? null : entry.getValue(); if (trace && tc.isDebugEnabled()) tcReturn(tcSessionMetaCache, "_iterator.next", id, value); if (id != null && !INVAL_KEY.equals(id)) { SessionInfo sessionInfo = new SessionInfo(value); long lastAccess = sessionInfo.getLastAccess(); short listenerTypes = sessionInfo.getListenerTypes(); int maxInactive = sessionInfo.getMaxInactiveTime(); if ((listenerTypes & BackedSession.HTTP_SESSION_BINDING_LISTENER) != 0 // sessions that DO have binding listeners && maxInactive >= 0 && maxInactive < (start - lastAccess) / 1000) { if (trace && tc.isDebugEnabled()) Tr.debug(this, tc, "processInvalidListeners for sessionID=" + id); CacheSession session = new CacheSession(this, id, _iStore.getStoreCallback()); session.initSession(_iStore); // depends on control dependency: [if], data = [none] session.setIsValid(true); // depends on control dependency: [if], data = [none] session.setIsNew(false); // depends on control dependency: [if], data = [none] session.updateLastAccessTime(lastAccess); // depends on control dependency: [if], data = [none] session.setCreationTime(sessionInfo.getCreationTime()); // depends on control dependency: [if], data = [none] session.internalSetMaxInactive(maxInactive); // depends on control dependency: [if], data = [none] session.internalSetUser(sessionInfo.getUser()); // depends on control dependency: [if], data = [none] session.setListenerFlag(listenerTypes); // depends on control dependency: [if], data = [none] long now = System.currentTimeMillis(); //handle the subset of session listeners lastAccess = session.getCurrentAccessTime(); // try using lastTouch again.. // depends on control dependency: [if], data = [none] try { // get the session ready and read in any listeners session.setIsNew(false); // depends on control dependency: [try], data = [none] session.getSwappableListeners(BackedSession.HTTP_SESSION_BINDING_LISTENER); // depends on control dependency: [try], data = [none] sessionInfo = sessionInfo.clone(); // depends on control dependency: [try], data = [none] sessionInfo.setLastAccess(lastAccess); // depends on control dependency: [try], data = [none] // only invalidate those which have not been accessed since // check in computeInvalidList ArrayList<Object> list = sessionInfo.getArrayList(); if (trace && tc.isDebugEnabled()) tcInvoke(tcSessionMetaCache, "remove", id, list); boolean removed = sessionMetaCache.remove(id, list); if (trace && tc.isDebugEnabled()) tcReturn(tcSessionMetaCache, "remove", removed); if (removed) { // return of session done as a result of this call session.internalInvalidate(true); // depends on control dependency: [if], data = [none] Set<String> propIds = sessionInfo.getSessionPropertyIds(); if (propIds != null && !propIds.isEmpty()) { HashSet<String> propKeys = new HashSet<String>(); for (String propId : propIds) propKeys.add(createSessionAttributeKey(id, propId)); if (trace && tc.isDebugEnabled()) tcInvoke(tcSessionAttrCache, "removeAll", propKeys); sessionAttributeCache.removeAll(propKeys); // depends on control dependency: [if], data = [none] if (trace && tc.isDebugEnabled()) tcReturn(tcSessionAttrCache, "removeAll"); } } /* * we don't want to update this on every invalidation with a listener that is processed. * We'll only update this if we're getting close. * * Processing Invalidation Listeners could take a long time. We should update the * NukerTimeStamp so that another server in this cluster doesn't kick off invalidation * while we are still processing. We only want to update the time stamp if we are getting * close to the time when it will expire. Therefore, we are going to do it after we're 1/2 way there. */ if ((now + _smc.getInvalidationCheckInterval() * (1000 / 2)) < System.currentTimeMillis()) { updateNukerTimeStamp(appName); // depends on control dependency: [if], data = [none] now = System.currentTimeMillis(); // depends on control dependency: [if], data = [none] } } catch (Exception e) { FFDCFilter.processException(e, getClass().getName(), "652", this, new Object[] { session }); throw e; } // depends on control dependency: [catch], data = [none] } } } } }
public class class_name { @SuppressWarnings("unchecked") public static List<Statement> getStatements(MethodNode method) { Statement code = method.getCode(); if (!(code instanceof BlockStatement)) { // null or single statement BlockStatement block = new BlockStatement(); if (code != null) block.addStatement(code); method.setCode(block); } return ((BlockStatement)method.getCode()).getStatements(); } }
public class class_name { @SuppressWarnings("unchecked") public static List<Statement> getStatements(MethodNode method) { Statement code = method.getCode(); if (!(code instanceof BlockStatement)) { // null or single statement BlockStatement block = new BlockStatement(); if (code != null) block.addStatement(code); method.setCode(block); // depends on control dependency: [if], data = [none] } return ((BlockStatement)method.getCode()).getStatements(); } }
public class class_name { private Item findPackageItem(String pkgName) { if (packageToItemMap == null) { return null; } return packageToItemMap.get(pkgName); } }
public class class_name { private Item findPackageItem(String pkgName) { if (packageToItemMap == null) { return null; // depends on control dependency: [if], data = [none] } return packageToItemMap.get(pkgName); } }
public class class_name { public static int regexFlags(final String s) { int flags = 0; if (s == null) { return flags; } for (final char f : s.toLowerCase().toCharArray()) { flags |= regexFlag(f); } return flags; } }
public class class_name { public static int regexFlags(final String s) { int flags = 0; if (s == null) { return flags; // depends on control dependency: [if], data = [none] } for (final char f : s.toLowerCase().toCharArray()) { flags |= regexFlag(f); // depends on control dependency: [for], data = [f] } return flags; } }
public class class_name { private static String processStringWithRegex(String text, Pattern pattern, int startIndex, boolean recurseEmojify) { //System.out.println(text); Matcher matcher = pattern.matcher(text); StringBuffer sb = new StringBuffer(); int resetIndex = 0; if(startIndex > 0) { matcher.region(startIndex, text.length()); } while (matcher.find()) { String emojiCode = matcher.group(); Emoji emoji = getEmoji(emojiCode); // replace matched tokens with emojis if(emoji!=null) { matcher.appendReplacement(sb, emoji.getEmoji()); } else { if(htmlSurrogateEntityPattern2.matcher(emojiCode).matches()) { String highSurrogate1 = matcher.group("H1"); String highSurrogate2 = matcher.group("H2"); String lowSurrogate1 = matcher.group("L1"); String lowSurrogate2 = matcher.group("L2"); matcher.appendReplacement(sb, processStringWithRegex(highSurrogate1+highSurrogate2, shortCodeOrHtmlEntityPattern, 0, false)); //basically this handles &#junk1;&#10084;&#65039;&#junk2; scenario //verifies if &#junk1;&#10084; or &#junk1; are valid emojis via recursion //if not move past &#junk1; and reset the cursor to &#10084; if(sb.toString().endsWith(highSurrogate2)) { resetIndex = sb.length() - highSurrogate2.length(); } else { resetIndex = sb.length(); } sb.append(lowSurrogate1); sb.append(lowSurrogate2); break; } else if(htmlSurrogateEntityPattern.matcher(emojiCode).matches()) { //could be individual html entities assumed as surrogate pair String highSurrogate = matcher.group("H"); String lowSurrogate = matcher.group("L"); matcher.appendReplacement(sb, processStringWithRegex(highSurrogate, htmlEntityPattern, 0, true)); resetIndex = sb.length(); sb.append(lowSurrogate); break; } else { matcher.appendReplacement(sb, emojiCode); } } } matcher.appendTail(sb); //do not recurse emojify when coming here through htmlSurrogateEntityPattern2..so we get a chance to check if the tail //is part of a surrogate entity if(recurseEmojify && resetIndex > 0) { return emojify(sb.toString(), resetIndex); } return sb.toString(); } }
public class class_name { private static String processStringWithRegex(String text, Pattern pattern, int startIndex, boolean recurseEmojify) { //System.out.println(text); Matcher matcher = pattern.matcher(text); StringBuffer sb = new StringBuffer(); int resetIndex = 0; if(startIndex > 0) { matcher.region(startIndex, text.length()); // depends on control dependency: [if], data = [(startIndex] } while (matcher.find()) { String emojiCode = matcher.group(); Emoji emoji = getEmoji(emojiCode); // replace matched tokens with emojis if(emoji!=null) { matcher.appendReplacement(sb, emoji.getEmoji()); // depends on control dependency: [if], data = [none] } else { if(htmlSurrogateEntityPattern2.matcher(emojiCode).matches()) { String highSurrogate1 = matcher.group("H1"); String highSurrogate2 = matcher.group("H2"); String lowSurrogate1 = matcher.group("L1"); String lowSurrogate2 = matcher.group("L2"); matcher.appendReplacement(sb, processStringWithRegex(highSurrogate1+highSurrogate2, shortCodeOrHtmlEntityPattern, 0, false)); // depends on control dependency: [if], data = [none] //basically this handles &#junk1;&#10084;&#65039;&#junk2; scenario //verifies if &#junk1;&#10084; or &#junk1; are valid emojis via recursion //if not move past &#junk1; and reset the cursor to &#10084; if(sb.toString().endsWith(highSurrogate2)) { resetIndex = sb.length() - highSurrogate2.length(); // depends on control dependency: [if], data = [none] } else { resetIndex = sb.length(); // depends on control dependency: [if], data = [none] } sb.append(lowSurrogate1); // depends on control dependency: [if], data = [none] sb.append(lowSurrogate2); // depends on control dependency: [if], data = [none] break; } else if(htmlSurrogateEntityPattern.matcher(emojiCode).matches()) { //could be individual html entities assumed as surrogate pair String highSurrogate = matcher.group("H"); String lowSurrogate = matcher.group("L"); matcher.appendReplacement(sb, processStringWithRegex(highSurrogate, htmlEntityPattern, 0, true)); // depends on control dependency: [if], data = [none] resetIndex = sb.length(); // depends on control dependency: [if], data = [none] sb.append(lowSurrogate); // depends on control dependency: [if], data = [none] break; } else { matcher.appendReplacement(sb, emojiCode); // depends on control dependency: [if], data = [none] } } } matcher.appendTail(sb); //do not recurse emojify when coming here through htmlSurrogateEntityPattern2..so we get a chance to check if the tail //is part of a surrogate entity if(recurseEmojify && resetIndex > 0) { return emojify(sb.toString(), resetIndex); // depends on control dependency: [if], data = [none] } return sb.toString(); } }
public class class_name { @ObjectiveCName("failure:") public synchronized Promise<T> failure(final Consumer<Exception> failure) { if (isFinished) { if (exception != null) { dispatcher.dispatch(() -> failure.apply(exception)); } } else { callbacks.add(new PromiseCallback<T>() { @Override public void onResult(T t) { // Do nothing } @Override public void onError(Exception e) { failure.apply(e); } }); } return this; } }
public class class_name { @ObjectiveCName("failure:") public synchronized Promise<T> failure(final Consumer<Exception> failure) { if (isFinished) { if (exception != null) { dispatcher.dispatch(() -> failure.apply(exception)); // depends on control dependency: [if], data = [(exception] } } else { callbacks.add(new PromiseCallback<T>() { @Override public void onResult(T t) { // Do nothing } @Override public void onError(Exception e) { failure.apply(e); } }); // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { @Override public void disconnect() { network.disconnect(); for (final L listener : listeners) { network.removeListener(listener); } listeners.clear(); } }
public class class_name { @Override public void disconnect() { network.disconnect(); for (final L listener : listeners) { network.removeListener(listener); // depends on control dependency: [for], data = [listener] } listeners.clear(); } }
public class class_name { private double handleCase1() { double stpc = SearchInterpolate.cubic2(fx, gx, stx, fp, gp, stp); double stpq = SearchInterpolate.quadratic(fx,gx,stx,fp,stp); // If the cubic step is closer to stx than the quadratic step take that bracket = true; if( Math.abs(stpc-stx) < Math.abs(stpq-stx)) { return stpc; } else { // otherwise go with the average of the twp return stpc + (stpq-stpc)/2.0; } } }
public class class_name { private double handleCase1() { double stpc = SearchInterpolate.cubic2(fx, gx, stx, fp, gp, stp); double stpq = SearchInterpolate.quadratic(fx,gx,stx,fp,stp); // If the cubic step is closer to stx than the quadratic step take that bracket = true; if( Math.abs(stpc-stx) < Math.abs(stpq-stx)) { return stpc; // depends on control dependency: [if], data = [none] } else { // otherwise go with the average of the twp return stpc + (stpq-stpc)/2.0; // depends on control dependency: [if], data = [none] } } }
public class class_name { public ByteBuffer readRawBlock() throws IOException, EthereumBlockReadException { // basically an Ethereum Block is simply a RLP encoded list ByteBuffer result=null; // get size of list this.in.mark(10); byte[] listHeader = new byte[10]; int totalRead = 0; int bRead=this.in.read(listHeader); if (bRead == -1) { // no further block to read return result; } else { totalRead += bRead; while (totalRead < 10) { bRead=this.in.read(listHeader, totalRead, 10 - totalRead); if (bRead == -1) { throw new EthereumBlockReadException("Error: Not enough block data available: " + String.valueOf(bRead)); } totalRead += bRead; } } ByteBuffer sizeByteBuffer=ByteBuffer.wrap(listHeader); long blockSize = EthereumUtil.getRLPListSize(sizeByteBuffer); // gets block size including indicator this.in.reset(); // check if blockSize is valid if (blockSize==0) { throw new EthereumBlockReadException("Error: Blocksize too small"); } if (blockSize<0) { throw new EthereumBlockReadException("Error: This block size cannot be handled currently (larger then largest number in positive signed int)"); } if (blockSize>this.maxSizeEthereumBlock) { throw new EthereumBlockReadException("Error: Block size is larger then defined in configuration - Please increase it if this is a valid block"); } // read block int blockSizeInt=(int)(blockSize); byte[] fullBlock=new byte[blockSizeInt]; int totalByteRead=0; int readByte; while ((readByte=this.in.read(fullBlock,totalByteRead,blockSizeInt-totalByteRead))>-1) { totalByteRead+=readByte; if (totalByteRead>=blockSize) { break; } } if (totalByteRead!=blockSize) { throw new EthereumBlockReadException("Error: Could not read full block"); } if (!(this.useDirectBuffer)) { result=ByteBuffer.wrap(fullBlock); } else { preAllocatedDirectByteBuffer.clear(); // clear out old bytebuffer preAllocatedDirectByteBuffer.limit(fullBlock.length); // limit the bytebuffer result=preAllocatedDirectByteBuffer; result.put(fullBlock); result.flip(); // put in read mode } result.order(ByteOrder.LITTLE_ENDIAN); return result; } }
public class class_name { public ByteBuffer readRawBlock() throws IOException, EthereumBlockReadException { // basically an Ethereum Block is simply a RLP encoded list ByteBuffer result=null; // get size of list this.in.mark(10); byte[] listHeader = new byte[10]; int totalRead = 0; int bRead=this.in.read(listHeader); if (bRead == -1) { // no further block to read return result; } else { totalRead += bRead; while (totalRead < 10) { bRead=this.in.read(listHeader, totalRead, 10 - totalRead); // depends on control dependency: [while], data = [none] if (bRead == -1) { throw new EthereumBlockReadException("Error: Not enough block data available: " + String.valueOf(bRead)); } totalRead += bRead; // depends on control dependency: [while], data = [none] } } ByteBuffer sizeByteBuffer=ByteBuffer.wrap(listHeader); long blockSize = EthereumUtil.getRLPListSize(sizeByteBuffer); // gets block size including indicator this.in.reset(); // check if blockSize is valid if (blockSize==0) { throw new EthereumBlockReadException("Error: Blocksize too small"); } if (blockSize<0) { throw new EthereumBlockReadException("Error: This block size cannot be handled currently (larger then largest number in positive signed int)"); } if (blockSize>this.maxSizeEthereumBlock) { throw new EthereumBlockReadException("Error: Block size is larger then defined in configuration - Please increase it if this is a valid block"); } // read block int blockSizeInt=(int)(blockSize); byte[] fullBlock=new byte[blockSizeInt]; int totalByteRead=0; int readByte; while ((readByte=this.in.read(fullBlock,totalByteRead,blockSizeInt-totalByteRead))>-1) { totalByteRead+=readByte; if (totalByteRead>=blockSize) { break; } } if (totalByteRead!=blockSize) { throw new EthereumBlockReadException("Error: Could not read full block"); } if (!(this.useDirectBuffer)) { result=ByteBuffer.wrap(fullBlock); } else { preAllocatedDirectByteBuffer.clear(); // clear out old bytebuffer preAllocatedDirectByteBuffer.limit(fullBlock.length); // limit the bytebuffer result=preAllocatedDirectByteBuffer; result.put(fullBlock); result.flip(); // put in read mode } result.order(ByteOrder.LITTLE_ENDIAN); return result; } }
public class class_name { public void startExtension(Map<String, String> attributes) throws IOException { startChangesIfNecessary(); ResponseWriter writer = getWrapped(); writer.startElement("extension", null); if (attributes != null && !attributes.isEmpty()) { for (Map.Entry<String, String> entry : attributes.entrySet()) { writer.writeAttribute(entry.getKey(), entry.getValue(), null); } } } }
public class class_name { public void startExtension(Map<String, String> attributes) throws IOException { startChangesIfNecessary(); ResponseWriter writer = getWrapped(); writer.startElement("extension", null); if (attributes != null && !attributes.isEmpty()) { for (Map.Entry<String, String> entry : attributes.entrySet()) { writer.writeAttribute(entry.getKey(), entry.getValue(), null); // depends on control dependency: [for], data = [entry] } } } }
public class class_name { private void init() throws CmsException { // first get all installed plugins // plugins are subfolders of the "/plugin/" folder with a template // property holdding the name of the plugin class List resources = m_cms.readResourcesWithProperty(VFS_PATH_PLUGIN_FOLDER, CmsToolManager.HANDLERCLASS_PROPERTY); Iterator i = resources.iterator(); while (i.hasNext()) { CmsResource res = (CmsResource)i.next(); // ony check folders if (res.isFolder()) { String classname = m_cms.readPropertyObject( res.getRootPath(), CmsToolManager.HANDLERCLASS_PROPERTY, false).getValue(); try { Object objectInstance = Class.forName(classname).newInstance(); if (objectInstance instanceof I_CmsContentCheck) { I_CmsContentCheck plugin = (I_CmsContentCheck)objectInstance; plugin.init(m_cms); // store the plugin instance m_plugins.add(plugin); LOG.info(Messages.get().getBundle().key(Messages.LOG_CREATE_PLUGIN_1, classname)); } else { LOG.warn(Messages.get().getBundle().key(Messages.LOG_CANNOT_CREATE_PLUGIN_1, classname)); } } catch (Throwable t) { LOG.error(Messages.get().getBundle().key(Messages.LOG_CANNOT_CREATE_PLUGIN_2, classname, t)); } } } } }
public class class_name { private void init() throws CmsException { // first get all installed plugins // plugins are subfolders of the "/plugin/" folder with a template // property holdding the name of the plugin class List resources = m_cms.readResourcesWithProperty(VFS_PATH_PLUGIN_FOLDER, CmsToolManager.HANDLERCLASS_PROPERTY); Iterator i = resources.iterator(); while (i.hasNext()) { CmsResource res = (CmsResource)i.next(); // ony check folders if (res.isFolder()) { String classname = m_cms.readPropertyObject( res.getRootPath(), CmsToolManager.HANDLERCLASS_PROPERTY, false).getValue(); try { Object objectInstance = Class.forName(classname).newInstance(); if (objectInstance instanceof I_CmsContentCheck) { I_CmsContentCheck plugin = (I_CmsContentCheck)objectInstance; plugin.init(m_cms); // depends on control dependency: [if], data = [none] // store the plugin instance m_plugins.add(plugin); // depends on control dependency: [if], data = [none] LOG.info(Messages.get().getBundle().key(Messages.LOG_CREATE_PLUGIN_1, classname)); // depends on control dependency: [if], data = [none] } else { LOG.warn(Messages.get().getBundle().key(Messages.LOG_CANNOT_CREATE_PLUGIN_1, classname)); // depends on control dependency: [if], data = [none] } } catch (Throwable t) { LOG.error(Messages.get().getBundle().key(Messages.LOG_CANNOT_CREATE_PLUGIN_2, classname, t)); } } } } }
public class class_name { protected void addNeighborToOrdering(TrustGraphNodeId neighbor) { int position = rng.nextInt(orderedNeighbors.size()+1); if (position == orderedNeighbors.size()) { orderedNeighbors.add(neighbor); } else { orderedNeighbors.add(position, neighbor); } } }
public class class_name { protected void addNeighborToOrdering(TrustGraphNodeId neighbor) { int position = rng.nextInt(orderedNeighbors.size()+1); if (position == orderedNeighbors.size()) { orderedNeighbors.add(neighbor); // depends on control dependency: [if], data = [none] } else { orderedNeighbors.add(position, neighbor); // depends on control dependency: [if], data = [(position] } } }
public class class_name { public void expectMin(String name, double minLength, String message) { String value = Optional.ofNullable(get(name)).orElse(""); if (StringUtils.isNumeric(value)) { if (Double.parseDouble(value) < minLength) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.MIN_KEY.name(), name, minLength))); } } else { if (value.length() < minLength) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.MIN_KEY.name(), name, minLength))); } } } }
public class class_name { public void expectMin(String name, double minLength, String message) { String value = Optional.ofNullable(get(name)).orElse(""); if (StringUtils.isNumeric(value)) { if (Double.parseDouble(value) < minLength) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.MIN_KEY.name(), name, minLength))); // depends on control dependency: [if], data = [minLength)] } } else { if (value.length() < minLength) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.MIN_KEY.name(), name, minLength))); // depends on control dependency: [if], data = [minLength)] } } } }
public class class_name { public static boolean containsIgnoreCase(final String string, final String[] strings) { if (null == strings) { return false; } return Arrays.stream(strings).anyMatch(str -> StringUtils.equalsIgnoreCase(string, str)); } }
public class class_name { public static boolean containsIgnoreCase(final String string, final String[] strings) { if (null == strings) { return false; // depends on control dependency: [if], data = [none] } return Arrays.stream(strings).anyMatch(str -> StringUtils.equalsIgnoreCase(string, str)); } }
public class class_name { private static int chunkSize(final InputStream stream) throws IOException { final ByteArrayOutputStream baos = ChunkedInputStream.sizeLine(stream); final int result; final String data = baos.toString(Charset.defaultCharset().name()); final int separator = data.indexOf(';'); try { // @checkstyle MagicNumberCheck (10 lines) if (separator > 0) { result = Integer.parseInt( data.substring(0, separator).trim(), 16 ); } else { result = Integer.parseInt(data.trim(), 16); } return result; } catch (final NumberFormatException ex) { throw new IOException( String.format( "Bad chunk size: %s", baos.toString(Charset.defaultCharset().name()) ), ex ); } } }
public class class_name { private static int chunkSize(final InputStream stream) throws IOException { final ByteArrayOutputStream baos = ChunkedInputStream.sizeLine(stream); final int result; final String data = baos.toString(Charset.defaultCharset().name()); final int separator = data.indexOf(';'); try { // @checkstyle MagicNumberCheck (10 lines) if (separator > 0) { result = Integer.parseInt( data.substring(0, separator).trim(), 16 ); // depends on control dependency: [if], data = [none] } else { result = Integer.parseInt(data.trim(), 16); // depends on control dependency: [if], data = [none] } return result; } catch (final NumberFormatException ex) { throw new IOException( String.format( "Bad chunk size: %s", baos.toString(Charset.defaultCharset().name()) ), ex ); } } }
public class class_name { @Override public Response replaceApplicationBindings( String applicationName, String externalExportPrefix, List<String> boundApps ) { if( this.logger.isLoggable( Level.FINE )) { StringBuilder sb = new StringBuilder(); sb.append( "Replacing the bindings for the " ); sb.append( externalExportPrefix ); sb.append( " prefix with " ); sb.append( Arrays.toString( boundApps.toArray())); sb.append( " in application " ); sb.append( applicationName ); sb.append( "." ); this.logger.fine( sb.toString()); } String lang = lang( this.manager ); Response response; try { ManagedApplication ma = this.manager.applicationMngr().findManagedApplicationByName( applicationName ); if( ma == null ) { response = RestServicesUtils.handleError( Status.NOT_FOUND, new RestError( ErrorCode.REST_INEXISTING, application( applicationName )), lang ).build(); } else { Set<String> apps = new TreeSet<> (); if( boundApps != null ) apps.addAll( boundApps ); this.manager.applicationMngr().replaceApplicationBindings( ma, externalExportPrefix, apps ); response = Response.ok().build(); } } catch( UnauthorizedActionException | IOException e ) { response = RestServicesUtils.handleError( Status.FORBIDDEN, new RestError( ErrorCode.REST_UNDETAILED_ERROR, e ), lang ).build(); } return response; } }
public class class_name { @Override public Response replaceApplicationBindings( String applicationName, String externalExportPrefix, List<String> boundApps ) { if( this.logger.isLoggable( Level.FINE )) { StringBuilder sb = new StringBuilder(); sb.append( "Replacing the bindings for the " ); // depends on control dependency: [if], data = [none] sb.append( externalExportPrefix ); // depends on control dependency: [if], data = [none] sb.append( " prefix with " ); // depends on control dependency: [if], data = [none] sb.append( Arrays.toString( boundApps.toArray())); // depends on control dependency: [if], data = [none] sb.append( " in application " ); // depends on control dependency: [if], data = [none] sb.append( applicationName ); // depends on control dependency: [if], data = [none] sb.append( "." ); // depends on control dependency: [if], data = [none] this.logger.fine( sb.toString()); // depends on control dependency: [if], data = [none] } String lang = lang( this.manager ); Response response; try { ManagedApplication ma = this.manager.applicationMngr().findManagedApplicationByName( applicationName ); if( ma == null ) { response = RestServicesUtils.handleError( Status.NOT_FOUND, new RestError( ErrorCode.REST_INEXISTING, application( applicationName )), lang ).build(); // depends on control dependency: [if], data = [none] } else { Set<String> apps = new TreeSet<> (); if( boundApps != null ) apps.addAll( boundApps ); this.manager.applicationMngr().replaceApplicationBindings( ma, externalExportPrefix, apps ); // depends on control dependency: [if], data = [( ma] response = Response.ok().build(); // depends on control dependency: [if], data = [none] } } catch( UnauthorizedActionException | IOException e ) { response = RestServicesUtils.handleError( Status.FORBIDDEN, new RestError( ErrorCode.REST_UNDETAILED_ERROR, e ), lang ).build(); } // depends on control dependency: [catch], data = [none] return response; } }
public class class_name { private int afterHookInsertLine(TestMethod method, int codeLineIndex) { // if multiple statements exist in one line, afterHook is inserted only after the last statement, // since when multi-line statements are like: // method(1);method( // 2); // insertion to the middle of the statement causes problem if (!isLineLastStament(method, codeLineIndex)) { return -1; } // insert hook to the next line of the codeLine // since insertAt method inserts code just before the specified line CodeLine codeLine = method.getCodeBody().get(codeLineIndex); return codeLine.getEndLine() + 1; } }
public class class_name { private int afterHookInsertLine(TestMethod method, int codeLineIndex) { // if multiple statements exist in one line, afterHook is inserted only after the last statement, // since when multi-line statements are like: // method(1);method( // 2); // insertion to the middle of the statement causes problem if (!isLineLastStament(method, codeLineIndex)) { return -1; // depends on control dependency: [if], data = [none] } // insert hook to the next line of the codeLine // since insertAt method inserts code just before the specified line CodeLine codeLine = method.getCodeBody().get(codeLineIndex); return codeLine.getEndLine() + 1; } }
public class class_name { public static Properties parseJSON(String json) { try { return utilsImpl.parseJSON(json); } catch (Exception e) { if (!GWT.isProdMode()) { System.err.println("Error while parsing json: " + e.getMessage() + ".\n" + json); } return Properties.create(); } } }
public class class_name { public static Properties parseJSON(String json) { try { return utilsImpl.parseJSON(json); // depends on control dependency: [try], data = [none] } catch (Exception e) { if (!GWT.isProdMode()) { System.err.println("Error while parsing json: " + e.getMessage() + ".\n" + json); // depends on control dependency: [if], data = [none] } return Properties.create(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { final public void add(long curTime, long val) { if (!enabled) return; lastSampleTime = curTime; if (!sync) { if (val > max) max = val; if (count > 0) { if (val < min) min = val; } else min = val; //set min=val for the first time /* * if (val < min || min < 0) * min = val; */ count++; total += val; sumOfSquares += val * val; } else { // synchronized ONLY the count updates synchronized (this) { count++; total += val; } if (val > max) max = val; if (count > 0) { if (val < min) min = val; } else min = val; //set min=val for the first time sumOfSquares += val * val; } } }
public class class_name { final public void add(long curTime, long val) { if (!enabled) return; lastSampleTime = curTime; if (!sync) { if (val > max) max = val; if (count > 0) { if (val < min) min = val; } else min = val; //set min=val for the first time /* * if (val < min || min < 0) * min = val; */ count++; // depends on control dependency: [if], data = [none] total += val; // depends on control dependency: [if], data = [none] sumOfSquares += val * val; // depends on control dependency: [if], data = [none] } else { // synchronized ONLY the count updates synchronized (this) { // depends on control dependency: [if], data = [none] count++; total += val; } if (val > max) max = val; if (count > 0) { if (val < min) min = val; } else min = val; //set min=val for the first time sumOfSquares += val * val; // depends on control dependency: [if], data = [none] } } }
public class class_name { public SemanticType extractFieldType(SemanticType.Record type, Identifier field) { if (type == null) { return null; } else { SemanticType fieldType = type.getField(field); if (fieldType == null) { // Indicates an invalid field selection syntaxError(field, INVALID_FIELD); } return fieldType; } } }
public class class_name { public SemanticType extractFieldType(SemanticType.Record type, Identifier field) { if (type == null) { return null; // depends on control dependency: [if], data = [none] } else { SemanticType fieldType = type.getField(field); if (fieldType == null) { // Indicates an invalid field selection syntaxError(field, INVALID_FIELD); // depends on control dependency: [if], data = [none] } return fieldType; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void interpret( Specification specification ) { Statistics stats = new Statistics(); skipFirstRowOfNextTable(); while (specification.hasMoreExamples() && canContinue( stats )) { Example next = specification.nextExample(); if (indicatesEndOfFlow( next )) { specification.exampleDone( new Statistics() ); return; } Table table = new Table( firstRowOf(next) ); execute(table); specification.exampleDone( table.getStatistics() ); stats.tally( table.getStatistics() ); includeFirstRowOfNextTable(); /* * In case there was a 'END' keyword sticked in the table. */ Example lastCells = next.firstChild().lastSibling().firstChild(); boolean indicatesEnd = "end".equalsIgnoreCase( ExampleUtil.contentOf( lastCells ) ); if (indicatesEnd) { specification.exampleDone( new Statistics() ); return; } } } }
public class class_name { public void interpret( Specification specification ) { Statistics stats = new Statistics(); skipFirstRowOfNextTable(); while (specification.hasMoreExamples() && canContinue( stats )) { Example next = specification.nextExample(); if (indicatesEndOfFlow( next )) { specification.exampleDone( new Statistics() ); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } Table table = new Table( firstRowOf(next) ); execute(table); // depends on control dependency: [while], data = [none] specification.exampleDone( table.getStatistics() ); // depends on control dependency: [while], data = [none] stats.tally( table.getStatistics() ); // depends on control dependency: [while], data = [none] includeFirstRowOfNextTable(); // depends on control dependency: [while], data = [none] /* * In case there was a 'END' keyword sticked in the table. */ Example lastCells = next.firstChild().lastSibling().firstChild(); boolean indicatesEnd = "end".equalsIgnoreCase( ExampleUtil.contentOf( lastCells ) ); if (indicatesEnd) { specification.exampleDone( new Statistics() ); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } } } }
public class class_name { public ListConferenceProvidersResult withConferenceProviders(ConferenceProvider... conferenceProviders) { if (this.conferenceProviders == null) { setConferenceProviders(new java.util.ArrayList<ConferenceProvider>(conferenceProviders.length)); } for (ConferenceProvider ele : conferenceProviders) { this.conferenceProviders.add(ele); } return this; } }
public class class_name { public ListConferenceProvidersResult withConferenceProviders(ConferenceProvider... conferenceProviders) { if (this.conferenceProviders == null) { setConferenceProviders(new java.util.ArrayList<ConferenceProvider>(conferenceProviders.length)); // depends on control dependency: [if], data = [none] } for (ConferenceProvider ele : conferenceProviders) { this.conferenceProviders.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public static X500Principal getIssuerX500Principal(X509CRL crl) { try { byte[] encoded = crl.getEncoded(); DerInputStream derIn = new DerInputStream(encoded); DerValue tbsCert = derIn.getSequence(3)[0]; DerInputStream tbsIn = tbsCert.data; DerValue tmp; // skip version number if present byte nextByte = (byte)tbsIn.peekByte(); if (nextByte == DerValue.tag_Integer) { tmp = tbsIn.getDerValue(); } tmp = tbsIn.getDerValue(); // skip signature tmp = tbsIn.getDerValue(); // issuer byte[] principalBytes = tmp.toByteArray(); return new X500Principal(principalBytes); } catch (Exception e) { throw new RuntimeException("Could not parse issuer", e); } } }
public class class_name { public static X500Principal getIssuerX500Principal(X509CRL crl) { try { byte[] encoded = crl.getEncoded(); DerInputStream derIn = new DerInputStream(encoded); DerValue tbsCert = derIn.getSequence(3)[0]; DerInputStream tbsIn = tbsCert.data; DerValue tmp; // skip version number if present byte nextByte = (byte)tbsIn.peekByte(); if (nextByte == DerValue.tag_Integer) { tmp = tbsIn.getDerValue(); // depends on control dependency: [if], data = [none] } tmp = tbsIn.getDerValue(); // skip signature // depends on control dependency: [try], data = [none] tmp = tbsIn.getDerValue(); // issuer // depends on control dependency: [try], data = [none] byte[] principalBytes = tmp.toByteArray(); return new X500Principal(principalBytes); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new RuntimeException("Could not parse issuer", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public boolean call(Context context, String dataName, Bundle data) { boolean useLocalBroadcast = BeaconManager.getInstanceForApplication(context).isMainProcess(); boolean success = false; if(useLocalBroadcast) { String action = null; if (dataName == "rangingData") { action = BeaconLocalBroadcastProcessor.RANGE_NOTIFICATION; } else { action = BeaconLocalBroadcastProcessor.MONITOR_NOTIFICATION; } Intent intent = new Intent(action); intent.putExtra(dataName, data); LogManager.d(TAG, "attempting callback via local broadcast intent: %s",action); success = LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } else { Intent intent = new Intent(); intent.setComponent(new ComponentName(context.getPackageName(), "org.altbeacon.beacon.BeaconIntentProcessor")); intent.putExtra(dataName, data); LogManager.d(TAG, "attempting callback via global broadcast intent: %s",intent.getComponent()); try { context.startService(intent); success = true; } catch (Exception e) { LogManager.e( TAG, "Failed attempting to start service: " + intent.getComponent().flattenToString(), e ); } } return success; } }
public class class_name { public boolean call(Context context, String dataName, Bundle data) { boolean useLocalBroadcast = BeaconManager.getInstanceForApplication(context).isMainProcess(); boolean success = false; if(useLocalBroadcast) { String action = null; if (dataName == "rangingData") { action = BeaconLocalBroadcastProcessor.RANGE_NOTIFICATION; // depends on control dependency: [if], data = [none] } else { action = BeaconLocalBroadcastProcessor.MONITOR_NOTIFICATION; // depends on control dependency: [if], data = [none] } Intent intent = new Intent(action); intent.putExtra(dataName, data); // depends on control dependency: [if], data = [none] LogManager.d(TAG, "attempting callback via local broadcast intent: %s",action); // depends on control dependency: [if], data = [none] success = LocalBroadcastManager.getInstance(context).sendBroadcast(intent); // depends on control dependency: [if], data = [none] } else { Intent intent = new Intent(); intent.setComponent(new ComponentName(context.getPackageName(), "org.altbeacon.beacon.BeaconIntentProcessor")); // depends on control dependency: [if], data = [none] intent.putExtra(dataName, data); // depends on control dependency: [if], data = [none] LogManager.d(TAG, "attempting callback via global broadcast intent: %s",intent.getComponent()); // depends on control dependency: [if], data = [none] try { context.startService(intent); // depends on control dependency: [try], data = [none] success = true; // depends on control dependency: [try], data = [none] } catch (Exception e) { LogManager.e( TAG, "Failed attempting to start service: " + intent.getComponent().flattenToString(), e ); } // depends on control dependency: [catch], data = [none] } return success; } }
public class class_name { @Override public void decryptBlock(byte[] data, int offset, byte[] dest, int destOffset) { // w128_t x; // x.q[0] = ((uint64_t *) blk)[0] ^ key->k[9].q[0]; // x.q[1] = ((uint64_t *) blk)[1] ^ key->k[9].q[1]; Kuz128 x = new Kuz128(); x.setQ(0, ByteStrings.bytesToLong(data, offset) ^ key.getK()[9].getQ(0)); x.setQ(1, ByteStrings.bytesToLong(data, offset + 8) ^ key.getK()[9].getQ(1)); for (int i = 8; i >= 0; i--) { // kuz_l_inv(&x); KuznechikMath.kuz_l_inv(x); for (int j = 0; j < 16; j++) { // x.b[j] = kuz_pi_inv[x.b[j]]; x.getB()[j] = KuznechikTables.kuz_pi_inv[x.getB()[j] & 0xFF]; } // x.q[0] ^= key->k[i].q[0]; x.setQ(0, x.getQ(0) ^ key.getK()[i].getQ(0)); // x.q[1] ^= key->k[i].q[1]; x.setQ(1, x.getQ(1) ^ key.getK()[i].getQ(1)); } // ((uint64_t *) blk)[0] = x.q[0]; // ((uint64_t *) blk)[1] = x.q[1]; ByteStrings.write(dest, destOffset, ByteStrings.longToBytes(x.getQ(0)), 0, 8); ByteStrings.write(dest, destOffset + 8, ByteStrings.longToBytes(x.getQ(1)), 0, 8); } }
public class class_name { @Override public void decryptBlock(byte[] data, int offset, byte[] dest, int destOffset) { // w128_t x; // x.q[0] = ((uint64_t *) blk)[0] ^ key->k[9].q[0]; // x.q[1] = ((uint64_t *) blk)[1] ^ key->k[9].q[1]; Kuz128 x = new Kuz128(); x.setQ(0, ByteStrings.bytesToLong(data, offset) ^ key.getK()[9].getQ(0)); x.setQ(1, ByteStrings.bytesToLong(data, offset + 8) ^ key.getK()[9].getQ(1)); for (int i = 8; i >= 0; i--) { // kuz_l_inv(&x); KuznechikMath.kuz_l_inv(x); // depends on control dependency: [for], data = [none] for (int j = 0; j < 16; j++) { // x.b[j] = kuz_pi_inv[x.b[j]]; x.getB()[j] = KuznechikTables.kuz_pi_inv[x.getB()[j] & 0xFF]; // depends on control dependency: [for], data = [j] } // x.q[0] ^= key->k[i].q[0]; x.setQ(0, x.getQ(0) ^ key.getK()[i].getQ(0)); // depends on control dependency: [for], data = [i] // x.q[1] ^= key->k[i].q[1]; x.setQ(1, x.getQ(1) ^ key.getK()[i].getQ(1)); // depends on control dependency: [for], data = [i] } // ((uint64_t *) blk)[0] = x.q[0]; // ((uint64_t *) blk)[1] = x.q[1]; ByteStrings.write(dest, destOffset, ByteStrings.longToBytes(x.getQ(0)), 0, 8); ByteStrings.write(dest, destOffset + 8, ByteStrings.longToBytes(x.getQ(1)), 0, 8); } }
public class class_name { private List<SemanticError> check(DataType dataType, Constructor constructor) { logger.finer("Checking semantic constraints on data type " + dataType.name + ", constructor " + constructor.name); final List<SemanticError> errors = new ArrayList<SemanticError>(); final Set<String> argNames = new HashSet<String>(); for (Arg arg : constructor.args) { if (argNames.contains(arg.name)) { errors.add(_DuplicateArgName(dataType.name, constructor.name, arg.name)); } else { argNames.add(arg.name); } errors.addAll(check(dataType, constructor, arg)); } return errors; } }
public class class_name { private List<SemanticError> check(DataType dataType, Constructor constructor) { logger.finer("Checking semantic constraints on data type " + dataType.name + ", constructor " + constructor.name); final List<SemanticError> errors = new ArrayList<SemanticError>(); final Set<String> argNames = new HashSet<String>(); for (Arg arg : constructor.args) { if (argNames.contains(arg.name)) { errors.add(_DuplicateArgName(dataType.name, constructor.name, arg.name)); // depends on control dependency: [if], data = [none] } else { argNames.add(arg.name); // depends on control dependency: [if], data = [none] } errors.addAll(check(dataType, constructor, arg)); // depends on control dependency: [for], data = [arg] } return errors; } }
public class class_name { public Destination withToAddresses(String... toAddresses) { if (this.toAddresses == null) { setToAddresses(new java.util.ArrayList<String>(toAddresses.length)); } for (String ele : toAddresses) { this.toAddresses.add(ele); } return this; } }
public class class_name { public Destination withToAddresses(String... toAddresses) { if (this.toAddresses == null) { setToAddresses(new java.util.ArrayList<String>(toAddresses.length)); // depends on control dependency: [if], data = [none] } for (String ele : toAddresses) { this.toAddresses.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { private boolean isSoilAnalysisExist(ArrayList<HashMap> icSubArr) { for (HashMap icSubData : icSubArr) { if (!getValueOr(icSubData, "slsc", "").equals("")) { return true; } } return false; } }
public class class_name { private boolean isSoilAnalysisExist(ArrayList<HashMap> icSubArr) { for (HashMap icSubData : icSubArr) { if (!getValueOr(icSubData, "slsc", "").equals("")) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { private void parseLiteral() { AtomicValue atomic; if (mToken.getType() == TokenType.VALUE || mToken.getType() == TokenType.POINT) { // is numeric literal atomic = parseIntegerLiteral(); } else { // is string literal assert (mToken.getType() == TokenType.DBL_QUOTE || mToken.getType() == TokenType.SINGLE_QUOTE); atomic = parseStringLiteral(); } mPipeBuilder.addLiteral(mRTX, atomic); } }
public class class_name { private void parseLiteral() { AtomicValue atomic; if (mToken.getType() == TokenType.VALUE || mToken.getType() == TokenType.POINT) { // is numeric literal atomic = parseIntegerLiteral(); // depends on control dependency: [if], data = [none] } else { // is string literal assert (mToken.getType() == TokenType.DBL_QUOTE || mToken.getType() == TokenType.SINGLE_QUOTE); // depends on control dependency: [if], data = [(mToken.getType()] atomic = parseStringLiteral(); // depends on control dependency: [if], data = [none] } mPipeBuilder.addLiteral(mRTX, atomic); } }
public class class_name { @Override protected Variable[] createVariablesSub(int num) { int[] tp = tpCreate(num); Variable[] ret = new Variable[num]; for (int i = 0; i < tp.length; i++) { ret[i] = tPoints[tp[i]]; } return ret; } }
public class class_name { @Override protected Variable[] createVariablesSub(int num) { int[] tp = tpCreate(num); Variable[] ret = new Variable[num]; for (int i = 0; i < tp.length; i++) { ret[i] = tPoints[tp[i]]; // depends on control dependency: [for], data = [i] } return ret; } }
public class class_name { synchronized TypeSerializerFactory factory(Class<?> type) { TypeSerializerFactory factory = factories.get(type); if (factory != null) { return factory; } Class<?> baseType; // If no factory was found, determine if an abstract serializer can be used. baseType = findBaseType(type, abstractFactories); if (baseType != null) { return abstractFactories.get(baseType); } // If no factory was found, determine if a default serializer can be used. baseType = findBaseType(type, defaultFactories); if (baseType != null) { return defaultFactories.get(baseType); } return null; } }
public class class_name { synchronized TypeSerializerFactory factory(Class<?> type) { TypeSerializerFactory factory = factories.get(type); if (factory != null) { return factory; // depends on control dependency: [if], data = [none] } Class<?> baseType; // If no factory was found, determine if an abstract serializer can be used. baseType = findBaseType(type, abstractFactories); if (baseType != null) { return abstractFactories.get(baseType); // depends on control dependency: [if], data = [(baseType] } // If no factory was found, determine if a default serializer can be used. baseType = findBaseType(type, defaultFactories); if (baseType != null) { return defaultFactories.get(baseType); // depends on control dependency: [if], data = [(baseType] } return null; } }
public class class_name { public static ParsedExpression parse(String expression) { ParsedExpression pe = (ParsedExpression)PARSED_CACHE.get(expression); if(pe != null) return pe; try { NetUIELParser learn = new NetUIELParser(new StringReader(expression)); ParsedExpression expr = learn.parse(); expr.seal(); /* infrequent; this should only happen when there is a cache miss */ synchronized(PARSED_CACHE) { PARSED_CACHE.put(expression, expr); } return expr; } catch(ParseException e) { String msg = "Error occurred parsing expression \"" + expression + "\"."; LOGGER.error(msg, e); throw new ExpressionParseException(msg, e); } catch(TokenMgrError tm) { String msg = "Error occurred parsing expression \"" + expression + "\"."; LOGGER.error(msg, tm); throw new ExpressionParseException(msg, tm); } } }
public class class_name { public static ParsedExpression parse(String expression) { ParsedExpression pe = (ParsedExpression)PARSED_CACHE.get(expression); if(pe != null) return pe; try { NetUIELParser learn = new NetUIELParser(new StringReader(expression)); ParsedExpression expr = learn.parse(); expr.seal(); // depends on control dependency: [try], data = [none] /* infrequent; this should only happen when there is a cache miss */ synchronized(PARSED_CACHE) { // depends on control dependency: [try], data = [none] PARSED_CACHE.put(expression, expr); } return expr; // depends on control dependency: [try], data = [none] } catch(ParseException e) { String msg = "Error occurred parsing expression \"" + expression + "\"."; LOGGER.error(msg, e); throw new ExpressionParseException(msg, e); } catch(TokenMgrError tm) { // depends on control dependency: [catch], data = [none] String msg = "Error occurred parsing expression \"" + expression + "\"."; LOGGER.error(msg, tm); throw new ExpressionParseException(msg, tm); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public boolean update(String tableName, String primaryKey, Record record) { Connection conn = null; try { conn = config.getConnection(); return update(config, conn, tableName, primaryKey, record); } catch (Exception e) { throw new ActiveRecordException(e); } finally { config.close(conn); } } }
public class class_name { public boolean update(String tableName, String primaryKey, Record record) { Connection conn = null; try { conn = config.getConnection(); // depends on control dependency: [try], data = [none] return update(config, conn, tableName, primaryKey, record); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new ActiveRecordException(e); } finally { // depends on control dependency: [catch], data = [none] config.close(conn); } } }
public class class_name { public Option options(Option... values) { if (values == null || values.length == 0) { return this; } this.options().addAll(Arrays.asList(values)); return this; } }
public class class_name { public Option options(Option... values) { if (values == null || values.length == 0) { return this; // depends on control dependency: [if], data = [none] } this.options().addAll(Arrays.asList(values)); return this; } }
public class class_name { static <T> FluentCloseableIterable<T> wrap(final Iterable<T> iterable, final AutoCloseable closeable) { return new FluentCloseableIterable<T>() { @Override protected void doClose() { try { closeable.close(); } catch (RuntimeException re) { throw re; } catch (Exception e) { throw new IllegalStateException(e); } } @Override protected Iterator<T> retrieveIterator() { return iterable.iterator(); } }; } }
public class class_name { static <T> FluentCloseableIterable<T> wrap(final Iterable<T> iterable, final AutoCloseable closeable) { return new FluentCloseableIterable<T>() { @Override protected void doClose() { try { closeable.close(); // depends on control dependency: [try], data = [none] } catch (RuntimeException re) { throw re; } catch (Exception e) { // depends on control dependency: [catch], data = [none] throw new IllegalStateException(e); } // depends on control dependency: [catch], data = [none] } @Override protected Iterator<T> retrieveIterator() { return iterable.iterator(); } }; } }
public class class_name { @Override final public void run() { while(true) { try { try { sleep(delayTime); } catch(InterruptedException err) { logger.log(Level.WARNING, null, err); } long time = System.currentTimeMillis(); List<C> connsToClose; synchronized(poolLock) { if(isClosed) return; // Find any connections that are available and been idle too long int maxIdle = maxIdleTime; connsToClose = new ArrayList<>(availableConnections.size()); for(PooledConnection<C> availableConnection : availableConnections) { synchronized(availableConnection) { C conn = availableConnection.connection; if(conn!=null) { if( (time-availableConnection.releaseTime) > maxIdle // Idle too long || ( maxConnectionAge!=UNLIMITED_MAX_CONNECTION_AGE && ( availableConnection.createTime > time // System time reset? || (time-availableConnection.createTime) >= maxConnectionAge // Max connection age reached ) ) ) { availableConnection.connection = null; connsToClose.add(conn); } } } } } // Close all of the connections for(C conn : connsToClose) { try { close(conn); } catch(Exception err) { logger.log(Level.WARNING, null, err); } } } catch (ThreadDeath TD) { throw TD; } catch (Throwable T) { logger.logp(Level.SEVERE, AOPool.class.getName(), "run", null, T); } } } }
public class class_name { @Override final public void run() { while(true) { try { try { sleep(delayTime); // depends on control dependency: [try], data = [none] } catch(InterruptedException err) { logger.log(Level.WARNING, null, err); } // depends on control dependency: [catch], data = [none] long time = System.currentTimeMillis(); List<C> connsToClose; synchronized(poolLock) { // depends on control dependency: [try], data = [none] if(isClosed) return; // Find any connections that are available and been idle too long int maxIdle = maxIdleTime; connsToClose = new ArrayList<>(availableConnections.size()); for(PooledConnection<C> availableConnection : availableConnections) { synchronized(availableConnection) { // depends on control dependency: [for], data = [availableConnection] C conn = availableConnection.connection; if(conn!=null) { if( (time-availableConnection.releaseTime) > maxIdle // Idle too long || ( maxConnectionAge!=UNLIMITED_MAX_CONNECTION_AGE && ( availableConnection.createTime > time // System time reset? || (time-availableConnection.createTime) >= maxConnectionAge // Max connection age reached ) ) ) { availableConnection.connection = null; // depends on control dependency: [if], data = [] connsToClose.add(conn); // depends on control dependency: [if], data = [] } } } } } // Close all of the connections for(C conn : connsToClose) { try { close(conn); // depends on control dependency: [try], data = [none] } catch(Exception err) { logger.log(Level.WARNING, null, err); } // depends on control dependency: [catch], data = [none] } } catch (ThreadDeath TD) { throw TD; } catch (Throwable T) { // depends on control dependency: [catch], data = [none] logger.logp(Level.SEVERE, AOPool.class.getName(), "run", null, T); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { private int binarySearchNonUnique(int fromIndex, int toIndex, long key1, long key2) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; long midVal1 = keys[mid]; long midVal2 = values[mid]; if (midVal1 < key1) { low = mid + 1; } else if (midVal1 > key1) { high = mid - 1; } else { if (midVal2 < key2) { low = mid + 1; } else if (midVal2 > key2) { high = mid - 1; } else { return mid; // key found } } } return -(low + 1); // key not found. } }
public class class_name { private int binarySearchNonUnique(int fromIndex, int toIndex, long key1, long key2) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; long midVal1 = keys[mid]; long midVal2 = values[mid]; if (midVal1 < key1) { low = mid + 1; // depends on control dependency: [if], data = [none] } else if (midVal1 > key1) { high = mid - 1; // depends on control dependency: [if], data = [none] } else { if (midVal2 < key2) { low = mid + 1; // depends on control dependency: [if], data = [none] } else if (midVal2 > key2) { high = mid - 1; // depends on control dependency: [if], data = [none] } else { return mid; // key found // depends on control dependency: [if], data = [none] } } } return -(low + 1); // key not found. } }
public class class_name { protected void printStackTrace(final PrintWriter printWriter, final Throwable throwable) { throwable.printStackTrace(printWriter); Throwable cause = throwable.getCause(); while (cause != null) { if (cause instanceof SQLException) { final SQLException nextException = ((SQLException) cause).getNextException(); if (nextException != null) { printWriter.print("Next exception: "); printStackTrace(printWriter, nextException); } } cause = cause.getCause(); } } }
public class class_name { protected void printStackTrace(final PrintWriter printWriter, final Throwable throwable) { throwable.printStackTrace(printWriter); Throwable cause = throwable.getCause(); while (cause != null) { if (cause instanceof SQLException) { final SQLException nextException = ((SQLException) cause).getNextException(); if (nextException != null) { printWriter.print("Next exception: "); // depends on control dependency: [if], data = [none] printStackTrace(printWriter, nextException); // depends on control dependency: [if], data = [none] } } cause = cause.getCause(); // depends on control dependency: [while], data = [none] } } }
public class class_name { protected MigrationReport convert(org.jbpm.runtime.manager.impl.migration.MigrationReport report) { List<MigrationEntry> logs = new ArrayList<MigrationEntry>(); for (org.jbpm.runtime.manager.impl.migration.MigrationEntry orig : report.getEntries()) { logs.add(new MigrationEntryImpl(orig.getTimestamp(), orig.getMessage(), orig.getType().toString())); } return new MigrationReportImpl(report.getMigrationSpec().getProcessInstanceId(), report.isSuccessful(), report.getStartDate(), report.getEndDate(), logs); } }
public class class_name { protected MigrationReport convert(org.jbpm.runtime.manager.impl.migration.MigrationReport report) { List<MigrationEntry> logs = new ArrayList<MigrationEntry>(); for (org.jbpm.runtime.manager.impl.migration.MigrationEntry orig : report.getEntries()) { logs.add(new MigrationEntryImpl(orig.getTimestamp(), orig.getMessage(), orig.getType().toString())); // depends on control dependency: [for], data = [orig] } return new MigrationReportImpl(report.getMigrationSpec().getProcessInstanceId(), report.isSuccessful(), report.getStartDate(), report.getEndDate(), logs); } }
public class class_name { public void marshall(ListSigningPlatformsRequest listSigningPlatformsRequest, ProtocolMarshaller protocolMarshaller) { if (listSigningPlatformsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listSigningPlatformsRequest.getCategory(), CATEGORY_BINDING); protocolMarshaller.marshall(listSigningPlatformsRequest.getPartner(), PARTNER_BINDING); protocolMarshaller.marshall(listSigningPlatformsRequest.getTarget(), TARGET_BINDING); protocolMarshaller.marshall(listSigningPlatformsRequest.getMaxResults(), MAXRESULTS_BINDING); protocolMarshaller.marshall(listSigningPlatformsRequest.getNextToken(), NEXTTOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ListSigningPlatformsRequest listSigningPlatformsRequest, ProtocolMarshaller protocolMarshaller) { if (listSigningPlatformsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listSigningPlatformsRequest.getCategory(), CATEGORY_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(listSigningPlatformsRequest.getPartner(), PARTNER_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(listSigningPlatformsRequest.getTarget(), TARGET_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(listSigningPlatformsRequest.getMaxResults(), MAXRESULTS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(listSigningPlatformsRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private String getPart(int pos) { String value = this.getValue(); if (value == null) { return null; } String[] parts = value.split("/"); return parts.length >= pos + 1 ? parts[pos] : null; } }
public class class_name { private String getPart(int pos) { String value = this.getValue(); if (value == null) { return null; // depends on control dependency: [if], data = [none] } String[] parts = value.split("/"); return parts.length >= pos + 1 ? parts[pos] : null; } }
public class class_name { @Override public CPAttachmentFileEntry fetchByC_C_LtD_S_First(long classNameId, long classPK, Date displayDate, int status, OrderByComparator<CPAttachmentFileEntry> orderByComparator) { List<CPAttachmentFileEntry> list = findByC_C_LtD_S(classNameId, classPK, displayDate, status, 0, 1, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; } }
public class class_name { @Override public CPAttachmentFileEntry fetchByC_C_LtD_S_First(long classNameId, long classPK, Date displayDate, int status, OrderByComparator<CPAttachmentFileEntry> orderByComparator) { List<CPAttachmentFileEntry> list = findByC_C_LtD_S(classNameId, classPK, displayDate, status, 0, 1, orderByComparator); if (!list.isEmpty()) { return list.get(0); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { private static String delimit(String s, char c) { int i = s.indexOf(c); while (i != -1) { if (i == 0 || s.charAt(i - 1) != '\\') { s = s.substring(0, i) + '\\' + s.substring(i); i = s.indexOf(c, i + 2); } else { i = s.indexOf(c, i + 1); } } return s; } }
public class class_name { private static String delimit(String s, char c) { int i = s.indexOf(c); while (i != -1) { if (i == 0 || s.charAt(i - 1) != '\\') { s = s.substring(0, i) + '\\' + s.substring(i); // depends on control dependency: [if], data = [(i] i = s.indexOf(c, i + 2); // depends on control dependency: [if], data = [none] } else { i = s.indexOf(c, i + 1); // depends on control dependency: [if], data = [none] } } return s; } }
public class class_name { private static Double eaDistance(double[] series, int a, int b, Integer motifSize, double range, double znormThreshold) { distCounter++; double cutOff2 = range * range; double[] seriesA = tp.znorm(tp.subseriesByCopy(series, a, a + motifSize), znormThreshold); double[] seriesB = tp.znorm(tp.subseriesByCopy(series, b, b + motifSize), znormThreshold); Double res = 0D; for (int i = 0; i < motifSize; i++) { res = res + distance2(seriesA[i], seriesB[i]); if (res > cutOff2) { eaCounter++; return Double.NaN; } } return Math.sqrt(res); } }
public class class_name { private static Double eaDistance(double[] series, int a, int b, Integer motifSize, double range, double znormThreshold) { distCounter++; double cutOff2 = range * range; double[] seriesA = tp.znorm(tp.subseriesByCopy(series, a, a + motifSize), znormThreshold); double[] seriesB = tp.znorm(tp.subseriesByCopy(series, b, b + motifSize), znormThreshold); Double res = 0D; for (int i = 0; i < motifSize; i++) { res = res + distance2(seriesA[i], seriesB[i]); // depends on control dependency: [for], data = [i] if (res > cutOff2) { eaCounter++; // depends on control dependency: [if], data = [none] return Double.NaN; // depends on control dependency: [if], data = [none] } } return Math.sqrt(res); } }
public class class_name { static <T> Single<T> wrap( SingleSource<T> source, Collection<ReactiveInstrumenter> instrumentations) { if (source instanceof Callable) { return new RxInstrumentedCallableSingle<>(source, instrumentations); } return new RxInstrumentedSingle<>(source, instrumentations); } }
public class class_name { static <T> Single<T> wrap( SingleSource<T> source, Collection<ReactiveInstrumenter> instrumentations) { if (source instanceof Callable) { return new RxInstrumentedCallableSingle<>(source, instrumentations); // depends on control dependency: [if], data = [none] } return new RxInstrumentedSingle<>(source, instrumentations); } }
public class class_name { private ItemStack handleDoubleClick(MalisisInventory inventory, MalisisSlot slot, boolean shiftClick) { if (!inventory.state.is(PLAYER_EXTRACT)) return ItemStack.EMPTY; // normal double click, go through all hovered slot inventory to merge the slots with the currently picked one if (!shiftClick && !pickedItemStack.isEmpty()) { for (int i = 0; i < 2; i++) { for (MalisisInventory inv : getInventories()) if (inv.pullItemStacks(pickedItemStack, i == 0)) break; if (pickedItemStack.getCount() < pickedItemStack.getMaxStackSize()) getPlayerInventory().pullItemStacks(pickedItemStack, i == 0); } setPickedItemStack(pickedItemStack); } // shift double click, go through all hovered slot's inventory to transfer matching itemStack to the other inventory else if (!lastShiftClicked.isEmpty()) { //transfer all matching itemStack into other inventories if (inventory == getPlayerInventory()) { } for (MalisisSlot s : inventory.getNonEmptySlots()) { ItemStack itemStack = s.getItemStack(); if (s.isState(PLAYER_EXTRACT) && ItemUtils.areItemStacksStackable(itemStack, lastShiftClicked)) { itemStack = transferSlotOutOfInventory(inventory, s); //replace what's left of the item back into the slot slot.setItemStack(itemStack); slot.onSlotChanged(); //itemStack is not empty, inventory is full, no need to keep looping the slots if (!itemStack.isEmpty()) return itemStack; } } } lastShiftClicked = ItemStack.EMPTY; return ItemStack.EMPTY; } }
public class class_name { private ItemStack handleDoubleClick(MalisisInventory inventory, MalisisSlot slot, boolean shiftClick) { if (!inventory.state.is(PLAYER_EXTRACT)) return ItemStack.EMPTY; // normal double click, go through all hovered slot inventory to merge the slots with the currently picked one if (!shiftClick && !pickedItemStack.isEmpty()) { for (int i = 0; i < 2; i++) { for (MalisisInventory inv : getInventories()) if (inv.pullItemStacks(pickedItemStack, i == 0)) break; if (pickedItemStack.getCount() < pickedItemStack.getMaxStackSize()) getPlayerInventory().pullItemStacks(pickedItemStack, i == 0); } setPickedItemStack(pickedItemStack); // depends on control dependency: [if], data = [none] } // shift double click, go through all hovered slot's inventory to transfer matching itemStack to the other inventory else if (!lastShiftClicked.isEmpty()) { //transfer all matching itemStack into other inventories if (inventory == getPlayerInventory()) { } for (MalisisSlot s : inventory.getNonEmptySlots()) { ItemStack itemStack = s.getItemStack(); if (s.isState(PLAYER_EXTRACT) && ItemUtils.areItemStacksStackable(itemStack, lastShiftClicked)) { itemStack = transferSlotOutOfInventory(inventory, s); // depends on control dependency: [if], data = [none] //replace what's left of the item back into the slot slot.setItemStack(itemStack); // depends on control dependency: [if], data = [none] slot.onSlotChanged(); // depends on control dependency: [if], data = [none] //itemStack is not empty, inventory is full, no need to keep looping the slots if (!itemStack.isEmpty()) return itemStack; } } } lastShiftClicked = ItemStack.EMPTY; return ItemStack.EMPTY; } }
public class class_name { public ISynchronizationPoint<IOException> write(char c) { if (!(stream instanceof ICharacterStream.Writable.Buffered)) return write(new char[] { c }, 0, 1); ISynchronizationPoint<IOException> last = lastWrite; if (last.isUnblocked()) { lastWrite = ((ICharacterStream.Writable.Buffered)stream).writeAsync(c); return lastWrite; } SynchronizationPoint<IOException> ours = new SynchronizationPoint<>(); lastWrite = ours; last.listenInline(() -> { ((ICharacterStream.Writable.Buffered)stream).writeAsync(c).listenInline(ours); }, ours); return ours; } }
public class class_name { public ISynchronizationPoint<IOException> write(char c) { if (!(stream instanceof ICharacterStream.Writable.Buffered)) return write(new char[] { c }, 0, 1); ISynchronizationPoint<IOException> last = lastWrite; if (last.isUnblocked()) { lastWrite = ((ICharacterStream.Writable.Buffered)stream).writeAsync(c); // depends on control dependency: [if], data = [none] return lastWrite; // depends on control dependency: [if], data = [none] } SynchronizationPoint<IOException> ours = new SynchronizationPoint<>(); lastWrite = ours; last.listenInline(() -> { ((ICharacterStream.Writable.Buffered)stream).writeAsync(c).listenInline(ours); }, ours); return ours; } }
public class class_name { public boolean sameAs(Frame<ValueType> other) { if (isTop != other.isTop) { return false; } if (isTop && other.isTop) { return true; } if (isBottom != other.isBottom) { return false; } if (isBottom && other.isBottom) { return true; } if (getNumSlots() != other.getNumSlots()) { return false; } for (int i = 0; i < getNumSlots(); ++i) { if (!getValue(i).equals(other.getValue(i))) { return false; } } return true; } }
public class class_name { public boolean sameAs(Frame<ValueType> other) { if (isTop != other.isTop) { return false; // depends on control dependency: [if], data = [none] } if (isTop && other.isTop) { return true; // depends on control dependency: [if], data = [none] } if (isBottom != other.isBottom) { return false; // depends on control dependency: [if], data = [none] } if (isBottom && other.isBottom) { return true; // depends on control dependency: [if], data = [none] } if (getNumSlots() != other.getNumSlots()) { return false; // depends on control dependency: [if], data = [none] } for (int i = 0; i < getNumSlots(); ++i) { if (!getValue(i).equals(other.getValue(i))) { return false; // depends on control dependency: [if], data = [none] } } return true; } }
public class class_name { public static URL removeTrailingSlash(URL url) { String file = url.getFile(); if (file.endsWith("/")) { //$NON-NLS-1$ file = file.substring(0, file.length() - 1); try { return new URL(url.getProtocol(), url.getHost(), url.getPort(), file); } catch (MalformedURLException e) { Assert.isTrue(false, e.getMessage()); } } else { return url; } return null; } }
public class class_name { public static URL removeTrailingSlash(URL url) { String file = url.getFile(); if (file.endsWith("/")) { //$NON-NLS-1$ file = file.substring(0, file.length() - 1); // depends on control dependency: [if], data = [none] try { return new URL(url.getProtocol(), url.getHost(), url.getPort(), file); // depends on control dependency: [try], data = [none] } catch (MalformedURLException e) { Assert.isTrue(false, e.getMessage()); } // depends on control dependency: [catch], data = [none] } else { return url; // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { private int prepare(IAtom atom, IBond prev) { int count = 0; amap[atom.getIndex()] = 1; for (IBond bond : atom.bonds()) { if (bond == prev) continue; IAtom nbr = bond.getOther(atom); if (amap[nbr.getIndex()] == 0) { qbonds[numBonds++] = (IQueryBond) bond; count += prepare(nbr, bond) + 1; } else if (nbr.getIndex() < atom.getIndex()) { ++count; // ring closure qbonds[numBonds++] = (IQueryBond) bond; } } return count; } }
public class class_name { private int prepare(IAtom atom, IBond prev) { int count = 0; amap[atom.getIndex()] = 1; for (IBond bond : atom.bonds()) { if (bond == prev) continue; IAtom nbr = bond.getOther(atom); if (amap[nbr.getIndex()] == 0) { qbonds[numBonds++] = (IQueryBond) bond; // depends on control dependency: [if], data = [none] count += prepare(nbr, bond) + 1; // depends on control dependency: [if], data = [none] } else if (nbr.getIndex() < atom.getIndex()) { ++count; // ring closure // depends on control dependency: [if], data = [none] qbonds[numBonds++] = (IQueryBond) bond; // depends on control dependency: [if], data = [none] } } return count; } }
public class class_name { void dedup(final Map<String, char[]> table) { String l = getLabel(); char[] v = table.get(l); if (v != null) { label = v; } else { table.put(l, label); } } }
public class class_name { void dedup(final Map<String, char[]> table) { String l = getLabel(); char[] v = table.get(l); if (v != null) { label = v; // depends on control dependency: [if], data = [none] } else { table.put(l, label); // depends on control dependency: [if], data = [none] } } }
public class class_name { protected void updateListeners() { TextGridEvent event = new TextGridEvent(this); for (TextGridListener listener : listeners) { listener.changedUpdate(event); } } }
public class class_name { protected void updateListeners() { TextGridEvent event = new TextGridEvent(this); for (TextGridListener listener : listeners) { listener.changedUpdate(event); // depends on control dependency: [for], data = [listener] } } }
public class class_name { public Audio getAIF(String ref, InputStream in) throws IOException { in = new BufferedInputStream(in); if (!soundWorks) { return new NullAudio(); } if (!inited) { throw new RuntimeException("Can't load sounds until SoundStore is init(). Use the container init() method."); } if (deferred) { return new DeferredSound(ref, in, DeferredSound.AIF); } int buffer = -1; if (loaded.get(ref) != null) { buffer = ((Integer) loaded.get(ref)).intValue(); } else { try { IntBuffer buf = BufferUtils.createIntBuffer(1); AiffData data = AiffData.create(in); AL10.alGenBuffers(buf); AL10.alBufferData(buf.get(0), data.format, data.data, data.samplerate); loaded.put(ref,new Integer(buf.get(0))); buffer = buf.get(0); } catch (Exception e) { Log.error(e); IOException x = new IOException("Failed to load: "+ref); x.initCause(e); throw x; } } if (buffer == -1) { throw new IOException("Unable to load: "+ref); } return new AudioImpl(this, buffer); } }
public class class_name { public Audio getAIF(String ref, InputStream in) throws IOException { in = new BufferedInputStream(in); if (!soundWorks) { return new NullAudio(); } if (!inited) { throw new RuntimeException("Can't load sounds until SoundStore is init(). Use the container init() method."); } if (deferred) { return new DeferredSound(ref, in, DeferredSound.AIF); } int buffer = -1; if (loaded.get(ref) != null) { buffer = ((Integer) loaded.get(ref)).intValue(); } else { try { IntBuffer buf = BufferUtils.createIntBuffer(1); AiffData data = AiffData.create(in); AL10.alGenBuffers(buf); // depends on control dependency: [try], data = [none] AL10.alBufferData(buf.get(0), data.format, data.data, data.samplerate); // depends on control dependency: [try], data = [none] loaded.put(ref,new Integer(buf.get(0))); // depends on control dependency: [try], data = [none] buffer = buf.get(0); // depends on control dependency: [try], data = [none] } catch (Exception e) { Log.error(e); IOException x = new IOException("Failed to load: "+ref); x.initCause(e); throw x; } // depends on control dependency: [catch], data = [none] } if (buffer == -1) { throw new IOException("Unable to load: "+ref); } return new AudioImpl(this, buffer); } }
public class class_name { static MetaBean lookup(Class<?> cls) { MetaBean meta = META_BEANS.get(cls); if (meta == null) { return metaBeanLookup(cls); } return meta; } }
public class class_name { static MetaBean lookup(Class<?> cls) { MetaBean meta = META_BEANS.get(cls); if (meta == null) { return metaBeanLookup(cls); // depends on control dependency: [if], data = [none] } return meta; } }
public class class_name { @Override public void generateSerializeOnXml(BindTypeContext context, MethodSpec.Builder methodBuilder, String serializerName, TypeName beanClass, String beanName, BindProperty property) { // define key and value type ParameterizedTypeName mapTypeName=(ParameterizedTypeName) property.getPropertyType().getTypeName(); TypeName keyTypeName = mapTypeName.typeArguments.get(0); TypeName valueTypeName = mapTypeName.typeArguments.get(1); //@formatter:off methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property)); if (property.xmlInfo.isWrappedCollection()) { methodBuilder.addCode("// write wrapper tag\n"); methodBuilder.addStatement("$L.writeStartElement($S)", serializerName, BindProperty.xmlName(property)); } BindTransform transformKey=BindTransformer.lookup(keyTypeName); // key can not be null // not in collection, it's included in an element BindProperty elementKeyProperty=BindProperty.builder(keyTypeName, property).inCollection(false).nullable(false).xmlType(property.xmlInfo.mapEntryType.toXmlType()).elementName(property.mapKeyName).build(); BindTransform transformValue=BindTransformer.lookup(valueTypeName); // not in collection, it's included in an element BindProperty elementValueProperty=BindProperty.builder(valueTypeName, property).inCollection(false).xmlType(property.xmlInfo.mapEntryType.toXmlType()).elementName(property.mapValueName).build(); methodBuilder.beginControlFlow("for ($T<$T, $T> item: $L.entrySet())", Entry.class, keyTypeName, valueTypeName, getter(beanName, beanClass, property)); methodBuilder.addStatement("$L.writeStartElement($S)$>", serializerName, property.xmlInfo.labelItem); transformKey.generateSerializeOnXml(context, methodBuilder, serializerName, null, "item.getKey()", elementKeyProperty); if (elementValueProperty.isNullable()) { methodBuilder.beginControlFlow("if (item.getValue()==null)"); methodBuilder.addStatement("$L.writeEmptyElement($S)", serializerName, property.mapValueName); methodBuilder.nextControlFlow("else"); transformValue.generateSerializeOnXml(context, methodBuilder, serializerName, null, "item.getValue()", elementValueProperty); methodBuilder.endControlFlow(); } else { transformValue.generateSerializeOnXml(context, methodBuilder, serializerName, null, "item.getValue()", elementValueProperty); } methodBuilder.addStatement("$<$L.writeEndElement()", serializerName); methodBuilder.endControlFlow(); if (property.xmlInfo.isWrappedCollection()) { methodBuilder.addStatement("$L.writeEndElement()", serializerName); } methodBuilder.endControlFlow(); //@formatter:on } }
public class class_name { @Override public void generateSerializeOnXml(BindTypeContext context, MethodSpec.Builder methodBuilder, String serializerName, TypeName beanClass, String beanName, BindProperty property) { // define key and value type ParameterizedTypeName mapTypeName=(ParameterizedTypeName) property.getPropertyType().getTypeName(); TypeName keyTypeName = mapTypeName.typeArguments.get(0); TypeName valueTypeName = mapTypeName.typeArguments.get(1); //@formatter:off methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property)); if (property.xmlInfo.isWrappedCollection()) { methodBuilder.addCode("// write wrapper tag\n"); methodBuilder.addStatement("$L.writeStartElement($S)", serializerName, BindProperty.xmlName(property)); // depends on control dependency: [if], data = [none] } BindTransform transformKey=BindTransformer.lookup(keyTypeName); // key can not be null // not in collection, it's included in an element BindProperty elementKeyProperty=BindProperty.builder(keyTypeName, property).inCollection(false).nullable(false).xmlType(property.xmlInfo.mapEntryType.toXmlType()).elementName(property.mapKeyName).build(); BindTransform transformValue=BindTransformer.lookup(valueTypeName); // not in collection, it's included in an element BindProperty elementValueProperty=BindProperty.builder(valueTypeName, property).inCollection(false).xmlType(property.xmlInfo.mapEntryType.toXmlType()).elementName(property.mapValueName).build(); methodBuilder.beginControlFlow("for ($T<$T, $T> item: $L.entrySet())", Entry.class, keyTypeName, valueTypeName, getter(beanName, beanClass, property)); methodBuilder.addStatement("$L.writeStartElement($S)$>", serializerName, property.xmlInfo.labelItem); transformKey.generateSerializeOnXml(context, methodBuilder, serializerName, null, "item.getKey()", elementKeyProperty); if (elementValueProperty.isNullable()) { methodBuilder.beginControlFlow("if (item.getValue()==null)"); // depends on control dependency: [if], data = [none] methodBuilder.addStatement("$L.writeEmptyElement($S)", serializerName, property.mapValueName); // depends on control dependency: [if], data = [none] methodBuilder.nextControlFlow("else"); // depends on control dependency: [if], data = [none] transformValue.generateSerializeOnXml(context, methodBuilder, serializerName, null, "item.getValue()", elementValueProperty); // depends on control dependency: [if], data = [none] methodBuilder.endControlFlow(); // depends on control dependency: [if], data = [none] } else { transformValue.generateSerializeOnXml(context, methodBuilder, serializerName, null, "item.getValue()", elementValueProperty); // depends on control dependency: [if], data = [none] } methodBuilder.addStatement("$<$L.writeEndElement()", serializerName); methodBuilder.endControlFlow(); if (property.xmlInfo.isWrappedCollection()) { methodBuilder.addStatement("$L.writeEndElement()", serializerName); // depends on control dependency: [if], data = [none] } methodBuilder.endControlFlow(); //@formatter:on } }
public class class_name { RangeSet getConditions() { RangeSet is = new RangeSet(); for (CharRange ic : transitions.keySet()) { if (ic != null) { is.add(ic); } } return is; } }
public class class_name { RangeSet getConditions() { RangeSet is = new RangeSet(); for (CharRange ic : transitions.keySet()) { if (ic != null) { is.add(ic); // depends on control dependency: [if], data = [(ic] } } return is; } }
public class class_name { public List<Meta> userMetadata(final long userId, final String key) throws SQLException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; List<Meta> meta = Lists.newArrayListWithExpectedSize(16); Timer.Context ctx = metrics.userMetadataTimer.time(); try { conn = connectionSupplier.getConnection(); stmt = conn.prepareStatement(selectUserMetaKeySQL); stmt.setLong(1, userId); stmt.setString(2, key); rs = stmt.executeQuery(); while(rs.next()) { meta.add(new Meta(rs.getLong(1), rs.getString(2), rs.getString(3))); } return meta; } finally { ctx.stop(); SQLUtil.closeQuietly(conn, stmt, rs); } } }
public class class_name { public List<Meta> userMetadata(final long userId, final String key) throws SQLException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; List<Meta> meta = Lists.newArrayListWithExpectedSize(16); Timer.Context ctx = metrics.userMetadataTimer.time(); try { conn = connectionSupplier.getConnection(); stmt = conn.prepareStatement(selectUserMetaKeySQL); stmt.setLong(1, userId); stmt.setString(2, key); rs = stmt.executeQuery(); while(rs.next()) { meta.add(new Meta(rs.getLong(1), rs.getString(2), rs.getString(3))); // depends on control dependency: [while], data = [none] } return meta; } finally { ctx.stop(); SQLUtil.closeQuietly(conn, stmt, rs); } } }
public class class_name { static String buildInstructionString(RouteProgress routeProgress, Milestone milestone) { if (milestone.getInstruction() != null) { // Create a new custom instruction based on the Instruction packaged with the Milestone return milestone.getInstruction().buildInstruction(routeProgress); } return EMPTY_STRING; } }
public class class_name { static String buildInstructionString(RouteProgress routeProgress, Milestone milestone) { if (milestone.getInstruction() != null) { // Create a new custom instruction based on the Instruction packaged with the Milestone return milestone.getInstruction().buildInstruction(routeProgress); // depends on control dependency: [if], data = [none] } return EMPTY_STRING; } }
public class class_name { public static void addMarkerAsPolyline(Marker marker, List<Marker> markers) { GeoPoint position = marker.getPosition(); int insertLocation = markers.size(); if (markers.size() > 1) { double[] distances = new double[markers.size()]; insertLocation = 0; distances[0] = SphericalUtil.computeDistanceBetween(position, markers.get(0).getPosition()); for (int i = 1; i < markers.size(); i++) { distances[i] = SphericalUtil.computeDistanceBetween(position, markers.get(i).getPosition()); if (distances[i] < distances[insertLocation]) { insertLocation = i; } } Integer beforeLocation = insertLocation > 0 ? insertLocation - 1 : null; Integer afterLocation = insertLocation < distances.length - 1 ? insertLocation + 1 : null; if (beforeLocation != null && afterLocation != null) { if (distances[beforeLocation] > distances[afterLocation]) { insertLocation = afterLocation; } } else if (beforeLocation != null) { if (distances[beforeLocation] >= SphericalUtil .computeDistanceBetween(markers.get(beforeLocation) .getPosition(), markers.get(insertLocation) .getPosition())) { insertLocation++; } } else { if (distances[afterLocation] < SphericalUtil .computeDistanceBetween(markers.get(afterLocation) .getPosition(), markers.get(insertLocation) .getPosition())) { insertLocation++; } } } markers.add(insertLocation, marker); } }
public class class_name { public static void addMarkerAsPolyline(Marker marker, List<Marker> markers) { GeoPoint position = marker.getPosition(); int insertLocation = markers.size(); if (markers.size() > 1) { double[] distances = new double[markers.size()]; insertLocation = 0; // depends on control dependency: [if], data = [none] distances[0] = SphericalUtil.computeDistanceBetween(position, markers.get(0).getPosition()); // depends on control dependency: [if], data = [none] for (int i = 1; i < markers.size(); i++) { distances[i] = SphericalUtil.computeDistanceBetween(position, markers.get(i).getPosition()); // depends on control dependency: [for], data = [i] if (distances[i] < distances[insertLocation]) { insertLocation = i; // depends on control dependency: [if], data = [none] } } Integer beforeLocation = insertLocation > 0 ? insertLocation - 1 : null; Integer afterLocation = insertLocation < distances.length - 1 ? insertLocation + 1 : null; if (beforeLocation != null && afterLocation != null) { if (distances[beforeLocation] > distances[afterLocation]) { insertLocation = afterLocation; // depends on control dependency: [if], data = [none] } } else if (beforeLocation != null) { if (distances[beforeLocation] >= SphericalUtil .computeDistanceBetween(markers.get(beforeLocation) .getPosition(), markers.get(insertLocation) .getPosition())) { insertLocation++; // depends on control dependency: [if], data = [none] } } else { if (distances[afterLocation] < SphericalUtil .computeDistanceBetween(markers.get(afterLocation) .getPosition(), markers.get(insertLocation) .getPosition())) { insertLocation++; // depends on control dependency: [if], data = [none] } } } markers.add(insertLocation, marker); } }
public class class_name { public String getHrefResolved(final String relativeUri) { if (Atom10Parser.isAbsoluteURI(relativeUri)) { return relativeUri; } else if (baseURI != null && collectionElement != null) { final int lastslash = baseURI.lastIndexOf("/"); return Atom10Parser.resolveURI(baseURI.substring(0, lastslash), collectionElement, relativeUri); } return null; } }
public class class_name { public String getHrefResolved(final String relativeUri) { if (Atom10Parser.isAbsoluteURI(relativeUri)) { return relativeUri; // depends on control dependency: [if], data = [none] } else if (baseURI != null && collectionElement != null) { final int lastslash = baseURI.lastIndexOf("/"); return Atom10Parser.resolveURI(baseURI.substring(0, lastslash), collectionElement, relativeUri); // depends on control dependency: [if], data = [(baseURI] } return null; } }
public class class_name { protected DecisionRequirementsDefinitionEntity loadDecisionRequirementsDefinition(String decisionRequirementsDefinitionId) { ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration(); DeploymentCache deploymentCache = configuration.getDeploymentCache(); DecisionRequirementsDefinitionEntity decisionRequirementsDefinition = deploymentCache.findDecisionRequirementsDefinitionFromCache(decisionRequirementsDefinitionId); if (decisionRequirementsDefinition == null) { CommandContext commandContext = Context.getCommandContext(); DecisionRequirementsDefinitionManager manager = commandContext.getDecisionRequirementsDefinitionManager(); decisionRequirementsDefinition = manager.findDecisionRequirementsDefinitionById(decisionRequirementsDefinitionId); if (decisionRequirementsDefinition != null) { decisionRequirementsDefinition = deploymentCache.resolveDecisionRequirementsDefinition(decisionRequirementsDefinition); } } return decisionRequirementsDefinition; } }
public class class_name { protected DecisionRequirementsDefinitionEntity loadDecisionRequirementsDefinition(String decisionRequirementsDefinitionId) { ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration(); DeploymentCache deploymentCache = configuration.getDeploymentCache(); DecisionRequirementsDefinitionEntity decisionRequirementsDefinition = deploymentCache.findDecisionRequirementsDefinitionFromCache(decisionRequirementsDefinitionId); if (decisionRequirementsDefinition == null) { CommandContext commandContext = Context.getCommandContext(); DecisionRequirementsDefinitionManager manager = commandContext.getDecisionRequirementsDefinitionManager(); decisionRequirementsDefinition = manager.findDecisionRequirementsDefinitionById(decisionRequirementsDefinitionId); // depends on control dependency: [if], data = [(decisionRequirementsDefinition] if (decisionRequirementsDefinition != null) { decisionRequirementsDefinition = deploymentCache.resolveDecisionRequirementsDefinition(decisionRequirementsDefinition); // depends on control dependency: [if], data = [(decisionRequirementsDefinition] } } return decisionRequirementsDefinition; } }
public class class_name { private CmsResource importResource( String source, String destination, String type, String uuidresource, long datelastmodified, String userlastmodified, long datecreated, String usercreated, String flags, List<CmsProperty> properties) { byte[] content = null; CmsResource result = null; try { // get the file content if (source != null) { content = getFileBytes(source); } int size = 0; if (content != null) { size = content.length; } // get all required information to create a CmsResource I_CmsResourceType resType; // get UUIDs for the user CmsUUID newUserlastmodified; CmsUUID newUsercreated; // check if user created and user lastmodified are valid users in this system. // if not, use the current user try { newUserlastmodified = m_cms.readUser(userlastmodified).getId(); } catch (CmsException e) { newUserlastmodified = m_cms.getRequestContext().getCurrentUser().getId(); // datelastmodified = System.currentTimeMillis(); } try { newUsercreated = m_cms.readUser(usercreated).getId(); } catch (CmsException e) { newUsercreated = m_cms.getRequestContext().getCurrentUser().getId(); // datecreated = System.currentTimeMillis(); } // convert to xml page if wanted if (m_convertToXmlPage && (type.equals(RESOURCE_TYPE_NEWPAGE_NAME))) { if (content != null) { //get the encoding String encoding = null; encoding = CmsProperty.get(CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, properties).getValue(); if (encoding == null) { encoding = OpenCms.getSystemInfo().getDefaultEncoding(); } CmsXmlPage xmlPage = CmsXmlPageConverter.convertToXmlPage( m_cms, content, getLocale(destination, properties), encoding); content = xmlPage.marshal(); } resType = OpenCms.getResourceManager().getResourceType(CmsResourceTypeXmlPage.getStaticTypeId()); } else if (type.equals(RESOURCE_TYPE_LINK_NAME)) { resType = OpenCms.getResourceManager().getResourceType(CmsResourceTypePointer.getStaticTypeId()); } else if (type.equals(RESOURCE_TYPE_LEGACY_PAGE_NAME)) { resType = OpenCms.getResourceManager().getResourceType(CmsResourceTypePlain.getStaticTypeId()); } else { resType = OpenCms.getResourceManager().getResourceType(type); } // get UUIDs for the resource and content CmsUUID newUuidresource = null; if ((uuidresource != null) && (!resType.isFolder())) { // create a UUID from the provided string newUuidresource = new CmsUUID(uuidresource); } else { // folders get always a new resource record UUID newUuidresource = new CmsUUID(); } // create a new CmsResource CmsResource resource = new CmsResource( new CmsUUID(), // structure ID is always a new UUID newUuidresource, destination, resType.getTypeId(), resType.isFolder(), new Integer(flags).intValue(), m_cms.getRequestContext().getCurrentProject().getUuid(), CmsResource.STATE_NEW, datecreated, newUsercreated, datelastmodified, newUserlastmodified, CmsResource.DATE_RELEASED_DEFAULT, CmsResource.DATE_EXPIRED_DEFAULT, 1, size, System.currentTimeMillis(), 0); if (type.equals(RESOURCE_TYPE_LINK_NAME)) { // store links for later conversion m_report.print(Messages.get().container(Messages.RPT_STORING_LINK_0), I_CmsReport.FORMAT_NOTE); m_linkStorage.put(m_importPath + destination, new String(content)); m_linkPropertyStorage.put(m_importPath + destination, properties); result = resource; } else { // import this resource in the VFS result = m_cms.importResource(destination, resource, content, properties); } if (result != null) { m_report.println( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0), I_CmsReport.FORMAT_OK); } } catch (Exception exc) { // an error while importing the file m_report.println(exc); m_report.addError(exc); try { // Sleep some time after an error so that the report output has a chance to keep up Thread.sleep(1000); } catch (Exception e) { // } } return result; } }
public class class_name { private CmsResource importResource( String source, String destination, String type, String uuidresource, long datelastmodified, String userlastmodified, long datecreated, String usercreated, String flags, List<CmsProperty> properties) { byte[] content = null; CmsResource result = null; try { // get the file content if (source != null) { content = getFileBytes(source); // depends on control dependency: [if], data = [(source] } int size = 0; if (content != null) { size = content.length; // depends on control dependency: [if], data = [none] } // get all required information to create a CmsResource I_CmsResourceType resType; // get UUIDs for the user CmsUUID newUserlastmodified; CmsUUID newUsercreated; // check if user created and user lastmodified are valid users in this system. // if not, use the current user try { newUserlastmodified = m_cms.readUser(userlastmodified).getId(); // depends on control dependency: [try], data = [none] } catch (CmsException e) { newUserlastmodified = m_cms.getRequestContext().getCurrentUser().getId(); // datelastmodified = System.currentTimeMillis(); } // depends on control dependency: [catch], data = [none] try { newUsercreated = m_cms.readUser(usercreated).getId(); // depends on control dependency: [try], data = [none] } catch (CmsException e) { newUsercreated = m_cms.getRequestContext().getCurrentUser().getId(); // datecreated = System.currentTimeMillis(); } // depends on control dependency: [catch], data = [none] // convert to xml page if wanted if (m_convertToXmlPage && (type.equals(RESOURCE_TYPE_NEWPAGE_NAME))) { if (content != null) { //get the encoding String encoding = null; encoding = CmsProperty.get(CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, properties).getValue(); // depends on control dependency: [if], data = [none] if (encoding == null) { encoding = OpenCms.getSystemInfo().getDefaultEncoding(); // depends on control dependency: [if], data = [none] } CmsXmlPage xmlPage = CmsXmlPageConverter.convertToXmlPage( m_cms, content, getLocale(destination, properties), encoding); content = xmlPage.marshal(); // depends on control dependency: [if], data = [none] } resType = OpenCms.getResourceManager().getResourceType(CmsResourceTypeXmlPage.getStaticTypeId()); // depends on control dependency: [if], data = [none] } else if (type.equals(RESOURCE_TYPE_LINK_NAME)) { resType = OpenCms.getResourceManager().getResourceType(CmsResourceTypePointer.getStaticTypeId()); // depends on control dependency: [if], data = [none] } else if (type.equals(RESOURCE_TYPE_LEGACY_PAGE_NAME)) { resType = OpenCms.getResourceManager().getResourceType(CmsResourceTypePlain.getStaticTypeId()); // depends on control dependency: [if], data = [none] } else { resType = OpenCms.getResourceManager().getResourceType(type); // depends on control dependency: [if], data = [none] } // get UUIDs for the resource and content CmsUUID newUuidresource = null; if ((uuidresource != null) && (!resType.isFolder())) { // create a UUID from the provided string newUuidresource = new CmsUUID(uuidresource); // depends on control dependency: [if], data = [none] } else { // folders get always a new resource record UUID newUuidresource = new CmsUUID(); // depends on control dependency: [if], data = [none] } // create a new CmsResource CmsResource resource = new CmsResource( new CmsUUID(), // structure ID is always a new UUID newUuidresource, destination, resType.getTypeId(), resType.isFolder(), new Integer(flags).intValue(), m_cms.getRequestContext().getCurrentProject().getUuid(), CmsResource.STATE_NEW, datecreated, newUsercreated, datelastmodified, newUserlastmodified, CmsResource.DATE_RELEASED_DEFAULT, CmsResource.DATE_EXPIRED_DEFAULT, 1, size, System.currentTimeMillis(), 0); if (type.equals(RESOURCE_TYPE_LINK_NAME)) { // store links for later conversion m_report.print(Messages.get().container(Messages.RPT_STORING_LINK_0), I_CmsReport.FORMAT_NOTE); // depends on control dependency: [if], data = [none] m_linkStorage.put(m_importPath + destination, new String(content)); // depends on control dependency: [if], data = [none] m_linkPropertyStorage.put(m_importPath + destination, properties); // depends on control dependency: [if], data = [none] result = resource; // depends on control dependency: [if], data = [none] } else { // import this resource in the VFS result = m_cms.importResource(destination, resource, content, properties); // depends on control dependency: [if], data = [none] } if (result != null) { m_report.println( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0), I_CmsReport.FORMAT_OK); // depends on control dependency: [if], data = [none] } } catch (Exception exc) { // an error while importing the file m_report.println(exc); m_report.addError(exc); try { // Sleep some time after an error so that the report output has a chance to keep up Thread.sleep(1000); // depends on control dependency: [try], data = [none] } catch (Exception e) { // } // depends on control dependency: [catch], data = [none] } // depends on control dependency: [catch], data = [none] return result; } }
public class class_name { public static long parseBytes(String input, ConfigOrigin originForException, String pathForException) { String s = ConfigImplUtil.unicodeTrim(input); String unitString = getUnits(s); String numberString = ConfigImplUtil.unicodeTrim(s.substring(0, s.length() - unitString.length())); // this would be caught later anyway, but the error message // is more helpful if we check it here. if (numberString.length() == 0) throw new ConfigException.BadValue(originForException, pathForException, "No number in size-in-bytes value '" + input + "'"); MemoryUnit units = MemoryUnit.parseUnit(unitString); if (units == null) { throw new ConfigException.BadValue(originForException, pathForException, "Could not parse size-in-bytes unit '" + unitString + "' (try k, K, kB, KiB, kilobytes, kibibytes)"); } try { BigInteger result; // if the string is purely digits, parse as an integer to avoid // possible precision loss; otherwise as a double. if (numberString.matches("[0-9]+")) { result = units.bytes.multiply(new BigInteger(numberString)); } else { BigDecimal resultDecimal = (new BigDecimal(units.bytes)).multiply(new BigDecimal(numberString)); result = resultDecimal.toBigInteger(); } if (result.bitLength() < 64) return result.longValue(); else throw new ConfigException.BadValue(originForException, pathForException, "size-in-bytes value is out of range for a 64-bit long: '" + input + "'"); } catch (NumberFormatException e) { throw new ConfigException.BadValue(originForException, pathForException, "Could not parse size-in-bytes number '" + numberString + "'"); } } }
public class class_name { public static long parseBytes(String input, ConfigOrigin originForException, String pathForException) { String s = ConfigImplUtil.unicodeTrim(input); String unitString = getUnits(s); String numberString = ConfigImplUtil.unicodeTrim(s.substring(0, s.length() - unitString.length())); // this would be caught later anyway, but the error message // is more helpful if we check it here. if (numberString.length() == 0) throw new ConfigException.BadValue(originForException, pathForException, "No number in size-in-bytes value '" + input + "'"); MemoryUnit units = MemoryUnit.parseUnit(unitString); if (units == null) { throw new ConfigException.BadValue(originForException, pathForException, "Could not parse size-in-bytes unit '" + unitString + "' (try k, K, kB, KiB, kilobytes, kibibytes)"); } try { BigInteger result; // if the string is purely digits, parse as an integer to avoid // possible precision loss; otherwise as a double. if (numberString.matches("[0-9]+")) { result = units.bytes.multiply(new BigInteger(numberString)); // depends on control dependency: [if], data = [none] } else { BigDecimal resultDecimal = (new BigDecimal(units.bytes)).multiply(new BigDecimal(numberString)); result = resultDecimal.toBigInteger(); // depends on control dependency: [if], data = [none] } if (result.bitLength() < 64) return result.longValue(); else throw new ConfigException.BadValue(originForException, pathForException, "size-in-bytes value is out of range for a 64-bit long: '" + input + "'"); } catch (NumberFormatException e) { throw new ConfigException.BadValue(originForException, pathForException, "Could not parse size-in-bytes number '" + numberString + "'"); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public V remove(Object key) { if (key == null) { return null; } purgeBeforeWrite(); return super.remove(key); } }
public class class_name { public V remove(Object key) { if (key == null) { return null; // depends on control dependency: [if], data = [none] } purgeBeforeWrite(); return super.remove(key); } }
public class class_name { public static void toJson(Writer writer, Object obj, JsonFormat format) { try { if (format == null) format = deft; JsonRender jr; Class<? extends JsonRender> jrCls = getJsonRenderCls(); if (jrCls == null) jr = new JsonRenderImpl(); else jr = Mirror.me(jrCls).born(); jr.setWriter(writer); jr.setFormat(format); jr.render(obj); writer.flush(); } catch (IOException e) { throw Lang.wrapThrow(e, JsonException.class); } } }
public class class_name { public static void toJson(Writer writer, Object obj, JsonFormat format) { try { if (format == null) format = deft; JsonRender jr; Class<? extends JsonRender> jrCls = getJsonRenderCls(); if (jrCls == null) jr = new JsonRenderImpl(); else jr = Mirror.me(jrCls).born(); jr.setWriter(writer); // depends on control dependency: [try], data = [none] jr.setFormat(format); // depends on control dependency: [try], data = [none] jr.render(obj); // depends on control dependency: [try], data = [none] writer.flush(); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw Lang.wrapThrow(e, JsonException.class); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void close() { Collection<WriterPoolMember> writers = drainAllWriters(); for (WriterPoolMember writer: writers) { try { destroyWriter(writer); } catch (IOException e) { logger.log(Level.WARNING,"problem closing writer",e); } } } }
public class class_name { public void close() { Collection<WriterPoolMember> writers = drainAllWriters(); for (WriterPoolMember writer: writers) { try { destroyWriter(writer); // depends on control dependency: [try], data = [none] } catch (IOException e) { logger.log(Level.WARNING,"problem closing writer",e); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public boolean isFinal(Path path) { // Step through the nodes based on the given path. If any intermediate // nodes are marked as final, we can just return true. Node currentNode = root; for (Term t : path.getTerms()) { Node nextNode = currentNode.getChild(t); if (nextNode == null) { return false; } else if (nextNode.isFinal()) { return true; } currentNode = nextNode; } // If we've made it to here, then the current node is the one which // corresponds to the last element in the path. Return true if it is // marked as final or it has any descendants. return currentNode.isFinal() || currentNode.hasChild(); } }
public class class_name { public boolean isFinal(Path path) { // Step through the nodes based on the given path. If any intermediate // nodes are marked as final, we can just return true. Node currentNode = root; for (Term t : path.getTerms()) { Node nextNode = currentNode.getChild(t); if (nextNode == null) { return false; // depends on control dependency: [if], data = [none] } else if (nextNode.isFinal()) { return true; // depends on control dependency: [if], data = [none] } currentNode = nextNode; // depends on control dependency: [for], data = [t] } // If we've made it to here, then the current node is the one which // corresponds to the last element in the path. Return true if it is // marked as final or it has any descendants. return currentNode.isFinal() || currentNode.hasChild(); } }
public class class_name { NodeInfo selectSeedCorner() { NodeInfo best = null; double bestScore = 0; double minAngle = Math.PI+0.1; for (int i = 0; i < contour.size; i++) { NodeInfo info = contour.get(i); if( info.angleBetween < minAngle ) continue; Edge middleR = selectClosest(info.right,info,true); if( middleR == null ) continue; Edge middleL = selectClosest(info,info.left,true); if( middleL == null ) continue; if( middleL.target != middleR.target ) continue; // With no perspective distortion, at the correct corners difference should be zero // while the bad ones will be around 60 degrees double r = UtilAngle.bound( middleR.angle + Math.PI); double difference = UtilAngle.dist(r,middleL.angle); double score = info.angleBetween - difference; if( score > bestScore ) { best = info; bestScore = score; } } if( best != null ) { best.marked = true; } return best; } }
public class class_name { NodeInfo selectSeedCorner() { NodeInfo best = null; double bestScore = 0; double minAngle = Math.PI+0.1; for (int i = 0; i < contour.size; i++) { NodeInfo info = contour.get(i); if( info.angleBetween < minAngle ) continue; Edge middleR = selectClosest(info.right,info,true); if( middleR == null ) continue; Edge middleL = selectClosest(info,info.left,true); if( middleL == null ) continue; if( middleL.target != middleR.target ) continue; // With no perspective distortion, at the correct corners difference should be zero // while the bad ones will be around 60 degrees double r = UtilAngle.bound( middleR.angle + Math.PI); double difference = UtilAngle.dist(r,middleL.angle); double score = info.angleBetween - difference; if( score > bestScore ) { best = info; // depends on control dependency: [if], data = [none] bestScore = score; // depends on control dependency: [if], data = [none] } } if( best != null ) { best.marked = true; // depends on control dependency: [if], data = [none] } return best; } }
public class class_name { protected boolean validateSARLSpecificElements(IJavaProject javaProject) { // Check if the "SARL" generation directory is a source folder. final IPath outputPath = SARLPreferences.getSARLOutputPathFor(javaProject.getProject()); if (outputPath == null) { final String message = MessageFormat.format( Messages.BuildSettingWizardPage_0, SARLConfig.FOLDER_SOURCE_GENERATED); final IStatus status = SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR, message); handleFinishException(getShell(), new InvocationTargetException(new CoreException(status))); return false; } if (!hasSourcePath(javaProject, outputPath)) { final String message = MessageFormat.format( Messages.SARLProjectCreationWizard_0, toOSString(outputPath), buildInvalidOutputPathMessageFragment(javaProject)); final IStatus status = SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR, message); handleFinishException(getShell(), new InvocationTargetException(new CoreException(status))); return false; } return true; } }
public class class_name { protected boolean validateSARLSpecificElements(IJavaProject javaProject) { // Check if the "SARL" generation directory is a source folder. final IPath outputPath = SARLPreferences.getSARLOutputPathFor(javaProject.getProject()); if (outputPath == null) { final String message = MessageFormat.format( Messages.BuildSettingWizardPage_0, SARLConfig.FOLDER_SOURCE_GENERATED); final IStatus status = SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR, message); handleFinishException(getShell(), new InvocationTargetException(new CoreException(status))); // depends on control dependency: [if], data = [none] return false; // depends on control dependency: [if], data = [none] } if (!hasSourcePath(javaProject, outputPath)) { final String message = MessageFormat.format( Messages.SARLProjectCreationWizard_0, toOSString(outputPath), buildInvalidOutputPathMessageFragment(javaProject)); final IStatus status = SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR, message); handleFinishException(getShell(), new InvocationTargetException(new CoreException(status))); // depends on control dependency: [if], data = [none] return false; // depends on control dependency: [if], data = [none] } return true; } }
public class class_name { @SuppressWarnings("checkstyle:cyclomaticcomplexity") void updateSizes(int fieldLength, int decimalPointPosition) { switch (this.type) { case STRING: if (fieldLength > this.length) { this.length = fieldLength; } break; case FLOATING_NUMBER: case NUMBER: if (decimalPointPosition > this.decimal) { final int intPart = this.length - this.decimal; this.decimal = decimalPointPosition; this.length = intPart + this.decimal; } if (fieldLength > this.length) { this.length = fieldLength; } break; //$CASES-OMITTED$ default: // Do nothing } } }
public class class_name { @SuppressWarnings("checkstyle:cyclomaticcomplexity") void updateSizes(int fieldLength, int decimalPointPosition) { switch (this.type) { case STRING: if (fieldLength > this.length) { this.length = fieldLength; // depends on control dependency: [if], data = [none] } break; case FLOATING_NUMBER: case NUMBER: if (decimalPointPosition > this.decimal) { final int intPart = this.length - this.decimal; this.decimal = decimalPointPosition; // depends on control dependency: [if], data = [none] this.length = intPart + this.decimal; // depends on control dependency: [if], data = [none] } if (fieldLength > this.length) { this.length = fieldLength; // depends on control dependency: [if], data = [none] } break; //$CASES-OMITTED$ default: // Do nothing } } }
public class class_name { @Override public EClass getIfcZShapeProfileDef() { if (ifcZShapeProfileDefEClass == null) { ifcZShapeProfileDefEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(775); } return ifcZShapeProfileDefEClass; } }
public class class_name { @Override public EClass getIfcZShapeProfileDef() { if (ifcZShapeProfileDefEClass == null) { ifcZShapeProfileDefEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(775); // depends on control dependency: [if], data = [none] } return ifcZShapeProfileDefEClass; } }
public class class_name { protected Icon getSizingIcon(AbstractButton b) { // NOTE: this is slightly different than BasicButtonUI, where it // would just use getIcon, but this should be ok. Icon icon = (b.isEnabled() || b.getDisabledIcon() == null) ? b.getIcon() : b.getDisabledIcon(); if (icon == null) { icon = getDefaultIcon(b); } return icon; } }
public class class_name { protected Icon getSizingIcon(AbstractButton b) { // NOTE: this is slightly different than BasicButtonUI, where it // would just use getIcon, but this should be ok. Icon icon = (b.isEnabled() || b.getDisabledIcon() == null) ? b.getIcon() : b.getDisabledIcon(); if (icon == null) { icon = getDefaultIcon(b); // depends on control dependency: [if], data = [none] } return icon; } }
public class class_name { @Override public int compareTo(ValueArray<IntValue> o) { IntValueArray other = (IntValueArray) o; int min = Math.min(position, other.position); for (int i = 0; i < min; i++) { int cmp = Integer.compare(data[i], other.data[i]); if (cmp != 0) { return cmp; } } return Integer.compare(position, other.position); } }
public class class_name { @Override public int compareTo(ValueArray<IntValue> o) { IntValueArray other = (IntValueArray) o; int min = Math.min(position, other.position); for (int i = 0; i < min; i++) { int cmp = Integer.compare(data[i], other.data[i]); if (cmp != 0) { return cmp; // depends on control dependency: [if], data = [none] } } return Integer.compare(position, other.position); } }
public class class_name { private void notifyConnected(Peer peer) { for(Listener listener : new HashSet<>(listeners)) { listener.onConnected(peer); } } }
public class class_name { private void notifyConnected(Peer peer) { for(Listener listener : new HashSet<>(listeners)) { listener.onConnected(peer); // depends on control dependency: [for], data = [listener] } } }
public class class_name { public void notifyAdapterItemRangeChanged(int position, int itemCount, @Nullable Object payload) { // handle our extensions for (IAdapterExtension<Item> ext : mExtensions.values()) { ext.notifyAdapterItemRangeChanged(position, itemCount, payload); } if (payload == null) { notifyItemRangeChanged(position, itemCount); } else { notifyItemRangeChanged(position, itemCount, payload); } } }
public class class_name { public void notifyAdapterItemRangeChanged(int position, int itemCount, @Nullable Object payload) { // handle our extensions for (IAdapterExtension<Item> ext : mExtensions.values()) { ext.notifyAdapterItemRangeChanged(position, itemCount, payload); // depends on control dependency: [for], data = [ext] } if (payload == null) { notifyItemRangeChanged(position, itemCount); // depends on control dependency: [if], data = [none] } else { notifyItemRangeChanged(position, itemCount, payload); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public boolean cancel(final String appName, final String id, final boolean isReplication) { if (super.cancel(appName, id, isReplication)) { replicateToPeers(Action.Cancel, appName, id, null, null, isReplication); synchronized (lock) { if (this.expectedNumberOfClientsSendingRenews > 0) { // Since the client wants to cancel it, reduce the number of clients to send renews this.expectedNumberOfClientsSendingRenews = this.expectedNumberOfClientsSendingRenews - 1; updateRenewsPerMinThreshold(); } } return true; } return false; } }
public class class_name { @Override public boolean cancel(final String appName, final String id, final boolean isReplication) { if (super.cancel(appName, id, isReplication)) { replicateToPeers(Action.Cancel, appName, id, null, null, isReplication); // depends on control dependency: [if], data = [none] synchronized (lock) { // depends on control dependency: [if], data = [none] if (this.expectedNumberOfClientsSendingRenews > 0) { // Since the client wants to cancel it, reduce the number of clients to send renews this.expectedNumberOfClientsSendingRenews = this.expectedNumberOfClientsSendingRenews - 1; // depends on control dependency: [if], data = [none] updateRenewsPerMinThreshold(); // depends on control dependency: [if], data = [none] } } return true; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { public void removeKeyword(String keyword) { if (!taxonomy.concepts.containsKey(keyword)) { throw new IllegalArgumentException(String.format("Concept %s does not exist.", keyword)); } taxonomy.concepts.remove(keyword); if (synset != null) { synset.remove(keyword); } } }
public class class_name { public void removeKeyword(String keyword) { if (!taxonomy.concepts.containsKey(keyword)) { throw new IllegalArgumentException(String.format("Concept %s does not exist.", keyword)); } taxonomy.concepts.remove(keyword); if (synset != null) { synset.remove(keyword); // depends on control dependency: [if], data = [none] } } }
public class class_name { protected void mergeRelationship(final Map<SpecNode, CSNodeWrapper> nodeMapping, final SpecNodeWithRelationships specNode, final CSNodeWrapper entity, final CSNodeProvider nodeProvider) { final UpdateableCollectionWrapper<CSRelatedNodeWrapper> relatedToNodes = entity.getRelatedToNodes() == null ? nodeProvider .newCSRelatedNodeCollection() : entity.getRelatedToNodes(); final List<CSRelatedNodeWrapper> existingRelationships = new ArrayList<CSRelatedNodeWrapper>(relatedToNodes.getItems()); LOG.debug("Processing relationships for entity: {}", entity.getEntityId()); // Check to make sure that the spec topic has any relationships if (!specNode.getRelationships().isEmpty()) { int relationshipSortCount = 1; for (final Relationship relationship : specNode.getRelationships()) { // All process relationships should not be stored if (relationship instanceof ProcessRelationship) continue; LOG.debug("Processing Relationship: {}", relationship.getSecondaryRelationshipId()); // Determine the relationship mode final Integer relationshipMode; if (relationship instanceof TargetRelationship) { relationshipMode = CommonConstants.CS_RELATIONSHIP_MODE_TARGET; } else { relationshipMode = CommonConstants.CS_RELATIONSHIP_MODE_ID; } // See if the related node already exists CSRelatedNodeWrapper foundRelatedNode = findExistingRelatedNode(relationship, existingRelationships); if (foundRelatedNode != null) { LOG.debug("Found existing related node {}", foundRelatedNode.getRelationshipId()); // Remove the related node from the list of existing nodes existingRelationships.remove(foundRelatedNode); // Found a node so update anything that might have changed boolean updated = false; if (foundRelatedNode.getRelationshipSort() != relationshipSortCount) { foundRelatedNode.setRelationshipSort(relationshipSortCount); updated = true; } // Make sure the modes still match if (!relationshipMode.equals(foundRelatedNode.getRelationshipMode())) { foundRelatedNode.setRelationshipMode(relationshipMode); updated = true; } // If the node was updated, set it's state in the collection to updated, otherwise just put it back in normally. if (updated) { relatedToNodes.remove(foundRelatedNode); relatedToNodes.addUpdateItem(foundRelatedNode); } } else { LOG.debug("Creating new relationship"); // No related node was found for the relationship so make a new one. final CSNodeWrapper relatedNode; if (relationship instanceof TargetRelationship) { relatedNode = nodeMapping.get(((TargetRelationship) relationship).getSecondaryRelationship()); } else { relatedNode = nodeMapping.get(((TopicRelationship) relationship).getSecondaryRelationship()); } foundRelatedNode = nodeProvider.newCSRelatedNode(relatedNode); foundRelatedNode.setRelationshipType(RelationshipType.getRelationshipTypeId(relationship.getType())); foundRelatedNode.setRelationshipSort(relationshipSortCount); foundRelatedNode.setRelationshipMode(relationshipMode); relatedToNodes.addNewItem(foundRelatedNode); } // increment the sort counter relationshipSortCount++; } } // Remove any existing relationships that are no longer valid if (!existingRelationships.isEmpty()) { for (final CSRelatedNodeWrapper relatedNode : existingRelationships) { LOG.debug("Removing relationship {}", relatedNode.getRelationshipId()); relatedToNodes.remove(relatedNode); relatedToNodes.addRemoveItem(relatedNode); } } // Check if anything was changed, if so then set the changes if (!relatedToNodes.getAddItems().isEmpty() || !relatedToNodes.getUpdateItems().isEmpty() || !relatedToNodes.getRemoveItems() .isEmpty()) { entity.setRelatedToNodes(relatedToNodes); // Make sure the node is in the updated state if (entity.getParent() == null) { entity.getContentSpec().getChildren().remove(entity); if (entity.getId() == null) { entity.getContentSpec().getChildren().addNewItem(entity); } else { entity.getContentSpec().getChildren().addUpdateItem(entity); } } else { final CSNodeWrapper parent = entity.getParent(); parent.getChildren().remove(entity); if (entity.getId() == null) { parent.getChildren().addNewItem(entity); } else { parent.getChildren().addUpdateItem(entity); } } } } }
public class class_name { protected void mergeRelationship(final Map<SpecNode, CSNodeWrapper> nodeMapping, final SpecNodeWithRelationships specNode, final CSNodeWrapper entity, final CSNodeProvider nodeProvider) { final UpdateableCollectionWrapper<CSRelatedNodeWrapper> relatedToNodes = entity.getRelatedToNodes() == null ? nodeProvider .newCSRelatedNodeCollection() : entity.getRelatedToNodes(); final List<CSRelatedNodeWrapper> existingRelationships = new ArrayList<CSRelatedNodeWrapper>(relatedToNodes.getItems()); LOG.debug("Processing relationships for entity: {}", entity.getEntityId()); // Check to make sure that the spec topic has any relationships if (!specNode.getRelationships().isEmpty()) { int relationshipSortCount = 1; for (final Relationship relationship : specNode.getRelationships()) { // All process relationships should not be stored if (relationship instanceof ProcessRelationship) continue; LOG.debug("Processing Relationship: {}", relationship.getSecondaryRelationshipId()); // depends on control dependency: [for], data = [relationship] // Determine the relationship mode final Integer relationshipMode; if (relationship instanceof TargetRelationship) { relationshipMode = CommonConstants.CS_RELATIONSHIP_MODE_TARGET; // depends on control dependency: [if], data = [none] } else { relationshipMode = CommonConstants.CS_RELATIONSHIP_MODE_ID; // depends on control dependency: [if], data = [none] } // See if the related node already exists CSRelatedNodeWrapper foundRelatedNode = findExistingRelatedNode(relationship, existingRelationships); if (foundRelatedNode != null) { LOG.debug("Found existing related node {}", foundRelatedNode.getRelationshipId()); // depends on control dependency: [if], data = [none] // Remove the related node from the list of existing nodes existingRelationships.remove(foundRelatedNode); // depends on control dependency: [if], data = [(foundRelatedNode] // Found a node so update anything that might have changed boolean updated = false; if (foundRelatedNode.getRelationshipSort() != relationshipSortCount) { foundRelatedNode.setRelationshipSort(relationshipSortCount); // depends on control dependency: [if], data = [relationshipSortCount)] updated = true; // depends on control dependency: [if], data = [none] } // Make sure the modes still match if (!relationshipMode.equals(foundRelatedNode.getRelationshipMode())) { foundRelatedNode.setRelationshipMode(relationshipMode); // depends on control dependency: [if], data = [none] updated = true; // depends on control dependency: [if], data = [none] } // If the node was updated, set it's state in the collection to updated, otherwise just put it back in normally. if (updated) { relatedToNodes.remove(foundRelatedNode); // depends on control dependency: [if], data = [none] relatedToNodes.addUpdateItem(foundRelatedNode); // depends on control dependency: [if], data = [none] } } else { LOG.debug("Creating new relationship"); // depends on control dependency: [if], data = [none] // No related node was found for the relationship so make a new one. final CSNodeWrapper relatedNode; if (relationship instanceof TargetRelationship) { relatedNode = nodeMapping.get(((TargetRelationship) relationship).getSecondaryRelationship()); // depends on control dependency: [if], data = [none] } else { relatedNode = nodeMapping.get(((TopicRelationship) relationship).getSecondaryRelationship()); // depends on control dependency: [if], data = [none] } foundRelatedNode = nodeProvider.newCSRelatedNode(relatedNode); // depends on control dependency: [if], data = [none] foundRelatedNode.setRelationshipType(RelationshipType.getRelationshipTypeId(relationship.getType())); // depends on control dependency: [if], data = [none] foundRelatedNode.setRelationshipSort(relationshipSortCount); // depends on control dependency: [if], data = [none] foundRelatedNode.setRelationshipMode(relationshipMode); // depends on control dependency: [if], data = [none] relatedToNodes.addNewItem(foundRelatedNode); // depends on control dependency: [if], data = [(foundRelatedNode] } // increment the sort counter relationshipSortCount++; // depends on control dependency: [for], data = [relationship] } } // Remove any existing relationships that are no longer valid if (!existingRelationships.isEmpty()) { for (final CSRelatedNodeWrapper relatedNode : existingRelationships) { LOG.debug("Removing relationship {}", relatedNode.getRelationshipId()); // depends on control dependency: [for], data = [relatedNode] relatedToNodes.remove(relatedNode); // depends on control dependency: [for], data = [relatedNode] relatedToNodes.addRemoveItem(relatedNode); // depends on control dependency: [for], data = [relatedNode] } } // Check if anything was changed, if so then set the changes if (!relatedToNodes.getAddItems().isEmpty() || !relatedToNodes.getUpdateItems().isEmpty() || !relatedToNodes.getRemoveItems() .isEmpty()) { entity.setRelatedToNodes(relatedToNodes); // depends on control dependency: [if], data = [none] // Make sure the node is in the updated state if (entity.getParent() == null) { entity.getContentSpec().getChildren().remove(entity); // depends on control dependency: [if], data = [none] if (entity.getId() == null) { entity.getContentSpec().getChildren().addNewItem(entity); // depends on control dependency: [if], data = [none] } else { entity.getContentSpec().getChildren().addUpdateItem(entity); // depends on control dependency: [if], data = [none] } } else { final CSNodeWrapper parent = entity.getParent(); parent.getChildren().remove(entity); // depends on control dependency: [if], data = [none] if (entity.getId() == null) { parent.getChildren().addNewItem(entity); // depends on control dependency: [if], data = [none] } else { parent.getChildren().addUpdateItem(entity); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { @FFDCIgnore(IllegalStateException.class) private void removeShutdownHook() { if (shutdownHook != null) { try { Runtime.getRuntime().removeShutdownHook(shutdownHook); } catch (IllegalStateException e) { // do nothing. } } } }
public class class_name { @FFDCIgnore(IllegalStateException.class) private void removeShutdownHook() { if (shutdownHook != null) { try { Runtime.getRuntime().removeShutdownHook(shutdownHook); // depends on control dependency: [try], data = [none] } catch (IllegalStateException e) { // do nothing. } // depends on control dependency: [catch], data = [none] } } }
public class class_name { @Override public List<DMNStyle> getDMNStyle() { if (dmnStyle == null) { dmnStyle = new ArrayList<DMNStyle>(); } return this.dmnStyle; } }
public class class_name { @Override public List<DMNStyle> getDMNStyle() { if (dmnStyle == null) { dmnStyle = new ArrayList<DMNStyle>(); // depends on control dependency: [if], data = [none] } return this.dmnStyle; } }
public class class_name { @Override public String filter(URL pageUrl, Metadata sourceMetadata, String url) { for (RegexRule rule : rules) { if (rule.match(url)) { return rule.accept() ? url : null; } } return null; } }
public class class_name { @Override public String filter(URL pageUrl, Metadata sourceMetadata, String url) { for (RegexRule rule : rules) { if (rule.match(url)) { return rule.accept() ? url : null; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public AspFactory createAspFactory(String aspName, String associationName, long aspid, boolean isHeartBeatEnabled) throws Exception { AspFactoryImpl factory = this.getAspFactory(aspName); if (factory != null) { throw new Exception(String.format(M3UAOAMMessages.CREATE_ASP_FAIL_NAME_EXIST, aspName)); } Association association = this.transportManagement.getAssociation(associationName); if (association == null) { throw new Exception(String.format(M3UAOAMMessages.NO_ASSOCIATION_FOUND, associationName)); } if (association.isStarted()) { throw new Exception(String.format(M3UAOAMMessages.ASSOCIATION_IS_STARTED, associationName)); } if (association.getAssociationListener() != null) { throw new Exception(String.format(M3UAOAMMessages.ASSOCIATION_IS_ASSOCIATED, associationName)); } for (FastList.Node<AspFactory> n = aspfactories.head(), end = aspfactories.tail(); (n = n.getNext()) != end;) { AspFactoryImpl aspFactoryImpl = (AspFactoryImpl) n.getValue(); if (aspid == aspFactoryImpl.getAspid().getAspId()) { throw new Exception(String.format(M3UAOAMMessages.ASP_ID_TAKEN, aspid)); } } factory = new AspFactoryImpl(aspName, this.getMaxSequenceNumber(), aspid, isHeartBeatEnabled); factory.setM3UAManagement(this); factory.setAssociation(association); factory.setTransportManagement(this.transportManagement); aspfactories.add(factory); this.store(); for (FastList.Node<M3UAManagementEventListener> n = this.managementEventListeners.head(), end = this.managementEventListeners .tail(); (n = n.getNext()) != end;) { M3UAManagementEventListener m3uaManagementEventListener = n.getValue(); try { m3uaManagementEventListener.onAspFactoryCreated(factory); } catch (Throwable ee) { logger.error("Exception while invoking onAspFactoryCreated", ee); } } return factory; } }
public class class_name { public AspFactory createAspFactory(String aspName, String associationName, long aspid, boolean isHeartBeatEnabled) throws Exception { AspFactoryImpl factory = this.getAspFactory(aspName); if (factory != null) { throw new Exception(String.format(M3UAOAMMessages.CREATE_ASP_FAIL_NAME_EXIST, aspName)); } Association association = this.transportManagement.getAssociation(associationName); if (association == null) { throw new Exception(String.format(M3UAOAMMessages.NO_ASSOCIATION_FOUND, associationName)); } if (association.isStarted()) { throw new Exception(String.format(M3UAOAMMessages.ASSOCIATION_IS_STARTED, associationName)); } if (association.getAssociationListener() != null) { throw new Exception(String.format(M3UAOAMMessages.ASSOCIATION_IS_ASSOCIATED, associationName)); } for (FastList.Node<AspFactory> n = aspfactories.head(), end = aspfactories.tail(); (n = n.getNext()) != end;) { AspFactoryImpl aspFactoryImpl = (AspFactoryImpl) n.getValue(); if (aspid == aspFactoryImpl.getAspid().getAspId()) { throw new Exception(String.format(M3UAOAMMessages.ASP_ID_TAKEN, aspid)); } } factory = new AspFactoryImpl(aspName, this.getMaxSequenceNumber(), aspid, isHeartBeatEnabled); factory.setM3UAManagement(this); factory.setAssociation(association); factory.setTransportManagement(this.transportManagement); aspfactories.add(factory); this.store(); for (FastList.Node<M3UAManagementEventListener> n = this.managementEventListeners.head(), end = this.managementEventListeners .tail(); (n = n.getNext()) != end;) { M3UAManagementEventListener m3uaManagementEventListener = n.getValue(); try { m3uaManagementEventListener.onAspFactoryCreated(factory); // depends on control dependency: [try], data = [none] } catch (Throwable ee) { logger.error("Exception while invoking onAspFactoryCreated", ee); } // depends on control dependency: [catch], data = [none] } return factory; } }
public class class_name { @SuppressWarnings("unchecked") private <IN1, IN2, OUT> TypeInformation<OUT> createTypeInfoFromFactory( Type t, ArrayList<Type> typeHierarchy, TypeInformation<IN1> in1Type, TypeInformation<IN2> in2Type) { final ArrayList<Type> factoryHierarchy = new ArrayList<>(typeHierarchy); final TypeInfoFactory<? super OUT> factory = getClosestFactory(factoryHierarchy, t); if (factory == null) { return null; } final Type factoryDefiningType = factoryHierarchy.get(factoryHierarchy.size() - 1); // infer possible type parameters from input final Map<String, TypeInformation<?>> genericParams; if (factoryDefiningType instanceof ParameterizedType) { genericParams = new HashMap<>(); final ParameterizedType paramDefiningType = (ParameterizedType) factoryDefiningType; final Type[] args = typeToClass(paramDefiningType).getTypeParameters(); final TypeInformation<?>[] subtypeInfo = createSubTypesInfo(t, paramDefiningType, factoryHierarchy, in1Type, in2Type, true); assert subtypeInfo != null; for (int i = 0; i < subtypeInfo.length; i++) { genericParams.put(args[i].toString(), subtypeInfo[i]); } } else { genericParams = Collections.emptyMap(); } final TypeInformation<OUT> createdTypeInfo = (TypeInformation<OUT>) factory.createTypeInfo(t, genericParams); if (createdTypeInfo == null) { throw new InvalidTypesException("TypeInfoFactory returned invalid TypeInformation 'null'"); } return createdTypeInfo; } }
public class class_name { @SuppressWarnings("unchecked") private <IN1, IN2, OUT> TypeInformation<OUT> createTypeInfoFromFactory( Type t, ArrayList<Type> typeHierarchy, TypeInformation<IN1> in1Type, TypeInformation<IN2> in2Type) { final ArrayList<Type> factoryHierarchy = new ArrayList<>(typeHierarchy); final TypeInfoFactory<? super OUT> factory = getClosestFactory(factoryHierarchy, t); if (factory == null) { return null; // depends on control dependency: [if], data = [none] } final Type factoryDefiningType = factoryHierarchy.get(factoryHierarchy.size() - 1); // infer possible type parameters from input final Map<String, TypeInformation<?>> genericParams; if (factoryDefiningType instanceof ParameterizedType) { genericParams = new HashMap<>(); // depends on control dependency: [if], data = [none] final ParameterizedType paramDefiningType = (ParameterizedType) factoryDefiningType; final Type[] args = typeToClass(paramDefiningType).getTypeParameters(); final TypeInformation<?>[] subtypeInfo = createSubTypesInfo(t, paramDefiningType, factoryHierarchy, in1Type, in2Type, true); assert subtypeInfo != null; for (int i = 0; i < subtypeInfo.length; i++) { genericParams.put(args[i].toString(), subtypeInfo[i]); // depends on control dependency: [for], data = [i] } } else { genericParams = Collections.emptyMap(); // depends on control dependency: [if], data = [none] } final TypeInformation<OUT> createdTypeInfo = (TypeInformation<OUT>) factory.createTypeInfo(t, genericParams); if (createdTypeInfo == null) { throw new InvalidTypesException("TypeInfoFactory returned invalid TypeInformation 'null'"); } return createdTypeInfo; } }
public class class_name { public void clientResolved (Name username, ClientObject clobj) { // we'll be keeping this bad boy _clobj = clobj; // if our connection was closed while we were resolving our client object, then just // abandon ship if (getConnection() == null) { log.info("Session ended before client object could be resolved " + this + "."); endSession(); return; } // Dump our secret into the client local for easy access clobj.getLocal(ClientLocal.class).secret = getSecret(); // finish up our regular business sessionWillStart(); sendBootstrap(); // let the client manager know that we're operational _clmgr.clientSessionDidStart(this); } }
public class class_name { public void clientResolved (Name username, ClientObject clobj) { // we'll be keeping this bad boy _clobj = clobj; // if our connection was closed while we were resolving our client object, then just // abandon ship if (getConnection() == null) { log.info("Session ended before client object could be resolved " + this + "."); // depends on control dependency: [if], data = [none] endSession(); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } // Dump our secret into the client local for easy access clobj.getLocal(ClientLocal.class).secret = getSecret(); // finish up our regular business sessionWillStart(); sendBootstrap(); // let the client manager know that we're operational _clmgr.clientSessionDidStart(this); } }
public class class_name { private boolean checkFilePath(String file, int depth) { // The file is either a node file or an edge file and needs to be stored at either: // flowGraphDir/nodeName/nodeName.properties (if it is a node file), or // flowGraphDir/nodeName/nodeName/edgeName.properties (if it is an edge file) Path filePath = new Path(file); String fileExtension = Files.getFileExtension(filePath.getName()); if (filePath.depth() != depth || !checkFileLevelRelativeToRoot(filePath, depth) || !(this.javaPropsExtensions.contains(fileExtension))) { log.warn("Changed file does not conform to directory structure and file name format, skipping: " + filePath); return false; } return true; } }
public class class_name { private boolean checkFilePath(String file, int depth) { // The file is either a node file or an edge file and needs to be stored at either: // flowGraphDir/nodeName/nodeName.properties (if it is a node file), or // flowGraphDir/nodeName/nodeName/edgeName.properties (if it is an edge file) Path filePath = new Path(file); String fileExtension = Files.getFileExtension(filePath.getName()); if (filePath.depth() != depth || !checkFileLevelRelativeToRoot(filePath, depth) || !(this.javaPropsExtensions.contains(fileExtension))) { log.warn("Changed file does not conform to directory structure and file name format, skipping: " + filePath); // depends on control dependency: [if], data = [none] return false; // depends on control dependency: [if], data = [none] } return true; } }
public class class_name { ServerSessionContext setKeepAliveIndex(long keepAliveIndex) { long previousKeepAliveIndex = this.keepAliveIndex; this.keepAliveIndex = keepAliveIndex; if (previousKeepAliveIndex > 0) { log.release(previousKeepAliveIndex); } return this; } }
public class class_name { ServerSessionContext setKeepAliveIndex(long keepAliveIndex) { long previousKeepAliveIndex = this.keepAliveIndex; this.keepAliveIndex = keepAliveIndex; if (previousKeepAliveIndex > 0) { log.release(previousKeepAliveIndex); // depends on control dependency: [if], data = [(previousKeepAliveIndex] } return this; } }
public class class_name { @Override public EClass getIfcReinforcingElementType() { if (ifcReinforcingElementTypeEClass == null) { ifcReinforcingElementTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(514); } return ifcReinforcingElementTypeEClass; } }
public class class_name { @Override public EClass getIfcReinforcingElementType() { if (ifcReinforcingElementTypeEClass == null) { ifcReinforcingElementTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(514); // depends on control dependency: [if], data = [none] } return ifcReinforcingElementTypeEClass; } }
public class class_name { public List<IfClassNotAvailable<Exclude<T>>> getAllIfClassNotAvailable() { List<IfClassNotAvailable<Exclude<T>>> list = new ArrayList<IfClassNotAvailable<Exclude<T>>>(); List<Node> nodeList = childNode.get("if-class-not-available"); for(Node node: nodeList) { IfClassNotAvailable<Exclude<T>> type = new IfClassNotAvailableImpl<Exclude<T>>(this, "if-class-not-available", childNode, node); list.add(type); } return list; } }
public class class_name { public List<IfClassNotAvailable<Exclude<T>>> getAllIfClassNotAvailable() { List<IfClassNotAvailable<Exclude<T>>> list = new ArrayList<IfClassNotAvailable<Exclude<T>>>(); List<Node> nodeList = childNode.get("if-class-not-available"); for(Node node: nodeList) { IfClassNotAvailable<Exclude<T>> type = new IfClassNotAvailableImpl<Exclude<T>>(this, "if-class-not-available", childNode, node); list.add(type); // depends on control dependency: [for], data = [none] } return list; } }