code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public void marshall(GetMethodRequest getMethodRequest, ProtocolMarshaller protocolMarshaller) { if (getMethodRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getMethodRequest.getRestApiId(), RESTAPIID_BINDING); protocolMarshaller.marshall(getMethodRequest.getResourceId(), RESOURCEID_BINDING); protocolMarshaller.marshall(getMethodRequest.getHttpMethod(), HTTPMETHOD_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(GetMethodRequest getMethodRequest, ProtocolMarshaller protocolMarshaller) { if (getMethodRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getMethodRequest.getRestApiId(), RESTAPIID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(getMethodRequest.getResourceId(), RESOURCEID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(getMethodRequest.getHttpMethod(), HTTPMETHOD_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public IRingSet findEssentialRings() { if (atomContainer == null) { return null; } IRingSet ringSet = toRingSet(atomContainer, cycleBasis().essentialCycles()); // atomContainer.setProperty(CDKConstants.ESSENTIAL_RINGS, ringSet); return ringSet; } }
public class class_name { public IRingSet findEssentialRings() { if (atomContainer == null) { return null; // depends on control dependency: [if], data = [none] } IRingSet ringSet = toRingSet(atomContainer, cycleBasis().essentialCycles()); // atomContainer.setProperty(CDKConstants.ESSENTIAL_RINGS, ringSet); return ringSet; } }
public class class_name { @Override public Thread newThread(final Runnable runnable) { Runnable wrapped = new Runnable() { @Override public void run() { try { // As the runnable is wrapped in another runnable object, we call the run method directly. runnable.run(); //NOSONAR } catch (Exception e) { //NOSONAR // Catching exception is acceptable here as the wrapped runnable can throw almost anything. log.error("Error while executing " + Thread.currentThread().getName(), e); } } }; Thread thread = factory.newThread(wrapped); thread.setName(prefix + "-" + thread.getName()); return thread; } }
public class class_name { @Override public Thread newThread(final Runnable runnable) { Runnable wrapped = new Runnable() { @Override public void run() { try { // As the runnable is wrapped in another runnable object, we call the run method directly. runnable.run(); //NOSONAR // depends on control dependency: [try], data = [none] } catch (Exception e) { //NOSONAR // Catching exception is acceptable here as the wrapped runnable can throw almost anything. log.error("Error while executing " + Thread.currentThread().getName(), e); } // depends on control dependency: [catch], data = [none] } }; Thread thread = factory.newThread(wrapped); thread.setName(prefix + "-" + thread.getName()); return thread; } }
public class class_name { @Override public void render(Graphic g, Handlables featurables) { for (final Renderable renderable : featurables.get(Renderable.class)) { renderable.render(g); } } }
public class class_name { @Override public void render(Graphic g, Handlables featurables) { for (final Renderable renderable : featurables.get(Renderable.class)) { renderable.render(g); // depends on control dependency: [for], data = [renderable] } } }
public class class_name { private static char[] growBuffer(char[] dest, int index, int size) { if (size < 0) { // overflow - should be OutOfMemoryError but GWT/j2cl don't support it throw new AssertionError("Cannot increase internal buffer any further"); } char[] copy = new char[size]; if (index > 0) { System.arraycopy(dest, 0, copy, 0, index); } return copy; } }
public class class_name { private static char[] growBuffer(char[] dest, int index, int size) { if (size < 0) { // overflow - should be OutOfMemoryError but GWT/j2cl don't support it throw new AssertionError("Cannot increase internal buffer any further"); } char[] copy = new char[size]; if (index > 0) { System.arraycopy(dest, 0, copy, 0, index); // depends on control dependency: [if], data = [none] } return copy; } }
public class class_name { public void marshall(GitSubmodulesConfig gitSubmodulesConfig, ProtocolMarshaller protocolMarshaller) { if (gitSubmodulesConfig == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(gitSubmodulesConfig.getFetchSubmodules(), FETCHSUBMODULES_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(GitSubmodulesConfig gitSubmodulesConfig, ProtocolMarshaller protocolMarshaller) { if (gitSubmodulesConfig == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(gitSubmodulesConfig.getFetchSubmodules(), FETCHSUBMODULES_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 List<String> getNamespaceMapping(Class<?> clazz) { int bestScore = 0; String bestNamespace = clazz.getName().replaceAll("\\.", "::"); for (Namespace namespace : mappings.getNamespaces()) { if (namespace.getJavaPackage().length() > bestScore && clazz.getName().matches(namespace.getJavaPackage())) { bestScore = namespace.getJavaPackage().length(); bestNamespace = Utils.isNullOrEmpty(namespace.getNamespace()) ? clazz.getSimpleName() : String.format("%s::%s", namespace.getNamespace(), clazz.getSimpleName()); } } return Arrays.asList(bestNamespace.split("::")); } }
public class class_name { private List<String> getNamespaceMapping(Class<?> clazz) { int bestScore = 0; String bestNamespace = clazz.getName().replaceAll("\\.", "::"); for (Namespace namespace : mappings.getNamespaces()) { if (namespace.getJavaPackage().length() > bestScore && clazz.getName().matches(namespace.getJavaPackage())) { bestScore = namespace.getJavaPackage().length(); // depends on control dependency: [if], data = [none] bestNamespace = Utils.isNullOrEmpty(namespace.getNamespace()) ? clazz.getSimpleName() : String.format("%s::%s", namespace.getNamespace(), clazz.getSimpleName()); // depends on control dependency: [if], data = [none] } } return Arrays.asList(bestNamespace.split("::")); } }
public class class_name { public NormalizedUserProfile getUserProfileInfo(AccessToken accessTokenParam) { if(accessTokenParam == null || (accessTokenParam.getAccessToken() == null || accessTokenParam.getAccessToken().trim().isEmpty())) { throw new FluidClientException( "Code must be provided.", FluidClientException.ErrorCode.FIELD_VALIDATE); } try { String accessToken = accessTokenParam.getAccessToken(); List<HeaderNameValue> headerListing = new ArrayList<HeaderNameValue>(); headerListing.add(new HeaderNameValue( NormalizedUserProfile.HeaderMapping.AUTHORIZATION, "Bearer "+accessToken)); return new NormalizedUserProfile( this.getJson(true, WS.Path.Auth0.Version1.userInfo(),headerListing)); } // catch (UnsupportedEncodingException e) { throw new FluidClientException( "Unable to Encode (Not Supported). "+ e.getMessage(), FluidClientException.ErrorCode.ILLEGAL_STATE_ERROR); } } }
public class class_name { public NormalizedUserProfile getUserProfileInfo(AccessToken accessTokenParam) { if(accessTokenParam == null || (accessTokenParam.getAccessToken() == null || accessTokenParam.getAccessToken().trim().isEmpty())) { throw new FluidClientException( "Code must be provided.", FluidClientException.ErrorCode.FIELD_VALIDATE); } try { String accessToken = accessTokenParam.getAccessToken(); List<HeaderNameValue> headerListing = new ArrayList<HeaderNameValue>(); headerListing.add(new HeaderNameValue( NormalizedUserProfile.HeaderMapping.AUTHORIZATION, "Bearer "+accessToken)); // depends on control dependency: [try], data = [none] return new NormalizedUserProfile( this.getJson(true, WS.Path.Auth0.Version1.userInfo(),headerListing)); // depends on control dependency: [try], data = [none] } // catch (UnsupportedEncodingException e) { throw new FluidClientException( "Unable to Encode (Not Supported). "+ e.getMessage(), FluidClientException.ErrorCode.ILLEGAL_STATE_ERROR); } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected void closeQuietly(Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (Exception t) { HTTP_LOGGER.warn("Unable to close {}: ", closeable, t); } } }
public class class_name { protected void closeQuietly(Closeable closeable) { if (closeable == null) { return; // depends on control dependency: [if], data = [none] } try { closeable.close(); } catch (Exception t) { HTTP_LOGGER.warn("Unable to close {}: ", closeable, t); } } }
public class class_name { @Override public void execute() throws MojoExecutionException { try { createApplicationBundle(); if (!disableDistributionPackaging) { if (wisdomDirectory != null) { getLog().warn("Cannot create the distribution of " + project.getArtifactId() + " because it is using a remote Wisdom server (" + wisdomDirectory .getAbsolutePath() + ")."); } else { createApplicationDistribution(); } } else { getLog().debug("Creation of the zip file disabled"); } } catch (Exception e) { throw new MojoExecutionException("Cannot build wisdom application", e); } displayNonBundleLibraryWarning(); } }
public class class_name { @Override public void execute() throws MojoExecutionException { try { createApplicationBundle(); if (!disableDistributionPackaging) { if (wisdomDirectory != null) { getLog().warn("Cannot create the distribution of " + project.getArtifactId() + " because it is using a remote Wisdom server (" + wisdomDirectory .getAbsolutePath() + ")."); // depends on control dependency: [if], data = [none] } else { createApplicationDistribution(); // depends on control dependency: [if], data = [none] } } else { getLog().debug("Creation of the zip file disabled"); } } catch (Exception e) { throw new MojoExecutionException("Cannot build wisdom application", e); } displayNonBundleLibraryWarning(); } }
public class class_name { public void setRevisionTargets(java.util.Collection<RevisionTarget> revisionTargets) { if (revisionTargets == null) { this.revisionTargets = null; return; } this.revisionTargets = new com.amazonaws.internal.SdkInternalList<RevisionTarget>(revisionTargets); } }
public class class_name { public void setRevisionTargets(java.util.Collection<RevisionTarget> revisionTargets) { if (revisionTargets == null) { this.revisionTargets = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.revisionTargets = new com.amazonaws.internal.SdkInternalList<RevisionTarget>(revisionTargets); } }
public class class_name { public static String buildPath(final boolean endWithSep, final String... val) { StringBuilder path = new StringBuilder(); for (String s: val) { if (s != null) { path.append(s); } } String s = path.toString().replaceAll("/+", "/"); if (endWithSep) { if (!s.endsWith("/")) { s += "/"; } } else if (s.endsWith("/")) { s = s.substring(0, s.length() - 1); } return s; } }
public class class_name { public static String buildPath(final boolean endWithSep, final String... val) { StringBuilder path = new StringBuilder(); for (String s: val) { if (s != null) { path.append(s); // depends on control dependency: [if], data = [(s] } } String s = path.toString().replaceAll("/+", "/"); if (endWithSep) { if (!s.endsWith("/")) { s += "/"; // depends on control dependency: [if], data = [none] } } else if (s.endsWith("/")) { s = s.substring(0, s.length() - 1); // depends on control dependency: [if], data = [none] } return s; } }
public class class_name { static DateTimeZone getDateTimeZone(PageContext pc, Tag fromTag) { DateTimeZone tz = null; Tag t = findAncestorWithClass(fromTag, DateTimeZoneSupport.class); if (t != null) { // use time zone from parent <timeZone> tag DateTimeZoneSupport parent = (DateTimeZoneSupport) t; tz = parent.getDateTimeZone(); } else { // get time zone from configuration setting Object obj = Config.find(pc, FMT_TIME_ZONE); if (obj != null) { if (obj instanceof DateTimeZone) { tz = (DateTimeZone) obj; } else { try { tz = DateTimeZone.forID((String) obj); } catch (IllegalArgumentException iae) { tz = DateTimeZone.UTC; } } } } return tz; } }
public class class_name { static DateTimeZone getDateTimeZone(PageContext pc, Tag fromTag) { DateTimeZone tz = null; Tag t = findAncestorWithClass(fromTag, DateTimeZoneSupport.class); if (t != null) { // use time zone from parent <timeZone> tag DateTimeZoneSupport parent = (DateTimeZoneSupport) t; tz = parent.getDateTimeZone(); // depends on control dependency: [if], data = [none] } else { // get time zone from configuration setting Object obj = Config.find(pc, FMT_TIME_ZONE); if (obj != null) { if (obj instanceof DateTimeZone) { tz = (DateTimeZone) obj; // depends on control dependency: [if], data = [none] } else { try { tz = DateTimeZone.forID((String) obj); // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException iae) { tz = DateTimeZone.UTC; } // depends on control dependency: [catch], data = [none] } } } return tz; } }
public class class_name { public void marshall(GetJobTemplateRequest getJobTemplateRequest, ProtocolMarshaller protocolMarshaller) { if (getJobTemplateRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getJobTemplateRequest.getName(), NAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(GetJobTemplateRequest getJobTemplateRequest, ProtocolMarshaller protocolMarshaller) { if (getJobTemplateRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getJobTemplateRequest.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private void run(Class<?> type, Object val, int limit) { int initial; initial = dest.getSize(); if (val == null) { if (type.isPrimitive()) { throw new IllegalArgumentException("primitive null"); } // null is not a string, but otherwise it is ambiguous dest.emit(LDC, (String) null); } else if (val instanceof String) { dest.emit(LDC, (String) val); } else if (type.isPrimitive()) { primitive(ClassRef.findComponent(type).id, val); } else if (type.isArray()) { array(type, val, limit); } else { object(type, val, limit); } if (dest.getSize() - initial > limit) { throw new IllegalStateException( "limit:" + limit + " used:" + (dest.getSize() - initial) + " val:" + val); } } }
public class class_name { private void run(Class<?> type, Object val, int limit) { int initial; initial = dest.getSize(); if (val == null) { if (type.isPrimitive()) { throw new IllegalArgumentException("primitive null"); } // null is not a string, but otherwise it is ambiguous dest.emit(LDC, (String) null); // depends on control dependency: [if], data = [null)] } else if (val instanceof String) { dest.emit(LDC, (String) val); // depends on control dependency: [if], data = [none] } else if (type.isPrimitive()) { primitive(ClassRef.findComponent(type).id, val); // depends on control dependency: [if], data = [none] } else if (type.isArray()) { array(type, val, limit); // depends on control dependency: [if], data = [none] } else { object(type, val, limit); // depends on control dependency: [if], data = [none] } if (dest.getSize() - initial > limit) { throw new IllegalStateException( "limit:" + limit + " used:" + (dest.getSize() - initial) + " val:" + val); } } }
public class class_name { private static boolean waitForServerUp(String hostname, int port, long timeout) { long start = System.currentTimeMillis(); while (true) { try { Socket sock = new Socket(hostname, port); BufferedReader reader = null; try { OutputStream outstream = sock.getOutputStream(); outstream.write("stat".getBytes()); outstream.flush(); Reader isr = new InputStreamReader(sock.getInputStream()); reader = new BufferedReader(isr); String line = reader.readLine(); if (line != null && line.startsWith("Zookeeper version:")) { return true; } } finally { sock.close(); if (reader != null) { reader.close(); } } } catch (IOException e) { // ignore as this is expected logger.info("server " + hostname + ":" + port + " not up " + e); } if (System.currentTimeMillis() > start + timeout) { break; } try { Thread.sleep(250); } catch (InterruptedException e) { // ignore } } return false; } }
public class class_name { private static boolean waitForServerUp(String hostname, int port, long timeout) { long start = System.currentTimeMillis(); while (true) { try { Socket sock = new Socket(hostname, port); BufferedReader reader = null; try { OutputStream outstream = sock.getOutputStream(); outstream.write("stat".getBytes()); // depends on control dependency: [try], data = [none] outstream.flush(); // depends on control dependency: [try], data = [none] Reader isr = new InputStreamReader(sock.getInputStream()); reader = new BufferedReader(isr); // depends on control dependency: [try], data = [none] String line = reader.readLine(); if (line != null && line.startsWith("Zookeeper version:")) { return true; // depends on control dependency: [if], data = [none] } } finally { sock.close(); if (reader != null) { reader.close(); // depends on control dependency: [if], data = [none] } } } catch (IOException e) { // ignore as this is expected logger.info("server " + hostname + ":" + port + " not up " + e); } // depends on control dependency: [catch], data = [none] if (System.currentTimeMillis() > start + timeout) { break; } try { Thread.sleep(250); // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { // ignore } // depends on control dependency: [catch], data = [none] } return false; } }
public class class_name { private void handleSnappyCompression(final ChannelHandlerContext ctx, final BinaryMemcacheRequest r) { if (!(r instanceof FullBinaryMemcacheRequest)) { // we only need to handle requests which send content return; } FullBinaryMemcacheRequest request = (FullBinaryMemcacheRequest) r; int uncompressedLength = request.content().readableBytes(); // don't bother compressing if below the min compression size if (uncompressedLength < minCompressionSize || uncompressedLength == 0) { return; } ByteBuf compressedContent; try { compressedContent = tryCompress(request.content()); } catch (Exception ex) { throw new RuntimeException("Could not snappy-compress value.", ex); } if (compressedContent != null) { // compressed is smaller, so adapt and apply new content request.setDataType((byte)(request.getDataType() | DATATYPE_SNAPPY)); request.setContent(compressedContent); request.setTotalBodyLength( request.getExtrasLength() + request.getKeyLength() + compressedContent.readableBytes() ); } } }
public class class_name { private void handleSnappyCompression(final ChannelHandlerContext ctx, final BinaryMemcacheRequest r) { if (!(r instanceof FullBinaryMemcacheRequest)) { // we only need to handle requests which send content return; // depends on control dependency: [if], data = [none] } FullBinaryMemcacheRequest request = (FullBinaryMemcacheRequest) r; int uncompressedLength = request.content().readableBytes(); // don't bother compressing if below the min compression size if (uncompressedLength < minCompressionSize || uncompressedLength == 0) { return; // depends on control dependency: [if], data = [none] } ByteBuf compressedContent; try { compressedContent = tryCompress(request.content()); // depends on control dependency: [try], data = [none] } catch (Exception ex) { throw new RuntimeException("Could not snappy-compress value.", ex); } // depends on control dependency: [catch], data = [none] if (compressedContent != null) { // compressed is smaller, so adapt and apply new content request.setDataType((byte)(request.getDataType() | DATATYPE_SNAPPY)); // depends on control dependency: [if], data = [none] request.setContent(compressedContent); // depends on control dependency: [if], data = [(compressedContent] request.setTotalBodyLength( request.getExtrasLength() + request.getKeyLength() + compressedContent.readableBytes() ); // depends on control dependency: [if], data = [none] } } }
public class class_name { static <E extends Entity> String getSqlCount( EntityType entityType, Query<E> q, List<Object> parameters) { StringBuilder sqlBuilder = new StringBuilder("SELECT COUNT"); String idAttribute = getColumnName(entityType.getIdAttribute()); List<QueryRule> queryRules = q.getRules(); if (queryRules == null || queryRules.isEmpty()) { sqlBuilder.append("(*) FROM ").append(getTableName(entityType)); } else { boolean distinctSelectRequired = isDistinctSelectRequired(entityType, q); if (distinctSelectRequired) { // distinct count in case query contains one or more rules referring to MREF attributes. sqlBuilder.append("(DISTINCT this.").append(idAttribute).append(')'); } else { sqlBuilder.append("(*)"); } String from = getSqlFrom(entityType, q); String where = getSqlWhere(entityType, q, parameters, new AtomicInteger()); sqlBuilder.append(from).append(" WHERE ").append(where); } return sqlBuilder.toString(); } }
public class class_name { static <E extends Entity> String getSqlCount( EntityType entityType, Query<E> q, List<Object> parameters) { StringBuilder sqlBuilder = new StringBuilder("SELECT COUNT"); String idAttribute = getColumnName(entityType.getIdAttribute()); List<QueryRule> queryRules = q.getRules(); if (queryRules == null || queryRules.isEmpty()) { sqlBuilder.append("(*) FROM ").append(getTableName(entityType)); // depends on control dependency: [if], data = [none] } else { boolean distinctSelectRequired = isDistinctSelectRequired(entityType, q); if (distinctSelectRequired) { // distinct count in case query contains one or more rules referring to MREF attributes. sqlBuilder.append("(DISTINCT this.").append(idAttribute).append(')'); // depends on control dependency: [if], data = [none] } else { sqlBuilder.append("(*)"); // depends on control dependency: [if], data = [none] } String from = getSqlFrom(entityType, q); String where = getSqlWhere(entityType, q, parameters, new AtomicInteger()); sqlBuilder.append(from).append(" WHERE ").append(where); // depends on control dependency: [if], data = [none] } return sqlBuilder.toString(); } }
public class class_name { private static LineMap loadScriptMap(Class cl) { ClassLoader loader = cl.getClassLoader(); if (loader == null) return new LineMap(); // null map try { String pathName = cl.getName().replace('.', '/') + ".class"; InputStream is = loader.getResourceAsStream(pathName); if (is == null) return null; try { JavaClass jClass = new ByteCodeParser().parse(is); Attribute attr = jClass.getAttribute("SourceDebugExtension"); if (attr == null) { int p = cl.getName().indexOf('$'); if (p > 0) { String className = cl.getName().substring(0, p); return loadScriptMap(loader.loadClass(className)); } return new LineMap(); } else if (attr instanceof OpaqueAttribute) { byte []value = ((OpaqueAttribute) attr).getValue(); ByteArrayInputStream bis = new ByteArrayInputStream(value); ReadStreamOld rs = VfsOld.openRead(bis); rs.setEncoding("UTF-8"); try { return parseSmap(rs); } finally { rs.close(); } } else throw new IllegalStateException(L.l("Expected opaque attribute at '{0}'", attr)); } finally { if (is != null) is.close(); } } catch (Throwable e) { log.finer(e.toString()); log.log(Level.FINEST, e.toString(), e); return new LineMap(); // null map } } }
public class class_name { private static LineMap loadScriptMap(Class cl) { ClassLoader loader = cl.getClassLoader(); if (loader == null) return new LineMap(); // null map try { String pathName = cl.getName().replace('.', '/') + ".class"; InputStream is = loader.getResourceAsStream(pathName); if (is == null) return null; try { JavaClass jClass = new ByteCodeParser().parse(is); Attribute attr = jClass.getAttribute("SourceDebugExtension"); if (attr == null) { int p = cl.getName().indexOf('$'); if (p > 0) { String className = cl.getName().substring(0, p); return loadScriptMap(loader.loadClass(className)); // depends on control dependency: [if], data = [none] } return new LineMap(); // depends on control dependency: [if], data = [none] } else if (attr instanceof OpaqueAttribute) { byte []value = ((OpaqueAttribute) attr).getValue(); ByteArrayInputStream bis = new ByteArrayInputStream(value); ReadStreamOld rs = VfsOld.openRead(bis); rs.setEncoding("UTF-8"); // depends on control dependency: [if], data = [none] try { return parseSmap(rs); // depends on control dependency: [try], data = [none] } finally { rs.close(); } } else throw new IllegalStateException(L.l("Expected opaque attribute at '{0}'", attr)); } finally { if (is != null) is.close(); } } catch (Throwable e) { log.finer(e.toString()); log.log(Level.FINEST, e.toString(), e); return new LineMap(); // null map } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static String getLocalName(Element element) { String name = element.getTagName(); if (name.indexOf(':') > 0) { name = name.substring(name.indexOf(':')+1); } return name; } }
public class class_name { public static String getLocalName(Element element) { String name = element.getTagName(); if (name.indexOf(':') > 0) { name = name.substring(name.indexOf(':')+1); // depends on control dependency: [if], data = [(name.indexOf(':')] } return name; } }
public class class_name { public boolean isConnectionHandleAlive(ConnectionHandle connection) { Statement stmt = null; boolean result = false; boolean logicallyClosed = connection.logicallyClosed.get(); try { connection.logicallyClosed.compareAndSet(true, false); // avoid checks later on if it's marked as closed. String testStatement = this.config.getConnectionTestStatement(); ResultSet rs = null; if (testStatement == null) { // Make a call to fetch the metadata instead of a dummy query. rs = connection.getMetaData().getTables( null, null, KEEPALIVEMETADATA, METADATATABLE ); } else { stmt = connection.createStatement(); stmt.execute(testStatement); } if (rs != null) { rs.close(); } result = true; } catch (SQLException e) { // connection must be broken! result = false; } finally { connection.logicallyClosed.set(logicallyClosed); connection.setConnectionLastResetInMs(System.currentTimeMillis()); result = closeStatement(stmt, result); } return result; } }
public class class_name { public boolean isConnectionHandleAlive(ConnectionHandle connection) { Statement stmt = null; boolean result = false; boolean logicallyClosed = connection.logicallyClosed.get(); try { connection.logicallyClosed.compareAndSet(true, false); // avoid checks later on if it's marked as closed. // depends on control dependency: [try], data = [none] String testStatement = this.config.getConnectionTestStatement(); ResultSet rs = null; if (testStatement == null) { // Make a call to fetch the metadata instead of a dummy query. rs = connection.getMetaData().getTables( null, null, KEEPALIVEMETADATA, METADATATABLE ); // depends on control dependency: [if], data = [none] } else { stmt = connection.createStatement(); // depends on control dependency: [if], data = [none] stmt.execute(testStatement); // depends on control dependency: [if], data = [(testStatement] } if (rs != null) { rs.close(); // depends on control dependency: [if], data = [none] } result = true; // depends on control dependency: [try], data = [none] } catch (SQLException e) { // connection must be broken! result = false; } finally { // depends on control dependency: [catch], data = [none] connection.logicallyClosed.set(logicallyClosed); connection.setConnectionLastResetInMs(System.currentTimeMillis()); result = closeStatement(stmt, result); } return result; } }
public class class_name { public double getNumericValue() { String original = getText().toString().replaceAll(mNumberFilterRegex, ""); if (hasCustomDecimalSeparator) { // swap custom decimal separator with locale one to allow parsing original = StringUtils.replace(original, String.valueOf(mDecimalSeparator), String.valueOf(DECIMAL_SEPARATOR)); } try { return NumberFormat.getInstance().parse(original).doubleValue(); } catch (ParseException e) { return Double.NaN; } } }
public class class_name { public double getNumericValue() { String original = getText().toString().replaceAll(mNumberFilterRegex, ""); if (hasCustomDecimalSeparator) { // swap custom decimal separator with locale one to allow parsing original = StringUtils.replace(original, String.valueOf(mDecimalSeparator), String.valueOf(DECIMAL_SEPARATOR)); // depends on control dependency: [if], data = [none] } try { return NumberFormat.getInstance().parse(original).doubleValue(); // depends on control dependency: [try], data = [none] } catch (ParseException e) { return Double.NaN; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void applyAllFormatterChanges( Map<CmsUUID, I_CmsFormatterBean> formatters, CmsFormatterConfigurationCacheState formatterCacheState) { for (CmsFormatterChangeSet changeSet : getFormatterChangeSets()) { changeSet.applyToFormatters(formatters, formatterCacheState); } } }
public class class_name { public void applyAllFormatterChanges( Map<CmsUUID, I_CmsFormatterBean> formatters, CmsFormatterConfigurationCacheState formatterCacheState) { for (CmsFormatterChangeSet changeSet : getFormatterChangeSets()) { changeSet.applyToFormatters(formatters, formatterCacheState); // depends on control dependency: [for], data = [changeSet] } } }
public class class_name { @Override public void firstPassE(NumberVector vec, double wei) { final int dim = mean.length; assert (vec.getDimensionality() == dim); assert (wei >= 0 && wei < Double.POSITIVE_INFINITY) : wei; if(wei < Double.MIN_NORMAL) { return; } // Aggregate for(int i = 0; i < dim; i++) { mean[i] += vec.doubleValue(i) * wei; } wsum += wei; } }
public class class_name { @Override public void firstPassE(NumberVector vec, double wei) { final int dim = mean.length; assert (vec.getDimensionality() == dim); assert (wei >= 0 && wei < Double.POSITIVE_INFINITY) : wei; if(wei < Double.MIN_NORMAL) { return; // depends on control dependency: [if], data = [none] } // Aggregate for(int i = 0; i < dim; i++) { mean[i] += vec.doubleValue(i) * wei; // depends on control dependency: [for], data = [i] } wsum += wei; } }
public class class_name { public static <E> CompletableSource resolveScopeFromLifecycle( final LifecycleScopeProvider<E> provider, final boolean checkEndBoundary) throws OutsideScopeException { E lastEvent = provider.peekLifecycle(); CorrespondingEventsFunction<E> eventsFunction = provider.correspondingEvents(); if (lastEvent == null) { throw new LifecycleNotStartedException(); } E endEvent; try { endEvent = eventsFunction.apply(lastEvent); } catch (Exception e) { if (checkEndBoundary && e instanceof LifecycleEndedException) { Consumer<? super OutsideScopeException> handler = AutoDisposePlugins.getOutsideScopeHandler(); if (handler != null) { try { handler.accept((LifecycleEndedException) e); // Swallowed the end exception, just silently dispose immediately. return Completable.complete(); } catch (Exception e1) { return Completable.error(e1); } } throw e; } return Completable.error(e); } return resolveScopeFromLifecycle(provider.lifecycle(), endEvent); } }
public class class_name { public static <E> CompletableSource resolveScopeFromLifecycle( final LifecycleScopeProvider<E> provider, final boolean checkEndBoundary) throws OutsideScopeException { E lastEvent = provider.peekLifecycle(); CorrespondingEventsFunction<E> eventsFunction = provider.correspondingEvents(); if (lastEvent == null) { throw new LifecycleNotStartedException(); } E endEvent; try { endEvent = eventsFunction.apply(lastEvent); } catch (Exception e) { if (checkEndBoundary && e instanceof LifecycleEndedException) { Consumer<? super OutsideScopeException> handler = AutoDisposePlugins.getOutsideScopeHandler(); // depends on control dependency: [if], data = [none] if (handler != null) { try { handler.accept((LifecycleEndedException) e); // depends on control dependency: [try], data = [none] // Swallowed the end exception, just silently dispose immediately. return Completable.complete(); // depends on control dependency: [try], data = [none] } catch (Exception e1) { return Completable.error(e1); } // depends on control dependency: [catch], data = [none] } throw e; } return Completable.error(e); } return resolveScopeFromLifecycle(provider.lifecycle(), endEvent); } }
public class class_name { public void install(Duration delay) { if(installed != null) { installed.unsubscribe(); } installed = events(delay).<Event>map(either -> either.unify( pos -> MouseStationaryEvent.beginAt(node.localToScreen(pos)), stop -> MouseStationaryEvent.end())) .subscribe(evt -> Event.fireEvent(node, evt)); } }
public class class_name { public void install(Duration delay) { if(installed != null) { installed.unsubscribe(); // depends on control dependency: [if], data = [none] } installed = events(delay).<Event>map(either -> either.unify( pos -> MouseStationaryEvent.beginAt(node.localToScreen(pos)), stop -> MouseStationaryEvent.end())) .subscribe(evt -> Event.fireEvent(node, evt)); } }
public class class_name { public void requestPubkey(final BitmessageAddress contact) { BitmessageAddress stored = addressRepository.getAddress(contact.getAddress()); tryToFindMatchingPubkey(contact); if (contact.getPubkey() != null) { if (stored != null) { stored.setPubkey(contact.getPubkey()); addressRepository.save(stored); } else { addressRepository.save(contact); } return; } if (stored == null) { addressRepository.save(contact); } long expires = UnixTime.now(TTL.getpubkey()); LOG.info("Expires at " + expires); final ObjectMessage request = new ObjectMessage.Builder() .stream(contact.getStream()) .expiresTime(expires) .payload(new GetPubkey(contact)) .build(); proofOfWorkService.doProofOfWork(request); } }
public class class_name { public void requestPubkey(final BitmessageAddress contact) { BitmessageAddress stored = addressRepository.getAddress(contact.getAddress()); tryToFindMatchingPubkey(contact); if (contact.getPubkey() != null) { if (stored != null) { stored.setPubkey(contact.getPubkey()); // depends on control dependency: [if], data = [none] addressRepository.save(stored); // depends on control dependency: [if], data = [(stored] } else { addressRepository.save(contact); // depends on control dependency: [if], data = [none] } return; // depends on control dependency: [if], data = [none] } if (stored == null) { addressRepository.save(contact); // depends on control dependency: [if], data = [none] } long expires = UnixTime.now(TTL.getpubkey()); LOG.info("Expires at " + expires); final ObjectMessage request = new ObjectMessage.Builder() .stream(contact.getStream()) .expiresTime(expires) .payload(new GetPubkey(contact)) .build(); proofOfWorkService.doProofOfWork(request); } }
public class class_name { @Override public void removeByGroupId(long groupId) { for (CPSpecificationOption cpSpecificationOption : findByGroupId( groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpSpecificationOption); } } }
public class class_name { @Override public void removeByGroupId(long groupId) { for (CPSpecificationOption cpSpecificationOption : findByGroupId( groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpSpecificationOption); // depends on control dependency: [for], data = [cpSpecificationOption] } } }
public class class_name { ListIterator<RuleConditionElement> stackIterator() { if (this.buildstack == null) { this.buildstack = new LinkedList<>(); } return this.buildstack.listIterator(this.buildstack.size()); } }
public class class_name { ListIterator<RuleConditionElement> stackIterator() { if (this.buildstack == null) { this.buildstack = new LinkedList<>(); // depends on control dependency: [if], data = [none] } return this.buildstack.listIterator(this.buildstack.size()); } }
public class class_name { private static <T extends Bean> Constructor<T> findConstructor(Class<T> beanType, List<Class<?>> propertyTypes) { Class<?>[] types = propertyTypes.toArray(new Class<?>[propertyTypes.size()]); try { Constructor<T> con = beanType.getDeclaredConstructor(types); return con; } catch (NoSuchMethodException ex) { // try a more lenient search // this handles cases where field is a concrete class and constructor is an interface @SuppressWarnings("unchecked") Constructor<T>[] cons = (Constructor<T>[]) beanType.getDeclaredConstructors(); Constructor<T> match = null; for (int i = 0; i < cons.length; i++) { Constructor<T> con = cons[i]; Class<?>[] conTypes = con.getParameterTypes(); if (conTypes.length == types.length) { for (int j = 0; j < types.length; j++) { if (!conTypes[j].isAssignableFrom(types[j])) { break; } } if (match != null) { throw new UnsupportedOperationException("Unable to find constructor: More than one matches"); } match = con; } } if (match == null) { String msg = "Unable to find constructor: " + beanType.getSimpleName() + "("; for (Class<?> type : types) { msg += Objects.toString(type.getName(), "<null>"); } msg += ")"; throw new UnsupportedOperationException(msg, ex); } return match; } } }
public class class_name { private static <T extends Bean> Constructor<T> findConstructor(Class<T> beanType, List<Class<?>> propertyTypes) { Class<?>[] types = propertyTypes.toArray(new Class<?>[propertyTypes.size()]); try { Constructor<T> con = beanType.getDeclaredConstructor(types); return con; } catch (NoSuchMethodException ex) { // try a more lenient search // this handles cases where field is a concrete class and constructor is an interface @SuppressWarnings("unchecked") Constructor<T>[] cons = (Constructor<T>[]) beanType.getDeclaredConstructors(); Constructor<T> match = null; for (int i = 0; i < cons.length; i++) { Constructor<T> con = cons[i]; Class<?>[] conTypes = con.getParameterTypes(); if (conTypes.length == types.length) { for (int j = 0; j < types.length; j++) { if (!conTypes[j].isAssignableFrom(types[j])) { break; } } if (match != null) { throw new UnsupportedOperationException("Unable to find constructor: More than one matches"); } match = con; // depends on control dependency: [if], data = [none] } } if (match == null) { String msg = "Unable to find constructor: " + beanType.getSimpleName() + "("; for (Class<?> type : types) { msg += Objects.toString(type.getName(), "<null>"); // depends on control dependency: [for], data = [type] } msg += ")"; // depends on control dependency: [if], data = [none] throw new UnsupportedOperationException(msg, ex); } return match; } } }
public class class_name { public static ModifyType detectModifyType(SQLiteModelMethod method, JQLType jqlType) { // Elements elementUtils = BaseProcessor.elementUtils; SQLiteDaoDefinition daoDefinition = method.getParent(); SQLiteEntity entity = method.getEntity(); ModifyType updateResultType = null; // check type of arguments int count = 0; for (Pair<String, TypeName> param : method.getParameters()) { if (method.isThisDynamicWhereConditionsName(param.value0)) { // if current parameter is dynamic where, skip it continue; } if (TypeUtility.isEquals(param.value1, typeName(entity.getElement()))) { count++; } } if (count == 0) { // method to update raw data: no bean is used updateResultType = jqlType == JQLType.UPDATE ? ModifyType.UPDATE_RAW : ModifyType.DELETE_RAW; ModelAnnotation annotation; if (jqlType == JQLType.UPDATE) { annotation = method.getAnnotation(BindSqlUpdate.class); AssertKripton.assertTrueOrInvalidMethodSignException( AnnotationUtility.extractAsStringArray(method, annotation, AnnotationAttributeType.FIELDS) .size() == 0, method, " can not use attribute %s in this kind of query definition", AnnotationAttributeType.FIELDS.getValue()); AssertKripton .assertTrueOrInvalidMethodSignException( AnnotationUtility.extractAsStringArray(method, annotation, AnnotationAttributeType.EXCLUDED_FIELDS).size() == 0, method, " can not use attribute %s in this kind of query definition", AnnotationAttributeType.EXCLUDED_FIELDS.getValue()); } else { annotation = method.getAnnotation(BindSqlDelete.class); } // check if there is only one parameter AssertKripton.failWithInvalidMethodSignException(method.getParameters().size() > 1 && TypeUtility.isEquals(method.getParameters().get(0).value1, daoDefinition.getEntityClassName()), method); } else if (count == 1) { updateResultType = jqlType == JQLType.UPDATE ? ModifyType.UPDATE_BEAN : ModifyType.DELETE_BEAN; // with dynamic where conditions, we have to add 1 to parameter // check size (one parameter is a bean and one is the where // conditions) AssertKripton.assertTrueOrInvalidMethodSignException( method.getParameters().size() == 1 + (method.hasDynamicWhereConditions() ? 1 : 0) + (method.hasDynamicWhereArgs() ? 1 : 0), method, " expected only one parameter of %s type", daoDefinition.getEntityClassName()); } else { throw (new InvalidMethodSignException(method, "only one parameter of type " + typeName(entity.getElement()) + " can be used")); } return updateResultType; } }
public class class_name { public static ModifyType detectModifyType(SQLiteModelMethod method, JQLType jqlType) { // Elements elementUtils = BaseProcessor.elementUtils; SQLiteDaoDefinition daoDefinition = method.getParent(); SQLiteEntity entity = method.getEntity(); ModifyType updateResultType = null; // check type of arguments int count = 0; for (Pair<String, TypeName> param : method.getParameters()) { if (method.isThisDynamicWhereConditionsName(param.value0)) { // if current parameter is dynamic where, skip it continue; } if (TypeUtility.isEquals(param.value1, typeName(entity.getElement()))) { count++; // depends on control dependency: [if], data = [none] } } if (count == 0) { // method to update raw data: no bean is used updateResultType = jqlType == JQLType.UPDATE ? ModifyType.UPDATE_RAW : ModifyType.DELETE_RAW; // depends on control dependency: [if], data = [none] ModelAnnotation annotation; if (jqlType == JQLType.UPDATE) { annotation = method.getAnnotation(BindSqlUpdate.class); // depends on control dependency: [if], data = [none] AssertKripton.assertTrueOrInvalidMethodSignException( AnnotationUtility.extractAsStringArray(method, annotation, AnnotationAttributeType.FIELDS) .size() == 0, method, " can not use attribute %s in this kind of query definition", AnnotationAttributeType.FIELDS.getValue()); // depends on control dependency: [if], data = [none] AssertKripton .assertTrueOrInvalidMethodSignException( AnnotationUtility.extractAsStringArray(method, annotation, AnnotationAttributeType.EXCLUDED_FIELDS).size() == 0, method, " can not use attribute %s in this kind of query definition", AnnotationAttributeType.EXCLUDED_FIELDS.getValue()); // depends on control dependency: [if], data = [none] } else { annotation = method.getAnnotation(BindSqlDelete.class); // depends on control dependency: [if], data = [none] } // check if there is only one parameter AssertKripton.failWithInvalidMethodSignException(method.getParameters().size() > 1 && TypeUtility.isEquals(method.getParameters().get(0).value1, daoDefinition.getEntityClassName()), method); // depends on control dependency: [if], data = [none] } else if (count == 1) { updateResultType = jqlType == JQLType.UPDATE ? ModifyType.UPDATE_BEAN : ModifyType.DELETE_BEAN; // depends on control dependency: [if], data = [none] // with dynamic where conditions, we have to add 1 to parameter // check size (one parameter is a bean and one is the where // conditions) AssertKripton.assertTrueOrInvalidMethodSignException( method.getParameters().size() == 1 + (method.hasDynamicWhereConditions() ? 1 : 0) + (method.hasDynamicWhereArgs() ? 1 : 0), method, " expected only one parameter of %s type", daoDefinition.getEntityClassName()); // depends on control dependency: [if], data = [none] } else { throw (new InvalidMethodSignException(method, "only one parameter of type " + typeName(entity.getElement()) + " can be used")); } return updateResultType; } }
public class class_name { private InnerEnum generateColumnEnum(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { // 生成内部枚举 InnerEnum innerEnum = new InnerEnum(new FullyQualifiedJavaType(ENUM_NAME)); innerEnum.setVisibility(JavaVisibility.PUBLIC); innerEnum.setStatic(true); commentGenerator.addEnumComment(innerEnum, introspectedTable); logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + "增加内部Builder类。"); // 生成常量 Field beginningDelimiterField = JavaElementGeneratorTools.generateField( CONST_BEGINNING_DELIMITER, JavaVisibility.PRIVATE, FullyQualifiedJavaType.getStringInstance(), "\"" + StringUtility.escapeStringForJava(context.getBeginningDelimiter()) + "\"" ); beginningDelimiterField.setStatic(true); beginningDelimiterField.setFinal(true); commentGenerator.addFieldComment(beginningDelimiterField, introspectedTable); innerEnum.addField(beginningDelimiterField); Field endingDelimiterField = JavaElementGeneratorTools.generateField( CONST_ENDING_DELIMITER, JavaVisibility.PRIVATE, FullyQualifiedJavaType.getStringInstance(), "\"" + StringUtility.escapeStringForJava(context.getEndingDelimiter()) + "\"" ); endingDelimiterField.setStatic(true); endingDelimiterField.setFinal(true); commentGenerator.addFieldComment(endingDelimiterField, introspectedTable); innerEnum.addField(endingDelimiterField); // 生成属性和构造函数 Field columnField = new Field("column", FullyQualifiedJavaType.getStringInstance()); columnField.setVisibility(JavaVisibility.PRIVATE); columnField.setFinal(true); commentGenerator.addFieldComment(columnField, introspectedTable); innerEnum.addField(columnField); Field isColumnNameDelimitedField = new Field("isColumnNameDelimited", FullyQualifiedJavaType.getBooleanPrimitiveInstance()); isColumnNameDelimitedField.setVisibility(JavaVisibility.PRIVATE); isColumnNameDelimitedField.setFinal(true); commentGenerator.addFieldComment(isColumnNameDelimitedField, introspectedTable); innerEnum.addField(isColumnNameDelimitedField); Field javaPropertyField = new Field("javaProperty", FullyQualifiedJavaType.getStringInstance()); javaPropertyField.setVisibility(JavaVisibility.PRIVATE); javaPropertyField.setFinal(true); commentGenerator.addFieldComment(javaPropertyField, introspectedTable); innerEnum.addField(javaPropertyField); Field jdbcTypeField = new Field("jdbcType", FullyQualifiedJavaType.getStringInstance()); jdbcTypeField.setVisibility(JavaVisibility.PRIVATE); jdbcTypeField.setFinal(true); commentGenerator.addFieldComment(jdbcTypeField, introspectedTable); innerEnum.addField(jdbcTypeField); Method mValue = new Method("value"); mValue.setVisibility(JavaVisibility.PUBLIC); mValue.setReturnType(FullyQualifiedJavaType.getStringInstance()); mValue.addBodyLine("return this.column;"); commentGenerator.addGeneralMethodComment(mValue, introspectedTable); FormatTools.addMethodWithBestPosition(innerEnum, mValue); Method mGetValue = new Method("getValue"); mGetValue.setVisibility(JavaVisibility.PUBLIC); mGetValue.setReturnType(FullyQualifiedJavaType.getStringInstance()); mGetValue.addBodyLine("return this.column;"); commentGenerator.addGeneralMethodComment(mGetValue, introspectedTable); FormatTools.addMethodWithBestPosition(innerEnum, mGetValue); Method mGetJavaProperty = JavaElementGeneratorTools.generateGetterMethod(javaPropertyField); commentGenerator.addGeneralMethodComment(mGetJavaProperty, introspectedTable); FormatTools.addMethodWithBestPosition(innerEnum, mGetJavaProperty); Method mGetJdbcType = JavaElementGeneratorTools.generateGetterMethod(jdbcTypeField); commentGenerator.addGeneralMethodComment(mGetJdbcType, introspectedTable); FormatTools.addMethodWithBestPosition(innerEnum, mGetJdbcType); Method constructor = new Method(ENUM_NAME); constructor.setConstructor(true); constructor.addBodyLine("this.column = column;"); constructor.addBodyLine("this.javaProperty = javaProperty;"); constructor.addBodyLine("this.jdbcType = jdbcType;"); constructor.addBodyLine("this.isColumnNameDelimited = isColumnNameDelimited;"); constructor.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "column")); constructor.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "javaProperty")); constructor.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "jdbcType")); constructor.addParameter(new Parameter(FullyQualifiedJavaType.getBooleanPrimitiveInstance(), "isColumnNameDelimited")); commentGenerator.addGeneralMethodComment(constructor, introspectedTable); FormatTools.addMethodWithBestPosition(innerEnum, constructor); logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加构造方法和column属性。"); // Enum枚举 for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) { Field field = JavaBeansUtil.getJavaBeansField(introspectedColumn, context, introspectedTable); StringBuffer sb = new StringBuffer(); sb.append(field.getName()); sb.append("(\""); sb.append(introspectedColumn.getActualColumnName()); sb.append("\", \""); sb.append(introspectedColumn.getJavaProperty()); sb.append("\", \""); sb.append(introspectedColumn.getJdbcTypeName()); sb.append("\", "); sb.append(introspectedColumn.isColumnNameDelimited()); sb.append(")"); innerEnum.addEnumConstant(sb.toString()); logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加" + field.getName() + "枚举。"); } // asc 和 desc 方法 Method desc = new Method("desc"); desc.setVisibility(JavaVisibility.PUBLIC); desc.setReturnType(FullyQualifiedJavaType.getStringInstance()); desc.addBodyLine("return this." + METHOD_GET_ESCAPED_COLUMN_NAME + "() + \" DESC\";"); commentGenerator.addGeneralMethodComment(desc, introspectedTable); FormatTools.addMethodWithBestPosition(innerEnum, desc); Method asc = new Method("asc"); asc.setVisibility(JavaVisibility.PUBLIC); asc.setReturnType(FullyQualifiedJavaType.getStringInstance()); asc.addBodyLine("return this." + METHOD_GET_ESCAPED_COLUMN_NAME + "() + \" ASC\";"); commentGenerator.addGeneralMethodComment(asc, introspectedTable); FormatTools.addMethodWithBestPosition(innerEnum, asc); logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加asc()和desc()方法。"); // excludes topLevelClass.addImportedType("java.util.Arrays"); topLevelClass.addImportedType(FullyQualifiedJavaType.getNewArrayListInstance()); Method mExcludes = JavaElementGeneratorTools.generateMethod( METHOD_EXCLUDES, JavaVisibility.PUBLIC, new FullyQualifiedJavaType(ENUM_NAME + "[]"), new Parameter(innerEnum.getType(), "excludes", true) ); commentGenerator.addGeneralMethodComment(mExcludes, introspectedTable); mExcludes.setStatic(true); JavaElementGeneratorTools.generateMethodBody( mExcludes, "ArrayList<Column> columns = new ArrayList<>(Arrays.asList(Column.values()));", "if (excludes != null && excludes.length > 0) {", "columns.removeAll(new ArrayList<>(Arrays.asList(excludes)));", "}", "return columns.toArray(new Column[]{});" ); FormatTools.addMethodWithBestPosition(innerEnum, mExcludes); logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加excludes方法。"); // getEscapedColumnName Method mGetEscapedColumnName = JavaElementGeneratorTools.generateMethod( METHOD_GET_ESCAPED_COLUMN_NAME, JavaVisibility.PUBLIC, FullyQualifiedJavaType.getStringInstance() ); commentGenerator.addGeneralMethodComment(mGetEscapedColumnName, introspectedTable); JavaElementGeneratorTools.generateMethodBody( mGetEscapedColumnName, "if (this.isColumnNameDelimited) {", "return new StringBuilder().append(" + CONST_BEGINNING_DELIMITER + ").append(this.column).append(" + CONST_ENDING_DELIMITER + ").toString();", "} else {", "return this.column;", "}" ); FormatTools.addMethodWithBestPosition(innerEnum, mGetEscapedColumnName); logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加getEscapedColumnName方法。"); // getAliasedEscapedColumnName Method mGetAliasedEscapedColumnName = JavaElementGeneratorTools.generateMethod( METHOD_GET_ALIASED_ESCAPED_COLUMN_NAME, JavaVisibility.PUBLIC, FullyQualifiedJavaType.getStringInstance() ); commentGenerator.addGeneralMethodComment(mGetAliasedEscapedColumnName, introspectedTable); if (StringUtility.stringHasValue(introspectedTable.getTableConfiguration().getAlias())) { String alias = introspectedTable.getTableConfiguration().getAlias(); mGetAliasedEscapedColumnName.addBodyLine("StringBuilder sb = new StringBuilder();"); mGetAliasedEscapedColumnName.addBodyLine("sb.append(\"" + alias + ".\");"); mGetAliasedEscapedColumnName.addBodyLine("sb.append(this." + METHOD_GET_ESCAPED_COLUMN_NAME + "());"); mGetAliasedEscapedColumnName.addBodyLine("sb.append(\" as \");"); mGetAliasedEscapedColumnName.addBodyLine("if (this.isColumnNameDelimited) {"); mGetAliasedEscapedColumnName.addBodyLine("sb.append("+CONST_BEGINNING_DELIMITER+");"); mGetAliasedEscapedColumnName.addBodyLine("}"); mGetAliasedEscapedColumnName.addBodyLine("sb.append(\""+alias+"_\");"); mGetAliasedEscapedColumnName.addBodyLine("sb.append(this.column);"); mGetAliasedEscapedColumnName.addBodyLine("if (this.isColumnNameDelimited) {"); mGetAliasedEscapedColumnName.addBodyLine("sb.append("+CONST_BEGINNING_DELIMITER+");"); mGetAliasedEscapedColumnName.addBodyLine("}"); mGetAliasedEscapedColumnName.addBodyLine("return sb.toString();"); } else { mGetAliasedEscapedColumnName.addBodyLine("return this." + METHOD_GET_ESCAPED_COLUMN_NAME + "();"); } FormatTools.addMethodWithBestPosition(innerEnum, mGetAliasedEscapedColumnName); logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加getAliasedEscapedColumnName方法。"); return innerEnum; } }
public class class_name { private InnerEnum generateColumnEnum(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { // 生成内部枚举 InnerEnum innerEnum = new InnerEnum(new FullyQualifiedJavaType(ENUM_NAME)); innerEnum.setVisibility(JavaVisibility.PUBLIC); innerEnum.setStatic(true); commentGenerator.addEnumComment(innerEnum, introspectedTable); logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + "增加内部Builder类。"); // 生成常量 Field beginningDelimiterField = JavaElementGeneratorTools.generateField( CONST_BEGINNING_DELIMITER, JavaVisibility.PRIVATE, FullyQualifiedJavaType.getStringInstance(), "\"" + StringUtility.escapeStringForJava(context.getBeginningDelimiter()) + "\"" ); beginningDelimiterField.setStatic(true); beginningDelimiterField.setFinal(true); commentGenerator.addFieldComment(beginningDelimiterField, introspectedTable); innerEnum.addField(beginningDelimiterField); Field endingDelimiterField = JavaElementGeneratorTools.generateField( CONST_ENDING_DELIMITER, JavaVisibility.PRIVATE, FullyQualifiedJavaType.getStringInstance(), "\"" + StringUtility.escapeStringForJava(context.getEndingDelimiter()) + "\"" ); endingDelimiterField.setStatic(true); endingDelimiterField.setFinal(true); commentGenerator.addFieldComment(endingDelimiterField, introspectedTable); innerEnum.addField(endingDelimiterField); // 生成属性和构造函数 Field columnField = new Field("column", FullyQualifiedJavaType.getStringInstance()); columnField.setVisibility(JavaVisibility.PRIVATE); columnField.setFinal(true); commentGenerator.addFieldComment(columnField, introspectedTable); innerEnum.addField(columnField); Field isColumnNameDelimitedField = new Field("isColumnNameDelimited", FullyQualifiedJavaType.getBooleanPrimitiveInstance()); isColumnNameDelimitedField.setVisibility(JavaVisibility.PRIVATE); isColumnNameDelimitedField.setFinal(true); commentGenerator.addFieldComment(isColumnNameDelimitedField, introspectedTable); innerEnum.addField(isColumnNameDelimitedField); Field javaPropertyField = new Field("javaProperty", FullyQualifiedJavaType.getStringInstance()); javaPropertyField.setVisibility(JavaVisibility.PRIVATE); javaPropertyField.setFinal(true); commentGenerator.addFieldComment(javaPropertyField, introspectedTable); innerEnum.addField(javaPropertyField); Field jdbcTypeField = new Field("jdbcType", FullyQualifiedJavaType.getStringInstance()); jdbcTypeField.setVisibility(JavaVisibility.PRIVATE); jdbcTypeField.setFinal(true); commentGenerator.addFieldComment(jdbcTypeField, introspectedTable); innerEnum.addField(jdbcTypeField); Method mValue = new Method("value"); mValue.setVisibility(JavaVisibility.PUBLIC); mValue.setReturnType(FullyQualifiedJavaType.getStringInstance()); mValue.addBodyLine("return this.column;"); commentGenerator.addGeneralMethodComment(mValue, introspectedTable); FormatTools.addMethodWithBestPosition(innerEnum, mValue); Method mGetValue = new Method("getValue"); mGetValue.setVisibility(JavaVisibility.PUBLIC); mGetValue.setReturnType(FullyQualifiedJavaType.getStringInstance()); mGetValue.addBodyLine("return this.column;"); commentGenerator.addGeneralMethodComment(mGetValue, introspectedTable); FormatTools.addMethodWithBestPosition(innerEnum, mGetValue); Method mGetJavaProperty = JavaElementGeneratorTools.generateGetterMethod(javaPropertyField); commentGenerator.addGeneralMethodComment(mGetJavaProperty, introspectedTable); FormatTools.addMethodWithBestPosition(innerEnum, mGetJavaProperty); Method mGetJdbcType = JavaElementGeneratorTools.generateGetterMethod(jdbcTypeField); commentGenerator.addGeneralMethodComment(mGetJdbcType, introspectedTable); FormatTools.addMethodWithBestPosition(innerEnum, mGetJdbcType); Method constructor = new Method(ENUM_NAME); constructor.setConstructor(true); constructor.addBodyLine("this.column = column;"); constructor.addBodyLine("this.javaProperty = javaProperty;"); constructor.addBodyLine("this.jdbcType = jdbcType;"); constructor.addBodyLine("this.isColumnNameDelimited = isColumnNameDelimited;"); constructor.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "column")); constructor.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "javaProperty")); constructor.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "jdbcType")); constructor.addParameter(new Parameter(FullyQualifiedJavaType.getBooleanPrimitiveInstance(), "isColumnNameDelimited")); commentGenerator.addGeneralMethodComment(constructor, introspectedTable); FormatTools.addMethodWithBestPosition(innerEnum, constructor); logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加构造方法和column属性。"); // Enum枚举 for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) { Field field = JavaBeansUtil.getJavaBeansField(introspectedColumn, context, introspectedTable); StringBuffer sb = new StringBuffer(); sb.append(field.getName()); // depends on control dependency: [for], data = [none] sb.append("(\""); // depends on control dependency: [for], data = [none] sb.append(introspectedColumn.getActualColumnName()); // depends on control dependency: [for], data = [introspectedColumn] sb.append("\", \""); // depends on control dependency: [for], data = [none] sb.append(introspectedColumn.getJavaProperty()); // depends on control dependency: [for], data = [introspectedColumn] sb.append("\", \""); // depends on control dependency: [for], data = [none] sb.append(introspectedColumn.getJdbcTypeName()); // depends on control dependency: [for], data = [introspectedColumn] sb.append("\", "); // depends on control dependency: [for], data = [none] sb.append(introspectedColumn.isColumnNameDelimited()); // depends on control dependency: [for], data = [introspectedColumn] sb.append(")"); // depends on control dependency: [for], data = [none] innerEnum.addEnumConstant(sb.toString()); // depends on control dependency: [for], data = [none] logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加" + field.getName() + "枚举。"); // depends on control dependency: [for], data = [none] } // asc 和 desc 方法 Method desc = new Method("desc"); desc.setVisibility(JavaVisibility.PUBLIC); desc.setReturnType(FullyQualifiedJavaType.getStringInstance()); desc.addBodyLine("return this." + METHOD_GET_ESCAPED_COLUMN_NAME + "() + \" DESC\";"); commentGenerator.addGeneralMethodComment(desc, introspectedTable); FormatTools.addMethodWithBestPosition(innerEnum, desc); Method asc = new Method("asc"); asc.setVisibility(JavaVisibility.PUBLIC); asc.setReturnType(FullyQualifiedJavaType.getStringInstance()); asc.addBodyLine("return this." + METHOD_GET_ESCAPED_COLUMN_NAME + "() + \" ASC\";"); commentGenerator.addGeneralMethodComment(asc, introspectedTable); FormatTools.addMethodWithBestPosition(innerEnum, asc); logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加asc()和desc()方法。"); // excludes topLevelClass.addImportedType("java.util.Arrays"); topLevelClass.addImportedType(FullyQualifiedJavaType.getNewArrayListInstance()); Method mExcludes = JavaElementGeneratorTools.generateMethod( METHOD_EXCLUDES, JavaVisibility.PUBLIC, new FullyQualifiedJavaType(ENUM_NAME + "[]"), new Parameter(innerEnum.getType(), "excludes", true) ); commentGenerator.addGeneralMethodComment(mExcludes, introspectedTable); mExcludes.setStatic(true); JavaElementGeneratorTools.generateMethodBody( mExcludes, "ArrayList<Column> columns = new ArrayList<>(Arrays.asList(Column.values()));", "if (excludes != null && excludes.length > 0) {", "columns.removeAll(new ArrayList<>(Arrays.asList(excludes)));", "}", "return columns.toArray(new Column[]{});" ); FormatTools.addMethodWithBestPosition(innerEnum, mExcludes); logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加excludes方法。"); // getEscapedColumnName Method mGetEscapedColumnName = JavaElementGeneratorTools.generateMethod( METHOD_GET_ESCAPED_COLUMN_NAME, JavaVisibility.PUBLIC, FullyQualifiedJavaType.getStringInstance() ); commentGenerator.addGeneralMethodComment(mGetEscapedColumnName, introspectedTable); JavaElementGeneratorTools.generateMethodBody( mGetEscapedColumnName, "if (this.isColumnNameDelimited) {", "return new StringBuilder().append(" + CONST_BEGINNING_DELIMITER + ").append(this.column).append(" + CONST_ENDING_DELIMITER + ").toString();", "} else {", "return this.column;", "}" ); FormatTools.addMethodWithBestPosition(innerEnum, mGetEscapedColumnName); logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加getEscapedColumnName方法。"); // getAliasedEscapedColumnName Method mGetAliasedEscapedColumnName = JavaElementGeneratorTools.generateMethod( METHOD_GET_ALIASED_ESCAPED_COLUMN_NAME, JavaVisibility.PUBLIC, FullyQualifiedJavaType.getStringInstance() ); commentGenerator.addGeneralMethodComment(mGetAliasedEscapedColumnName, introspectedTable); if (StringUtility.stringHasValue(introspectedTable.getTableConfiguration().getAlias())) { String alias = introspectedTable.getTableConfiguration().getAlias(); mGetAliasedEscapedColumnName.addBodyLine("StringBuilder sb = new StringBuilder();"); mGetAliasedEscapedColumnName.addBodyLine("sb.append(\"" + alias + ".\");"); mGetAliasedEscapedColumnName.addBodyLine("sb.append(this." + METHOD_GET_ESCAPED_COLUMN_NAME + "());"); mGetAliasedEscapedColumnName.addBodyLine("sb.append(\" as \");"); mGetAliasedEscapedColumnName.addBodyLine("if (this.isColumnNameDelimited) {"); mGetAliasedEscapedColumnName.addBodyLine("sb.append("+CONST_BEGINNING_DELIMITER+");"); mGetAliasedEscapedColumnName.addBodyLine("}"); mGetAliasedEscapedColumnName.addBodyLine("sb.append(\""+alias+"_\");"); mGetAliasedEscapedColumnName.addBodyLine("sb.append(this.column);"); mGetAliasedEscapedColumnName.addBodyLine("if (this.isColumnNameDelimited) {"); mGetAliasedEscapedColumnName.addBodyLine("sb.append("+CONST_BEGINNING_DELIMITER+");"); mGetAliasedEscapedColumnName.addBodyLine("}"); mGetAliasedEscapedColumnName.addBodyLine("return sb.toString();"); } else { mGetAliasedEscapedColumnName.addBodyLine("return this." + METHOD_GET_ESCAPED_COLUMN_NAME + "();"); } FormatTools.addMethodWithBestPosition(innerEnum, mGetAliasedEscapedColumnName); logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加getAliasedEscapedColumnName方法。"); return innerEnum; } }
public class class_name { public SubscriptionQos setPublicationTtlMs(final long publicationTtlMs) { if (publicationTtlMs < MIN_PUBLICATION_TTL_MS) { this.publicationTtlMs = MIN_PUBLICATION_TTL_MS; logger.warn("publicationTtlMs < MIN_PUBLICATION_TTL. Using MIN_PUBLICATION_TTL: {}", MIN_PUBLICATION_TTL_MS); } else if (publicationTtlMs > MAX_PUBLICATION_TTL_MS) { this.publicationTtlMs = MAX_PUBLICATION_TTL_MS; logger.warn("publicationTtlMs > MAX_PUBLICATION_TTL. Using MAX_PUBLICATION_TTL: {}", MAX_PUBLICATION_TTL_MS); } else { this.publicationTtlMs = publicationTtlMs; } return this; } }
public class class_name { public SubscriptionQos setPublicationTtlMs(final long publicationTtlMs) { if (publicationTtlMs < MIN_PUBLICATION_TTL_MS) { this.publicationTtlMs = MIN_PUBLICATION_TTL_MS; // depends on control dependency: [if], data = [none] logger.warn("publicationTtlMs < MIN_PUBLICATION_TTL. Using MIN_PUBLICATION_TTL: {}", MIN_PUBLICATION_TTL_MS); // depends on control dependency: [if], data = [none] } else if (publicationTtlMs > MAX_PUBLICATION_TTL_MS) { this.publicationTtlMs = MAX_PUBLICATION_TTL_MS; // depends on control dependency: [if], data = [none] logger.warn("publicationTtlMs > MAX_PUBLICATION_TTL. Using MAX_PUBLICATION_TTL: {}", MAX_PUBLICATION_TTL_MS); // depends on control dependency: [if], data = [none] } else { this.publicationTtlMs = publicationTtlMs; // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { @Override public HttpPublishing getHttpPublishing() { if (delegate == null) { return this.httpPublishing; } else { return this.httpPublishing == null ? delegate.getHttpPublishing() : this.httpPublishing; } } }
public class class_name { @Override public HttpPublishing getHttpPublishing() { if (delegate == null) { return this.httpPublishing; // depends on control dependency: [if], data = [none] } else { return this.httpPublishing == null ? delegate.getHttpPublishing() : this.httpPublishing; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static int qmf_stop_channel(int bs_stop_freq, SampleFrequency sample_rate, int k0) { if(bs_stop_freq==15) { return Math.min(64, k0*3); } else if(bs_stop_freq==14) { return Math.min(64, k0*2); } else { int stopMin = stopMinTable[sample_rate.getIndex()]; /* bs_stop_freq <= 13 */ return Math.min(64, stopMin+STOP_OFFSET_TABLE[sample_rate.getIndex()][Math.min(bs_stop_freq, 13)]); } } }
public class class_name { public static int qmf_stop_channel(int bs_stop_freq, SampleFrequency sample_rate, int k0) { if(bs_stop_freq==15) { return Math.min(64, k0*3); // depends on control dependency: [if], data = [none] } else if(bs_stop_freq==14) { return Math.min(64, k0*2); // depends on control dependency: [if], data = [none] } else { int stopMin = stopMinTable[sample_rate.getIndex()]; /* bs_stop_freq <= 13 */ return Math.min(64, stopMin+STOP_OFFSET_TABLE[sample_rate.getIndex()][Math.min(bs_stop_freq, 13)]); // depends on control dependency: [if], data = [(bs_stop_freq] } } }
public class class_name { public <P extends ParaObject> List<P> getItems(String at, Map<String, Object> result, Pager... pager) { if (result != null && !result.isEmpty() && !StringUtils.isBlank(at) && result.containsKey(at)) { if (pager != null && pager.length > 0 && pager[0] != null) { if (result.containsKey("totalHits")) { pager[0].setCount(((Integer) result.get("totalHits")).longValue()); } if (result.containsKey("lastKey")) { pager[0].setLastKey((String) result.get("lastKey")); } } return getItemsFromList((List<?>) result.get(at)); } return Collections.emptyList(); } }
public class class_name { public <P extends ParaObject> List<P> getItems(String at, Map<String, Object> result, Pager... pager) { if (result != null && !result.isEmpty() && !StringUtils.isBlank(at) && result.containsKey(at)) { if (pager != null && pager.length > 0 && pager[0] != null) { if (result.containsKey("totalHits")) { pager[0].setCount(((Integer) result.get("totalHits")).longValue()); // depends on control dependency: [if], data = [none] } if (result.containsKey("lastKey")) { pager[0].setLastKey((String) result.get("lastKey")); // depends on control dependency: [if], data = [none] } } return getItemsFromList((List<?>) result.get(at)); // depends on control dependency: [if], data = [none] } return Collections.emptyList(); } }
public class class_name { public static <T, R> R injectIntoTokens( String string, String separator, R injectedValue, Function2<R, String, R> function) { R result = injectedValue; for (StringTokenizer stringTokenizer = new StringTokenizer(string, separator); stringTokenizer.hasMoreTokens(); ) { String token = stringTokenizer.nextToken(); result = function.value(result, token); } return result; } }
public class class_name { public static <T, R> R injectIntoTokens( String string, String separator, R injectedValue, Function2<R, String, R> function) { R result = injectedValue; for (StringTokenizer stringTokenizer = new StringTokenizer(string, separator); stringTokenizer.hasMoreTokens(); ) { String token = stringTokenizer.nextToken(); result = function.value(result, token); // depends on control dependency: [for], data = [none] } return result; } }
public class class_name { private void makeAnswerArraysAndTagIndex(Collection<List<IN>> docs) { if (answerArrays == null) { answerArrays = new HashSet<List<String>>(); } if (classIndex == null) { classIndex = new HashIndex<String>(); } for (List<IN> doc : docs) { if (flags.useReverse) { Collections.reverse(doc); } int leng = doc.size(); for (int start = 0; start < leng; start++) { for (int diff = 1; diff <= flags.maxLeft && start + diff <= leng; diff++) { String[] seq = new String[diff]; for (int i = start; i < start + diff; i++) { seq[i - start] = doc.get(i).get(AnswerAnnotation.class); } answerArrays.add(Arrays.asList(seq)); } } for (int i = 0; i < leng; i++) { CoreLabel wordInfo = doc.get(i); classIndex.add(wordInfo.get(AnswerAnnotation.class)); } if (flags.useReverse) { Collections.reverse(doc); } } } }
public class class_name { private void makeAnswerArraysAndTagIndex(Collection<List<IN>> docs) { if (answerArrays == null) { answerArrays = new HashSet<List<String>>(); // depends on control dependency: [if], data = [none] } if (classIndex == null) { classIndex = new HashIndex<String>(); // depends on control dependency: [if], data = [none] } for (List<IN> doc : docs) { if (flags.useReverse) { Collections.reverse(doc); // depends on control dependency: [if], data = [none] } int leng = doc.size(); for (int start = 0; start < leng; start++) { for (int diff = 1; diff <= flags.maxLeft && start + diff <= leng; diff++) { String[] seq = new String[diff]; for (int i = start; i < start + diff; i++) { seq[i - start] = doc.get(i).get(AnswerAnnotation.class); // depends on control dependency: [for], data = [i] } answerArrays.add(Arrays.asList(seq)); // depends on control dependency: [for], data = [none] } } for (int i = 0; i < leng; i++) { CoreLabel wordInfo = doc.get(i); classIndex.add(wordInfo.get(AnswerAnnotation.class)); // depends on control dependency: [for], data = [none] } if (flags.useReverse) { Collections.reverse(doc); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public String getViewSelect(String htmlAttributes) { List<String> options = new ArrayList<String>(); List<String> values = new ArrayList<String>(); int selectedIndex = 0; // loop through the vectors and fill the result vectors Iterator<CmsWorkplaceView> i = OpenCms.getWorkplaceManager().getViews().iterator(); int count = -1; String currentView = getSettings().getViewUri(); if (CmsStringUtil.isNotEmpty(currentView)) { // remove possible parameters from current view int pos = currentView.indexOf('?'); if (pos >= 0) { currentView = currentView.substring(0, pos); } } while (i.hasNext()) { CmsWorkplaceView view = i.next(); if (getCms().existsResource(view.getUri(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) { count++; // ensure the current user has +v+r permissions on the view String loopLink = getJsp().link(view.getUri()); String localizedKey = resolveMacros(view.getKey()); options.add(localizedKey); values.add(loopLink); if (loopLink.equals(currentView)) { selectedIndex = count; } } } return buildSelect(htmlAttributes, options, values, selectedIndex); } }
public class class_name { public String getViewSelect(String htmlAttributes) { List<String> options = new ArrayList<String>(); List<String> values = new ArrayList<String>(); int selectedIndex = 0; // loop through the vectors and fill the result vectors Iterator<CmsWorkplaceView> i = OpenCms.getWorkplaceManager().getViews().iterator(); int count = -1; String currentView = getSettings().getViewUri(); if (CmsStringUtil.isNotEmpty(currentView)) { // remove possible parameters from current view int pos = currentView.indexOf('?'); if (pos >= 0) { currentView = currentView.substring(0, pos); // depends on control dependency: [if], data = [none] } } while (i.hasNext()) { CmsWorkplaceView view = i.next(); if (getCms().existsResource(view.getUri(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) { count++; // depends on control dependency: [if], data = [none] // ensure the current user has +v+r permissions on the view String loopLink = getJsp().link(view.getUri()); String localizedKey = resolveMacros(view.getKey()); options.add(localizedKey); // depends on control dependency: [if], data = [none] values.add(loopLink); // depends on control dependency: [if], data = [none] if (loopLink.equals(currentView)) { selectedIndex = count; // depends on control dependency: [if], data = [none] } } } return buildSelect(htmlAttributes, options, values, selectedIndex); } }
public class class_name { public static void horizontal(GrayF64 input, GrayF64 output, int radius) { boolean processed = BOverrideConvolveImageMean.invokeNativeHorizontal(input, output, radius); if( !processed ) { Kernel1D_F64 kernel = FactoryKernel.table1D_F64(radius, true); if (kernel.width > input.width) { ConvolveImageNormalized.horizontal(kernel, input, output); } else { InputSanityCheck.checkSameShape(input, output); ConvolveNormalized_JustBorder_SB.horizontal(kernel, input, output); if(BoofConcurrency.USE_CONCURRENT) { ImplConvolveMean_MT.horizontal(input, output, radius); } else { ImplConvolveMean.horizontal(input, output, radius); } } } } }
public class class_name { public static void horizontal(GrayF64 input, GrayF64 output, int radius) { boolean processed = BOverrideConvolveImageMean.invokeNativeHorizontal(input, output, radius); if( !processed ) { Kernel1D_F64 kernel = FactoryKernel.table1D_F64(radius, true); if (kernel.width > input.width) { ConvolveImageNormalized.horizontal(kernel, input, output); // depends on control dependency: [if], data = [none] } else { InputSanityCheck.checkSameShape(input, output); // depends on control dependency: [if], data = [none] ConvolveNormalized_JustBorder_SB.horizontal(kernel, input, output); // depends on control dependency: [if], data = [none] if(BoofConcurrency.USE_CONCURRENT) { ImplConvolveMean_MT.horizontal(input, output, radius); // depends on control dependency: [if], data = [none] } else { ImplConvolveMean.horizontal(input, output, radius); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { public Map<Integer, ResourceWorkerSlot> getTaskToNodePortbyNode(String supervisorId) { Map<Integer, ResourceWorkerSlot> result = new HashMap<>(); for (ResourceWorkerSlot worker : workers) { if (worker.getNodeId().equals(supervisorId)) { result.put(worker.getPort(), worker); } } return result; } }
public class class_name { public Map<Integer, ResourceWorkerSlot> getTaskToNodePortbyNode(String supervisorId) { Map<Integer, ResourceWorkerSlot> result = new HashMap<>(); for (ResourceWorkerSlot worker : workers) { if (worker.getNodeId().equals(supervisorId)) { result.put(worker.getPort(), worker); // depends on control dependency: [if], data = [none] } } return result; } }
public class class_name { public void marshall(GetBaiduChannelRequest getBaiduChannelRequest, ProtocolMarshaller protocolMarshaller) { if (getBaiduChannelRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getBaiduChannelRequest.getApplicationId(), APPLICATIONID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(GetBaiduChannelRequest getBaiduChannelRequest, ProtocolMarshaller protocolMarshaller) { if (getBaiduChannelRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getBaiduChannelRequest.getApplicationId(), APPLICATIONID_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 { protected static String formatMessage(String message, byte[] hostData, int start, int curPos, int bytesLen) { StringBuilder sb = new StringBuilder(); sb.append(message); if (hostData != null && hostData.length > 0 && curPos < hostData.length && curPos >= start && bytesLen > 0 && start + bytesLen <= hostData.length) { sb.append(". Error at offset "); sb.append(curPos); sb.append(" : [0x"); int spyStart = Math.max(start - SPYBUF_MAX_LEN, 0); appendData(sb, hostData, spyStart, start - spyStart); sb.append(start > spyStart ? "->" : ""); if (curPos > start) { appendData(sb, hostData, start, curPos - start); sb.append("^"); appendData(sb, hostData, curPos, bytesLen + start - curPos); } else { appendData(sb, hostData, start, bytesLen); } int spyStop = Math.min(start + bytesLen + SPYBUF_MAX_LEN, hostData.length); sb.append(spyStop > start + bytesLen ? "<-" : ""); appendData(sb, hostData, start + bytesLen, spyStop - start - bytesLen); sb.append("]"); } else { sb.append(". Position is "); sb.append(curPos); } return sb.toString(); } }
public class class_name { protected static String formatMessage(String message, byte[] hostData, int start, int curPos, int bytesLen) { StringBuilder sb = new StringBuilder(); sb.append(message); if (hostData != null && hostData.length > 0 && curPos < hostData.length && curPos >= start && bytesLen > 0 && start + bytesLen <= hostData.length) { sb.append(". Error at offset "); // depends on control dependency: [if], data = [none] sb.append(curPos); // depends on control dependency: [if], data = [none] sb.append(" : [0x"); // depends on control dependency: [if], data = [none] int spyStart = Math.max(start - SPYBUF_MAX_LEN, 0); appendData(sb, hostData, spyStart, start - spyStart); // depends on control dependency: [if], data = [none] sb.append(start > spyStart ? "->" : ""); // depends on control dependency: [if], data = [none] if (curPos > start) { appendData(sb, hostData, start, curPos - start); // depends on control dependency: [if], data = [start)] sb.append("^"); // depends on control dependency: [if], data = [none] appendData(sb, hostData, curPos, bytesLen + start - curPos); // depends on control dependency: [if], data = [none] } else { appendData(sb, hostData, start, bytesLen); // depends on control dependency: [if], data = [none] } int spyStop = Math.min(start + bytesLen + SPYBUF_MAX_LEN, hostData.length); sb.append(spyStop > start + bytesLen ? "<-" : ""); // depends on control dependency: [if], data = [none] appendData(sb, hostData, start + bytesLen, spyStop - start - bytesLen); // depends on control dependency: [if], data = [none] sb.append("]"); // depends on control dependency: [if], data = [none] } else { sb.append(". Position is "); // depends on control dependency: [if], data = [none] sb.append(curPos); // depends on control dependency: [if], data = [none] } return sb.toString(); } }
public class class_name { @Deprecated private void emitJvmMemMetrics(ServiceEmitter emitter) { // I have no idea why, but jvm/mem is slightly more than the sum of jvm/pool. Let's just include // them both. final Map<String, MemoryUsage> usages = ImmutableMap.of( "heap", ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(), "nonheap", ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage() ); for (Map.Entry<String, MemoryUsage> entry : usages.entrySet()) { final String kind = entry.getKey(); final MemoryUsage usage = entry.getValue(); final ServiceMetricEvent.Builder builder = builder().setDimension("memKind", kind); MonitorUtils.addDimensionsToBuilder(builder, dimensions); emitter.emit(builder.build("jvm/mem/max", usage.getMax())); emitter.emit(builder.build("jvm/mem/committed", usage.getCommitted())); emitter.emit(builder.build("jvm/mem/used", usage.getUsed())); emitter.emit(builder.build("jvm/mem/init", usage.getInit())); } // jvm/pool for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) { final String kind = pool.getType() == MemoryType.HEAP ? "heap" : "nonheap"; final MemoryUsage usage = pool.getUsage(); final ServiceMetricEvent.Builder builder = builder() .setDimension("poolKind", kind) .setDimension("poolName", pool.getName()); MonitorUtils.addDimensionsToBuilder(builder, dimensions); emitter.emit(builder.build("jvm/pool/max", usage.getMax())); emitter.emit(builder.build("jvm/pool/committed", usage.getCommitted())); emitter.emit(builder.build("jvm/pool/used", usage.getUsed())); emitter.emit(builder.build("jvm/pool/init", usage.getInit())); } } }
public class class_name { @Deprecated private void emitJvmMemMetrics(ServiceEmitter emitter) { // I have no idea why, but jvm/mem is slightly more than the sum of jvm/pool. Let's just include // them both. final Map<String, MemoryUsage> usages = ImmutableMap.of( "heap", ManagementFactory.getMemoryMXBean().getHeapMemoryUsage(), "nonheap", ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage() ); for (Map.Entry<String, MemoryUsage> entry : usages.entrySet()) { final String kind = entry.getKey(); final MemoryUsage usage = entry.getValue(); final ServiceMetricEvent.Builder builder = builder().setDimension("memKind", kind); MonitorUtils.addDimensionsToBuilder(builder, dimensions); // depends on control dependency: [for], data = [none] emitter.emit(builder.build("jvm/mem/max", usage.getMax())); // depends on control dependency: [for], data = [none] emitter.emit(builder.build("jvm/mem/committed", usage.getCommitted())); // depends on control dependency: [for], data = [none] emitter.emit(builder.build("jvm/mem/used", usage.getUsed())); // depends on control dependency: [for], data = [none] emitter.emit(builder.build("jvm/mem/init", usage.getInit())); // depends on control dependency: [for], data = [none] } // jvm/pool for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) { final String kind = pool.getType() == MemoryType.HEAP ? "heap" : "nonheap"; final MemoryUsage usage = pool.getUsage(); final ServiceMetricEvent.Builder builder = builder() .setDimension("poolKind", kind) .setDimension("poolName", pool.getName()); MonitorUtils.addDimensionsToBuilder(builder, dimensions); // depends on control dependency: [for], data = [none] emitter.emit(builder.build("jvm/pool/max", usage.getMax())); // depends on control dependency: [for], data = [pool] emitter.emit(builder.build("jvm/pool/committed", usage.getCommitted())); // depends on control dependency: [for], data = [pool] emitter.emit(builder.build("jvm/pool/used", usage.getUsed())); // depends on control dependency: [for], data = [pool] emitter.emit(builder.build("jvm/pool/init", usage.getInit())); // depends on control dependency: [for], data = [pool] } } }
public class class_name { public final void setCancelable(final Cancelable cancelable) { if (SwingUtilities.isEventDispatchThread()) { setCancelableIntern(cancelable); } else { try { SwingUtilities.invokeLater(new Runnable() { public void run() { setCancelableIntern(cancelable); } }); } catch (final Exception ex) { ignore(); } } } }
public class class_name { public final void setCancelable(final Cancelable cancelable) { if (SwingUtilities.isEventDispatchThread()) { setCancelableIntern(cancelable); // depends on control dependency: [if], data = [none] } else { try { SwingUtilities.invokeLater(new Runnable() { public void run() { setCancelableIntern(cancelable); } }); // depends on control dependency: [try], data = [none] } catch (final Exception ex) { ignore(); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { private boolean nodeArtifactsMatch (org.eclipse.aether.graph.DependencyNode nodeA, org.eclipse.aether.graph.DependencyNode nodeB) { if (nodeA == null || nodeB == null) { return false; } return nodeA.getArtifact().getGroupId ().equals(nodeB.getArtifact().getGroupId()) && nodeA.getArtifact().getArtifactId ().equals(nodeB.getArtifact().getArtifactId()); } }
public class class_name { private boolean nodeArtifactsMatch (org.eclipse.aether.graph.DependencyNode nodeA, org.eclipse.aether.graph.DependencyNode nodeB) { if (nodeA == null || nodeB == null) { return false; // depends on control dependency: [if], data = [none] } return nodeA.getArtifact().getGroupId ().equals(nodeB.getArtifact().getGroupId()) && nodeA.getArtifact().getArtifactId ().equals(nodeB.getArtifact().getArtifactId()); } }
public class class_name { public RosterEntry getEntry(String user) { if (user == null) { return null; } // Roster entries never include a resource so remove the resource // if it's a part of the XMPP address. user = StringUtils.parseBareAddress(user); String userLowerCase = user.toLowerCase(); synchronized (entries) { for (RosterEntry entry : entries) { if (entry.getUser().equals(userLowerCase)) { return entry; } } } return null; } }
public class class_name { public RosterEntry getEntry(String user) { if (user == null) { return null; // depends on control dependency: [if], data = [none] } // Roster entries never include a resource so remove the resource // if it's a part of the XMPP address. user = StringUtils.parseBareAddress(user); String userLowerCase = user.toLowerCase(); synchronized (entries) { for (RosterEntry entry : entries) { if (entry.getUser().equals(userLowerCase)) { return entry; // depends on control dependency: [if], data = [none] } } } return null; } }
public class class_name { public boolean isMasked(final @CheckForNull ParameterValue value, final @Nonnull String paramValueClassName) { // We always mask sensitive variables, the configuration does not matter in such case if (value != null && value.isSensitive()) { return true; } synchronized(this) { // Check if the value is in the cache if (paramValueCache_maskedClasses.contains(paramValueClassName)) { return true; } if (paramValueCache_nonMaskedClasses.contains(paramValueClassName)) { return false; } // Now guess boolean guessSo = guessIfShouldMask(paramValueClassName); if (guessSo) { // We are pretty sure it requires masking paramValueCache_maskedClasses.add(paramValueClassName); return true; } else { // It does not require masking, but we are not so sure // The warning will be printed each time the cache is invalidated due to whatever reason LOGGER.log(Level.WARNING, "Identified the {0} class as a ParameterValue class, which does not require masking. It may be false-negative", paramValueClassName); paramValueCache_nonMaskedClasses.add(paramValueClassName); return false; } } } }
public class class_name { public boolean isMasked(final @CheckForNull ParameterValue value, final @Nonnull String paramValueClassName) { // We always mask sensitive variables, the configuration does not matter in such case if (value != null && value.isSensitive()) { return true; // depends on control dependency: [if], data = [none] } synchronized(this) { // Check if the value is in the cache if (paramValueCache_maskedClasses.contains(paramValueClassName)) { return true; // depends on control dependency: [if], data = [none] } if (paramValueCache_nonMaskedClasses.contains(paramValueClassName)) { return false; // depends on control dependency: [if], data = [none] } // Now guess boolean guessSo = guessIfShouldMask(paramValueClassName); if (guessSo) { // We are pretty sure it requires masking paramValueCache_maskedClasses.add(paramValueClassName); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } else { // It does not require masking, but we are not so sure // The warning will be printed each time the cache is invalidated due to whatever reason LOGGER.log(Level.WARNING, "Identified the {0} class as a ParameterValue class, which does not require masking. It may be false-negative", paramValueClassName); // depends on control dependency: [if], data = [none] paramValueCache_nonMaskedClasses.add(paramValueClassName); // depends on control dependency: [if], data = [none] return false; // depends on control dependency: [if], data = [none] } } } }
public class class_name { public void onChanged(ChangedEvent event) { String value = (String) scaleItem.getValue(); Double scale = valueToScale.get(value); if (scale != null && !Double.isNaN(pixelLength) && 0.0 != pixelLength) { mapView.setCurrentScale(scale / pixelLength, MapView.ZoomOption.LEVEL_CLOSEST); } } }
public class class_name { public void onChanged(ChangedEvent event) { String value = (String) scaleItem.getValue(); Double scale = valueToScale.get(value); if (scale != null && !Double.isNaN(pixelLength) && 0.0 != pixelLength) { mapView.setCurrentScale(scale / pixelLength, MapView.ZoomOption.LEVEL_CLOSEST); // depends on control dependency: [if], data = [(scale] } } }
public class class_name { @SuppressWarnings("unchecked") public <E> List<E> upsert(List<E> entities) { if (entities == null || entities.isEmpty()) { return new ArrayList<>(); } try { entityManager.executeEntityListeners(CallbackType.PRE_UPSERT, entities); FullEntity<?>[] nativeEntities = toNativeFullEntities(entities, entityManager, Intent.UPSERT); Class<?> entityClass = entities.get(0).getClass(); List<Entity> upsertedNativeEntities = nativeWriter.put(nativeEntities); List<E> upsertedEntities = (List<E>) toEntities(entityClass, upsertedNativeEntities); entityManager.executeEntityListeners(CallbackType.POST_UPSERT, upsertedEntities); return upsertedEntities; } catch (DatastoreException exp) { throw DatastoreUtils.wrap(exp); } } }
public class class_name { @SuppressWarnings("unchecked") public <E> List<E> upsert(List<E> entities) { if (entities == null || entities.isEmpty()) { return new ArrayList<>(); // depends on control dependency: [if], data = [none] } try { entityManager.executeEntityListeners(CallbackType.PRE_UPSERT, entities); // depends on control dependency: [try], data = [none] FullEntity<?>[] nativeEntities = toNativeFullEntities(entities, entityManager, Intent.UPSERT); Class<?> entityClass = entities.get(0).getClass(); // depends on control dependency: [try], data = [none] List<Entity> upsertedNativeEntities = nativeWriter.put(nativeEntities); List<E> upsertedEntities = (List<E>) toEntities(entityClass, upsertedNativeEntities); entityManager.executeEntityListeners(CallbackType.POST_UPSERT, upsertedEntities); // depends on control dependency: [try], data = [none] return upsertedEntities; // depends on control dependency: [try], data = [none] } catch (DatastoreException exp) { throw DatastoreUtils.wrap(exp); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static void updateAllForFacade(DataStore dataStore, Iterator<Update> updateIter, Set<String> tags) { // Invoke dataStore.updateAll() with smallish batches so if one batch fails due to server failure, we will // fail over to another server using the Ostrich retry/failover infrastructure and continue from the point // of the failure. // Use time-based partitioning that adjusts batch sizes dynamically in an effort to settle on a batches that // take 500 milliseconds to execute. This should make the TimeLimitedIterator used by the DataStoreClient // unnecessary, but the TimeLimitedIterator is still relevant for clients that don't use DataStoreStreaming. // For now, hard-code initial/min/max/goal values. Iterator<List<Update>> batchIter = new TimePartitioningIterator<>(updateIter, 50, 1, 2500, Duration.ofMillis(500L)); while (batchIter.hasNext()) { // Ostrich will retry each batch as necessary dataStore.updateAllForFacade(batchIter.next(), tags); } } }
public class class_name { public static void updateAllForFacade(DataStore dataStore, Iterator<Update> updateIter, Set<String> tags) { // Invoke dataStore.updateAll() with smallish batches so if one batch fails due to server failure, we will // fail over to another server using the Ostrich retry/failover infrastructure and continue from the point // of the failure. // Use time-based partitioning that adjusts batch sizes dynamically in an effort to settle on a batches that // take 500 milliseconds to execute. This should make the TimeLimitedIterator used by the DataStoreClient // unnecessary, but the TimeLimitedIterator is still relevant for clients that don't use DataStoreStreaming. // For now, hard-code initial/min/max/goal values. Iterator<List<Update>> batchIter = new TimePartitioningIterator<>(updateIter, 50, 1, 2500, Duration.ofMillis(500L)); while (batchIter.hasNext()) { // Ostrich will retry each batch as necessary dataStore.updateAllForFacade(batchIter.next(), tags); // depends on control dependency: [while], data = [none] } } }
public class class_name { public static String getGroupName(final File file) { if (OsValidator.WINDOWS) { logger.trace("Determining 'group' is skipped for file [{}] on [{}]", file, OsValidator.OS); return null; } try { final Path path = Paths.get(file.getAbsolutePath()); final PosixFileAttributes posixFileAttributes = Files.getFileAttributeView(path, PosixFileAttributeView.class).readAttributes(); return posixFileAttributes != null ? posixFileAttributes.group().getName() : null; } catch (Exception e) { logger.warn("Failed to determine 'group' of {}: {}", file, e.getMessage()); return null; } } }
public class class_name { public static String getGroupName(final File file) { if (OsValidator.WINDOWS) { logger.trace("Determining 'group' is skipped for file [{}] on [{}]", file, OsValidator.OS); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } try { final Path path = Paths.get(file.getAbsolutePath()); final PosixFileAttributes posixFileAttributes = Files.getFileAttributeView(path, PosixFileAttributeView.class).readAttributes(); return posixFileAttributes != null ? posixFileAttributes.group().getName() : null; // depends on control dependency: [try], data = [none] } catch (Exception e) { logger.warn("Failed to determine 'group' of {}: {}", file, e.getMessage()); return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { static StereoEncoder newEncoder(IAtomContainer container, IAtom left, IAtom leftParent, IAtom right, IAtom rightParent, int[][] graph) { List<IBond> leftBonds = container.getConnectedBondsList(left); List<IBond> rightBonds = container.getConnectedBondsList(right); // check the left and right bonds are acceptable if (accept(left, leftBonds) && accept(right, rightBonds)) { int leftIndex = container.indexOf(left); int rightIndex = container.indexOf(right); int leftParentIndex = container.indexOf(leftParent); int rightParentIndex = container.indexOf(rightParent); // neighbors of u/v with the bonded atoms (left,right) moved // to the back of each array. this is important as we can // drop it when we build the permutation parity int[] leftNeighbors = moveToBack(graph[leftIndex], leftParentIndex); int[] rightNeighbors = moveToBack(graph[rightIndex], rightParentIndex); int l1 = leftNeighbors[0]; int l2 = leftNeighbors[1] == leftParentIndex ? leftIndex : leftNeighbors[1]; int r1 = rightNeighbors[0]; int r2 = rightNeighbors[1] == rightParentIndex ? rightIndex : rightNeighbors[1]; // make 2D/3D geometry GeometricParity geometric = geometric(container, leftIndex, rightIndex, l1, l2, r1, r2); // geometric is null if there were no coordinates if (geometric != null) { return new GeometryEncoder(new int[]{leftIndex, rightIndex}, new CombinedPermutationParity( permutation(leftNeighbors), permutation(rightNeighbors)), geometric); } } return null; } }
public class class_name { static StereoEncoder newEncoder(IAtomContainer container, IAtom left, IAtom leftParent, IAtom right, IAtom rightParent, int[][] graph) { List<IBond> leftBonds = container.getConnectedBondsList(left); List<IBond> rightBonds = container.getConnectedBondsList(right); // check the left and right bonds are acceptable if (accept(left, leftBonds) && accept(right, rightBonds)) { int leftIndex = container.indexOf(left); int rightIndex = container.indexOf(right); int leftParentIndex = container.indexOf(leftParent); int rightParentIndex = container.indexOf(rightParent); // neighbors of u/v with the bonded atoms (left,right) moved // to the back of each array. this is important as we can // drop it when we build the permutation parity int[] leftNeighbors = moveToBack(graph[leftIndex], leftParentIndex); int[] rightNeighbors = moveToBack(graph[rightIndex], rightParentIndex); int l1 = leftNeighbors[0]; int l2 = leftNeighbors[1] == leftParentIndex ? leftIndex : leftNeighbors[1]; int r1 = rightNeighbors[0]; int r2 = rightNeighbors[1] == rightParentIndex ? rightIndex : rightNeighbors[1]; // make 2D/3D geometry GeometricParity geometric = geometric(container, leftIndex, rightIndex, l1, l2, r1, r2); // geometric is null if there were no coordinates if (geometric != null) { return new GeometryEncoder(new int[]{leftIndex, rightIndex}, new CombinedPermutationParity( permutation(leftNeighbors), permutation(rightNeighbors)), geometric); // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { @Override public void visitCode(Code obj) { Method m = getMethod(); stack.resetForMethodEntry(this); initializedRegs.clear(); modifyRegs.clear(); Type[] argTypes = m.getArgumentTypes(); int arg = m.isStatic() ? 0 : 1; for (Type argType : argTypes) { String argSig = argType.getSignature(); initializedRegs.set(arg); arg += SignatureUtils.getSignatureSize(argSig); } nullStoreToLocation.clear(); super.visitCode(obj); for (Integer pc : nullStoreToLocation.values()) { bugReporter.reportBug(new BugInstance(this, BugType.AIOB_ARRAY_STORE_TO_NULL_REFERENCE.name(), HIGH_PRIORITY).addClass(this).addMethod(this) .addSourceLine(this, pc.intValue())); } } }
public class class_name { @Override public void visitCode(Code obj) { Method m = getMethod(); stack.resetForMethodEntry(this); initializedRegs.clear(); modifyRegs.clear(); Type[] argTypes = m.getArgumentTypes(); int arg = m.isStatic() ? 0 : 1; for (Type argType : argTypes) { String argSig = argType.getSignature(); initializedRegs.set(arg); // depends on control dependency: [for], data = [none] arg += SignatureUtils.getSignatureSize(argSig); // depends on control dependency: [for], data = [none] } nullStoreToLocation.clear(); super.visitCode(obj); for (Integer pc : nullStoreToLocation.values()) { bugReporter.reportBug(new BugInstance(this, BugType.AIOB_ARRAY_STORE_TO_NULL_REFERENCE.name(), HIGH_PRIORITY).addClass(this).addMethod(this) .addSourceLine(this, pc.intValue())); // depends on control dependency: [for], data = [none] } } }
public class class_name { private Map<Class<?>, InterfaceInfo> getInterfaceInfoMap() { if (interfaceInfoMap == null) { interfaceInfoMap = new HashMap<Class<?>, InterfaceInfo>(); for (final Class<?> c : packageClasses) { if (INTERESTING_CLASSES.accept( c )) { if (!interfaceInfoMap.containsKey( c )) { interfaceInfoMap.put( c, new InterfaceInfo( c ) ); } } else { final Contract contract = c.getAnnotation( Contract.class ); if (contract != null) { InterfaceInfo ii = interfaceInfoMap.get( contract.value() ); if (ii == null) { ii = new InterfaceInfo( contract.value() ); interfaceInfoMap.put( contract.value(), ii ); } ii.add( c ); } } } } return interfaceInfoMap; } }
public class class_name { private Map<Class<?>, InterfaceInfo> getInterfaceInfoMap() { if (interfaceInfoMap == null) { interfaceInfoMap = new HashMap<Class<?>, InterfaceInfo>(); // depends on control dependency: [if], data = [none] for (final Class<?> c : packageClasses) { if (INTERESTING_CLASSES.accept( c )) { if (!interfaceInfoMap.containsKey( c )) { interfaceInfoMap.put( c, new InterfaceInfo( c ) ); // depends on control dependency: [if], data = [none] } } else { final Contract contract = c.getAnnotation( Contract.class ); if (contract != null) { InterfaceInfo ii = interfaceInfoMap.get( contract.value() ); if (ii == null) { ii = new InterfaceInfo( contract.value() ); // depends on control dependency: [if], data = [none] interfaceInfoMap.put( contract.value(), ii ); // depends on control dependency: [if], data = [none] } ii.add( c ); // depends on control dependency: [if], data = [none] } } } } return interfaceInfoMap; } }
public class class_name { static int guessNumWords(Beliefs b) { int n = -1; for (int v=0; v<b.varBeliefs.length; v++) { Var var = b.varBeliefs[v].getVars().get(0); if (var instanceof LinkVar) { LinkVar link = (LinkVar) var; int p = link.getParent(); int c = link.getChild(); n = Math.max(n, Math.max(p, c)); } } return n+1; } }
public class class_name { static int guessNumWords(Beliefs b) { int n = -1; for (int v=0; v<b.varBeliefs.length; v++) { Var var = b.varBeliefs[v].getVars().get(0); if (var instanceof LinkVar) { LinkVar link = (LinkVar) var; int p = link.getParent(); int c = link.getChild(); n = Math.max(n, Math.max(p, c)); // depends on control dependency: [if], data = [none] } } return n+1; } }
public class class_name { public DescribeIamInstanceProfileAssociationsResult withIamInstanceProfileAssociations(IamInstanceProfileAssociation... iamInstanceProfileAssociations) { if (this.iamInstanceProfileAssociations == null) { setIamInstanceProfileAssociations(new com.amazonaws.internal.SdkInternalList<IamInstanceProfileAssociation>(iamInstanceProfileAssociations.length)); } for (IamInstanceProfileAssociation ele : iamInstanceProfileAssociations) { this.iamInstanceProfileAssociations.add(ele); } return this; } }
public class class_name { public DescribeIamInstanceProfileAssociationsResult withIamInstanceProfileAssociations(IamInstanceProfileAssociation... iamInstanceProfileAssociations) { if (this.iamInstanceProfileAssociations == null) { setIamInstanceProfileAssociations(new com.amazonaws.internal.SdkInternalList<IamInstanceProfileAssociation>(iamInstanceProfileAssociations.length)); // depends on control dependency: [if], data = [none] } for (IamInstanceProfileAssociation ele : iamInstanceProfileAssociations) { this.iamInstanceProfileAssociations.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { @Override public final void setReplyPriority(int value) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setReplyPriority", Integer.valueOf(value)); if ((value >= MfpConstants.MIN_PRIORITY) && (value <= MfpConstants.MAX_PRIORITY)) { getApi().setIntField(JsApiAccess.REPLYPRIORITY_VALUE, value); } else { IllegalArgumentException e = new IllegalArgumentException(Integer.toString(value)); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setReplyPriority", e); throw e; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setReplyPriority"); } }
public class class_name { @Override public final void setReplyPriority(int value) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setReplyPriority", Integer.valueOf(value)); if ((value >= MfpConstants.MIN_PRIORITY) && (value <= MfpConstants.MAX_PRIORITY)) { getApi().setIntField(JsApiAccess.REPLYPRIORITY_VALUE, value); // depends on control dependency: [if], data = [none] } else { IllegalArgumentException e = new IllegalArgumentException(Integer.toString(value)); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setReplyPriority", e); throw e; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setReplyPriority"); } }
public class class_name { private boolean isStyle(String style) { for (int i = 0; i < style.length(); ++i) { char c = style.charAt(i); if (!Character.isWhitespace(c)) { return (c == '<'); } } return false; } }
public class class_name { private boolean isStyle(String style) { for (int i = 0; i < style.length(); ++i) { char c = style.charAt(i); if (!Character.isWhitespace(c)) { return (c == '<'); // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { public Observable<ServiceResponse<GenericResourceInner>> beginUpdateWithServiceResponseAsync(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, String resourceType, String resourceName, String apiVersion, GenericResourceInner parameters) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (resourceProviderNamespace == null) { throw new IllegalArgumentException("Parameter resourceProviderNamespace is required and cannot be null."); } if (parentResourcePath == null) { throw new IllegalArgumentException("Parameter parentResourcePath is required and cannot be null."); } if (resourceType == null) { throw new IllegalArgumentException("Parameter resourceType is required and cannot be null."); } if (resourceName == null) { throw new IllegalArgumentException("Parameter resourceName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (apiVersion == null) { throw new IllegalArgumentException("Parameter apiVersion is required and cannot be null."); } if (parameters == null) { throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } Validator.validate(parameters); return service.beginUpdate(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, this.client.subscriptionId(), apiVersion, parameters, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<GenericResourceInner>>>() { @Override public Observable<ServiceResponse<GenericResourceInner>> call(Response<ResponseBody> response) { try { ServiceResponse<GenericResourceInner> clientResponse = beginUpdateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } }
public class class_name { public Observable<ServiceResponse<GenericResourceInner>> beginUpdateWithServiceResponseAsync(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, String resourceType, String resourceName, String apiVersion, GenericResourceInner parameters) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (resourceProviderNamespace == null) { throw new IllegalArgumentException("Parameter resourceProviderNamespace is required and cannot be null."); } if (parentResourcePath == null) { throw new IllegalArgumentException("Parameter parentResourcePath is required and cannot be null."); } if (resourceType == null) { throw new IllegalArgumentException("Parameter resourceType is required and cannot be null."); } if (resourceName == null) { throw new IllegalArgumentException("Parameter resourceName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (apiVersion == null) { throw new IllegalArgumentException("Parameter apiVersion is required and cannot be null."); } if (parameters == null) { throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } Validator.validate(parameters); return service.beginUpdate(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, this.client.subscriptionId(), apiVersion, parameters, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<GenericResourceInner>>>() { @Override public Observable<ServiceResponse<GenericResourceInner>> call(Response<ResponseBody> response) { try { ServiceResponse<GenericResourceInner> clientResponse = beginUpdateDelegate(response); return Observable.just(clientResponse); // depends on control dependency: [try], data = [none] } catch (Throwable t) { return Observable.error(t); } // depends on control dependency: [catch], data = [none] } }); } }
public class class_name { public static Path doPath(String s) { int n = s.length(); ParserHelper ph = new ParserHelper(s); ph.skipWhitespace(); Path p = new Path(); float lastX = 0; float lastY = 0; float lastX1 = 0; float lastY1 = 0; float contourInitialX = 0; float contourInitialY = 0; RectF r = new RectF(); char cmd = 'x'; while (ph.pos < n) { char next = s.charAt(ph.pos); if (!Character.isDigit(next) && !(next == '.') && !(next == '-')) { cmd = next; ph.advance(); } else if (cmd == 'M') { // implied command cmd = 'L'; } else if (cmd == 'm') { // implied command cmd = 'l'; } else { // implied command //ignore } p.computeBounds(r, true); // Log.d(TAG, " " + cmd + " " + r); // Util.debug("* Commands remaining: '" + path + "'."); boolean wasCurve = false; switch (cmd) { case 'M': case 'm': { float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'm') { p.rMoveTo(x, y); lastX += x; lastY += y; } else { p.moveTo(x, y); lastX = x; lastY = y; } contourInitialX = lastX; contourInitialY = lastY; break; } case 'Z': case 'z': { /// p.lineTo(contourInitialX, contourInitialY); p.close(); lastX = contourInitialX; lastY = contourInitialY; break; } case 'L': case 'l': { float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'l') { p.rLineTo(x, y); lastX += x; lastY += y; } else { p.lineTo(x, y); lastX = x; lastY = y; } break; } case 'H': case 'h': { float x = ph.nextFloat(); if (cmd == 'h') { p.rLineTo(x, 0); lastX += x; } else { p.lineTo(x, lastY); lastX = x; } break; } case 'V': case 'v': { float y = ph.nextFloat(); if (cmd == 'v') { p.rLineTo(0, y); lastY += y; } else { p.lineTo(lastX, y); lastY = y; } break; } case 'C': case 'c': { wasCurve = true; float x1 = ph.nextFloat(); float y1 = ph.nextFloat(); float x2 = ph.nextFloat(); float y2 = ph.nextFloat(); float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'c') { x1 += lastX; x2 += lastX; x += lastX; y1 += lastY; y2 += lastY; y += lastY; } p.cubicTo(x1, y1, x2, y2, x, y); lastX1 = x2; lastY1 = y2; lastX = x; lastY = y; break; } case 'S': case 's': { wasCurve = true; float x2 = ph.nextFloat(); float y2 = ph.nextFloat(); float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 's') { x2 += lastX; x += lastX; y2 += lastY; y += lastY; } float x1 = 2 * lastX - lastX1; float y1 = 2 * lastY - lastY1; p.cubicTo(x1, y1, x2, y2, x, y); lastX1 = x2; lastY1 = y2; lastX = x; lastY = y; break; } case 'A': case 'a': { float rx = ph.nextFloat(); float ry = ph.nextFloat(); float theta = ph.nextFloat(); int largeArc = (int) ph.nextFloat(); int sweepArc = (int) ph.nextFloat(); float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'a') { x += lastX; y += lastY; } drawArc(p, lastX, lastY, x, y, rx, ry, theta, largeArc == 1, sweepArc == 1); lastX = x; lastY = y; break; } case 'T': case 't': { wasCurve = true; float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 't') { x += lastX; y += lastY; } float x1 = 2 * lastX - lastX1; float y1 = 2 * lastY - lastY1; p.cubicTo( lastX, lastY, x1, y1, x, y ); lastX = x; lastY = y; lastX1 = x1; lastY1 = y1; break; } case 'Q': case 'q': { wasCurve = true; float x1 = ph.nextFloat(); float y1 = ph.nextFloat(); float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'q') { x += lastX; y += lastY; x1 += lastX; y1 += lastY; } p.cubicTo( lastX, lastY, x1, y1, x, y ); lastX1 = x1; lastY1 = y1; lastX = x; lastY = y; break; } default: Log.w(TAG, "Invalid path command: " + cmd); ph.advance(); } if (!wasCurve) { lastX1 = lastX; lastY1 = lastY; } ph.skipWhitespace(); } return p; } }
public class class_name { public static Path doPath(String s) { int n = s.length(); ParserHelper ph = new ParserHelper(s); ph.skipWhitespace(); Path p = new Path(); float lastX = 0; float lastY = 0; float lastX1 = 0; float lastY1 = 0; float contourInitialX = 0; float contourInitialY = 0; RectF r = new RectF(); char cmd = 'x'; while (ph.pos < n) { char next = s.charAt(ph.pos); if (!Character.isDigit(next) && !(next == '.') && !(next == '-')) { cmd = next; // depends on control dependency: [if], data = [none] ph.advance(); // depends on control dependency: [if], data = [none] } else if (cmd == 'M') { // implied command cmd = 'L'; // depends on control dependency: [if], data = [none] } else if (cmd == 'm') { // implied command cmd = 'l'; // depends on control dependency: [if], data = [none] } else { // implied command //ignore } p.computeBounds(r, true); // depends on control dependency: [while], data = [none] // Log.d(TAG, " " + cmd + " " + r); // Util.debug("* Commands remaining: '" + path + "'."); boolean wasCurve = false; switch (cmd) { case 'M': case 'm': { float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'm') { p.rMoveTo(x, y); // depends on control dependency: [if], data = [none] lastX += x; // depends on control dependency: [if], data = [none] lastY += y; // depends on control dependency: [if], data = [none] } else { p.moveTo(x, y); // depends on control dependency: [if], data = [none] lastX = x; // depends on control dependency: [if], data = [none] lastY = y; // depends on control dependency: [if], data = [none] } contourInitialX = lastX; contourInitialY = lastY; break; } case 'Z': case 'z': { /// p.lineTo(contourInitialX, contourInitialY); p.close(); lastX = contourInitialX; lastY = contourInitialY; break; } case 'L': case 'l': { float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'l') { p.rLineTo(x, y); // depends on control dependency: [if], data = [none] lastX += x; // depends on control dependency: [if], data = [none] lastY += y; // depends on control dependency: [if], data = [none] } else { p.lineTo(x, y); // depends on control dependency: [if], data = [none] lastX = x; // depends on control dependency: [if], data = [none] lastY = y; // depends on control dependency: [if], data = [none] } break; } case 'H': case 'h': { float x = ph.nextFloat(); if (cmd == 'h') { p.rLineTo(x, 0); // depends on control dependency: [if], data = [none] lastX += x; // depends on control dependency: [if], data = [none] } else { p.lineTo(x, lastY); // depends on control dependency: [if], data = [none] lastX = x; // depends on control dependency: [if], data = [none] } break; } case 'V': case 'v': { float y = ph.nextFloat(); if (cmd == 'v') { p.rLineTo(0, y); // depends on control dependency: [if], data = [none] lastY += y; // depends on control dependency: [if], data = [none] } else { p.lineTo(lastX, y); // depends on control dependency: [if], data = [none] lastY = y; // depends on control dependency: [if], data = [none] } break; } case 'C': case 'c': { wasCurve = true; float x1 = ph.nextFloat(); float y1 = ph.nextFloat(); float x2 = ph.nextFloat(); float y2 = ph.nextFloat(); float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'c') { x1 += lastX; // depends on control dependency: [if], data = [none] x2 += lastX; // depends on control dependency: [if], data = [none] x += lastX; // depends on control dependency: [if], data = [none] y1 += lastY; // depends on control dependency: [if], data = [none] y2 += lastY; // depends on control dependency: [if], data = [none] y += lastY; // depends on control dependency: [if], data = [none] } p.cubicTo(x1, y1, x2, y2, x, y); lastX1 = x2; lastY1 = y2; lastX = x; lastY = y; break; } case 'S': case 's': { wasCurve = true; float x2 = ph.nextFloat(); float y2 = ph.nextFloat(); float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 's') { x2 += lastX; // depends on control dependency: [if], data = [none] x += lastX; // depends on control dependency: [if], data = [none] y2 += lastY; // depends on control dependency: [if], data = [none] y += lastY; // depends on control dependency: [if], data = [none] } float x1 = 2 * lastX - lastX1; float y1 = 2 * lastY - lastY1; p.cubicTo(x1, y1, x2, y2, x, y); lastX1 = x2; lastY1 = y2; lastX = x; lastY = y; break; } case 'A': case 'a': { float rx = ph.nextFloat(); float ry = ph.nextFloat(); float theta = ph.nextFloat(); int largeArc = (int) ph.nextFloat(); int sweepArc = (int) ph.nextFloat(); float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'a') { x += lastX; // depends on control dependency: [if], data = [none] y += lastY; // depends on control dependency: [if], data = [none] } drawArc(p, lastX, lastY, x, y, rx, ry, theta, largeArc == 1, sweepArc == 1); lastX = x; lastY = y; break; } case 'T': case 't': { wasCurve = true; float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 't') { x += lastX; // depends on control dependency: [if], data = [none] y += lastY; // depends on control dependency: [if], data = [none] } float x1 = 2 * lastX - lastX1; float y1 = 2 * lastY - lastY1; p.cubicTo( lastX, lastY, x1, y1, x, y ); lastX = x; lastY = y; lastX1 = x1; lastY1 = y1; break; } case 'Q': case 'q': { wasCurve = true; float x1 = ph.nextFloat(); float y1 = ph.nextFloat(); float x = ph.nextFloat(); float y = ph.nextFloat(); if (cmd == 'q') { x += lastX; // depends on control dependency: [if], data = [none] y += lastY; // depends on control dependency: [if], data = [none] x1 += lastX; // depends on control dependency: [if], data = [none] y1 += lastY; // depends on control dependency: [if], data = [none] } p.cubicTo( lastX, lastY, x1, y1, x, y ); lastX1 = x1; lastY1 = y1; lastX = x; lastY = y; break; } default: Log.w(TAG, "Invalid path command: " + cmd); ph.advance(); } if (!wasCurve) { lastX1 = lastX; // depends on control dependency: [if], data = [none] lastY1 = lastY; // depends on control dependency: [if], data = [none] } ph.skipWhitespace(); // depends on control dependency: [while], data = [none] } return p; } }
public class class_name { protected EventBuilder createEventBuilder(LoggingEvent loggingEvent) { EventBuilder eventBuilder = new EventBuilder() .withSdkIntegration("log4j") .withTimestamp(new Date(loggingEvent.getTimeStamp())) .withMessage(loggingEvent.getRenderedMessage()) .withLogger(loggingEvent.getLoggerName()) .withLevel(formatLevel(loggingEvent.getLevel())) .withExtra(THREAD_NAME, loggingEvent.getThreadName()); ThrowableInformation throwableInformation = null; try { throwableInformation = loggingEvent.getThrowableInformation(); } catch (NullPointerException expected) { // `throwableInformation` is already set. } if (throwableInformation != null) { Throwable throwable = throwableInformation.getThrowable(); eventBuilder.withSentryInterface(new ExceptionInterface(throwable)); } else if (loggingEvent.getLocationInformation().fullInfo != null) { LocationInfo location = loggingEvent.getLocationInformation(); if (!LocationInfo.NA.equals(location.getFileName()) && !LocationInfo.NA.equals(location.getLineNumber())) { StackTraceElement[] stackTrace = {asStackTraceElement(location)}; eventBuilder.withSentryInterface(new StackTraceInterface(stackTrace)); } } if (loggingEvent.getNDC() != null) { eventBuilder.withExtra(LOG4J_NDC, loggingEvent.getNDC()); } Set<String> extraTags = Sentry.getStoredClient().getMdcTags(); @SuppressWarnings("unchecked") Map<String, Object> properties = (Map<String, Object>) loggingEvent.getProperties(); for (Map.Entry<String, Object> mdcEntry : properties.entrySet()) { if (extraTags.contains(mdcEntry.getKey())) { eventBuilder.withTag(mdcEntry.getKey(), mdcEntry.getValue().toString()); } else { eventBuilder.withExtra(mdcEntry.getKey(), mdcEntry.getValue()); } } return eventBuilder; } }
public class class_name { protected EventBuilder createEventBuilder(LoggingEvent loggingEvent) { EventBuilder eventBuilder = new EventBuilder() .withSdkIntegration("log4j") .withTimestamp(new Date(loggingEvent.getTimeStamp())) .withMessage(loggingEvent.getRenderedMessage()) .withLogger(loggingEvent.getLoggerName()) .withLevel(formatLevel(loggingEvent.getLevel())) .withExtra(THREAD_NAME, loggingEvent.getThreadName()); ThrowableInformation throwableInformation = null; try { throwableInformation = loggingEvent.getThrowableInformation(); // depends on control dependency: [try], data = [none] } catch (NullPointerException expected) { // `throwableInformation` is already set. } // depends on control dependency: [catch], data = [none] if (throwableInformation != null) { Throwable throwable = throwableInformation.getThrowable(); eventBuilder.withSentryInterface(new ExceptionInterface(throwable)); // depends on control dependency: [if], data = [none] } else if (loggingEvent.getLocationInformation().fullInfo != null) { LocationInfo location = loggingEvent.getLocationInformation(); if (!LocationInfo.NA.equals(location.getFileName()) && !LocationInfo.NA.equals(location.getLineNumber())) { StackTraceElement[] stackTrace = {asStackTraceElement(location)}; eventBuilder.withSentryInterface(new StackTraceInterface(stackTrace)); // depends on control dependency: [if], data = [none] } } if (loggingEvent.getNDC() != null) { eventBuilder.withExtra(LOG4J_NDC, loggingEvent.getNDC()); // depends on control dependency: [if], data = [none] } Set<String> extraTags = Sentry.getStoredClient().getMdcTags(); @SuppressWarnings("unchecked") Map<String, Object> properties = (Map<String, Object>) loggingEvent.getProperties(); for (Map.Entry<String, Object> mdcEntry : properties.entrySet()) { if (extraTags.contains(mdcEntry.getKey())) { eventBuilder.withTag(mdcEntry.getKey(), mdcEntry.getValue().toString()); // depends on control dependency: [if], data = [none] } else { eventBuilder.withExtra(mdcEntry.getKey(), mdcEntry.getValue()); // depends on control dependency: [if], data = [none] } } return eventBuilder; } }
public class class_name { public Object convertFormValueToModelValue(Object propertyValue) { if (propertyValue==null || "".equals(propertyValue)) { return null; } try { return dateFormat.parseObject(propertyValue.toString()); } catch (ParseException e) { throw new ProcessEngineException("invalid date value "+propertyValue); } } }
public class class_name { public Object convertFormValueToModelValue(Object propertyValue) { if (propertyValue==null || "".equals(propertyValue)) { return null; // depends on control dependency: [if], data = [none] } try { return dateFormat.parseObject(propertyValue.toString()); // depends on control dependency: [try], data = [none] } catch (ParseException e) { throw new ProcessEngineException("invalid date value "+propertyValue); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public final boolean synpred88_InternalXbase() { state.backtracking++; int start = input.mark(); try { synpred88_InternalXbase_fragment(); // can never throw exception } catch (RecognitionException re) { System.err.println("impossible: "+re); } boolean success = !state.failed; input.rewind(start); state.backtracking--; state.failed=false; return success; } }
public class class_name { public final boolean synpred88_InternalXbase() { state.backtracking++; int start = input.mark(); try { synpred88_InternalXbase_fragment(); // can never throw exception // depends on control dependency: [try], data = [none] } catch (RecognitionException re) { System.err.println("impossible: "+re); } // depends on control dependency: [catch], data = [none] boolean success = !state.failed; input.rewind(start); state.backtracking--; state.failed=false; return success; } }
public class class_name { @Override public String produce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException { String nextSourceOffset = null; LOG.debug("lastSourceOffset: {}", lastSourceOffset); // send event only once for each time we run out of data. if(shouldSendNoMoreDataEvent) { CommonEvents.NO_MORE_DATA.create(getContext()).createAndSend(); shouldSendNoMoreDataEvent = false; return lastSourceOffset; } int batchSize = Math.min(conf.basicConfig.maxBatchSize, maxBatchSize); if (!conf.queryExistingData || (null != lastSourceOffset && lastSourceOffset.startsWith(EVENT_ID_OFFSET_PREFIX))) { if (conf.subscribeToStreaming) { nextSourceOffset = streamingProduce(lastSourceOffset, batchSize, batchMaker); } else { // We're done reading existing data, but we don't want to subscribe to Streaming API return null; } } else if (conf.queryExistingData) { if (!queryInProgress()) { long now = System.currentTimeMillis(); long delay = Math.max(0, (lastQueryCompletedTime + (1000 * conf.queryInterval)) - now); if (delay > 0) { // Sleep in one second increments so we don't tie up the app. LOG.info("{}ms remaining until next fetch.", delay); ThreadUtil.sleep(Math.min(delay, 1000)); return lastSourceOffset; } } if (conf.useBulkAPI) { nextSourceOffset = bulkProduce(lastSourceOffset, batchSize, batchMaker); } else { nextSourceOffset = soapProduce(lastSourceOffset, batchSize, batchMaker); } } else if (conf.subscribeToStreaming) { // No offset, and we're not querying existing data, so switch to streaming nextSourceOffset = READ_EVENTS_FROM_NOW; } LOG.debug("nextSourceOffset: {}", nextSourceOffset); return nextSourceOffset; } }
public class class_name { @Override public String produce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException { String nextSourceOffset = null; LOG.debug("lastSourceOffset: {}", lastSourceOffset); // send event only once for each time we run out of data. if(shouldSendNoMoreDataEvent) { CommonEvents.NO_MORE_DATA.create(getContext()).createAndSend(); shouldSendNoMoreDataEvent = false; return lastSourceOffset; } int batchSize = Math.min(conf.basicConfig.maxBatchSize, maxBatchSize); if (!conf.queryExistingData || (null != lastSourceOffset && lastSourceOffset.startsWith(EVENT_ID_OFFSET_PREFIX))) { if (conf.subscribeToStreaming) { nextSourceOffset = streamingProduce(lastSourceOffset, batchSize, batchMaker); // depends on control dependency: [if], data = [none] } else { // We're done reading existing data, but we don't want to subscribe to Streaming API return null; // depends on control dependency: [if], data = [none] } } else if (conf.queryExistingData) { if (!queryInProgress()) { long now = System.currentTimeMillis(); long delay = Math.max(0, (lastQueryCompletedTime + (1000 * conf.queryInterval)) - now); if (delay > 0) { // Sleep in one second increments so we don't tie up the app. LOG.info("{}ms remaining until next fetch.", delay); // depends on control dependency: [if], data = [none] ThreadUtil.sleep(Math.min(delay, 1000)); // depends on control dependency: [if], data = [(delay] return lastSourceOffset; // depends on control dependency: [if], data = [none] } } if (conf.useBulkAPI) { nextSourceOffset = bulkProduce(lastSourceOffset, batchSize, batchMaker); // depends on control dependency: [if], data = [none] } else { nextSourceOffset = soapProduce(lastSourceOffset, batchSize, batchMaker); // depends on control dependency: [if], data = [none] } } else if (conf.subscribeToStreaming) { // No offset, and we're not querying existing data, so switch to streaming nextSourceOffset = READ_EVENTS_FROM_NOW; } LOG.debug("nextSourceOffset: {}", nextSourceOffset); return nextSourceOffset; } }
public class class_name { protected Name nextNameForVersionNode( Property predecessors, ChildReferences historyChildren ) { String proposedName = null; CachedNode versionNode = null; // Try to find the versions in the history that are considered predecessors ... if (predecessors != null) { for (Object predecessor : predecessors) { if (predecessor == null) continue; NodeKey key = ((NodeKeyReference)predecessor).getNodeKey(); CachedNode predecessorNode = system.getNode(key); Name predecessorName = predecessorNode.getName(system); if (proposedName == null || predecessorName.getLocalName().length() < proposedName.length()) { proposedName = predecessorName.getLocalName(); versionNode = predecessorNode; } } } if (proposedName == null) { proposedName = "1.0"; Name versionName = names.create(proposedName); if (historyChildren.getChild(versionName) == null) return versionName; // Otherwise use the root version ... versionNode = system.getNode(historyChildren.getChild(JcrLexicon.ROOT_VERSION)); } assert versionNode != null; // Now make sure the name is not used ... int index = proposedName.lastIndexOf('.'); if (index > 0) { proposedName = proposedName.substring(0, index + 1) + (Integer.parseInt(proposedName.substring(index + 1)) + 1); Name versionName = names.create(proposedName); // excludes the trailing '.' while (historyChildren.getChild(versionName) != null) { proposedName = proposedName + ".0"; versionName = names.create(proposedName); } return versionName; } // Get the number of successors of the version Property successors = versionNode.getProperty(JcrLexicon.SUCCESSORS, system); String baseName = successors != null ? Integer.toString(successors.size() + 1) : "1"; return names.create(baseName + ".0"); } }
public class class_name { protected Name nextNameForVersionNode( Property predecessors, ChildReferences historyChildren ) { String proposedName = null; CachedNode versionNode = null; // Try to find the versions in the history that are considered predecessors ... if (predecessors != null) { for (Object predecessor : predecessors) { if (predecessor == null) continue; NodeKey key = ((NodeKeyReference)predecessor).getNodeKey(); CachedNode predecessorNode = system.getNode(key); Name predecessorName = predecessorNode.getName(system); if (proposedName == null || predecessorName.getLocalName().length() < proposedName.length()) { proposedName = predecessorName.getLocalName(); // depends on control dependency: [if], data = [none] versionNode = predecessorNode; // depends on control dependency: [if], data = [none] } } } if (proposedName == null) { proposedName = "1.0"; // depends on control dependency: [if], data = [none] Name versionName = names.create(proposedName); if (historyChildren.getChild(versionName) == null) return versionName; // Otherwise use the root version ... versionNode = system.getNode(historyChildren.getChild(JcrLexicon.ROOT_VERSION)); // depends on control dependency: [if], data = [none] } assert versionNode != null; // Now make sure the name is not used ... int index = proposedName.lastIndexOf('.'); if (index > 0) { proposedName = proposedName.substring(0, index + 1) + (Integer.parseInt(proposedName.substring(index + 1)) + 1); // depends on control dependency: [if], data = [(index] Name versionName = names.create(proposedName); // excludes the trailing '.' while (historyChildren.getChild(versionName) != null) { proposedName = proposedName + ".0"; // depends on control dependency: [while], data = [none] versionName = names.create(proposedName); // depends on control dependency: [while], data = [none] } return versionName; // depends on control dependency: [if], data = [none] } // Get the number of successors of the version Property successors = versionNode.getProperty(JcrLexicon.SUCCESSORS, system); String baseName = successors != null ? Integer.toString(successors.size() + 1) : "1"; return names.create(baseName + ".0"); } }
public class class_name { private List<String> createRoles(HttpConstraintElement httpConstraint) { String[] rolesFromAnno = httpConstraint.getRolesAllowed(); List<String> roles = new ArrayList<String>(); for (int i = 0; i < rolesFromAnno.length; i++) { roles.add(rolesFromAnno[i]); } return roles; } }
public class class_name { private List<String> createRoles(HttpConstraintElement httpConstraint) { String[] rolesFromAnno = httpConstraint.getRolesAllowed(); List<String> roles = new ArrayList<String>(); for (int i = 0; i < rolesFromAnno.length; i++) { roles.add(rolesFromAnno[i]); // depends on control dependency: [for], data = [i] } return roles; } }
public class class_name { @Override public void handlePopups() { /* * try { executeJavaScript("window.alert = function(msg){return true;};" + * "window.confirm = function(msg){return true;};" + * "window.prompt = function(msg){return true;};"); } catch (CrawljaxException e) { * LOGGER.error("Handling of PopUp windows failed", e); } */ /* Workaround: Popups handling currently not supported in PhantomJS. */ if (browser instanceof PhantomJSDriver) { return; } if (ExpectedConditions.alertIsPresent().apply(browser) != null) { try { browser.switchTo().alert().accept(); LOGGER.info("Alert accepted"); } catch (Exception e) { LOGGER.error("Handling of PopUp windows failed"); } } } }
public class class_name { @Override public void handlePopups() { /* * try { executeJavaScript("window.alert = function(msg){return true;};" + * "window.confirm = function(msg){return true;};" + * "window.prompt = function(msg){return true;};"); } catch (CrawljaxException e) { * LOGGER.error("Handling of PopUp windows failed", e); } */ /* Workaround: Popups handling currently not supported in PhantomJS. */ if (browser instanceof PhantomJSDriver) { return; // depends on control dependency: [if], data = [none] } if (ExpectedConditions.alertIsPresent().apply(browser) != null) { try { browser.switchTo().alert().accept(); // depends on control dependency: [try], data = [none] LOGGER.info("Alert accepted"); // depends on control dependency: [try], data = [none] } catch (Exception e) { LOGGER.error("Handling of PopUp windows failed"); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public void undeployManaged(@Observes UnDeployManagedDeployments event) throws Exception { forEachDeployedDeployment(new Operation<Container, Deployment>() { @Inject private Event<DeploymentEvent> event; @Override public void perform(Container container, Deployment deployment) throws Exception { if (container.getState().equals(Container.State.STARTED) && deployment.isDeployed()) { event.fire(new UnDeployDeployment(container, deployment)); } } }); } }
public class class_name { public void undeployManaged(@Observes UnDeployManagedDeployments event) throws Exception { forEachDeployedDeployment(new Operation<Container, Deployment>() { @Inject private Event<DeploymentEvent> event; @Override public void perform(Container container, Deployment deployment) throws Exception { if (container.getState().equals(Container.State.STARTED) && deployment.isDeployed()) { event.fire(new UnDeployDeployment(container, deployment)); // depends on control dependency: [if], data = [none] } } }); } }
public class class_name { private static int gregoYearFromIslamicStart(int year) { // ad hoc conversion, improve under #10752 // rough est for now, ok for grego 1846-2138, // otherwise occasionally wrong (for 3% of years) int cycle, offset, shift = 0; if (year >= 1397) { cycle = (year - 1397) / 67; offset = (year - 1397) % 67; shift = 2*cycle + ((offset >= 33)? 1: 0); } else { cycle = (year - 1396) / 67 - 1; offset = -(year - 1396) % 67; shift = 2*cycle + ((offset <= 33)? 1: 0); } return year + 579 - shift; } }
public class class_name { private static int gregoYearFromIslamicStart(int year) { // ad hoc conversion, improve under #10752 // rough est for now, ok for grego 1846-2138, // otherwise occasionally wrong (for 3% of years) int cycle, offset, shift = 0; if (year >= 1397) { cycle = (year - 1397) / 67; // depends on control dependency: [if], data = [(year] offset = (year - 1397) % 67; // depends on control dependency: [if], data = [(year] shift = 2*cycle + ((offset >= 33)? 1: 0); // depends on control dependency: [if], data = [none] } else { cycle = (year - 1396) / 67 - 1; // depends on control dependency: [if], data = [(year] offset = -(year - 1396) % 67; // depends on control dependency: [if], data = [(year] shift = 2*cycle + ((offset <= 33)? 1: 0); // depends on control dependency: [if], data = [none] } return year + 579 - shift; } }
public class class_name { @Override public void run() { synchronized (this) { // Save current event pipeline and currently handled event // because a SynchronousEventPipeline can be called while // handling an event (from another event processor). InternalEventPipeline currentPipeline = FeedBackPipelineFilter .getAssociatedPipeline(); EventBase<?> currentEvent = newEventsParent.get(); try { super.run(); } finally { newEventsParent.set(currentEvent); FeedBackPipelineFilter.setAssociatedPipeline(currentPipeline); } } } }
public class class_name { @Override public void run() { synchronized (this) { // Save current event pipeline and currently handled event // because a SynchronousEventPipeline can be called while // handling an event (from another event processor). InternalEventPipeline currentPipeline = FeedBackPipelineFilter .getAssociatedPipeline(); EventBase<?> currentEvent = newEventsParent.get(); try { super.run(); // depends on control dependency: [try], data = [none] } finally { newEventsParent.set(currentEvent); FeedBackPipelineFilter.setAssociatedPipeline(currentPipeline); } } } }
public class class_name { public static List<Field> getNotKeyColumns(Class<?> clazz) { List<Field> fields = getColumns(clazz); List<Field> keyFields = new ArrayList<Field>(); for(Field field : fields) { Column column = field.getAnnotation(Column.class); if(!column.isKey()) { keyFields.add(field); } } return keyFields; } }
public class class_name { public static List<Field> getNotKeyColumns(Class<?> clazz) { List<Field> fields = getColumns(clazz); List<Field> keyFields = new ArrayList<Field>(); for(Field field : fields) { Column column = field.getAnnotation(Column.class); if(!column.isKey()) { keyFields.add(field); // depends on control dependency: [if], data = [none] } } return keyFields; } }
public class class_name { public static String encodeUnicode(final String gbString) { char[] utfBytes = gbString.toCharArray(); String unicodeBytes = ""; for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) { String hexB = Integer.toHexString(utfBytes[byteIndex]); //转换为16进制整型字符串 if (hexB.length() <= 2) { hexB = "00" + hexB; } unicodeBytes = unicodeBytes + "\\u" + hexB; } System.out.println("unicodeBytes is: " + unicodeBytes); return unicodeBytes; } }
public class class_name { public static String encodeUnicode(final String gbString) { char[] utfBytes = gbString.toCharArray(); String unicodeBytes = ""; for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) { String hexB = Integer.toHexString(utfBytes[byteIndex]); //转换为16进制整型字符串 if (hexB.length() <= 2) { hexB = "00" + hexB; // depends on control dependency: [if], data = [none] } unicodeBytes = unicodeBytes + "\\u" + hexB; // depends on control dependency: [for], data = [none] } System.out.println("unicodeBytes is: " + unicodeBytes); return unicodeBytes; } }
public class class_name { @Override public Multimedia addMultimediaToPerson(final Person person, final String string) { if (person == null || string == null) { return new Multimedia(); } final Multimedia mm = new Multimedia(person, "Multimedia", string); person.insert(mm); return mm; } }
public class class_name { @Override public Multimedia addMultimediaToPerson(final Person person, final String string) { if (person == null || string == null) { return new Multimedia(); // depends on control dependency: [if], data = [none] } final Multimedia mm = new Multimedia(person, "Multimedia", string); person.insert(mm); return mm; } }
public class class_name { public synchronized Taxonomy<ElkObjectProperty> getObjectPropertyTaxonomyQuietly() throws ElkException { Taxonomy<ElkObjectProperty> result; try { result = getObjectPropertyTaxonomy(); } catch (ElkInconsistentOntologyException e) { LOGGER_.debug("Ontology is inconsistent"); result = new SingletoneTaxonomy<ElkObjectProperty, OrphanTaxonomyNode<ElkObjectProperty>>( ElkObjectPropertyKeyProvider.INSTANCE, getAllObjectProperties(), new TaxonomyNodeFactory<ElkObjectProperty, OrphanTaxonomyNode<ElkObjectProperty>, Taxonomy<ElkObjectProperty>>() { @Override public OrphanTaxonomyNode<ElkObjectProperty> createNode( final Iterable<? extends ElkObjectProperty> members, final int size, final Taxonomy<ElkObjectProperty> taxonomy) { return new OrphanTaxonomyNode<ElkObjectProperty>( members, size, elkFactory_.getOwlBottomObjectProperty(), taxonomy); } }); } return result; } }
public class class_name { public synchronized Taxonomy<ElkObjectProperty> getObjectPropertyTaxonomyQuietly() throws ElkException { Taxonomy<ElkObjectProperty> result; try { result = getObjectPropertyTaxonomy(); // depends on control dependency: [try], data = [none] } catch (ElkInconsistentOntologyException e) { LOGGER_.debug("Ontology is inconsistent"); result = new SingletoneTaxonomy<ElkObjectProperty, OrphanTaxonomyNode<ElkObjectProperty>>( ElkObjectPropertyKeyProvider.INSTANCE, getAllObjectProperties(), new TaxonomyNodeFactory<ElkObjectProperty, OrphanTaxonomyNode<ElkObjectProperty>, Taxonomy<ElkObjectProperty>>() { @Override public OrphanTaxonomyNode<ElkObjectProperty> createNode( final Iterable<? extends ElkObjectProperty> members, final int size, final Taxonomy<ElkObjectProperty> taxonomy) { return new OrphanTaxonomyNode<ElkObjectProperty>( members, size, elkFactory_.getOwlBottomObjectProperty(), taxonomy); } }); } // depends on control dependency: [catch], data = [none] return result; } }
public class class_name { public JmsDestinationType<WebFragmentDescriptor> getOrCreateJmsDestination() { List<Node> nodeList = model.get("jms-destination"); if (nodeList != null && nodeList.size() > 0) { return new JmsDestinationTypeImpl<WebFragmentDescriptor>(this, "jms-destination", model, nodeList.get(0)); } return createJmsDestination(); } }
public class class_name { public JmsDestinationType<WebFragmentDescriptor> getOrCreateJmsDestination() { List<Node> nodeList = model.get("jms-destination"); if (nodeList != null && nodeList.size() > 0) { return new JmsDestinationTypeImpl<WebFragmentDescriptor>(this, "jms-destination", model, nodeList.get(0)); // depends on control dependency: [if], data = [none] } return createJmsDestination(); } }
public class class_name { public String getInitialTransport() { if(getTransaction() != null) { return ((SIPTransaction)getTransaction()).getTransport(); } else { ViaHeader via = (ViaHeader) message.getHeader(ViaHeader.NAME); if(via == null || // https://github.com/Mobicents/sip-servlets/issues/47 // check if the via is container generated, if it is then it means // this is an outgoing request or response and thus should return null !sipFactoryImpl.getSipApplicationDispatcher().isViaHeaderExternal(via) ) { return null; } else { return via.getTransport(); } } } }
public class class_name { public String getInitialTransport() { if(getTransaction() != null) { return ((SIPTransaction)getTransaction()).getTransport(); // depends on control dependency: [if], data = [none] } else { ViaHeader via = (ViaHeader) message.getHeader(ViaHeader.NAME); if(via == null || // https://github.com/Mobicents/sip-servlets/issues/47 // check if the via is container generated, if it is then it means // this is an outgoing request or response and thus should return null !sipFactoryImpl.getSipApplicationDispatcher().isViaHeaderExternal(via) ) { return null; // depends on control dependency: [if], data = [none] } else { return via.getTransport(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public Map<String, Object> asMap() { Map<String, Object> map = getBody().asMap(); // add meta properties: ID, rev, deleted map.put("_id", id); if (revision != null) { map.put("_rev", revision); } if (this.isDeleted()) { map.put("_deleted", true); } return map; } }
public class class_name { public Map<String, Object> asMap() { Map<String, Object> map = getBody().asMap(); // add meta properties: ID, rev, deleted map.put("_id", id); if (revision != null) { map.put("_rev", revision); // depends on control dependency: [if], data = [none] } if (this.isDeleted()) { map.put("_deleted", true); // depends on control dependency: [if], data = [none] } return map; } }
public class class_name { public CRDTTimestampedLong subtractAndGet(long delta, VectorClock observedTimestamps) { checkSessionConsistency(observedTimestamps); stateWriteLock.lock(); try { checkNotMigrated(); if (delta < 0) { return addAndGet(-delta, observedTimestamps); } return updateAndGet(delta, observedTimestamps, false); } finally { stateWriteLock.unlock(); } } }
public class class_name { public CRDTTimestampedLong subtractAndGet(long delta, VectorClock observedTimestamps) { checkSessionConsistency(observedTimestamps); stateWriteLock.lock(); try { checkNotMigrated(); // depends on control dependency: [try], data = [none] if (delta < 0) { return addAndGet(-delta, observedTimestamps); // depends on control dependency: [if], data = [none] } return updateAndGet(delta, observedTimestamps, false); // depends on control dependency: [try], data = [none] } finally { stateWriteLock.unlock(); } } }
public class class_name { private char getRelationFromStringMatchers(String sourceLabel, String targetLabel) { char relation = IMappingElement.IDK; int i = 0; while ((relation == IMappingElement.IDK) && (i < stringMatchers.size())) { relation = stringMatchers.get(i).match(sourceLabel, targetLabel); i++; } return relation; } }
public class class_name { private char getRelationFromStringMatchers(String sourceLabel, String targetLabel) { char relation = IMappingElement.IDK; int i = 0; while ((relation == IMappingElement.IDK) && (i < stringMatchers.size())) { relation = stringMatchers.get(i).match(sourceLabel, targetLabel); // depends on control dependency: [while], data = [none] i++; // depends on control dependency: [while], data = [none] } return relation; } }
public class class_name { public static Map<String, Object> get(File packageFile) throws IOException { ZipFile zipFile = null; try { zipFile = new ZipFile(packageFile); ZipArchiveEntry entry = zipFile.getEntry(ZIP_ENTRY_PROPERTIES); if (entry != null && !entry.isDirectory()) { Map<String, Object> props = getPackageProperties(zipFile, entry); return new TreeMap<>(transformPropertyTypes(props)); } return Collections.emptyMap(); } finally { IOUtils.closeQuietly(zipFile); } } }
public class class_name { public static Map<String, Object> get(File packageFile) throws IOException { ZipFile zipFile = null; try { zipFile = new ZipFile(packageFile); ZipArchiveEntry entry = zipFile.getEntry(ZIP_ENTRY_PROPERTIES); if (entry != null && !entry.isDirectory()) { Map<String, Object> props = getPackageProperties(zipFile, entry); return new TreeMap<>(transformPropertyTypes(props)); // depends on control dependency: [if], data = [none] } return Collections.emptyMap(); } finally { IOUtils.closeQuietly(zipFile); } } }
public class class_name { @Override public void accumulateChunk(NDArrayMessageChunk chunk) { String id = chunk.getId(); if (!chunks.containsKey(id)) { List<NDArrayMessageChunk> list = new ArrayList<>(); list.add(chunk); chunks.put(id, list); } else { List<NDArrayMessageChunk> chunkList = chunks.get(id); chunkList.add(chunk); } log.debug("Accumulating chunk for id " + chunk.getId()); } }
public class class_name { @Override public void accumulateChunk(NDArrayMessageChunk chunk) { String id = chunk.getId(); if (!chunks.containsKey(id)) { List<NDArrayMessageChunk> list = new ArrayList<>(); list.add(chunk); // depends on control dependency: [if], data = [none] chunks.put(id, list); // depends on control dependency: [if], data = [none] } else { List<NDArrayMessageChunk> chunkList = chunks.get(id); chunkList.add(chunk); // depends on control dependency: [if], data = [none] } log.debug("Accumulating chunk for id " + chunk.getId()); } }
public class class_name { @VisibleForTesting public static void runMain(final String[] args) throws Exception { final CliHelpDefinition helpCli = new CliHelpDefinition(); try { Args.parse(helpCli, args); if (helpCli.help) { printUsage(0); return; } } catch (IllegalArgumentException invalidOption) { // Ignore because it is probably one of the non-help options. } final CliDefinition cli = new CliDefinition(); try { List<String> unusedArguments = Args.parse(cli, args); if (!unusedArguments.isEmpty()) { System.out.println("\n\nThe following arguments are not recognized: " + unusedArguments); printUsage(1); return; } } catch (IllegalArgumentException invalidOption) { System.out.println("\n\n" + invalidOption.getMessage()); printUsage(1); return; } configureLogs(cli.verbose); AbstractXmlApplicationContext context = new ClassPathXmlApplicationContext(DEFAULT_SPRING_CONTEXT); if (cli.springConfig != null) { context = new ClassPathXmlApplicationContext(DEFAULT_SPRING_CONTEXT, cli.springConfig); } try { context.getBean(Main.class).run(cli); } finally { context.close(); } } }
public class class_name { @VisibleForTesting public static void runMain(final String[] args) throws Exception { final CliHelpDefinition helpCli = new CliHelpDefinition(); try { Args.parse(helpCli, args); if (helpCli.help) { printUsage(0); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } } catch (IllegalArgumentException invalidOption) { // Ignore because it is probably one of the non-help options. } final CliDefinition cli = new CliDefinition(); try { List<String> unusedArguments = Args.parse(cli, args); if (!unusedArguments.isEmpty()) { System.out.println("\n\nThe following arguments are not recognized: " + unusedArguments); // depends on control dependency: [if], data = [none] printUsage(1); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } } catch (IllegalArgumentException invalidOption) { System.out.println("\n\n" + invalidOption.getMessage()); printUsage(1); return; } configureLogs(cli.verbose); AbstractXmlApplicationContext context = new ClassPathXmlApplicationContext(DEFAULT_SPRING_CONTEXT); if (cli.springConfig != null) { context = new ClassPathXmlApplicationContext(DEFAULT_SPRING_CONTEXT, cli.springConfig); } try { context.getBean(Main.class).run(cli); } finally { context.close(); } } }
public class class_name { @Override @Trivial public synchronized Collection<File> getFileset() { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "Retrieving fileSet", pid); // check if the filters are current // and re-evaluate if necessary if (!!!this.isCurrent) { evaluateFilters(); } // check if the cached set can be returned // and if not apply the filters to get a new set if (!!!this.returnCached) { applyFilters(); } //return a copied Collection of the fileset so that the caller can modify without //destroying the real fileset Collection<File> filesetToReturn = new ArrayList<File>(this.fileset.size()); filesetToReturn.addAll(this.fileset); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "returning fileset: " + filesetToReturn, pid); return filesetToReturn; } }
public class class_name { @Override @Trivial public synchronized Collection<File> getFileset() { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "Retrieving fileSet", pid); // check if the filters are current // and re-evaluate if necessary if (!!!this.isCurrent) { evaluateFilters(); // depends on control dependency: [if], data = [none] } // check if the cached set can be returned // and if not apply the filters to get a new set if (!!!this.returnCached) { applyFilters(); // depends on control dependency: [if], data = [none] } //return a copied Collection of the fileset so that the caller can modify without //destroying the real fileset Collection<File> filesetToReturn = new ArrayList<File>(this.fileset.size()); filesetToReturn.addAll(this.fileset); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "returning fileset: " + filesetToReturn, pid); return filesetToReturn; } }
public class class_name { @Override String[] getProgramArguments() throws IOException { LOGGER.entering(); List<String> args = new LinkedList<>(Arrays.asList(super.getProgramArguments())); // add the defaults which we don't already have a value for for (Entry<String, JsonElement> entry : defaultArgs.entrySet()) { String key = entry.getKey(); if (!args.contains(key)) { args.add(key); String val = defaultArgs.get(key).getAsString(); if (StringUtils.isNotBlank(val)) { args.add(val); } } } removeSeLionArgumentsAndValues(args); LOGGER.exiting(args.toString()); return args.toArray(new String[args.size()]); } }
public class class_name { @Override String[] getProgramArguments() throws IOException { LOGGER.entering(); List<String> args = new LinkedList<>(Arrays.asList(super.getProgramArguments())); // add the defaults which we don't already have a value for for (Entry<String, JsonElement> entry : defaultArgs.entrySet()) { String key = entry.getKey(); if (!args.contains(key)) { args.add(key); String val = defaultArgs.get(key).getAsString(); if (StringUtils.isNotBlank(val)) { args.add(val); // depends on control dependency: [if], data = [none] } } } removeSeLionArgumentsAndValues(args); LOGGER.exiting(args.toString()); return args.toArray(new String[args.size()]); } }
public class class_name { static synchronized void shutDownHub() { LOGGER.entering(); if (!isRunLocally()) { LOGGER.exiting(); return; } // shutdown in reverse order Collections.reverse(toBoot); for (LocalServerComponent eachItem : toBoot) { eachItem.shutdown(); } clearToBootList(); LOGGER.exiting(); } }
public class class_name { static synchronized void shutDownHub() { LOGGER.entering(); if (!isRunLocally()) { LOGGER.exiting(); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } // shutdown in reverse order Collections.reverse(toBoot); for (LocalServerComponent eachItem : toBoot) { eachItem.shutdown(); // depends on control dependency: [for], data = [eachItem] } clearToBootList(); LOGGER.exiting(); } }
public class class_name { @SuppressWarnings("unchecked") public static <T> Stream<T> create(final Iterable<? extends T> iterable) { if (iterable instanceof Stream) { return (Stream<T>) iterable; } else if (iterable instanceof ImmutableCollection<?> && ((ImmutableCollection<? extends T>) iterable).isEmpty()) { return new EmptyStream<T>(); } else { return new IterableStream<T>(iterable); } } }
public class class_name { @SuppressWarnings("unchecked") public static <T> Stream<T> create(final Iterable<? extends T> iterable) { if (iterable instanceof Stream) { return (Stream<T>) iterable; // depends on control dependency: [if], data = [none] } else if (iterable instanceof ImmutableCollection<?> && ((ImmutableCollection<? extends T>) iterable).isEmpty()) { return new EmptyStream<T>(); // depends on control dependency: [if], data = [none] } else { return new IterableStream<T>(iterable); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public void pickTraining(@NonNull SkipGramRequestMessage message) { RequestDescriptor descriptor = RequestDescriptor.createDescriptor(message.getOriginatorId(), message.getTaskId()); if (!chains.containsKey(descriptor)) { SkipGramChain chain = new SkipGramChain(message); // log.info("sI_{} Picking chain: originator: {}; taskId: {}", transport.getShardIndex(), message.getOriginatorId(), message.getTaskId()); chains.put(descriptor, chain); } } }
public class class_name { @Override public void pickTraining(@NonNull SkipGramRequestMessage message) { RequestDescriptor descriptor = RequestDescriptor.createDescriptor(message.getOriginatorId(), message.getTaskId()); if (!chains.containsKey(descriptor)) { SkipGramChain chain = new SkipGramChain(message); // log.info("sI_{} Picking chain: originator: {}; taskId: {}", transport.getShardIndex(), message.getOriginatorId(), message.getTaskId()); chains.put(descriptor, chain); // depends on control dependency: [if], data = [none] } } }
public class class_name { protected Observable<PreparedPayload> prepare(Statement statement) { final PrepareStatement prepared; if (statement instanceof PrepareStatement) { prepared = (PrepareStatement) statement; } else { //not including an explicit name here will produce a hash as explicit name //null would have let the server generate a name prepared = PrepareStatement.prepare(statement); } final SimpleN1qlQuery query = N1qlQuery.simple(prepared); Observable<GenericQueryResponse> source; if (isEncodedPlanEnabled()) { //we'll include the encodedPlan in each EXECUTE, so we don't broadcast during PREPARE source = deferAndWatch(new Func1<Subscriber, Observable<? extends GenericQueryResponse>>() { @Override public Observable<GenericQueryResponse> call(Subscriber subscriber) { GenericQueryRequest request = createN1qlRequest(query, bucket, username, password, null); request.subscriber(subscriber); return core.send(request); } }); } else { //we won't include the encoded plan in each EXECUTE, so we'll broadcast the PREPARE source = Observable.defer(new Func0<Observable<GetClusterConfigResponse>>() { @Override public Observable<GetClusterConfigResponse> call() { return core.send(new GetClusterConfigRequest()); } }).flatMap(new Func1<GetClusterConfigResponse, Observable<NodeInfo>>() { @Override public Observable<NodeInfo> call(GetClusterConfigResponse getClusterConfigResponse) { return Observable.from(getClusterConfigResponse.config() .bucketConfig(bucket) .nodes()); } }).filter(new Func1<NodeInfo, Boolean>() { @Override public Boolean call(NodeInfo nodeInfo) { return nodeInfo.services().containsKey(ServiceType.QUERY) || nodeInfo.sslServices().containsKey(ServiceType.QUERY); } }).flatMap(new Func1<NodeInfo, Observable<GenericQueryResponse>>() { @Override public Observable<GenericQueryResponse> call(NodeInfo nodeInfo) { try { InetAddress hostname = InetAddress.getByName(nodeInfo.hostname().address()); final GenericQueryRequest req = createN1qlRequest(query, bucket, username, password, hostname); return deferAndWatch(new Func1<Subscriber, Observable<? extends GenericQueryResponse>>() { @Override public Observable<? extends GenericQueryResponse> call(Subscriber subscriber) { req.subscriber(subscriber); return core.send(req); } }); } catch (UnknownHostException e) { return Observable.error(e); } } }); } return source.flatMap(new Func1<GenericQueryResponse, Observable<PreparedPayload>>() { @Override public Observable<PreparedPayload> call(GenericQueryResponse r) { if (r.status().isSuccess()) { r.info().subscribe(Buffers.BYTE_BUF_RELEASER); r.signature().subscribe(Buffers.BYTE_BUF_RELEASER); r.errors().subscribe(Buffers.BYTE_BUF_RELEASER); r.profileInfo().subscribe(Buffers.BYTE_BUF_RELEASER); return r.rows().map(new Func1<ByteBuf, PreparedPayload>() { @Override public PreparedPayload call(ByteBuf byteBuf) { try { JsonObject value = JSON_OBJECT_TRANSCODER.byteBufToJsonObject(byteBuf); return extractPreparedPayloadFromResponse(prepared, value); } catch (Exception e) { throw new TranscodingException("Could not decode N1QL Query Plan.", e); } finally { byteBuf.release(); } } }); } else { r.info().subscribe(Buffers.BYTE_BUF_RELEASER); r.signature().subscribe(Buffers.BYTE_BUF_RELEASER); r.rows().subscribe(Buffers.BYTE_BUF_RELEASER); r.profileInfo().subscribe(Buffers.BYTE_BUF_RELEASER); return r.errors().map(new Func1<ByteBuf, Exception>() { @Override public Exception call(ByteBuf byteBuf) { try { JsonObject value = JSON_OBJECT_TRANSCODER.byteBufToJsonObject(byteBuf); return new CouchbaseException("N1qlQuery Error - " + value.toString()); } catch (Exception e) { throw new TranscodingException("Could not decode N1QL Query Plan.", e); } finally { byteBuf.release(); } } }) .reduce(new ArrayList<Throwable>(), new Func2<ArrayList<Throwable>, Exception, ArrayList<Throwable>>() { @Override public ArrayList<Throwable> call(ArrayList<Throwable> throwables, Exception error) { throwables.add(error); return throwables; } }) .flatMap(new Func1<ArrayList<Throwable>, Observable<PreparedPayload>>() { @Override public Observable<PreparedPayload> call(ArrayList<Throwable> errors) { if (errors.size() == 1) { return Observable.error(new CouchbaseException( "Error while preparing plan", errors.get(0))); } else { return Observable.error(new CompositeException( "Multiple errors while preparing plan", errors)); } } }); } } }).last(); } }
public class class_name { protected Observable<PreparedPayload> prepare(Statement statement) { final PrepareStatement prepared; if (statement instanceof PrepareStatement) { prepared = (PrepareStatement) statement; // depends on control dependency: [if], data = [none] } else { //not including an explicit name here will produce a hash as explicit name //null would have let the server generate a name prepared = PrepareStatement.prepare(statement); // depends on control dependency: [if], data = [none] } final SimpleN1qlQuery query = N1qlQuery.simple(prepared); Observable<GenericQueryResponse> source; if (isEncodedPlanEnabled()) { //we'll include the encodedPlan in each EXECUTE, so we don't broadcast during PREPARE source = deferAndWatch(new Func1<Subscriber, Observable<? extends GenericQueryResponse>>() { @Override public Observable<GenericQueryResponse> call(Subscriber subscriber) { GenericQueryRequest request = createN1qlRequest(query, bucket, username, password, null); request.subscriber(subscriber); return core.send(request); } }); // depends on control dependency: [if], data = [none] } else { //we won't include the encoded plan in each EXECUTE, so we'll broadcast the PREPARE source = Observable.defer(new Func0<Observable<GetClusterConfigResponse>>() { @Override public Observable<GetClusterConfigResponse> call() { return core.send(new GetClusterConfigRequest()); } }).flatMap(new Func1<GetClusterConfigResponse, Observable<NodeInfo>>() { @Override public Observable<NodeInfo> call(GetClusterConfigResponse getClusterConfigResponse) { return Observable.from(getClusterConfigResponse.config() .bucketConfig(bucket) .nodes()); } }).filter(new Func1<NodeInfo, Boolean>() { @Override public Boolean call(NodeInfo nodeInfo) { return nodeInfo.services().containsKey(ServiceType.QUERY) || nodeInfo.sslServices().containsKey(ServiceType.QUERY); } }).flatMap(new Func1<NodeInfo, Observable<GenericQueryResponse>>() { @Override public Observable<GenericQueryResponse> call(NodeInfo nodeInfo) { try { InetAddress hostname = InetAddress.getByName(nodeInfo.hostname().address()); final GenericQueryRequest req = createN1qlRequest(query, bucket, username, password, hostname); return deferAndWatch(new Func1<Subscriber, Observable<? extends GenericQueryResponse>>() { @Override public Observable<? extends GenericQueryResponse> call(Subscriber subscriber) { req.subscriber(subscriber); return core.send(req); } }); // depends on control dependency: [try], data = [none] } catch (UnknownHostException e) { return Observable.error(e); } // depends on control dependency: [catch], data = [none] } }); // depends on control dependency: [if], data = [none] } return source.flatMap(new Func1<GenericQueryResponse, Observable<PreparedPayload>>() { @Override public Observable<PreparedPayload> call(GenericQueryResponse r) { if (r.status().isSuccess()) { r.info().subscribe(Buffers.BYTE_BUF_RELEASER); // depends on control dependency: [if], data = [none] r.signature().subscribe(Buffers.BYTE_BUF_RELEASER); // depends on control dependency: [if], data = [none] r.errors().subscribe(Buffers.BYTE_BUF_RELEASER); // depends on control dependency: [if], data = [none] r.profileInfo().subscribe(Buffers.BYTE_BUF_RELEASER); // depends on control dependency: [if], data = [none] return r.rows().map(new Func1<ByteBuf, PreparedPayload>() { @Override public PreparedPayload call(ByteBuf byteBuf) { try { JsonObject value = JSON_OBJECT_TRANSCODER.byteBufToJsonObject(byteBuf); return extractPreparedPayloadFromResponse(prepared, value); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new TranscodingException("Could not decode N1QL Query Plan.", e); } finally { // depends on control dependency: [catch], data = [none] byteBuf.release(); } } }); // depends on control dependency: [if], data = [none] } else { r.info().subscribe(Buffers.BYTE_BUF_RELEASER); // depends on control dependency: [if], data = [none] r.signature().subscribe(Buffers.BYTE_BUF_RELEASER); // depends on control dependency: [if], data = [none] r.rows().subscribe(Buffers.BYTE_BUF_RELEASER); // depends on control dependency: [if], data = [none] r.profileInfo().subscribe(Buffers.BYTE_BUF_RELEASER); // depends on control dependency: [if], data = [none] return r.errors().map(new Func1<ByteBuf, Exception>() { @Override public Exception call(ByteBuf byteBuf) { try { JsonObject value = JSON_OBJECT_TRANSCODER.byteBufToJsonObject(byteBuf); return new CouchbaseException("N1qlQuery Error - " + value.toString()); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new TranscodingException("Could not decode N1QL Query Plan.", e); } finally { // depends on control dependency: [catch], data = [none] byteBuf.release(); } } }) .reduce(new ArrayList<Throwable>(), new Func2<ArrayList<Throwable>, Exception, ArrayList<Throwable>>() { @Override public ArrayList<Throwable> call(ArrayList<Throwable> throwables, Exception error) { throwables.add(error); return throwables; } }) .flatMap(new Func1<ArrayList<Throwable>, Observable<PreparedPayload>>() { @Override public Observable<PreparedPayload> call(ArrayList<Throwable> errors) { if (errors.size() == 1) { return Observable.error(new CouchbaseException( "Error while preparing plan", errors.get(0))); // depends on control dependency: [if], data = [none] } else { return Observable.error(new CompositeException( "Multiple errors while preparing plan", errors)); // depends on control dependency: [if], data = [none] } } }); // depends on control dependency: [if], data = [none] } } }).last(); } }
public class class_name { public boolean removeBusStop(BusStop busStop) { if (this.validBusStops.remove(busStop)) { busStop.setContainer(null); busStop.setEventFirable(true); fireShapeChanged(new BusChangeEvent(this, BusChangeEventType.STOP_REMOVED, busStop, -1, "shape", //$NON-NLS-1$ null, null)); checkPrimitiveValidity(); return true; } final int idx = ListUtil.remove(this.invalidBusStops, INVALID_STOP_COMPARATOR, busStop); if (idx >= 0) { busStop.setContainer(null); fireShapeChanged(new BusChangeEvent(this, BusChangeEventType.STOP_REMOVED, busStop, -1, "shape", //$NON-NLS-1$ null, null)); checkPrimitiveValidity(); return true; } return false; } }
public class class_name { public boolean removeBusStop(BusStop busStop) { if (this.validBusStops.remove(busStop)) { busStop.setContainer(null); // depends on control dependency: [if], data = [none] busStop.setEventFirable(true); // depends on control dependency: [if], data = [none] fireShapeChanged(new BusChangeEvent(this, BusChangeEventType.STOP_REMOVED, busStop, -1, "shape", //$NON-NLS-1$ null, null)); // depends on control dependency: [if], data = [none] checkPrimitiveValidity(); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } final int idx = ListUtil.remove(this.invalidBusStops, INVALID_STOP_COMPARATOR, busStop); if (idx >= 0) { busStop.setContainer(null); // depends on control dependency: [if], data = [none] fireShapeChanged(new BusChangeEvent(this, BusChangeEventType.STOP_REMOVED, busStop, -1, "shape", //$NON-NLS-1$ null, null)); // depends on control dependency: [if], data = [none] checkPrimitiveValidity(); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { @VisibleForTesting public ControllerServiceStarter awaitServiceStarting() { monitor.enterWhenUninterruptibly(hasReachedStarting); try { if (serviceState != ServiceState.STARTING) { throw new IllegalStateException("Expected state=" + ServiceState.STARTING + ", but actual state=" + serviceState); } else { return this.starter; } } finally { monitor.leave(); } } }
public class class_name { @VisibleForTesting public ControllerServiceStarter awaitServiceStarting() { monitor.enterWhenUninterruptibly(hasReachedStarting); try { if (serviceState != ServiceState.STARTING) { throw new IllegalStateException("Expected state=" + ServiceState.STARTING + ", but actual state=" + serviceState); } else { return this.starter; // depends on control dependency: [if], data = [none] } } finally { monitor.leave(); } } }
public class class_name { public java.util.List<String> getBaseEndpointDnsNames() { if (baseEndpointDnsNames == null) { baseEndpointDnsNames = new com.amazonaws.internal.SdkInternalList<String>(); } return baseEndpointDnsNames; } }
public class class_name { public java.util.List<String> getBaseEndpointDnsNames() { if (baseEndpointDnsNames == null) { baseEndpointDnsNames = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none] } return baseEndpointDnsNames; } }
public class class_name { public Observable<ServiceResponse<OperationStatus>> updateWithServiceResponseAsync(UUID appId, ApplicationUpdateObject applicationUpdateObject) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (applicationUpdateObject == null) { throw new IllegalArgumentException("Parameter applicationUpdateObject is required and cannot be null."); } Validator.validate(applicationUpdateObject); String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint()); return service.update(appId, applicationUpdateObject, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<OperationStatus>>>() { @Override public Observable<ServiceResponse<OperationStatus>> call(Response<ResponseBody> response) { try { ServiceResponse<OperationStatus> clientResponse = updateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } }
public class class_name { public Observable<ServiceResponse<OperationStatus>> updateWithServiceResponseAsync(UUID appId, ApplicationUpdateObject applicationUpdateObject) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (appId == null) { throw new IllegalArgumentException("Parameter appId is required and cannot be null."); } if (applicationUpdateObject == null) { throw new IllegalArgumentException("Parameter applicationUpdateObject is required and cannot be null."); } Validator.validate(applicationUpdateObject); String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint()); return service.update(appId, applicationUpdateObject, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<OperationStatus>>>() { @Override public Observable<ServiceResponse<OperationStatus>> call(Response<ResponseBody> response) { try { ServiceResponse<OperationStatus> clientResponse = updateDelegate(response); return Observable.just(clientResponse); // depends on control dependency: [try], data = [none] } catch (Throwable t) { return Observable.error(t); } // depends on control dependency: [catch], data = [none] } }); } }
public class class_name { public FindingFilter withSeverities(Severity... severities) { java.util.ArrayList<String> severitiesCopy = new java.util.ArrayList<String>(severities.length); for (Severity value : severities) { severitiesCopy.add(value.toString()); } if (getSeverities() == null) { setSeverities(severitiesCopy); } else { getSeverities().addAll(severitiesCopy); } return this; } }
public class class_name { public FindingFilter withSeverities(Severity... severities) { java.util.ArrayList<String> severitiesCopy = new java.util.ArrayList<String>(severities.length); for (Severity value : severities) { severitiesCopy.add(value.toString()); // depends on control dependency: [for], data = [value] } if (getSeverities() == null) { setSeverities(severitiesCopy); // depends on control dependency: [if], data = [none] } else { getSeverities().addAll(severitiesCopy); // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { public void addAddon(MapAddon addon) { if (null == addons) { addons = new ArrayList<MapAddon>(); } addons.add(addon); } }
public class class_name { public void addAddon(MapAddon addon) { if (null == addons) { addons = new ArrayList<MapAddon>(); // depends on control dependency: [if], data = [none] } addons.add(addon); } }
public class class_name { void removeAllButDeepestAndAddCacheLeafNodes(int depth) { Queue<SchemaTableTree> queue = new LinkedList<>(); queue.add(this); while (!queue.isEmpty()) { SchemaTableTree current = queue.remove(); if (current.stepDepth < depth && current.children.isEmpty() && !current.isEmit() && !current.isOptionalLeftJoin()) { removeNode(current); } else { queue.addAll(current.children); if ((current.stepDepth == depth && current.children.isEmpty()) || (current.isEmit() && current.children.isEmpty()) || current.isOptionalLeftJoin() && current.children.isEmpty()) { this.leafNodes.add(current); } } } } }
public class class_name { void removeAllButDeepestAndAddCacheLeafNodes(int depth) { Queue<SchemaTableTree> queue = new LinkedList<>(); queue.add(this); while (!queue.isEmpty()) { SchemaTableTree current = queue.remove(); if (current.stepDepth < depth && current.children.isEmpty() && !current.isEmit() && !current.isOptionalLeftJoin()) { removeNode(current); // depends on control dependency: [if], data = [none] } else { queue.addAll(current.children); // depends on control dependency: [if], data = [none] if ((current.stepDepth == depth && current.children.isEmpty()) || (current.isEmit() && current.children.isEmpty()) || current.isOptionalLeftJoin() && current.children.isEmpty()) { this.leafNodes.add(current); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { public static String decode(Geometry geometry, float scale) { if (geometry == null) { return ""; } if (geometry instanceof LinearRing) { return decodeLinearRing((LinearRing) geometry, scale); } else if (geometry instanceof LineString) { return decodeLine((LineString) geometry, scale); } else if (geometry instanceof Polygon) { return decodePolygon((Polygon) geometry, scale); } else if (geometry instanceof MultiPolygon) { return decodeMultiPolygon((MultiPolygon) geometry, scale); } else if (geometry instanceof MultiLineString) { return decodeMultiLine((MultiLineString) geometry, scale); } return ""; } }
public class class_name { public static String decode(Geometry geometry, float scale) { if (geometry == null) { return ""; // depends on control dependency: [if], data = [none] } if (geometry instanceof LinearRing) { return decodeLinearRing((LinearRing) geometry, scale); // depends on control dependency: [if], data = [none] } else if (geometry instanceof LineString) { return decodeLine((LineString) geometry, scale); // depends on control dependency: [if], data = [none] } else if (geometry instanceof Polygon) { return decodePolygon((Polygon) geometry, scale); // depends on control dependency: [if], data = [none] } else if (geometry instanceof MultiPolygon) { return decodeMultiPolygon((MultiPolygon) geometry, scale); // depends on control dependency: [if], data = [none] } else if (geometry instanceof MultiLineString) { return decodeMultiLine((MultiLineString) geometry, scale); // depends on control dependency: [if], data = [none] } return ""; } }
public class class_name { public boolean triggerCheckpoint(long timestamp, boolean isPeriodic) { try { triggerCheckpoint(timestamp, checkpointProperties, null, isPeriodic, false); return true; } catch (CheckpointException e) { return false; } } }
public class class_name { public boolean triggerCheckpoint(long timestamp, boolean isPeriodic) { try { triggerCheckpoint(timestamp, checkpointProperties, null, isPeriodic, false); // depends on control dependency: [try], data = [none] return true; // depends on control dependency: [try], data = [none] } catch (CheckpointException e) { return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public String decryptOrNull(String data) { try { return decrypt(data); } catch (Exception e) { e.printStackTrace(); return null; } } }
public class class_name { public String decryptOrNull(String data) { try { return decrypt(data); // depends on control dependency: [try], data = [none] } catch (Exception e) { e.printStackTrace(); return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public boolean doCommand(String strCommand, ScreenField sourceSField, int iCommandOptions) { boolean bFlag = super.doCommand(strCommand, sourceSField, iCommandOptions); // This will send the command to my view if (bFlag) return bFlag; // Handled by my view int iIndex = strCommand.indexOf('='); if (iIndex != -1) if (this instanceof BaseScreen) { // only BaseScreens send commands if ((strCommand.indexOf(Param.TASK + '=') != -1) || (strCommand.indexOf(Params.APPLET + '=') != -1)) { // Asking to start a job Task task = this.getTask(); //xif (task == null) //x task = BaseApplet.getSharedInstance(); // ?? TaskScheduler js = ((Application)task.getApplication()).getTaskScheduler(); js.addTask(strCommand); return true; } BasePanel parentScreen = this.getParentScreen(); ScreenLocation itsLocation = null; if ((iCommandOptions & ScreenConstants.USE_NEW_WINDOW) == ScreenConstants.USE_SAME_WINDOW) // Use same window itsLocation = this.getScreenLocation(); else parentScreen = Screen.makeWindow(this.getTask().getApplication()); Task task = parentScreen.getTask();//getAppletScreen().getScreenFieldView().getControl(); if ((iCommandOptions & ScreenConstants.USE_NEW_WINDOW) == ScreenConstants.USE_SAME_WINDOW) // Use same window this.free(); // Remove this screen task.setProperties(null); Map<String,Object> properties = new Hashtable<String,Object>(); Util.parseArgs(properties, strCommand); // Set these properties task.setProperties(properties); BaseScreen.makeScreenFromParams(task, itsLocation, parentScreen, iCommandOptions, properties); bFlag = true; // Handled } if (strCommand.equalsIgnoreCase(MenuConstants.RESET)) bFlag = this.onRefresh(); if (strCommand.equalsIgnoreCase(MenuConstants.DELETE)) bFlag = this.onDelete(); if (strCommand.equalsIgnoreCase(MenuConstants.BACK)) bFlag = this.onBack(); if (strCommand.equalsIgnoreCase(MenuConstants.CUT)) bFlag = true; // Ignore this command (handled by CutActionHandler) if (strCommand.equalsIgnoreCase(MenuConstants.COPY)) bFlag = true; // Ignore this command if (strCommand.equalsIgnoreCase(MenuConstants.PASTE)) bFlag = true; // Ignore this command // Commands before this line do not validate the current field if (bFlag == false) // Not yet handled if (strCommand.length() > 0) // Valid command if (!(strCommand.equalsIgnoreCase(MenuConstants.UNDO))) // Don't select first on undo this.selectField(null, DBConstants.SELECT_FIRST_FIELD); // Validate current field // Commands after this line do validate the current field if (strCommand.equalsIgnoreCase(MenuConstants.FIRST)) bFlag = this.onMove(Constants.FIRST_RECORD); if (strCommand.equalsIgnoreCase(MenuConstants.PREVIOUS)) bFlag = this.onMove(Constants.PREVIOUS_RECORD); if (strCommand.equalsIgnoreCase(MenuConstants.NEXT)) bFlag = this.onMove(Constants.NEXT_RECORD); if (strCommand.equalsIgnoreCase(MenuConstants.LAST)) bFlag = this.onMove(Constants.LAST_RECORD); if (strCommand.equalsIgnoreCase(MenuConstants.SUBMIT)) bFlag = this.onAdd(); if (strCommand.equalsIgnoreCase(MenuConstants.LOOKUP)) return (this.onForm(null, (((iCommandOptions & ScreenConstants.USE_NEW_WINDOW) == ScreenConstants.USE_SAME_WINDOW) ? ScreenConstants.DISPLAY_MODE : ScreenConstants.SELECT_MODE), true, iCommandOptions, null) != null); if (strCommand.equalsIgnoreCase(MenuConstants.FORM)) bFlag = (this.onForm(null, ScreenConstants.MAINT_MODE, false, iCommandOptions, null) != null); if (strCommand.equalsIgnoreCase(MenuConstants.FORMLINK)) bFlag = (this.onForm(null, ScreenConstants.MAINT_MODE, true, iCommandOptions, null) != null); if (strCommand.equalsIgnoreCase(MenuConstants.LOOKUPCLONE)) return (this.onForm(null, ScreenConstants.SELECT_MODE, true, ScreenConstants.USE_NEW_WINDOW, null) != null); if (strCommand.equalsIgnoreCase(MenuConstants.FORMCLONE)) bFlag = (this.onForm(null, ScreenConstants.MAINT_MODE, true, ScreenConstants.USE_NEW_WINDOW, null) != null); if (strCommand.equalsIgnoreCase(MenuConstants.FORMDETAIL)) bFlag = (this.onForm(null, ScreenConstants.DETAIL_MODE, true, iCommandOptions, null) != null); if (strCommand.equalsIgnoreCase(MenuConstants.POST)) bFlag = (this.onForm(null, ScreenConstants.POST_MODE, true, iCommandOptions, null) != null); if (strCommand.equalsIgnoreCase(MenuConstants.HELP)) bFlag = this.onHelp(iCommandOptions); if (strCommand.equalsIgnoreCase(MenuConstants.HOME)) bFlag = this.onHome(); if (strCommand.equalsIgnoreCase(MenuConstants.CLONE)) bFlag = this.onClone(); if (strCommand.equalsIgnoreCase(MenuConstants.NEW_WINDOW)) bFlag = this.onNewWindow(); if (strCommand.equalsIgnoreCase(MenuConstants.DISPLAY)) bFlag = this.onDisplay(); if (strCommand.equalsIgnoreCase(MenuConstants.LOGIN)) bFlag = this.onLogin(); if (strCommand.equalsIgnoreCase(MenuConstants.LOGON)) bFlag = this.onLogon(); if (strCommand.equalsIgnoreCase(MenuConstants.LOGOUT)) bFlag = this.onLogout(); if (strCommand.equalsIgnoreCase(MenuConstants.CHANGE_PASSWORD)) bFlag = this.onChangePassword(); if (strCommand.equalsIgnoreCase(MenuConstants.SETTINGS)) bFlag = this.onChangeSettings(); return bFlag; } }
public class class_name { public boolean doCommand(String strCommand, ScreenField sourceSField, int iCommandOptions) { boolean bFlag = super.doCommand(strCommand, sourceSField, iCommandOptions); // This will send the command to my view if (bFlag) return bFlag; // Handled by my view int iIndex = strCommand.indexOf('='); if (iIndex != -1) if (this instanceof BaseScreen) { // only BaseScreens send commands if ((strCommand.indexOf(Param.TASK + '=') != -1) || (strCommand.indexOf(Params.APPLET + '=') != -1)) { // Asking to start a job Task task = this.getTask(); //xif (task == null) //x task = BaseApplet.getSharedInstance(); // ?? TaskScheduler js = ((Application)task.getApplication()).getTaskScheduler(); js.addTask(strCommand); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } BasePanel parentScreen = this.getParentScreen(); ScreenLocation itsLocation = null; if ((iCommandOptions & ScreenConstants.USE_NEW_WINDOW) == ScreenConstants.USE_SAME_WINDOW) // Use same window itsLocation = this.getScreenLocation(); else parentScreen = Screen.makeWindow(this.getTask().getApplication()); Task task = parentScreen.getTask();//getAppletScreen().getScreenFieldView().getControl(); if ((iCommandOptions & ScreenConstants.USE_NEW_WINDOW) == ScreenConstants.USE_SAME_WINDOW) // Use same window this.free(); // Remove this screen task.setProperties(null); // depends on control dependency: [if], data = [none] Map<String,Object> properties = new Hashtable<String,Object>(); Util.parseArgs(properties, strCommand); // Set these properties // depends on control dependency: [if], data = [none] task.setProperties(properties); // depends on control dependency: [if], data = [none] BaseScreen.makeScreenFromParams(task, itsLocation, parentScreen, iCommandOptions, properties); // depends on control dependency: [if], data = [none] bFlag = true; // Handled // depends on control dependency: [if], data = [none] } if (strCommand.equalsIgnoreCase(MenuConstants.RESET)) bFlag = this.onRefresh(); if (strCommand.equalsIgnoreCase(MenuConstants.DELETE)) bFlag = this.onDelete(); if (strCommand.equalsIgnoreCase(MenuConstants.BACK)) bFlag = this.onBack(); if (strCommand.equalsIgnoreCase(MenuConstants.CUT)) bFlag = true; // Ignore this command (handled by CutActionHandler) if (strCommand.equalsIgnoreCase(MenuConstants.COPY)) bFlag = true; // Ignore this command if (strCommand.equalsIgnoreCase(MenuConstants.PASTE)) bFlag = true; // Ignore this command // Commands before this line do not validate the current field if (bFlag == false) // Not yet handled if (strCommand.length() > 0) // Valid command if (!(strCommand.equalsIgnoreCase(MenuConstants.UNDO))) // Don't select first on undo this.selectField(null, DBConstants.SELECT_FIRST_FIELD); // Validate current field // Commands after this line do validate the current field if (strCommand.equalsIgnoreCase(MenuConstants.FIRST)) bFlag = this.onMove(Constants.FIRST_RECORD); if (strCommand.equalsIgnoreCase(MenuConstants.PREVIOUS)) bFlag = this.onMove(Constants.PREVIOUS_RECORD); if (strCommand.equalsIgnoreCase(MenuConstants.NEXT)) bFlag = this.onMove(Constants.NEXT_RECORD); if (strCommand.equalsIgnoreCase(MenuConstants.LAST)) bFlag = this.onMove(Constants.LAST_RECORD); if (strCommand.equalsIgnoreCase(MenuConstants.SUBMIT)) bFlag = this.onAdd(); if (strCommand.equalsIgnoreCase(MenuConstants.LOOKUP)) return (this.onForm(null, (((iCommandOptions & ScreenConstants.USE_NEW_WINDOW) == ScreenConstants.USE_SAME_WINDOW) ? ScreenConstants.DISPLAY_MODE : ScreenConstants.SELECT_MODE), true, iCommandOptions, null) != null); if (strCommand.equalsIgnoreCase(MenuConstants.FORM)) bFlag = (this.onForm(null, ScreenConstants.MAINT_MODE, false, iCommandOptions, null) != null); if (strCommand.equalsIgnoreCase(MenuConstants.FORMLINK)) bFlag = (this.onForm(null, ScreenConstants.MAINT_MODE, true, iCommandOptions, null) != null); if (strCommand.equalsIgnoreCase(MenuConstants.LOOKUPCLONE)) return (this.onForm(null, ScreenConstants.SELECT_MODE, true, ScreenConstants.USE_NEW_WINDOW, null) != null); if (strCommand.equalsIgnoreCase(MenuConstants.FORMCLONE)) bFlag = (this.onForm(null, ScreenConstants.MAINT_MODE, true, ScreenConstants.USE_NEW_WINDOW, null) != null); if (strCommand.equalsIgnoreCase(MenuConstants.FORMDETAIL)) bFlag = (this.onForm(null, ScreenConstants.DETAIL_MODE, true, iCommandOptions, null) != null); if (strCommand.equalsIgnoreCase(MenuConstants.POST)) bFlag = (this.onForm(null, ScreenConstants.POST_MODE, true, iCommandOptions, null) != null); if (strCommand.equalsIgnoreCase(MenuConstants.HELP)) bFlag = this.onHelp(iCommandOptions); if (strCommand.equalsIgnoreCase(MenuConstants.HOME)) bFlag = this.onHome(); if (strCommand.equalsIgnoreCase(MenuConstants.CLONE)) bFlag = this.onClone(); if (strCommand.equalsIgnoreCase(MenuConstants.NEW_WINDOW)) bFlag = this.onNewWindow(); if (strCommand.equalsIgnoreCase(MenuConstants.DISPLAY)) bFlag = this.onDisplay(); if (strCommand.equalsIgnoreCase(MenuConstants.LOGIN)) bFlag = this.onLogin(); if (strCommand.equalsIgnoreCase(MenuConstants.LOGON)) bFlag = this.onLogon(); if (strCommand.equalsIgnoreCase(MenuConstants.LOGOUT)) bFlag = this.onLogout(); if (strCommand.equalsIgnoreCase(MenuConstants.CHANGE_PASSWORD)) bFlag = this.onChangePassword(); if (strCommand.equalsIgnoreCase(MenuConstants.SETTINGS)) bFlag = this.onChangeSettings(); return bFlag; } }