code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public static StepExecutionResult wrapDispatcherResult(final DispatcherResult dispatcherResult) { final StepExecutionResultImpl result; if(dispatcherResult.isSuccess()) { result = NodeDispatchStepExecutorResult.success(dispatcherResult); }else{ result = NodeDispatchStepExecutorResult.failure(dispatcherResult, null, Reason.NodeDispatchFailure, "Node dispatch failed"); //extract failed nodes ArrayList<String> nodeNames = new ArrayList<>(); for (String nodeName : dispatcherResult.getResults().keySet()) { NodeStepResult nodeStepResult = dispatcherResult.getResults().get(nodeName); if(!nodeStepResult.isSuccess()) { nodeNames.add(nodeName); } } if(!nodeNames.isEmpty()){ result.getFailureData().put(FAILURE_DATA_FAILED_NODES, StringUtils.join(nodeNames, ",")); } } return result; } }
public class class_name { public static StepExecutionResult wrapDispatcherResult(final DispatcherResult dispatcherResult) { final StepExecutionResultImpl result; if(dispatcherResult.isSuccess()) { result = NodeDispatchStepExecutorResult.success(dispatcherResult); // depends on control dependency: [if], data = [none] }else{ result = NodeDispatchStepExecutorResult.failure(dispatcherResult, null, Reason.NodeDispatchFailure, "Node dispatch failed"); // depends on control dependency: [if], data = [none] //extract failed nodes ArrayList<String> nodeNames = new ArrayList<>(); for (String nodeName : dispatcherResult.getResults().keySet()) { NodeStepResult nodeStepResult = dispatcherResult.getResults().get(nodeName); if(!nodeStepResult.isSuccess()) { nodeNames.add(nodeName); // depends on control dependency: [if], data = [none] } } if(!nodeNames.isEmpty()){ result.getFailureData().put(FAILURE_DATA_FAILED_NODES, StringUtils.join(nodeNames, ",")); // depends on control dependency: [if], data = [none] } } return result; } }
public class class_name { public void setRootDirectory(String cacheDir) { if (!cacheDir.endsWith("/")) cacheDir = cacheDir + "/"; root = StringUtil2.replace(cacheDir, '\\', "/"); // no nasty backslash File dir = new File(root); if (!dir.mkdirs()) { // ok } if (!dir.exists()) { fail = true; cacheLog.error("DiskCache2 failed to create directory "+root); } else { cacheLog.debug("DiskCache2 create directory "+root); } } }
public class class_name { public void setRootDirectory(String cacheDir) { if (!cacheDir.endsWith("/")) cacheDir = cacheDir + "/"; root = StringUtil2.replace(cacheDir, '\\', "/"); // no nasty backslash File dir = new File(root); if (!dir.mkdirs()) { // ok } if (!dir.exists()) { fail = true; // depends on control dependency: [if], data = [none] cacheLog.error("DiskCache2 failed to create directory "+root); // depends on control dependency: [if], data = [none] } else { cacheLog.debug("DiskCache2 create directory "+root); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static Locale deriveLocale(String str) { if (str == null) { return null; } int len = str.length(); if (len != 2 && len != 5 && len < 7) { return null; } char ch0 = str.charAt(0); char ch1 = str.charAt(1); if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') { return null; } if (len == 2) { return new Locale(str, ""); } else { if (str.charAt(2) != '_') { return null; } char ch3 = str.charAt(3); if (ch3 == '_') { return new Locale(str.substring(0, 2), "", str.substring(4)); } char ch4 = str.charAt(4); if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') { return null; } if (len == 5) { return new Locale(str.substring(0, 2), str.substring(3, 5)); } else { if (str.charAt(5) != '_') { return null; } return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6)); } } } }
public class class_name { public static Locale deriveLocale(String str) { if (str == null) { return null; // depends on control dependency: [if], data = [none] } int len = str.length(); if (len != 2 && len != 5 && len < 7) { return null; // depends on control dependency: [if], data = [none] } char ch0 = str.charAt(0); char ch1 = str.charAt(1); if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') { return null; // depends on control dependency: [if], data = [none] } if (len == 2) { return new Locale(str, ""); // depends on control dependency: [if], data = [none] } else { if (str.charAt(2) != '_') { return null; // depends on control dependency: [if], data = [none] } char ch3 = str.charAt(3); if (ch3 == '_') { return new Locale(str.substring(0, 2), "", str.substring(4)); // depends on control dependency: [if], data = [none] } char ch4 = str.charAt(4); if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') { return null; // depends on control dependency: [if], data = [none] } if (len == 5) { return new Locale(str.substring(0, 2), str.substring(3, 5)); // depends on control dependency: [if], data = [5)] } else { if (str.charAt(5) != '_') { return null; // depends on control dependency: [if], data = [none] } return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6)); // depends on control dependency: [if], data = [5)] } } } }
public class class_name { private Frame reBalance(final Frame fr, boolean local) { int chunks = (int)Math.min( 4 * H2O.NUMCPUS * (local ? 1 : H2O.CLOUD.size()), fr.numRows()); if (fr.anyVec().nChunks() > chunks && !reproducible) { Log.info("Dataset already contains " + fr.anyVec().nChunks() + " chunks. No need to rebalance."); return fr; } else if (reproducible) { Log.warn("Reproducibility enforced - using only 1 thread - can be slow."); chunks = 1; } if (!quiet_mode) Log.info("ReBalancing dataset into (at least) " + chunks + " chunks."); // return MRUtils.shuffleAndBalance(fr, chunks, seed, local, shuffle_training_data); String snewKey = fr._key != null ? (fr._key.toString() + ".balanced") : Key.rand(); Key newKey = Key.makeSystem(snewKey); RebalanceDataSet rb = new RebalanceDataSet(fr, newKey, chunks); H2O.submitTask(rb); rb.join(); return UKV.get(newKey); } }
public class class_name { private Frame reBalance(final Frame fr, boolean local) { int chunks = (int)Math.min( 4 * H2O.NUMCPUS * (local ? 1 : H2O.CLOUD.size()), fr.numRows()); if (fr.anyVec().nChunks() > chunks && !reproducible) { Log.info("Dataset already contains " + fr.anyVec().nChunks() + " chunks. No need to rebalance."); // depends on control dependency: [if], data = [none] return fr; // depends on control dependency: [if], data = [none] } else if (reproducible) { Log.warn("Reproducibility enforced - using only 1 thread - can be slow."); // depends on control dependency: [if], data = [none] chunks = 1; // depends on control dependency: [if], data = [none] } if (!quiet_mode) Log.info("ReBalancing dataset into (at least) " + chunks + " chunks."); // return MRUtils.shuffleAndBalance(fr, chunks, seed, local, shuffle_training_data); String snewKey = fr._key != null ? (fr._key.toString() + ".balanced") : Key.rand(); Key newKey = Key.makeSystem(snewKey); RebalanceDataSet rb = new RebalanceDataSet(fr, newKey, chunks); H2O.submitTask(rb); rb.join(); return UKV.get(newKey); } }
public class class_name { @Override public BigInteger convert(String value) { try { return (this.radix == null ? new BigInteger(String.valueOf(value).trim()) : new BigInteger(String.valueOf(value).trim(), this.radix)); } catch (NumberFormatException cause) { throw newConversionException(cause, "[%s] is not a valid BigInteger", value); } } }
public class class_name { @Override public BigInteger convert(String value) { try { return (this.radix == null ? new BigInteger(String.valueOf(value).trim()) : new BigInteger(String.valueOf(value).trim(), this.radix)); // depends on control dependency: [try], data = [none] } catch (NumberFormatException cause) { throw newConversionException(cause, "[%s] is not a valid BigInteger", value); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void marshall(ResumeSessionRequest resumeSessionRequest, ProtocolMarshaller protocolMarshaller) { if (resumeSessionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(resumeSessionRequest.getSessionId(), SESSIONID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ResumeSessionRequest resumeSessionRequest, ProtocolMarshaller protocolMarshaller) { if (resumeSessionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(resumeSessionRequest.getSessionId(), SESSIONID_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 void storeConcept(String tableVersion, String parameterNumber, String key, String value) { HashMap<String, HashMap<String, String>> tmpTable; if (localConcepts.containsKey(tableVersion)) { tmpTable = localConcepts.get(tableVersion); if (tmpTable.containsKey(parameterNumber)) { HashMap<String, String> tmpParam = tmpTable.get(parameterNumber); if (!tmpParam.containsKey(key)) { tmpParam.put(key, value); } else { System.out.println("already has key value pair: " + key + ":" + value); } } else { HashMap<String, String> tmpParam = new HashMap<>(4); tmpParam.put(key, value); tmpTable.put(parameterNumber, tmpParam); } } else { tmpTable = new HashMap<>(); HashMap<String, String> tmpParam = new HashMap<>(4); tmpParam.put(key, value); tmpTable.put(parameterNumber, tmpParam); } localConcepts.put(tableVersion, tmpTable); } }
public class class_name { private void storeConcept(String tableVersion, String parameterNumber, String key, String value) { HashMap<String, HashMap<String, String>> tmpTable; if (localConcepts.containsKey(tableVersion)) { tmpTable = localConcepts.get(tableVersion); // depends on control dependency: [if], data = [none] if (tmpTable.containsKey(parameterNumber)) { HashMap<String, String> tmpParam = tmpTable.get(parameterNumber); if (!tmpParam.containsKey(key)) { tmpParam.put(key, value); // depends on control dependency: [if], data = [none] } else { System.out.println("already has key value pair: " + key + ":" + value); // depends on control dependency: [if], data = [none] } } else { HashMap<String, String> tmpParam = new HashMap<>(4); tmpParam.put(key, value); // depends on control dependency: [if], data = [none] tmpTable.put(parameterNumber, tmpParam); // depends on control dependency: [if], data = [none] } } else { tmpTable = new HashMap<>(); // depends on control dependency: [if], data = [none] HashMap<String, String> tmpParam = new HashMap<>(4); tmpParam.put(key, value); // depends on control dependency: [if], data = [none] tmpTable.put(parameterNumber, tmpParam); // depends on control dependency: [if], data = [none] } localConcepts.put(tableVersion, tmpTable); } }
public class class_name { public static Method getDeclaredMethod(Class<?> clazz, String name, Class<?>... params) { try { return clazz.getDeclaredMethod(name, params); } catch (Exception e) { throw new IllegalArgumentException("Could not access method: " + name + " on " + clazz, e); } } }
public class class_name { public static Method getDeclaredMethod(Class<?> clazz, String name, Class<?>... params) { try { return clazz.getDeclaredMethod(name, params); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new IllegalArgumentException("Could not access method: " + name + " on " + clazz, e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private void initializeGenerationFromDisk(final CatalogMap<Connector> connectors, final ExportDataProcessor processor, File[] files, List<Pair<Integer, Integer>> localPartitionsToSites, long genId) { List<Integer> onDiskPartitions = new ArrayList<Integer>(); NavigableSet<Table> streams = CatalogUtil.getExportTablesExcludeViewOnly(connectors); Set<String> exportedTables = new HashSet<>(); for (Table stream : streams) { exportedTables.add(stream.getTypeName()); } /* * Find all the data files. Once one is found, extract the nonce * and check for any advertisements related to the data files. If * there are orphaned advertisements, delete them. */ Map<String, File> dataFiles = new HashMap<>(); for (File data: files) { if (data.getName().endsWith(".pbd")) { PbdSegmentName pbdName = PbdSegmentName.parseFile(exportLog, data); if (pbdName.m_nonce != null) { String nonce = pbdName.m_nonce; String streamName = getStreamNameFromNonce(nonce); if (exportedTables.contains(streamName)) { dataFiles.put(nonce, data); } else { // ENG-15740, stream can be dropped while node is offline, delete .pbd files // if stream is no longer in catalog data.delete(); } } else if (pbdName.m_result == Result.NOT_PBD) { exportLog.warn(data.getAbsolutePath() + " is not a PBD file."); } else if (pbdName.m_result == Result.INVALID_NAME) { exportLog.warn(data.getAbsolutePath() + " doesn't have valid PBD name."); } } } for (File ad: files) { if (ad.getName().endsWith(".ad")) { String nonce = getNonceFromAdFile(ad); File dataFile = dataFiles.get(nonce); if (dataFile != null) { try { addDataSource(ad, localPartitionsToSites, onDiskPartitions, processor, genId); } catch (IOException e) { VoltDB.crashLocalVoltDB("Error intializing export datasource " + ad, true, e); } } else { //Delete ads that have no data ad.delete(); } } } // Count unique partitions only Set<Integer> allLocalPartitions = localPartitionsToSites.stream() .map(p -> p.getFirst()) .collect(Collectors.toSet()); Set<Integer> onDIskPartitionsSet = new HashSet<Integer>(onDiskPartitions); onDIskPartitionsSet.removeAll(allLocalPartitions); // One export mailbox per node, since we only keep one generation if (!onDIskPartitionsSet.isEmpty()) { createAckMailboxesIfNeeded(onDIskPartitionsSet); } } }
public class class_name { private void initializeGenerationFromDisk(final CatalogMap<Connector> connectors, final ExportDataProcessor processor, File[] files, List<Pair<Integer, Integer>> localPartitionsToSites, long genId) { List<Integer> onDiskPartitions = new ArrayList<Integer>(); NavigableSet<Table> streams = CatalogUtil.getExportTablesExcludeViewOnly(connectors); Set<String> exportedTables = new HashSet<>(); for (Table stream : streams) { exportedTables.add(stream.getTypeName()); // depends on control dependency: [for], data = [stream] } /* * Find all the data files. Once one is found, extract the nonce * and check for any advertisements related to the data files. If * there are orphaned advertisements, delete them. */ Map<String, File> dataFiles = new HashMap<>(); for (File data: files) { if (data.getName().endsWith(".pbd")) { PbdSegmentName pbdName = PbdSegmentName.parseFile(exportLog, data); if (pbdName.m_nonce != null) { String nonce = pbdName.m_nonce; String streamName = getStreamNameFromNonce(nonce); if (exportedTables.contains(streamName)) { dataFiles.put(nonce, data); // depends on control dependency: [if], data = [none] } else { // ENG-15740, stream can be dropped while node is offline, delete .pbd files // if stream is no longer in catalog data.delete(); // depends on control dependency: [if], data = [none] } } else if (pbdName.m_result == Result.NOT_PBD) { exportLog.warn(data.getAbsolutePath() + " is not a PBD file."); // depends on control dependency: [if], data = [none] } else if (pbdName.m_result == Result.INVALID_NAME) { exportLog.warn(data.getAbsolutePath() + " doesn't have valid PBD name."); // depends on control dependency: [if], data = [none] } } } for (File ad: files) { if (ad.getName().endsWith(".ad")) { String nonce = getNonceFromAdFile(ad); File dataFile = dataFiles.get(nonce); if (dataFile != null) { try { addDataSource(ad, localPartitionsToSites, onDiskPartitions, processor, genId); // depends on control dependency: [try], data = [none] } catch (IOException e) { VoltDB.crashLocalVoltDB("Error intializing export datasource " + ad, true, e); } // depends on control dependency: [catch], data = [none] } else { //Delete ads that have no data ad.delete(); // depends on control dependency: [if], data = [none] } } } // Count unique partitions only Set<Integer> allLocalPartitions = localPartitionsToSites.stream() .map(p -> p.getFirst()) .collect(Collectors.toSet()); Set<Integer> onDIskPartitionsSet = new HashSet<Integer>(onDiskPartitions); onDIskPartitionsSet.removeAll(allLocalPartitions); // One export mailbox per node, since we only keep one generation if (!onDIskPartitionsSet.isEmpty()) { createAckMailboxesIfNeeded(onDIskPartitionsSet); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override String getRequestString() { StringBuilder requestString = new StringBuilder(); requestString.append("fromStation=").append(fromStation).append('&'); requestString.append("toStation=").append(toStation).append('&'); if (viaStation != null && viaStation.trim().length() != 0) { requestString.append("viaStation=").append(viaStation).append('&'); } if (previousAdvices != null) { requestString.append("previousAdvices=").append(previousAdvices).append('&'); } if (nextAdvices != null) { requestString.append("nextAdvices=").append(nextAdvices).append('&'); } if (dateTime != null) { requestString.append("dateTime=").append(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(dateTime)) .append('&'); } if (departure != null) { requestString.append("departure=").append(departure).append('&'); } if (hslAllowed != null) { requestString.append("hslAllowed=").append(hslAllowed).append('&'); } if (yearCard != null) { requestString.append("yearCard=").append(yearCard).append('&'); } return requestString.toString(); } }
public class class_name { @Override String getRequestString() { StringBuilder requestString = new StringBuilder(); requestString.append("fromStation=").append(fromStation).append('&'); requestString.append("toStation=").append(toStation).append('&'); if (viaStation != null && viaStation.trim().length() != 0) { requestString.append("viaStation=").append(viaStation).append('&'); // depends on control dependency: [if], data = [(viaStation] } if (previousAdvices != null) { requestString.append("previousAdvices=").append(previousAdvices).append('&'); // depends on control dependency: [if], data = [(previousAdvices] } if (nextAdvices != null) { requestString.append("nextAdvices=").append(nextAdvices).append('&'); // depends on control dependency: [if], data = [(nextAdvices] } if (dateTime != null) { requestString.append("dateTime=").append(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(dateTime)) .append('&'); // depends on control dependency: [if], data = [none] } if (departure != null) { requestString.append("departure=").append(departure).append('&'); // depends on control dependency: [if], data = [(departure] } if (hslAllowed != null) { requestString.append("hslAllowed=").append(hslAllowed).append('&'); // depends on control dependency: [if], data = [(hslAllowed] } if (yearCard != null) { requestString.append("yearCard=").append(yearCard).append('&'); // depends on control dependency: [if], data = [(yearCard] } return requestString.toString(); } }
public class class_name { public static String stripIllegalCharacters(String s) { char c; boolean needsStrip = false; StringBuilder sb; if (s == null) { return null; } for (int i = 0; i < s.length(); i++) { c = s.charAt(i); if (c >= '0' && c <= '9') { // continue } // NOPMD else if (c >= 'a' && c <= 'z') { // continue } // NOPMD else { needsStrip = true; break; } } if (!needsStrip) { return s; } sb = new StringBuilder(s.length()); for (int i = 0; i < s.length(); i++) { c = s.charAt(i); if (c >= '0' && c <= '9') { sb.append(c); } else if (c >= 'a' && c <= 'z') { sb.append(c); } } return sb.toString(); } }
public class class_name { public static String stripIllegalCharacters(String s) { char c; boolean needsStrip = false; StringBuilder sb; if (s == null) { return null; // depends on control dependency: [if], data = [none] } for (int i = 0; i < s.length(); i++) { c = s.charAt(i); // depends on control dependency: [for], data = [i] if (c >= '0' && c <= '9') { // continue } // NOPMD else if (c >= 'a' && c <= 'z') { // continue } // NOPMD else { needsStrip = true; // depends on control dependency: [if], data = [none] break; } } if (!needsStrip) { return s; // depends on control dependency: [if], data = [none] } sb = new StringBuilder(s.length()); for (int i = 0; i < s.length(); i++) { c = s.charAt(i); // depends on control dependency: [for], data = [i] if (c >= '0' && c <= '9') { sb.append(c); // depends on control dependency: [if], data = [(c] } else if (c >= 'a' && c <= 'z') { sb.append(c); // depends on control dependency: [if], data = [(c] } } return sb.toString(); } }
public class class_name { private void lookForVariableAccess(OptFunctionNode fn, Node n) { switch (n.getType()) { case Token.TYPEOFNAME: { // TYPEOFNAME may be used with undefined names, which is why // this is handled separately from GETVAR above. int varIndex = fn.fnode.getIndexForNameNode(n); if (varIndex > -1 && !itsNotDefSet.get(varIndex)) itsUseBeforeDefSet.set(varIndex); } break; case Token.DEC : case Token.INC : { Node child = n.getFirstChild(); if (child.getType() == Token.GETVAR) { int varIndex = fn.getVarIndex(child); if (!itsNotDefSet.get(varIndex)) itsUseBeforeDefSet.set(varIndex); itsNotDefSet.set(varIndex); } else { lookForVariableAccess(fn, child); } } break; case Token.SETVAR : case Token.SETCONSTVAR : { Node lhs = n.getFirstChild(); Node rhs = lhs.getNext(); lookForVariableAccess(fn, rhs); itsNotDefSet.set(fn.getVarIndex(n)); } break; case Token.GETVAR : { int varIndex = fn.getVarIndex(n); if (!itsNotDefSet.get(varIndex)) itsUseBeforeDefSet.set(varIndex); } break; default : Node child = n.getFirstChild(); while (child != null) { lookForVariableAccess(fn, child); child = child.getNext(); } break; } } }
public class class_name { private void lookForVariableAccess(OptFunctionNode fn, Node n) { switch (n.getType()) { case Token.TYPEOFNAME: { // TYPEOFNAME may be used with undefined names, which is why // this is handled separately from GETVAR above. int varIndex = fn.fnode.getIndexForNameNode(n); if (varIndex > -1 && !itsNotDefSet.get(varIndex)) itsUseBeforeDefSet.set(varIndex); } break; case Token.DEC : case Token.INC : { Node child = n.getFirstChild(); if (child.getType() == Token.GETVAR) { int varIndex = fn.getVarIndex(child); if (!itsNotDefSet.get(varIndex)) itsUseBeforeDefSet.set(varIndex); itsNotDefSet.set(varIndex); // depends on control dependency: [if], data = [none] } else { lookForVariableAccess(fn, child); // depends on control dependency: [if], data = [none] } } break; case Token.SETVAR : case Token.SETCONSTVAR : { Node lhs = n.getFirstChild(); Node rhs = lhs.getNext(); lookForVariableAccess(fn, rhs); itsNotDefSet.set(fn.getVarIndex(n)); } break; case Token.GETVAR : { int varIndex = fn.getVarIndex(n); if (!itsNotDefSet.get(varIndex)) itsUseBeforeDefSet.set(varIndex); } break; default : Node child = n.getFirstChild(); while (child != null) { lookForVariableAccess(fn, child); child = child.getNext(); } break; } } }
public class class_name { @Override public Time fromString(Class targetClass, String s) { if (s == null) { return null; } if (StringUtils.isNumeric(s)) { return new Time(Long.parseLong(s)); } Time t = Time.valueOf(s); return t; } }
public class class_name { @Override public Time fromString(Class targetClass, String s) { if (s == null) { return null; // depends on control dependency: [if], data = [none] } if (StringUtils.isNumeric(s)) { return new Time(Long.parseLong(s)); // depends on control dependency: [if], data = [none] } Time t = Time.valueOf(s); return t; } }
public class class_name { protected String getRelativePath(final HttpServletRequest request) { // IMPORTANT: DefaultServlet can be mapped to '/' or '/path/*' but // always // serves resources from the web app root with context rooted paths. // i.e. it can not be used to mount the web app root under a sub-path // This method must construct a complete context rooted path, although // subclasses can change this behaviour. // Are we being processed by a RequestDispatcher.include()? if (request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null) { String result = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO); if (result == null) { result = (String) request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); } else { result = (String) request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH) + result; } if ((result == null) || (result.equals(""))) { result = "/"; } return (result); } // No, extract the desired path directly from the request String result = request.getPathInfo(); if (result == null) { result = request.getServletPath(); } else { result = request.getServletPath() + result; } if ((result == null) || (result.equals(""))) { result = "/"; } return (result); } }
public class class_name { protected String getRelativePath(final HttpServletRequest request) { // IMPORTANT: DefaultServlet can be mapped to '/' or '/path/*' but // always // serves resources from the web app root with context rooted paths. // i.e. it can not be used to mount the web app root under a sub-path // This method must construct a complete context rooted path, although // subclasses can change this behaviour. // Are we being processed by a RequestDispatcher.include()? if (request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null) { String result = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO); if (result == null) { result = (String) request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); // depends on control dependency: [if], data = [none] } else { result = (String) request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH) + result; // depends on control dependency: [if], data = [none] } if ((result == null) || (result.equals(""))) { result = "/"; // depends on control dependency: [if], data = [none] } return (result); // depends on control dependency: [if], data = [none] } // No, extract the desired path directly from the request String result = request.getPathInfo(); if (result == null) { result = request.getServletPath(); // depends on control dependency: [if], data = [none] } else { result = request.getServletPath() + result; // depends on control dependency: [if], data = [none] } if ((result == null) || (result.equals(""))) { result = "/"; // depends on control dependency: [if], data = [none] } return (result); } }
public class class_name { public void setQueryable(String queryableStateName) { Preconditions.checkArgument( ttlConfig.getUpdateType() == StateTtlConfig.UpdateType.Disabled, "Queryable state is currently not supported with TTL"); if (this.queryableStateName == null) { this.queryableStateName = Preconditions.checkNotNull(queryableStateName, "Registration name"); } else { throw new IllegalStateException("Queryable state name already set"); } } }
public class class_name { public void setQueryable(String queryableStateName) { Preconditions.checkArgument( ttlConfig.getUpdateType() == StateTtlConfig.UpdateType.Disabled, "Queryable state is currently not supported with TTL"); if (this.queryableStateName == null) { this.queryableStateName = Preconditions.checkNotNull(queryableStateName, "Registration name"); // depends on control dependency: [if], data = [none] } else { throw new IllegalStateException("Queryable state name already set"); } } }
public class class_name { private void parseTree(List<Block> sourceBlocks) { Block matchStartBlock = null; int count = 0; Block mappingCursor = this.mappingTree.getChildren().get(0); Block sourceBlock = sourceBlocks.get(0); while (sourceBlock != null) { while (mappingCursor != null) { if (blockEquals(sourceBlock, mappingCursor)) { if (matchStartBlock == null) { matchStartBlock = sourceBlock; } count++; mappingCursor = mappingCursor.getChildren().get(0); // If we reach the Image Block then we've found a match! if (mappingCursor instanceof ImageBlock) { // Replace the first source block with the image block and remove all other blocks... for (int i = 0; i < count - 1; i++) { matchStartBlock.getParent().removeBlock(matchStartBlock.getNextSibling()); } sourceBlock = mappingCursor.clone(); matchStartBlock.getParent().replaceChild(sourceBlock, matchStartBlock); mappingCursor = null; matchStartBlock = null; count = 0; } else { // Look for next block match break; } } else { mappingCursor = mappingCursor.getNextSibling(); } } // Look for a match in children of the source block List<Block> filteredSourceBlocks = this.filter.filter(sourceBlock.getChildren()); if (!filteredSourceBlocks.isEmpty()) { parseTree(filteredSourceBlocks); } else if (mappingCursor == null) { // No match has been found, reset state variables mappingCursor = this.mappingTree.getChildren().get(0); count = 0; matchStartBlock = null; } sourceBlock = this.filter.getNextSibling(sourceBlock); } } }
public class class_name { private void parseTree(List<Block> sourceBlocks) { Block matchStartBlock = null; int count = 0; Block mappingCursor = this.mappingTree.getChildren().get(0); Block sourceBlock = sourceBlocks.get(0); while (sourceBlock != null) { while (mappingCursor != null) { if (blockEquals(sourceBlock, mappingCursor)) { if (matchStartBlock == null) { matchStartBlock = sourceBlock; // depends on control dependency: [if], data = [none] } count++; // depends on control dependency: [if], data = [none] mappingCursor = mappingCursor.getChildren().get(0); // depends on control dependency: [if], data = [none] // If we reach the Image Block then we've found a match! if (mappingCursor instanceof ImageBlock) { // Replace the first source block with the image block and remove all other blocks... for (int i = 0; i < count - 1; i++) { matchStartBlock.getParent().removeBlock(matchStartBlock.getNextSibling()); // depends on control dependency: [for], data = [none] } sourceBlock = mappingCursor.clone(); // depends on control dependency: [if], data = [none] matchStartBlock.getParent().replaceChild(sourceBlock, matchStartBlock); // depends on control dependency: [if], data = [none] mappingCursor = null; // depends on control dependency: [if], data = [none] matchStartBlock = null; // depends on control dependency: [if], data = [none] count = 0; // depends on control dependency: [if], data = [none] } else { // Look for next block match break; } } else { mappingCursor = mappingCursor.getNextSibling(); // depends on control dependency: [if], data = [none] } } // Look for a match in children of the source block List<Block> filteredSourceBlocks = this.filter.filter(sourceBlock.getChildren()); if (!filteredSourceBlocks.isEmpty()) { parseTree(filteredSourceBlocks); // depends on control dependency: [if], data = [none] } else if (mappingCursor == null) { // No match has been found, reset state variables mappingCursor = this.mappingTree.getChildren().get(0); // depends on control dependency: [if], data = [none] count = 0; // depends on control dependency: [if], data = [none] matchStartBlock = null; // depends on control dependency: [if], data = [none] } sourceBlock = this.filter.getNextSibling(sourceBlock); // depends on control dependency: [while], data = [(sourceBlock] } } }
public class class_name { protected void logDisabledFork() { if (getLog().isWarnEnabled()) { if (hasAgent()) { getLog().warn("Fork mode disabled, ignoring agent"); } if (hasJvmArgs()) { RunArguments runArguments = resolveJvmArguments(); getLog().warn("Fork mode disabled, ignoring JVM argument(s) [" + Arrays .stream(runArguments.asArray()).collect(Collectors.joining(" ")) + "]"); } if (hasWorkingDirectorySet()) { getLog().warn( "Fork mode disabled, ignoring working directory configuration"); } } } }
public class class_name { protected void logDisabledFork() { if (getLog().isWarnEnabled()) { if (hasAgent()) { getLog().warn("Fork mode disabled, ignoring agent"); // depends on control dependency: [if], data = [none] } if (hasJvmArgs()) { RunArguments runArguments = resolveJvmArguments(); getLog().warn("Fork mode disabled, ignoring JVM argument(s) [" + Arrays .stream(runArguments.asArray()).collect(Collectors.joining(" ")) + "]"); // depends on control dependency: [if], data = [none] } if (hasWorkingDirectorySet()) { getLog().warn( "Fork mode disabled, ignoring working directory configuration"); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static Cluster randomShufflePartitions(final Cluster nextCandidateCluster, final int randomSwapAttempts, final int randomSwapSuccesses, final List<Integer> randomSwapZoneIds, List<StoreDefinition> storeDefs) { List<Integer> zoneIds = null; if(randomSwapZoneIds.isEmpty()) { zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds()); } else { zoneIds = new ArrayList<Integer>(randomSwapZoneIds); } List<Integer> nodeIds = new ArrayList<Integer>(); Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster); double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility(); int successes = 0; for(int i = 0; i < randomSwapAttempts; i++) { // Iterate over zone ids to decide which node ids to include for // intra-zone swapping. // In future, if there is a need to support inter-zone swapping, // then just remove the // zone specific logic that populates nodeIdSet and add all nodes // from across all zones. int zoneIdOffset = i % zoneIds.size(); Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset)); nodeIds = new ArrayList<Integer>(nodeIdSet); Collections.shuffle(zoneIds, new Random(System.currentTimeMillis())); Cluster shuffleResults = swapRandomPartitionsAmongNodes(returnCluster, nodeIds); double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility(); if(nextUtility < currentUtility) { System.out.println("Swap improved max-min ratio: " + currentUtility + " -> " + nextUtility + " (improvement " + successes + " on swap attempt " + i + ")"); successes++; returnCluster = shuffleResults; currentUtility = nextUtility; } if(successes >= randomSwapSuccesses) { // Enough successes, move on. break; } } return returnCluster; } }
public class class_name { public static Cluster randomShufflePartitions(final Cluster nextCandidateCluster, final int randomSwapAttempts, final int randomSwapSuccesses, final List<Integer> randomSwapZoneIds, List<StoreDefinition> storeDefs) { List<Integer> zoneIds = null; if(randomSwapZoneIds.isEmpty()) { zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds()); // depends on control dependency: [if], data = [none] } else { zoneIds = new ArrayList<Integer>(randomSwapZoneIds); // depends on control dependency: [if], data = [none] } List<Integer> nodeIds = new ArrayList<Integer>(); Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster); double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility(); int successes = 0; for(int i = 0; i < randomSwapAttempts; i++) { // Iterate over zone ids to decide which node ids to include for // intra-zone swapping. // In future, if there is a need to support inter-zone swapping, // then just remove the // zone specific logic that populates nodeIdSet and add all nodes // from across all zones. int zoneIdOffset = i % zoneIds.size(); Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset)); nodeIds = new ArrayList<Integer>(nodeIdSet); // depends on control dependency: [for], data = [none] Collections.shuffle(zoneIds, new Random(System.currentTimeMillis())); // depends on control dependency: [for], data = [none] Cluster shuffleResults = swapRandomPartitionsAmongNodes(returnCluster, nodeIds); double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility(); if(nextUtility < currentUtility) { System.out.println("Swap improved max-min ratio: " + currentUtility + " -> " + nextUtility + " (improvement " + successes + " on swap attempt " + i + ")"); successes++; returnCluster = shuffleResults; currentUtility = nextUtility; } if(successes >= randomSwapSuccesses) { // Enough successes, move on. break; } } return returnCluster; // depends on control dependency: [if], data = [none] } }
public class class_name { String getSQLForSelectCount() { final DBTable dbTable = mModelClazz.getAnnotation(DBTable.class); final String dbTableName = dbTable.tableName(); final List<DBColumn> primaryKeyList = getPrimaryKeyColumnList(); final String preparedSql; if (primaryKeyList.size() > 0) { final DBColumn primaryKey = primaryKeyList.get(0); final String primaryKeyColumnName = primaryKey.columnName(); preparedSql = "SELECT COUNT(" + primaryKeyColumnName + ") FROM " + dbTableName; } else { preparedSql = "SELECT COUNT(" + "*" + ") FROM " + dbTableName; } return preparedSql; } }
public class class_name { String getSQLForSelectCount() { final DBTable dbTable = mModelClazz.getAnnotation(DBTable.class); final String dbTableName = dbTable.tableName(); final List<DBColumn> primaryKeyList = getPrimaryKeyColumnList(); final String preparedSql; if (primaryKeyList.size() > 0) { final DBColumn primaryKey = primaryKeyList.get(0); final String primaryKeyColumnName = primaryKey.columnName(); preparedSql = "SELECT COUNT(" + primaryKeyColumnName + ") FROM " + dbTableName; // depends on control dependency: [if], data = [none] } else { preparedSql = "SELECT COUNT(" + "*" + ") FROM " + dbTableName; // depends on control dependency: [if], data = [none] } return preparedSql; } }
public class class_name { Node popNode() { if (--sp < mk) { mk = ((Integer)marks.pop()).intValue(); } return (Node)nodes.pop(); } }
public class class_name { Node popNode() { if (--sp < mk) { mk = ((Integer)marks.pop()).intValue(); // depends on control dependency: [if], data = [none] } return (Node)nodes.pop(); } }
public class class_name { protected void estimateP3P(int excluded) { // the point used to check the solutions is the last one inputP3P.clear(); for( int i = 0; i < 4; i++ ) { if( i != excluded ) { inputP3P.add( points.get(i) ); } } // initial estimate for the pose solutions.reset(); if( !p3p.process(inputP3P,solutions) ) { // System.err.println("PIP Failed!?! That's weird"); return; } for (int i = 0; i < solutions.size; i++) { double error = computeErrors(solutions.get(i)); // see if it's better and it should save the results if( error < bestError ) { bestError = error; bestPose.set(solutions.get(i)); } } } }
public class class_name { protected void estimateP3P(int excluded) { // the point used to check the solutions is the last one inputP3P.clear(); for( int i = 0; i < 4; i++ ) { if( i != excluded ) { inputP3P.add( points.get(i) ); // depends on control dependency: [if], data = [none] } } // initial estimate for the pose solutions.reset(); if( !p3p.process(inputP3P,solutions) ) { // System.err.println("PIP Failed!?! That's weird"); return; // depends on control dependency: [if], data = [none] } for (int i = 0; i < solutions.size; i++) { double error = computeErrors(solutions.get(i)); // see if it's better and it should save the results if( error < bestError ) { bestError = error; // depends on control dependency: [if], data = [none] bestPose.set(solutions.get(i)); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static boolean contains(Iterable self, Object item) { for (Object e : self) { if (item == null ? e == null : item.equals(e)) { return true; } } return false; } }
public class class_name { public static boolean contains(Iterable self, Object item) { for (Object e : self) { if (item == null ? e == null : item.equals(e)) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { @Override public Node getGroup(final String cn) { try { String query = "(&(objectClass=" + groupObjectClass + ")(" + groupIdentifyer + "=" + cn + "))"; SearchResult searchResult; Attributes attributes; SearchControls controls = new SearchControls(); controls.setReturningAttributes(new String[]{LdapKeys.ASTERISK, LdapKeys.MODIFY_TIMESTAMP, LdapKeys.MODIFIERS_NAME, LdapKeys.ENTRY_UUID}); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = ctx.search("", query, controls); queryCount++; if (results.hasMore()) { LdapGroup group = new LdapGroup(cn, this); searchResult = results.next(); group.setDn(searchResult.getNameInNamespace()); attributes = searchResult.getAttributes(); group = fillAttributesInGroup((LdapGroup) group, attributes); return group; } } catch (NamingException ex) { handleNamingException(instanceName + ":" + cn, ex); } return new LdapGroup(); } }
public class class_name { @Override public Node getGroup(final String cn) { try { String query = "(&(objectClass=" + groupObjectClass + ")(" + groupIdentifyer + "=" + cn + "))"; SearchResult searchResult; Attributes attributes; SearchControls controls = new SearchControls(); controls.setReturningAttributes(new String[]{LdapKeys.ASTERISK, LdapKeys.MODIFY_TIMESTAMP, LdapKeys.MODIFIERS_NAME, LdapKeys.ENTRY_UUID}); // depends on control dependency: [try], data = [none] controls.setSearchScope(SearchControls.SUBTREE_SCOPE); // depends on control dependency: [try], data = [none] NamingEnumeration<SearchResult> results = ctx.search("", query, controls); queryCount++; // depends on control dependency: [try], data = [none] if (results.hasMore()) { LdapGroup group = new LdapGroup(cn, this); searchResult = results.next(); // depends on control dependency: [if], data = [none] group.setDn(searchResult.getNameInNamespace()); // depends on control dependency: [if], data = [none] attributes = searchResult.getAttributes(); // depends on control dependency: [if], data = [none] group = fillAttributesInGroup((LdapGroup) group, attributes); // depends on control dependency: [if], data = [none] return group; // depends on control dependency: [if], data = [none] } } catch (NamingException ex) { handleNamingException(instanceName + ":" + cn, ex); } // depends on control dependency: [catch], data = [none] return new LdapGroup(); } }
public class class_name { public static String md5(String text) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch(NoSuchAlgorithmException e) { throw new BugError("Java runtime without MD5 support."); } md.update(text.getBytes()); byte[] md5 = md.digest(); char[] buffer = new char[32]; for(int i = 0; i < 16; i++) { buffer[i * 2] = HEXA[(md5[i] & 0xf0) >> 4]; buffer[i * 2 + 1] = HEXA[md5[i] & 0x0f]; } return new String(buffer); } }
public class class_name { public static String md5(String text) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); // depends on control dependency: [try], data = [none] } catch(NoSuchAlgorithmException e) { throw new BugError("Java runtime without MD5 support."); } // depends on control dependency: [catch], data = [none] md.update(text.getBytes()); byte[] md5 = md.digest(); char[] buffer = new char[32]; for(int i = 0; i < 16; i++) { buffer[i * 2] = HEXA[(md5[i] & 0xf0) >> 4]; // depends on control dependency: [for], data = [i] buffer[i * 2 + 1] = HEXA[md5[i] & 0x0f]; // depends on control dependency: [for], data = [i] } return new String(buffer); } }
public class class_name { public static base_responses add(nitro_service client, lbwlm resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { lbwlm addresources[] = new lbwlm[resources.length]; for (int i=0;i<resources.length;i++){ addresources[i] = new lbwlm(); addresources[i].wlmname = resources[i].wlmname; addresources[i].ipaddress = resources[i].ipaddress; addresources[i].port = resources[i].port; addresources[i].lbuid = resources[i].lbuid; addresources[i].katimeout = resources[i].katimeout; } result = add_bulk_request(client, addresources); } return result; } }
public class class_name { public static base_responses add(nitro_service client, lbwlm resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { lbwlm addresources[] = new lbwlm[resources.length]; for (int i=0;i<resources.length;i++){ addresources[i] = new lbwlm(); // depends on control dependency: [for], data = [i] addresources[i].wlmname = resources[i].wlmname; // depends on control dependency: [for], data = [i] addresources[i].ipaddress = resources[i].ipaddress; // depends on control dependency: [for], data = [i] addresources[i].port = resources[i].port; // depends on control dependency: [for], data = [i] addresources[i].lbuid = resources[i].lbuid; // depends on control dependency: [for], data = [i] addresources[i].katimeout = resources[i].katimeout; // depends on control dependency: [for], data = [i] } result = add_bulk_request(client, addresources); } return result; } }
public class class_name { private void encodeSubject(Subject subject, PrintStream out, Indenter indenter) { char [] indent = indenter.makeString().toCharArray(); out.print(indent); out.append("<Subject SubjectCategory=\"") .append(subject.getCategory().toString()).append('"'); List subjectAttrs = subject.getAttributesAsList(); if (subjectAttrs.size() == 0) { // there's nothing in this Subject, so just close the tag out.println("/>"); } else { // there's content, so fill it in out.println('>'); encodeAttributes(subjectAttrs, out, indenter); out.print(indent); out.println("</Subject>"); } } }
public class class_name { private void encodeSubject(Subject subject, PrintStream out, Indenter indenter) { char [] indent = indenter.makeString().toCharArray(); out.print(indent); out.append("<Subject SubjectCategory=\"") .append(subject.getCategory().toString()).append('"'); List subjectAttrs = subject.getAttributesAsList(); if (subjectAttrs.size() == 0) { // there's nothing in this Subject, so just close the tag out.println("/>"); // depends on control dependency: [if], data = [none] } else { // there's content, so fill it in out.println('>'); // depends on control dependency: [if], data = [none] encodeAttributes(subjectAttrs, out, indenter); // depends on control dependency: [if], data = [none] out.print(indent); // depends on control dependency: [if], data = [none] out.println("</Subject>"); // depends on control dependency: [if], data = [none] } } }
public class class_name { private NotificationResponse mapToNotificationResponse(PortletRequest request, ResponseEntity<String> response) { Configuration config = Configuration.builder().options( Option.DEFAULT_PATH_LEAF_TO_NULL ).build(); ReadContext readContext = JsonPath .using(config) .parse(response.getBody()); // check the status embedded in the response too... String success = readContext.read(SUCCESS_QUERY); // grr. SSP returns this as a string... if (!"true".equalsIgnoreCase(success)) { String error = readContext.read(MESSAGE_QUERY); return notificationError(error); } // read the actual tasks... Object rows = readContext.read(ROWS_QUERY); if (!(rows instanceof JSONArray)) { throw new RuntimeException("Expected 'rows' to be an array of tasks"); } String source = getNotificationSource(request); List<NotificationEntry> list = new ArrayList<>(); for (int i = 0; i < ((JSONArray)rows).size(); i++) { NotificationEntry entry = mapNotificationEntry(readContext, i, source); if (entry != null) { attachActions(request, entry); list.add(entry); } } // build the notification response... NotificationResponse notification = new NotificationResponse(); if (!list.isEmpty()) { NotificationCategory category = getNotificationCategory(request); category.addEntries(list); notification.setCategories(Arrays.asList(category)); } return notification; } }
public class class_name { private NotificationResponse mapToNotificationResponse(PortletRequest request, ResponseEntity<String> response) { Configuration config = Configuration.builder().options( Option.DEFAULT_PATH_LEAF_TO_NULL ).build(); ReadContext readContext = JsonPath .using(config) .parse(response.getBody()); // check the status embedded in the response too... String success = readContext.read(SUCCESS_QUERY); // grr. SSP returns this as a string... if (!"true".equalsIgnoreCase(success)) { String error = readContext.read(MESSAGE_QUERY); return notificationError(error); // depends on control dependency: [if], data = [none] } // read the actual tasks... Object rows = readContext.read(ROWS_QUERY); if (!(rows instanceof JSONArray)) { throw new RuntimeException("Expected 'rows' to be an array of tasks"); } String source = getNotificationSource(request); List<NotificationEntry> list = new ArrayList<>(); for (int i = 0; i < ((JSONArray)rows).size(); i++) { NotificationEntry entry = mapNotificationEntry(readContext, i, source); if (entry != null) { attachActions(request, entry); // depends on control dependency: [if], data = [none] list.add(entry); // depends on control dependency: [if], data = [(entry] } } // build the notification response... NotificationResponse notification = new NotificationResponse(); if (!list.isEmpty()) { NotificationCategory category = getNotificationCategory(request); category.addEntries(list); // depends on control dependency: [if], data = [none] notification.setCategories(Arrays.asList(category)); // depends on control dependency: [if], data = [none] } return notification; } }
public class class_name { public java.util.List<TargetConfigurationRequest> getTargetConfigurations() { if (targetConfigurations == null) { targetConfigurations = new com.amazonaws.internal.SdkInternalList<TargetConfigurationRequest>(); } return targetConfigurations; } }
public class class_name { public java.util.List<TargetConfigurationRequest> getTargetConfigurations() { if (targetConfigurations == null) { targetConfigurations = new com.amazonaws.internal.SdkInternalList<TargetConfigurationRequest>(); // depends on control dependency: [if], data = [none] } return targetConfigurations; } }
public class class_name { protected File selectResource(String baseLocation, final String symbolicName, final VersionRange versionRange, final boolean performURICheck, final boolean selectBaseBundle) { // If the baseLocation is null or the empty string use the default location. if (baseLocation == null || "".equals(baseLocation)) { baseLocation = getDefaultBaseLocation(); } Set<String> baseLocationParts; // If we have an exact location ... if (!!!baseLocation.contains(",")) { File candidateFile; if (performURICheck) { // ... try to see if we have a URL (actually not sure this is used ever). If it exists return it. try { candidateFile = new File(URI.create(baseLocation)); if (candidateFile.exists() && candidateFile.isFile() && candidateFile.isAbsolute()) { return validateR4Bundle(candidateFile); } } catch (IllegalArgumentException iae) { // Just ignore, not a URI, and move on. } } // If it wasn't a URL then see if we can find it. If we do return it. If we don't we assume // the location is a directory and fall through to that processing. candidateFile = new File(getRootDirectory(), baseLocation); if (candidateFile.exists() && candidateFile.isFile()) { return validateR4Bundle(candidateFile); } // Prime baseLocationParts with this single baseLocation. baseLocationParts = new HashSet<String>(); baseLocationParts.add(baseLocation); } else { // If we found a comma we assume we have a comma separated list of directories so split them up. baseLocationParts = new HashSet<String>(Arrays.asList(baseLocation.split(","))); } // Loop around all the locations (well DUH!). for (String baseLocationPart : baseLocationParts) { // Need to trim whitespace in case someone padded the locations in the source. baseLocationPart = baseLocationPart.trim(); // If we haven't seen this location before we need to include the directory looking at the resources in the directory. if (!!!isBaseLocationIncluded(baseLocationPart)) { // Make sure we don't include again and then include the directory loading all missed resources into this object. includeBaseLocation(baseLocationPart); } } // Now we have loaded everything into memory we grab the candidates with the right symbolic name. If we // get nothing back then we will ultimately return a null file. List<Resource> candidateResources = getResourcesBySymbolicName(symbolicName); if (candidateResources != null) { // Sort the candidates (using a sorted set might be more efficient, although // we aren't likely to often select the same resource multiple times). // As a result of calling the resource in our example are sorted in this following order: // (First entry) a.b/1.0.2.v2, a.b/1.0.1.v1, a.b/1.0.1 (Last entry) Collections.sort(candidateResources); Resource bestMatch = null; // Loop around all the candidates. for (Resource candidateResource : candidateResources) { // Make sure the candidate is in the baseLocations provided in the selection rules. If it isn't we don't // want it. We also don't want it if it doesn't match the version range passed in. If either of these // conditions are met we just skip. if (!!!baseLocationParts.contains(candidateResource.getBaseLocation()) || !!!versionRange.includes(candidateResource.getVersion())) { continue; } // If the best match is null this is the first possible match. if (bestMatch == null) { // If we've got a standard resource here and isn't an IFix then we need to just take the // top entry, which will give us the highest versioned resource. if (!!!candidateResource.isFix()) { return candidateResource.getFile(); //resource is a basebundle, no action needed for selectBaseBundle } else { // Save the best match, but we need to keep going to make sure the base resource can be found. bestMatch = candidateResource; // Kernel.boot jar when ifixed has no base bundle as the jar keeps the same name due to tooling // having the jar by name on manifest classpaths. Therefore for this jar there will only be a // single match so return as soon as we have it. if ("com.ibm.ws.kernel.boot".equals(symbolicName)) { return bestMatch.getFile(); } } } else { // Fetching here because in the error case we will need to re-fetch. int bestMatchMajor = bestMatch.getVersion().getMajor(); int bestMatchMinor = bestMatch.getVersion().getMinor(); int bestMatchMicro = bestMatch.getVersion().getMicro(); // If the major, minor and micro exist then this is a resource on the same base level (could be another // but older IFix, or the base resource, but it has to be one of them). if (bestMatchMajor == candidateResource.getVersion().getMajor() && bestMatchMinor == candidateResource.getVersion().getMinor() && bestMatchMicro == candidateResource.getVersion().getMicro()) { // If we hit something that is not an IFix then we have a valid best IFix so we return it. if (!!!candidateResource.isFix()) { //match was for baseBundle for an ifix, return appropriately. return selectBaseBundle ? candidateResource.getFile() : bestMatch.getFile(); } } else { // If we got here then the previous best match did not have a base resource installed. So we // need to output a warning and move on. This message makes an assumption about the way the // resources are named that might not hold, but given no base resource exists we have to make an assumption. warnThatAnIFixWasIgnored(bestMatch.getFile().getName(), bestMatch.getSymbolicName(), bestMatchMajor, bestMatchMinor, bestMatchMicro); // If we can't find an existing match resource for the IFix, then we still need to try and load // a non-IFix version of the resource, if one exists. if (!!!candidateResource.isFix()) { return candidateResource.getFile(); //not ifix, no action needed for selectBaseBundle. } else { bestMatch = candidateResource; } } } } // If we get here and we have a best match that is not an ifix, we need to return the file for it. // This should not happen, as we only store iFixes into bestMatch.. if (bestMatch != null && !!!bestMatch.isFix()) { //not an ifix, so no need to handle selectBaseBundle return bestMatch.getFile(); } } // If we get here we didn't find a match so just return null. return null; } }
public class class_name { protected File selectResource(String baseLocation, final String symbolicName, final VersionRange versionRange, final boolean performURICheck, final boolean selectBaseBundle) { // If the baseLocation is null or the empty string use the default location. if (baseLocation == null || "".equals(baseLocation)) { baseLocation = getDefaultBaseLocation(); // depends on control dependency: [if], data = [none] } Set<String> baseLocationParts; // If we have an exact location ... if (!!!baseLocation.contains(",")) { File candidateFile; if (performURICheck) { // ... try to see if we have a URL (actually not sure this is used ever). If it exists return it. try { candidateFile = new File(URI.create(baseLocation)); // depends on control dependency: [try], data = [none] if (candidateFile.exists() && candidateFile.isFile() && candidateFile.isAbsolute()) { return validateR4Bundle(candidateFile); // depends on control dependency: [if], data = [none] } } catch (IllegalArgumentException iae) { // Just ignore, not a URI, and move on. } // depends on control dependency: [catch], data = [none] } // If it wasn't a URL then see if we can find it. If we do return it. If we don't we assume // the location is a directory and fall through to that processing. candidateFile = new File(getRootDirectory(), baseLocation); // depends on control dependency: [if], data = [none] if (candidateFile.exists() && candidateFile.isFile()) { return validateR4Bundle(candidateFile); // depends on control dependency: [if], data = [none] } // Prime baseLocationParts with this single baseLocation. baseLocationParts = new HashSet<String>(); // depends on control dependency: [if], data = [none] baseLocationParts.add(baseLocation); // depends on control dependency: [if], data = [none] } else { // If we found a comma we assume we have a comma separated list of directories so split them up. baseLocationParts = new HashSet<String>(Arrays.asList(baseLocation.split(","))); // depends on control dependency: [if], data = [none] } // Loop around all the locations (well DUH!). for (String baseLocationPart : baseLocationParts) { // Need to trim whitespace in case someone padded the locations in the source. baseLocationPart = baseLocationPart.trim(); // depends on control dependency: [for], data = [baseLocationPart] // If we haven't seen this location before we need to include the directory looking at the resources in the directory. if (!!!isBaseLocationIncluded(baseLocationPart)) { // Make sure we don't include again and then include the directory loading all missed resources into this object. includeBaseLocation(baseLocationPart); // depends on control dependency: [if], data = [none] } } // Now we have loaded everything into memory we grab the candidates with the right symbolic name. If we // get nothing back then we will ultimately return a null file. List<Resource> candidateResources = getResourcesBySymbolicName(symbolicName); if (candidateResources != null) { // Sort the candidates (using a sorted set might be more efficient, although // we aren't likely to often select the same resource multiple times). // As a result of calling the resource in our example are sorted in this following order: // (First entry) a.b/1.0.2.v2, a.b/1.0.1.v1, a.b/1.0.1 (Last entry) Collections.sort(candidateResources); // depends on control dependency: [if], data = [(candidateResources] Resource bestMatch = null; // Loop around all the candidates. for (Resource candidateResource : candidateResources) { // Make sure the candidate is in the baseLocations provided in the selection rules. If it isn't we don't // want it. We also don't want it if it doesn't match the version range passed in. If either of these // conditions are met we just skip. if (!!!baseLocationParts.contains(candidateResource.getBaseLocation()) || !!!versionRange.includes(candidateResource.getVersion())) { continue; } // If the best match is null this is the first possible match. if (bestMatch == null) { // If we've got a standard resource here and isn't an IFix then we need to just take the // top entry, which will give us the highest versioned resource. if (!!!candidateResource.isFix()) { return candidateResource.getFile(); //resource is a basebundle, no action needed for selectBaseBundle // depends on control dependency: [if], data = [none] } else { // Save the best match, but we need to keep going to make sure the base resource can be found. bestMatch = candidateResource; // depends on control dependency: [if], data = [none] // Kernel.boot jar when ifixed has no base bundle as the jar keeps the same name due to tooling // having the jar by name on manifest classpaths. Therefore for this jar there will only be a // single match so return as soon as we have it. if ("com.ibm.ws.kernel.boot".equals(symbolicName)) { return bestMatch.getFile(); // depends on control dependency: [if], data = [none] } } } else { // Fetching here because in the error case we will need to re-fetch. int bestMatchMajor = bestMatch.getVersion().getMajor(); int bestMatchMinor = bestMatch.getVersion().getMinor(); int bestMatchMicro = bestMatch.getVersion().getMicro(); // If the major, minor and micro exist then this is a resource on the same base level (could be another // but older IFix, or the base resource, but it has to be one of them). if (bestMatchMajor == candidateResource.getVersion().getMajor() && bestMatchMinor == candidateResource.getVersion().getMinor() && bestMatchMicro == candidateResource.getVersion().getMicro()) { // If we hit something that is not an IFix then we have a valid best IFix so we return it. if (!!!candidateResource.isFix()) { //match was for baseBundle for an ifix, return appropriately. return selectBaseBundle ? candidateResource.getFile() : bestMatch.getFile(); // depends on control dependency: [if], data = [none] } } else { // If we got here then the previous best match did not have a base resource installed. So we // need to output a warning and move on. This message makes an assumption about the way the // resources are named that might not hold, but given no base resource exists we have to make an assumption. warnThatAnIFixWasIgnored(bestMatch.getFile().getName(), bestMatch.getSymbolicName(), bestMatchMajor, bestMatchMinor, bestMatchMicro); // depends on control dependency: [if], data = [none] // If we can't find an existing match resource for the IFix, then we still need to try and load // a non-IFix version of the resource, if one exists. if (!!!candidateResource.isFix()) { return candidateResource.getFile(); //not ifix, no action needed for selectBaseBundle. // depends on control dependency: [if], data = [none] } else { bestMatch = candidateResource; // depends on control dependency: [if], data = [none] } } } } // If we get here and we have a best match that is not an ifix, we need to return the file for it. // This should not happen, as we only store iFixes into bestMatch.. if (bestMatch != null && !!!bestMatch.isFix()) { //not an ifix, so no need to handle selectBaseBundle return bestMatch.getFile(); // depends on control dependency: [if], data = [none] } } // If we get here we didn't find a match so just return null. return null; } }
public class class_name { private Subquery<ImageFile> getImagesWithFileNameSubquery(final String filename, final FilterStringLogic searchLogic) { final CriteriaBuilder criteriaBuilder = getCriteriaBuilder(); final Subquery<ImageFile> subQuery = getCriteriaQuery().subquery(ImageFile.class); final Root<LanguageImage> root = subQuery.from(LanguageImage.class); subQuery.select(root.get("imageFile").as(ImageFile.class)); // Create the Condition for the subquery final Predicate imageIdMatch = criteriaBuilder.equal(getRootPath().get("imageFileId"), root.get("imageFile").get("imageFileId")); final Predicate filenameMatch; if (searchLogic == FilterStringLogic.MATCHES) { filenameMatch = criteriaBuilder.equal(root.get("originalFileName"), filename); } else { filenameMatch = criteriaBuilder.like(criteriaBuilder.lower(root.get("originalFileName").as(String.class)), '%' + cleanLikeCondition(filename).toLowerCase() + '%'); } subQuery.where(criteriaBuilder.and(imageIdMatch, filenameMatch)); return subQuery; } }
public class class_name { private Subquery<ImageFile> getImagesWithFileNameSubquery(final String filename, final FilterStringLogic searchLogic) { final CriteriaBuilder criteriaBuilder = getCriteriaBuilder(); final Subquery<ImageFile> subQuery = getCriteriaQuery().subquery(ImageFile.class); final Root<LanguageImage> root = subQuery.from(LanguageImage.class); subQuery.select(root.get("imageFile").as(ImageFile.class)); // Create the Condition for the subquery final Predicate imageIdMatch = criteriaBuilder.equal(getRootPath().get("imageFileId"), root.get("imageFile").get("imageFileId")); final Predicate filenameMatch; if (searchLogic == FilterStringLogic.MATCHES) { filenameMatch = criteriaBuilder.equal(root.get("originalFileName"), filename); // depends on control dependency: [if], data = [none] } else { filenameMatch = criteriaBuilder.like(criteriaBuilder.lower(root.get("originalFileName").as(String.class)), '%' + cleanLikeCondition(filename).toLowerCase() + '%'); // depends on control dependency: [if], data = [none] } subQuery.where(criteriaBuilder.and(imageIdMatch, filenameMatch)); return subQuery; } }
public class class_name { private static String getLongString(IoBufferEx buffer) { long len = getUnsignedInt(buffer); StringBuilder builder = new StringBuilder(); for (int i = 0; i < len; i++) { builder.append((char)(buffer.getUnsigned())); } String s = builder.toString(); return s; } }
public class class_name { private static String getLongString(IoBufferEx buffer) { long len = getUnsignedInt(buffer); StringBuilder builder = new StringBuilder(); for (int i = 0; i < len; i++) { builder.append((char)(buffer.getUnsigned())); // depends on control dependency: [for], data = [none] } String s = builder.toString(); return s; } }
public class class_name { public static String removeCComments(final String src) { final StringBuilder ret = new StringBuilder(); boolean inComments = false; for (int i = 0; i < src.length(); i++) { char c = src.charAt(i); if (inComments) { if (c == '*' && src.charAt(i + 1) == '/') { inComments = false; i++; } } else { if (c == '/') { if (src.charAt(i + 1) == '*') { inComments = true; i++; } else { ret.append(c); } } else ret.append(c); } } return ret.toString(); } }
public class class_name { public static String removeCComments(final String src) { final StringBuilder ret = new StringBuilder(); boolean inComments = false; for (int i = 0; i < src.length(); i++) { char c = src.charAt(i); if (inComments) { if (c == '*' && src.charAt(i + 1) == '/') { inComments = false; // depends on control dependency: [if], data = [none] i++; // depends on control dependency: [if], data = [none] } } else { if (c == '/') { if (src.charAt(i + 1) == '*') { inComments = true; // depends on control dependency: [if], data = [none] i++; // depends on control dependency: [if], data = [none] } else { ret.append(c); // depends on control dependency: [if], data = [none] } } else ret.append(c); } } return ret.toString(); } }
public class class_name { private static int bucketizeValue(double wt) { int index; if (wt >= 0.0) { index = ((int) (wt * 10.0)) + 100; } else { index = ((int) (Math.floor(wt * 10.0))) + 100; } if (index < 0) { index = 201; } else if (index > 200) { index = 200; } return index; } }
public class class_name { private static int bucketizeValue(double wt) { int index; if (wt >= 0.0) { index = ((int) (wt * 10.0)) + 100; // depends on control dependency: [if], data = [(wt] } else { index = ((int) (Math.floor(wt * 10.0))) + 100; // depends on control dependency: [if], data = [(wt] } if (index < 0) { index = 201; // depends on control dependency: [if], data = [none] } else if (index > 200) { index = 200; // depends on control dependency: [if], data = [none] } return index; } }
public class class_name { void removeAllEventListeners() { for (JcrListenerAdapter adapter : this.listeners) { assert (adapter != null); this.repositoryObservable.unregister(adapter); } this.listeners.clear(); } }
public class class_name { void removeAllEventListeners() { for (JcrListenerAdapter adapter : this.listeners) { assert (adapter != null); // depends on control dependency: [for], data = [adapter] this.repositoryObservable.unregister(adapter); // depends on control dependency: [for], data = [adapter] } this.listeners.clear(); } }
public class class_name { @Nullable public UnixPath getFileName() { if (path.isEmpty()) { return EMPTY_PATH; } else if (isRoot()) { return null; } else { List<String> parts = getParts(); String last = parts.get(parts.size() - 1); return parts.size() == 1 && path.equals(last) ? this : new UnixPath(permitEmptyComponents, last); } } }
public class class_name { @Nullable public UnixPath getFileName() { if (path.isEmpty()) { return EMPTY_PATH; // depends on control dependency: [if], data = [none] } else if (isRoot()) { return null; // depends on control dependency: [if], data = [none] } else { List<String> parts = getParts(); String last = parts.get(parts.size() - 1); return parts.size() == 1 && path.equals(last) ? this : new UnixPath(permitEmptyComponents, last); // depends on control dependency: [if], data = [none] } } }
public class class_name { public boolean canCreateNodesAndPublishItems() throws NoResponseException, NotConnectedException, InterruptedException, XMPPErrorException { LeafNode leafNode = null; try { leafNode = createNode(); } catch (XMPPErrorException e) { if (e.getStanzaError().getCondition() == StanzaError.Condition.forbidden) { return false; } throw e; } finally { if (leafNode != null) { deleteNode(leafNode.getId()); } } return true; } }
public class class_name { public boolean canCreateNodesAndPublishItems() throws NoResponseException, NotConnectedException, InterruptedException, XMPPErrorException { LeafNode leafNode = null; try { leafNode = createNode(); } catch (XMPPErrorException e) { if (e.getStanzaError().getCondition() == StanzaError.Condition.forbidden) { return false; // depends on control dependency: [if], data = [none] } throw e; } finally { if (leafNode != null) { deleteNode(leafNode.getId()); // depends on control dependency: [if], data = [(leafNode] } } return true; } }
public class class_name { public Tile getTile (int tileIndex, Colorization[] zations) { Tile tile = null; // first look in the active set; if it's in use by anyone or in the cache, it will be in // the active set synchronized (_atiles) { _key.tileSet = this; _key.tileIndex = tileIndex; _key.zations = zations; SoftReference<Tile> sref = _atiles.get(_key); if (sref != null) { tile = sref.get(); } } // if it's not in the active set, it's not in memory; so load it if (tile == null) { tile = createTile(); tile.key = new Tile.Key(this, tileIndex, zations); initTile(tile, tileIndex, zations); synchronized (_atiles) { _atiles.put(tile.key, new SoftReference<Tile>(tile)); } } // periodically report our image cache performance reportCachePerformance(); return tile; } }
public class class_name { public Tile getTile (int tileIndex, Colorization[] zations) { Tile tile = null; // first look in the active set; if it's in use by anyone or in the cache, it will be in // the active set synchronized (_atiles) { _key.tileSet = this; _key.tileIndex = tileIndex; _key.zations = zations; SoftReference<Tile> sref = _atiles.get(_key); if (sref != null) { tile = sref.get(); // depends on control dependency: [if], data = [none] } } // if it's not in the active set, it's not in memory; so load it if (tile == null) { tile = createTile(); // depends on control dependency: [if], data = [none] tile.key = new Tile.Key(this, tileIndex, zations); // depends on control dependency: [if], data = [none] initTile(tile, tileIndex, zations); // depends on control dependency: [if], data = [(tile] synchronized (_atiles) { // depends on control dependency: [if], data = [none] _atiles.put(tile.key, new SoftReference<Tile>(tile)); } } // periodically report our image cache performance reportCachePerformance(); return tile; } }
public class class_name { private String generateFileName() { int checksum = 1; Set<TypeId<?>> typesKeySet = types.keySet(); Iterator<TypeId<?>> it = typesKeySet.iterator(); int[] checksums = new int[typesKeySet.size()]; int i = 0; while (it.hasNext()) { TypeId<?> typeId = it.next(); TypeDeclaration decl = getTypeDeclaration(typeId); Set<MethodId> methodSet = decl.methods.keySet(); if (decl.supertype != null) { int sum = 31 * decl.supertype.hashCode() + decl.interfaces.hashCode(); checksums[i++] = 31 * sum + methodSet.hashCode(); } } Arrays.sort(checksums); for (int sum : checksums) { checksum *= 31; checksum += sum; } return "Generated_" + checksum +".jar"; } }
public class class_name { private String generateFileName() { int checksum = 1; Set<TypeId<?>> typesKeySet = types.keySet(); Iterator<TypeId<?>> it = typesKeySet.iterator(); int[] checksums = new int[typesKeySet.size()]; int i = 0; while (it.hasNext()) { TypeId<?> typeId = it.next(); TypeDeclaration decl = getTypeDeclaration(typeId); Set<MethodId> methodSet = decl.methods.keySet(); if (decl.supertype != null) { int sum = 31 * decl.supertype.hashCode() + decl.interfaces.hashCode(); checksums[i++] = 31 * sum + methodSet.hashCode(); // depends on control dependency: [if], data = [none] } } Arrays.sort(checksums); for (int sum : checksums) { checksum *= 31; // depends on control dependency: [for], data = [sum] checksum += sum; // depends on control dependency: [for], data = [sum] } return "Generated_" + checksum +".jar"; } }
public class class_name { private void introspectSerializer(MapSerializer mapSerializer, MapTypeJrapidoc type) { try { Field keyTypeField = mapSerializer.getClass().getDeclaredField("_keyType"); keyTypeField.setAccessible(true); JavaType keyType = (JavaType) keyTypeField.get(mapSerializer); JavaType valueType = mapSerializer.getContentType(); getType(keyType); getType(valueType); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
public class class_name { private void introspectSerializer(MapSerializer mapSerializer, MapTypeJrapidoc type) { try { Field keyTypeField = mapSerializer.getClass().getDeclaredField("_keyType"); keyTypeField.setAccessible(true); // depends on control dependency: [try], data = [none] JavaType keyType = (JavaType) keyTypeField.get(mapSerializer); JavaType valueType = mapSerializer.getContentType(); getType(keyType); // depends on control dependency: [try], data = [none] getType(valueType); // depends on control dependency: [try], data = [none] } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { // depends on control dependency: [catch], data = [none] e.printStackTrace(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public com.google.privacy.dlp.v2.TransientCryptoKey getTransient() { if (sourceCase_ == 1) { return (com.google.privacy.dlp.v2.TransientCryptoKey) source_; } return com.google.privacy.dlp.v2.TransientCryptoKey.getDefaultInstance(); } }
public class class_name { public com.google.privacy.dlp.v2.TransientCryptoKey getTransient() { if (sourceCase_ == 1) { return (com.google.privacy.dlp.v2.TransientCryptoKey) source_; // depends on control dependency: [if], data = [none] } return com.google.privacy.dlp.v2.TransientCryptoKey.getDefaultInstance(); } }
public class class_name { public boolean expandArchive(String sourcePath, String targetPath) { try { return ArchiveExpander.coreExpandArchive(sourcePath, targetPath); } catch (IOException e) { FFDCFilter.processException(e, getClass().getName(), "expandArchive"); } return false; } }
public class class_name { public boolean expandArchive(String sourcePath, String targetPath) { try { return ArchiveExpander.coreExpandArchive(sourcePath, targetPath); // depends on control dependency: [try], data = [none] } catch (IOException e) { FFDCFilter.processException(e, getClass().getName(), "expandArchive"); } // depends on control dependency: [catch], data = [none] return false; } }
public class class_name { @Override public void deleteHistoricIdentityLink(String id) { if (isHistoryLevelAtLeast(HistoryLevel.AUDIT)) { getHistoricIdentityLinkEntityManager().delete(id); } } }
public class class_name { @Override public void deleteHistoricIdentityLink(String id) { if (isHistoryLevelAtLeast(HistoryLevel.AUDIT)) { getHistoricIdentityLinkEntityManager().delete(id); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void initHandlers() { registerHandler(Boolean.class,BooleanOptionHandler.class); registerHandler(boolean.class,BooleanOptionHandler.class); registerHandler(File.class,FileOptionHandler.class); registerHandler(URL.class, URLOptionHandler.class); registerHandler(URI.class, URIOptionHandler.class); registerHandler(Integer.class,IntOptionHandler.class); registerHandler(int.class,IntOptionHandler.class); registerHandler(Double.class, DoubleOptionHandler.class); registerHandler(double.class,DoubleOptionHandler.class); registerHandler(String.class,StringOptionHandler.class); registerHandler(Byte.class, ByteOptionHandler.class); registerHandler(byte.class, ByteOptionHandler.class); registerHandler(Character.class, CharOptionHandler.class); registerHandler(char.class, CharOptionHandler.class); registerHandler(Float.class, FloatOptionHandler.class); registerHandler(float.class, FloatOptionHandler.class); registerHandler(Long.class, LongOptionHandler.class); registerHandler(long.class, LongOptionHandler.class); registerHandler(Short.class, ShortOptionHandler.class); registerHandler(short.class, ShortOptionHandler.class); registerHandler(InetAddress.class, InetAddressOptionHandler.class); registerHandler(Pattern.class, PatternOptionHandler.class); // enum is a special case registerHandler(Map.class,MapOptionHandler.class); try { Class p = Class.forName("java.nio.file.Path"); registerHandler(p, PathOptionHandler.class); } catch (ClassNotFoundException e) { // running in Java6 or earlier } } }
public class class_name { private void initHandlers() { registerHandler(Boolean.class,BooleanOptionHandler.class); registerHandler(boolean.class,BooleanOptionHandler.class); registerHandler(File.class,FileOptionHandler.class); registerHandler(URL.class, URLOptionHandler.class); registerHandler(URI.class, URIOptionHandler.class); registerHandler(Integer.class,IntOptionHandler.class); registerHandler(int.class,IntOptionHandler.class); registerHandler(Double.class, DoubleOptionHandler.class); registerHandler(double.class,DoubleOptionHandler.class); registerHandler(String.class,StringOptionHandler.class); registerHandler(Byte.class, ByteOptionHandler.class); registerHandler(byte.class, ByteOptionHandler.class); registerHandler(Character.class, CharOptionHandler.class); registerHandler(char.class, CharOptionHandler.class); registerHandler(Float.class, FloatOptionHandler.class); registerHandler(float.class, FloatOptionHandler.class); registerHandler(Long.class, LongOptionHandler.class); registerHandler(long.class, LongOptionHandler.class); registerHandler(Short.class, ShortOptionHandler.class); registerHandler(short.class, ShortOptionHandler.class); registerHandler(InetAddress.class, InetAddressOptionHandler.class); registerHandler(Pattern.class, PatternOptionHandler.class); // enum is a special case registerHandler(Map.class,MapOptionHandler.class); try { Class p = Class.forName("java.nio.file.Path"); registerHandler(p, PathOptionHandler.class); } catch (ClassNotFoundException e) { // running in Java6 or earlier } // depends on control dependency: [catch], data = [none] } }
public class class_name { public IoFuture await() throws InterruptedException { synchronized (lock) { while (!ready) { waiters++; try { // Wait for a notify, or if no notify is called, // assume that we have a deadlock and exit the // loop to check for a potential deadlock. lock.wait(DEAD_LOCK_CHECK_INTERVAL); } finally { waiters--; if (!ready) { checkDeadLock(); } } } } return this; } }
public class class_name { public IoFuture await() throws InterruptedException { synchronized (lock) { while (!ready) { waiters++; // depends on control dependency: [while], data = [none] try { // Wait for a notify, or if no notify is called, // assume that we have a deadlock and exit the // loop to check for a potential deadlock. lock.wait(DEAD_LOCK_CHECK_INTERVAL); // depends on control dependency: [try], data = [none] } finally { waiters--; if (!ready) { checkDeadLock(); // depends on control dependency: [if], data = [none] } } } } return this; } }
public class class_name { protected static BufferedImage createBufferedImage(int width, int height, boolean hasAlpha) { BufferedImage bimage = null; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); try { // Determine the type of transparency of the new buffered image int transparency = Transparency.OPAQUE; if (hasAlpha) { transparency = Transparency.TRANSLUCENT; } // Create the buffered image GraphicsDevice gs = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gs.getDefaultConfiguration(); bimage = gc.createCompatibleImage(width, height, transparency); } catch (HeadlessException e) { // The system does not have a screen } if (bimage == null) { // Create a buffered image using the default color model int type = BufferedImage.TYPE_INT_RGB; if (hasAlpha) { type = BufferedImage.TYPE_INT_ARGB; } bimage = new BufferedImage(width, height, type); } return bimage; } }
public class class_name { protected static BufferedImage createBufferedImage(int width, int height, boolean hasAlpha) { BufferedImage bimage = null; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); try { // Determine the type of transparency of the new buffered image int transparency = Transparency.OPAQUE; if (hasAlpha) { transparency = Transparency.TRANSLUCENT; // depends on control dependency: [if], data = [none] } // Create the buffered image GraphicsDevice gs = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gs.getDefaultConfiguration(); bimage = gc.createCompatibleImage(width, height, transparency); // depends on control dependency: [try], data = [none] } catch (HeadlessException e) { // The system does not have a screen } // depends on control dependency: [catch], data = [none] if (bimage == null) { // Create a buffered image using the default color model int type = BufferedImage.TYPE_INT_RGB; if (hasAlpha) { type = BufferedImage.TYPE_INT_ARGB; // depends on control dependency: [if], data = [none] } bimage = new BufferedImage(width, height, type); // depends on control dependency: [if], data = [none] } return bimage; } }
public class class_name { public DescribeFolderContentsResult withFolders(FolderMetadata... folders) { if (this.folders == null) { setFolders(new java.util.ArrayList<FolderMetadata>(folders.length)); } for (FolderMetadata ele : folders) { this.folders.add(ele); } return this; } }
public class class_name { public DescribeFolderContentsResult withFolders(FolderMetadata... folders) { if (this.folders == null) { setFolders(new java.util.ArrayList<FolderMetadata>(folders.length)); // depends on control dependency: [if], data = [none] } for (FolderMetadata ele : folders) { this.folders.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public ResultSet executeWithKeys() { context = startContext(connection(), metadata, entity); try { PreparedStatement stmt = null; if (batches.isEmpty()) { stmt = createStatement(true); listeners.notifyInsert(entity, metadata, columns, values, subQuery); listeners.preExecute(context); stmt.executeUpdate(); listeners.executed(context); } else if (batchToBulk) { stmt = createStatement(true); listeners.notifyInserts(entity, metadata, batches); listeners.preExecute(context); stmt.executeUpdate(); listeners.executed(context); } else { Collection<PreparedStatement> stmts = createStatements(true); if (stmts != null && stmts.size() > 1) { throw new IllegalStateException("executeWithKeys called with batch statement and multiple SQL strings"); } stmt = stmts.iterator().next(); listeners.notifyInserts(entity, metadata, batches); listeners.preExecute(context); stmt.executeBatch(); listeners.executed(context); } final Statement stmt2 = stmt; ResultSet rs = stmt.getGeneratedKeys(); return new ResultSetAdapter(rs) { @Override public void close() throws SQLException { try { super.close(); } finally { stmt2.close(); reset(); endContext(context); } } }; } catch (SQLException e) { onException(context, e); reset(); endContext(context); throw configuration.translate(queryString, constants, e); } } }
public class class_name { public ResultSet executeWithKeys() { context = startContext(connection(), metadata, entity); try { PreparedStatement stmt = null; if (batches.isEmpty()) { stmt = createStatement(true); // depends on control dependency: [if], data = [none] listeners.notifyInsert(entity, metadata, columns, values, subQuery); // depends on control dependency: [if], data = [none] listeners.preExecute(context); // depends on control dependency: [if], data = [none] stmt.executeUpdate(); // depends on control dependency: [if], data = [none] listeners.executed(context); // depends on control dependency: [if], data = [none] } else if (batchToBulk) { stmt = createStatement(true); // depends on control dependency: [if], data = [none] listeners.notifyInserts(entity, metadata, batches); // depends on control dependency: [if], data = [none] listeners.preExecute(context); // depends on control dependency: [if], data = [none] stmt.executeUpdate(); // depends on control dependency: [if], data = [none] listeners.executed(context); // depends on control dependency: [if], data = [none] } else { Collection<PreparedStatement> stmts = createStatements(true); if (stmts != null && stmts.size() > 1) { throw new IllegalStateException("executeWithKeys called with batch statement and multiple SQL strings"); } stmt = stmts.iterator().next(); // depends on control dependency: [if], data = [none] listeners.notifyInserts(entity, metadata, batches); // depends on control dependency: [if], data = [none] listeners.preExecute(context); // depends on control dependency: [if], data = [none] stmt.executeBatch(); // depends on control dependency: [if], data = [none] listeners.executed(context); // depends on control dependency: [if], data = [none] } final Statement stmt2 = stmt; ResultSet rs = stmt.getGeneratedKeys(); return new ResultSetAdapter(rs) { @Override public void close() throws SQLException { try { super.close(); } finally { stmt2.close(); reset(); endContext(context); } } }; } catch (SQLException e) { onException(context, e); reset(); endContext(context); throw configuration.translate(queryString, constants, e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { static String unknownQualityScores(final int length) { StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { sb.append("B"); } return sb.toString(); } }
public class class_name { static String unknownQualityScores(final int length) { StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { sb.append("B"); // depends on control dependency: [for], data = [none] } return sb.toString(); } }
public class class_name { @Override public void updateAfterMisfire(org.quartz.core.Calendar cal) { int instr = getMisfireInstruction(); if (instr == Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY) { return; } if (instr == MISFIRE_INSTRUCTION_SMART_POLICY) { instr = MISFIRE_INSTRUCTION_FIRE_ONCE_NOW; } if (instr == MISFIRE_INSTRUCTION_DO_NOTHING) { Date newFireTime = getFireTimeAfter(new Date()); while (newFireTime != null && cal != null && !cal.isTimeIncluded(newFireTime.getTime())) { newFireTime = getFireTimeAfter(newFireTime); } setNextFireTime(newFireTime); } else if (instr == MISFIRE_INSTRUCTION_FIRE_ONCE_NOW) { setNextFireTime(new Date()); } } }
public class class_name { @Override public void updateAfterMisfire(org.quartz.core.Calendar cal) { int instr = getMisfireInstruction(); if (instr == Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY) { return; // depends on control dependency: [if], data = [none] } if (instr == MISFIRE_INSTRUCTION_SMART_POLICY) { instr = MISFIRE_INSTRUCTION_FIRE_ONCE_NOW; // depends on control dependency: [if], data = [none] } if (instr == MISFIRE_INSTRUCTION_DO_NOTHING) { Date newFireTime = getFireTimeAfter(new Date()); while (newFireTime != null && cal != null && !cal.isTimeIncluded(newFireTime.getTime())) { newFireTime = getFireTimeAfter(newFireTime); // depends on control dependency: [while], data = [(newFireTime] } setNextFireTime(newFireTime); // depends on control dependency: [if], data = [none] } else if (instr == MISFIRE_INSTRUCTION_FIRE_ONCE_NOW) { setNextFireTime(new Date()); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public EEnum getIfcTimeSeriesDataTypeEnum() { if (ifcTimeSeriesDataTypeEnumEEnum == null) { ifcTimeSeriesDataTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(1088); } return ifcTimeSeriesDataTypeEnumEEnum; } }
public class class_name { @Override public EEnum getIfcTimeSeriesDataTypeEnum() { if (ifcTimeSeriesDataTypeEnumEEnum == null) { ifcTimeSeriesDataTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(1088); // depends on control dependency: [if], data = [none] } return ifcTimeSeriesDataTypeEnumEEnum; } }
public class class_name { private void _registerAsynchConsumerCallback(AsynchConsumerCallback callback, int maxActiveMessages, long messageLockExpiry, int maxBatchSize, OrderingContext orderContext, int maxSequentialFailures, //SIB0115d.comms long hiddenMessageDelay, boolean stoppable) //472879 throws SISessionUnavailableException, SISessionDroppedException, SIConnectionUnavailableException, SIConnectionDroppedException, SIErrorException, SIIncorrectCallException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "_registerAsynchConsumerCallback", new Object[] { callback, maxActiveMessages, messageLockExpiry, maxBatchSize, orderContext, maxSequentialFailures, hiddenMessageDelay, stoppable }); boolean completed = false; if (callback != null) { // Before we flow the register, ensure we increment the use count on the order context // if they passed one. This is to ensure one gets created if it does not exist // already. OrderingContextProxy oc = (OrderingContextProxy) orderContext; // Did they supply an ordering context for us to use? if (oc == null) { // If they did not, see if we already have an ordered async consumer registered, If so, // decrement the use count on the old order context and discard it. if (currentOrderingContext != null) { currentOrderingContext.decrementUseCount(); currentOrderingContext = null; } } // They did supply an ordering context to use else { // Do we already have an un-ordered async consumer registered? // If so, we should increment the count on the new one. if (currentOrderingContext == null && asynchConsumerRegistered) { oc.incrementUseCount(); } else if (currentOrderingContext != null && asynchConsumerRegistered) { // Do we already have an ordered async consumer registered? if (oc == currentOrderingContext) { // Is it the same? If it is - do nothing. } else { // If it is not the same, decrement the old, and increment the new. currentOrderingContext.decrementUseCount(); oc.incrementUseCount(); } } // Otherwise, new registration - so increment the use count else if (!asynchConsumerRegistered) { oc.incrementUseCount(); } } try { try { if (isReadAhead) { if ((maxActiveMessages != 0) || (messageLockExpiry != 0) || (stoppable)) //472879 { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled() && stoppable) { //SIB0115d.comms,472879 SibTr.debug(this, tc, "Forcing Read Ahead off because callback is Stoppable"); //SIB0115d.comms } //SIB0115d.comms // If we had a read ahead proxy queue and someone has attempted to // register an asynchronous consumer with either maxActiveMessages // or messageLockExpiry - trash the read ahead proxy queue and // substitute it with an asynch proxy queue. This is because we // currently do not support these options on read ahead. Using a s // Stoppable callback also forced read ahead off. short seqNumber = proxyQueue.getCurrentMessageBatchSequenceNumber(); short id = proxyQueue.getId(); ProxyQueueConversationGroup pqcg = ((ClientConversationState) getConversation().getAttachment()).getProxyQueueConversationGroup(); seqNumber++; isReadAhead = false; proxyQueue = pqcg.createAsynchConsumerProxyQueue(id, seqNumber, orderContext); proxyQueue.setConsumerSession(this); proxyQueue.setAsynchCallback(callback, maxActiveMessages, messageLockExpiry, maxBatchSize, orderContext, maxSequentialFailures, hiddenMessageDelay, stoppable); //SIB0115d.comms,472879 } else { proxyQueue.setAsynchCallback(callback, maxActiveMessages, messageLockExpiry, maxBatchSize, null, maxSequentialFailures, //SIB0115d.comms hiddenMessageDelay, stoppable); //472879 } } // If async proxy queue is not null, then we already have a callback registered // and the caller would like to replace the callback or switch to / from // ordered delivery else if (proxyQueue != null) // No readahead { proxyQueue.setAsynchCallback(callback, maxActiveMessages, messageLockExpiry, maxBatchSize, orderContext, maxSequentialFailures, //SIB0115d.comms hiddenMessageDelay, stoppable); //472879 } else // Create a new Proxy Queue { ClientConversationState clientConvState = (ClientConversationState) getConversation().getAttachment(); ProxyQueueConversationGroup pqcg = clientConvState.getProxyQueueConversationGroup(); if (pqcg == null) { ProxyQueueConversationGroupFactory pqFact = ProxyQueueConversationGroupFactory.getRef(); pqcg = pqFact.create(getConversation()); clientConvState.setProxyQueueConversationGroup(pqcg); } proxyQueue = pqcg.createAsynchConsumerProxyQueue(orderContext); proxyQueue.setConsumerSession(this); proxyQueue.setAsynchCallback(callback, maxActiveMessages, messageLockExpiry, maxBatchSize, orderContext, maxSequentialFailures, //SIB0115d.comms hiddenMessageDelay, stoppable); //472879 } } catch (SIResourceException e) { // We failed to re-register the proxy queue. This could be because the call to create // a proxy queue or destroy a proxy queue failed. We must rethrow this as an // SIConnectionLostException as we will be unsure what the state of the system is FFDCFilter.processException(e, CLASS_NAME + "._registerAsynchConsumerCallback", CommsConstants.CONSUMERSESSIONPROXY_REGASYNC_01, this); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Caught a resource exception", e); // And rethrow throw new SIConnectionDroppedException(e.getMessage(), e); } completed = true; // And stash the order context in case we need it later currentOrderingContext = oc; asynchConsumerRegistered = true; } finally { // Ensure we decrement again if we failed if (!completed && oc != null) oc.decrementUseCount(); } } else { // User supplied a null callback - this is the same as a de-reg deregisterAsynchConsumerCallback(); // Ensure we decrement the count when we de-register if (currentOrderingContext != null) { currentOrderingContext.decrementUseCount(); // And don't reference it anymore currentOrderingContext = null; } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "_registerAsynchConsumerCallback"); } }
public class class_name { private void _registerAsynchConsumerCallback(AsynchConsumerCallback callback, int maxActiveMessages, long messageLockExpiry, int maxBatchSize, OrderingContext orderContext, int maxSequentialFailures, //SIB0115d.comms long hiddenMessageDelay, boolean stoppable) //472879 throws SISessionUnavailableException, SISessionDroppedException, SIConnectionUnavailableException, SIConnectionDroppedException, SIErrorException, SIIncorrectCallException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "_registerAsynchConsumerCallback", new Object[] { callback, maxActiveMessages, messageLockExpiry, maxBatchSize, orderContext, maxSequentialFailures, hiddenMessageDelay, stoppable }); boolean completed = false; if (callback != null) { // Before we flow the register, ensure we increment the use count on the order context // if they passed one. This is to ensure one gets created if it does not exist // already. OrderingContextProxy oc = (OrderingContextProxy) orderContext; // Did they supply an ordering context for us to use? if (oc == null) { // If they did not, see if we already have an ordered async consumer registered, If so, // decrement the use count on the old order context and discard it. if (currentOrderingContext != null) { currentOrderingContext.decrementUseCount(); // depends on control dependency: [if], data = [none] currentOrderingContext = null; // depends on control dependency: [if], data = [none] } } // They did supply an ordering context to use else { // Do we already have an un-ordered async consumer registered? // If so, we should increment the count on the new one. if (currentOrderingContext == null && asynchConsumerRegistered) { oc.incrementUseCount(); // depends on control dependency: [if], data = [none] } else if (currentOrderingContext != null && asynchConsumerRegistered) { // Do we already have an ordered async consumer registered? if (oc == currentOrderingContext) { // Is it the same? If it is - do nothing. } else { // If it is not the same, decrement the old, and increment the new. currentOrderingContext.decrementUseCount(); // depends on control dependency: [if], data = [none] oc.incrementUseCount(); // depends on control dependency: [if], data = [none] } } // Otherwise, new registration - so increment the use count else if (!asynchConsumerRegistered) { oc.incrementUseCount(); // depends on control dependency: [if], data = [none] } } try { try { if (isReadAhead) { if ((maxActiveMessages != 0) || (messageLockExpiry != 0) || (stoppable)) //472879 { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled() && stoppable) { //SIB0115d.comms,472879 SibTr.debug(this, tc, "Forcing Read Ahead off because callback is Stoppable"); //SIB0115d.comms // depends on control dependency: [if], data = [none] } //SIB0115d.comms // If we had a read ahead proxy queue and someone has attempted to // register an asynchronous consumer with either maxActiveMessages // or messageLockExpiry - trash the read ahead proxy queue and // substitute it with an asynch proxy queue. This is because we // currently do not support these options on read ahead. Using a s // Stoppable callback also forced read ahead off. short seqNumber = proxyQueue.getCurrentMessageBatchSequenceNumber(); short id = proxyQueue.getId(); ProxyQueueConversationGroup pqcg = ((ClientConversationState) getConversation().getAttachment()).getProxyQueueConversationGroup(); seqNumber++; // depends on control dependency: [if], data = [none] isReadAhead = false; // depends on control dependency: [if], data = [none] proxyQueue = pqcg.createAsynchConsumerProxyQueue(id, seqNumber, orderContext); // depends on control dependency: [if], data = [none] proxyQueue.setConsumerSession(this); // depends on control dependency: [if], data = [none] proxyQueue.setAsynchCallback(callback, maxActiveMessages, messageLockExpiry, maxBatchSize, orderContext, maxSequentialFailures, hiddenMessageDelay, stoppable); //SIB0115d.comms,472879 // depends on control dependency: [if], data = [none] } else { proxyQueue.setAsynchCallback(callback, maxActiveMessages, messageLockExpiry, maxBatchSize, null, maxSequentialFailures, //SIB0115d.comms hiddenMessageDelay, stoppable); //472879 // depends on control dependency: [if], data = [none] } } // If async proxy queue is not null, then we already have a callback registered // and the caller would like to replace the callback or switch to / from // ordered delivery else if (proxyQueue != null) // No readahead { proxyQueue.setAsynchCallback(callback, maxActiveMessages, messageLockExpiry, maxBatchSize, orderContext, maxSequentialFailures, //SIB0115d.comms hiddenMessageDelay, stoppable); //472879 // depends on control dependency: [if], data = [none] } else // Create a new Proxy Queue { ClientConversationState clientConvState = (ClientConversationState) getConversation().getAttachment(); ProxyQueueConversationGroup pqcg = clientConvState.getProxyQueueConversationGroup(); if (pqcg == null) { ProxyQueueConversationGroupFactory pqFact = ProxyQueueConversationGroupFactory.getRef(); pqcg = pqFact.create(getConversation()); // depends on control dependency: [if], data = [none] clientConvState.setProxyQueueConversationGroup(pqcg); // depends on control dependency: [if], data = [(pqcg] } proxyQueue = pqcg.createAsynchConsumerProxyQueue(orderContext); // depends on control dependency: [if], data = [none] proxyQueue.setConsumerSession(this); // depends on control dependency: [if], data = [none] proxyQueue.setAsynchCallback(callback, maxActiveMessages, messageLockExpiry, maxBatchSize, orderContext, maxSequentialFailures, //SIB0115d.comms hiddenMessageDelay, stoppable); //472879 // depends on control dependency: [if], data = [none] } } catch (SIResourceException e) { // We failed to re-register the proxy queue. This could be because the call to create // a proxy queue or destroy a proxy queue failed. We must rethrow this as an // SIConnectionLostException as we will be unsure what the state of the system is FFDCFilter.processException(e, CLASS_NAME + "._registerAsynchConsumerCallback", CommsConstants.CONSUMERSESSIONPROXY_REGASYNC_01, this); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Caught a resource exception", e); // And rethrow throw new SIConnectionDroppedException(e.getMessage(), e); } // depends on control dependency: [catch], data = [none] completed = true; // And stash the order context in case we need it later currentOrderingContext = oc; asynchConsumerRegistered = true; } finally { // Ensure we decrement again if we failed if (!completed && oc != null) oc.decrementUseCount(); } } else { // User supplied a null callback - this is the same as a de-reg deregisterAsynchConsumerCallback(); // Ensure we decrement the count when we de-register if (currentOrderingContext != null) { currentOrderingContext.decrementUseCount(); // And don't reference it anymore currentOrderingContext = null; } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "_registerAsynchConsumerCallback"); } }
public class class_name { @Override public Bus<M> send(M message) { logger.trace("starting dispatching message '{}' to destinations", message); for(Destination<M> destination : destinations) { logger.trace("dispatching to destination {}", destination); destination.onMessage(message); } logger.trace("done dispatching message '{}' to destinations", message); return this; } }
public class class_name { @Override public Bus<M> send(M message) { logger.trace("starting dispatching message '{}' to destinations", message); for(Destination<M> destination : destinations) { logger.trace("dispatching to destination {}", destination); // depends on control dependency: [for], data = [destination] destination.onMessage(message); // depends on control dependency: [for], data = [destination] } logger.trace("done dispatching message '{}' to destinations", message); return this; } }
public class class_name { @Override protected void preparePaintComponent(final Request request) { if (getAttribute(ERROR_KEY) == null) { try { for (int i = 0; i < shim.getChildCount(); i++) { shim.getChildAt(i).preparePaint(request); } } catch (final Exception e) { if (isAjaxOrTargetedRequest(request)) { throw new SystemException(e.getMessage(), e); } else { setAttribute(ERROR_KEY, e); } } } } }
public class class_name { @Override protected void preparePaintComponent(final Request request) { if (getAttribute(ERROR_KEY) == null) { try { for (int i = 0; i < shim.getChildCount(); i++) { shim.getChildAt(i).preparePaint(request); // depends on control dependency: [for], data = [i] } } catch (final Exception e) { if (isAjaxOrTargetedRequest(request)) { throw new SystemException(e.getMessage(), e); } else { setAttribute(ERROR_KEY, e); // depends on control dependency: [if], data = [none] } } // depends on control dependency: [catch], data = [none] } } }
public class class_name { private String bytesToString(byte[] bytes, boolean truncate) { CharsetDecoder decoder = Charset.defaultCharset() .newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); CharBuffer charBuffer; try { charBuffer = decoder.decode(byteBuffer); } catch (CharacterCodingException e) { // Shouldn't happen due to choosing REPLACE above, but Java makes us catch it anyway. throw new RuntimeException(e); } String s = charBuffer.toString(); if (truncate && s.length() > TRUNCATED_STRING_MAX_LEN) { return new StringBuilder().append(s, 0, TRUNCATED_STRING_MAX_LEN).append("[...]").toString(); } else { return s; } } }
public class class_name { private String bytesToString(byte[] bytes, boolean truncate) { CharsetDecoder decoder = Charset.defaultCharset() .newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); CharBuffer charBuffer; try { charBuffer = decoder.decode(byteBuffer); // depends on control dependency: [try], data = [none] } catch (CharacterCodingException e) { // Shouldn't happen due to choosing REPLACE above, but Java makes us catch it anyway. throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] String s = charBuffer.toString(); if (truncate && s.length() > TRUNCATED_STRING_MAX_LEN) { return new StringBuilder().append(s, 0, TRUNCATED_STRING_MAX_LEN).append("[...]").toString(); // depends on control dependency: [if], data = [TRUNCATED_STRING_MAX_LEN)] } else { return s; // depends on control dependency: [if], data = [none] } } }
public class class_name { private Term evalIsBlank(Function term) { Term teval = eval(term.getTerm(0)); if (teval instanceof Function) { Function function = (Function) teval; Predicate predicate = function.getFunctionSymbol(); return termFactory.getBooleanConstant(predicate instanceof BNodePredicate); } return term; } }
public class class_name { private Term evalIsBlank(Function term) { Term teval = eval(term.getTerm(0)); if (teval instanceof Function) { Function function = (Function) teval; Predicate predicate = function.getFunctionSymbol(); return termFactory.getBooleanConstant(predicate instanceof BNodePredicate); // depends on control dependency: [if], data = [none] } return term; } }
public class class_name { public List<Entry<String, Object>> getTraceParameterSettings(int index) { List<Entry<String, Object>> result = new ArrayList<Map.Entry<String,Object>>(); List<String> dimensions = getSearchDimensions(); for (int i = 0; i < dimensions.size(); ++i) { String parameter = dimensions.get(i); Object value = m_Trace.get(index).getValue().getValues().getValue(i); Map.Entry<String, Object> current = new AbstractMap.SimpleEntry<String,Object>(parameter,value); result.add(i, current); } return result; } }
public class class_name { public List<Entry<String, Object>> getTraceParameterSettings(int index) { List<Entry<String, Object>> result = new ArrayList<Map.Entry<String,Object>>(); List<String> dimensions = getSearchDimensions(); for (int i = 0; i < dimensions.size(); ++i) { String parameter = dimensions.get(i); Object value = m_Trace.get(index).getValue().getValues().getValue(i); Map.Entry<String, Object> current = new AbstractMap.SimpleEntry<String,Object>(parameter,value); result.add(i, current); // depends on control dependency: [for], data = [i] } return result; } }
public class class_name { public static void closeSession(String wrapper) { Session session = map.get(wrapper); if (session != null) { Method method; try { method = session.getClass().getDeclaredMethod("protectedClose"); method.setAccessible(true); method.invoke(session); } catch (InvocationTargetException e) { throw new RiverException(e.getCause().getMessage(), e); } catch (Exception e) { throw new RiverException(e); } map.remove(wrapper); } } }
public class class_name { public static void closeSession(String wrapper) { Session session = map.get(wrapper); if (session != null) { Method method; try { method = session.getClass().getDeclaredMethod("protectedClose"); // depends on control dependency: [try], data = [none] method.setAccessible(true); // depends on control dependency: [try], data = [none] method.invoke(session); // depends on control dependency: [try], data = [none] } catch (InvocationTargetException e) { throw new RiverException(e.getCause().getMessage(), e); } catch (Exception e) { // depends on control dependency: [catch], data = [none] throw new RiverException(e); } // depends on control dependency: [catch], data = [none] map.remove(wrapper); // depends on control dependency: [if], data = [none] } } }
public class class_name { public List<DuplicationInfo> getDupIssues() { List<DuplicationInfo> dupIssues = new LinkedList<>(); for (DuplicationInfo dupInfo : dupInfos.values()) { if (dupInfo.hasIssues()) { dupIssues.add(dupInfo); } } return dupIssues; } }
public class class_name { public List<DuplicationInfo> getDupIssues() { List<DuplicationInfo> dupIssues = new LinkedList<>(); for (DuplicationInfo dupInfo : dupInfos.values()) { if (dupInfo.hasIssues()) { dupIssues.add(dupInfo); // depends on control dependency: [if], data = [none] } } return dupIssues; } }
public class class_name { protected final void removeFilter(IoFilterChain filterChain, IoFilter filter) { if (filterChain.contains(filter)) { filterChain.remove(filter); } } }
public class class_name { protected final void removeFilter(IoFilterChain filterChain, IoFilter filter) { if (filterChain.contains(filter)) { filterChain.remove(filter); // depends on control dependency: [if], data = [none] } } }
public class class_name { private static LottieTask<LottieComposition> cache( @Nullable final String cacheKey, Callable<LottieResult<LottieComposition>> callable) { final LottieComposition cachedComposition = cacheKey == null ? null : LottieCompositionCache.getInstance().get(cacheKey); if (cachedComposition != null) { return new LottieTask<>(new Callable<LottieResult<LottieComposition>>() { @Override public LottieResult<LottieComposition> call() { return new LottieResult<>(cachedComposition); } }); } if (cacheKey != null && taskCache.containsKey(cacheKey)) { return taskCache.get(cacheKey); } LottieTask<LottieComposition> task = new LottieTask<>(callable); task.addListener(new LottieListener<LottieComposition>() { @Override public void onResult(LottieComposition result) { if (cacheKey != null) { LottieCompositionCache.getInstance().put(cacheKey, result); } taskCache.remove(cacheKey); } }); task.addFailureListener(new LottieListener<Throwable>() { @Override public void onResult(Throwable result) { taskCache.remove(cacheKey); } }); taskCache.put(cacheKey, task); return task; } }
public class class_name { private static LottieTask<LottieComposition> cache( @Nullable final String cacheKey, Callable<LottieResult<LottieComposition>> callable) { final LottieComposition cachedComposition = cacheKey == null ? null : LottieCompositionCache.getInstance().get(cacheKey); if (cachedComposition != null) { return new LottieTask<>(new Callable<LottieResult<LottieComposition>>() { @Override public LottieResult<LottieComposition> call() { return new LottieResult<>(cachedComposition); } }); // depends on control dependency: [if], data = [none] } if (cacheKey != null && taskCache.containsKey(cacheKey)) { return taskCache.get(cacheKey); // depends on control dependency: [if], data = [(cacheKey] } LottieTask<LottieComposition> task = new LottieTask<>(callable); task.addListener(new LottieListener<LottieComposition>() { @Override public void onResult(LottieComposition result) { if (cacheKey != null) { LottieCompositionCache.getInstance().put(cacheKey, result); // depends on control dependency: [if], data = [(cacheKey] } taskCache.remove(cacheKey); } }); task.addFailureListener(new LottieListener<Throwable>() { @Override public void onResult(Throwable result) { taskCache.remove(cacheKey); } }); taskCache.put(cacheKey, task); return task; } }
public class class_name { protected int newestStamp(int first, int last, int bestStampSoFar) { int bestStamp = bestStampSoFar; for (int i=first; i<=last; ++i) { if (stamp[i] > bestStamp) { bestStamp = stamp[i]; } } return bestStamp; } }
public class class_name { protected int newestStamp(int first, int last, int bestStampSoFar) { int bestStamp = bestStampSoFar; for (int i=first; i<=last; ++i) { if (stamp[i] > bestStamp) { bestStamp = stamp[i]; // depends on control dependency: [if], data = [none] } } return bestStamp; } }
public class class_name { public synchronized EmbeddedGobblin distributeJarWithPriority(String jarPath, int priority) { if (this.distributedJars.containsKey(jarPath)) { this.distributedJars.put(jarPath, Math.min(priority, this.distributedJars.get(jarPath))); } else { this.distributedJars.put(jarPath, priority); } return this; } }
public class class_name { public synchronized EmbeddedGobblin distributeJarWithPriority(String jarPath, int priority) { if (this.distributedJars.containsKey(jarPath)) { this.distributedJars.put(jarPath, Math.min(priority, this.distributedJars.get(jarPath))); // depends on control dependency: [if], data = [none] } else { this.distributedJars.put(jarPath, priority); // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { public static <E> double dotProduct(Counter<E> c, double[] a, Index<E> idx) { double dotProd = 0; for (Map.Entry<E, Double> entry : c.entrySet()) { int keyIdx = idx.indexOf(entry.getKey()); if (keyIdx == -1) { continue; } dotProd += entry.getValue() * a[keyIdx]; } return dotProd; } }
public class class_name { public static <E> double dotProduct(Counter<E> c, double[] a, Index<E> idx) { double dotProd = 0; for (Map.Entry<E, Double> entry : c.entrySet()) { int keyIdx = idx.indexOf(entry.getKey()); if (keyIdx == -1) { continue; } dotProd += entry.getValue() * a[keyIdx]; // depends on control dependency: [for], data = [entry] } return dotProd; } }
public class class_name { protected SortKey getSortKey(String column) { if (column == null) { return null; } if (column.equals(LIST_COLUMN_EMAIL)) { return SortKey.email; } else if (column.equals(LIST_COLUMN_LOGIN)) { return SortKey.loginName; } else if (column.equals(LIST_COLUMN_NAME)) { return SortKey.fullName; } return null; } }
public class class_name { protected SortKey getSortKey(String column) { if (column == null) { return null; // depends on control dependency: [if], data = [none] } if (column.equals(LIST_COLUMN_EMAIL)) { return SortKey.email; // depends on control dependency: [if], data = [none] } else if (column.equals(LIST_COLUMN_LOGIN)) { return SortKey.loginName; // depends on control dependency: [if], data = [none] } else if (column.equals(LIST_COLUMN_NAME)) { return SortKey.fullName; // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { @Override public boolean isTransacted() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.entry(this, tc, "isTransacted"); SibTr.exit(this, tc, "isTransacted", Boolean.valueOf(transacted)); } return transacted; } }
public class class_name { @Override public boolean isTransacted() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.entry(this, tc, "isTransacted"); // depends on control dependency: [if], data = [none] SibTr.exit(this, tc, "isTransacted", Boolean.valueOf(transacted)); // depends on control dependency: [if], data = [none] } return transacted; } }
public class class_name { public boolean supported(Object element) { for (Class c : getSupportedClasses()) { if (c.isAssignableFrom(element.getClass())) { if (log.isLoggable(Level.FINE)) { log.fine(element.getClass().getName() + " will be styled, it is assignable from " + c.getName()); } return true; } } return false; } }
public class class_name { public boolean supported(Object element) { for (Class c : getSupportedClasses()) { if (c.isAssignableFrom(element.getClass())) { if (log.isLoggable(Level.FINE)) { log.fine(element.getClass().getName() + " will be styled, it is assignable from " + c.getName()); // depends on control dependency: [if], data = [none] } return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { void addBlocksToBeInvalidated(List<Block> blocklist) { assert(blocklist != null && blocklist.size() > 0); synchronized (invalidateBlocks) { for(Block blk : blocklist) { invalidateBlocks.add(blk); } } } }
public class class_name { void addBlocksToBeInvalidated(List<Block> blocklist) { assert(blocklist != null && blocklist.size() > 0); synchronized (invalidateBlocks) { for(Block blk : blocklist) { invalidateBlocks.add(blk); // depends on control dependency: [for], data = [blk] } } } }
public class class_name { public static ClientBean unmarshallClient(Map<String, Object> source) { if (source == null) { return null; } ClientBean bean = new ClientBean(); bean.setId(asString(source.get("id"))); bean.setName(asString(source.get("name"))); bean.setDescription(asString(source.get("description"))); bean.setCreatedBy(asString(source.get("createdBy"))); bean.setCreatedOn(asDate(source.get("createdOn"))); postMarshall(bean); return bean; } }
public class class_name { public static ClientBean unmarshallClient(Map<String, Object> source) { if (source == null) { return null; // depends on control dependency: [if], data = [none] } ClientBean bean = new ClientBean(); bean.setId(asString(source.get("id"))); bean.setName(asString(source.get("name"))); bean.setDescription(asString(source.get("description"))); bean.setCreatedBy(asString(source.get("createdBy"))); bean.setCreatedOn(asDate(source.get("createdOn"))); postMarshall(bean); return bean; } }
public class class_name { private List<Path> mergeRoots(Path[] dupRoots) { sortPathByDepth(dupRoots); List<Path> roots = new ArrayList<Path>(); for (Path candidate : dupRoots) { boolean shouldAdd = true; for (Path root : roots) { if (isAncestorPath(root.toUri().getPath(), candidate.toUri().getPath())) { shouldAdd = false; break; } } if (shouldAdd) { roots.add(candidate); } } return roots; } }
public class class_name { private List<Path> mergeRoots(Path[] dupRoots) { sortPathByDepth(dupRoots); List<Path> roots = new ArrayList<Path>(); for (Path candidate : dupRoots) { boolean shouldAdd = true; for (Path root : roots) { if (isAncestorPath(root.toUri().getPath(), candidate.toUri().getPath())) { shouldAdd = false; // depends on control dependency: [if], data = [none] break; } } if (shouldAdd) { roots.add(candidate); // depends on control dependency: [if], data = [none] } } return roots; } }
public class class_name { protected void drainToLoad(long targetLoad, int time, boolean useHandoff) { final double startingLoad = myLoad(); double currentLoad = startingLoad; List<String> drainList = new LinkedList<String>(); Set<String> eligibleToDrop = new LinkedHashSet<String>(cluster.myWorkUnits); eligibleToDrop.removeAll(cluster.workUnitsPeggedToMe); for (String workUnit : eligibleToDrop) { if (currentLoad <= targetLoad) { break; } double workUnitLoad = cluster.getWorkUnitLoad(workUnit); if (workUnitLoad > 0 && (currentLoad - workUnitLoad) > targetLoad) { drainList.add(workUnit); currentLoad -= workUnitLoad; } } int drainInterval = (int) (((double) config.drainTime / drainList.size()) * 1000); TimerTask drainTask = buildDrainTask(drainList, drainInterval, useHandoff, currentLoad); if (!drainList.isEmpty()) { LOG.info("Releasing work units over {} seconds. Current load: {}. Target: {}. Releasing: {}", time, startingLoad, targetLoad, Strings.mkstring(drainList, ", ")); cluster.schedule(drainTask, 0, TimeUnit.SECONDS); } } }
public class class_name { protected void drainToLoad(long targetLoad, int time, boolean useHandoff) { final double startingLoad = myLoad(); double currentLoad = startingLoad; List<String> drainList = new LinkedList<String>(); Set<String> eligibleToDrop = new LinkedHashSet<String>(cluster.myWorkUnits); eligibleToDrop.removeAll(cluster.workUnitsPeggedToMe); for (String workUnit : eligibleToDrop) { if (currentLoad <= targetLoad) { break; } double workUnitLoad = cluster.getWorkUnitLoad(workUnit); if (workUnitLoad > 0 && (currentLoad - workUnitLoad) > targetLoad) { drainList.add(workUnit); // depends on control dependency: [if], data = [none] currentLoad -= workUnitLoad; // depends on control dependency: [if], data = [none] } } int drainInterval = (int) (((double) config.drainTime / drainList.size()) * 1000); TimerTask drainTask = buildDrainTask(drainList, drainInterval, useHandoff, currentLoad); if (!drainList.isEmpty()) { LOG.info("Releasing work units over {} seconds. Current load: {}. Target: {}. Releasing: {}", time, startingLoad, targetLoad, Strings.mkstring(drainList, ", ")); // depends on control dependency: [if], data = [none] cluster.schedule(drainTask, 0, TimeUnit.SECONDS); // depends on control dependency: [if], data = [none] } } }
public class class_name { public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) { // replace alias variable by real name String queryFragment = jpql.replace( "{alias}", queryBuilder.getRequiredAlias(criteria) ); // process parameters for(int i = 1; i <= values.length; i++) { // create positional parameter for this value String paramater = queryBuilder.createPositionalParameter(); /* * Replace variable with generated positional parameter. * Note: This kind of string processing is not very efficient, * because it generates a new string object in each iteration. * But we assume that the number of iterations will be * relative small, so it won't be a real problem. */ queryFragment = queryFragment.replace( "{"+i+"}", paramater); } return queryFragment; } }
public class class_name { public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) { // replace alias variable by real name String queryFragment = jpql.replace( "{alias}", queryBuilder.getRequiredAlias(criteria) ); // process parameters for(int i = 1; i <= values.length; i++) { // create positional parameter for this value String paramater = queryBuilder.createPositionalParameter(); /* * Replace variable with generated positional parameter. * Note: This kind of string processing is not very efficient, * because it generates a new string object in each iteration. * But we assume that the number of iterations will be * relative small, so it won't be a real problem. */ queryFragment = queryFragment.replace( "{"+i+"}", paramater); // depends on control dependency: [for], data = [i] } return queryFragment; } }
public class class_name { protected void _notifyActionComponentsNow() { for( Iterator iter = _mapItems.keySet().iterator(); iter.hasNext(); ) { JComponent item = (JComponent)iter.next(); // if( !item.isShowing() ) // { // continue; // } Action action = (Action)item.getClientProperty( GenericAction.ACTION_PROPERTY ); if( action == null ) { if( item instanceof AbstractButton ) { action = ((AbstractButton)item).getAction(); } if( action == null ) { continue; } } boolean bEnabled = action.isEnabled(); // long lTime = System.currentTime(); // boolean bEnabled = action.isEnabled(); // long diff = System.currentTime() - lTime; // if( diff > 50 ) // { // //!! Uncomment following line and set a break point there to debug poor performing isEnabled() impl. // //action.isEnabled(); // // ConditionalActionHandler cah = null; // if( action instanceof GenericAction ) // { // cah = ((GenericAction)action).getConditionalActionHandler(); // } // System.out.println( "!!!!!!!!!!!!!!!!!!!!!!!\n" + // "An action.isEnabled() impl needs to be optimized.\nIt took " + diff + "ms to complete.\n" + // (cah == null ? "" : "ConditionalActionHandler: " + cah.getClass().getName() + "\n") + // "Debug UpdateNotifier.notifyActionComponentsNow() to find the naughty code." + // "\n!!!!!!!!!!!!!!!!!!!!!!!" ); // } if( item.isEnabled() != bEnabled ) { item.setEnabled( bEnabled ); } // Also handle "selected" state for togglable :) items if( action instanceof GenericAction ) { boolean bSelected = ((GenericAction)action).isSelected(); if( item instanceof JToggleButton ) { JToggleButton tb = (JToggleButton)item; if( tb.isSelected() != bSelected ) { tb.setSelected( bSelected ); } } else if( item instanceof JCheckBoxMenuItem ) { JCheckBoxMenuItem tb = (JCheckBoxMenuItem)item; if( tb.getState() != bSelected ) { tb.setState( bSelected ); } } } } } }
public class class_name { protected void _notifyActionComponentsNow() { for( Iterator iter = _mapItems.keySet().iterator(); iter.hasNext(); ) { JComponent item = (JComponent)iter.next(); // if( !item.isShowing() ) // { // continue; // } Action action = (Action)item.getClientProperty( GenericAction.ACTION_PROPERTY ); if( action == null ) { if( item instanceof AbstractButton ) { action = ((AbstractButton)item).getAction(); // depends on control dependency: [if], data = [none] } if( action == null ) { continue; } } boolean bEnabled = action.isEnabled(); // long lTime = System.currentTime(); // boolean bEnabled = action.isEnabled(); // long diff = System.currentTime() - lTime; // if( diff > 50 ) // { // //!! Uncomment following line and set a break point there to debug poor performing isEnabled() impl. // //action.isEnabled(); // // ConditionalActionHandler cah = null; // if( action instanceof GenericAction ) // { // cah = ((GenericAction)action).getConditionalActionHandler(); // } // System.out.println( "!!!!!!!!!!!!!!!!!!!!!!!\n" + // "An action.isEnabled() impl needs to be optimized.\nIt took " + diff + "ms to complete.\n" + // (cah == null ? "" : "ConditionalActionHandler: " + cah.getClass().getName() + "\n") + // "Debug UpdateNotifier.notifyActionComponentsNow() to find the naughty code." + // "\n!!!!!!!!!!!!!!!!!!!!!!!" ); // } if( item.isEnabled() != bEnabled ) { item.setEnabled( bEnabled ); // depends on control dependency: [if], data = [bEnabled )] } // Also handle "selected" state for togglable :) items if( action instanceof GenericAction ) { boolean bSelected = ((GenericAction)action).isSelected(); if( item instanceof JToggleButton ) { JToggleButton tb = (JToggleButton)item; if( tb.isSelected() != bSelected ) { tb.setSelected( bSelected ); // depends on control dependency: [if], data = [bSelected )] } } else if( item instanceof JCheckBoxMenuItem ) { JCheckBoxMenuItem tb = (JCheckBoxMenuItem)item; if( tb.getState() != bSelected ) { tb.setState( bSelected ); // depends on control dependency: [if], data = [bSelected )] } } } } } }
public class class_name { public static boolean hasAccess(Config config, int type) { boolean has = true; if (config instanceof ConfigWeb) { has = ((ConfigWeb) config).getSecurityManager().getAccess(type) != SecurityManager.VALUE_NO; } return has; } }
public class class_name { public static boolean hasAccess(Config config, int type) { boolean has = true; if (config instanceof ConfigWeb) { has = ((ConfigWeb) config).getSecurityManager().getAccess(type) != SecurityManager.VALUE_NO; // depends on control dependency: [if], data = [none] } return has; } }
public class class_name { public static String getClientIPByHeader(HttpServletRequest request, String... headerNames) { String ip; for (String header : headerNames) { ip = request.getHeader(header); if (false == isUnknow(ip)) { return getMultistageReverseProxyIp(ip); } } ip = request.getRemoteAddr(); return getMultistageReverseProxyIp(ip); } }
public class class_name { public static String getClientIPByHeader(HttpServletRequest request, String... headerNames) { String ip; for (String header : headerNames) { ip = request.getHeader(header); // depends on control dependency: [for], data = [header] if (false == isUnknow(ip)) { return getMultistageReverseProxyIp(ip); // depends on control dependency: [if], data = [none] } } ip = request.getRemoteAddr(); return getMultistageReverseProxyIp(ip); } }
public class class_name { public Response handle( AuthleteApi api, BackchannelAuthenticationRequestHandlerSpi spi, MultivaluedMap<String, String> parameters, String authorization, String[] clientCertificatePath) { try { // Create a handler. BackchannelAuthenticationRequestHandler handler = new BackchannelAuthenticationRequestHandler(api, spi); // Delegate the task to the handler. return handler.handle(parameters, authorization, clientCertificatePath); } catch (WebApplicationException e) { // An error occurred in the handler. onError(e); // Convert the error to a Response. return e.getResponse(); } } }
public class class_name { public Response handle( AuthleteApi api, BackchannelAuthenticationRequestHandlerSpi spi, MultivaluedMap<String, String> parameters, String authorization, String[] clientCertificatePath) { try { // Create a handler. BackchannelAuthenticationRequestHandler handler = new BackchannelAuthenticationRequestHandler(api, spi); // Delegate the task to the handler. return handler.handle(parameters, authorization, clientCertificatePath); // depends on control dependency: [try], data = [none] } catch (WebApplicationException e) { // An error occurred in the handler. onError(e); // Convert the error to a Response. return e.getResponse(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private Object parseOption(UNode optionNode) { if (optionNode.isValue()) { return optionNode.getValue(); } Map<String, Object> optValueMap = new HashMap<>(); for (UNode suboptNode : optionNode.getMemberList()) { optValueMap.put(suboptNode.getName(), parseOption(suboptNode)); } return optValueMap; } }
public class class_name { private Object parseOption(UNode optionNode) { if (optionNode.isValue()) { return optionNode.getValue(); // depends on control dependency: [if], data = [none] } Map<String, Object> optValueMap = new HashMap<>(); for (UNode suboptNode : optionNode.getMemberList()) { optValueMap.put(suboptNode.getName(), parseOption(suboptNode)); // depends on control dependency: [for], data = [suboptNode] } return optValueMap; } }
public class class_name { public final <T extends IInvoice, L extends IInvoiceLine<T>, TL extends AInvTxLn<T>> void makeTotals(final Map<String, Object> pReqVars, final L pLine, final AccSettings pAs, final TaxDestination pTxRules, final IInvTxMeth<T, TL> pInvTxMeth) throws Exception { //all tax lines will be redone: pReqVars.put(pInvTxMeth.getInvTxLnCl().getSimpleName() + "itsOwnerdeepLevel", 1); List<TL> invTxLns = getSrvOrm().retrieveListWithConditions( pReqVars, pInvTxMeth.getInvTxLnCl(), "where ITSOWNER=" + pLine.getItsOwner().getItsId()); pReqVars.remove(pInvTxMeth.getInvTxLnCl().getSimpleName() + "itsOwnerdeepLevel"); for (TL tl : invTxLns) { tl.setTax(null); tl.setTaxableInvBas(BigDecimal.ZERO); tl.setTaxableInvBasFc(BigDecimal.ZERO); tl.setItsTotal(BigDecimal.ZERO); tl.setForeignTotalTaxes(BigDecimal.ZERO); } if (pTxRules != null) { DataTx dtTx = retrieveDataTx(pReqVars, pLine, pAs, pTxRules, pInvTxMeth); if (!pTxRules.getSalTaxUseAggregItBas() && !(pTxRules .getSalTaxIsInvoiceBase() && pLine.getItsOwner().getPriceIncTax())) { //non-aggregate except invoice basis with included taxes: for (int i = 0; i < dtTx.getTxs().size(); i++) { TL tl = findCreateTaxLine(pReqVars, pLine.getItsOwner(), invTxLns, dtTx.getTxs().get(i), false, pInvTxMeth.getFctInvTxLn()); Double txTotd; Double txTotdFc = 0.0; if (!pTxRules.getSalTaxIsInvoiceBase()) { //item basis, taxes excluded/included: txTotd = dtTx.getTxTotTaxb().get(i); txTotdFc = dtTx.getTxTotTaxbFc().get(i); } else { //invoice basis, taxes excluded: txTotd = dtTx.getTxTotTaxb().get(i) * dtTx.getTxPerc().get(i) / 100.0; tl.setTaxableInvBas(BigDecimal.valueOf(dtTx.getTxTotTaxb().get(i))); if (pLine.getItsOwner().getForeignCurrency() != null) { txTotdFc = dtTx.getTxTotTaxbFc().get(i) * dtTx.getTxPerc().get(i) / 100.0; tl.setTaxableInvBasFc(BigDecimal .valueOf(dtTx.getTxTotTaxbFc().get(i))); } } tl.setItsTotal(BigDecimal.valueOf(txTotd).setScale(pAs. getPricePrecision(), pTxRules.getSalTaxRoundMode())); tl.setForeignTotalTaxes(BigDecimal.valueOf(txTotdFc).setScale(pAs. getPricePrecision(), pTxRules.getSalTaxRoundMode())); if (tl.getIsNew()) { getSrvOrm().insertEntity(pReqVars, tl); tl.setIsNew(false); } else { getSrvOrm().updateEntity(pReqVars, tl); } } } else { //non-aggregate invoice basis with included taxes //and aggregate for others: BigDecimal bd100 = new BigDecimal("100.00"); Comparator<InvItemTaxCategoryLine> cmpr = Collections .reverseOrder(new CmprTaxCatLnRate()); for (SalesInvoiceServiceLine txdLn : dtTx.getTxdLns()) { int ti = 0; //aggregate rate line scoped storages: BigDecimal taxAggegated = null; BigDecimal taxAggrAccum = BigDecimal.ZERO; BigDecimal taxAggegatedFc = BigDecimal.ZERO; BigDecimal taxAggrAccumFc = BigDecimal.ZERO; Collections.sort(txdLn.getTaxCategory().getTaxes(), cmpr); for (InvItemTaxCategoryLine itcl : txdLn.getTaxCategory().getTaxes()) { ti++; if (taxAggegated == null) { if (pTxRules.getSalTaxIsInvoiceBase()) { //invoice basis: if (pLine.getItsOwner().getPriceIncTax()) { taxAggegated = txdLn.getItsTotal().subtract(txdLn.getItsTotal() .divide(BigDecimal.ONE.add(txdLn.getTaxCategory().getAggrOnlyPercent() .divide(bd100)), pAs.getPricePrecision(), pTxRules.getSalTaxRoundMode())); if (pLine.getItsOwner().getForeignCurrency() != null) { taxAggegatedFc = txdLn.getForeignTotal().subtract(txdLn .getForeignTotal().divide(BigDecimal.ONE.add(txdLn.getTaxCategory() .getAggrOnlyPercent().divide(bd100)), pAs.getPricePrecision(), pTxRules.getSalTaxRoundMode())); } } else { taxAggegated = txdLn.getSubtotal().multiply(txdLn .getTaxCategory().getAggrOnlyPercent()).divide(bd100, pAs .getPricePrecision(), pTxRules.getSalTaxRoundMode()); if (pLine.getItsOwner().getForeignCurrency() != null) { taxAggegatedFc = txdLn.getForeignSubtotal().multiply(txdLn .getTaxCategory().getAggrOnlyPercent()).divide(bd100, pAs .getPricePrecision(), pTxRules.getSalTaxRoundMode()); } } } else { //item basis, taxes included/excluded taxAggegated = txdLn.getTotalTaxes(); taxAggegatedFc = txdLn.getForeignTotalTaxes(); } } //here total taxes mean total for current tax: if (ti < txdLn.getTaxCategory().getTaxes().size()) { txdLn.setTotalTaxes(taxAggegated.multiply(itcl.getItsPercentage()) .divide(txdLn.getTaxCategory().getAggrOnlyPercent(), pAs.getPricePrecision(), pTxRules.getSalTaxRoundMode())); taxAggrAccum = taxAggrAccum.add(txdLn.getTotalTaxes()); if (pLine.getItsOwner().getForeignCurrency() != null) { txdLn.setForeignTotalTaxes(taxAggegatedFc.multiply(itcl .getItsPercentage()).divide(txdLn.getTaxCategory().getAggrOnlyPercent(), pAs.getPricePrecision(), pTxRules.getSalTaxRoundMode())); taxAggrAccumFc = taxAggrAccumFc.add(txdLn.getForeignTotalTaxes()); } } else { //the rest or only tax: txdLn.setTotalTaxes(taxAggegated.subtract(taxAggrAccum)); if (pLine.getItsOwner().getForeignCurrency() != null) { txdLn.setForeignTotalTaxes(taxAggegatedFc.subtract(taxAggrAccumFc)); } } TL tl = findCreateTaxLine(pReqVars, pLine.getItsOwner(), invTxLns, itcl.getTax(), true, pInvTxMeth.getFctInvTxLn()); tl.setItsTotal(tl.getItsTotal().add(txdLn.getTotalTaxes())); if (pLine.getItsOwner().getForeignCurrency() != null) { tl.setForeignTotalTaxes(tl.getForeignTotalTaxes() .add(txdLn.getForeignTotalTaxes())); } if (pTxRules.getSalTaxIsInvoiceBase()) { if (ti == txdLn.getTaxCategory().getTaxes().size()) { //total line taxes for farther invoice adjusting: txdLn.setTotalTaxes(taxAggegated); txdLn.setTotalTaxes(taxAggegatedFc); } if (!pLine.getItsOwner().getPriceIncTax()) { tl.setTaxableInvBas(tl.getTaxableInvBas() .add(txdLn.getSubtotal())); if (pLine.getItsOwner().getForeignCurrency() != null) { tl.setTaxableInvBasFc(tl.getTaxableInvBasFc() .add(txdLn.getForeignSubtotal())); } } else { tl.setTaxableInvBas(tl.getTaxableInvBas() .add(txdLn.getItsTotal())); if (pLine.getItsOwner().getForeignCurrency() != null) { tl.setTaxableInvBasFc(tl.getTaxableInvBasFc() .add(txdLn.getForeignTotal())); } } } if (tl.getIsNew()) { getSrvOrm().insertEntity(pReqVars, tl); tl.setIsNew(false); } else { getSrvOrm().updateEntity(pReqVars, tl); } } } } if (pTxRules.getSalTaxIsInvoiceBase()) { adjustInvoiceLns(pReqVars, pLine.getItsOwner(), dtTx.getTxdLns(), pAs, pInvTxMeth); } } //delete tax lines with zero tax: for (TL tl : invTxLns) { if (tl.getTax() == null) { getSrvOrm().deleteEntity(pReqVars, tl); } } if (pTxRules != null && !pTxRules.getSalTaxUseAggregItBas() && pLine.getItsOwner().getPriceIncTax()) { String watr = "TTR without aggregate! "; if (pLine.getItsOwner().getDescription() == null) { pLine.getItsOwner().setDescription(watr); } else if (!pLine.getItsOwner().getDescription().contains(watr)) { pLine.getItsOwner().setDescription(watr + pLine.getItsOwner().getDescription()); } } updInvTots(pReqVars, pLine.getItsOwner(), pAs, pInvTxMeth); } }
public class class_name { public final <T extends IInvoice, L extends IInvoiceLine<T>, TL extends AInvTxLn<T>> void makeTotals(final Map<String, Object> pReqVars, final L pLine, final AccSettings pAs, final TaxDestination pTxRules, final IInvTxMeth<T, TL> pInvTxMeth) throws Exception { //all tax lines will be redone: pReqVars.put(pInvTxMeth.getInvTxLnCl().getSimpleName() + "itsOwnerdeepLevel", 1); List<TL> invTxLns = getSrvOrm().retrieveListWithConditions( pReqVars, pInvTxMeth.getInvTxLnCl(), "where ITSOWNER=" + pLine.getItsOwner().getItsId()); pReqVars.remove(pInvTxMeth.getInvTxLnCl().getSimpleName() + "itsOwnerdeepLevel"); for (TL tl : invTxLns) { tl.setTax(null); tl.setTaxableInvBas(BigDecimal.ZERO); tl.setTaxableInvBasFc(BigDecimal.ZERO); tl.setItsTotal(BigDecimal.ZERO); tl.setForeignTotalTaxes(BigDecimal.ZERO); } if (pTxRules != null) { DataTx dtTx = retrieveDataTx(pReqVars, pLine, pAs, pTxRules, pInvTxMeth); if (!pTxRules.getSalTaxUseAggregItBas() && !(pTxRules .getSalTaxIsInvoiceBase() && pLine.getItsOwner().getPriceIncTax())) { //non-aggregate except invoice basis with included taxes: for (int i = 0; i < dtTx.getTxs().size(); i++) { TL tl = findCreateTaxLine(pReqVars, pLine.getItsOwner(), invTxLns, dtTx.getTxs().get(i), false, pInvTxMeth.getFctInvTxLn()); Double txTotd; Double txTotdFc = 0.0; if (!pTxRules.getSalTaxIsInvoiceBase()) { //item basis, taxes excluded/included: txTotd = dtTx.getTxTotTaxb().get(i); // depends on control dependency: [if], data = [none] txTotdFc = dtTx.getTxTotTaxbFc().get(i); // depends on control dependency: [if], data = [none] } else { //invoice basis, taxes excluded: txTotd = dtTx.getTxTotTaxb().get(i) * dtTx.getTxPerc().get(i) / 100.0; // depends on control dependency: [if], data = [none] tl.setTaxableInvBas(BigDecimal.valueOf(dtTx.getTxTotTaxb().get(i))); // depends on control dependency: [if], data = [none] if (pLine.getItsOwner().getForeignCurrency() != null) { txTotdFc = dtTx.getTxTotTaxbFc().get(i) * dtTx.getTxPerc().get(i) / 100.0; // depends on control dependency: [if], data = [none] tl.setTaxableInvBasFc(BigDecimal .valueOf(dtTx.getTxTotTaxbFc().get(i))); // depends on control dependency: [if], data = [none] } } tl.setItsTotal(BigDecimal.valueOf(txTotd).setScale(pAs. getPricePrecision(), pTxRules.getSalTaxRoundMode())); // depends on control dependency: [for], data = [none] tl.setForeignTotalTaxes(BigDecimal.valueOf(txTotdFc).setScale(pAs. getPricePrecision(), pTxRules.getSalTaxRoundMode())); // depends on control dependency: [for], data = [none] if (tl.getIsNew()) { getSrvOrm().insertEntity(pReqVars, tl); // depends on control dependency: [if], data = [none] tl.setIsNew(false); // depends on control dependency: [if], data = [none] } else { getSrvOrm().updateEntity(pReqVars, tl); // depends on control dependency: [if], data = [none] } } } else { //non-aggregate invoice basis with included taxes //and aggregate for others: BigDecimal bd100 = new BigDecimal("100.00"); Comparator<InvItemTaxCategoryLine> cmpr = Collections .reverseOrder(new CmprTaxCatLnRate()); for (SalesInvoiceServiceLine txdLn : dtTx.getTxdLns()) { int ti = 0; //aggregate rate line scoped storages: BigDecimal taxAggegated = null; BigDecimal taxAggrAccum = BigDecimal.ZERO; BigDecimal taxAggegatedFc = BigDecimal.ZERO; BigDecimal taxAggrAccumFc = BigDecimal.ZERO; Collections.sort(txdLn.getTaxCategory().getTaxes(), cmpr); // depends on control dependency: [for], data = [txdLn] for (InvItemTaxCategoryLine itcl : txdLn.getTaxCategory().getTaxes()) { ti++; // depends on control dependency: [for], data = [none] if (taxAggegated == null) { if (pTxRules.getSalTaxIsInvoiceBase()) { //invoice basis: if (pLine.getItsOwner().getPriceIncTax()) { taxAggegated = txdLn.getItsTotal().subtract(txdLn.getItsTotal() .divide(BigDecimal.ONE.add(txdLn.getTaxCategory().getAggrOnlyPercent() .divide(bd100)), pAs.getPricePrecision(), pTxRules.getSalTaxRoundMode())); // depends on control dependency: [if], data = [none] if (pLine.getItsOwner().getForeignCurrency() != null) { taxAggegatedFc = txdLn.getForeignTotal().subtract(txdLn .getForeignTotal().divide(BigDecimal.ONE.add(txdLn.getTaxCategory() .getAggrOnlyPercent().divide(bd100)), pAs.getPricePrecision(), pTxRules.getSalTaxRoundMode())); // depends on control dependency: [if], data = [none] } } else { taxAggegated = txdLn.getSubtotal().multiply(txdLn .getTaxCategory().getAggrOnlyPercent()).divide(bd100, pAs .getPricePrecision(), pTxRules.getSalTaxRoundMode()); // depends on control dependency: [if], data = [none] if (pLine.getItsOwner().getForeignCurrency() != null) { taxAggegatedFc = txdLn.getForeignSubtotal().multiply(txdLn .getTaxCategory().getAggrOnlyPercent()).divide(bd100, pAs .getPricePrecision(), pTxRules.getSalTaxRoundMode()); // depends on control dependency: [if], data = [none] } } } else { //item basis, taxes included/excluded taxAggegated = txdLn.getTotalTaxes(); // depends on control dependency: [if], data = [none] taxAggegatedFc = txdLn.getForeignTotalTaxes(); // depends on control dependency: [if], data = [none] } } //here total taxes mean total for current tax: if (ti < txdLn.getTaxCategory().getTaxes().size()) { txdLn.setTotalTaxes(taxAggegated.multiply(itcl.getItsPercentage()) .divide(txdLn.getTaxCategory().getAggrOnlyPercent(), pAs.getPricePrecision(), pTxRules.getSalTaxRoundMode())); // depends on control dependency: [if], data = [none] taxAggrAccum = taxAggrAccum.add(txdLn.getTotalTaxes()); // depends on control dependency: [if], data = [none] if (pLine.getItsOwner().getForeignCurrency() != null) { txdLn.setForeignTotalTaxes(taxAggegatedFc.multiply(itcl .getItsPercentage()).divide(txdLn.getTaxCategory().getAggrOnlyPercent(), pAs.getPricePrecision(), pTxRules.getSalTaxRoundMode())); // depends on control dependency: [if], data = [none] taxAggrAccumFc = taxAggrAccumFc.add(txdLn.getForeignTotalTaxes()); // depends on control dependency: [if], data = [none] } } else { //the rest or only tax: txdLn.setTotalTaxes(taxAggegated.subtract(taxAggrAccum)); // depends on control dependency: [if], data = [none] if (pLine.getItsOwner().getForeignCurrency() != null) { txdLn.setForeignTotalTaxes(taxAggegatedFc.subtract(taxAggrAccumFc)); // depends on control dependency: [if], data = [none] } } TL tl = findCreateTaxLine(pReqVars, pLine.getItsOwner(), invTxLns, itcl.getTax(), true, pInvTxMeth.getFctInvTxLn()); tl.setItsTotal(tl.getItsTotal().add(txdLn.getTotalTaxes())); // depends on control dependency: [for], data = [none] if (pLine.getItsOwner().getForeignCurrency() != null) { tl.setForeignTotalTaxes(tl.getForeignTotalTaxes() .add(txdLn.getForeignTotalTaxes())); // depends on control dependency: [if], data = [none] } if (pTxRules.getSalTaxIsInvoiceBase()) { if (ti == txdLn.getTaxCategory().getTaxes().size()) { //total line taxes for farther invoice adjusting: txdLn.setTotalTaxes(taxAggegated); // depends on control dependency: [if], data = [none] txdLn.setTotalTaxes(taxAggegatedFc); // depends on control dependency: [if], data = [none] } if (!pLine.getItsOwner().getPriceIncTax()) { tl.setTaxableInvBas(tl.getTaxableInvBas() .add(txdLn.getSubtotal())); // depends on control dependency: [if], data = [none] if (pLine.getItsOwner().getForeignCurrency() != null) { tl.setTaxableInvBasFc(tl.getTaxableInvBasFc() .add(txdLn.getForeignSubtotal())); // depends on control dependency: [if], data = [none] } } else { tl.setTaxableInvBas(tl.getTaxableInvBas() .add(txdLn.getItsTotal())); // depends on control dependency: [if], data = [none] if (pLine.getItsOwner().getForeignCurrency() != null) { tl.setTaxableInvBasFc(tl.getTaxableInvBasFc() .add(txdLn.getForeignTotal())); // depends on control dependency: [if], data = [none] } } } if (tl.getIsNew()) { getSrvOrm().insertEntity(pReqVars, tl); // depends on control dependency: [if], data = [none] tl.setIsNew(false); // depends on control dependency: [if], data = [none] } else { getSrvOrm().updateEntity(pReqVars, tl); // depends on control dependency: [if], data = [none] } } } } if (pTxRules.getSalTaxIsInvoiceBase()) { adjustInvoiceLns(pReqVars, pLine.getItsOwner(), dtTx.getTxdLns(), pAs, pInvTxMeth); } } //delete tax lines with zero tax: for (TL tl : invTxLns) { if (tl.getTax() == null) { getSrvOrm().deleteEntity(pReqVars, tl); // depends on control dependency: [if], data = [none] } } if (pTxRules != null && !pTxRules.getSalTaxUseAggregItBas() && pLine.getItsOwner().getPriceIncTax()) { String watr = "TTR without aggregate! "; if (pLine.getItsOwner().getDescription() == null) { pLine.getItsOwner().setDescription(watr); } else if (!pLine.getItsOwner().getDescription().contains(watr)) { pLine.getItsOwner().setDescription(watr + pLine.getItsOwner().getDescription()); } } updInvTots(pReqVars, pLine.getItsOwner(), pAs, pInvTxMeth); } }
public class class_name { public static void generate(ConfigurationImpl configuration, PackageDoc pkg, PackageDoc prev, PackageDoc next, boolean noDeprecated) { PackageTreeWriter packgen; DocPath path = DocPath.forPackage(pkg).resolve(DocPaths.PACKAGE_TREE); try { packgen = new PackageTreeWriter(configuration, path, pkg, prev, next); packgen.generatePackageTreeFile(); packgen.close(); } catch (IOException exc) { configuration.standardmessage.error( "doclet.exception_encountered", exc.toString(), path.getPath()); throw new DocletAbortException(exc); } } }
public class class_name { public static void generate(ConfigurationImpl configuration, PackageDoc pkg, PackageDoc prev, PackageDoc next, boolean noDeprecated) { PackageTreeWriter packgen; DocPath path = DocPath.forPackage(pkg).resolve(DocPaths.PACKAGE_TREE); try { packgen = new PackageTreeWriter(configuration, path, pkg, prev, next); // depends on control dependency: [try], data = [none] packgen.generatePackageTreeFile(); // depends on control dependency: [try], data = [none] packgen.close(); // depends on control dependency: [try], data = [none] } catch (IOException exc) { configuration.standardmessage.error( "doclet.exception_encountered", exc.toString(), path.getPath()); throw new DocletAbortException(exc); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static TransportAddress applyXor(TransportAddress address, byte[] transactionID) { byte[] addressBytes = address.getAddressBytes(); char port = (char) address.getPort(); char portModifier = (char) ((transactionID[0] << 8 & 0x0000FF00) | (transactionID[1] & 0x000000FF)); port ^= portModifier; for (int i = 0; i < addressBytes.length; i++) { addressBytes[i] ^= transactionID[i]; } try { TransportAddress xoredAdd = new TransportAddress( InetAddress.getByAddress(addressBytes), port, TransportProtocol.UDP); return xoredAdd; } catch (UnknownHostException e) { // shouldn't happen so just throw an illegal arg throw new IllegalArgumentException(e); } } }
public class class_name { public static TransportAddress applyXor(TransportAddress address, byte[] transactionID) { byte[] addressBytes = address.getAddressBytes(); char port = (char) address.getPort(); char portModifier = (char) ((transactionID[0] << 8 & 0x0000FF00) | (transactionID[1] & 0x000000FF)); port ^= portModifier; for (int i = 0; i < addressBytes.length; i++) { addressBytes[i] ^= transactionID[i]; // depends on control dependency: [for], data = [i] } try { TransportAddress xoredAdd = new TransportAddress( InetAddress.getByAddress(addressBytes), port, TransportProtocol.UDP); return xoredAdd; // depends on control dependency: [try], data = [none] } catch (UnknownHostException e) { // shouldn't happen so just throw an illegal arg throw new IllegalArgumentException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void animateClose() { prepareContent(); if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollStarted(); } animateClose(vertical ? viewHandle.getTop() : viewHandle.getLeft()); if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollEnded(); } } }
public class class_name { public void animateClose() { prepareContent(); if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollStarted(); // depends on control dependency: [if], data = [none] } animateClose(vertical ? viewHandle.getTop() : viewHandle.getLeft()); if (onDrawerScrollListener != null) { onDrawerScrollListener.onScrollEnded(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public Db tx(TransactionLevel transactionLevel, VoidFunc1<Db> func) throws SQLException { final Connection conn = getConnection(); // 检查是否支持事务 checkTransactionSupported(conn); // 设置事务级别 if (null != transactionLevel) { final int level = transactionLevel.getLevel(); if (conn.getTransactionIsolation() < level) { // 用户定义的事务级别如果比默认级别更严格,则按照严格的级别进行 conn.setTransactionIsolation(level); } } // 开始事务 boolean autoCommit = conn.getAutoCommit(); if (autoCommit) { conn.setAutoCommit(false); } // 执行事务 try { func.call(this); // 提交 conn.commit(); } catch (Throwable e) { quietRollback(conn); throw (e instanceof SQLException) ? (SQLException) e : new SQLException(e); } finally { // 还原事务状态 quietSetAutoCommit(conn, autoCommit); // 关闭连接或将连接归还连接池 closeConnection(conn); } return this; } }
public class class_name { public Db tx(TransactionLevel transactionLevel, VoidFunc1<Db> func) throws SQLException { final Connection conn = getConnection(); // 检查是否支持事务 checkTransactionSupported(conn); // 设置事务级别 if (null != transactionLevel) { final int level = transactionLevel.getLevel(); if (conn.getTransactionIsolation() < level) { // 用户定义的事务级别如果比默认级别更严格,则按照严格的级别进行 conn.setTransactionIsolation(level); // depends on control dependency: [if], data = [level)] } } // 开始事务 boolean autoCommit = conn.getAutoCommit(); if (autoCommit) { conn.setAutoCommit(false); } // 执行事务 try { func.call(this); // 提交 conn.commit(); } catch (Throwable e) { quietRollback(conn); throw (e instanceof SQLException) ? (SQLException) e : new SQLException(e); } finally { // 还原事务状态 quietSetAutoCommit(conn, autoCommit); // 关闭连接或将连接归还连接池 closeConnection(conn); } return this; } }
public class class_name { protected void saveRequestedUrl(final C context, final List<Client> currentClients, AjaxRequestResolver ajaxRequestResolver) { if (ajaxRequestResolver == null || !ajaxRequestResolver.isAjax(context)) { savedRequestHandler.save(context); } } }
public class class_name { protected void saveRequestedUrl(final C context, final List<Client> currentClients, AjaxRequestResolver ajaxRequestResolver) { if (ajaxRequestResolver == null || !ajaxRequestResolver.isAjax(context)) { savedRequestHandler.save(context); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void parseNamespaceValidationElements(Element messageElement, XmlMessageValidationContext context) { //check for validate elements, these elements can either have script, xpath or namespace validation information //for now we only handle namespace validation Map<String, String> validateNamespaces = new HashMap<String, String>(); List<?> validateElements = DomUtils.getChildElementsByTagName(messageElement, "validate"); if (validateElements.size() > 0) { for (Iterator<?> iter = validateElements.iterator(); iter.hasNext();) { Element validateElement = (Element) iter.next(); //check for namespace validation elements List<?> validateNamespaceElements = DomUtils.getChildElementsByTagName(validateElement, "namespace"); if (validateNamespaceElements.size() > 0) { for (Iterator<?> namespaceIterator = validateNamespaceElements.iterator(); namespaceIterator.hasNext();) { Element namespaceElement = (Element) namespaceIterator.next(); validateNamespaces.put(namespaceElement.getAttribute("prefix"), namespaceElement.getAttribute("value")); } } } context.setControlNamespaces(validateNamespaces); } } }
public class class_name { private void parseNamespaceValidationElements(Element messageElement, XmlMessageValidationContext context) { //check for validate elements, these elements can either have script, xpath or namespace validation information //for now we only handle namespace validation Map<String, String> validateNamespaces = new HashMap<String, String>(); List<?> validateElements = DomUtils.getChildElementsByTagName(messageElement, "validate"); if (validateElements.size() > 0) { for (Iterator<?> iter = validateElements.iterator(); iter.hasNext();) { Element validateElement = (Element) iter.next(); //check for namespace validation elements List<?> validateNamespaceElements = DomUtils.getChildElementsByTagName(validateElement, "namespace"); if (validateNamespaceElements.size() > 0) { for (Iterator<?> namespaceIterator = validateNamespaceElements.iterator(); namespaceIterator.hasNext();) { Element namespaceElement = (Element) namespaceIterator.next(); validateNamespaces.put(namespaceElement.getAttribute("prefix"), namespaceElement.getAttribute("value")); // depends on control dependency: [for], data = [none] } } } context.setControlNamespaces(validateNamespaces); // depends on control dependency: [if], data = [none] } } }
public class class_name { protected static void printDeliveryStreams() { // list all of my DeliveryStreams List<String> deliveryStreamNames = listDeliveryStreams(); LOG.info("Printing my list of DeliveryStreams : "); if (deliveryStreamNames.isEmpty()) { LOG.info("There are no DeliveryStreams for account: " + accountId); } else { LOG.info("List of my DeliveryStreams: "); } for (int i = 0; i < deliveryStreamNames.size(); i++) { LOG.info(deliveryStreamNames.get(i)); } } }
public class class_name { protected static void printDeliveryStreams() { // list all of my DeliveryStreams List<String> deliveryStreamNames = listDeliveryStreams(); LOG.info("Printing my list of DeliveryStreams : "); if (deliveryStreamNames.isEmpty()) { LOG.info("There are no DeliveryStreams for account: " + accountId); // depends on control dependency: [if], data = [none] } else { LOG.info("List of my DeliveryStreams: "); // depends on control dependency: [if], data = [none] } for (int i = 0; i < deliveryStreamNames.size(); i++) { LOG.info(deliveryStreamNames.get(i)); // depends on control dependency: [for], data = [i] } } }
public class class_name { public CompletableFuture<Void> deregisterApplicationAndClose( final ApplicationStatus applicationStatus, final @Nullable String diagnostics) { if (isRunning.compareAndSet(true, false)) { final CompletableFuture<Void> closeWebMonitorAndDeregisterAppFuture = FutureUtils.composeAfterwards(webMonitorEndpoint.closeAsync(), () -> deregisterApplication(applicationStatus, diagnostics)); return FutureUtils.composeAfterwards(closeWebMonitorAndDeregisterAppFuture, this::closeAsyncInternal); } else { return terminationFuture; } } }
public class class_name { public CompletableFuture<Void> deregisterApplicationAndClose( final ApplicationStatus applicationStatus, final @Nullable String diagnostics) { if (isRunning.compareAndSet(true, false)) { final CompletableFuture<Void> closeWebMonitorAndDeregisterAppFuture = FutureUtils.composeAfterwards(webMonitorEndpoint.closeAsync(), () -> deregisterApplication(applicationStatus, diagnostics)); return FutureUtils.composeAfterwards(closeWebMonitorAndDeregisterAppFuture, this::closeAsyncInternal); // depends on control dependency: [if], data = [none] } else { return terminationFuture; // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public synchronized void write(final Collection<BatchPoints> collection) { // empty the cached data first ListIterator<BatchPoints> batchQueueIterator = batchQueue.listIterator(); while (batchQueueIterator.hasNext()) { BatchPoints entry = batchQueueIterator.next(); WriteResult result = tryToWrite(entry); if (result.outcome == WriteResultOutcome.WRITTEN || result.outcome == WriteResultOutcome.FAILED_RETRY_IMPOSSIBLE) { batchQueueIterator.remove(); usedRetryBufferCapacity -= entry.getPoints().size(); // we are throwing out data, notify the client if (result.outcome == WriteResultOutcome.FAILED_RETRY_IMPOSSIBLE) { exceptionHandler.accept(entry.getPoints(), result.throwable); } } else { // we cannot send more data otherwise we would write them in different // order than in which were submitted for (BatchPoints batchPoints : collection) { addToBatchQueue(batchPoints); } return; } } // write the last given batch last so that duplicate data points get overwritten correctly Iterator<BatchPoints> collectionIterator = collection.iterator(); while (collectionIterator.hasNext()) { BatchPoints batchPoints = collectionIterator.next(); WriteResult result = tryToWrite(batchPoints); switch (result.outcome) { case FAILED_RETRY_POSSIBLE: addToBatchQueue(batchPoints); while (collectionIterator.hasNext()) { addToBatchQueue(collectionIterator.next()); } break; case FAILED_RETRY_IMPOSSIBLE: exceptionHandler.accept(batchPoints.getPoints(), result.throwable); break; default: } } } }
public class class_name { @Override public synchronized void write(final Collection<BatchPoints> collection) { // empty the cached data first ListIterator<BatchPoints> batchQueueIterator = batchQueue.listIterator(); while (batchQueueIterator.hasNext()) { BatchPoints entry = batchQueueIterator.next(); WriteResult result = tryToWrite(entry); if (result.outcome == WriteResultOutcome.WRITTEN || result.outcome == WriteResultOutcome.FAILED_RETRY_IMPOSSIBLE) { batchQueueIterator.remove(); // depends on control dependency: [if], data = [none] usedRetryBufferCapacity -= entry.getPoints().size(); // depends on control dependency: [if], data = [none] // we are throwing out data, notify the client if (result.outcome == WriteResultOutcome.FAILED_RETRY_IMPOSSIBLE) { exceptionHandler.accept(entry.getPoints(), result.throwable); // depends on control dependency: [if], data = [none] } } else { // we cannot send more data otherwise we would write them in different // order than in which were submitted for (BatchPoints batchPoints : collection) { addToBatchQueue(batchPoints); // depends on control dependency: [for], data = [batchPoints] } return; // depends on control dependency: [if], data = [none] } } // write the last given batch last so that duplicate data points get overwritten correctly Iterator<BatchPoints> collectionIterator = collection.iterator(); while (collectionIterator.hasNext()) { BatchPoints batchPoints = collectionIterator.next(); WriteResult result = tryToWrite(batchPoints); switch (result.outcome) { case FAILED_RETRY_POSSIBLE: addToBatchQueue(batchPoints); while (collectionIterator.hasNext()) { addToBatchQueue(collectionIterator.next()); // depends on control dependency: [while], data = [none] } break; case FAILED_RETRY_IMPOSSIBLE: exceptionHandler.accept(batchPoints.getPoints(), result.throwable); break; default: } } } }
public class class_name { public synchronized TableModel<V> removeColumn(int index) { String removedColumnHeader = columns.remove(index); List<V> removedColumn = new ArrayList<V>(); for(List<V> row : rows) { removedColumn.add(row.remove(index)); } for(Listener<V> listener: listeners) { listener.onColumnRemoved(this, index, removedColumnHeader, removedColumn); } return this; } }
public class class_name { public synchronized TableModel<V> removeColumn(int index) { String removedColumnHeader = columns.remove(index); List<V> removedColumn = new ArrayList<V>(); for(List<V> row : rows) { removedColumn.add(row.remove(index)); // depends on control dependency: [for], data = [row] } for(Listener<V> listener: listeners) { listener.onColumnRemoved(this, index, removedColumnHeader, removedColumn); // depends on control dependency: [for], data = [listener] } return this; } }
public class class_name { protected Map<String, String> extract(String propertyPrefix, Map<String, String> properties, boolean removeProps) { if (null == properties || properties.isEmpty()) { return Collections.<String, String> emptyMap(); } Map<String, String> extractProps = new HashMap<String, String>(); Iterator<Map.Entry<String, String>> propIter = properties.entrySet().iterator(); while (propIter.hasNext()) { Map.Entry<String, String> propEntry = propIter.next(); if (null != propEntry.getKey() && propEntry.getKey().startsWith(propertyPrefix)) { String propKey = propEntry.getKey().substring(propertyPrefix.length()); extractProps.put(propKey, propEntry.getValue()); if (removeProps) { propIter.remove(); } } } return extractProps; } }
public class class_name { protected Map<String, String> extract(String propertyPrefix, Map<String, String> properties, boolean removeProps) { if (null == properties || properties.isEmpty()) { return Collections.<String, String> emptyMap(); // depends on control dependency: [if], data = [none] } Map<String, String> extractProps = new HashMap<String, String>(); Iterator<Map.Entry<String, String>> propIter = properties.entrySet().iterator(); while (propIter.hasNext()) { Map.Entry<String, String> propEntry = propIter.next(); if (null != propEntry.getKey() && propEntry.getKey().startsWith(propertyPrefix)) { String propKey = propEntry.getKey().substring(propertyPrefix.length()); extractProps.put(propKey, propEntry.getValue()); // depends on control dependency: [if], data = [none] if (removeProps) { propIter.remove(); // depends on control dependency: [if], data = [none] } } } return extractProps; } }
public class class_name { public void actionDeleteCascade() throws JspException { // save initialized instance of this class in request attribute for included sub-elements getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this); try { // list of all resources containing this propertydefinition List resourcesWithProperty = getCms().readResourcesWithProperty(getParamPropertyName()); // list of all resources locked by another user, containing this propertydefinition List resourcesLockedByOtherUser = getResourcesLockedByOtherUser(resourcesWithProperty); // do the following operations only if all of the resources are not locked by another user if (resourcesLockedByOtherUser.isEmpty()) { // save the site root String storedSiteRoot = getCms().getRequestContext().getSiteRoot(); try { // change to the root site getCms().getRequestContext().setSiteRoot("/"); Iterator i = resourcesWithProperty.iterator(); while (i.hasNext()) { CmsResource resource = (CmsResource)i.next(); // read the property object CmsProperty property = getCms().readPropertyObject( resource.getRootPath(), getParamPropertyName(), false); // try to delete the property if it is not the NULL PROPERTY // if the property is the NULL PROPERTY, it only had a shared // value which was deleted at a sibling which was already processed if (!property.isNullProperty()) { CmsLock lock = getCms().getLock(resource); if (lock.isUnlocked()) { // lock the resource for the current (Admin) user getCms().lockResource(resource.getRootPath()); } property.setStructureValue(CmsProperty.DELETE_VALUE); property.setResourceValue(CmsProperty.DELETE_VALUE); // write the property with the null value to the resource and cascade it from the definition getCms().writePropertyObject(resource.getRootPath(), property); // unlock the resource getCms().unlockResource(resource.getRootPath()); } } // delete the property definition at last getCms().deletePropertyDefinition(getParamPropertyName()); } finally { // restore the siteroot getCms().getRequestContext().setSiteRoot(storedSiteRoot); // close the dialog actionCloseDialog(); } } else { StringBuffer reason = new StringBuffer(); reason.append(dialogWhiteBoxStart()); reason.append(buildResourceList(resourcesLockedByOtherUser, true)); reason.append(dialogWhiteBoxEnd()); throw new CmsVfsException( Messages.get().container(Messages.ERR_DEL_PROP_RESOURCES_LOCKED_1, reason.toString())); } } catch (Throwable e) { // error while deleting property definition, show error dialog includeErrorpage(this, e); } } }
public class class_name { public void actionDeleteCascade() throws JspException { // save initialized instance of this class in request attribute for included sub-elements getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this); try { // list of all resources containing this propertydefinition List resourcesWithProperty = getCms().readResourcesWithProperty(getParamPropertyName()); // list of all resources locked by another user, containing this propertydefinition List resourcesLockedByOtherUser = getResourcesLockedByOtherUser(resourcesWithProperty); // do the following operations only if all of the resources are not locked by another user if (resourcesLockedByOtherUser.isEmpty()) { // save the site root String storedSiteRoot = getCms().getRequestContext().getSiteRoot(); try { // change to the root site getCms().getRequestContext().setSiteRoot("/"); // depends on control dependency: [try], data = [none] Iterator i = resourcesWithProperty.iterator(); while (i.hasNext()) { CmsResource resource = (CmsResource)i.next(); // read the property object CmsProperty property = getCms().readPropertyObject( resource.getRootPath(), getParamPropertyName(), false); // try to delete the property if it is not the NULL PROPERTY // if the property is the NULL PROPERTY, it only had a shared // value which was deleted at a sibling which was already processed if (!property.isNullProperty()) { CmsLock lock = getCms().getLock(resource); if (lock.isUnlocked()) { // lock the resource for the current (Admin) user getCms().lockResource(resource.getRootPath()); // depends on control dependency: [if], data = [none] } property.setStructureValue(CmsProperty.DELETE_VALUE); // depends on control dependency: [if], data = [none] property.setResourceValue(CmsProperty.DELETE_VALUE); // depends on control dependency: [if], data = [none] // write the property with the null value to the resource and cascade it from the definition getCms().writePropertyObject(resource.getRootPath(), property); // depends on control dependency: [if], data = [none] // unlock the resource getCms().unlockResource(resource.getRootPath()); // depends on control dependency: [if], data = [none] } } // delete the property definition at last getCms().deletePropertyDefinition(getParamPropertyName()); // depends on control dependency: [try], data = [none] } finally { // restore the siteroot getCms().getRequestContext().setSiteRoot(storedSiteRoot); // close the dialog actionCloseDialog(); } } else { StringBuffer reason = new StringBuffer(); reason.append(dialogWhiteBoxStart()); // depends on control dependency: [if], data = [none] reason.append(buildResourceList(resourcesLockedByOtherUser, true)); // depends on control dependency: [if], data = [none] reason.append(dialogWhiteBoxEnd()); // depends on control dependency: [if], data = [none] throw new CmsVfsException( Messages.get().container(Messages.ERR_DEL_PROP_RESOURCES_LOCKED_1, reason.toString())); } } catch (Throwable e) { // error while deleting property definition, show error dialog includeErrorpage(this, e); } } }
public class class_name { public static Dialect getDialect(DataSource ds) { Dialect dialect = dialectPool.get(ds); if(null == dialect) { synchronized (lock) { dialect = dialectPool.get(ds); if(null == dialect) { dialect = newDialect(ds); dialectPool.put(ds, dialect); } } } return dialect; } }
public class class_name { public static Dialect getDialect(DataSource ds) { Dialect dialect = dialectPool.get(ds); if(null == dialect) { synchronized (lock) { // depends on control dependency: [if], data = [none] dialect = dialectPool.get(ds); if(null == dialect) { dialect = newDialect(ds); // depends on control dependency: [if], data = [none] dialectPool.put(ds, dialect); // depends on control dependency: [if], data = [dialect)] } } } return dialect; } }
public class class_name { public void marshall(GetDatabasesRequest getDatabasesRequest, ProtocolMarshaller protocolMarshaller) { if (getDatabasesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getDatabasesRequest.getCatalogId(), CATALOGID_BINDING); protocolMarshaller.marshall(getDatabasesRequest.getNextToken(), NEXTTOKEN_BINDING); protocolMarshaller.marshall(getDatabasesRequest.getMaxResults(), MAXRESULTS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(GetDatabasesRequest getDatabasesRequest, ProtocolMarshaller protocolMarshaller) { if (getDatabasesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getDatabasesRequest.getCatalogId(), CATALOGID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(getDatabasesRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(getDatabasesRequest.getMaxResults(), MAXRESULTS_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public boolean validateObject(Object key, PooledObject<Object> pooledObject) { Assert.notNull(this.dirContextValidator, "DirContextValidator may not be null"); Assert.isTrue(key instanceof DirContextType, "key must be a DirContextType"); Assert.notNull(pooledObject, "The Object to validate must not be null"); Assert.isTrue(pooledObject.getObject() instanceof DirContext, "The Object to validate must be of type '" + DirContext.class + "'"); try { final DirContextType contextType = (DirContextType) key; final DirContext dirContext = (DirContext) pooledObject.getObject(); return this.dirContextValidator.validateDirContext(contextType, dirContext); } catch (Exception e) { this.logger.warn("Failed to validate '" + pooledObject.getObject() + "' due to an unexpected exception.", e); return false; } } }
public class class_name { @Override public boolean validateObject(Object key, PooledObject<Object> pooledObject) { Assert.notNull(this.dirContextValidator, "DirContextValidator may not be null"); Assert.isTrue(key instanceof DirContextType, "key must be a DirContextType"); Assert.notNull(pooledObject, "The Object to validate must not be null"); Assert.isTrue(pooledObject.getObject() instanceof DirContext, "The Object to validate must be of type '" + DirContext.class + "'"); try { final DirContextType contextType = (DirContextType) key; final DirContext dirContext = (DirContext) pooledObject.getObject(); return this.dirContextValidator.validateDirContext(contextType, dirContext); // depends on control dependency: [try], data = [none] } catch (Exception e) { this.logger.warn("Failed to validate '" + pooledObject.getObject() + "' due to an unexpected exception.", e); return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public String getDescription(CmsObject cms) { if (m_description == null) { if (m_element.element(PARAM_DESCRIPTION) != null) { m_description = m_element.element(PARAM_DESCRIPTION).getText(); } if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_description)) { m_description = getParameterValue(cms, PARAM_DESCRIPTION); m_description = CmsEncoder.unescape(m_description, CmsEncoder.ENCODING_UTF_8); } } return m_description; } }
public class class_name { public String getDescription(CmsObject cms) { if (m_description == null) { if (m_element.element(PARAM_DESCRIPTION) != null) { m_description = m_element.element(PARAM_DESCRIPTION).getText(); // depends on control dependency: [if], data = [none] } if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_description)) { m_description = getParameterValue(cms, PARAM_DESCRIPTION); // depends on control dependency: [if], data = [none] m_description = CmsEncoder.unescape(m_description, CmsEncoder.ENCODING_UTF_8); // depends on control dependency: [if], data = [none] } } return m_description; } }
public class class_name { public Contact[] getSelectedContacts() { int[] selected = getTable().getSelectedRows(); Contact[] contacts = new Contact[selected.length]; for (int i = 0; i < selected.length; i++) { contacts[i] = (Contact) getTableModel().getElementAt(selected[i]); } return contacts; } }
public class class_name { public Contact[] getSelectedContacts() { int[] selected = getTable().getSelectedRows(); Contact[] contacts = new Contact[selected.length]; for (int i = 0; i < selected.length; i++) { contacts[i] = (Contact) getTableModel().getElementAt(selected[i]); // depends on control dependency: [for], data = [i] } return contacts; } }
public class class_name { public void swap(final Type prev, final Type type) { if (type.getSize() == 1) { if (prev.getSize() == 1) { swap(); // same as dupX1(), pop(); } else { dupX2(); pop(); } } else { if (prev.getSize() == 1) { dup2X1(); pop2(); } else { dup2X2(); pop2(); } } } }
public class class_name { public void swap(final Type prev, final Type type) { if (type.getSize() == 1) { if (prev.getSize() == 1) { swap(); // same as dupX1(), pop(); // depends on control dependency: [if], data = [none] } else { dupX2(); // depends on control dependency: [if], data = [none] pop(); // depends on control dependency: [if], data = [none] } } else { if (prev.getSize() == 1) { dup2X1(); // depends on control dependency: [if], data = [none] pop2(); // depends on control dependency: [if], data = [none] } else { dup2X2(); // depends on control dependency: [if], data = [none] pop2(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public double[] getSentenceProbabilities() { double[] sentProbArray = new double[sentProbs.size()]; for (int i = 0; i < sentProbArray.length; i++) { sentProbArray[i] = ((Double) sentProbs.get(i)).doubleValue(); } return sentProbArray; } }
public class class_name { public double[] getSentenceProbabilities() { double[] sentProbArray = new double[sentProbs.size()]; for (int i = 0; i < sentProbArray.length; i++) { sentProbArray[i] = ((Double) sentProbs.get(i)).doubleValue(); // depends on control dependency: [for], data = [i] } return sentProbArray; } }
public class class_name { private Object formatVerboseObj(Object obj) { // Make sure that we don't truncate any stack traces during verbose logging if (obj instanceof TruncatableThrowable) { TruncatableThrowable truncatable = (TruncatableThrowable) obj; final Throwable wrappedException = truncatable.getWrappedException(); return DataFormatHelper.throwableToString(wrappedException); } else if (obj instanceof Throwable) { return DataFormatHelper.throwableToString((Throwable) obj); } return null; } }
public class class_name { private Object formatVerboseObj(Object obj) { // Make sure that we don't truncate any stack traces during verbose logging if (obj instanceof TruncatableThrowable) { TruncatableThrowable truncatable = (TruncatableThrowable) obj; final Throwable wrappedException = truncatable.getWrappedException(); return DataFormatHelper.throwableToString(wrappedException); // depends on control dependency: [if], data = [none] } else if (obj instanceof Throwable) { return DataFormatHelper.throwableToString((Throwable) obj); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { public static byte[] encode(String s, Charset charset) { CharsetEncoder encoder = charset.newEncoder(); try { ByteBuffer buffer = encoder.encode(CharBuffer.wrap(s)); byte[] bytes = buffer.array(); // Make another copy iff there's garbage after the limit. int limit = buffer.limit(); if (limit < bytes.length) { bytes = copyOf(bytes, limit); } return bytes; } catch (CharacterCodingException e) { throw new IonException("Invalid string data", e); } } }
public class class_name { public static byte[] encode(String s, Charset charset) { CharsetEncoder encoder = charset.newEncoder(); try { ByteBuffer buffer = encoder.encode(CharBuffer.wrap(s)); byte[] bytes = buffer.array(); // Make another copy iff there's garbage after the limit. int limit = buffer.limit(); if (limit < bytes.length) { bytes = copyOf(bytes, limit); // depends on control dependency: [if], data = [none] } return bytes; } catch (CharacterCodingException e) { throw new IonException("Invalid string data", e); } } }
public class class_name { public void close() { boolean isPreviouslyClosed = isClosed.getAndSet(true); if (isPreviouslyClosed) { return; } AdminClient client; while ((client = clientCache.poll()) != null) { client.close(); } } }
public class class_name { public void close() { boolean isPreviouslyClosed = isClosed.getAndSet(true); if (isPreviouslyClosed) { return; // depends on control dependency: [if], data = [none] } AdminClient client; while ((client = clientCache.poll()) != null) { client.close(); // depends on control dependency: [while], data = [none] } } }
public class class_name { @GET @Produces(MediaType.APPLICATION_JSON) @Path("/id/{userId}") @Description("Returns the user having the given ID.") public PrincipalUserDto getUserById(@Context HttpServletRequest req, @PathParam("userId") final BigInteger userId) { if (userId == null || userId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("User Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } PrincipalUser remoteUser = validateAndGetOwner(req, null); PrincipalUser user = _uService.findUserByPrimaryKey(userId); if (user != null) { super.validateResourceAuthorization(req, user, remoteUser); return PrincipalUserDto.transformToDto(user); } throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND); } }
public class class_name { @GET @Produces(MediaType.APPLICATION_JSON) @Path("/id/{userId}") @Description("Returns the user having the given ID.") public PrincipalUserDto getUserById(@Context HttpServletRequest req, @PathParam("userId") final BigInteger userId) { if (userId == null || userId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("User Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } PrincipalUser remoteUser = validateAndGetOwner(req, null); PrincipalUser user = _uService.findUserByPrimaryKey(userId); if (user != null) { super.validateResourceAuthorization(req, user, remoteUser); // depends on control dependency: [if], data = [none] return PrincipalUserDto.transformToDto(user); // depends on control dependency: [if], data = [(user] } throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND); } }