code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { private void adaptHelperText(final float score) { if (!helperTexts.isEmpty()) { CharSequence helperText = getHelperText(score); if (helperText != null) { int color = getHelperTextColor(score); helperText = "<font color=\"" + color + "\">" + helperText + "</font>"; String prefix = getPasswordVerificationPrefix(); if (prefix != null) { prefix = "<font color=\"" + regularHelperTextColor + "\">" + prefix + ": </font>"; } else { prefix = ""; } setHelperText(Html.fromHtml(prefix + helperText)); } else { setHelperText(regularHelperText); } } else { setHelperText(regularHelperText); } } }
public class class_name { private void adaptHelperText(final float score) { if (!helperTexts.isEmpty()) { CharSequence helperText = getHelperText(score); if (helperText != null) { int color = getHelperTextColor(score); helperText = "<font color=\"" + color + "\">" + helperText + "</font>"; // depends on control dependency: [if], data = [none] String prefix = getPasswordVerificationPrefix(); if (prefix != null) { prefix = "<font color=\"" + regularHelperTextColor + "\">" + prefix + ": </font>"; // depends on control dependency: [if], data = [none] } else { prefix = ""; // depends on control dependency: [if], data = [none] } setHelperText(Html.fromHtml(prefix + helperText)); // depends on control dependency: [if], data = [none] } else { setHelperText(regularHelperText); // depends on control dependency: [if], data = [none] } } else { setHelperText(regularHelperText); // depends on control dependency: [if], data = [none] } } }
public class class_name { public EEnum getBDAFlags() { if (bdaFlagsEEnum == null) { bdaFlagsEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(1); } return bdaFlagsEEnum; } }
public class class_name { public EEnum getBDAFlags() { if (bdaFlagsEEnum == null) { bdaFlagsEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(1); // depends on control dependency: [if], data = [none] } return bdaFlagsEEnum; } }
public class class_name { static Object getIndexObject(String s) { long indexTest = indexFromString(s); if (indexTest >= 0) { return Integer.valueOf((int)indexTest); } return s; } }
public class class_name { static Object getIndexObject(String s) { long indexTest = indexFromString(s); if (indexTest >= 0) { return Integer.valueOf((int)indexTest); // depends on control dependency: [if], data = [none] } return s; } }
public class class_name { private static char digitToBasic(int digit, boolean uppercase) { /* 0..25 map to ASCII a..z or A..Z */ /* 26..35 map to ASCII 0..9 */ if(digit<26) { if(uppercase) { return (char)(CAPITAL_A+digit); } else { return (char)(SMALL_A+digit); } } else { return (char)((ZERO-26)+digit); } } }
public class class_name { private static char digitToBasic(int digit, boolean uppercase) { /* 0..25 map to ASCII a..z or A..Z */ /* 26..35 map to ASCII 0..9 */ if(digit<26) { if(uppercase) { return (char)(CAPITAL_A+digit); // depends on control dependency: [if], data = [none] } else { return (char)(SMALL_A+digit); // depends on control dependency: [if], data = [none] } } else { return (char)((ZERO-26)+digit); // depends on control dependency: [if], data = [26)] } } }
public class class_name { public void saveEntity(CmsEntity entity, final boolean clearOnSuccess, final Command callback) { AsyncCallback<CmsValidationResult> asyncCallback = new AsyncCallback<CmsValidationResult>() { public void onFailure(Throwable caught) { onRpcError(caught); } public void onSuccess(CmsValidationResult result) { callback.execute(); if (clearOnSuccess) { destroyForm(true); } } }; getService().saveEntity(entity, asyncCallback); } }
public class class_name { public void saveEntity(CmsEntity entity, final boolean clearOnSuccess, final Command callback) { AsyncCallback<CmsValidationResult> asyncCallback = new AsyncCallback<CmsValidationResult>() { public void onFailure(Throwable caught) { onRpcError(caught); } public void onSuccess(CmsValidationResult result) { callback.execute(); if (clearOnSuccess) { destroyForm(true); // depends on control dependency: [if], data = [none] } } }; getService().saveEntity(entity, asyncCallback); } }
public class class_name { public ModifyTargetGroupAttributesRequest withAttributes(TargetGroupAttribute... attributes) { if (this.attributes == null) { setAttributes(new java.util.ArrayList<TargetGroupAttribute>(attributes.length)); } for (TargetGroupAttribute ele : attributes) { this.attributes.add(ele); } return this; } }
public class class_name { public ModifyTargetGroupAttributesRequest withAttributes(TargetGroupAttribute... attributes) { if (this.attributes == null) { setAttributes(new java.util.ArrayList<TargetGroupAttribute>(attributes.length)); // depends on control dependency: [if], data = [none] } for (TargetGroupAttribute ele : attributes) { this.attributes.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { static Class<?> getComponentInterface(Class<?> homeInterface, String beanName) throws EJBConfigurationException { Class<?> compInterface = null; Method[] methods = homeInterface.getMethods(); for (Method method : methods) { if (method.getName().startsWith("create")) { compInterface = method.getReturnType(); if (compInterface == Void.TYPE) { // Log the error and throw meaningful exception. d457128.2 Tr.error(tc, "JIT_VOID_CREATE_RETURN_CNTR5018E", new Object[] { beanName, homeInterface.getName(), method.getName() }); throw new EJBConfigurationException("EJB home interface " + homeInterface.getName() + " 'create' method must return the component interface : " + method + " : " + beanName); } break; } } if (compInterface == null) { // Log the error and throw meaningful exception. d457128.2 Tr.error(tc, "JIT_NO_CREATE_METHOD_CNTR5019E", new Object[] { beanName, homeInterface.getName() }); throw new EJBConfigurationException("EJB home interface " + homeInterface.getName() + " must define a 'create' method : " + beanName); } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "getComponentInterface : " + compInterface); return compInterface; } }
public class class_name { static Class<?> getComponentInterface(Class<?> homeInterface, String beanName) throws EJBConfigurationException { Class<?> compInterface = null; Method[] methods = homeInterface.getMethods(); for (Method method : methods) { if (method.getName().startsWith("create")) { compInterface = method.getReturnType(); // depends on control dependency: [if], data = [none] if (compInterface == Void.TYPE) { // Log the error and throw meaningful exception. d457128.2 Tr.error(tc, "JIT_VOID_CREATE_RETURN_CNTR5018E", new Object[] { beanName, homeInterface.getName(), method.getName() }); // depends on control dependency: [if], data = [none] throw new EJBConfigurationException("EJB home interface " + homeInterface.getName() + " 'create' method must return the component interface : " + method + " : " + beanName); } break; } } if (compInterface == null) { // Log the error and throw meaningful exception. d457128.2 Tr.error(tc, "JIT_NO_CREATE_METHOD_CNTR5019E", new Object[] { beanName, homeInterface.getName() }); throw new EJBConfigurationException("EJB home interface " + homeInterface.getName() + " must define a 'create' method : " + beanName); } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "getComponentInterface : " + compInterface); return compInterface; // depends on control dependency: [if], data = [none] } }
public class class_name { public void setReplicationTaskAssessmentResults(java.util.Collection<ReplicationTaskAssessmentResult> replicationTaskAssessmentResults) { if (replicationTaskAssessmentResults == null) { this.replicationTaskAssessmentResults = null; return; } this.replicationTaskAssessmentResults = new java.util.ArrayList<ReplicationTaskAssessmentResult>(replicationTaskAssessmentResults); } }
public class class_name { public void setReplicationTaskAssessmentResults(java.util.Collection<ReplicationTaskAssessmentResult> replicationTaskAssessmentResults) { if (replicationTaskAssessmentResults == null) { this.replicationTaskAssessmentResults = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.replicationTaskAssessmentResults = new java.util.ArrayList<ReplicationTaskAssessmentResult>(replicationTaskAssessmentResults); } }
public class class_name { @SuppressWarnings("unchecked") public static <T> T stripProxy(@Nullable final WrappingProxy<T> wrappingProxy) { if (wrappingProxy == null) { return null; } T delegate = wrappingProxy.getWrappedDelegate(); int numProxiesStripped = 0; while (delegate instanceof WrappingProxy) { throwIfSafetyNetExceeded(++numProxiesStripped); delegate = ((WrappingProxy<T>) delegate).getWrappedDelegate(); } return delegate; } }
public class class_name { @SuppressWarnings("unchecked") public static <T> T stripProxy(@Nullable final WrappingProxy<T> wrappingProxy) { if (wrappingProxy == null) { return null; // depends on control dependency: [if], data = [none] } T delegate = wrappingProxy.getWrappedDelegate(); int numProxiesStripped = 0; while (delegate instanceof WrappingProxy) { throwIfSafetyNetExceeded(++numProxiesStripped); // depends on control dependency: [while], data = [none] delegate = ((WrappingProxy<T>) delegate).getWrappedDelegate(); // depends on control dependency: [while], data = [none] } return delegate; } }
public class class_name { private ExceptionCollection collectDependencies(Engine engine, MavenProject project, List<DependencyNode> nodes, ProjectBuildingRequest buildingRequest, boolean aggregate) { ExceptionCollection exCol; exCol = collectMavenDependencies(engine, project, nodes, buildingRequest, aggregate); final FileSet[] projectScan; if (scanSet == null || scanSet.length == 0) { // Define the default FileSets final FileSet resourcesSet = new FileSet(); final FileSet filtersSet = new FileSet(); final FileSet webappSet = new FileSet(); try { resourcesSet.setDirectory(new File(project.getBasedir(), "src/main/resources").getCanonicalPath()); filtersSet.setDirectory(new File(project.getBasedir(), "src/main/filters").getCanonicalPath()); webappSet.setDirectory(new File(project.getBasedir(), "src/main/webapp").getCanonicalPath()); } catch (IOException ex) { if (exCol == null) { exCol = new ExceptionCollection(); } exCol.addException(ex); } projectScan = new FileSet[]{resourcesSet, filtersSet, webappSet}; } else if (aggregate) { projectScan = new FileSet[scanSet.length]; for (int x = 0; x < scanSet.length; x++) { //deep copy of the FileSet - modifying the directory if it is not absolute. final FileSet copyFrom = scanSet[x]; final FileSet fsCopy = new FileSet(); final File f = new File(copyFrom.getDirectory()); if (f.isAbsolute()) { fsCopy.setDirectory(copyFrom.getDirectory()); } else { try { fsCopy.setDirectory(new File(project.getBasedir(), copyFrom.getDirectory()).getCanonicalPath()); } catch (IOException ex) { if (exCol == null) { exCol = new ExceptionCollection(); } exCol.addException(ex); fsCopy.setDirectory(copyFrom.getDirectory()); } } fsCopy.setDirectoryMode(copyFrom.getDirectoryMode()); fsCopy.setExcludes(copyFrom.getExcludes()); fsCopy.setFileMode(copyFrom.getFileMode()); fsCopy.setFollowSymlinks(copyFrom.isFollowSymlinks()); fsCopy.setIncludes(copyFrom.getIncludes()); fsCopy.setLineEnding(copyFrom.getLineEnding()); fsCopy.setMapper(copyFrom.getMapper()); fsCopy.setModelEncoding(copyFrom.getModelEncoding()); fsCopy.setOutputDirectory(copyFrom.getOutputDirectory()); fsCopy.setUseDefaultExcludes(copyFrom.isUseDefaultExcludes()); projectScan[x] = fsCopy; } } else { projectScan = scanSet; } // Iterate through FileSets and scan included files final FileSetManager fileSetManager = new FileSetManager(); for (FileSet fileSet : projectScan) { final String[] includedFiles = fileSetManager.getIncludedFiles(fileSet); for (String include : includedFiles) { final File includeFile = new File(fileSet.getDirectory(), include).getAbsoluteFile(); if (includeFile.exists()) { engine.scan(includeFile, project.getName()); } //TODO - should we add an exception/error reporting for files that do not exist? } } return exCol; } }
public class class_name { private ExceptionCollection collectDependencies(Engine engine, MavenProject project, List<DependencyNode> nodes, ProjectBuildingRequest buildingRequest, boolean aggregate) { ExceptionCollection exCol; exCol = collectMavenDependencies(engine, project, nodes, buildingRequest, aggregate); final FileSet[] projectScan; if (scanSet == null || scanSet.length == 0) { // Define the default FileSets final FileSet resourcesSet = new FileSet(); final FileSet filtersSet = new FileSet(); final FileSet webappSet = new FileSet(); try { resourcesSet.setDirectory(new File(project.getBasedir(), "src/main/resources").getCanonicalPath()); // depends on control dependency: [try], data = [none] filtersSet.setDirectory(new File(project.getBasedir(), "src/main/filters").getCanonicalPath()); // depends on control dependency: [try], data = [none] webappSet.setDirectory(new File(project.getBasedir(), "src/main/webapp").getCanonicalPath()); // depends on control dependency: [try], data = [none] } catch (IOException ex) { if (exCol == null) { exCol = new ExceptionCollection(); // depends on control dependency: [if], data = [none] } exCol.addException(ex); } // depends on control dependency: [catch], data = [none] projectScan = new FileSet[]{resourcesSet, filtersSet, webappSet}; // depends on control dependency: [if], data = [none] } else if (aggregate) { projectScan = new FileSet[scanSet.length]; // depends on control dependency: [if], data = [none] for (int x = 0; x < scanSet.length; x++) { //deep copy of the FileSet - modifying the directory if it is not absolute. final FileSet copyFrom = scanSet[x]; final FileSet fsCopy = new FileSet(); final File f = new File(copyFrom.getDirectory()); if (f.isAbsolute()) { fsCopy.setDirectory(copyFrom.getDirectory()); // depends on control dependency: [if], data = [none] } else { try { fsCopy.setDirectory(new File(project.getBasedir(), copyFrom.getDirectory()).getCanonicalPath()); // depends on control dependency: [try], data = [none] } catch (IOException ex) { if (exCol == null) { exCol = new ExceptionCollection(); // depends on control dependency: [if], data = [none] } exCol.addException(ex); fsCopy.setDirectory(copyFrom.getDirectory()); } // depends on control dependency: [catch], data = [none] } fsCopy.setDirectoryMode(copyFrom.getDirectoryMode()); // depends on control dependency: [for], data = [none] fsCopy.setExcludes(copyFrom.getExcludes()); // depends on control dependency: [for], data = [none] fsCopy.setFileMode(copyFrom.getFileMode()); // depends on control dependency: [for], data = [none] fsCopy.setFollowSymlinks(copyFrom.isFollowSymlinks()); // depends on control dependency: [for], data = [none] fsCopy.setIncludes(copyFrom.getIncludes()); // depends on control dependency: [for], data = [none] fsCopy.setLineEnding(copyFrom.getLineEnding()); // depends on control dependency: [for], data = [none] fsCopy.setMapper(copyFrom.getMapper()); // depends on control dependency: [for], data = [none] fsCopy.setModelEncoding(copyFrom.getModelEncoding()); // depends on control dependency: [for], data = [none] fsCopy.setOutputDirectory(copyFrom.getOutputDirectory()); // depends on control dependency: [for], data = [none] fsCopy.setUseDefaultExcludes(copyFrom.isUseDefaultExcludes()); // depends on control dependency: [for], data = [none] projectScan[x] = fsCopy; // depends on control dependency: [for], data = [x] } } else { projectScan = scanSet; // depends on control dependency: [if], data = [none] } // Iterate through FileSets and scan included files final FileSetManager fileSetManager = new FileSetManager(); for (FileSet fileSet : projectScan) { final String[] includedFiles = fileSetManager.getIncludedFiles(fileSet); for (String include : includedFiles) { final File includeFile = new File(fileSet.getDirectory(), include).getAbsoluteFile(); if (includeFile.exists()) { engine.scan(includeFile, project.getName()); // depends on control dependency: [if], data = [none] } //TODO - should we add an exception/error reporting for files that do not exist? } } return exCol; } }
public class class_name { @PluginFactory public static TerminalConsoleAppender createAppender( @Required(message = "No name provided for TerminalConsoleAppender") @PluginAttribute("name") String name, @PluginElement("Filter") Filter filter, @PluginElement("Layout") @Nullable Layout<? extends Serializable> layout, @PluginAttribute(value = "ignoreExceptions", defaultBoolean = true) boolean ignoreExceptions) { if (layout == null) { layout = PatternLayout.createDefaultLayout(); } return new TerminalConsoleAppender(name, filter, layout, ignoreExceptions); } }
public class class_name { @PluginFactory public static TerminalConsoleAppender createAppender( @Required(message = "No name provided for TerminalConsoleAppender") @PluginAttribute("name") String name, @PluginElement("Filter") Filter filter, @PluginElement("Layout") @Nullable Layout<? extends Serializable> layout, @PluginAttribute(value = "ignoreExceptions", defaultBoolean = true) boolean ignoreExceptions) { if (layout == null) { layout = PatternLayout.createDefaultLayout(); // depends on control dependency: [if], data = [none] } return new TerminalConsoleAppender(name, filter, layout, ignoreExceptions); } }
public class class_name { public static BytesRefTermStream get(IndexReader reader, IndexFieldData indexFieldData) { if (indexFieldData instanceof IndexNumericFieldData) { IndexNumericFieldData numFieldData = (IndexNumericFieldData) indexFieldData; switch (numFieldData.getNumericType()) { case INT: return new IntegerBytesRefTermStream(reader, numFieldData); case LONG: return new LongBytesRefTermStream(reader, numFieldData); default: throw new UnsupportedOperationException("Streaming numeric type '" + numFieldData.getNumericType().name() + "' is unsupported"); } } else { return new BytesBytesRefTermStream(reader, indexFieldData); } } }
public class class_name { public static BytesRefTermStream get(IndexReader reader, IndexFieldData indexFieldData) { if (indexFieldData instanceof IndexNumericFieldData) { IndexNumericFieldData numFieldData = (IndexNumericFieldData) indexFieldData; switch (numFieldData.getNumericType()) { case INT: return new IntegerBytesRefTermStream(reader, numFieldData); // depends on control dependency: [if], data = [none] case LONG: return new LongBytesRefTermStream(reader, numFieldData); // depends on control dependency: [if], data = [none] default: throw new UnsupportedOperationException("Streaming numeric type '" + numFieldData.getNumericType().name() + "' is unsupported"); } } else { return new BytesBytesRefTermStream(reader, indexFieldData); } } }
public class class_name { public CmsXmlContentErrorHandler saveContent(Map<String, String> contentValues) throws CmsUgcException { checkNotFinished(); try { CmsFile file = m_cms.readFile(m_editResource); CmsXmlContent content = addContentValues(file, contentValues); CmsXmlContentErrorHandler errorHandler = content.validate(m_cms); if (!errorHandler.hasErrors()) { file.setContents(content.marshal()); // the file content might have been modified during the write operation file = m_cms.writeFile(file); } return errorHandler; } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); throw new CmsUgcException(e, CmsUgcConstants.ErrorCode.errMisc, e.getLocalizedMessage()); } } }
public class class_name { public CmsXmlContentErrorHandler saveContent(Map<String, String> contentValues) throws CmsUgcException { checkNotFinished(); try { CmsFile file = m_cms.readFile(m_editResource); CmsXmlContent content = addContentValues(file, contentValues); CmsXmlContentErrorHandler errorHandler = content.validate(m_cms); if (!errorHandler.hasErrors()) { file.setContents(content.marshal()); // depends on control dependency: [if], data = [none] // the file content might have been modified during the write operation file = m_cms.writeFile(file); // depends on control dependency: [if], data = [none] } return errorHandler; } catch (CmsException e) { LOG.error(e.getLocalizedMessage(), e); throw new CmsUgcException(e, CmsUgcConstants.ErrorCode.errMisc, e.getLocalizedMessage()); } } }
public class class_name { public Instant adjustTime(Instant instant, ZoneId zoneId, boolean roundUp, DayOfWeek firstDayOfWeek) { requireNonNull(instant); requireNonNull(zoneId); requireNonNull(firstDayOfWeek); ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId); if (roundUp) { zonedDateTime = zonedDateTime.plus(getAmount(), getUnit()); } zonedDateTime = Util.truncate(zonedDateTime, getUnit(), getAmount(), firstDayOfWeek); return Instant.from(zonedDateTime); } }
public class class_name { public Instant adjustTime(Instant instant, ZoneId zoneId, boolean roundUp, DayOfWeek firstDayOfWeek) { requireNonNull(instant); requireNonNull(zoneId); requireNonNull(firstDayOfWeek); ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId); if (roundUp) { zonedDateTime = zonedDateTime.plus(getAmount(), getUnit()); // depends on control dependency: [if], data = [none] } zonedDateTime = Util.truncate(zonedDateTime, getUnit(), getAmount(), firstDayOfWeek); return Instant.from(zonedDateTime); } }
public class class_name { public static void postConstructQuietly(Object obj, Logger log) { try { postConstruct(obj, log); } catch( Throwable t ) { log.warn("Could not @PostConstruct object", t); } } }
public class class_name { public static void postConstructQuietly(Object obj, Logger log) { try { postConstruct(obj, log); // depends on control dependency: [try], data = [none] } catch( Throwable t ) { log.warn("Could not @PostConstruct object", t); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public CommerceDiscount fetchByG_C_Last(long groupId, String couponCode, OrderByComparator<CommerceDiscount> orderByComparator) { int count = countByG_C(groupId, couponCode); if (count == 0) { return null; } List<CommerceDiscount> list = findByG_C(groupId, couponCode, count - 1, count, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; } }
public class class_name { @Override public CommerceDiscount fetchByG_C_Last(long groupId, String couponCode, OrderByComparator<CommerceDiscount> orderByComparator) { int count = countByG_C(groupId, couponCode); if (count == 0) { return null; // depends on control dependency: [if], data = [none] } List<CommerceDiscount> list = findByG_C(groupId, couponCode, count - 1, count, orderByComparator); if (!list.isEmpty()) { return list.get(0); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { @Override public ITag readTag() { ITag tag = null; if (log.isTraceEnabled()) { log.trace("Read tag - prevFrameSize {} audio: {} video: {}", new Object[] { prevFrameSize, audioCount, videoCount }); } // ensure there are frames before proceeding if (!frames.isEmpty()) { try { lock.acquire(); //log.debug("Read tag"); //empty-out the pre-streaming tags first if (!firstTags.isEmpty()) { //log.debug("Returning pre-tag"); // Return first tags before media data return firstTags.removeFirst(); } //get the current frame MP4Frame frame = frames.get(currentFrame); if (frame != null) { log.debug("Playback #{} {}", currentFrame, frame); int sampleSize = frame.getSize(); int time = (int) Math.round(frame.getTime() * 1000.0); //log.debug("Read tag - dst: {} base: {} time: {}", new Object[]{frameTs, baseTs, time}); long samplePos = frame.getOffset(); //log.debug("Read tag - samplePos {}", samplePos); //determine frame type and packet body padding byte type = frame.getType(); //assume video type int pad = 5; if (type == TYPE_AUDIO) { pad = 2; } //create a byte buffer of the size of the sample ByteBuffer data = ByteBuffer.allocate(sampleSize + pad); try { //prefix is different for keyframes if (type == TYPE_VIDEO) { if (frame.isKeyFrame()) { //log.debug("Writing keyframe prefix"); data.put(PREFIX_VIDEO_KEYFRAME); } else { //log.debug("Writing interframe prefix"); data.put(PREFIX_VIDEO_FRAME); } // match the sample with its ctts / mdhd adjustment time int timeOffset = prevVideoTS != -1 ? time - prevVideoTS : 0; data.put((byte) ((timeOffset >>> 16) & 0xff)); data.put((byte) ((timeOffset >>> 8) & 0xff)); data.put((byte) (timeOffset & 0xff)); if (log.isTraceEnabled()) { byte[] prefix = new byte[5]; int p = data.position(); data.position(0); data.get(prefix); data.position(p); log.trace("{}", prefix); } // track video frame count videoCount++; prevVideoTS = time; } else { //log.debug("Writing audio prefix"); data.put(PREFIX_AUDIO_FRAME); // track audio frame count audioCount++; } // do we need to add the mdat offset to the sample position? dataSource.position(samplePos); // read from the channel dataSource.read(data); } catch (IOException e) { log.error("Error on channel position / read", e); } // chunk the data IoBuffer payload = IoBuffer.wrap(data.array()); // create the tag tag = new Tag(type, time, payload.limit(), payload, prevFrameSize); //log.debug("Read tag - type: {} body size: {}", (type == TYPE_AUDIO ? "Audio" : "Video"), tag.getBodySize()); // increment the frame number currentFrame++; // set the frame / tag size prevFrameSize = tag.getBodySize(); } } catch (InterruptedException e) { log.warn("Exception acquiring lock", e); } finally { lock.release(); } } else { log.warn("No frames are available for the requested item"); } //log.debug("Tag: {}", tag); return tag; } }
public class class_name { @Override public ITag readTag() { ITag tag = null; if (log.isTraceEnabled()) { log.trace("Read tag - prevFrameSize {} audio: {} video: {}", new Object[] { prevFrameSize, audioCount, videoCount }); // depends on control dependency: [if], data = [none] } // ensure there are frames before proceeding if (!frames.isEmpty()) { try { lock.acquire(); // depends on control dependency: [try], data = [none] //log.debug("Read tag"); //empty-out the pre-streaming tags first if (!firstTags.isEmpty()) { //log.debug("Returning pre-tag"); // Return first tags before media data return firstTags.removeFirst(); // depends on control dependency: [if], data = [none] } //get the current frame MP4Frame frame = frames.get(currentFrame); if (frame != null) { log.debug("Playback #{} {}", currentFrame, frame); // depends on control dependency: [if], data = [none] int sampleSize = frame.getSize(); int time = (int) Math.round(frame.getTime() * 1000.0); //log.debug("Read tag - dst: {} base: {} time: {}", new Object[]{frameTs, baseTs, time}); long samplePos = frame.getOffset(); //log.debug("Read tag - samplePos {}", samplePos); //determine frame type and packet body padding byte type = frame.getType(); //assume video type int pad = 5; if (type == TYPE_AUDIO) { pad = 2; // depends on control dependency: [if], data = [none] } //create a byte buffer of the size of the sample ByteBuffer data = ByteBuffer.allocate(sampleSize + pad); try { //prefix is different for keyframes if (type == TYPE_VIDEO) { if (frame.isKeyFrame()) { //log.debug("Writing keyframe prefix"); data.put(PREFIX_VIDEO_KEYFRAME); // depends on control dependency: [if], data = [none] } else { //log.debug("Writing interframe prefix"); data.put(PREFIX_VIDEO_FRAME); // depends on control dependency: [if], data = [none] } // match the sample with its ctts / mdhd adjustment time int timeOffset = prevVideoTS != -1 ? time - prevVideoTS : 0; data.put((byte) ((timeOffset >>> 16) & 0xff)); // depends on control dependency: [if], data = [none] data.put((byte) ((timeOffset >>> 8) & 0xff)); // depends on control dependency: [if], data = [none] data.put((byte) (timeOffset & 0xff)); // depends on control dependency: [if], data = [none] if (log.isTraceEnabled()) { byte[] prefix = new byte[5]; int p = data.position(); data.position(0); // depends on control dependency: [if], data = [none] data.get(prefix); // depends on control dependency: [if], data = [none] data.position(p); // depends on control dependency: [if], data = [none] log.trace("{}", prefix); // depends on control dependency: [if], data = [none] } // track video frame count videoCount++; // depends on control dependency: [if], data = [none] prevVideoTS = time; // depends on control dependency: [if], data = [none] } else { //log.debug("Writing audio prefix"); data.put(PREFIX_AUDIO_FRAME); // depends on control dependency: [if], data = [none] // track audio frame count audioCount++; // depends on control dependency: [if], data = [none] } // do we need to add the mdat offset to the sample position? dataSource.position(samplePos); // depends on control dependency: [try], data = [none] // read from the channel dataSource.read(data); // depends on control dependency: [try], data = [none] } catch (IOException e) { log.error("Error on channel position / read", e); } // depends on control dependency: [catch], data = [none] // chunk the data IoBuffer payload = IoBuffer.wrap(data.array()); // create the tag tag = new Tag(type, time, payload.limit(), payload, prevFrameSize); // depends on control dependency: [if], data = [none] //log.debug("Read tag - type: {} body size: {}", (type == TYPE_AUDIO ? "Audio" : "Video"), tag.getBodySize()); // increment the frame number currentFrame++; // depends on control dependency: [if], data = [none] // set the frame / tag size prevFrameSize = tag.getBodySize(); // depends on control dependency: [if], data = [none] } } catch (InterruptedException e) { log.warn("Exception acquiring lock", e); } finally { // depends on control dependency: [catch], data = [none] lock.release(); } } else { log.warn("No frames are available for the requested item"); // depends on control dependency: [if], data = [none] } //log.debug("Tag: {}", tag); return tag; } }
public class class_name { @Override public void setFilterGroup(ExclusionCaptureFilterGroup filterGroup) { super.setFilterGroup(filterGroup); if ((filterGroup != null) && (filterGroup.getCaptureFilterGroupCanonicalizer() != null)) { this.canonicalizer = filterGroup.getCaptureFilterGroupCanonicalizer(); } } }
public class class_name { @Override public void setFilterGroup(ExclusionCaptureFilterGroup filterGroup) { super.setFilterGroup(filterGroup); if ((filterGroup != null) && (filterGroup.getCaptureFilterGroupCanonicalizer() != null)) { this.canonicalizer = filterGroup.getCaptureFilterGroupCanonicalizer(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void checkAllThreads() { // if nothing is plugged in, exit early if (this.monitorPlugin == null) { return; } long currentTime = 0; // lazily initialize current time try { for (Iterator i = this.threads_.values().iterator(); i.hasNext();) { Worker thread = (Worker) i.next(); synchronized (thread) { // d204471 if (thread.getStartTime() > 0) { if (currentTime == 0) { currentTime = System.currentTimeMillis(); } if (!thread.isHung && this.monitorPlugin.checkThread(thread, thread.threadNumber, currentTime - thread.getStartTime())) { // PK25446 thread.isHung = true; } } } } this.lastThreadCheckDidntComplete = false; // D222794 } catch (ConcurrentModificationException e) { // begin D222794 // NOTE: we can pretty much ignore this exception ... if // we occasionally fail on the check, we'll be OK. So // we simply keep track with a flag. If two consecutive // checks fail, then we'll log to FFDC if (this.lastThreadCheckDidntComplete) { // Alex Ffdc.log(e, this, this.getClass().getName(), "1181", this); // // D477704.2 } this.lastThreadCheckDidntComplete = true; } // end D222794 } }
public class class_name { public void checkAllThreads() { // if nothing is plugged in, exit early if (this.monitorPlugin == null) { return; // depends on control dependency: [if], data = [none] } long currentTime = 0; // lazily initialize current time try { for (Iterator i = this.threads_.values().iterator(); i.hasNext();) { Worker thread = (Worker) i.next(); synchronized (thread) { // d204471 // depends on control dependency: [for], data = [none] if (thread.getStartTime() > 0) { if (currentTime == 0) { currentTime = System.currentTimeMillis(); // depends on control dependency: [if], data = [none] } if (!thread.isHung && this.monitorPlugin.checkThread(thread, thread.threadNumber, currentTime - thread.getStartTime())) { // PK25446 thread.isHung = true; // depends on control dependency: [if], data = [none] } } } } this.lastThreadCheckDidntComplete = false; // D222794 // depends on control dependency: [try], data = [none] } catch (ConcurrentModificationException e) { // begin D222794 // NOTE: we can pretty much ignore this exception ... if // we occasionally fail on the check, we'll be OK. So // we simply keep track with a flag. If two consecutive // checks fail, then we'll log to FFDC if (this.lastThreadCheckDidntComplete) { // Alex Ffdc.log(e, this, this.getClass().getName(), "1181", this); // // D477704.2 } this.lastThreadCheckDidntComplete = true; } // end D222794 // depends on control dependency: [catch], data = [none] } }
public class class_name { public void cleanup() { state = null; if (headerBuffer != null) { bufferPool.deallocate(headerBuffer); } if (dataBuffer != null) { bufferPool.deallocate(dataBuffer); } } }
public class class_name { public void cleanup() { state = null; if (headerBuffer != null) { bufferPool.deallocate(headerBuffer); // depends on control dependency: [if], data = [(headerBuffer] } if (dataBuffer != null) { bufferPool.deallocate(dataBuffer); // depends on control dependency: [if], data = [(dataBuffer] } } }
public class class_name { @Override public Color interpolate(Color a, Color b, float mixing) { float[] compA, compB; // Get components // Don't convert colorSpaces unless necessary if(a.getColorSpace().equals(colorSpace) ) { compA = a.getComponents(null); } else { compA = a.getComponents(colorSpace, null); } if(b.getColorSpace().equals(colorSpace)) { compB = b.getComponents(null); } else { compB = b.getComponents(colorSpace, null); } float[] compMixed = new float[compA.length]; for(int i=0;i<compA.length;i++){ //Normalizing to [0,1] after the interpolation, // INNER means between a and b // OUTER means between max(a,b) and min(a,b)+1 // UPPER means between a and b' s.t. b'>a and b' in {b, b+1} // LOWER means between a and b' s.t. b'<a and b' in {b, b-1} float left, right; left = compA[i]; //Alpha uses INNER direction InterpolationDirection dir = i<interpolationDirection.length ? interpolationDirection[i] : InterpolationDirection.INNER; switch(dir) { case INNER: right = compB[i]; break; case OUTER: if(compA[i]<compB[i]) { right = compB[i]-1; } else { right = compB[i]+1; } break; case UPPER: if(compA[i]<compB[i]) { right = compB[i]; } else { right = compB[i]+1; } break; case LOWER: if(compA[i]<compB[i]) { right = compB[i]-1; } else { right = compB[i]; } break; default: throw new IllegalStateException("Unkown interpolation Direction "+interpolationDirection[i]); } //Perform mixing compMixed[i] = mixing*left + (1-mixing)*right; if(dir != InterpolationDirection.INNER) { //Normalize to [0,1] if(compMixed[i] < 0) compMixed[i] += 1f; if(compMixed[i] > 1) compMixed[i] -= 1f; } } return new Color(colorSpace,compMixed,compMixed[compMixed.length-1]); } }
public class class_name { @Override public Color interpolate(Color a, Color b, float mixing) { float[] compA, compB; // Get components // Don't convert colorSpaces unless necessary if(a.getColorSpace().equals(colorSpace) ) { compA = a.getComponents(null); // depends on control dependency: [if], data = [none] } else { compA = a.getComponents(colorSpace, null); // depends on control dependency: [if], data = [none] } if(b.getColorSpace().equals(colorSpace)) { compB = b.getComponents(null); // depends on control dependency: [if], data = [none] } else { compB = b.getComponents(colorSpace, null); // depends on control dependency: [if], data = [none] } float[] compMixed = new float[compA.length]; for(int i=0;i<compA.length;i++){ //Normalizing to [0,1] after the interpolation, // INNER means between a and b // OUTER means between max(a,b) and min(a,b)+1 // UPPER means between a and b' s.t. b'>a and b' in {b, b+1} // LOWER means between a and b' s.t. b'<a and b' in {b, b-1} float left, right; left = compA[i]; // depends on control dependency: [for], data = [i] //Alpha uses INNER direction InterpolationDirection dir = i<interpolationDirection.length ? interpolationDirection[i] : InterpolationDirection.INNER; switch(dir) { case INNER: right = compB[i]; break; case OUTER: if(compA[i]<compB[i]) { right = compB[i]-1; // depends on control dependency: [if], data = [none] } else { right = compB[i]+1; // depends on control dependency: [if], data = [none] } break; case UPPER: if(compA[i]<compB[i]) { right = compB[i]; // depends on control dependency: [if], data = [none] } else { right = compB[i]+1; // depends on control dependency: [if], data = [none] } break; case LOWER: if(compA[i]<compB[i]) { right = compB[i]-1; // depends on control dependency: [if], data = [none] } else { right = compB[i]; // depends on control dependency: [if], data = [none] } break; default: throw new IllegalStateException("Unkown interpolation Direction "+interpolationDirection[i]); } //Perform mixing compMixed[i] = mixing*left + (1-mixing)*right; // depends on control dependency: [for], data = [i] if(dir != InterpolationDirection.INNER) { //Normalize to [0,1] if(compMixed[i] < 0) compMixed[i] += 1f; if(compMixed[i] > 1) compMixed[i] -= 1f; } } return new Color(colorSpace,compMixed,compMixed[compMixed.length-1]); } }
public class class_name { private ImmutableMap<Integer, Grib2Parameter> readTable(String path) throws IOException { ImmutableMap.Builder<Integer, Grib2Parameter> builder = ImmutableMap.builder(); if (debugOpen) { System.out.printf("readEcmwfTable path= %s%n", path); } ClassLoader cl = Grib2TableConfig.class.getClassLoader(); try (InputStream is = cl.getResourceAsStream(path)) { if (is == null) { throw new IllegalStateException("Cant find " + path); } try (BufferedReader dataIS = new BufferedReader( new InputStreamReader(is, Charset.forName("UTF8")))) { int count = 0; while (true) { String line = dataIS.readLine(); if (line == null) { break; } if (line.startsWith("#") || line.trim().length() == 0) { continue; } count++; int posBlank1 = line.indexOf(' '); int posBlank2 = line.indexOf(' ', posBlank1 + 1); int lastParen = line.lastIndexOf('('); String num1 = line.substring(0, posBlank1).trim(); String num2 = line.substring(posBlank1 + 1, posBlank2); String desc = (lastParen > 0) ? line.substring(posBlank2 + 1, lastParen).trim() : line.substring(posBlank2 + 1).trim(); String units = (lastParen > 0) ? line.substring(lastParen).trim() : ""; if (units.startsWith("(") & units.endsWith(")")) units = units.substring(1, units.length()-1); if (!num1.equals(num2)) { if (debug) { System.out.printf("*****num1 != num2 for %s%n", line); } continue; } int number = Integer.parseInt(num1); // public Grib2Parameter(int discipline, int category, int number, String name, String unit, String abbrev) { Grib2Parameter parameter = new Grib2Parameter(discipline, category, number, desc, units, null, desc); builder.put(parameter.getNumber(), parameter); if (debug) { System.out.printf(" %s%n", parameter); } } } } return builder.build(); } }
public class class_name { private ImmutableMap<Integer, Grib2Parameter> readTable(String path) throws IOException { ImmutableMap.Builder<Integer, Grib2Parameter> builder = ImmutableMap.builder(); if (debugOpen) { System.out.printf("readEcmwfTable path= %s%n", path); } ClassLoader cl = Grib2TableConfig.class.getClassLoader(); try (InputStream is = cl.getResourceAsStream(path)) { if (is == null) { throw new IllegalStateException("Cant find " + path); } try (BufferedReader dataIS = new BufferedReader( new InputStreamReader(is, Charset.forName("UTF8")))) { int count = 0; while (true) { String line = dataIS.readLine(); if (line == null) { break; } if (line.startsWith("#") || line.trim().length() == 0) { continue; } count++; // depends on control dependency: [while], data = [none] int posBlank1 = line.indexOf(' '); int posBlank2 = line.indexOf(' ', posBlank1 + 1); int lastParen = line.lastIndexOf('('); String num1 = line.substring(0, posBlank1).trim(); String num2 = line.substring(posBlank1 + 1, posBlank2); String desc = (lastParen > 0) ? line.substring(posBlank2 + 1, lastParen).trim() : line.substring(posBlank2 + 1).trim(); String units = (lastParen > 0) ? line.substring(lastParen).trim() : ""; if (units.startsWith("(") & units.endsWith(")")) units = units.substring(1, units.length()-1); if (!num1.equals(num2)) { if (debug) { System.out.printf("*****num1 != num2 for %s%n", line); // depends on control dependency: [if], data = [none] } continue; } int number = Integer.parseInt(num1); // public Grib2Parameter(int discipline, int category, int number, String name, String unit, String abbrev) { Grib2Parameter parameter = new Grib2Parameter(discipline, category, number, desc, units, null, desc); builder.put(parameter.getNumber(), parameter); // depends on control dependency: [while], data = [none] if (debug) { System.out.printf(" %s%n", parameter); // depends on control dependency: [if], data = [none] } } } } return builder.build(); } }
public class class_name { @Override public DefaultJsonWriter value( JavaScriptObject value ) { if (value == null) { return nullValue(); } writeDeferredName(); beforeValue(false); out.append(stringify( value )); return this; } }
public class class_name { @Override public DefaultJsonWriter value( JavaScriptObject value ) { if (value == null) { return nullValue(); // depends on control dependency: [if], data = [none] } writeDeferredName(); beforeValue(false); out.append(stringify( value )); return this; } }
public class class_name { public void expectRegex(String name, Pattern pattern, String message) { String value = Optional.ofNullable(get(name)).orElse(""); if (!pattern.matcher(value).matches()) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.REGEX_KEY.name(), name))); } } }
public class class_name { public void expectRegex(String name, Pattern pattern, String message) { String value = Optional.ofNullable(get(name)).orElse(""); if (!pattern.matcher(value).matches()) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.REGEX_KEY.name(), name))); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void installLayout(JRootPane root) { if (layoutManager == null) { layoutManager = createLayoutManager(); } savedOldLayout = root.getLayout(); root.setLayout(layoutManager); } }
public class class_name { private void installLayout(JRootPane root) { if (layoutManager == null) { layoutManager = createLayoutManager(); // depends on control dependency: [if], data = [none] } savedOldLayout = root.getLayout(); root.setLayout(layoutManager); } }
public class class_name { static String wildcardTypeToString(DocEnv env, Type.WildcardType wildThing, boolean full) { if (env.legacyDoclet) { return TypeMaker.getTypeName(env.types.erasure(wildThing), full); } StringBuilder s = new StringBuilder("?"); List<Type> bounds = getExtendsBounds(wildThing); if (bounds.nonEmpty()) { s.append(" extends "); } else { bounds = getSuperBounds(wildThing); if (bounds.nonEmpty()) { s.append(" super "); } } boolean first = true; // currently only one bound is allowed for (Type b : bounds) { if (!first) { s.append(" & "); } s.append(TypeMaker.getTypeString(env, b, full)); first = false; } return s.toString(); } }
public class class_name { static String wildcardTypeToString(DocEnv env, Type.WildcardType wildThing, boolean full) { if (env.legacyDoclet) { return TypeMaker.getTypeName(env.types.erasure(wildThing), full); // depends on control dependency: [if], data = [none] } StringBuilder s = new StringBuilder("?"); List<Type> bounds = getExtendsBounds(wildThing); if (bounds.nonEmpty()) { s.append(" extends "); // depends on control dependency: [if], data = [none] } else { bounds = getSuperBounds(wildThing); // depends on control dependency: [if], data = [none] if (bounds.nonEmpty()) { s.append(" super "); // depends on control dependency: [if], data = [none] } } boolean first = true; // currently only one bound is allowed for (Type b : bounds) { if (!first) { s.append(" & "); // depends on control dependency: [if], data = [none] } s.append(TypeMaker.getTypeString(env, b, full)); // depends on control dependency: [for], data = [b] first = false; // depends on control dependency: [for], data = [none] } return s.toString(); } }
public class class_name { public static List<Referenceable> createProcessEntity(org.apache.falcon.entity.v0.process.Process process, ConfigurationStore falconStore) throws Exception { LOG.info("Creating process Entity : {}", process.getName()); // The requirement is for each cluster, create a process entity with name // clustername.processname List<Referenceable> entities = new ArrayList<>(); if (process.getClusters() != null) { for (Cluster processCluster : process.getClusters().getClusters()) { org.apache.falcon.entity.v0.cluster.Cluster cluster = falconStore.get(EntityType.CLUSTER, processCluster.getName()); Referenceable clusterReferenceable = getClusterEntityReference(cluster.getName(), cluster.getColo()); entities.add(clusterReferenceable); List<Referenceable> inputs = new ArrayList<>(); if (process.getInputs() != null) { for (Input input : process.getInputs().getInputs()) { Feed feed = falconStore.get(EntityType.FEED, input.getFeed()); Referenceable inputReferenceable = getFeedDataSetReference(feed, clusterReferenceable); entities.add(inputReferenceable); inputs.add(inputReferenceable); } } List<Referenceable> outputs = new ArrayList<>(); if (process.getOutputs() != null) { for (Output output : process.getOutputs().getOutputs()) { Feed feed = falconStore.get(EntityType.FEED, output.getFeed()); Referenceable outputReferenceable = getFeedDataSetReference(feed, clusterReferenceable); entities.add(outputReferenceable); outputs.add(outputReferenceable); } } if (!inputs.isEmpty() || !outputs.isEmpty()) { Referenceable processEntity = new Referenceable(FalconDataTypes.FALCON_PROCESS.getName()); processEntity.set(AtlasClient.NAME, process.getName()); processEntity.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, getProcessQualifiedName(process.getName(), cluster.getName())); processEntity.set(FalconBridge.FREQUENCY, process.getFrequency().toString()); if (!inputs.isEmpty()) { processEntity.set(AtlasClient.PROCESS_ATTRIBUTE_INPUTS, inputs); } if (!outputs.isEmpty()) { processEntity.set(AtlasClient.PROCESS_ATTRIBUTE_OUTPUTS, outputs); } // set cluster processEntity.set(FalconBridge.RUNSON, clusterReferenceable); // Set user if (process.getACL() != null) { processEntity.set(AtlasClient.OWNER, process.getACL().getOwner()); } if (StringUtils.isNotEmpty(process.getTags())) { processEntity.set(FalconBridge.TAGS, EventUtil.convertKeyValueStringToMap(process.getTags())); } if (process.getPipelines() != null) { processEntity.set(FalconBridge.PIPELINES, process.getPipelines()); } processEntity.set(FalconBridge.WFPROPERTIES, getProcessEntityWFProperties(process.getWorkflow(), process.getName())); entities.add(processEntity); } } } return entities; } }
public class class_name { public static List<Referenceable> createProcessEntity(org.apache.falcon.entity.v0.process.Process process, ConfigurationStore falconStore) throws Exception { LOG.info("Creating process Entity : {}", process.getName()); // The requirement is for each cluster, create a process entity with name // clustername.processname List<Referenceable> entities = new ArrayList<>(); if (process.getClusters() != null) { for (Cluster processCluster : process.getClusters().getClusters()) { org.apache.falcon.entity.v0.cluster.Cluster cluster = falconStore.get(EntityType.CLUSTER, processCluster.getName()); Referenceable clusterReferenceable = getClusterEntityReference(cluster.getName(), cluster.getColo()); entities.add(clusterReferenceable); List<Referenceable> inputs = new ArrayList<>(); if (process.getInputs() != null) { for (Input input : process.getInputs().getInputs()) { Feed feed = falconStore.get(EntityType.FEED, input.getFeed()); Referenceable inputReferenceable = getFeedDataSetReference(feed, clusterReferenceable); entities.add(inputReferenceable); // depends on control dependency: [for], data = [input] inputs.add(inputReferenceable); // depends on control dependency: [for], data = [input] } } List<Referenceable> outputs = new ArrayList<>(); if (process.getOutputs() != null) { for (Output output : process.getOutputs().getOutputs()) { Feed feed = falconStore.get(EntityType.FEED, output.getFeed()); Referenceable outputReferenceable = getFeedDataSetReference(feed, clusterReferenceable); entities.add(outputReferenceable); // depends on control dependency: [for], data = [output] outputs.add(outputReferenceable); // depends on control dependency: [for], data = [output] } } if (!inputs.isEmpty() || !outputs.isEmpty()) { Referenceable processEntity = new Referenceable(FalconDataTypes.FALCON_PROCESS.getName()); processEntity.set(AtlasClient.NAME, process.getName()); // depends on control dependency: [if], data = [none] processEntity.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, getProcessQualifiedName(process.getName(), cluster.getName())); // depends on control dependency: [if], data = [none] processEntity.set(FalconBridge.FREQUENCY, process.getFrequency().toString()); // depends on control dependency: [if], data = [none] if (!inputs.isEmpty()) { processEntity.set(AtlasClient.PROCESS_ATTRIBUTE_INPUTS, inputs); // depends on control dependency: [if], data = [none] } if (!outputs.isEmpty()) { processEntity.set(AtlasClient.PROCESS_ATTRIBUTE_OUTPUTS, outputs); // depends on control dependency: [if], data = [none] } // set cluster processEntity.set(FalconBridge.RUNSON, clusterReferenceable); // depends on control dependency: [if], data = [none] // Set user if (process.getACL() != null) { processEntity.set(AtlasClient.OWNER, process.getACL().getOwner()); // depends on control dependency: [if], data = [none] } if (StringUtils.isNotEmpty(process.getTags())) { processEntity.set(FalconBridge.TAGS, EventUtil.convertKeyValueStringToMap(process.getTags())); // depends on control dependency: [if], data = [none] } if (process.getPipelines() != null) { processEntity.set(FalconBridge.PIPELINES, process.getPipelines()); // depends on control dependency: [if], data = [none] } processEntity.set(FalconBridge.WFPROPERTIES, getProcessEntityWFProperties(process.getWorkflow(), process.getName())); // depends on control dependency: [if], data = [none] entities.add(processEntity); // depends on control dependency: [if], data = [none] } } } return entities; } }
public class class_name { public ListCommandsRequest withFilters(CommandFilter... filters) { if (this.filters == null) { setFilters(new com.amazonaws.internal.SdkInternalList<CommandFilter>(filters.length)); } for (CommandFilter ele : filters) { this.filters.add(ele); } return this; } }
public class class_name { public ListCommandsRequest withFilters(CommandFilter... filters) { if (this.filters == null) { setFilters(new com.amazonaws.internal.SdkInternalList<CommandFilter>(filters.length)); // depends on control dependency: [if], data = [none] } for (CommandFilter ele : filters) { this.filters.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { @Override public final QueryResult execute(String queryId, LogicalWorkflow workflow) throws ConnectorException { QueryResult result = null; Long time = null; try { for (LogicalStep project : workflow.getInitialSteps()) { ClusterName clusterName = ((Project) project).getClusterName(); connectionHandler.startJob(clusterName.getName()); } if (logger.isDebugEnabled()) { logger.debug("Executing [" + workflow.toString() + "]"); } time = System.currentTimeMillis(); result = executeWorkFlow(workflow); if (logger.isDebugEnabled()) { logger.debug( "The query has finished. The result form the query [" + workflow.toString() + "] has returned " + "[" + result .getResultSet() .size() + "] rows"); } } finally { for (LogicalStep project : workflow.getInitialSteps()) { connectionHandler.endJob(((Project) project).getClusterName().getName()); } if (time != null) { logger.info("TIME - The execute time has been [" + (System.currentTimeMillis() - time) + "]"); } } return result; } }
public class class_name { @Override public final QueryResult execute(String queryId, LogicalWorkflow workflow) throws ConnectorException { QueryResult result = null; Long time = null; try { for (LogicalStep project : workflow.getInitialSteps()) { ClusterName clusterName = ((Project) project).getClusterName(); connectionHandler.startJob(clusterName.getName()); // depends on control dependency: [for], data = [none] } if (logger.isDebugEnabled()) { logger.debug("Executing [" + workflow.toString() + "]"); // depends on control dependency: [if], data = [none] } time = System.currentTimeMillis(); result = executeWorkFlow(workflow); if (logger.isDebugEnabled()) { logger.debug( "The query has finished. The result form the query [" + workflow.toString() + "] has returned " + "[" + result .getResultSet() .size() + "] rows"); // depends on control dependency: [if], data = [none] } } finally { for (LogicalStep project : workflow.getInitialSteps()) { connectionHandler.endJob(((Project) project).getClusterName().getName()); // depends on control dependency: [for], data = [project] } if (time != null) { logger.info("TIME - The execute time has been [" + (System.currentTimeMillis() - time) + "]"); // depends on control dependency: [if], data = [none] } } return result; } }
public class class_name { public static void saveMinifiedSchema(final LmlParser parser, final Appendable appendable) { try { new Dtd().setAppendComments(false).getDtdSchema(parser, appendable); } catch (final IOException exception) { throw new GdxRuntimeException("Unable to append to file.", exception); } } }
public class class_name { public static void saveMinifiedSchema(final LmlParser parser, final Appendable appendable) { try { new Dtd().setAppendComments(false).getDtdSchema(parser, appendable); // depends on control dependency: [try], data = [none] } catch (final IOException exception) { throw new GdxRuntimeException("Unable to append to file.", exception); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private MethodRefActive createMethodRefActive(ServiceRefAmp serviceRef) { MethodRefAmp methodRef; if (_type != null) { methodRef = serviceRef.methodByName(_name, _type); } else { methodRef = serviceRef.methodByName(_name); } MethodShim methodShim; ClassLoader methodLoader = methodRef.serviceRef().classLoader(); //System.out.println("SR: " + serviceRef + " " + serviceRef.getActor()); if (methodLoader == _sourceLoader || serviceRef.stub() instanceof StubLink) { //methodShim = new MethodShimIdentity(methodRef.getMethod()); methodShim = new MethodShimIdentity(methodRef, isLocalService(serviceRef)); } else { PodImport importContext; importContext = PodImportContext.create(_sourceLoader).getPodImport(methodLoader); //importContext = ImportContext.create(methodLoader).getModuleImport(_sourceLoader); //methodShim = new MethodShimImport(methodRef.getMethod(), importContext); methodShim = new MethodShimImport(methodRef, importContext, isLocalService(serviceRef)); } return new MethodRefActive(serviceRef, methodRef, methodShim); } }
public class class_name { private MethodRefActive createMethodRefActive(ServiceRefAmp serviceRef) { MethodRefAmp methodRef; if (_type != null) { methodRef = serviceRef.methodByName(_name, _type); // depends on control dependency: [if], data = [none] } else { methodRef = serviceRef.methodByName(_name); // depends on control dependency: [if], data = [none] } MethodShim methodShim; ClassLoader methodLoader = methodRef.serviceRef().classLoader(); //System.out.println("SR: " + serviceRef + " " + serviceRef.getActor()); if (methodLoader == _sourceLoader || serviceRef.stub() instanceof StubLink) { //methodShim = new MethodShimIdentity(methodRef.getMethod()); methodShim = new MethodShimIdentity(methodRef, isLocalService(serviceRef)); // depends on control dependency: [if], data = [none] } else { PodImport importContext; importContext = PodImportContext.create(_sourceLoader).getPodImport(methodLoader); // depends on control dependency: [if], data = [(methodLoader] //importContext = ImportContext.create(methodLoader).getModuleImport(_sourceLoader); //methodShim = new MethodShimImport(methodRef.getMethod(), importContext); methodShim = new MethodShimImport(methodRef, importContext, isLocalService(serviceRef)); // depends on control dependency: [if], data = [none] } return new MethodRefActive(serviceRef, methodRef, methodShim); } }
public class class_name { protected List<HistoryReference> getSelectedHistoryReferences(HttpMessageContainer httpMessageContainer) { if (httpMessageContainer instanceof SelectableHistoryReferencesContainer) { return ((SelectableHistoryReferencesContainer) httpMessageContainer).getSelectedHistoryReferences(); } else if (httpMessageContainer instanceof SingleHistoryReferenceContainer) { SingleHistoryReferenceContainer singleContainer = (SingleHistoryReferenceContainer) httpMessageContainer; if (!singleContainer.isEmpty()) { List<HistoryReference> selectedHistoryReferences = new ArrayList<>(1); selectedHistoryReferences.add(singleContainer.getHistoryReference()); return selectedHistoryReferences; } } return Collections.emptyList(); } }
public class class_name { protected List<HistoryReference> getSelectedHistoryReferences(HttpMessageContainer httpMessageContainer) { if (httpMessageContainer instanceof SelectableHistoryReferencesContainer) { return ((SelectableHistoryReferencesContainer) httpMessageContainer).getSelectedHistoryReferences(); // depends on control dependency: [if], data = [none] } else if (httpMessageContainer instanceof SingleHistoryReferenceContainer) { SingleHistoryReferenceContainer singleContainer = (SingleHistoryReferenceContainer) httpMessageContainer; if (!singleContainer.isEmpty()) { List<HistoryReference> selectedHistoryReferences = new ArrayList<>(1); selectedHistoryReferences.add(singleContainer.getHistoryReference()); // depends on control dependency: [if], data = [none] return selectedHistoryReferences; // depends on control dependency: [if], data = [none] } } return Collections.emptyList(); } }
public class class_name { private Optional<String> getContentVersions(String currentUrl, Collection<SerializationFormat> formats, ArrayList<String> redirects){ Optional<SerializationFormat> test = formats.stream().filter(x -> currentUrl.trim().endsWith(x.getExtension())).findFirst(); if(currentUrl != null && ! test.isPresent()){ for(SerializationFormat format : formats) { String tryOwl = StringUtils.replacePattern(currentUrl, "#$", ""); tryOwl = StringUtils.replacePattern(tryOwl, "/$", ""); tryOwl = StringUtils.replacePattern(tryOwl, "\\.html$", ""); tryOwl = StringUtils.replacePattern(tryOwl, "\\.htm$", ""); Optional<String> res = getContentLocation(tryOwl + "." + format.getExtension(), format, redirects); if (res.isPresent()) return res; res = getContentLocation(tryOwl + "/ontology." + format.getExtension(), format, redirects); if (res.isPresent()) return res; res = getContentLocation(tryOwl + "/schema." + format.getExtension(), format, redirects); if (res.isPresent()) return res; } } return Optional.empty(); } }
public class class_name { private Optional<String> getContentVersions(String currentUrl, Collection<SerializationFormat> formats, ArrayList<String> redirects){ Optional<SerializationFormat> test = formats.stream().filter(x -> currentUrl.trim().endsWith(x.getExtension())).findFirst(); if(currentUrl != null && ! test.isPresent()){ for(SerializationFormat format : formats) { String tryOwl = StringUtils.replacePattern(currentUrl, "#$", ""); tryOwl = StringUtils.replacePattern(tryOwl, "/$", ""); // depends on control dependency: [for], data = [none] tryOwl = StringUtils.replacePattern(tryOwl, "\\.html$", ""); // depends on control dependency: [for], data = [none] tryOwl = StringUtils.replacePattern(tryOwl, "\\.htm$", ""); // depends on control dependency: [for], data = [none] Optional<String> res = getContentLocation(tryOwl + "." + format.getExtension(), format, redirects); if (res.isPresent()) return res; res = getContentLocation(tryOwl + "/ontology." + format.getExtension(), format, redirects); // depends on control dependency: [for], data = [format] if (res.isPresent()) return res; res = getContentLocation(tryOwl + "/schema." + format.getExtension(), format, redirects); // depends on control dependency: [for], data = [format] if (res.isPresent()) return res; } } return Optional.empty(); } }
public class class_name { public void marshall(ElasticsearchRetryOptions elasticsearchRetryOptions, ProtocolMarshaller protocolMarshaller) { if (elasticsearchRetryOptions == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(elasticsearchRetryOptions.getDurationInSeconds(), DURATIONINSECONDS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ElasticsearchRetryOptions elasticsearchRetryOptions, ProtocolMarshaller protocolMarshaller) { if (elasticsearchRetryOptions == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(elasticsearchRetryOptions.getDurationInSeconds(), DURATIONINSECONDS_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 StorageService verifyStorageServiceOption(ApplicationDefinition currAppDef, ApplicationDefinition appDef) { // Verify or assign StorageService String ssName = getStorageServiceOption(appDef); StorageService storageService = getStorageService(appDef); Utils.require(storageService != null, "StorageService is unknown or hasn't been initialized: %s", ssName); // Currently, StorageService can't be changed. if (currAppDef != null) { String currSSName = getStorageServiceOption(currAppDef); Utils.require(currSSName.equals(ssName), "'StorageService' cannot be changed for application: %s", appDef.getAppName()); } return storageService; } }
public class class_name { private StorageService verifyStorageServiceOption(ApplicationDefinition currAppDef, ApplicationDefinition appDef) { // Verify or assign StorageService String ssName = getStorageServiceOption(appDef); StorageService storageService = getStorageService(appDef); Utils.require(storageService != null, "StorageService is unknown or hasn't been initialized: %s", ssName); // Currently, StorageService can't be changed. if (currAppDef != null) { String currSSName = getStorageServiceOption(currAppDef); Utils.require(currSSName.equals(ssName), "'StorageService' cannot be changed for application: %s", appDef.getAppName()); // depends on control dependency: [if], data = [none] } return storageService; } }
public class class_name { protected OutputStream getAsynchronousOutputStream( final OutputStream outputStream) throws IOException { final int SIZE = 1024 * 1024 * 10; final PipedOutputStream pos = new PipedOutputStream(); final PipedInputStream pis = new PipedInputStream(pos, SIZE); final FinishableRunnable run = new FinishableRunnable() { volatile boolean finish = false; volatile boolean hasFinished = false; @Override public void finish() { this.finish = true; while (!this.hasFinished) { // loop until thread is really finished } } @Override public void run() { try { byte[] bytes = new byte[SIZE]; // Note that we finish really gently here, writing all data // that is still in the input first (in theory, new data // could arrive asynchronously, so that the thread never // finishes, but this is not the intended mode of // operation). for (int len; (!this.finish || pis.available() > 0) && (len = pis.read(bytes)) > 0;) { outputStream.write(bytes, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { close(pis); close(outputStream); this.hasFinished = true; } } }; new Thread(run, "async-output-stream").start(); this.outputStreams.add(new Closeable() { @Override public void close() throws IOException { run.finish(); } }); return pos; } }
public class class_name { protected OutputStream getAsynchronousOutputStream( final OutputStream outputStream) throws IOException { final int SIZE = 1024 * 1024 * 10; final PipedOutputStream pos = new PipedOutputStream(); final PipedInputStream pis = new PipedInputStream(pos, SIZE); final FinishableRunnable run = new FinishableRunnable() { volatile boolean finish = false; volatile boolean hasFinished = false; @Override public void finish() { this.finish = true; while (!this.hasFinished) { // loop until thread is really finished } } @Override public void run() { try { byte[] bytes = new byte[SIZE]; // Note that we finish really gently here, writing all data // that is still in the input first (in theory, new data // could arrive asynchronously, so that the thread never // finishes, but this is not the intended mode of // operation). for (int len; (!this.finish || pis.available() > 0) && (len = pis.read(bytes)) > 0;) { outputStream.write(bytes, 0, len); // depends on control dependency: [for], data = [none] } } catch (IOException e) { e.printStackTrace(); } finally { // depends on control dependency: [catch], data = [none] close(pis); close(outputStream); this.hasFinished = true; } } }; new Thread(run, "async-output-stream").start(); this.outputStreams.add(new Closeable() { @Override public void close() throws IOException { run.finish(); } }); return pos; } }
public class class_name { public static Type getReturnType(final String methodDescriptor) { // Skip the first character, which is always a '('. int currentOffset = 1; // Skip the argument types, one at a each loop iteration. while (methodDescriptor.charAt(currentOffset) != ')') { while (methodDescriptor.charAt(currentOffset) == '[') { currentOffset++; } if (methodDescriptor.charAt(currentOffset++) == 'L') { // Skip the argument descriptor content. currentOffset = methodDescriptor.indexOf(';', currentOffset) + 1; } } return getTypeInternal(methodDescriptor, currentOffset + 1, methodDescriptor.length()); } }
public class class_name { public static Type getReturnType(final String methodDescriptor) { // Skip the first character, which is always a '('. int currentOffset = 1; // Skip the argument types, one at a each loop iteration. while (methodDescriptor.charAt(currentOffset) != ')') { while (methodDescriptor.charAt(currentOffset) == '[') { currentOffset++; // depends on control dependency: [while], data = [none] } if (methodDescriptor.charAt(currentOffset++) == 'L') { // Skip the argument descriptor content. currentOffset = methodDescriptor.indexOf(';', currentOffset) + 1; // depends on control dependency: [if], data = [none] } } return getTypeInternal(methodDescriptor, currentOffset + 1, methodDescriptor.length()); } }
public class class_name { public void setStop(final double STOP) { if (null == stop) { _stop = STOP; fireSectionEvent(UPDATE_EVENT); } else { stop.set(STOP); } } }
public class class_name { public void setStop(final double STOP) { if (null == stop) { _stop = STOP; // depends on control dependency: [if], data = [none] fireSectionEvent(UPDATE_EVENT); // depends on control dependency: [if], data = [none] } else { stop.set(STOP); // depends on control dependency: [if], data = [none] } } }
public class class_name { private boolean handleWrapping(MouseEvent e) { if (robot == null) { return false; } PointerInfo pointerInfo = null; try { pointerInfo = MouseInfo.getPointerInfo(); } catch (SecurityException ex) { return false; } Rectangle r = pointerInfo.getDevice().getDefaultConfiguration().getBounds(); Point onScreen = pointerInfo.getLocation(); if (onScreen.y == 0) { robot.mouseMove(onScreen.x, r.height-2); previousPoint = new Point(onScreen.x, r.height-2); SwingUtilities.convertPointFromScreen(previousPoint, spinner); return true; } else if (onScreen.y == r.height - 1) { robot.mouseMove(onScreen.x, 1); previousPoint = new Point(onScreen.x, 1); SwingUtilities.convertPointFromScreen(previousPoint, spinner); return true; } return false; } }
public class class_name { private boolean handleWrapping(MouseEvent e) { if (robot == null) { return false; // depends on control dependency: [if], data = [none] } PointerInfo pointerInfo = null; try { pointerInfo = MouseInfo.getPointerInfo(); // depends on control dependency: [try], data = [none] } catch (SecurityException ex) { return false; } // depends on control dependency: [catch], data = [none] Rectangle r = pointerInfo.getDevice().getDefaultConfiguration().getBounds(); Point onScreen = pointerInfo.getLocation(); if (onScreen.y == 0) { robot.mouseMove(onScreen.x, r.height-2); // depends on control dependency: [if], data = [none] previousPoint = new Point(onScreen.x, r.height-2); // depends on control dependency: [if], data = [none] SwingUtilities.convertPointFromScreen(previousPoint, spinner); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } else if (onScreen.y == r.height - 1) { robot.mouseMove(onScreen.x, 1); // depends on control dependency: [if], data = [none] previousPoint = new Point(onScreen.x, 1); // depends on control dependency: [if], data = [none] SwingUtilities.convertPointFromScreen(previousPoint, spinner); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { public void dumpDebugFile() { try { File f = File.createTempFile("elki-debug", ".svg"); f.deleteOnExit(); this.saveAsSVG(f); LoggingUtil.warning("Saved debug file to: " + f.getAbsolutePath()); } catch(Throwable err) { // Ignore. } } }
public class class_name { public void dumpDebugFile() { try { File f = File.createTempFile("elki-debug", ".svg"); f.deleteOnExit(); // depends on control dependency: [try], data = [none] this.saveAsSVG(f); // depends on control dependency: [try], data = [none] LoggingUtil.warning("Saved debug file to: " + f.getAbsolutePath()); // depends on control dependency: [try], data = [none] } catch(Throwable err) { // Ignore. } // depends on control dependency: [catch], data = [none] } }
public class class_name { @PostConstruct protected void postConstruct() throws GeomajasException { if (null == baseTmsUrl) { throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "baseTmsUrl"); } // Make sure we have a base URL we can work with: if ((baseTmsUrl.startsWith("http://") || baseTmsUrl.startsWith("https://")) && !baseTmsUrl.endsWith("/")) { baseTmsUrl += "/"; } // Make sure there is a correct RasterLayerInfo object: if (layerInfo == null || layerInfo == UNUSABLE_LAYER_INFO) { try { tileMap = configurationService.getCapabilities(this); version = tileMap.getVersion(); extension = tileMap.getTileFormat().getExtension(); layerInfo = configurationService.asLayerInfo(tileMap); usable = true; } catch (TmsLayerException e) { // a layer needs an info object to keep the DtoConfigurationPostProcessor happy ! layerInfo = UNUSABLE_LAYER_INFO; usable = false; log.warn("The layer could not be correctly initialized: " + getId(), e); } } else if (extension == null) { throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "extension"); } if (layerInfo != null) { // Finally prepare some often needed values: state = new TileServiceState(geoService, layerInfo); // when proxying the real url will be resolved later on, just use a simple one for now boolean proxying = useCache || useProxy || null != authentication; if (tileMap != null && !proxying) { urlBuilder = new TileMapUrlBuilder(tileMap); } else { urlBuilder = new SimpleTmsUrlBuilder(extension); } } } }
public class class_name { @PostConstruct protected void postConstruct() throws GeomajasException { if (null == baseTmsUrl) { throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "baseTmsUrl"); } // Make sure we have a base URL we can work with: if ((baseTmsUrl.startsWith("http://") || baseTmsUrl.startsWith("https://")) && !baseTmsUrl.endsWith("/")) { baseTmsUrl += "/"; } // Make sure there is a correct RasterLayerInfo object: if (layerInfo == null || layerInfo == UNUSABLE_LAYER_INFO) { try { tileMap = configurationService.getCapabilities(this); // depends on control dependency: [try], data = [none] version = tileMap.getVersion(); // depends on control dependency: [try], data = [none] extension = tileMap.getTileFormat().getExtension(); // depends on control dependency: [try], data = [none] layerInfo = configurationService.asLayerInfo(tileMap); // depends on control dependency: [try], data = [none] usable = true; // depends on control dependency: [try], data = [none] } catch (TmsLayerException e) { // a layer needs an info object to keep the DtoConfigurationPostProcessor happy ! layerInfo = UNUSABLE_LAYER_INFO; usable = false; log.warn("The layer could not be correctly initialized: " + getId(), e); } // depends on control dependency: [catch], data = [none] } else if (extension == null) { throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "extension"); } if (layerInfo != null) { // Finally prepare some often needed values: state = new TileServiceState(geoService, layerInfo); // when proxying the real url will be resolved later on, just use a simple one for now boolean proxying = useCache || useProxy || null != authentication; if (tileMap != null && !proxying) { urlBuilder = new TileMapUrlBuilder(tileMap); } else { urlBuilder = new SimpleTmsUrlBuilder(extension); } } } }
public class class_name { public List<String> introspect() { List<String> rc = new LinkedList<String>(); String prefix = getClass().getSimpleName() + "@" + hashCode() + ": "; rc.add(prefix + "aborted=" + this.aborted); rc.add(prefix + "forceQueue=" + this.forceQueue); rc.add(prefix + "ioAmount=" + this.ioAmount); rc.add(prefix + "ioCompleteAmt=" + this.ioCompleteAmt); rc.add(prefix + "ioDoneAmt=" + this.ioDoneAmt); rc.add(prefix + "lastIOAmt=" + this.lastIOAmt); rc.add(prefix + "isRead=" + this.requestTypeRead); rc.add(prefix + "timeoutInterval=" + this.timeoutInterval); rc.add(prefix + "timeoutTime=" + this.timeoutTime); rc.add(prefix + "link=" + this.oTCPConnLink); if (null != this.oTCPConnLink) { rc.addAll(this.oTCPConnLink.introspect()); } return rc; } }
public class class_name { public List<String> introspect() { List<String> rc = new LinkedList<String>(); String prefix = getClass().getSimpleName() + "@" + hashCode() + ": "; rc.add(prefix + "aborted=" + this.aborted); rc.add(prefix + "forceQueue=" + this.forceQueue); rc.add(prefix + "ioAmount=" + this.ioAmount); rc.add(prefix + "ioCompleteAmt=" + this.ioCompleteAmt); rc.add(prefix + "ioDoneAmt=" + this.ioDoneAmt); rc.add(prefix + "lastIOAmt=" + this.lastIOAmt); rc.add(prefix + "isRead=" + this.requestTypeRead); rc.add(prefix + "timeoutInterval=" + this.timeoutInterval); rc.add(prefix + "timeoutTime=" + this.timeoutTime); rc.add(prefix + "link=" + this.oTCPConnLink); if (null != this.oTCPConnLink) { rc.addAll(this.oTCPConnLink.introspect()); // depends on control dependency: [if], data = [none] } return rc; } }
public class class_name { public static long byteArrayToLongBE( byte[] data ) { if (data == null) return 0x0; long accum = 0; int shiftBy = 8 * data.length - 8; for( byte b : data ) { accum |= (long) (0xff & b) << shiftBy; shiftBy -= 8; } return accum; } }
public class class_name { public static long byteArrayToLongBE( byte[] data ) { if (data == null) return 0x0; long accum = 0; int shiftBy = 8 * data.length - 8; for( byte b : data ) { accum |= (long) (0xff & b) << shiftBy; // depends on control dependency: [for], data = [b] shiftBy -= 8; // depends on control dependency: [for], data = [none] } return accum; } }
public class class_name { private static boolean hasTz( String pattern ) { boolean inQuote = false; for ( int i = 0; i < pattern.length(); i++ ) { char ch = pattern.charAt( i ); // If inside quote, except two quote connected, just copy or exit. if ( inQuote ) { if ( ch == '\'' ) { if ( i + 1 < pattern.length() && pattern.charAt( i + 1 ) == '\'' ) { // Quote appeared twice continuously, interpret as one quote. ++i; } else { inQuote = false; } } continue; } // Outside quote now. if ( "Zzv".indexOf( ch ) >= 0 ) { return true; } // Two consecutive quotes is a quote literal, inside or outside of quotes. if ( ch == '\'' ) { if ( i + 1 < pattern.length() && pattern.charAt( i + 1 ) == '\'' ) { i++; } else { inQuote = true; } } } return false; } }
public class class_name { private static boolean hasTz( String pattern ) { boolean inQuote = false; for ( int i = 0; i < pattern.length(); i++ ) { char ch = pattern.charAt( i ); // If inside quote, except two quote connected, just copy or exit. if ( inQuote ) { if ( ch == '\'' ) { if ( i + 1 < pattern.length() && pattern.charAt( i + 1 ) == '\'' ) { // Quote appeared twice continuously, interpret as one quote. ++i; // depends on control dependency: [if], data = [none] } else { inQuote = false; // depends on control dependency: [if], data = [none] } } continue; } // Outside quote now. if ( "Zzv".indexOf( ch ) >= 0 ) { return true; // depends on control dependency: [if], data = [none] } // Two consecutive quotes is a quote literal, inside or outside of quotes. if ( ch == '\'' ) { if ( i + 1 < pattern.length() && pattern.charAt( i + 1 ) == '\'' ) { i++; // depends on control dependency: [if], data = [none] } else { inQuote = true; // depends on control dependency: [if], data = [none] } } } return false; } }
public class class_name { @Override public void removeByG_E(long groupId, boolean enabled) { for (CommerceNotificationTemplate commerceNotificationTemplate : findByG_E( groupId, enabled, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceNotificationTemplate); } } }
public class class_name { @Override public void removeByG_E(long groupId, boolean enabled) { for (CommerceNotificationTemplate commerceNotificationTemplate : findByG_E( groupId, enabled, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commerceNotificationTemplate); // depends on control dependency: [for], data = [commerceNotificationTemplate] } } }
public class class_name { public void getGroupHistory(final String groupId, final Integer maxMessages, final Date before, final GroupHistoryCompletionListener completionListener) { if (!isConnected()) { getGroupHistoryError(completionListener, "Can't complete request when not connected, " + "Please reconnect!"); return; } if ((maxMessages == null) || (maxMessages < 1)) { getGroupHistoryError(completionListener, "maxMessages must be at least 1"); return; } if ((groupId == null) || groupId.length() == 0) { getGroupHistoryError(completionListener, "groupId cannot be blank"); return; } Uri.Builder builder = new Uri.Builder(); builder.appendQueryParameter("limit", maxMessages.toString()); if (before != null) { builder.appendQueryParameter("before", Long.toString(before.getTime())); } String urlEndpoint = String.format("/v1/groups/%s/history%s", groupId, builder.build().toString()); signalingChannel.sendRESTMessage("get", urlEndpoint, null, new RespokeSignalingChannel.RESTListener() { @Override public void onSuccess(Object response) { if (!(response instanceof JSONArray)) { getGroupHistoryError(completionListener, "Invalid response from server"); return; } final JSONArray json = (JSONArray) response; final ArrayList<RespokeGroupMessage> results = new ArrayList<>(json.length()); try { for (int i = 0; i < json.length(); i++) { final JSONObject jsonMessage = json.getJSONObject(i); final RespokeGroupMessage message = buildGroupMessage(jsonMessage); results.add(message); } } catch (JSONException e) { getGroupHistoryError(completionListener, "Error parsing JSON response"); return; } new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (completionListener != null) { completionListener.onSuccess(results); } } }); } @Override public void onError(final String errorMessage) { getGroupHistoryError(completionListener, errorMessage); } }); } }
public class class_name { public void getGroupHistory(final String groupId, final Integer maxMessages, final Date before, final GroupHistoryCompletionListener completionListener) { if (!isConnected()) { getGroupHistoryError(completionListener, "Can't complete request when not connected, " + "Please reconnect!"); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } if ((maxMessages == null) || (maxMessages < 1)) { getGroupHistoryError(completionListener, "maxMessages must be at least 1"); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } if ((groupId == null) || groupId.length() == 0) { getGroupHistoryError(completionListener, "groupId cannot be blank"); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } Uri.Builder builder = new Uri.Builder(); builder.appendQueryParameter("limit", maxMessages.toString()); if (before != null) { builder.appendQueryParameter("before", Long.toString(before.getTime())); // depends on control dependency: [if], data = [(before] } String urlEndpoint = String.format("/v1/groups/%s/history%s", groupId, builder.build().toString()); signalingChannel.sendRESTMessage("get", urlEndpoint, null, new RespokeSignalingChannel.RESTListener() { @Override public void onSuccess(Object response) { if (!(response instanceof JSONArray)) { getGroupHistoryError(completionListener, "Invalid response from server"); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } final JSONArray json = (JSONArray) response; final ArrayList<RespokeGroupMessage> results = new ArrayList<>(json.length()); try { for (int i = 0; i < json.length(); i++) { final JSONObject jsonMessage = json.getJSONObject(i); final RespokeGroupMessage message = buildGroupMessage(jsonMessage); results.add(message); // depends on control dependency: [for], data = [none] } } catch (JSONException e) { getGroupHistoryError(completionListener, "Error parsing JSON response"); return; } // depends on control dependency: [catch], data = [none] new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (completionListener != null) { completionListener.onSuccess(results); // depends on control dependency: [if], data = [none] } } }); } @Override public void onError(final String errorMessage) { getGroupHistoryError(completionListener, errorMessage); } }); } }
public class class_name { public void marshall(RunCommandTarget runCommandTarget, ProtocolMarshaller protocolMarshaller) { if (runCommandTarget == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(runCommandTarget.getKey(), KEY_BINDING); protocolMarshaller.marshall(runCommandTarget.getValues(), VALUES_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(RunCommandTarget runCommandTarget, ProtocolMarshaller protocolMarshaller) { if (runCommandTarget == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(runCommandTarget.getKey(), KEY_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(runCommandTarget.getValues(), VALUES_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 Future<WriteResponse> write (Batch<String> batch, WriteCallback callback) { Timer.Context context = writeTimer.time(); int returnCode = 0; LOG.info ("Dispatching batch " + batch.getId()); recordsAttempted.mark(batch.getRecords().size()); try { String encoded = encodeBatch(batch); returnCode = request (encoded); WriteResponse<Integer> response = WRITE_RESPONSE_WRAPPER.wrap(returnCode); callback.onSuccess(response); bytesWritten.mark(encoded.length()); recordsSuccess.mark(batch.getRecords().size()); } catch (Exception e) { LOG.error("Dispatching batch " + batch.getId() + " failed :" + e.toString()); callback.onFailure(e); recordsFailed.mark(batch.getRecords().size()); } context.close(); Future<Integer> future = Futures.immediateFuture(returnCode); return new WriteResponseFuture<>(future, WRITE_RESPONSE_WRAPPER); } }
public class class_name { public Future<WriteResponse> write (Batch<String> batch, WriteCallback callback) { Timer.Context context = writeTimer.time(); int returnCode = 0; LOG.info ("Dispatching batch " + batch.getId()); recordsAttempted.mark(batch.getRecords().size()); try { String encoded = encodeBatch(batch); returnCode = request (encoded); // depends on control dependency: [try], data = [none] WriteResponse<Integer> response = WRITE_RESPONSE_WRAPPER.wrap(returnCode); callback.onSuccess(response); // depends on control dependency: [try], data = [none] bytesWritten.mark(encoded.length()); // depends on control dependency: [try], data = [none] recordsSuccess.mark(batch.getRecords().size()); // depends on control dependency: [try], data = [none] } catch (Exception e) { LOG.error("Dispatching batch " + batch.getId() + " failed :" + e.toString()); callback.onFailure(e); recordsFailed.mark(batch.getRecords().size()); } // depends on control dependency: [catch], data = [none] context.close(); Future<Integer> future = Futures.immediateFuture(returnCode); return new WriteResponseFuture<>(future, WRITE_RESPONSE_WRAPPER); } }
public class class_name { @Override public Long ssExpire(byte[] key, byte[] field, long expireSeconds) { try { if (isPipelined()) { pipeline(new JedisResult(pipeline.ssexpire(key, field, expireSeconds))); return null; } return this.client.ssexpire(key, field, expireSeconds); } catch (Exception ex) { throw convertException(ex); } } }
public class class_name { @Override public Long ssExpire(byte[] key, byte[] field, long expireSeconds) { try { if (isPipelined()) { pipeline(new JedisResult(pipeline.ssexpire(key, field, expireSeconds))); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } return this.client.ssexpire(key, field, expireSeconds); // depends on control dependency: [try], data = [none] } catch (Exception ex) { throw convertException(ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public boolean acquireGlobalLock(boolean exclusive, long timeout) { log.tracef("About to acquire global lock. Exclusive? %s", exclusive); boolean success = true; for (int i = 0; i < sharedLocks.length; i++) { Lock toAcquire = exclusive ? sharedLocks[i].writeLock() : sharedLocks[i].readLock(); try { success = toAcquire.tryLock(timeout, TimeUnit.MILLISECONDS); if (!success) { if (trace) log.tracef("Could not acquire lock on %s. Exclusive? %b", toAcquire, exclusive); break; } } catch (InterruptedException e) { if (trace) log.trace("Caught InterruptedException while trying to acquire global lock", e); success = false; Thread.currentThread().interrupt(); } finally { if (!success) { for (int j = 0; j < i; j++) { Lock toRelease = exclusive ? sharedLocks[j].writeLock() : sharedLocks[j].readLock(); toRelease.unlock(); } } } } return success; } }
public class class_name { public boolean acquireGlobalLock(boolean exclusive, long timeout) { log.tracef("About to acquire global lock. Exclusive? %s", exclusive); boolean success = true; for (int i = 0; i < sharedLocks.length; i++) { Lock toAcquire = exclusive ? sharedLocks[i].writeLock() : sharedLocks[i].readLock(); try { success = toAcquire.tryLock(timeout, TimeUnit.MILLISECONDS); // depends on control dependency: [try], data = [none] if (!success) { if (trace) log.tracef("Could not acquire lock on %s. Exclusive? %b", toAcquire, exclusive); break; } } catch (InterruptedException e) { if (trace) log.trace("Caught InterruptedException while trying to acquire global lock", e); success = false; Thread.currentThread().interrupt(); } finally { // depends on control dependency: [catch], data = [none] if (!success) { for (int j = 0; j < i; j++) { Lock toRelease = exclusive ? sharedLocks[j].writeLock() : sharedLocks[j].readLock(); toRelease.unlock(); // depends on control dependency: [for], data = [none] } } } } return success; } }
public class class_name { private synchronized ZNames loadMetaZoneNames(String mzID) { ZNames mznames = _mzNamesMap.get(mzID); if (mznames == null) { ZNamesLoader loader = new ZNamesLoader(); loader.loadMetaZone(_zoneStrings, mzID); mznames = ZNames.createMetaZoneAndPutInCache(_mzNamesMap, loader.getNames(), mzID); } return mznames; } }
public class class_name { private synchronized ZNames loadMetaZoneNames(String mzID) { ZNames mznames = _mzNamesMap.get(mzID); if (mznames == null) { ZNamesLoader loader = new ZNamesLoader(); loader.loadMetaZone(_zoneStrings, mzID); // depends on control dependency: [if], data = [none] mznames = ZNames.createMetaZoneAndPutInCache(_mzNamesMap, loader.getNames(), mzID); // depends on control dependency: [if], data = [none] } return mznames; } }
public class class_name { public static boolean hasField(Connection connection, String tableName, String fieldName) throws SQLException { final Statement statement = connection.createStatement(); try { final ResultSet resultSet = statement.executeQuery( "SELECT * FROM " + TableLocation.parse(tableName) + " LIMIT 0;"); try { return hasField(resultSet.getMetaData(), fieldName); } finally { resultSet.close(); } } catch (SQLException ex) { return false; } finally { statement.close(); } } }
public class class_name { public static boolean hasField(Connection connection, String tableName, String fieldName) throws SQLException { final Statement statement = connection.createStatement(); try { final ResultSet resultSet = statement.executeQuery( "SELECT * FROM " + TableLocation.parse(tableName) + " LIMIT 0;"); try { return hasField(resultSet.getMetaData(), fieldName); // depends on control dependency: [try], data = [none] } finally { resultSet.close(); } } catch (SQLException ex) { return false; } finally { statement.close(); } } }
public class class_name { protected String getSelectedValue(CmsObject cms, I_CmsWidgetParameter param) { String paramValue = param.getStringValue(cms); if (CmsStringUtil.isEmpty(paramValue)) { CmsSelectWidgetOption option = CmsSelectWidgetOption.getDefaultOption(m_selectOptions); if (option != null) { paramValue = option.getValue(); } } return paramValue; } }
public class class_name { protected String getSelectedValue(CmsObject cms, I_CmsWidgetParameter param) { String paramValue = param.getStringValue(cms); if (CmsStringUtil.isEmpty(paramValue)) { CmsSelectWidgetOption option = CmsSelectWidgetOption.getDefaultOption(m_selectOptions); if (option != null) { paramValue = option.getValue(); // depends on control dependency: [if], data = [none] } } return paramValue; } }
public class class_name { public static String toHexString(final BitSet set) { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(out); final long[] longs = set.toLongArray(); for (long aLong : longs) { writer.write(Long.toHexString(aLong)); } writer.flush(); return new String(out.toByteArray(), java.nio.charset.StandardCharsets.UTF_8); } }
public class class_name { public static String toHexString(final BitSet set) { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(out); final long[] longs = set.toLongArray(); for (long aLong : longs) { writer.write(Long.toHexString(aLong)); // depends on control dependency: [for], data = [aLong] } writer.flush(); return new String(out.toByteArray(), java.nio.charset.StandardCharsets.UTF_8); } }
public class class_name { private static void imdct12(float[] src, float[] dst, int outOff, int wndIdx) { for (int j = 15 + wndIdx, k = 12 + wndIdx; j >= 3 + wndIdx; j -= 3, k -= 3) src[j] += src[k]; src[15 + wndIdx] += src[9 + wndIdx]; src[9 + wndIdx] += src[3 + wndIdx]; float pp2 = src[12 + wndIdx] * cos600; float pp1 = src[6 + wndIdx] * cos300; float sum = src[0 + wndIdx] + pp2; tmp[1] = src[wndIdx] - src[12 + wndIdx]; tmp[0] = sum + pp1; tmp[2] = sum - pp1; pp2 = src[15 + wndIdx] * cos600; pp1 = src[9 + wndIdx] * cos300; sum = src[3 + wndIdx] + pp2; tmp[4] = src[3 + wndIdx] - src[15 + wndIdx]; tmp[5] = sum + pp1; tmp[3] = sum - pp1; tmp[3] *= factor12pt0; tmp[4] *= cos450; tmp[5] *= factor12pt1; float t = tmp[0]; tmp[0] += tmp[5]; tmp[5] = t - tmp[5]; t = tmp[1]; tmp[1] += tmp[4]; tmp[4] = t - tmp[4]; t = tmp[2]; tmp[2] += tmp[3]; tmp[3] = t - tmp[3]; for (int j = 0; j < 6; j++) tmp[j] *= factor12[j]; tmp[8] = -tmp[0] * cos375; tmp[9] = -tmp[0] * cos525; tmp[7] = -tmp[1] * cos225; tmp[10] = -tmp[1] * cos675; tmp[6] = -tmp[2] * cos075; tmp[11] = -tmp[2] * cos825; tmp[0] = tmp[3]; tmp[1] = tmp[4] * cos675; tmp[2] = tmp[5] * cos525; tmp[3] = -tmp[5] * cos375; tmp[4] = -tmp[4] * cos225; tmp[5] = -tmp[0] * cos075; tmp[0] *= cos825; for (int i = 0, j = outOff + 6; i < 12; i++, j++) { dst[j] += tmp[i]; } } }
public class class_name { private static void imdct12(float[] src, float[] dst, int outOff, int wndIdx) { for (int j = 15 + wndIdx, k = 12 + wndIdx; j >= 3 + wndIdx; j -= 3, k -= 3) src[j] += src[k]; src[15 + wndIdx] += src[9 + wndIdx]; src[9 + wndIdx] += src[3 + wndIdx]; float pp2 = src[12 + wndIdx] * cos600; float pp1 = src[6 + wndIdx] * cos300; float sum = src[0 + wndIdx] + pp2; tmp[1] = src[wndIdx] - src[12 + wndIdx]; tmp[0] = sum + pp1; tmp[2] = sum - pp1; pp2 = src[15 + wndIdx] * cos600; pp1 = src[9 + wndIdx] * cos300; sum = src[3 + wndIdx] + pp2; tmp[4] = src[3 + wndIdx] - src[15 + wndIdx]; tmp[5] = sum + pp1; tmp[3] = sum - pp1; tmp[3] *= factor12pt0; tmp[4] *= cos450; tmp[5] *= factor12pt1; float t = tmp[0]; tmp[0] += tmp[5]; tmp[5] = t - tmp[5]; t = tmp[1]; tmp[1] += tmp[4]; tmp[4] = t - tmp[4]; t = tmp[2]; tmp[2] += tmp[3]; tmp[3] = t - tmp[3]; for (int j = 0; j < 6; j++) tmp[j] *= factor12[j]; tmp[8] = -tmp[0] * cos375; tmp[9] = -tmp[0] * cos525; tmp[7] = -tmp[1] * cos225; tmp[10] = -tmp[1] * cos675; tmp[6] = -tmp[2] * cos075; tmp[11] = -tmp[2] * cos825; tmp[0] = tmp[3]; tmp[1] = tmp[4] * cos675; tmp[2] = tmp[5] * cos525; tmp[3] = -tmp[5] * cos375; tmp[4] = -tmp[4] * cos225; tmp[5] = -tmp[0] * cos075; tmp[0] *= cos825; for (int i = 0, j = outOff + 6; i < 12; i++, j++) { dst[j] += tmp[i]; // depends on control dependency: [for], data = [i] } } }
public class class_name { public static void waitWhileState(final DeviceProxy proxy, final DevState waitState, final long timeout, final long pollingTime) throws DevFailed, TimeoutException { final long time0 = System.currentTimeMillis(); while (proxy.state().equals(waitState)) { if (System.currentTimeMillis() - time0 > timeout) { throw new TimeoutException( "Stateutilities.waitWhileState : timeout reached while waiting end of state " + TangoConst.Tango_DevStateName[waitState.value()]); } try { Thread.sleep(pollingTime); } catch (final InterruptedException e) { // ignore } } } }
public class class_name { public static void waitWhileState(final DeviceProxy proxy, final DevState waitState, final long timeout, final long pollingTime) throws DevFailed, TimeoutException { final long time0 = System.currentTimeMillis(); while (proxy.state().equals(waitState)) { if (System.currentTimeMillis() - time0 > timeout) { throw new TimeoutException( "Stateutilities.waitWhileState : timeout reached while waiting end of state " + TangoConst.Tango_DevStateName[waitState.value()]); } try { Thread.sleep(pollingTime); // depends on control dependency: [try], data = [none] } catch (final InterruptedException e) { // ignore } // depends on control dependency: [catch], data = [none] } } }
public class class_name { private UriTuple parseUriTuple(String uri, Map<String, String[]> params) throws UnsupportedEncodingException { String requestUri = null; String queryString = ""; // default final int queryStringBegin = uri.indexOf("?"); if (queryStringBegin == -1) { // Simple case -- no querystring requestUri = uri; } else { // Complex case -- uri+querystring requestUri = uri.substring(0, queryStringBegin); queryString = uri.substring(queryStringBegin); // will already contain the '?' character } // Inject requestUri params for (Map.Entry<String, String[]> y : params.entrySet()) { final String token = "{" + y.getKey() + "}"; final String[] values = y.getValue(); switch (values.length) { case 0: // Strange -- I guess we omit it? while(requestUri.contains(token)) { // Don't use String.replaceAll b/c token looks like an illegal regex requestUri = requestUri.replace(token, ""); } break; case 1: // This is healthy & normal final String inject = URLEncoder.encode(values[0], "UTF-8"); while(requestUri.contains(token)) { // Don't use String.replaceAll b/c token looks like an illegal regex requestUri = requestUri.replace(token, inject); } break; default: // OOPS! -- can't have more than 1 value for a requestUri token final String msg = "Can't support multiple values for non-querystring URI token: " + token; throw new IllegalArgumentException(msg); } } // Inject queryString params for (Map.Entry<String, String[]> y : params.entrySet()) { final String paramName = y.getKey(); final String token = "{" + paramName + "}"; if (queryString.contains(token)) { final StringBuilder value = new StringBuilder(); for (String s : y.getValue()) { final String inject = URLEncoder.encode(s, "UTF-8"); value.append(value.length() != 0 ? "&" : ""); value.append(paramName).append("=").append(inject); } queryString = queryString.replace(token, value); } } // Split into contextName+uri final int contextSeparatorPos = requestUri.indexOf("/", 1); // A valid input starts with a slash, followed by the contextName final String contextName = requestUri.substring(0, contextSeparatorPos); // Includes leading '/' requestUri = requestUri.substring(contextSeparatorPos); // Includes leading '/' return new UriTuple(contextName, requestUri + queryString); } }
public class class_name { private UriTuple parseUriTuple(String uri, Map<String, String[]> params) throws UnsupportedEncodingException { String requestUri = null; String queryString = ""; // default final int queryStringBegin = uri.indexOf("?"); if (queryStringBegin == -1) { // Simple case -- no querystring requestUri = uri; } else { // Complex case -- uri+querystring requestUri = uri.substring(0, queryStringBegin); queryString = uri.substring(queryStringBegin); // will already contain the '?' character } // Inject requestUri params for (Map.Entry<String, String[]> y : params.entrySet()) { final String token = "{" + y.getKey() + "}"; final String[] values = y.getValue(); switch (values.length) { case 0: // Strange -- I guess we omit it? while(requestUri.contains(token)) { // Don't use String.replaceAll b/c token looks like an illegal regex requestUri = requestUri.replace(token, ""); // depends on control dependency: [while], data = [none] } break; case 1: // This is healthy & normal final String inject = URLEncoder.encode(values[0], "UTF-8"); while(requestUri.contains(token)) { // Don't use String.replaceAll b/c token looks like an illegal regex requestUri = requestUri.replace(token, inject); // depends on control dependency: [while], data = [none] } break; default: // OOPS! -- can't have more than 1 value for a requestUri token final String msg = "Can't support multiple values for non-querystring URI token: " + token; throw new IllegalArgumentException(msg); } } // Inject queryString params for (Map.Entry<String, String[]> y : params.entrySet()) { final String paramName = y.getKey(); final String token = "{" + paramName + "}"; if (queryString.contains(token)) { final StringBuilder value = new StringBuilder(); for (String s : y.getValue()) { final String inject = URLEncoder.encode(s, "UTF-8"); value.append(value.length() != 0 ? "&" : ""); value.append(paramName).append("=").append(inject); } queryString = queryString.replace(token, value); } } // Split into contextName+uri final int contextSeparatorPos = requestUri.indexOf("/", 1); // A valid input starts with a slash, followed by the contextName final String contextName = requestUri.substring(0, contextSeparatorPos); // Includes leading '/' requestUri = requestUri.substring(contextSeparatorPos); // Includes leading '/' return new UriTuple(contextName, requestUri + queryString); } }
public class class_name { public void setUrlPattern(String filterURI) { // determine what type of filter uri we have and set the mapping type if (filterURI.equals("/")) mappingType = WebAppFilterManager.FMI_MAPPING_SINGLE_SLASH; else if (filterURI.startsWith("/") && filterURI.endsWith("/*")) { mappingType = WebAppFilterManager.FMI_MAPPING_PATH_MATCH; // go ahead and strip the /* for later matching filterURI = filterURI.substring(0, filterURI.length() - 2); } else if (filterURI.startsWith("*.")) mappingType = WebAppFilterManager.FMI_MAPPING_EXTENSION_MATCH; // PK57083 START else if (WCCustomProperties.MAP_FILTERS_TO_ASTERICK && filterURI.equals("*")) { mappingType = WebAppFilterManager.FMI_MAPPING_PATH_MATCH; filterURI = ""; } // PK57083 END else mappingType = WebAppFilterManager.FMI_MAPPING_EXACT_MATCH; this.urlPattern = filterURI; } }
public class class_name { public void setUrlPattern(String filterURI) { // determine what type of filter uri we have and set the mapping type if (filterURI.equals("/")) mappingType = WebAppFilterManager.FMI_MAPPING_SINGLE_SLASH; else if (filterURI.startsWith("/") && filterURI.endsWith("/*")) { mappingType = WebAppFilterManager.FMI_MAPPING_PATH_MATCH; // depends on control dependency: [if], data = [none] // go ahead and strip the /* for later matching filterURI = filterURI.substring(0, filterURI.length() - 2); // depends on control dependency: [if], data = [none] } else if (filterURI.startsWith("*.")) mappingType = WebAppFilterManager.FMI_MAPPING_EXTENSION_MATCH; // PK57083 START else if (WCCustomProperties.MAP_FILTERS_TO_ASTERICK && filterURI.equals("*")) { mappingType = WebAppFilterManager.FMI_MAPPING_PATH_MATCH; // depends on control dependency: [if], data = [none] filterURI = ""; // depends on control dependency: [if], data = [none] } // PK57083 END else mappingType = WebAppFilterManager.FMI_MAPPING_EXACT_MATCH; this.urlPattern = filterURI; } }
public class class_name { public java.util.List<CancelledSpotInstanceRequest> getCancelledSpotInstanceRequests() { if (cancelledSpotInstanceRequests == null) { cancelledSpotInstanceRequests = new com.amazonaws.internal.SdkInternalList<CancelledSpotInstanceRequest>(); } return cancelledSpotInstanceRequests; } }
public class class_name { public java.util.List<CancelledSpotInstanceRequest> getCancelledSpotInstanceRequests() { if (cancelledSpotInstanceRequests == null) { cancelledSpotInstanceRequests = new com.amazonaws.internal.SdkInternalList<CancelledSpotInstanceRequest>(); // depends on control dependency: [if], data = [none] } return cancelledSpotInstanceRequests; } }
public class class_name { private void addFormulaAnd(final LinkedHashSet<Formula> ops, final Formula f) { if (f.type() == TRUE) { this.formulaAdditionResult[0] = true; this.formulaAdditionResult[1] = true; } else if (f.type == FALSE || containsComplement(ops, f)) { this.formulaAdditionResult[0] = false; this.formulaAdditionResult[1] = false; } else { ops.add(f); this.formulaAdditionResult[0] = true; this.formulaAdditionResult[1] = f.type == LITERAL || f.type == OR && ((Or) f).isCNFClause(); } } }
public class class_name { private void addFormulaAnd(final LinkedHashSet<Formula> ops, final Formula f) { if (f.type() == TRUE) { this.formulaAdditionResult[0] = true; // depends on control dependency: [if], data = [none] this.formulaAdditionResult[1] = true; // depends on control dependency: [if], data = [none] } else if (f.type == FALSE || containsComplement(ops, f)) { this.formulaAdditionResult[0] = false; // depends on control dependency: [if], data = [none] this.formulaAdditionResult[1] = false; // depends on control dependency: [if], data = [none] } else { ops.add(f); // depends on control dependency: [if], data = [none] this.formulaAdditionResult[0] = true; // depends on control dependency: [if], data = [none] this.formulaAdditionResult[1] = f.type == LITERAL || f.type == OR && ((Or) f).isCNFClause(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static Map<ResourceType, Integer> getResourceTypeToCountMap( int numCpus, Map<Integer, Map<ResourceType, Integer>> cpuToResourcePartitioning) { Map<ResourceType, Integer> ret = cpuToResourcePartitioning.get(numCpus); if (ret == null) { Map<ResourceType, Integer> oneCpuMap = cpuToResourcePartitioning.get(1); if (oneCpuMap == null) { throw new RuntimeException( "No matching entry for cpu count: " + numCpus + " in node and no 1 cpu map"); } ret = new EnumMap<ResourceType, Integer>(ResourceType.class); for (ResourceType key: oneCpuMap.keySet()) { ret.put(key, oneCpuMap.get(key).intValue() * numCpus); } } return ret; } }
public class class_name { public static Map<ResourceType, Integer> getResourceTypeToCountMap( int numCpus, Map<Integer, Map<ResourceType, Integer>> cpuToResourcePartitioning) { Map<ResourceType, Integer> ret = cpuToResourcePartitioning.get(numCpus); if (ret == null) { Map<ResourceType, Integer> oneCpuMap = cpuToResourcePartitioning.get(1); if (oneCpuMap == null) { throw new RuntimeException( "No matching entry for cpu count: " + numCpus + " in node and no 1 cpu map"); } ret = new EnumMap<ResourceType, Integer>(ResourceType.class); // depends on control dependency: [if], data = [none] for (ResourceType key: oneCpuMap.keySet()) { ret.put(key, oneCpuMap.get(key).intValue() * numCpus); // depends on control dependency: [for], data = [key] } } return ret; } }
public class class_name { public static <T> T newInstance(Class<T> class1) { try { return class1.newInstance(); } catch (Exception e) { throww(e); return null; } } }
public class class_name { public static <T> T newInstance(Class<T> class1) { try { return class1.newInstance(); // depends on control dependency: [try], data = [none] } catch (Exception e) { throww(e); return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public boolean checkPermission(boolean showAppInfoDialogEnabled) { boolean hasPermission; if (permissionRationaleMessageResId != 0) { hasPermission = checkPermission(permissionDelegate, getPermissionRationaleTitleResId(), permissionRationaleMessageResId, permission, permissionRequestCode); } else { hasPermission = checkPermission(permissionDelegate, permission, permissionRequestCode); } if (!hasPermission && showAppInfoDialogEnabled) { previouslyShouldShowRequestPermissionRationale = permissionDelegate.shouldShowRequestPermissionRationale(permission); } else { previouslyShouldShowRequestPermissionRationale = null; } return hasPermission; } }
public class class_name { public boolean checkPermission(boolean showAppInfoDialogEnabled) { boolean hasPermission; if (permissionRationaleMessageResId != 0) { hasPermission = checkPermission(permissionDelegate, getPermissionRationaleTitleResId(), permissionRationaleMessageResId, permission, permissionRequestCode); // depends on control dependency: [if], data = [none] } else { hasPermission = checkPermission(permissionDelegate, permission, permissionRequestCode); // depends on control dependency: [if], data = [none] } if (!hasPermission && showAppInfoDialogEnabled) { previouslyShouldShowRequestPermissionRationale = permissionDelegate.shouldShowRequestPermissionRationale(permission); // depends on control dependency: [if], data = [none] } else { previouslyShouldShowRequestPermissionRationale = null; // depends on control dependency: [if], data = [none] } return hasPermission; } }
public class class_name { List<String> matchNcepNames(GridDataset gds, String oldName) { List<String> result = new ArrayList<>(); // look for exact match if (contains(gds, oldName)) { result.add(oldName); return result; } Attribute att = gds.findGlobalAttributeIgnoreCase(CDM.FILE_FORMAT); boolean isGrib1 = (att != null) && att.getStringValue().startsWith("GRIB-1"); boolean isGrib2 = (att != null) && att.getStringValue().startsWith("GRIB-2"); HashMap<String, Renamer> map; if (isGrib1) { if (map1 == null) initMap1(); map = map1; } else if (isGrib2) { if (map2 == null) initMap2(); map = map2; } else { return result; // empty list } // look in our renamer map Renamer mbean = map.get(oldName); if (mbean != null && mbean.newName != null && contains(gds, mbean.newName)) { result.add(mbean.newName); // if its unique, then we are done return result; } // not unique - match against NCEP dataset if (mbean != null) { String dataset = extractDatasetFromLocation(gds.getLocation()); for (VariableRenamerBean r : mbean.newVars) { if (r.getDatasetType().equals(dataset) && contains(gds, r.newName)) result.add(r.newName); } if (result.size() == 1) return result; // return if unique } // not unique, no unique match against dataset - check existence in the dataset result.clear(); if (mbean != null) { for (VariableRenamerBean r : mbean.newVarsMap.values()) { if (contains(gds, r.newName)) result.add(r.newName); } if (result.size() > 0) return result; } // try to map oldName -> new prefix result.clear(); String oldMunged = munge(oldName); for (GridDatatype grid : gds.getGrids()) { String newMunged = munge(grid.getShortName()); if (newMunged.startsWith(oldMunged)) result.add(grid.getShortName()); } if (result.size() > 0) return result; // return empty list return result; } }
public class class_name { List<String> matchNcepNames(GridDataset gds, String oldName) { List<String> result = new ArrayList<>(); // look for exact match if (contains(gds, oldName)) { result.add(oldName); // depends on control dependency: [if], data = [none] return result; // depends on control dependency: [if], data = [none] } Attribute att = gds.findGlobalAttributeIgnoreCase(CDM.FILE_FORMAT); boolean isGrib1 = (att != null) && att.getStringValue().startsWith("GRIB-1"); boolean isGrib2 = (att != null) && att.getStringValue().startsWith("GRIB-2"); HashMap<String, Renamer> map; if (isGrib1) { if (map1 == null) initMap1(); map = map1; // depends on control dependency: [if], data = [none] } else if (isGrib2) { if (map2 == null) initMap2(); map = map2; // depends on control dependency: [if], data = [none] } else { return result; // empty list // depends on control dependency: [if], data = [none] } // look in our renamer map Renamer mbean = map.get(oldName); if (mbean != null && mbean.newName != null && contains(gds, mbean.newName)) { result.add(mbean.newName); // if its unique, then we are done // depends on control dependency: [if], data = [(mbean] return result; // depends on control dependency: [if], data = [none] } // not unique - match against NCEP dataset if (mbean != null) { String dataset = extractDatasetFromLocation(gds.getLocation()); for (VariableRenamerBean r : mbean.newVars) { if (r.getDatasetType().equals(dataset) && contains(gds, r.newName)) result.add(r.newName); } if (result.size() == 1) return result; // return if unique } // not unique, no unique match against dataset - check existence in the dataset result.clear(); if (mbean != null) { for (VariableRenamerBean r : mbean.newVarsMap.values()) { if (contains(gds, r.newName)) result.add(r.newName); } if (result.size() > 0) return result; } // try to map oldName -> new prefix result.clear(); String oldMunged = munge(oldName); for (GridDatatype grid : gds.getGrids()) { String newMunged = munge(grid.getShortName()); if (newMunged.startsWith(oldMunged)) result.add(grid.getShortName()); } if (result.size() > 0) return result; // return empty list return result; } }
public class class_name { public static void longpoll(DbxAuthInfo auth, String path) throws IOException { long longpollTimeoutSecs = TimeUnit.MINUTES.toSeconds(2); // need 2 Dropbox clients for making calls: // // (1) One for longpoll requests, with its read timeout set longer than our polling timeout // (2) One for all other requests, with its read timeout set to the default, shorter timeout // StandardHttpRequestor.Config config = StandardHttpRequestor.Config.DEFAULT_INSTANCE; StandardHttpRequestor.Config longpollConfig = config.copy() // read timeout should be greater than our longpoll timeout and include enough buffer // for the jitter introduced by the server. The server will add a random amount of delay // to our longpoll timeout to avoid the stampeding herd problem. See // DbxFiles.listFolderLongpoll(String, long) documentation for details. .withReadTimeout(5, TimeUnit.MINUTES) .build(); DbxClientV2 dbxClient = createClient(auth, config); DbxClientV2 dbxLongpollClient = createClient(auth, longpollConfig); try { // We only care about file changes, not existing files, so grab latest cursor for this // path and then longpoll for changes. String cursor = getLatestCursor(dbxClient, path); System.out.println("Longpolling for changes... press CTRL-C to exit."); while (true) { // will block for longpollTimeoutSecs or until a change is made in the folder ListFolderLongpollResult result = dbxLongpollClient.files() .listFolderLongpoll(cursor, longpollTimeoutSecs); // we have changes, list them if (result.getChanges()) { cursor = printChanges(dbxClient, cursor); } // we were asked to back off from our polling, wait the requested amount of seconds // before issuing another longpoll request. Long backoff = result.getBackoff(); if (backoff != null) { try { System.out.printf("backing off for %d secs...\n", backoff.longValue()); Thread.sleep(TimeUnit.SECONDS.toMillis(backoff)); } catch (InterruptedException ex) { System.exit(0); } } } } catch (DbxApiException ex) { // if a user message is available, try using that instead String message = ex.getUserMessage() != null ? ex.getUserMessage().getText() : ex.getMessage(); System.err.println("Error making API call: " + message); System.exit(1); } catch (NetworkIOException ex) { System.err.println("Error making API call: " + ex.getMessage()); if (ex.getCause() instanceof SocketTimeoutException) { System.err.println("Consider increasing socket read timeout or decreasing longpoll timeout."); } System.exit(1); } catch (DbxException ex) { System.err.println("Error making API call: " + ex.getMessage()); System.exit(1); } } }
public class class_name { public static void longpoll(DbxAuthInfo auth, String path) throws IOException { long longpollTimeoutSecs = TimeUnit.MINUTES.toSeconds(2); // need 2 Dropbox clients for making calls: // // (1) One for longpoll requests, with its read timeout set longer than our polling timeout // (2) One for all other requests, with its read timeout set to the default, shorter timeout // StandardHttpRequestor.Config config = StandardHttpRequestor.Config.DEFAULT_INSTANCE; StandardHttpRequestor.Config longpollConfig = config.copy() // read timeout should be greater than our longpoll timeout and include enough buffer // for the jitter introduced by the server. The server will add a random amount of delay // to our longpoll timeout to avoid the stampeding herd problem. See // DbxFiles.listFolderLongpoll(String, long) documentation for details. .withReadTimeout(5, TimeUnit.MINUTES) .build(); DbxClientV2 dbxClient = createClient(auth, config); DbxClientV2 dbxLongpollClient = createClient(auth, longpollConfig); try { // We only care about file changes, not existing files, so grab latest cursor for this // path and then longpoll for changes. String cursor = getLatestCursor(dbxClient, path); System.out.println("Longpolling for changes... press CTRL-C to exit."); while (true) { // will block for longpollTimeoutSecs or until a change is made in the folder ListFolderLongpollResult result = dbxLongpollClient.files() .listFolderLongpoll(cursor, longpollTimeoutSecs); // we have changes, list them if (result.getChanges()) { cursor = printChanges(dbxClient, cursor); // depends on control dependency: [if], data = [none] } // we were asked to back off from our polling, wait the requested amount of seconds // before issuing another longpoll request. Long backoff = result.getBackoff(); if (backoff != null) { try { System.out.printf("backing off for %d secs...\n", backoff.longValue()); // depends on control dependency: [try], data = [none] Thread.sleep(TimeUnit.SECONDS.toMillis(backoff)); // depends on control dependency: [try], data = [none] } catch (InterruptedException ex) { System.exit(0); } // depends on control dependency: [catch], data = [none] } } } catch (DbxApiException ex) { // if a user message is available, try using that instead String message = ex.getUserMessage() != null ? ex.getUserMessage().getText() : ex.getMessage(); System.err.println("Error making API call: " + message); System.exit(1); } catch (NetworkIOException ex) { System.err.println("Error making API call: " + ex.getMessage()); if (ex.getCause() instanceof SocketTimeoutException) { System.err.println("Consider increasing socket read timeout or decreasing longpoll timeout."); // depends on control dependency: [if], data = [none] } System.exit(1); } catch (DbxException ex) { System.err.println("Error making API call: " + ex.getMessage()); System.exit(1); } } }
public class class_name { static DateTime determineRotationPeriodAnchor(@Nullable DateTime lastAnchor, Period period) { final Period normalized = period.normalizedStandard(); int years = normalized.getYears(); int months = normalized.getMonths(); int weeks = normalized.getWeeks(); int days = normalized.getDays(); int hours = normalized.getHours(); int minutes = normalized.getMinutes(); int seconds = normalized.getSeconds(); if (years == 0 && months == 0 && weeks == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0) { throw new IllegalArgumentException("Invalid rotation period specified"); } // find the largest non-zero stride in the period. that's our anchor type. statement order matters here! DateTimeFieldType largestStrideType = null; if (seconds > 0) largestStrideType = secondOfMinute(); if (minutes > 0) largestStrideType = minuteOfHour(); if (hours > 0) largestStrideType = hourOfDay(); if (days > 0) largestStrideType = dayOfMonth(); if (weeks > 0) largestStrideType = weekOfWeekyear(); if (months > 0) largestStrideType = monthOfYear(); if (years > 0) largestStrideType = year(); if (largestStrideType == null) { throw new IllegalArgumentException("Could not determine rotation stride length."); } final DateTime anchorTime = MoreObjects.firstNonNull(lastAnchor, Tools.nowUTC()); final DateTimeField field = largestStrideType.getField(anchorTime.getChronology()); // use normalized here to make sure we actually have the largestStride type available! see https://github.com/Graylog2/graylog2-server/issues/836 int periodValue = normalized.get(largestStrideType.getDurationType()); final long fieldValue = field.roundFloor(anchorTime.getMillis()); final int fieldValueInUnit = field.get(fieldValue); if (periodValue == 0) { // https://github.com/Graylog2/graylog2-server/issues/836 log.warn("Determining stride length failed because of a 0 period. Defaulting back to 1 period to avoid crashing, but this is a bug!"); periodValue = 1; } final long difference = fieldValueInUnit % periodValue; final long newValue = field.add(fieldValue, -1 * difference); return new DateTime(newValue, DateTimeZone.UTC); } }
public class class_name { static DateTime determineRotationPeriodAnchor(@Nullable DateTime lastAnchor, Period period) { final Period normalized = period.normalizedStandard(); int years = normalized.getYears(); int months = normalized.getMonths(); int weeks = normalized.getWeeks(); int days = normalized.getDays(); int hours = normalized.getHours(); int minutes = normalized.getMinutes(); int seconds = normalized.getSeconds(); if (years == 0 && months == 0 && weeks == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0) { throw new IllegalArgumentException("Invalid rotation period specified"); } // find the largest non-zero stride in the period. that's our anchor type. statement order matters here! DateTimeFieldType largestStrideType = null; if (seconds > 0) largestStrideType = secondOfMinute(); if (minutes > 0) largestStrideType = minuteOfHour(); if (hours > 0) largestStrideType = hourOfDay(); if (days > 0) largestStrideType = dayOfMonth(); if (weeks > 0) largestStrideType = weekOfWeekyear(); if (months > 0) largestStrideType = monthOfYear(); if (years > 0) largestStrideType = year(); if (largestStrideType == null) { throw new IllegalArgumentException("Could not determine rotation stride length."); } final DateTime anchorTime = MoreObjects.firstNonNull(lastAnchor, Tools.nowUTC()); final DateTimeField field = largestStrideType.getField(anchorTime.getChronology()); // use normalized here to make sure we actually have the largestStride type available! see https://github.com/Graylog2/graylog2-server/issues/836 int periodValue = normalized.get(largestStrideType.getDurationType()); final long fieldValue = field.roundFloor(anchorTime.getMillis()); final int fieldValueInUnit = field.get(fieldValue); if (periodValue == 0) { // https://github.com/Graylog2/graylog2-server/issues/836 log.warn("Determining stride length failed because of a 0 period. Defaulting back to 1 period to avoid crashing, but this is a bug!"); // depends on control dependency: [if], data = [none] periodValue = 1; // depends on control dependency: [if], data = [none] } final long difference = fieldValueInUnit % periodValue; final long newValue = field.add(fieldValue, -1 * difference); return new DateTime(newValue, DateTimeZone.UTC); } }
public class class_name { @Override public Map<String, WorkItemHandler> getWorkItemHandlers(RuntimeEngine runtime) { Map<String, WorkItemHandler> map = new HashMap<String, WorkItemHandler>(); map.putAll(_rootFactory.getWorkItemHandlers(runtime)); for (RegisterableItemsFactory f : _factories) { map.putAll(f.getWorkItemHandlers(runtime)); } return map; } }
public class class_name { @Override public Map<String, WorkItemHandler> getWorkItemHandlers(RuntimeEngine runtime) { Map<String, WorkItemHandler> map = new HashMap<String, WorkItemHandler>(); map.putAll(_rootFactory.getWorkItemHandlers(runtime)); for (RegisterableItemsFactory f : _factories) { map.putAll(f.getWorkItemHandlers(runtime)); // depends on control dependency: [for], data = [f] } return map; } }
public class class_name { @SuppressWarnings("deprecation") private void updateParentBoundingBox(SvgElement obj) { if (obj.parent == null) // skip this if obj is root element return; if (obj.boundingBox == null) // empty bbox, possibly as a result of a badly defined element (eg bad use reference etc) return; // Convert the corners of the child bbox to world space Matrix m = new Matrix(); // Get the inverse of the child transform if (matrixStack.peek().invert(m)) { float[] pts = {obj.boundingBox.minX, obj.boundingBox.minY, obj.boundingBox.maxX(), obj.boundingBox.minY, obj.boundingBox.maxX(), obj.boundingBox.maxY(), obj.boundingBox.minX, obj.boundingBox.maxY()}; // Now concatenate the parent's matrix to create a child-to-parent transform m.preConcat(canvas.getMatrix()); m.mapPoints(pts); // Finally, find the bounding box of the transformed points RectF rect = new RectF(pts[0], pts[1], pts[0], pts[1]); for (int i=2; i<=6; i+=2) { if (pts[i] < rect.left) rect.left = pts[i]; if (pts[i] > rect.right) rect.right = pts[i]; if (pts[i+1] < rect.top) rect.top = pts[i+1]; if (pts[i+1] > rect.bottom) rect.bottom = pts[i+1]; } // Update the parent bounding box with the transformed bbox SvgElement parent = (SvgElement) parentStack.peek(); if (parent.boundingBox == null) parent.boundingBox = Box.fromLimits(rect.left, rect.top, rect.right, rect.bottom); else parent.boundingBox.union(Box.fromLimits(rect.left, rect.top, rect.right, rect.bottom)); } } }
public class class_name { @SuppressWarnings("deprecation") private void updateParentBoundingBox(SvgElement obj) { if (obj.parent == null) // skip this if obj is root element return; if (obj.boundingBox == null) // empty bbox, possibly as a result of a badly defined element (eg bad use reference etc) return; // Convert the corners of the child bbox to world space Matrix m = new Matrix(); // Get the inverse of the child transform if (matrixStack.peek().invert(m)) { float[] pts = {obj.boundingBox.minX, obj.boundingBox.minY, obj.boundingBox.maxX(), obj.boundingBox.minY, obj.boundingBox.maxX(), obj.boundingBox.maxY(), obj.boundingBox.minX, obj.boundingBox.maxY()}; // Now concatenate the parent's matrix to create a child-to-parent transform m.preConcat(canvas.getMatrix()); // depends on control dependency: [if], data = [none] m.mapPoints(pts); // depends on control dependency: [if], data = [none] // Finally, find the bounding box of the transformed points RectF rect = new RectF(pts[0], pts[1], pts[0], pts[1]); for (int i=2; i<=6; i+=2) { if (pts[i] < rect.left) rect.left = pts[i]; if (pts[i] > rect.right) rect.right = pts[i]; if (pts[i+1] < rect.top) rect.top = pts[i+1]; if (pts[i+1] > rect.bottom) rect.bottom = pts[i+1]; } // Update the parent bounding box with the transformed bbox SvgElement parent = (SvgElement) parentStack.peek(); if (parent.boundingBox == null) parent.boundingBox = Box.fromLimits(rect.left, rect.top, rect.right, rect.bottom); else parent.boundingBox.union(Box.fromLimits(rect.left, rect.top, rect.right, rect.bottom)); } } }
public class class_name { public void position() { // get the window client width int windowWidth = Window.getClientWidth(); // get the min left position int minLeft = MIN_MARGIN; // get the max right position int maxRight = windowWidth - MIN_MARGIN; // get the middle button position CmsPositionBean buttonPosition = CmsPositionBean.generatePositionInfo(m_button.getElement()); int buttonMiddle = (buttonPosition.getLeft() - Window.getScrollLeft()) + (buttonPosition.getWidth() / 2); // get the content width int contentWidth = getOffsetWidth(); // the optimum left position is in the middle of the button minus the half content width // assume that the optimum fits into the space int contentLeft = buttonMiddle - (contentWidth / 2); if (minLeft > contentLeft) { // if the optimum left position of the popup is outside the min left position: // move the popup to the right (take the min left position as left) contentLeft = minLeft; } else if ((contentLeft + contentWidth) > maxRight) { // if the left position plus the content width is outside the max right position: // move the popup to the left (take the max right position minus the content width) contentLeft = maxRight - contentWidth; } // limit the right position if the popup is right outside the window if ((contentLeft + contentWidth + MIN_MARGIN) > windowWidth) { contentLeft = windowWidth - contentWidth - MIN_MARGIN; } // limit the left position if the popup is left outside the window if (contentLeft < MIN_MARGIN) { contentLeft = MIN_MARGIN; } int arrowSpace = 10; int arrowWidth = 40; int arrowHeight = 12; // the optimum position for the arrow is in the middle of the button int arrowLeft = buttonMiddle - contentLeft - (arrowWidth / 2); if ((arrowLeft + arrowWidth + arrowSpace) > contentWidth) { // limit the arrow position if the maximum is reached (content width 'minus x') arrowLeft = contentWidth - arrowWidth - arrowSpace; } else if ((arrowLeft - arrowSpace) < 0) { // limit the arrow position if the minimum is reached ('plus x') arrowLeft = arrowWidth + arrowSpace; } int arrowTop = -(arrowHeight - 2); String arrowClass = I_CmsLayoutBundle.INSTANCE.dialogCss().menuArrowTop(); int contentTop = (((buttonPosition.getTop() + buttonPosition.getHeight()) - Window.getScrollTop()) + arrowHeight) - 2; if (!m_isToolbarMode) { contentTop = (buttonPosition.getTop() + buttonPosition.getHeight() + arrowHeight) - 2; int contentHeight = getOffsetHeight(); int windowHeight = Window.getClientHeight(); if (((contentHeight + MIN_MARGIN) < windowHeight) && ((buttonPosition.getTop() - Window.getScrollTop()) > contentHeight) && (((contentHeight + MIN_MARGIN + contentTop) - Window.getScrollTop()) > windowHeight)) { // content fits into the window height, // there is enough space above the button // and there is to little space below the button // so show above contentTop = ((buttonPosition.getTop() - arrowHeight) + 2) - contentHeight; arrowTop = contentHeight - 1; arrowClass = I_CmsLayoutBundle.INSTANCE.dialogCss().menuArrowBottom(); } } else { contentLeft = contentLeft - Window.getScrollLeft(); setPositionFixed(); } m_arrow.setClassName(arrowClass); m_arrow.getStyle().setLeft(arrowLeft, Unit.PX); m_arrow.getStyle().setTop(arrowTop, Unit.PX); showArrow(m_arrow); setPopupPosition(contentLeft + Window.getScrollLeft(), contentTop); } }
public class class_name { public void position() { // get the window client width int windowWidth = Window.getClientWidth(); // get the min left position int minLeft = MIN_MARGIN; // get the max right position int maxRight = windowWidth - MIN_MARGIN; // get the middle button position CmsPositionBean buttonPosition = CmsPositionBean.generatePositionInfo(m_button.getElement()); int buttonMiddle = (buttonPosition.getLeft() - Window.getScrollLeft()) + (buttonPosition.getWidth() / 2); // get the content width int contentWidth = getOffsetWidth(); // the optimum left position is in the middle of the button minus the half content width // assume that the optimum fits into the space int contentLeft = buttonMiddle - (contentWidth / 2); if (minLeft > contentLeft) { // if the optimum left position of the popup is outside the min left position: // move the popup to the right (take the min left position as left) contentLeft = minLeft; // depends on control dependency: [if], data = [none] } else if ((contentLeft + contentWidth) > maxRight) { // if the left position plus the content width is outside the max right position: // move the popup to the left (take the max right position minus the content width) contentLeft = maxRight - contentWidth; // depends on control dependency: [if], data = [none] } // limit the right position if the popup is right outside the window if ((contentLeft + contentWidth + MIN_MARGIN) > windowWidth) { contentLeft = windowWidth - contentWidth - MIN_MARGIN; // depends on control dependency: [if], data = [none] } // limit the left position if the popup is left outside the window if (contentLeft < MIN_MARGIN) { contentLeft = MIN_MARGIN; // depends on control dependency: [if], data = [none] } int arrowSpace = 10; int arrowWidth = 40; int arrowHeight = 12; // the optimum position for the arrow is in the middle of the button int arrowLeft = buttonMiddle - contentLeft - (arrowWidth / 2); if ((arrowLeft + arrowWidth + arrowSpace) > contentWidth) { // limit the arrow position if the maximum is reached (content width 'minus x') arrowLeft = contentWidth - arrowWidth - arrowSpace; // depends on control dependency: [if], data = [none] } else if ((arrowLeft - arrowSpace) < 0) { // limit the arrow position if the minimum is reached ('plus x') arrowLeft = arrowWidth + arrowSpace; // depends on control dependency: [if], data = [none] } int arrowTop = -(arrowHeight - 2); String arrowClass = I_CmsLayoutBundle.INSTANCE.dialogCss().menuArrowTop(); int contentTop = (((buttonPosition.getTop() + buttonPosition.getHeight()) - Window.getScrollTop()) + arrowHeight) - 2; if (!m_isToolbarMode) { contentTop = (buttonPosition.getTop() + buttonPosition.getHeight() + arrowHeight) - 2; // depends on control dependency: [if], data = [none] int contentHeight = getOffsetHeight(); int windowHeight = Window.getClientHeight(); if (((contentHeight + MIN_MARGIN) < windowHeight) && ((buttonPosition.getTop() - Window.getScrollTop()) > contentHeight) && (((contentHeight + MIN_MARGIN + contentTop) - Window.getScrollTop()) > windowHeight)) { // content fits into the window height, // there is enough space above the button // and there is to little space below the button // so show above contentTop = ((buttonPosition.getTop() - arrowHeight) + 2) - contentHeight; // depends on control dependency: [if], data = [none] arrowTop = contentHeight - 1; // depends on control dependency: [if], data = [none] arrowClass = I_CmsLayoutBundle.INSTANCE.dialogCss().menuArrowBottom(); // depends on control dependency: [if], data = [none] } } else { contentLeft = contentLeft - Window.getScrollLeft(); // depends on control dependency: [if], data = [none] setPositionFixed(); // depends on control dependency: [if], data = [none] } m_arrow.setClassName(arrowClass); m_arrow.getStyle().setLeft(arrowLeft, Unit.PX); m_arrow.getStyle().setTop(arrowTop, Unit.PX); showArrow(m_arrow); setPopupPosition(contentLeft + Window.getScrollLeft(), contentTop); } }
public class class_name { protected Rect calculateItemRect(Item item, Point coords, Rect reuse) { final Rect out = reuse != null ? reuse : new Rect(); HotspotPlace hotspot = item.getMarkerHotspot(); if (hotspot == null) { hotspot = HotspotPlace.BOTTOM_CENTER; } final int state = (mDrawFocusedItem && (mFocusedItem == item) ? OverlayItem.ITEM_STATE_FOCUSED_MASK : 0); final Drawable marker = (item.getMarker(state) == null) ? getDefaultMarker(state) : item.getMarker(state); int itemWidth = marker.getIntrinsicWidth(); int itemHeight = marker.getIntrinsicHeight(); switch (hotspot) { case NONE: out.set(coords.x - itemWidth / 2, coords.y - itemHeight / 2, coords.x + itemWidth / 2, coords.y + itemHeight / 2); break; case CENTER: out.set(coords.x - itemWidth / 2, coords.y - itemHeight / 2, coords.x + itemWidth / 2, coords.y + itemHeight / 2); break; case BOTTOM_CENTER: out.set(coords.x - itemWidth / 2, coords.y - itemHeight, coords.x + itemWidth / 2, coords.y); break; case TOP_CENTER: out.set(coords.x - itemWidth / 2, coords.y, coords.x + itemWidth / 2, coords.y + itemHeight); break; case RIGHT_CENTER: out.set(coords.x - itemWidth, coords.y - itemHeight / 2, coords.x , coords.y + itemHeight / 2); break; case LEFT_CENTER: out.set(coords.x, coords.y - itemHeight / 2, coords.x + itemWidth, coords.y + itemHeight / 2); break; case UPPER_RIGHT_CORNER: out.set(coords.x - itemWidth, coords.y, coords.x , coords.y + itemHeight); break; case LOWER_RIGHT_CORNER: out.set(coords.x - itemWidth, coords.y - itemHeight, coords.x, coords.y); break; case UPPER_LEFT_CORNER: out.set(coords.x , coords.y, coords.x + itemWidth, coords.y + itemHeight); break; case LOWER_LEFT_CORNER: out.set(coords.x , coords.y - itemHeight, coords.x + itemWidth, coords.y); break; } return out; } }
public class class_name { protected Rect calculateItemRect(Item item, Point coords, Rect reuse) { final Rect out = reuse != null ? reuse : new Rect(); HotspotPlace hotspot = item.getMarkerHotspot(); if (hotspot == null) { hotspot = HotspotPlace.BOTTOM_CENTER; // depends on control dependency: [if], data = [none] } final int state = (mDrawFocusedItem && (mFocusedItem == item) ? OverlayItem.ITEM_STATE_FOCUSED_MASK : 0); final Drawable marker = (item.getMarker(state) == null) ? getDefaultMarker(state) : item.getMarker(state); int itemWidth = marker.getIntrinsicWidth(); int itemHeight = marker.getIntrinsicHeight(); switch (hotspot) { case NONE: out.set(coords.x - itemWidth / 2, coords.y - itemHeight / 2, coords.x + itemWidth / 2, coords.y + itemHeight / 2); break; case CENTER: out.set(coords.x - itemWidth / 2, coords.y - itemHeight / 2, coords.x + itemWidth / 2, coords.y + itemHeight / 2); break; case BOTTOM_CENTER: out.set(coords.x - itemWidth / 2, coords.y - itemHeight, coords.x + itemWidth / 2, coords.y); break; case TOP_CENTER: out.set(coords.x - itemWidth / 2, coords.y, coords.x + itemWidth / 2, coords.y + itemHeight); break; case RIGHT_CENTER: out.set(coords.x - itemWidth, coords.y - itemHeight / 2, coords.x , coords.y + itemHeight / 2); break; case LEFT_CENTER: out.set(coords.x, coords.y - itemHeight / 2, coords.x + itemWidth, coords.y + itemHeight / 2); break; case UPPER_RIGHT_CORNER: out.set(coords.x - itemWidth, coords.y, coords.x , coords.y + itemHeight); break; case LOWER_RIGHT_CORNER: out.set(coords.x - itemWidth, coords.y - itemHeight, coords.x, coords.y); break; case UPPER_LEFT_CORNER: out.set(coords.x , coords.y, coords.x + itemWidth, coords.y + itemHeight); break; case LOWER_LEFT_CORNER: out.set(coords.x , coords.y - itemHeight, coords.x + itemWidth, coords.y); break; } return out; } }
public class class_name { public static double JensenShannonDivergence(double[] p, double[] q) { double[] m = new double[p.length]; for (int i = 0; i < m.length; i++) { m[i] = (p[i] + q[i]) / 2; } return (KullbackLeiblerDivergence(p, m) + KullbackLeiblerDivergence(q, m)) / 2; } }
public class class_name { public static double JensenShannonDivergence(double[] p, double[] q) { double[] m = new double[p.length]; for (int i = 0; i < m.length; i++) { m[i] = (p[i] + q[i]) / 2; // depends on control dependency: [for], data = [i] } return (KullbackLeiblerDivergence(p, m) + KullbackLeiblerDivergence(q, m)) / 2; } }
public class class_name { private void release(TestSession session, SessionTerminationReason reason) { try { lock.lock(); boolean removed = activeTestSessions.remove(session, reason); if (removed) { fireMatcherStateChanged(); } } finally { lock.unlock(); } } }
public class class_name { private void release(TestSession session, SessionTerminationReason reason) { try { lock.lock(); // depends on control dependency: [try], data = [none] boolean removed = activeTestSessions.remove(session, reason); if (removed) { fireMatcherStateChanged(); // depends on control dependency: [if], data = [none] } } finally { lock.unlock(); } } }
public class class_name { private void updateCache(int index, QueryParameters params) { if (generatedCacheMap.containsKey(index) == true) { this.generatedCacheMap.put(index, params); } else { this.resultSetCacheMap.put(index, params); } } }
public class class_name { private void updateCache(int index, QueryParameters params) { if (generatedCacheMap.containsKey(index) == true) { this.generatedCacheMap.put(index, params); // depends on control dependency: [if], data = [none] } else { this.resultSetCacheMap.put(index, params); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String appendSystemtimeToFilename(final File fileToRename, final Date add2Name) { final String format = "HHmmssSSS"; String sysTime = null; if (null != add2Name) { final DateFormat df = new SimpleDateFormat(format); sysTime = df.format(add2Name); } else { final DateFormat df = new SimpleDateFormat(format); sysTime = df.format(new Date()); } final String fileName = fileToRename.getName(); final int ext_index = fileName.lastIndexOf("."); final String ext = fileName.substring(ext_index, fileName.length()); String newName = fileName.substring(0, ext_index); newName += "_" + sysTime + ext; return newName; } }
public class class_name { public static String appendSystemtimeToFilename(final File fileToRename, final Date add2Name) { final String format = "HHmmssSSS"; String sysTime = null; if (null != add2Name) { final DateFormat df = new SimpleDateFormat(format); sysTime = df.format(add2Name); // depends on control dependency: [if], data = [add2Name)] } else { final DateFormat df = new SimpleDateFormat(format); sysTime = df.format(new Date()); // depends on control dependency: [if], data = [none] } final String fileName = fileToRename.getName(); final int ext_index = fileName.lastIndexOf("."); final String ext = fileName.substring(ext_index, fileName.length()); String newName = fileName.substring(0, ext_index); newName += "_" + sysTime + ext; return newName; } }
public class class_name { public Object makeObject() { if (logger.isTraceEnabled()) { logger.trace("makeObject()"); } ProfileObjectImpl profileObject = new ProfileObjectImpl(profileTable); profileObject.setProfileContext(new ProfileContextImpl(profileTable)); return profileObject; } }
public class class_name { public Object makeObject() { if (logger.isTraceEnabled()) { logger.trace("makeObject()"); // depends on control dependency: [if], data = [none] } ProfileObjectImpl profileObject = new ProfileObjectImpl(profileTable); profileObject.setProfileContext(new ProfileContextImpl(profileTable)); return profileObject; } }
public class class_name { public long getPrecision() { switch (type) { case OLDDECIMAL: case DECIMAL: //DECIMAL and OLDDECIMAL are "exact" fixed-point number. //so : // - if can be signed, 1 byte is saved for sign // - if decimal > 0, one byte more for dot if (isSigned()) { return length - ((decimals > 0) ? 2 : 1); } else { return length - ((decimals > 0) ? 1 : 0); } default: return length; } } }
public class class_name { public long getPrecision() { switch (type) { case OLDDECIMAL: case DECIMAL: //DECIMAL and OLDDECIMAL are "exact" fixed-point number. //so : // - if can be signed, 1 byte is saved for sign // - if decimal > 0, one byte more for dot if (isSigned()) { return length - ((decimals > 0) ? 2 : 1); // depends on control dependency: [if], data = [none] } else { return length - ((decimals > 0) ? 1 : 0); // depends on control dependency: [if], data = [none] } default: return length; } } }
public class class_name { public static String getProperty(String name, String defaultValue) { if (PropertiesManager.props == null) loadProps(); String returnValue = defaultValue; try { returnValue = getProperty(name); } catch (MissingPropertyException mpe) { // Do nothing, since we have already recorded and logged the missing property. } return returnValue; } }
public class class_name { public static String getProperty(String name, String defaultValue) { if (PropertiesManager.props == null) loadProps(); String returnValue = defaultValue; try { returnValue = getProperty(name); // depends on control dependency: [try], data = [none] } catch (MissingPropertyException mpe) { // Do nothing, since we have already recorded and logged the missing property. } // depends on control dependency: [catch], data = [none] return returnValue; } }
public class class_name { public String buildRequest(DescribeService describeService, double minX, double minY, double maxX, double maxY, List<Param> optionalParams, double lon, double lat) throws POIProxyException { ServiceParams params = new ServiceParams(); Extent e1 = new Extent(minX, minY, maxX, maxY); double[] minXY = GeotoolsUtils.transform(GEODETIC_SRS, describeService.getSRS(), new double[] { e1.getMinX(), e1.getMinY() }); double[] maxXY = GeotoolsUtils.transform(GEODETIC_SRS, describeService.getSRS(), new double[] { e1.getMaxX(), e1.getMaxY() }); int distanceMeters = this.getDistanceMeters(e1); e1.setMinX(minXY[0]); e1.setMinY(minXY[1]); e1.setMaxX(maxXY[0]); e1.setMaxY(maxXY[1]); params.putParam(ServiceParams.MINX, String.valueOf(minXY[0])); params.putParam(ServiceParams.MINY, String.valueOf(minXY[1])); params.putParam(ServiceParams.MAXX, String.valueOf(maxXY[0])); params.putParam(ServiceParams.MAXY, String.valueOf(maxXY[1])); double longitude = (lon != 0) ? lon : e1.getCenter().getX(); double latitude = (lat != 0) ? lat : e1.getCenter().getY(); params.putParam(ServiceParams.LON, String.valueOf(longitude)); params.putParam(ServiceParams.LAT, String.valueOf(latitude)); params.putParam(ServiceParams.FORMAT, "json"); params.putParam(ServiceParams.DIST, String.valueOf((int) distanceMeters)); params.putParam(ServiceParams.DISTKM, String.valueOf(Double.valueOf(distanceMeters) / 1000)); params.putParam(ServiceParams.KEY, describeService.getApiKey()); if (optionalParams != null) { String p; for (Param optParam : optionalParams) { //NO IDEA HOW CAN THIS BE NULL BUT IT IS HAPPENING if (optParam == null) { continue; } p = params.getServiceParamFromURLParam(optParam.getType()); if (p == null) { if (describeService.isEncodeUrl()) { try { params.putParam(p, URLEncoder.encode(optParam.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { logger.warn(e); } } else { params.putParam(optParam.getType(), optParam.getValue()); } } else { if (describeService.isEncodeUrl()) { try { params.putParam(p, URLEncoder.encode(optParam.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { logger.warn(e); } } else { params.putParam(p, optParam.getValue()); } } } } String url = describeService.getRequestForParam(optionalParams, params); Set<String> keys = params.getParams().keySet(); Iterator<String> it = keys.iterator(); String key; while (it.hasNext()) { key = it.next(); if (describeService.isSpecialParam(key)) { url = url.replaceAll(key, getValue(params, key, describeService)); } } return url; } }
public class class_name { public String buildRequest(DescribeService describeService, double minX, double minY, double maxX, double maxY, List<Param> optionalParams, double lon, double lat) throws POIProxyException { ServiceParams params = new ServiceParams(); Extent e1 = new Extent(minX, minY, maxX, maxY); double[] minXY = GeotoolsUtils.transform(GEODETIC_SRS, describeService.getSRS(), new double[] { e1.getMinX(), e1.getMinY() }); double[] maxXY = GeotoolsUtils.transform(GEODETIC_SRS, describeService.getSRS(), new double[] { e1.getMaxX(), e1.getMaxY() }); int distanceMeters = this.getDistanceMeters(e1); e1.setMinX(minXY[0]); e1.setMinY(minXY[1]); e1.setMaxX(maxXY[0]); e1.setMaxY(maxXY[1]); params.putParam(ServiceParams.MINX, String.valueOf(minXY[0])); params.putParam(ServiceParams.MINY, String.valueOf(minXY[1])); params.putParam(ServiceParams.MAXX, String.valueOf(maxXY[0])); params.putParam(ServiceParams.MAXY, String.valueOf(maxXY[1])); double longitude = (lon != 0) ? lon : e1.getCenter().getX(); double latitude = (lat != 0) ? lat : e1.getCenter().getY(); params.putParam(ServiceParams.LON, String.valueOf(longitude)); params.putParam(ServiceParams.LAT, String.valueOf(latitude)); params.putParam(ServiceParams.FORMAT, "json"); params.putParam(ServiceParams.DIST, String.valueOf((int) distanceMeters)); params.putParam(ServiceParams.DISTKM, String.valueOf(Double.valueOf(distanceMeters) / 1000)); params.putParam(ServiceParams.KEY, describeService.getApiKey()); if (optionalParams != null) { String p; for (Param optParam : optionalParams) { //NO IDEA HOW CAN THIS BE NULL BUT IT IS HAPPENING if (optParam == null) { continue; } p = params.getServiceParamFromURLParam(optParam.getType()); if (p == null) { if (describeService.isEncodeUrl()) { try { params.putParam(p, URLEncoder.encode(optParam.getValue(), "UTF-8")); // depends on control dependency: [try], data = [none] } catch (UnsupportedEncodingException e) { logger.warn(e); } // depends on control dependency: [catch], data = [none] } else { params.putParam(optParam.getType(), optParam.getValue()); // depends on control dependency: [if], data = [none] } } else { if (describeService.isEncodeUrl()) { try { params.putParam(p, URLEncoder.encode(optParam.getValue(), "UTF-8")); // depends on control dependency: [try], data = [none] } catch (UnsupportedEncodingException e) { logger.warn(e); } // depends on control dependency: [catch], data = [none] } else { params.putParam(p, optParam.getValue()); // depends on control dependency: [if], data = [none] } } } } String url = describeService.getRequestForParam(optionalParams, params); Set<String> keys = params.getParams().keySet(); Iterator<String> it = keys.iterator(); String key; while (it.hasNext()) { key = it.next(); if (describeService.isSpecialParam(key)) { url = url.replaceAll(key, getValue(params, key, describeService)); } } return url; } }
public class class_name { protected DateFormat createFormatter(final Optional<XlsDateTimeConverter> converterAnno) { final boolean lenient = converterAnno.map(a -> a.lenient()).orElse(false); if(!converterAnno.isPresent()) { SimpleDateFormat formatter = new SimpleDateFormat(getDefaultJavaPattern()); formatter.setLenient(lenient); return formatter; } final String pattern = getJavaPattern(converterAnno); final Locale locale = Utils.getLocale(converterAnno.get().locale()); final TimeZone timeZone = converterAnno.get().timezone().isEmpty() ? TimeZone.getDefault() : TimeZone.getTimeZone(converterAnno.get().timezone()); final SimpleDateFormat formatter = new SimpleDateFormat(pattern, locale); formatter.setLenient(lenient); formatter.setTimeZone(timeZone); return formatter; } }
public class class_name { protected DateFormat createFormatter(final Optional<XlsDateTimeConverter> converterAnno) { final boolean lenient = converterAnno.map(a -> a.lenient()).orElse(false); if(!converterAnno.isPresent()) { SimpleDateFormat formatter = new SimpleDateFormat(getDefaultJavaPattern()); formatter.setLenient(lenient); // depends on control dependency: [if], data = [none] return formatter; // depends on control dependency: [if], data = [none] } final String pattern = getJavaPattern(converterAnno); final Locale locale = Utils.getLocale(converterAnno.get().locale()); final TimeZone timeZone = converterAnno.get().timezone().isEmpty() ? TimeZone.getDefault() : TimeZone.getTimeZone(converterAnno.get().timezone()); final SimpleDateFormat formatter = new SimpleDateFormat(pattern, locale); formatter.setLenient(lenient); formatter.setTimeZone(timeZone); return formatter; } }
public class class_name { protected boolean refreshFromSystem() { Lock lock = this.namespacesLock.writeLock(); try { lock.lock(); // Re-read and re-register all of the namespaces ... SessionCache systemCache = repository.createSystemSession(context, false); SystemContent system = new SystemContent(systemCache); Collection<Namespace> namespaces = system.readAllNamespaces(); if (namespaces.isEmpty()) return false; this.cache.clear(); this.cache.register(namespaces); } catch (Throwable e) { logger.error(e, JcrI18n.errorRefreshingNodeTypes, repository.name()); } finally { lock.unlock(); } return true; } }
public class class_name { protected boolean refreshFromSystem() { Lock lock = this.namespacesLock.writeLock(); try { lock.lock(); // depends on control dependency: [try], data = [none] // Re-read and re-register all of the namespaces ... SessionCache systemCache = repository.createSystemSession(context, false); SystemContent system = new SystemContent(systemCache); Collection<Namespace> namespaces = system.readAllNamespaces(); if (namespaces.isEmpty()) return false; this.cache.clear(); // depends on control dependency: [try], data = [none] this.cache.register(namespaces); // depends on control dependency: [try], data = [none] } catch (Throwable e) { logger.error(e, JcrI18n.errorRefreshingNodeTypes, repository.name()); } finally { // depends on control dependency: [catch], data = [none] lock.unlock(); } return true; } }
public class class_name { public void write( Object data, Map<String, Object> output, WalkedPath walkedPath ) { List<String> evaledPaths = evaluate( walkedPath ); if ( evaledPaths != null ) { traversr.set( output, evaledPaths, data ); } } }
public class class_name { public void write( Object data, Map<String, Object> output, WalkedPath walkedPath ) { List<String> evaledPaths = evaluate( walkedPath ); if ( evaledPaths != null ) { traversr.set( output, evaledPaths, data ); // depends on control dependency: [if], data = [none] } } }
public class class_name { public int controlledPoll(final ControlledFragmentHandler handler, final int fragmentLimit) { if (isClosed) { return 0; } int fragmentsRead = 0; long initialPosition = subscriberPosition.get(); int initialOffset = (int)initialPosition & termLengthMask; int resultingOffset = initialOffset; final UnsafeBuffer termBuffer = activeTermBuffer(initialPosition); final int capacity = termBuffer.capacity(); final Header header = this.header; header.buffer(termBuffer); try { while (fragmentsRead < fragmentLimit && resultingOffset < capacity) { final int length = frameLengthVolatile(termBuffer, resultingOffset); if (length <= 0) { break; } final int frameOffset = resultingOffset; final int alignedLength = BitUtil.align(length, FRAME_ALIGNMENT); resultingOffset += alignedLength; if (isPaddingFrame(termBuffer, frameOffset)) { continue; } header.offset(frameOffset); final Action action = handler.onFragment( termBuffer, frameOffset + HEADER_LENGTH, length - HEADER_LENGTH, header); if (action == ABORT) { resultingOffset -= alignedLength; break; } ++fragmentsRead; if (action == BREAK) { break; } else if (action == COMMIT) { initialPosition += (resultingOffset - initialOffset); initialOffset = resultingOffset; subscriberPosition.setOrdered(initialPosition); } } } catch (final Throwable t) { errorHandler.onError(t); } finally { final long resultingPosition = initialPosition + (resultingOffset - initialOffset); if (resultingPosition > initialPosition) { subscriberPosition.setOrdered(resultingPosition); } } return fragmentsRead; } }
public class class_name { public int controlledPoll(final ControlledFragmentHandler handler, final int fragmentLimit) { if (isClosed) { return 0; // depends on control dependency: [if], data = [none] } int fragmentsRead = 0; long initialPosition = subscriberPosition.get(); int initialOffset = (int)initialPosition & termLengthMask; int resultingOffset = initialOffset; final UnsafeBuffer termBuffer = activeTermBuffer(initialPosition); final int capacity = termBuffer.capacity(); final Header header = this.header; header.buffer(termBuffer); try { while (fragmentsRead < fragmentLimit && resultingOffset < capacity) { final int length = frameLengthVolatile(termBuffer, resultingOffset); if (length <= 0) { break; } final int frameOffset = resultingOffset; final int alignedLength = BitUtil.align(length, FRAME_ALIGNMENT); resultingOffset += alignedLength; // depends on control dependency: [while], data = [none] if (isPaddingFrame(termBuffer, frameOffset)) { continue; } header.offset(frameOffset); // depends on control dependency: [while], data = [none] final Action action = handler.onFragment( termBuffer, frameOffset + HEADER_LENGTH, length - HEADER_LENGTH, header); if (action == ABORT) { resultingOffset -= alignedLength; // depends on control dependency: [if], data = [none] break; } ++fragmentsRead; // depends on control dependency: [while], data = [none] if (action == BREAK) { break; } else if (action == COMMIT) { initialPosition += (resultingOffset - initialOffset); // depends on control dependency: [if], data = [none] initialOffset = resultingOffset; // depends on control dependency: [if], data = [none] subscriberPosition.setOrdered(initialPosition); // depends on control dependency: [if], data = [none] } } } catch (final Throwable t) { errorHandler.onError(t); } // depends on control dependency: [catch], data = [none] finally { final long resultingPosition = initialPosition + (resultingOffset - initialOffset); if (resultingPosition > initialPosition) { subscriberPosition.setOrdered(resultingPosition); // depends on control dependency: [if], data = [(resultingPosition] } } return fragmentsRead; } }
public class class_name { @Override public void execute(final Object context, int uiTaskId, final Object... args) { Activity activity = ContextUtils.asActivity(context); Set<Method> methods = MethodUtils.getAllMethods(context, UI.class); for (final Method method : methods) { final UI uiTask = method.getAnnotation(UI.class); if(uiTask.value() == uiTaskId) { final Runnable runnable = new Runnable() { @Override public void run() { try { if(!method.isAccessible()) method.setAccessible(true); method.invoke(context, args); } catch (Exception e) { StringBuilder stringBuilder = new StringBuilder() .append("Failed to execute UI task ") .append(method.getName()) .append(" on ") .append(context.getClass().getName()) .append(" with arguments ") .append(Arrays.toString(args)) .append(". "); Log.e(UITaskService.class.getName(), stringBuilder.toString(), e); } } }; if(uiTask.delay() > 0l) { try { Thread.sleep(uiTask.delay()); } catch (InterruptedException ie) { StringBuilder stringBuilder = new StringBuilder() .append("UI task delay of ") .append(uiTask.delay()) .append(" for ") .append(method.getName()) .append(" on ") .append(context.getClass().getName()) .append(" was interrupted!"); Log.e(getClass().getSimpleName(), stringBuilder.toString(), ie); } } activity.runOnUiThread(runnable); break; } } } }
public class class_name { @Override public void execute(final Object context, int uiTaskId, final Object... args) { Activity activity = ContextUtils.asActivity(context); Set<Method> methods = MethodUtils.getAllMethods(context, UI.class); for (final Method method : methods) { final UI uiTask = method.getAnnotation(UI.class); if(uiTask.value() == uiTaskId) { final Runnable runnable = new Runnable() { @Override public void run() { try { if(!method.isAccessible()) method.setAccessible(true); method.invoke(context, args); // depends on control dependency: [try], data = [none] } catch (Exception e) { StringBuilder stringBuilder = new StringBuilder() .append("Failed to execute UI task ") .append(method.getName()) .append(" on ") .append(context.getClass().getName()) .append(" with arguments ") .append(Arrays.toString(args)) .append(". "); Log.e(UITaskService.class.getName(), stringBuilder.toString(), e); } // depends on control dependency: [catch], data = [none] } }; if(uiTask.delay() > 0l) { try { Thread.sleep(uiTask.delay()); // depends on control dependency: [try], data = [none] } catch (InterruptedException ie) { StringBuilder stringBuilder = new StringBuilder() .append("UI task delay of ") .append(uiTask.delay()) .append(" for ") .append(method.getName()) .append(" on ") .append(context.getClass().getName()) .append(" was interrupted!"); Log.e(getClass().getSimpleName(), stringBuilder.toString(), ie); } // depends on control dependency: [catch], data = [none] } activity.runOnUiThread(runnable); // depends on control dependency: [if], data = [none] break; } } } }
public class class_name { public static ApproximateHistogram fromBytes(ByteBuffer buf) { // negative size indicates compact representation // this works regardless of whether we use int or short for the size since the leftmost bit is the sign bit if (buf.getShort(buf.position()) < 0) { return fromBytesCompact(buf); } else { // ignore size, determine if sparse or dense based on sign of binCount if (buf.getInt(buf.position() + Integer.BYTES) < 0) { return fromBytesSparse(buf); } else { return fromBytesDense(buf); } } } }
public class class_name { public static ApproximateHistogram fromBytes(ByteBuffer buf) { // negative size indicates compact representation // this works regardless of whether we use int or short for the size since the leftmost bit is the sign bit if (buf.getShort(buf.position()) < 0) { return fromBytesCompact(buf); // depends on control dependency: [if], data = [none] } else { // ignore size, determine if sparse or dense based on sign of binCount if (buf.getInt(buf.position() + Integer.BYTES) < 0) { return fromBytesSparse(buf); // depends on control dependency: [if], data = [none] } else { return fromBytesDense(buf); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static String escapeJava(final String string) { int strLen = string.length(); StringBuilder sb = new StringBuilder(strLen); for (int i = 0; i < strLen; i++) { char c = string.charAt(i); switch (c) { case '\b' : sb.append("\\b"); break; case '\t' : sb.append("\\t"); break; case '\n' : sb.append("\\n"); break; case '\f' : sb.append("\\f"); break; case '\r' : sb.append("\\r"); break; case '\"' : sb.append("\\\""); break; case '\\' : sb.append("\\\\"); break; default: if ((c < 32) || (c > 127)) { String hex = Integer.toHexString(c); sb.append("\\u"); for (int k = hex.length(); k < 4; k++) { sb.append('0'); } sb.append(hex); } else { sb.append(c); } } } return sb.toString(); } }
public class class_name { public static String escapeJava(final String string) { int strLen = string.length(); StringBuilder sb = new StringBuilder(strLen); for (int i = 0; i < strLen; i++) { char c = string.charAt(i); switch (c) { case '\b' : sb.append("\\b"); break; case '\t' : sb.append("\\t"); break; case '\n' : sb.append("\\n"); break; case '\f' : sb.append("\\f"); break; case '\r' : sb.append("\\r"); break; case '\"' : sb.append("\\\""); break; case '\\' : sb.append("\\\\"); break; default: if ((c < 32) || (c > 127)) { String hex = Integer.toHexString(c); sb.append("\\u"); // depends on control dependency: [if], data = [none] for (int k = hex.length(); k < 4; k++) { sb.append('0'); // depends on control dependency: [for], data = [none] } sb.append(hex); // depends on control dependency: [if], data = [none] } else { sb.append(c); // depends on control dependency: [if], data = [none] } } } return sb.toString(); } }
public class class_name { @Override public Future<?> submit(Runnable task) { try { if (this.concurrentExecutor instanceof ExecutorService) { return ((ExecutorService) this.concurrentExecutor).submit(task); } else { FutureTask<Object> future = new FutureTask<Object>(task, null); this.concurrentExecutor.execute(future); return future; } } catch (RejectedExecutionException ex) { throw new TaskRejectedException("Executor [" + this.concurrentExecutor + "] did not accept task: " + task, ex); } } }
public class class_name { @Override public Future<?> submit(Runnable task) { try { if (this.concurrentExecutor instanceof ExecutorService) { return ((ExecutorService) this.concurrentExecutor).submit(task); // depends on control dependency: [if], data = [none] } else { FutureTask<Object> future = new FutureTask<Object>(task, null); this.concurrentExecutor.execute(future); // depends on control dependency: [if], data = [none] return future; // depends on control dependency: [if], data = [none] } } catch (RejectedExecutionException ex) { throw new TaskRejectedException("Executor [" + this.concurrentExecutor + "] did not accept task: " + task, ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected boolean doesTopicMatch(final SpecTopic specTopic, final CSNodeWrapper node, boolean matchTypes) { if (!EntityUtilities.isNodeATopic(node)) return false; // Check if the node/topic type matches if (matchTypes) { boolean matches = true; switch (specTopic.getTopicType()) { case INITIAL_CONTENT: matches = node.getNodeType().equals(CommonConstants.CS_NODE_INITIAL_CONTENT_TOPIC); break; case NORMAL: matches = node.getNodeType().equals(CommonConstants.CS_NODE_TOPIC); break; case FEEDBACK: case LEGAL_NOTICE: case REVISION_HISTORY: case AUTHOR_GROUP: case ABSTRACT: matches = node.getNodeType().equals(CommonConstants.CS_NODE_META_DATA_TOPIC); break; } if (!matches) { return false; } } // If the unique id is not from the parser, in which case it will start with a number than use the unique id to compare if (specTopic.getUniqueId() != null && specTopic.getUniqueId().matches("^\\d.*")) { return specTopic.getUniqueId().equals(Integer.toString(node.getId())); } else { // Check the parent has the same name if (specTopic.getParent() != null && node.getParent() != null && node.getParent() instanceof Level) { if (!((Level) specTopic.getParent()).getTitle().equals(node.getParent().getTitle())) { return false; } } // Since a content spec doesn't contain the database ids for the nodes use what is available to see if the topics match return specTopic.getDBId().equals(node.getEntityId()); } } }
public class class_name { protected boolean doesTopicMatch(final SpecTopic specTopic, final CSNodeWrapper node, boolean matchTypes) { if (!EntityUtilities.isNodeATopic(node)) return false; // Check if the node/topic type matches if (matchTypes) { boolean matches = true; switch (specTopic.getTopicType()) { case INITIAL_CONTENT: matches = node.getNodeType().equals(CommonConstants.CS_NODE_INITIAL_CONTENT_TOPIC); break; case NORMAL: matches = node.getNodeType().equals(CommonConstants.CS_NODE_TOPIC); break; case FEEDBACK: case LEGAL_NOTICE: case REVISION_HISTORY: case AUTHOR_GROUP: case ABSTRACT: matches = node.getNodeType().equals(CommonConstants.CS_NODE_META_DATA_TOPIC); break; } if (!matches) { return false; // depends on control dependency: [if], data = [none] } } // If the unique id is not from the parser, in which case it will start with a number than use the unique id to compare if (specTopic.getUniqueId() != null && specTopic.getUniqueId().matches("^\\d.*")) { return specTopic.getUniqueId().equals(Integer.toString(node.getId())); } else { // Check the parent has the same name if (specTopic.getParent() != null && node.getParent() != null && node.getParent() instanceof Level) { if (!((Level) specTopic.getParent()).getTitle().equals(node.getParent().getTitle())) { return false; // depends on control dependency: [if], data = [none] } } // Since a content spec doesn't contain the database ids for the nodes use what is available to see if the topics match return specTopic.getDBId().equals(node.getEntityId()); } } }
public class class_name { private boolean isIgnoredType(Class<?> pReturnType) { for (Class<?> type : IGNORED_RETURN_TYPES) { if (type.isAssignableFrom(pReturnType)) { return true; } } return false; } }
public class class_name { private boolean isIgnoredType(Class<?> pReturnType) { for (Class<?> type : IGNORED_RETURN_TYPES) { if (type.isAssignableFrom(pReturnType)) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { protected void setObject(Object obj) { if (obj instanceof NodeVector) { // Keep our superclass informed of the current NodeVector // ... if we don't the smoketest fails (don't know why). super.setObject(obj); // A copy of the code of what SetVector() would do. NodeVector v = (NodeVector)obj; if (m_cache != null) { m_cache.setVector(v); } else if (v!=null) { m_cache = new IteratorCache(); m_cache.setVector(v); } } else if (obj instanceof IteratorCache) { IteratorCache cache = (IteratorCache) obj; m_cache = cache; m_cache.increaseUseCount(); // Keep our superclass informed of the current NodeVector super.setObject(cache.getVector()); } else { super.setObject(obj); } } }
public class class_name { protected void setObject(Object obj) { if (obj instanceof NodeVector) { // Keep our superclass informed of the current NodeVector // ... if we don't the smoketest fails (don't know why). super.setObject(obj); // depends on control dependency: [if], data = [none] // A copy of the code of what SetVector() would do. NodeVector v = (NodeVector)obj; if (m_cache != null) { m_cache.setVector(v); // depends on control dependency: [if], data = [none] } else if (v!=null) { m_cache = new IteratorCache(); // depends on control dependency: [if], data = [none] m_cache.setVector(v); // depends on control dependency: [if], data = [(v] } } else if (obj instanceof IteratorCache) { IteratorCache cache = (IteratorCache) obj; m_cache = cache; // depends on control dependency: [if], data = [none] m_cache.increaseUseCount(); // depends on control dependency: [if], data = [none] // Keep our superclass informed of the current NodeVector super.setObject(cache.getVector()); // depends on control dependency: [if], data = [none] } else { super.setObject(obj); // depends on control dependency: [if], data = [none] } } }
public class class_name { public double getValueAtAsDouble(final int row, final int col) { final Object valueAt = getValueAt(row, col); double number = 0; if (valueAt != null && !valueAt.toString().equals("")) { number = Double.parseDouble(valueAt.toString().trim()); } return number; } }
public class class_name { public double getValueAtAsDouble(final int row, final int col) { final Object valueAt = getValueAt(row, col); double number = 0; if (valueAt != null && !valueAt.toString().equals("")) { number = Double.parseDouble(valueAt.toString().trim()); // depends on control dependency: [if], data = [(valueAt] } return number; } }
public class class_name { public static ApproximateHistogram fromBytesSparse(ByteBuffer buf) { int size = buf.getInt(); int binCount = -1 * buf.getInt(); float[] positions = new float[size]; long[] bins = new long[size]; for (int i = 0; i < binCount; ++i) { positions[i] = buf.getFloat(); } for (int i = 0; i < binCount; ++i) { bins[i] = buf.getLong(); } float min = buf.getFloat(); float max = buf.getFloat(); return new ApproximateHistogram(binCount, positions, bins, min, max); } }
public class class_name { public static ApproximateHistogram fromBytesSparse(ByteBuffer buf) { int size = buf.getInt(); int binCount = -1 * buf.getInt(); float[] positions = new float[size]; long[] bins = new long[size]; for (int i = 0; i < binCount; ++i) { positions[i] = buf.getFloat(); // depends on control dependency: [for], data = [i] } for (int i = 0; i < binCount; ++i) { bins[i] = buf.getLong(); // depends on control dependency: [for], data = [i] } float min = buf.getFloat(); float max = buf.getFloat(); return new ApproximateHistogram(binCount, positions, bins, min, max); } }
public class class_name { public List<com.ibm.wsspi.security.wim.model.Entity> getEntities() { if (entities == null) { entities = new ArrayList<com.ibm.wsspi.security.wim.model.Entity>(); } return this.entities; } }
public class class_name { public List<com.ibm.wsspi.security.wim.model.Entity> getEntities() { if (entities == null) { entities = new ArrayList<com.ibm.wsspi.security.wim.model.Entity>(); // depends on control dependency: [if], data = [none] } return this.entities; } }
public class class_name { @OverridingMethodsMustInvokeSuper protected void setDefaultDerivedValues () { if (m_sReceiverAS2KeyAlias == null) { // No key alias is specified, so use the same as the receiver ID (which // may be null) m_sReceiverAS2KeyAlias = m_sReceiverAS2ID; if (LOGGER.isDebugEnabled ()) LOGGER.debug ("The receiver AS2 key alias was defaulted to the AS2 receiver ID ('" + m_sReceiverAS2ID + "')"); } } }
public class class_name { @OverridingMethodsMustInvokeSuper protected void setDefaultDerivedValues () { if (m_sReceiverAS2KeyAlias == null) { // No key alias is specified, so use the same as the receiver ID (which // may be null) m_sReceiverAS2KeyAlias = m_sReceiverAS2ID; // depends on control dependency: [if], data = [none] if (LOGGER.isDebugEnabled ()) LOGGER.debug ("The receiver AS2 key alias was defaulted to the AS2 receiver ID ('" + m_sReceiverAS2ID + "')"); } } }
public class class_name { private void loadAndCheckPropertyFile() { final String methodName = "loadAndCheckPropertyFile()"; final File f = new File(htodPropertyFileName); final File swapDirPathFile = new File(swapDirPath); final CacheOnDisk cod = this; traceDebug(methodName, "cacheName=" + this.cacheName); AccessController.doPrivileged(new PrivilegedAction() { public Object run() { cod.propertyFileStatus = PROPERTY_FILE_OK; String[] files = swapDirPathFile.list(); if (files != null && files.length > 0) { for (int i = 0; i < files.length; i++) { if (files[i].startsWith(HTOD_PREF + HTODDynacache.object_suffix)) { cod.dataFiles++; } else if (files[i].startsWith(HTOD_PREF + HTODDynacache.dependency_suffix)) { cod.dependencyIdFiles++; } else if (files[i].startsWith(HTOD_PREF + HTODDynacache.template_suffix)) { cod.templateFiles++; } } } else { traceDebug(methodName, "cacheName=" + cod.cacheName + " no disk cache files exist"); cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_NO_FILES); return null; } if (f.exists()) { FileInputStream fis = null; try { fis = new FileInputStream(f); Properties htodProp = new Properties(); htodProp.load(fis); String sTemp = (String) htodProp.get(DISABLE_DEPENDENCY_ID); if (sTemp != null) { cod.disableDependencyIdFromPropertyFile = (Boolean.valueOf(sTemp)).booleanValue(); } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_DISABLE_DEPID); } sTemp = (String) htodProp.get(DISABLE_TEMPLATE_SUPPORT); if (sTemp != null) { cod.disableTemplatesSupprotFromPropertyFile = (Boolean.valueOf(sTemp)).booleanValue(); } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_DISABLE_TEMPLATE); } sTemp = (String) htodProp.get(CACHE_SIZE_IN_BYTES); long currentCacheSizeInBytes = 0; if (sTemp != null) { currentCacheSizeInBytes = Long.parseLong(sTemp); } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_CACHE_SIZE); return null; } byte[] b = sTemp.getBytes("UTF-8"); int fieldCheck = 0; for (int i = 0; i < b.length; i++) { fieldCheck += (int) b[i]; } fieldCheck = fieldCheck * 3; sTemp = (String) htodProp.get(FIELD_CHECK); if (sTemp != null) { int expFieldCheck = Integer.parseInt(sTemp); if (fieldCheck != expFieldCheck) { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_FIELD_CHECK); return null; } } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_FIELD_CHECK); return null; } sTemp = (String) htodProp.get(DATA_GB); int dataGB = 0; if (sTemp != null) { dataGB = Integer.parseInt(sTemp); } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_GB); return null; } sTemp = (String) htodProp.get(DEPID_GB); int dependencyIdGB = 0; if (sTemp != null) { dependencyIdGB = Integer.parseInt(sTemp); } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_GB); return null; } sTemp = (String) htodProp.get(TEMPLATE_GB); int templateGB = 0; if (sTemp != null) { templateGB = Integer.parseInt(sTemp); } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_GB); return null; } cod.currentCacheSizeInBytes = currentCacheSizeInBytes; cod.dataGB = dataGB; cod.dependencyIdGB = dependencyIdGB; cod.templateGB = templateGB; traceDebug(methodName, "cacheName=" + cod.cacheName + " htod.properties exist with status=" + cod.propertyFileStatus + " disableDependencyIdFromProperty=" + cod.disableDependencyIdFromPropertyFile + " disableTemplatesSupportFromProperty=" + cod.disableTemplatesSupprotFromPropertyFile + " cacheSizeInBytes=" + cod.currentCacheSizeInBytes + " dataGB=" + cod.dataGB + " dependencyIdGB=" + cod.dependencyIdGB + " templateGB=" + cod.templateGB); } catch (Throwable t) { com.ibm.ws.ffdc.FFDCFilter.processException(t, "com.ibm.ws.cache.CacheOnDisk.loadAndCheckPropertyFile", "782", cod); traceDebug(methodName, "cacheName=" + cod.cacheName + "\nException: " + ExceptionUtility.getStackTrace(t)); cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_FILE_CORRUPT); } finally { try { if (fis != null) { fis.close(); } } catch (Throwable t) { com.ibm.ws.ffdc.FFDCFilter.processException(t, "com.ibm.ws.cache.CacheOnDisk.loadAndCheckPropertyFile", "791", cod); traceDebug(methodName, "cacheName=" + cod.cacheName + "\nException: " + ExceptionUtility.getStackTrace(t)); } } } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_FILE_NOT_EXIST); traceDebug(methodName, "cacheName=" + cod.cacheName + " htod.properties not exist" + " dependencyIdFiles=" + cod.dependencyIdFiles + " templateFiles=" + cod.templateFiles); } return null; } }); } }
public class class_name { private void loadAndCheckPropertyFile() { final String methodName = "loadAndCheckPropertyFile()"; final File f = new File(htodPropertyFileName); final File swapDirPathFile = new File(swapDirPath); final CacheOnDisk cod = this; traceDebug(methodName, "cacheName=" + this.cacheName); AccessController.doPrivileged(new PrivilegedAction() { public Object run() { cod.propertyFileStatus = PROPERTY_FILE_OK; String[] files = swapDirPathFile.list(); if (files != null && files.length > 0) { for (int i = 0; i < files.length; i++) { if (files[i].startsWith(HTOD_PREF + HTODDynacache.object_suffix)) { cod.dataFiles++; // depends on control dependency: [if], data = [none] } else if (files[i].startsWith(HTOD_PREF + HTODDynacache.dependency_suffix)) { cod.dependencyIdFiles++; // depends on control dependency: [if], data = [none] } else if (files[i].startsWith(HTOD_PREF + HTODDynacache.template_suffix)) { cod.templateFiles++; // depends on control dependency: [if], data = [none] } } } else { traceDebug(methodName, "cacheName=" + cod.cacheName + " no disk cache files exist"); // depends on control dependency: [if], data = [none] cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_NO_FILES); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } if (f.exists()) { FileInputStream fis = null; try { fis = new FileInputStream(f); // depends on control dependency: [try], data = [none] Properties htodProp = new Properties(); htodProp.load(fis); // depends on control dependency: [try], data = [none] String sTemp = (String) htodProp.get(DISABLE_DEPENDENCY_ID); if (sTemp != null) { cod.disableDependencyIdFromPropertyFile = (Boolean.valueOf(sTemp)).booleanValue(); // depends on control dependency: [if], data = [(sTemp] } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_DISABLE_DEPID); // depends on control dependency: [if], data = [none] } sTemp = (String) htodProp.get(DISABLE_TEMPLATE_SUPPORT); // depends on control dependency: [try], data = [none] if (sTemp != null) { cod.disableTemplatesSupprotFromPropertyFile = (Boolean.valueOf(sTemp)).booleanValue(); // depends on control dependency: [if], data = [(sTemp] } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_DISABLE_TEMPLATE); // depends on control dependency: [if], data = [none] } sTemp = (String) htodProp.get(CACHE_SIZE_IN_BYTES); // depends on control dependency: [try], data = [none] long currentCacheSizeInBytes = 0; if (sTemp != null) { currentCacheSizeInBytes = Long.parseLong(sTemp); // depends on control dependency: [if], data = [(sTemp] } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_CACHE_SIZE); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } byte[] b = sTemp.getBytes("UTF-8"); int fieldCheck = 0; for (int i = 0; i < b.length; i++) { fieldCheck += (int) b[i]; // depends on control dependency: [for], data = [i] } fieldCheck = fieldCheck * 3; // depends on control dependency: [try], data = [none] sTemp = (String) htodProp.get(FIELD_CHECK); // depends on control dependency: [try], data = [none] if (sTemp != null) { int expFieldCheck = Integer.parseInt(sTemp); if (fieldCheck != expFieldCheck) { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_FIELD_CHECK); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_FIELD_CHECK); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } sTemp = (String) htodProp.get(DATA_GB); // depends on control dependency: [try], data = [none] int dataGB = 0; if (sTemp != null) { dataGB = Integer.parseInt(sTemp); // depends on control dependency: [if], data = [(sTemp] } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_GB); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } sTemp = (String) htodProp.get(DEPID_GB); // depends on control dependency: [try], data = [none] int dependencyIdGB = 0; if (sTemp != null) { dependencyIdGB = Integer.parseInt(sTemp); // depends on control dependency: [if], data = [(sTemp] } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_GB); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } sTemp = (String) htodProp.get(TEMPLATE_GB); // depends on control dependency: [try], data = [none] int templateGB = 0; if (sTemp != null) { templateGB = Integer.parseInt(sTemp); // depends on control dependency: [if], data = [(sTemp] } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_GB); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } cod.currentCacheSizeInBytes = currentCacheSizeInBytes; // depends on control dependency: [try], data = [none] cod.dataGB = dataGB; // depends on control dependency: [try], data = [none] cod.dependencyIdGB = dependencyIdGB; // depends on control dependency: [try], data = [none] cod.templateGB = templateGB; // depends on control dependency: [try], data = [none] traceDebug(methodName, "cacheName=" + cod.cacheName + " htod.properties exist with status=" + cod.propertyFileStatus + " disableDependencyIdFromProperty=" + cod.disableDependencyIdFromPropertyFile + " disableTemplatesSupportFromProperty=" + cod.disableTemplatesSupprotFromPropertyFile + " cacheSizeInBytes=" + cod.currentCacheSizeInBytes + " dataGB=" + cod.dataGB + " dependencyIdGB=" + cod.dependencyIdGB + " templateGB=" + cod.templateGB); // depends on control dependency: [try], data = [none] } catch (Throwable t) { com.ibm.ws.ffdc.FFDCFilter.processException(t, "com.ibm.ws.cache.CacheOnDisk.loadAndCheckPropertyFile", "782", cod); traceDebug(methodName, "cacheName=" + cod.cacheName + "\nException: " + ExceptionUtility.getStackTrace(t)); cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_FILE_CORRUPT); } finally { // depends on control dependency: [catch], data = [none] try { if (fis != null) { fis.close(); // depends on control dependency: [if], data = [none] } } catch (Throwable t) { com.ibm.ws.ffdc.FFDCFilter.processException(t, "com.ibm.ws.cache.CacheOnDisk.loadAndCheckPropertyFile", "791", cod); traceDebug(methodName, "cacheName=" + cod.cacheName + "\nException: " + ExceptionUtility.getStackTrace(t)); } // depends on control dependency: [catch], data = [none] } } else { cod.propertyFileStatus = (byte) (cod.propertyFileStatus | PROPERTY_ERROR_FILE_NOT_EXIST); // depends on control dependency: [if], data = [none] traceDebug(methodName, "cacheName=" + cod.cacheName + " htod.properties not exist" + " dependencyIdFiles=" + cod.dependencyIdFiles + " templateFiles=" + cod.templateFiles); // depends on control dependency: [if], data = [none] } return null; } }); } }
public class class_name { public static String cat (Object... components) { StringBuilder stringBuilder = new StringBuilder (); if (components.length > 0) { stringBuilder.append (components[0]); for (int i = 1; i < components.length; ++i) { stringBuilder.append (BagObject.PATH_SEPARATOR).append (components[i].toString ()); } } return stringBuilder.toString (); } }
public class class_name { public static String cat (Object... components) { StringBuilder stringBuilder = new StringBuilder (); if (components.length > 0) { stringBuilder.append (components[0]); // depends on control dependency: [if], data = [none] for (int i = 1; i < components.length; ++i) { stringBuilder.append (BagObject.PATH_SEPARATOR).append (components[i].toString ()); // depends on control dependency: [for], data = [i] } } return stringBuilder.toString (); } }
public class class_name { public List<FacesConfigFlowDefinitionFlowReturnType<FacesConfigFlowDefinitionType<T>>> getAllFlowReturn() { List<FacesConfigFlowDefinitionFlowReturnType<FacesConfigFlowDefinitionType<T>>> list = new ArrayList<FacesConfigFlowDefinitionFlowReturnType<FacesConfigFlowDefinitionType<T>>>(); List<Node> nodeList = childNode.get("flow-return"); for(Node node: nodeList) { FacesConfigFlowDefinitionFlowReturnType<FacesConfigFlowDefinitionType<T>> type = new FacesConfigFlowDefinitionFlowReturnTypeImpl<FacesConfigFlowDefinitionType<T>>(this, "flow-return", childNode, node); list.add(type); } return list; } }
public class class_name { public List<FacesConfigFlowDefinitionFlowReturnType<FacesConfigFlowDefinitionType<T>>> getAllFlowReturn() { List<FacesConfigFlowDefinitionFlowReturnType<FacesConfigFlowDefinitionType<T>>> list = new ArrayList<FacesConfigFlowDefinitionFlowReturnType<FacesConfigFlowDefinitionType<T>>>(); List<Node> nodeList = childNode.get("flow-return"); for(Node node: nodeList) { FacesConfigFlowDefinitionFlowReturnType<FacesConfigFlowDefinitionType<T>> type = new FacesConfigFlowDefinitionFlowReturnTypeImpl<FacesConfigFlowDefinitionType<T>>(this, "flow-return", childNode, node); list.add(type); // depends on control dependency: [for], data = [none] } return list; } }
public class class_name { private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern) { float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.getX(), (int) pattern.getY(), (int) otherPattern.getX(), (int) otherPattern.getY()); float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int) otherPattern.getX(), (int) otherPattern.getY(), (int) pattern.getX(), (int) pattern.getY()); if (Float.isNaN(moduleSizeEst1)) { return moduleSizeEst2 / 7.0f; } if (Float.isNaN(moduleSizeEst2)) { return moduleSizeEst1 / 7.0f; } // Average them, and divide by 7 since we've counted the width of 3 black modules, // and 1 white and 1 black module on either side. Ergo, divide sum by 14. return (moduleSizeEst1 + moduleSizeEst2) / 14.0f; } }
public class class_name { private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern) { float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.getX(), (int) pattern.getY(), (int) otherPattern.getX(), (int) otherPattern.getY()); float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int) otherPattern.getX(), (int) otherPattern.getY(), (int) pattern.getX(), (int) pattern.getY()); if (Float.isNaN(moduleSizeEst1)) { return moduleSizeEst2 / 7.0f; // depends on control dependency: [if], data = [none] } if (Float.isNaN(moduleSizeEst2)) { return moduleSizeEst1 / 7.0f; // depends on control dependency: [if], data = [none] } // Average them, and divide by 7 since we've counted the width of 3 black modules, // and 1 white and 1 black module on either side. Ergo, divide sum by 14. return (moduleSizeEst1 + moduleSizeEst2) / 14.0f; } }
public class class_name { @Override public void create() { if (!environment.isProd()) { config.serverConfigs().forEach((key, serverConfig) -> { String evolutionScript = generateEvolutionScript(servers.get(key)); if (evolutionScript != null) { File evolutions = environment.getFile("conf/evolutions/" + key + "/1.sql"); try { String content = ""; if (evolutions.exists()) { content = new String(Files.readAllBytes(evolutions.toPath()), "utf-8"); } if (content.isEmpty() || content.startsWith("# --- Created by Ebean DDL")) { environment.getFile("conf/evolutions/" + key).mkdirs(); if (!content.equals(evolutionScript)) { Files.write(evolutions.toPath(), evolutionScript.getBytes("utf-8")); } } } catch (IOException e) { throw new RuntimeException(e); } } }); } } }
public class class_name { @Override public void create() { if (!environment.isProd()) { config.serverConfigs().forEach((key, serverConfig) -> { String evolutionScript = generateEvolutionScript(servers.get(key)); if (evolutionScript != null) { File evolutions = environment.getFile("conf/evolutions/" + key + "/1.sql"); try { String content = ""; if (evolutions.exists()) { content = new String(Files.readAllBytes(evolutions.toPath()), "utf-8"); // depends on control dependency: [if], data = [none] } if (content.isEmpty() || content.startsWith("# --- Created by Ebean DDL")) { environment.getFile("conf/evolutions/" + key).mkdirs(); // depends on control dependency: [if], data = [none] if (!content.equals(evolutionScript)) { Files.write(evolutions.toPath(), evolutionScript.getBytes("utf-8")); // depends on control dependency: [if], data = [none] } } } catch (IOException e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] } }); } } }
public class class_name { public long getSecondsUntilExpiry(Sha256Hash id) { lock.lock(); try { final Set<StoredClientChannel> setChannels = mapChannels.get(id); final long nowSeconds = Utils.currentTimeSeconds(); int earliestTime = Integer.MAX_VALUE; for (StoredClientChannel channel : setChannels) { synchronized (channel) { if (channel.expiryTimeSeconds() > nowSeconds) earliestTime = Math.min(earliestTime, (int) channel.expiryTimeSeconds()); } } return earliestTime == Integer.MAX_VALUE ? 0 : earliestTime - nowSeconds; } finally { lock.unlock(); } } }
public class class_name { public long getSecondsUntilExpiry(Sha256Hash id) { lock.lock(); try { final Set<StoredClientChannel> setChannels = mapChannels.get(id); final long nowSeconds = Utils.currentTimeSeconds(); int earliestTime = Integer.MAX_VALUE; for (StoredClientChannel channel : setChannels) { synchronized (channel) { // depends on control dependency: [for], data = [channel] if (channel.expiryTimeSeconds() > nowSeconds) earliestTime = Math.min(earliestTime, (int) channel.expiryTimeSeconds()); } } return earliestTime == Integer.MAX_VALUE ? 0 : earliestTime - nowSeconds; // depends on control dependency: [try], data = [none] } finally { lock.unlock(); } } }
public class class_name { private static char next(String glob, int i) { if (i < glob.length()) { return glob.charAt(i); } return EOL; } }
public class class_name { private static char next(String glob, int i) { if (i < glob.length()) { return glob.charAt(i); // depends on control dependency: [if], data = [(i] } return EOL; } }