code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public static DenseTensor copyOf(Tensor tensor) { if (tensor instanceof DenseTensor) { // Tensors are immutable, so there's no reason to copy the input. return (DenseTensor) tensor; } else { DenseTensorBuilder builder = new DenseTensorBuilder(tensor.getDimensionNumbers(), tensor.getDimensionSizes()); double[] otherValues = tensor.getValues(); for (int i = 0; i < otherValues.length; i++) { builder.putByKeyNum(tensor.indexToKeyNum(i), otherValues[i]); } return builder.buildNoCopy(); } } }
public class class_name { public static DenseTensor copyOf(Tensor tensor) { if (tensor instanceof DenseTensor) { // Tensors are immutable, so there's no reason to copy the input. return (DenseTensor) tensor; // depends on control dependency: [if], data = [none] } else { DenseTensorBuilder builder = new DenseTensorBuilder(tensor.getDimensionNumbers(), tensor.getDimensionSizes()); double[] otherValues = tensor.getValues(); for (int i = 0; i < otherValues.length; i++) { builder.putByKeyNum(tensor.indexToKeyNum(i), otherValues[i]); // depends on control dependency: [for], data = [i] } return builder.buildNoCopy(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void feedRequest(final CrawlRequest request, final boolean isCrawlSeed) { if (config.isOffsiteRequestFilteringEnabled()) { boolean inCrawlDomain = false; for (CrawlDomain allowedCrawlDomain : config.getAllowedCrawlDomains()) { if (allowedCrawlDomain.contains(request.getDomain())) { inCrawlDomain = true; break; } } if (!inCrawlDomain) { return; } } if (config.isDuplicateRequestFilteringEnabled()) { String urlFingerprint = createFingerprintForUrl(request.getRequestUrl()); if (urlFingerprints.contains(urlFingerprint)) { return; } urlFingerprints.add(urlFingerprint); } CrawlCandidateBuilder builder = new CrawlCandidateBuilder(request); if (!isCrawlSeed) { int crawlDepthLimit = config.getMaximumCrawlDepth(); int nextCrawlDepth = currentCandidate.getCrawlDepth() + 1; if (crawlDepthLimit != 0 && nextCrawlDepth > crawlDepthLimit) { return; } builder = builder .setRefererUrl(currentCandidate.getRequestUrl()) .setCrawlDepth(nextCrawlDepth); } candidates.add(builder.build()); } }
public class class_name { public void feedRequest(final CrawlRequest request, final boolean isCrawlSeed) { if (config.isOffsiteRequestFilteringEnabled()) { boolean inCrawlDomain = false; for (CrawlDomain allowedCrawlDomain : config.getAllowedCrawlDomains()) { if (allowedCrawlDomain.contains(request.getDomain())) { inCrawlDomain = true; // depends on control dependency: [if], data = [none] break; } } if (!inCrawlDomain) { return; // depends on control dependency: [if], data = [none] } } if (config.isDuplicateRequestFilteringEnabled()) { String urlFingerprint = createFingerprintForUrl(request.getRequestUrl()); if (urlFingerprints.contains(urlFingerprint)) { return; // depends on control dependency: [if], data = [none] } urlFingerprints.add(urlFingerprint); // depends on control dependency: [if], data = [none] } CrawlCandidateBuilder builder = new CrawlCandidateBuilder(request); if (!isCrawlSeed) { int crawlDepthLimit = config.getMaximumCrawlDepth(); int nextCrawlDepth = currentCandidate.getCrawlDepth() + 1; if (crawlDepthLimit != 0 && nextCrawlDepth > crawlDepthLimit) { return; // depends on control dependency: [if], data = [none] } builder = builder .setRefererUrl(currentCandidate.getRequestUrl()) .setCrawlDepth(nextCrawlDepth); // depends on control dependency: [if], data = [none] } candidates.add(builder.build()); } }
public class class_name { private Optional<ArrayLabelSetter> createField(final Class<?> beanClass, final String fieldName) { final String labelFieldName = fieldName + "Label"; final Field labelField; try { labelField = beanClass.getDeclaredField(labelFieldName); labelField.setAccessible(true); } catch (NoSuchFieldException | SecurityException e) { return Optional.empty(); } if(!List.class.isAssignableFrom(labelField.getType())) { return Optional.empty(); } final ParameterizedType type = (ParameterizedType) labelField.getGenericType(); final Class<?> valueType = (Class<?>) type.getActualTypeArguments()[0]; if(valueType.equals(String.class)) { return Optional.of(new ArrayLabelSetter() { @SuppressWarnings("unchecked") @Override public void set(final Object beanObj, final String label, final int index) { ArgUtils.notNull(beanObj, "beanObj"); ArgUtils.notEmpty(label, "label"); try { List<String> labelListObj = (List<String>) labelField.get(beanObj); if(labelListObj == null) { labelListObj = new ArrayList<>(); labelField.set(beanObj, labelListObj); } Utils.addListWithIndex(labelListObj, label, index); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("fail access label field.", e); } } }); } return Optional.empty(); } }
public class class_name { private Optional<ArrayLabelSetter> createField(final Class<?> beanClass, final String fieldName) { final String labelFieldName = fieldName + "Label"; final Field labelField; try { labelField = beanClass.getDeclaredField(labelFieldName); // depends on control dependency: [try], data = [none] labelField.setAccessible(true); // depends on control dependency: [try], data = [none] } catch (NoSuchFieldException | SecurityException e) { return Optional.empty(); } // depends on control dependency: [catch], data = [none] if(!List.class.isAssignableFrom(labelField.getType())) { return Optional.empty(); // depends on control dependency: [if], data = [none] } final ParameterizedType type = (ParameterizedType) labelField.getGenericType(); final Class<?> valueType = (Class<?>) type.getActualTypeArguments()[0]; if(valueType.equals(String.class)) { return Optional.of(new ArrayLabelSetter() { @SuppressWarnings("unchecked") @Override public void set(final Object beanObj, final String label, final int index) { ArgUtils.notNull(beanObj, "beanObj"); ArgUtils.notEmpty(label, "label"); try { List<String> labelListObj = (List<String>) labelField.get(beanObj); if(labelListObj == null) { labelListObj = new ArrayList<>(); // depends on control dependency: [if], data = [none] labelField.set(beanObj, labelListObj); // depends on control dependency: [if], data = [none] } Utils.addListWithIndex(labelListObj, label, index); // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("fail access label field.", e); } // depends on control dependency: [catch], data = [none] } }); // depends on control dependency: [if], data = [none] } return Optional.empty(); } }
public class class_name { synchronized private void saveMetadata() throws StageException { // 0) Validate pre-conditions if(Files.exists(newMetadataFile)) { throw new StageException(BlobStoreError.BLOB_STORE_0010); } // 1) New content is written into a new temporary file. try ( OutputStream os = Files.newOutputStream(newMetadataFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING) ) { jsonMapper.writeValue(os, metadata); } catch (IOException e) { throw new StageException(BlobStoreError.BLOB_STORE_0001, e.toString(), e); } // 2) Old metadata is dropped try { if(Files.exists(metadataFile)) { Files.delete(metadataFile); } } catch (IOException e) { throw new StageException(BlobStoreError.BLOB_STORE_0011, e.toString(), e); } // 3) Rename from new to old is done try { Files.move(newMetadataFile, metadataFile); } catch (IOException e) { throw new StageException(BlobStoreError.BLOB_STORE_0012, e.toString(), e); } } }
public class class_name { synchronized private void saveMetadata() throws StageException { // 0) Validate pre-conditions if(Files.exists(newMetadataFile)) { throw new StageException(BlobStoreError.BLOB_STORE_0010); } // 1) New content is written into a new temporary file. try ( OutputStream os = Files.newOutputStream(newMetadataFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING) ) { jsonMapper.writeValue(os, metadata); } catch (IOException e) { throw new StageException(BlobStoreError.BLOB_STORE_0001, e.toString(), e); } // 2) Old metadata is dropped try { if(Files.exists(metadataFile)) { Files.delete(metadataFile); // depends on control dependency: [if], data = [none] } } catch (IOException e) { throw new StageException(BlobStoreError.BLOB_STORE_0011, e.toString(), e); } // 3) Rename from new to old is done try { Files.move(newMetadataFile, metadataFile); } catch (IOException e) { throw new StageException(BlobStoreError.BLOB_STORE_0012, e.toString(), e); } } }
public class class_name { public static List<Object> getDecoratorLineage(Object obj) { List<Object> lineage = Lists.newArrayList(obj); Object currentObject = obj; while(currentObject instanceof Decorator) { currentObject = ((Decorator)currentObject).getDecoratedObject(); lineage.add(currentObject); } return Lists.reverse(lineage); } }
public class class_name { public static List<Object> getDecoratorLineage(Object obj) { List<Object> lineage = Lists.newArrayList(obj); Object currentObject = obj; while(currentObject instanceof Decorator) { currentObject = ((Decorator)currentObject).getDecoratedObject(); // depends on control dependency: [while], data = [none] lineage.add(currentObject); // depends on control dependency: [while], data = [none] } return Lists.reverse(lineage); } }
public class class_name { private void drawFlippingShadeShine(Canvas canvas) { final float degreesFlipped = getDegreesFlipped(); if (degreesFlipped < 90) { final int alpha = (int) ((degreesFlipped / 90f) * MAX_SHINE_ALPHA); mShinePaint.setAlpha(alpha); canvas.drawRect(isFlippingVertically() ? mBottomRect : mRightRect, mShinePaint); } else { final int alpha = (int) ((Math.abs(degreesFlipped - 180) / 90f) * MAX_SHADE_ALPHA); mShadePaint.setAlpha(alpha); canvas.drawRect(isFlippingVertically() ? mTopRect : mLeftRect, mShadePaint); } } }
public class class_name { private void drawFlippingShadeShine(Canvas canvas) { final float degreesFlipped = getDegreesFlipped(); if (degreesFlipped < 90) { final int alpha = (int) ((degreesFlipped / 90f) * MAX_SHINE_ALPHA); mShinePaint.setAlpha(alpha); // depends on control dependency: [if], data = [none] canvas.drawRect(isFlippingVertically() ? mBottomRect : mRightRect, mShinePaint); // depends on control dependency: [if], data = [none] } else { final int alpha = (int) ((Math.abs(degreesFlipped - 180) / 90f) * MAX_SHADE_ALPHA); mShadePaint.setAlpha(alpha); // depends on control dependency: [if], data = [none] canvas.drawRect(isFlippingVertically() ? mTopRect : mLeftRect, mShadePaint); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void storeInSession() { try { Context.getThreadContext().setSessionAttribute(getCacheKey(), isExpanded()); } catch (final EFapsException e) { UIMenuItem.LOG.error("Error storing Session info for UIMenuItem called by Command with UUID: {}", getCommandUUID(), e); } } }
public class class_name { private void storeInSession() { try { Context.getThreadContext().setSessionAttribute(getCacheKey(), isExpanded()); // depends on control dependency: [try], data = [none] } catch (final EFapsException e) { UIMenuItem.LOG.error("Error storing Session info for UIMenuItem called by Command with UUID: {}", getCommandUUID(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private void negotiate(final ChannelHandlerContext ctx) { if (controlSettings.hasNext()) { Map.Entry<String, String> setting = controlSettings.next(); LOGGER.debug("Negotiating DCP Control {}: {}", setting.getKey(), setting.getValue()); ByteBuf request = ctx.alloc().buffer(); DcpControlRequest.init(request); DcpControlRequest.key(setting.getKey(), request); DcpControlRequest.value(Unpooled.copiedBuffer(setting.getValue(), CharsetUtil.UTF_8), request); ctx.writeAndFlush(request); } else { originalPromise().setSuccess(); ctx.pipeline().remove(this); ctx.fireChannelActive(); LOGGER.debug("Negotiated all DCP Control settings against Node {}", ctx.channel().remoteAddress()); } } }
public class class_name { private void negotiate(final ChannelHandlerContext ctx) { if (controlSettings.hasNext()) { Map.Entry<String, String> setting = controlSettings.next(); LOGGER.debug("Negotiating DCP Control {}: {}", setting.getKey(), setting.getValue()); // depends on control dependency: [if], data = [none] ByteBuf request = ctx.alloc().buffer(); DcpControlRequest.init(request); // depends on control dependency: [if], data = [none] DcpControlRequest.key(setting.getKey(), request); // depends on control dependency: [if], data = [none] DcpControlRequest.value(Unpooled.copiedBuffer(setting.getValue(), CharsetUtil.UTF_8), request); // depends on control dependency: [if], data = [none] ctx.writeAndFlush(request); // depends on control dependency: [if], data = [none] } else { originalPromise().setSuccess(); // depends on control dependency: [if], data = [none] ctx.pipeline().remove(this); // depends on control dependency: [if], data = [none] ctx.fireChannelActive(); // depends on control dependency: [if], data = [none] LOGGER.debug("Negotiated all DCP Control settings against Node {}", ctx.channel().remoteAddress()); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void shutdownTasks() throws InterruptedException { log.info("Shutting down tasks"); for (Task task: this.tasks) { task.shutdown(); } for (Task task : this.tasks) { task.awaitShutdown(1000); } for (Task task : this.tasks) { if (task.cancel()) { log.info("Task {} cancelled.", task.getTaskId()); } else { log.info("Task {} could not be cancelled.", task.getTaskId()); } } } }
public class class_name { public void shutdownTasks() throws InterruptedException { log.info("Shutting down tasks"); for (Task task: this.tasks) { task.shutdown(); } for (Task task : this.tasks) { task.awaitShutdown(1000); } for (Task task : this.tasks) { if (task.cancel()) { log.info("Task {} cancelled.", task.getTaskId()); // depends on control dependency: [if], data = [none] } else { log.info("Task {} could not be cancelled.", task.getTaskId()); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public double mean(double[] series) { double res = 0D; int count = 0; for (double tp : series) { res += tp; count += 1; } if (count > 0) { return res / ((Integer) count).doubleValue(); } return Double.NaN; } }
public class class_name { public double mean(double[] series) { double res = 0D; int count = 0; for (double tp : series) { res += tp; // depends on control dependency: [for], data = [tp] count += 1; // depends on control dependency: [for], data = [none] } if (count > 0) { return res / ((Integer) count).doubleValue(); // depends on control dependency: [if], data = [none] } return Double.NaN; } }
public class class_name { boolean isValidPackageName(String s) { if (s.contains("/")) { String[] a = s.split("/"); if (a.length == 2) { return isValidPackageName0(a[0]) && isValidPackageName0(a[1]); } return false; } return isValidPackageName0(s); } }
public class class_name { boolean isValidPackageName(String s) { if (s.contains("/")) { String[] a = s.split("/"); if (a.length == 2) { return isValidPackageName0(a[0]) && isValidPackageName0(a[1]); // depends on control dependency: [if], data = [none] } return false; // depends on control dependency: [if], data = [none] } return isValidPackageName0(s); } }
public class class_name { private static boolean deleteIfExists(FileSystem fileSystem, Path path, boolean recursive) { try { // attempt to delete the path if (fileSystem.delete(path, recursive)) { return true; } // delete failed // check if path still exists return !fileSystem.exists(path); } catch (FileNotFoundException ignored) { // path was already removed or never existed return true; } catch (IOException ignored) { } return false; } }
public class class_name { private static boolean deleteIfExists(FileSystem fileSystem, Path path, boolean recursive) { try { // attempt to delete the path if (fileSystem.delete(path, recursive)) { return true; // depends on control dependency: [if], data = [none] } // delete failed // check if path still exists return !fileSystem.exists(path); // depends on control dependency: [try], data = [none] } catch (FileNotFoundException ignored) { // path was already removed or never existed return true; } // depends on control dependency: [catch], data = [none] catch (IOException ignored) { } // depends on control dependency: [catch], data = [none] return false; } }
public class class_name { private boolean set_cache( long cache ) { while( true ) { // Spin till get it long old = _cache; // Read once at the start if( !H2O.larger(cloud(cache),cloud(old)) ) // Rolling backwards? // Attempt to set for an older Cloud. Blow out with a failure; caller // should retry on a new Cloud. return false; assert cloud(cache) != cloud(old) || cache == old; if( old == cache ) return true; // Fast-path cutout if( _cacheUpdater.compareAndSet(this,old,cache) ) return true; // Can fail if the cache is really old, and just got updated to a version // which is still not the latest, and we are trying to update it again. } } }
public class class_name { private boolean set_cache( long cache ) { while( true ) { // Spin till get it long old = _cache; // Read once at the start if( !H2O.larger(cloud(cache),cloud(old)) ) // Rolling backwards? // Attempt to set for an older Cloud. Blow out with a failure; caller // should retry on a new Cloud. return false; assert cloud(cache) != cloud(old) || cache == old; // depends on control dependency: [while], data = [none] if( old == cache ) return true; // Fast-path cutout if( _cacheUpdater.compareAndSet(this,old,cache) ) return true; // Can fail if the cache is really old, and just got updated to a version // which is still not the latest, and we are trying to update it again. } } }
public class class_name { public static XtextFactory init() { try { XtextFactory theXtextFactory = (XtextFactory)EPackage.Registry.INSTANCE.getEFactory(XtextPackage.eNS_URI); if (theXtextFactory != null) { return theXtextFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new XtextFactoryImpl(); } }
public class class_name { public static XtextFactory init() { try { XtextFactory theXtextFactory = (XtextFactory)EPackage.Registry.INSTANCE.getEFactory(XtextPackage.eNS_URI); if (theXtextFactory != null) { return theXtextFactory; // depends on control dependency: [if], data = [none] } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } // depends on control dependency: [catch], data = [none] return new XtextFactoryImpl(); } }
public class class_name { public File processNamespaceHeader(String resourceLocation, File rawNamespace, File namespaceHomeFile) throws IndexingFailure { NamespaceHeaderParser nshParser = new NamespaceHeaderParser(); NamespaceHeader namespaceHeader; try { namespaceHeader = nshParser.parseNamespace(resourceLocation, rawNamespace); characterStopOffset = nshParser.getNextCharacterOffset(); } catch (IOException e) { final String name = rawNamespace.getAbsolutePath(); throw new IndexingFailure(name, e); } catch (BELDataMissingPropertyException e) { final String name = rawNamespace.getAbsolutePath(); throw new IndexingFailure(name, e); } catch (BELDataConversionException e) { final String name = rawNamespace.getAbsolutePath(); throw new IndexingFailure(name, e); } String output = asPath(namespaceHomeFile.getAbsolutePath(), "namespace.header"); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream( new FileOutputStream(output)); oos.writeObject(namespaceHeader); return new File(output); } catch (IOException e) { final String msg = "Error writing namespace header."; throw new IndexingFailure(resourceLocation, msg, e); } finally { if (oos != null) { try { oos.close(); } catch (IOException e) {} } } } }
public class class_name { public File processNamespaceHeader(String resourceLocation, File rawNamespace, File namespaceHomeFile) throws IndexingFailure { NamespaceHeaderParser nshParser = new NamespaceHeaderParser(); NamespaceHeader namespaceHeader; try { namespaceHeader = nshParser.parseNamespace(resourceLocation, rawNamespace); characterStopOffset = nshParser.getNextCharacterOffset(); } catch (IOException e) { final String name = rawNamespace.getAbsolutePath(); throw new IndexingFailure(name, e); } catch (BELDataMissingPropertyException e) { final String name = rawNamespace.getAbsolutePath(); throw new IndexingFailure(name, e); } catch (BELDataConversionException e) { final String name = rawNamespace.getAbsolutePath(); throw new IndexingFailure(name, e); } String output = asPath(namespaceHomeFile.getAbsolutePath(), "namespace.header"); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream( new FileOutputStream(output)); oos.writeObject(namespaceHeader); return new File(output); } catch (IOException e) { final String msg = "Error writing namespace header."; throw new IndexingFailure(resourceLocation, msg, e); } finally { if (oos != null) { try { oos.close(); // depends on control dependency: [try], data = [none] } catch (IOException e) {} // depends on control dependency: [catch], data = [none] } } } }
public class class_name { public <S> S get(Class<S> service) { Check.notNull(service); for (final Object object : servicesSet) { if (service.isAssignableFrom(object.getClass())) { return service.cast(object); } } if (service == getClass()) { return service.cast(this); } throw new LionEngineException(ERROR_SERVICE_GET + service.getName()); } }
public class class_name { public <S> S get(Class<S> service) { Check.notNull(service); for (final Object object : servicesSet) { if (service.isAssignableFrom(object.getClass())) { return service.cast(object); // depends on control dependency: [if], data = [none] } } if (service == getClass()) { return service.cast(this); // depends on control dependency: [if], data = [none] } throw new LionEngineException(ERROR_SERVICE_GET + service.getName()); } }
public class class_name { private void trace(char mod, int i, int j) { if(mod == '0' || i <= 0 || j <= 0) { B1 = i + 1; B2 = j + 1; } if(mod == 's') { trace(trace[i - 1][j - 1], i - 1, j - 1); rep(); } else if(mod == 'D') { trace(trace[i - 1][j], i - 1, j); del(1); } else if(mod == 'd') { trace(dtrace[i - 1][j], i - 1, j); del(1); } else if(mod == 'E') { trace(trace[i][j - 1], i, j - 1); ins(1); } else if(mod == 'e') { trace(etrace[i][j - 1], i, j - 1); ins(1); } } }
public class class_name { private void trace(char mod, int i, int j) { if(mod == '0' || i <= 0 || j <= 0) { B1 = i + 1; // depends on control dependency: [if], data = [none] B2 = j + 1; // depends on control dependency: [if], data = [none] } if(mod == 's') { trace(trace[i - 1][j - 1], i - 1, j - 1); // depends on control dependency: [if], data = [none] rep(); // depends on control dependency: [if], data = [none] } else if(mod == 'D') { trace(trace[i - 1][j], i - 1, j); // depends on control dependency: [if], data = [none] del(1); // depends on control dependency: [if], data = [none] } else if(mod == 'd') { trace(dtrace[i - 1][j], i - 1, j); // depends on control dependency: [if], data = [none] del(1); // depends on control dependency: [if], data = [none] } else if(mod == 'E') { trace(trace[i][j - 1], i, j - 1); // depends on control dependency: [if], data = [none] ins(1); // depends on control dependency: [if], data = [none] } else if(mod == 'e') { trace(etrace[i][j - 1], i, j - 1); // depends on control dependency: [if], data = [none] ins(1); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public void removeAppender(Appender appender) { if (appender == null || aai == null) { return; } boolean wasAttached = aai.isAttached(appender); aai.removeAppender(appender); if (wasAttached) { fireRemoveAppenderEvent(appender); } } }
public class class_name { @Override public void removeAppender(Appender appender) { if (appender == null || aai == null) { return; // depends on control dependency: [if], data = [none] } boolean wasAttached = aai.isAttached(appender); aai.removeAppender(appender); if (wasAttached) { fireRemoveAppenderEvent(appender); // depends on control dependency: [if], data = [none] } } }
public class class_name { public LongBigList signatures(final int signatureWidth, final ProgressLogger pl) throws IOException { final LongBigList signatures = LongArrayBitVector.getInstance().asLongBigList(signatureWidth); final long signatureMask = -1L >>> Long.SIZE - signatureWidth; signatures.size(size()); pl.expectedUpdates = size(); pl.itemsName = "signatures"; pl.start("Signing..."); for (final ChunkedHashStore.Chunk chunk : this) { final Iterator<long[]> chunkIterator = chunk.iterator(); for(int i = chunk.size(); i-- != 0;) { final long[] quadruple = chunkIterator.next(); signatures.set(quadruple[3], signatureMask & quadruple[0]); pl.lightUpdate(); } } pl.done(); return signatures; } }
public class class_name { public LongBigList signatures(final int signatureWidth, final ProgressLogger pl) throws IOException { final LongBigList signatures = LongArrayBitVector.getInstance().asLongBigList(signatureWidth); final long signatureMask = -1L >>> Long.SIZE - signatureWidth; signatures.size(size()); pl.expectedUpdates = size(); pl.itemsName = "signatures"; pl.start("Signing..."); for (final ChunkedHashStore.Chunk chunk : this) { final Iterator<long[]> chunkIterator = chunk.iterator(); for(int i = chunk.size(); i-- != 0;) { final long[] quadruple = chunkIterator.next(); signatures.set(quadruple[3], signatureMask & quadruple[0]); // depends on control dependency: [for], data = [none] pl.lightUpdate(); // depends on control dependency: [for], data = [none] } } pl.done(); return signatures; } }
public class class_name { public Source getAssociatedStylesheet( Source source, String media, String title, String charset) throws TransformerConfigurationException { String baseID; InputSource isource = null; Node node = null; XMLReader reader = null; if (source instanceof DOMSource) { DOMSource dsource = (DOMSource) source; node = dsource.getNode(); baseID = dsource.getSystemId(); } else { isource = SAXSource.sourceToInputSource(source); baseID = isource.getSystemId(); } // What I try to do here is parse until the first startElement // is found, then throw a special exception in order to terminate // the parse. StylesheetPIHandler handler = new StylesheetPIHandler(baseID, media, title, charset); // Use URIResolver. Patch from Dmitri Ilyin if (m_uriResolver != null) { handler.setURIResolver(m_uriResolver); } try { if (null != node) { TreeWalker walker = new TreeWalker(handler, new org.apache.xml.utils.DOM2Helper(), baseID); walker.traverse(node); } else { // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); if (m_isSecureProcessing) { try { factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (org.xml.sax.SAXException e) {} } javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2){} catch (AbstractMethodError ame){} if (null == reader) { reader = XMLReaderFactory.createXMLReader(); } if(m_isSecureProcessing) { reader.setFeature("http://xml.org/sax/features/external-general-entities",false); } // Need to set options! reader.setContentHandler(handler); reader.parse(isource); } } catch (StopParseException spe) { // OK, good. } catch (org.xml.sax.SAXException se) { throw new TransformerConfigurationException( "getAssociatedStylesheets failed", se); } catch (IOException ioe) { throw new TransformerConfigurationException( "getAssociatedStylesheets failed", ioe); } return handler.getAssociatedStylesheet(); } }
public class class_name { public Source getAssociatedStylesheet( Source source, String media, String title, String charset) throws TransformerConfigurationException { String baseID; InputSource isource = null; Node node = null; XMLReader reader = null; if (source instanceof DOMSource) { DOMSource dsource = (DOMSource) source; node = dsource.getNode(); baseID = dsource.getSystemId(); } else { isource = SAXSource.sourceToInputSource(source); baseID = isource.getSystemId(); } // What I try to do here is parse until the first startElement // is found, then throw a special exception in order to terminate // the parse. StylesheetPIHandler handler = new StylesheetPIHandler(baseID, media, title, charset); // Use URIResolver. Patch from Dmitri Ilyin if (m_uriResolver != null) { handler.setURIResolver(m_uriResolver); } try { if (null != node) { TreeWalker walker = new TreeWalker(handler, new org.apache.xml.utils.DOM2Helper(), baseID); walker.traverse(node); // depends on control dependency: [if], data = [node)] } else { // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); // depends on control dependency: [try], data = [none] if (m_isSecureProcessing) { try { factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); // depends on control dependency: [try], data = [none] } catch (org.xml.sax.SAXException e) {} // depends on control dependency: [catch], data = [none] } javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); // depends on control dependency: [try], data = [none] } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } // depends on control dependency: [catch], data = [none] catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } // depends on control dependency: [catch], data = [none] catch (NoSuchMethodError ex2){} // depends on control dependency: [catch], data = [none] catch (AbstractMethodError ame){} // depends on control dependency: [catch], data = [none] if (null == reader) { reader = XMLReaderFactory.createXMLReader(); // depends on control dependency: [if], data = [none] } if(m_isSecureProcessing) { reader.setFeature("http://xml.org/sax/features/external-general-entities",false); } // Need to set options! reader.setContentHandler(handler); // depends on control dependency: [if], data = [none] reader.parse(isource); // depends on control dependency: [if], data = [none] } } catch (StopParseException spe) { // OK, good. } catch (org.xml.sax.SAXException se) { throw new TransformerConfigurationException( "getAssociatedStylesheets failed", se); } catch (IOException ioe) { throw new TransformerConfigurationException( "getAssociatedStylesheets failed", ioe); } return handler.getAssociatedStylesheet(); } }
public class class_name { public <A extends Association> A getAssociationForTarget(Class<? extends Model> targetClass){ Association result = null; for (Association association : associations) { if (association.getTargetClass().getName().equals(targetClass.getName())) { result = association; break; } } return (A) result; } }
public class class_name { public <A extends Association> A getAssociationForTarget(Class<? extends Model> targetClass){ Association result = null; for (Association association : associations) { if (association.getTargetClass().getName().equals(targetClass.getName())) { result = association; break; // depends on control dependency: [if], data = [none] } } return (A) result; } }
public class class_name { public void setPath(String path) { if (path != null) { manifest = ManifestIterator.getInstance().findByPath(path); } } }
public class class_name { public void setPath(String path) { if (path != null) { manifest = ManifestIterator.getInstance().findByPath(path); // depends on control dependency: [if], data = [(path] } } }
public class class_name { private void prepare() { try { final Class<?> codecCapabilitiesClass = Class.forName("android.media.MediaCodecInfo$CodecCapabilities"); // Retrieve list of possible Color Format for (Field f : codecCapabilitiesClass.getFields()) { if (Modifier.isStatic(f.getModifiers()) && Modifier.isFinal(f.getModifiers()) && f.getName().startsWith(COLOR_FORMAT_PREFIX)) { mColorFormatValues.put(f.getInt(null), f.getName()); } } // Retrieve lists of possible codecs profiles and levels final Class<?> codecProfileLevelClass = Class.forName("android.media.MediaCodecInfo$CodecProfileLevel"); for (Field f : codecProfileLevelClass.getFields()) { if (Modifier.isStatic(f.getModifiers()) && Modifier.isFinal(f.getModifiers())) { if (f.getName().startsWith("AVCLevel")) { mAVCLevelValues.put(f.getInt(null), f.getName()); } else if (f.getName().startsWith("AVCProfile")) { mAVCProfileValues.put(f.getInt(null), f.getName()); } else if (f.getName().startsWith("H263Level")) { mH263LevelValues.put(f.getInt(null), f.getName()); } else if (f.getName().startsWith("H263Profile")) { mH263ProfileValues.put(f.getInt(null), f.getName()); } else if (f.getName().startsWith("MPEG4Level")) { mMPEG4LevelValues.put(f.getInt(null), f.getName()); } else if (f.getName().startsWith("MPEG4Profile")) { mMPEG4ProfileValues.put(f.getInt(null), f.getName()); } else if (f.getName().startsWith("AAC")) { mAACProfileValues.put(f.getInt(null), f.getName()); } } } } catch (@NonNull ClassNotFoundException ignored) { // NOOP } catch (@NonNull SecurityException ignored) { // NOOP } catch (@NonNull IllegalAccessException ignored) { // NOOP } catch (@NonNull IllegalArgumentException ignored) { // NOOP } } }
public class class_name { private void prepare() { try { final Class<?> codecCapabilitiesClass = Class.forName("android.media.MediaCodecInfo$CodecCapabilities"); // Retrieve list of possible Color Format for (Field f : codecCapabilitiesClass.getFields()) { if (Modifier.isStatic(f.getModifiers()) && Modifier.isFinal(f.getModifiers()) && f.getName().startsWith(COLOR_FORMAT_PREFIX)) { mColorFormatValues.put(f.getInt(null), f.getName()); // depends on control dependency: [if], data = [none] } } // Retrieve lists of possible codecs profiles and levels final Class<?> codecProfileLevelClass = Class.forName("android.media.MediaCodecInfo$CodecProfileLevel"); for (Field f : codecProfileLevelClass.getFields()) { if (Modifier.isStatic(f.getModifiers()) && Modifier.isFinal(f.getModifiers())) { if (f.getName().startsWith("AVCLevel")) { mAVCLevelValues.put(f.getInt(null), f.getName()); // depends on control dependency: [if], data = [none] } else if (f.getName().startsWith("AVCProfile")) { mAVCProfileValues.put(f.getInt(null), f.getName()); // depends on control dependency: [if], data = [none] } else if (f.getName().startsWith("H263Level")) { mH263LevelValues.put(f.getInt(null), f.getName()); // depends on control dependency: [if], data = [none] } else if (f.getName().startsWith("H263Profile")) { mH263ProfileValues.put(f.getInt(null), f.getName()); // depends on control dependency: [if], data = [none] } else if (f.getName().startsWith("MPEG4Level")) { mMPEG4LevelValues.put(f.getInt(null), f.getName()); // depends on control dependency: [if], data = [none] } else if (f.getName().startsWith("MPEG4Profile")) { mMPEG4ProfileValues.put(f.getInt(null), f.getName()); // depends on control dependency: [if], data = [none] } else if (f.getName().startsWith("AAC")) { mAACProfileValues.put(f.getInt(null), f.getName()); // depends on control dependency: [if], data = [none] } } } } catch (@NonNull ClassNotFoundException ignored) { // NOOP } catch (@NonNull SecurityException ignored) { // depends on control dependency: [catch], data = [none] // NOOP } catch (@NonNull IllegalAccessException ignored) { // depends on control dependency: [catch], data = [none] // NOOP } catch (@NonNull IllegalArgumentException ignored) { // depends on control dependency: [catch], data = [none] // NOOP } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static MaterializedViewInfo getMaterializedViewInfo(Table tbl) { MaterializedViewInfo mvInfo = null; Table source = tbl.getMaterializer(); if (source != null) { mvInfo = source.getViews().get(tbl.getTypeName()); } return mvInfo; } }
public class class_name { public static MaterializedViewInfo getMaterializedViewInfo(Table tbl) { MaterializedViewInfo mvInfo = null; Table source = tbl.getMaterializer(); if (source != null) { mvInfo = source.getViews().get(tbl.getTypeName()); // depends on control dependency: [if], data = [none] } return mvInfo; } }
public class class_name { @CheckReturnValue @VisibleForTesting ImmutableList<Server> mergeServerLists(List<Server> firstList, List<Server> secondList) { ImmutableList.Builder<Server> results = ImmutableList.builder(); List<Server> toProcess = new ArrayList<>(secondList); for (Server firstServer : firstList) { if (toProcess.contains(firstServer)) { Server found = toProcess.get(secondList.indexOf(firstServer)); results.add(merge(firstServer, found)); // remove server as it is already merged toProcess.remove(found); } else { results.add(firstServer); } } // add servers from the second list that are not in the first one results.addAll(toProcess); return results.build(); } }
public class class_name { @CheckReturnValue @VisibleForTesting ImmutableList<Server> mergeServerLists(List<Server> firstList, List<Server> secondList) { ImmutableList.Builder<Server> results = ImmutableList.builder(); List<Server> toProcess = new ArrayList<>(secondList); for (Server firstServer : firstList) { if (toProcess.contains(firstServer)) { Server found = toProcess.get(secondList.indexOf(firstServer)); results.add(merge(firstServer, found)); // depends on control dependency: [if], data = [none] // remove server as it is already merged toProcess.remove(found); // depends on control dependency: [if], data = [none] } else { results.add(firstServer); // depends on control dependency: [if], data = [none] } } // add servers from the second list that are not in the first one results.addAll(toProcess); return results.build(); } }
public class class_name { public boolean isRequestedSessionIdValid(HttpServletRequest _request, HttpSession sess) { SessionAffinityContext sac = getSessionAffinityContext(_request); String sessionId = sac.getRequestedSessionID(); if ((sessionId != null) && (sess != null) && (!sess.isNew() || !_smc.checkSessionNewOnIsValidRequest()) && sessionId.equals(sess.getId())) { return true; } return false; } }
public class class_name { public boolean isRequestedSessionIdValid(HttpServletRequest _request, HttpSession sess) { SessionAffinityContext sac = getSessionAffinityContext(_request); String sessionId = sac.getRequestedSessionID(); if ((sessionId != null) && (sess != null) && (!sess.isNew() || !_smc.checkSessionNewOnIsValidRequest()) && sessionId.equals(sess.getId())) { return true; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { public List<MutableInputColumn<?>> getOutputColumns() { if (!isConfigured()) { // as long as the transformer is not configured, just return an // empty list return Collections.emptyList(); } final Transformer<?> component = getComponentInstance(); final TransformerBeanDescriptor<T> descriptor = getDescriptor(); final InjectionManager injectionManager = getAnalysisJobBuilder().getConfiguration().getInjectionManager(null); final LifeCycleHelper lifeCycleHelper = new LifeCycleHelper(injectionManager, null, false); // mimic the configuration of a real transformer bean instance final BeanConfiguration beanConfiguration = new ImmutableBeanConfiguration(getConfiguredProperties()); lifeCycleHelper.assignConfiguredProperties(descriptor, component, beanConfiguration); lifeCycleHelper.assignProvidedProperties(descriptor, component); // only validate, don't initialize lifeCycleHelper.validate(descriptor, component); final OutputColumns outputColumns = component.getOutputColumns(); if (outputColumns == null) { throw new IllegalStateException("getOutputColumns() returned null on transformer: " + component); } boolean changed = false; // adjust the amount of output columns final int expectedCols = outputColumns.getColumnCount(); final int existingCols = _outputColumns.size(); if (expectedCols != existingCols) { changed = true; int colDiff = expectedCols - existingCols; if (colDiff > 0) { for (int i = 0; i < colDiff; i++) { final int nextIndex = _outputColumns.size(); final String name = getColumnName(outputColumns, nextIndex); final String id = _id + "-" + _idGenerator.nextId(); _outputColumns.add(new TransformedInputColumn<Object>(name, id)); _automaticOutputColumnNames.add(name); } } else if (colDiff < 0) { for (int i = 0; i < Math.abs(colDiff); i++) { // remove from the tail _outputColumns.remove(_outputColumns.size() - 1); _automaticOutputColumnNames.remove(_automaticOutputColumnNames.size() - 1); } } // reset the names when the number of output columns change and the // initial name has changed for (int i = 0; i < expectedCols; i++) { final MutableInputColumn<?> column = _outputColumns.get(i); final String previousProposedName = column.getInitialName(); final String newProposedName = outputColumns.getColumnName(i); if (newProposedName != null && !newProposedName.equals(previousProposedName)) { column.setName(newProposedName); } } } // automatically update names and types of columns if they have not been // manually set for (int i = 0; i < expectedCols; i++) { final String proposedName = getColumnName(outputColumns, i); Class<?> dataType = outputColumns.getColumnType(i); if (dataType == null) { dataType = descriptor.getOutputDataType(); } final TransformedInputColumn<?> col = (TransformedInputColumn<?>) _outputColumns.get(i); col.setInitialName(proposedName); if (dataType != col.getDataType()) { col.setDataType(dataType); changed = true; } final String automaticName = _automaticOutputColumnNames.get(i); final String columnName = col.getName(); if (StringUtils.isNullOrEmpty(columnName) || automaticName.equals(columnName)) { if (proposedName != null) { col.setName(proposedName); _automaticOutputColumnNames.set(i, proposedName); } } } if (changed) { // notify listeners onOutputChanged(); } return Collections.unmodifiableList(_outputColumns); } }
public class class_name { public List<MutableInputColumn<?>> getOutputColumns() { if (!isConfigured()) { // as long as the transformer is not configured, just return an // empty list return Collections.emptyList(); // depends on control dependency: [if], data = [none] } final Transformer<?> component = getComponentInstance(); final TransformerBeanDescriptor<T> descriptor = getDescriptor(); final InjectionManager injectionManager = getAnalysisJobBuilder().getConfiguration().getInjectionManager(null); final LifeCycleHelper lifeCycleHelper = new LifeCycleHelper(injectionManager, null, false); // mimic the configuration of a real transformer bean instance final BeanConfiguration beanConfiguration = new ImmutableBeanConfiguration(getConfiguredProperties()); lifeCycleHelper.assignConfiguredProperties(descriptor, component, beanConfiguration); lifeCycleHelper.assignProvidedProperties(descriptor, component); // only validate, don't initialize lifeCycleHelper.validate(descriptor, component); final OutputColumns outputColumns = component.getOutputColumns(); if (outputColumns == null) { throw new IllegalStateException("getOutputColumns() returned null on transformer: " + component); } boolean changed = false; // adjust the amount of output columns final int expectedCols = outputColumns.getColumnCount(); final int existingCols = _outputColumns.size(); if (expectedCols != existingCols) { changed = true; // depends on control dependency: [if], data = [none] int colDiff = expectedCols - existingCols; if (colDiff > 0) { for (int i = 0; i < colDiff; i++) { final int nextIndex = _outputColumns.size(); final String name = getColumnName(outputColumns, nextIndex); final String id = _id + "-" + _idGenerator.nextId(); _outputColumns.add(new TransformedInputColumn<Object>(name, id)); // depends on control dependency: [for], data = [none] _automaticOutputColumnNames.add(name); // depends on control dependency: [for], data = [none] } } else if (colDiff < 0) { for (int i = 0; i < Math.abs(colDiff); i++) { // remove from the tail _outputColumns.remove(_outputColumns.size() - 1); // depends on control dependency: [for], data = [none] _automaticOutputColumnNames.remove(_automaticOutputColumnNames.size() - 1); // depends on control dependency: [for], data = [none] } } // reset the names when the number of output columns change and the // initial name has changed for (int i = 0; i < expectedCols; i++) { final MutableInputColumn<?> column = _outputColumns.get(i); final String previousProposedName = column.getInitialName(); final String newProposedName = outputColumns.getColumnName(i); if (newProposedName != null && !newProposedName.equals(previousProposedName)) { column.setName(newProposedName); // depends on control dependency: [if], data = [(newProposedName] } } } // automatically update names and types of columns if they have not been // manually set for (int i = 0; i < expectedCols; i++) { final String proposedName = getColumnName(outputColumns, i); Class<?> dataType = outputColumns.getColumnType(i); if (dataType == null) { dataType = descriptor.getOutputDataType(); // depends on control dependency: [if], data = [none] } final TransformedInputColumn<?> col = (TransformedInputColumn<?>) _outputColumns.get(i); col.setInitialName(proposedName); // depends on control dependency: [for], data = [none] if (dataType != col.getDataType()) { col.setDataType(dataType); // depends on control dependency: [if], data = [(dataType] changed = true; // depends on control dependency: [if], data = [none] } final String automaticName = _automaticOutputColumnNames.get(i); final String columnName = col.getName(); if (StringUtils.isNullOrEmpty(columnName) || automaticName.equals(columnName)) { if (proposedName != null) { col.setName(proposedName); // depends on control dependency: [if], data = [(proposedName] _automaticOutputColumnNames.set(i, proposedName); // depends on control dependency: [if], data = [none] } } } if (changed) { // notify listeners onOutputChanged(); // depends on control dependency: [if], data = [none] } return Collections.unmodifiableList(_outputColumns); } }
public class class_name { public void free() { super.free(); // Do any inherited try { if (m_remoteDatabase != null) { synchronized (this.getSyncObject(m_remoteDatabase)) { m_remoteDatabase.freeRemoteSession(); m_remoteDatabase = null; } } } catch (RemoteException ex) { Utility.getLogger().warning("Remote free error: " + ex.getMessage()); ex.printStackTrace(); } } }
public class class_name { public void free() { super.free(); // Do any inherited try { if (m_remoteDatabase != null) { synchronized (this.getSyncObject(m_remoteDatabase)) // depends on control dependency: [if], data = [(m_remoteDatabase] { m_remoteDatabase.freeRemoteSession(); m_remoteDatabase = null; } } } catch (RemoteException ex) { Utility.getLogger().warning("Remote free error: " + ex.getMessage()); ex.printStackTrace(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void shutdown() { if (state != null) { for (HystrixRequestVariableDefault<?> v : state.keySet()) { // for each RequestVariable we call 'remove' which performs the shutdown logic try { HystrixRequestVariableDefault.remove(this, v); } catch (Throwable t) { HystrixRequestVariableDefault.logger.error("Error in shutdown, will continue with shutdown of other variables", t); } } // null out so it can be garbage collected even if the containing object is still // being held in ThreadLocals on threads that weren't cleaned up state = null; } } }
public class class_name { public void shutdown() { if (state != null) { for (HystrixRequestVariableDefault<?> v : state.keySet()) { // for each RequestVariable we call 'remove' which performs the shutdown logic try { HystrixRequestVariableDefault.remove(this, v); // depends on control dependency: [try], data = [none] } catch (Throwable t) { HystrixRequestVariableDefault.logger.error("Error in shutdown, will continue with shutdown of other variables", t); } // depends on control dependency: [catch], data = [none] } // null out so it can be garbage collected even if the containing object is still // being held in ThreadLocals on threads that weren't cleaned up state = null; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static Function<ResourceModelSourceFactory, ResourceModelSource> factoryConverter( final Properties configuration ) { //nb: not using lambda due to inability to mock this class within grails tests, some conflict with cglib and // j8 lambdas return new Function<ResourceModelSourceFactory, ResourceModelSource>() { @Override public ResourceModelSource apply(final ResourceModelSourceFactory resourceModelSourceFactory) { try { return resourceModelSourceFactory.createResourceModelSource(configuration); } catch (ConfigurationException e) { throw new RuntimeException(e); } } }; } }
public class class_name { public static Function<ResourceModelSourceFactory, ResourceModelSource> factoryConverter( final Properties configuration ) { //nb: not using lambda due to inability to mock this class within grails tests, some conflict with cglib and // j8 lambdas return new Function<ResourceModelSourceFactory, ResourceModelSource>() { @Override public ResourceModelSource apply(final ResourceModelSourceFactory resourceModelSourceFactory) { try { return resourceModelSourceFactory.createResourceModelSource(configuration); // depends on control dependency: [try], data = [none] } catch (ConfigurationException e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] } }; } }
public class class_name { private static boolean hasMagic(byte[] edata) { try { int i = 0; while (i < edata.length) { if (get16(edata, i) == JAR_MAGIC) { return true; } i += get16(edata, i + 2) + 4; } } catch (ArrayIndexOutOfBoundsException e) { // Invalid extra field data } return false; } }
public class class_name { private static boolean hasMagic(byte[] edata) { try { int i = 0; while (i < edata.length) { if (get16(edata, i) == JAR_MAGIC) { return true; // depends on control dependency: [if], data = [none] } i += get16(edata, i + 2) + 4; // depends on control dependency: [while], data = [none] } } catch (ArrayIndexOutOfBoundsException e) { // Invalid extra field data } // depends on control dependency: [catch], data = [none] return false; } }
public class class_name { private Reuters21578 getReuters21578StoryFromText(String storyText) { // System.out.println(storyText); // ATTRIBUTES ///////////////////////// String firstLine = storyText.split(System.getProperty("line.separator"))[0]; // System.out.println(firstLine); String newIdString = extractAttribute(firstLine, "NEWID"); int newId = Integer.parseInt(newIdString); String oldIdString = extractAttribute(firstLine, "OLDID"); int oldId = Integer.parseInt(oldIdString); String topicsString = extractAttribute(firstLine, "TOPICS"); boolean topicsBool = topicsString.equalsIgnoreCase("YES"); String lewissplitString = extractAttribute(firstLine, "LEWISSPLIT"); String cgisplitString = extractAttribute(firstLine, "CGISPLIT"); // DATE ///////////////////////// String dateString = extractTextBetweenTags(storyText, "DATE"); // System.out.println("date=" + dateString); Date date = null; try { DateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SS"); date = sdf.parse(dateString); } catch (ParseException e) { e.printStackTrace(); } // TOPICS ///////////////////////// String topicsText = extractTextBetweenTags(storyText, "TOPICS"); List<String> topicsArray = extractElementAsLines(topicsText, "D"); // System.out.println(topicsArray); String topicsCSV = Joiner.join(",", topicsArray); // System.out.println("topicsCSV: " + topicsCSV); // PLACES ///////////////////////// String placesText = extractTextBetweenTags(storyText, "PLACES"); List<String> placesArray = extractElementAsLines(placesText, "D"); String placesCSV = Joiner.join(",", placesArray); // PEOPLE ///////////////////////// String peopleText = extractTextBetweenTags(storyText, "PEOPLE"); List<String> peopleArray = extractElementAsLines(peopleText, "D"); String peopleCSV = Joiner.join(",", peopleArray); // ORGS ///////////////////////// String orgsText = extractTextBetweenTags(storyText, "ORGS"); List<String> orgsArray = extractElementAsLines(orgsText, "D"); String orgsCSV = Joiner.join(",", orgsArray); // EXCHANGES ///////////////////////// String exchangesText = extractTextBetweenTags(storyText, "EXCHANGES"); List<String> exchangesArray = extractElementAsLines(exchangesText, "D"); String exchangesCSV = Joiner.join(",", exchangesArray); // COMPANIES ///////////////////////// String companiesText = extractTextBetweenTags(storyText, "COMPANIES"); List<String> companiesArray = extractElementAsLines(companiesText, "D"); String companiesCSV = Joiner.join(",", companiesArray); // TITLE ///////////////////////// String titleText = extractTextBetweenTags(storyText, "TITLE"); // DATELINE ///////////////////////// String datelineText = extractTextBetweenTags(storyText, "DATELINE"); // BODY ///////////////////////// String body = extractTextBetweenTags(storyText, "BODY").replaceAll("\\s+", " "); // System.out.println(body); if (body.length() > maxBodyLength) { maxBodyLength = body.length(); } Reuters21578 reuters21578 = new Reuters21578(); reuters21578.setNewid(newId); reuters21578.setOldid(oldId); reuters21578.setTopicsbool(topicsBool); reuters21578.setLewissplit(lewissplitString); reuters21578.setCgisplit(cgisplitString); reuters21578.setDate(date); reuters21578.setTopics(topicsCSV); reuters21578.setPlaces(placesCSV); reuters21578.setPeople(peopleCSV); reuters21578.setOrgs(orgsCSV); reuters21578.setExchanges(exchangesCSV); reuters21578.setCompanies(companiesCSV); reuters21578.setTitle(titleText); reuters21578.setDateline(datelineText); reuters21578.setBody(body); // System.out.println(reuters21578.toString()); return reuters21578; } }
public class class_name { private Reuters21578 getReuters21578StoryFromText(String storyText) { // System.out.println(storyText); // ATTRIBUTES ///////////////////////// String firstLine = storyText.split(System.getProperty("line.separator"))[0]; // System.out.println(firstLine); String newIdString = extractAttribute(firstLine, "NEWID"); int newId = Integer.parseInt(newIdString); String oldIdString = extractAttribute(firstLine, "OLDID"); int oldId = Integer.parseInt(oldIdString); String topicsString = extractAttribute(firstLine, "TOPICS"); boolean topicsBool = topicsString.equalsIgnoreCase("YES"); String lewissplitString = extractAttribute(firstLine, "LEWISSPLIT"); String cgisplitString = extractAttribute(firstLine, "CGISPLIT"); // DATE ///////////////////////// String dateString = extractTextBetweenTags(storyText, "DATE"); // System.out.println("date=" + dateString); Date date = null; try { DateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SS"); date = sdf.parse(dateString); } catch (ParseException e) { e.printStackTrace(); } // TOPICS ///////////////////////// String topicsText = extractTextBetweenTags(storyText, "TOPICS"); List<String> topicsArray = extractElementAsLines(topicsText, "D"); // System.out.println(topicsArray); String topicsCSV = Joiner.join(",", topicsArray); // System.out.println("topicsCSV: " + topicsCSV); // PLACES ///////////////////////// String placesText = extractTextBetweenTags(storyText, "PLACES"); List<String> placesArray = extractElementAsLines(placesText, "D"); String placesCSV = Joiner.join(",", placesArray); // PEOPLE ///////////////////////// String peopleText = extractTextBetweenTags(storyText, "PEOPLE"); List<String> peopleArray = extractElementAsLines(peopleText, "D"); String peopleCSV = Joiner.join(",", peopleArray); // ORGS ///////////////////////// String orgsText = extractTextBetweenTags(storyText, "ORGS"); List<String> orgsArray = extractElementAsLines(orgsText, "D"); String orgsCSV = Joiner.join(",", orgsArray); // EXCHANGES ///////////////////////// String exchangesText = extractTextBetweenTags(storyText, "EXCHANGES"); List<String> exchangesArray = extractElementAsLines(exchangesText, "D"); String exchangesCSV = Joiner.join(",", exchangesArray); // COMPANIES ///////////////////////// String companiesText = extractTextBetweenTags(storyText, "COMPANIES"); List<String> companiesArray = extractElementAsLines(companiesText, "D"); String companiesCSV = Joiner.join(",", companiesArray); // TITLE ///////////////////////// String titleText = extractTextBetweenTags(storyText, "TITLE"); // DATELINE ///////////////////////// String datelineText = extractTextBetweenTags(storyText, "DATELINE"); // BODY ///////////////////////// String body = extractTextBetweenTags(storyText, "BODY").replaceAll("\\s+", " "); // System.out.println(body); if (body.length() > maxBodyLength) { maxBodyLength = body.length(); // depends on control dependency: [if], data = [none] } Reuters21578 reuters21578 = new Reuters21578(); reuters21578.setNewid(newId); reuters21578.setOldid(oldId); reuters21578.setTopicsbool(topicsBool); reuters21578.setLewissplit(lewissplitString); reuters21578.setCgisplit(cgisplitString); reuters21578.setDate(date); reuters21578.setTopics(topicsCSV); reuters21578.setPlaces(placesCSV); reuters21578.setPeople(peopleCSV); reuters21578.setOrgs(orgsCSV); reuters21578.setExchanges(exchangesCSV); reuters21578.setCompanies(companiesCSV); reuters21578.setTitle(titleText); reuters21578.setDateline(datelineText); reuters21578.setBody(body); // System.out.println(reuters21578.toString()); return reuters21578; } }
public class class_name { public static int readZipInputStreamAnd( InputStream inputStream, Consumer<TrackedContent> consumer ) throws IOException, ClassNotFoundException { int count = 0; try ( ZipInputStream stream = new ZipInputStream( inputStream ) ) { ZipEntry entry; while((entry = stream.getNextEntry())!=null) { logger.trace( "Read entry: %s, len: %d", entry.getName(), entry.getSize() ); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int len; byte[] buffer = new byte[1024]; while ((len = stream.read( buffer)) > 0) { bos.write(buffer, 0, len); } bos.close(); ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( bos.toByteArray() )); TrackedContent record = (TrackedContent) ois.readObject(); consumer.accept( record ); count++; } } return count; } }
public class class_name { public static int readZipInputStreamAnd( InputStream inputStream, Consumer<TrackedContent> consumer ) throws IOException, ClassNotFoundException { int count = 0; try ( ZipInputStream stream = new ZipInputStream( inputStream ) ) { ZipEntry entry; while((entry = stream.getNextEntry())!=null) { logger.trace( "Read entry: %s, len: %d", entry.getName(), entry.getSize() ); // depends on control dependency: [while], data = [none] ByteArrayOutputStream bos = new ByteArrayOutputStream(); int len; byte[] buffer = new byte[1024]; while ((len = stream.read( buffer)) > 0) { bos.write(buffer, 0, len); // depends on control dependency: [while], data = [none] } bos.close(); // depends on control dependency: [while], data = [none] ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( bos.toByteArray() )); TrackedContent record = (TrackedContent) ois.readObject(); consumer.accept( record ); // depends on control dependency: [while], data = [none] count++; // depends on control dependency: [while], data = [none] } } return count; } }
public class class_name { protected void destroyConnection(ThriftConnectionHandle<T> conn) { postDestroyConnection(conn); try { conn.internalClose(); } catch (ThriftConnectionPoolException e) { logger.error("Error in attempting to close connection", e); } } }
public class class_name { protected void destroyConnection(ThriftConnectionHandle<T> conn) { postDestroyConnection(conn); try { conn.internalClose(); // depends on control dependency: [try], data = [none] } catch (ThriftConnectionPoolException e) { logger.error("Error in attempting to close connection", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void toASCII(PrintWriter pw, boolean addName, String rootName, boolean newLine) { if (_Debug) System.out.println("asciiSeq.toASCII(" + addName + ",'" + rootName + "') getName(): " + getEncodedName()); //System.out.println("this: " + this + " Has "+allValues.size() + " elements."); if (rootName != null) rootName += "." + getEncodedName(); else rootName = getEncodedName(); pw.print(toASCIIFlatName(rootName)); /* for(Enumeration e1 = allValues.elements(); e1.hasMoreElements(); ) { // get next instance vector Vector v = (Vector)e1.nextElement(); for(Enumeration e2 = v.elements(); e2.hasMoreElements(); ) { // get next instance variable BaseType bt = (BaseType)e2.nextElement(); pw.print(bt.toASCIIFlatName(rootName)+","); } break; } */ pw.println(""); int i = 0; for (Enumeration e1 = allValues.elements(); e1.hasMoreElements();) { int j = 0; // get next instance vector Vector v = (Vector) e1.nextElement(); for (Enumeration e2 = v.elements(); e2.hasMoreElements();) { // get next instance variable toASCII ta = (toASCII) e2.nextElement(); if (j > 0) pw.print(", "); ta.toASCII(pw, false, rootName, false); j++; } pw.println(""); } if (newLine) pw.print("\n"); } }
public class class_name { public void toASCII(PrintWriter pw, boolean addName, String rootName, boolean newLine) { if (_Debug) System.out.println("asciiSeq.toASCII(" + addName + ",'" + rootName + "') getName(): " + getEncodedName()); //System.out.println("this: " + this + " Has "+allValues.size() + " elements."); if (rootName != null) rootName += "." + getEncodedName(); else rootName = getEncodedName(); pw.print(toASCIIFlatName(rootName)); /* for(Enumeration e1 = allValues.elements(); e1.hasMoreElements(); ) { // get next instance vector Vector v = (Vector)e1.nextElement(); for(Enumeration e2 = v.elements(); e2.hasMoreElements(); ) { // get next instance variable BaseType bt = (BaseType)e2.nextElement(); pw.print(bt.toASCIIFlatName(rootName)+","); } break; } */ pw.println(""); int i = 0; for (Enumeration e1 = allValues.elements(); e1.hasMoreElements();) { int j = 0; // get next instance vector Vector v = (Vector) e1.nextElement(); for (Enumeration e2 = v.elements(); e2.hasMoreElements();) { // get next instance variable toASCII ta = (toASCII) e2.nextElement(); if (j > 0) pw.print(", "); ta.toASCII(pw, false, rootName, false); // depends on control dependency: [for], data = [none] j++; // depends on control dependency: [for], data = [none] } pw.println(""); // depends on control dependency: [for], data = [none] } if (newLine) pw.print("\n"); } }
public class class_name { @SuppressWarnings("unchecked") @Override public final <T extends SolrDataQuery> T setFacetOptions(@Nullable FacetOptions facetOptions) { if (facetOptions != null) { Assert.isTrue(facetOptions.hasFacets(), "Cannot set facet options having neither fields nor queries."); } this.facetOptions = facetOptions; return (T) this; } }
public class class_name { @SuppressWarnings("unchecked") @Override public final <T extends SolrDataQuery> T setFacetOptions(@Nullable FacetOptions facetOptions) { if (facetOptions != null) { Assert.isTrue(facetOptions.hasFacets(), "Cannot set facet options having neither fields nor queries."); // depends on control dependency: [if], data = [(facetOptions] } this.facetOptions = facetOptions; return (T) this; } }
public class class_name { @Override public void send(Message message) throws MessagingException { LOG.info("Sending message..."); LOG.debug("{}", message); LOG.debug("Find senders that is able to send the message {}", message); boolean sent = false; for (ConditionalSender sender : senders) { if (sender.supports(message)) { LOG.debug("Sending message {} using sender {}...", message, sender); sender.send(message); LOG.debug("Message {} sent using sender {}", message, sender); sent = true; } else { LOG.debug("Sender {} can't handle the message {}", sender, message); } } if(sent) { LOG.info("Message sent"); LOG.debug("{}", message); } else { throw new MessageNotSentException("No sender available to send the message", message); } } }
public class class_name { @Override public void send(Message message) throws MessagingException { LOG.info("Sending message..."); LOG.debug("{}", message); LOG.debug("Find senders that is able to send the message {}", message); boolean sent = false; for (ConditionalSender sender : senders) { if (sender.supports(message)) { LOG.debug("Sending message {} using sender {}...", message, sender); // depends on control dependency: [if], data = [none] sender.send(message); // depends on control dependency: [if], data = [none] LOG.debug("Message {} sent using sender {}", message, sender); // depends on control dependency: [if], data = [none] sent = true; // depends on control dependency: [if], data = [none] } else { LOG.debug("Sender {} can't handle the message {}", sender, message); // depends on control dependency: [if], data = [none] } } if(sent) { LOG.info("Message sent"); LOG.debug("{}", message); } else { throw new MessageNotSentException("No sender available to send the message", message); } } }
public class class_name { public static ProcessEngine lookupProcessEngine(String engineName) { ServiceLoader<ProcessEngineProvider> serviceLoader = ServiceLoader.load(ProcessEngineProvider.class); Iterator<ProcessEngineProvider> iterator = serviceLoader.iterator(); if(iterator.hasNext()) { ProcessEngineProvider provider = iterator.next(); if (engineName == null) { return provider.getDefaultProcessEngine(); } else { return provider.getProcessEngine(engineName); } } else { throw new RestException(Status.INTERNAL_SERVER_ERROR, "Could not find an implementation of the "+ProcessEngineProvider.class+"- SPI"); } } }
public class class_name { public static ProcessEngine lookupProcessEngine(String engineName) { ServiceLoader<ProcessEngineProvider> serviceLoader = ServiceLoader.load(ProcessEngineProvider.class); Iterator<ProcessEngineProvider> iterator = serviceLoader.iterator(); if(iterator.hasNext()) { ProcessEngineProvider provider = iterator.next(); if (engineName == null) { return provider.getDefaultProcessEngine(); // depends on control dependency: [if], data = [none] } else { return provider.getProcessEngine(engineName); // depends on control dependency: [if], data = [(engineName] } } else { throw new RestException(Status.INTERNAL_SERVER_ERROR, "Could not find an implementation of the "+ProcessEngineProvider.class+"- SPI"); } } }
public class class_name { private synchronized void refresh() { pendingRefresh.set(null); // Clear if(LOG.isDebuggingFine()) { LOG.debugFine("Refresh in thread " + Thread.currentThread().getName()); } boolean updateStyle = false; Iterator<Entry<VisualizationTask, Visualization>> it = taskmap.entrySet().stream() // .sorted((a, b) -> Integer.compare(a.getKey().level(), b.getKey().level())) // .iterator(); Element insertpos = null; while(it.hasNext()) { Entry<VisualizationTask, Visualization> ent = it.next(); VisualizationTask task = ent.getKey(); Visualization vis = ent.getValue(); if(!task.isVisible()) { if(vis != null) { SVGUtil.removeFromParent(vis.getLayer()); } continue; } if(vis == null) { ent.setValue(vis = instantiateVisualization(task)); } Element layer = vis.getLayer(); if(task.has(RenderFlag.NO_EXPORT)) { layer.setAttribute(NO_EXPORT_ATTRIBUTE, NO_EXPORT_ATTRIBUTE); } // Insert or append if(layer.getParentNode() != getRoot()) { if(insertpos != null && insertpos.getNextSibling() != null) { getRoot().insertBefore(layer, insertpos.getNextSibling()); } else { getRoot().appendChild(layer); } } updateStyle = true; insertpos = layer; } if(updateStyle) { updateStyleElement(); } } }
public class class_name { private synchronized void refresh() { pendingRefresh.set(null); // Clear if(LOG.isDebuggingFine()) { LOG.debugFine("Refresh in thread " + Thread.currentThread().getName()); // depends on control dependency: [if], data = [none] } boolean updateStyle = false; Iterator<Entry<VisualizationTask, Visualization>> it = taskmap.entrySet().stream() // .sorted((a, b) -> Integer.compare(a.getKey().level(), b.getKey().level())) // .iterator(); Element insertpos = null; while(it.hasNext()) { Entry<VisualizationTask, Visualization> ent = it.next(); VisualizationTask task = ent.getKey(); Visualization vis = ent.getValue(); if(!task.isVisible()) { if(vis != null) { SVGUtil.removeFromParent(vis.getLayer()); // depends on control dependency: [if], data = [(vis] } continue; } if(vis == null) { ent.setValue(vis = instantiateVisualization(task)); // depends on control dependency: [if], data = [(vis] } Element layer = vis.getLayer(); if(task.has(RenderFlag.NO_EXPORT)) { layer.setAttribute(NO_EXPORT_ATTRIBUTE, NO_EXPORT_ATTRIBUTE); // depends on control dependency: [if], data = [none] } // Insert or append if(layer.getParentNode() != getRoot()) { if(insertpos != null && insertpos.getNextSibling() != null) { getRoot().insertBefore(layer, insertpos.getNextSibling()); // depends on control dependency: [if], data = [none] } else { getRoot().appendChild(layer); // depends on control dependency: [if], data = [none] } } updateStyle = true; // depends on control dependency: [while], data = [none] insertpos = layer; // depends on control dependency: [while], data = [none] } if(updateStyle) { updateStyleElement(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static final int findNextCharNotPrefixedBy(ByteBuf buf, char c, char prefix) { int found = buf.bytesBefore((byte) c); if (found < 1) { return found; } else { int from; while (found > -1 && (char) buf.getByte( buf.readerIndex() + found - 1) == prefix) { //advance from from = buf.readerIndex() + found + 1; //search again int next = buf.bytesBefore(from, buf.readableBytes() - from + buf.readerIndex(), (byte) c); if (next == -1) { return -1; } else { found += next + 1; } } return found; } } }
public class class_name { public static final int findNextCharNotPrefixedBy(ByteBuf buf, char c, char prefix) { int found = buf.bytesBefore((byte) c); if (found < 1) { return found; // depends on control dependency: [if], data = [none] } else { int from; while (found > -1 && (char) buf.getByte( buf.readerIndex() + found - 1) == prefix) { //advance from from = buf.readerIndex() + found + 1; // depends on control dependency: [while], data = [none] //search again int next = buf.bytesBefore(from, buf.readableBytes() - from + buf.readerIndex(), (byte) c); if (next == -1) { return -1; // depends on control dependency: [if], data = [none] } else { found += next + 1; // depends on control dependency: [if], data = [none] } } return found; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static BugCollection combineBugHistories() { try { FBFileChooser chooser = new FBFileChooser(); chooser.setFileFilter(new FindBugsAnalysisFileFilter()); // chooser.setCurrentDirectory(GUISaveState.getInstance().getStarterDirectoryForLoadBugs()); // This is done by FBFileChooser. chooser.setMultiSelectionEnabled(true); chooser.setDialogTitle(edu.umd.cs.findbugs.L10N.getLocalString("dlg.choose_xmls_ttl", "Choose All XML's To Combine")); if (chooser.showOpenDialog(MainFrame.getInstance()) == JFileChooser.CANCEL_OPTION) { return null; } SortedBugCollection conglomeration = new SortedBugCollection(); conglomeration.readXML(chooser.getSelectedFiles()[0]); Update update = new Update(); for (int x = 1; x < chooser.getSelectedFiles().length; x++) { File f = chooser.getSelectedFiles()[x]; SortedBugCollection col = new SortedBugCollection(); col.readXML(f); conglomeration = (SortedBugCollection) update.mergeCollections(conglomeration, col, false, false);// False // means // dont // show // dead // bugs } return conglomeration; } catch (IOException e) { Debug.println(e); return null; } catch (DocumentException e) { Debug.println(e); return null; } } }
public class class_name { public static BugCollection combineBugHistories() { try { FBFileChooser chooser = new FBFileChooser(); chooser.setFileFilter(new FindBugsAnalysisFileFilter()); // depends on control dependency: [try], data = [none] // chooser.setCurrentDirectory(GUISaveState.getInstance().getStarterDirectoryForLoadBugs()); // This is done by FBFileChooser. chooser.setMultiSelectionEnabled(true); // depends on control dependency: [try], data = [none] chooser.setDialogTitle(edu.umd.cs.findbugs.L10N.getLocalString("dlg.choose_xmls_ttl", "Choose All XML's To Combine")); // depends on control dependency: [try], data = [none] if (chooser.showOpenDialog(MainFrame.getInstance()) == JFileChooser.CANCEL_OPTION) { return null; // depends on control dependency: [if], data = [none] } SortedBugCollection conglomeration = new SortedBugCollection(); conglomeration.readXML(chooser.getSelectedFiles()[0]); // depends on control dependency: [try], data = [none] Update update = new Update(); // depends on control dependency: [try], data = [none] for (int x = 1; x < chooser.getSelectedFiles().length; x++) { File f = chooser.getSelectedFiles()[x]; SortedBugCollection col = new SortedBugCollection(); col.readXML(f); // depends on control dependency: [for], data = [none] conglomeration = (SortedBugCollection) update.mergeCollections(conglomeration, col, false, false);// False // depends on control dependency: [for], data = [none] // means // dont // show // dead // bugs } return conglomeration; // depends on control dependency: [try], data = [none] } catch (IOException e) { Debug.println(e); return null; } catch (DocumentException e) { // depends on control dependency: [catch], data = [none] Debug.println(e); return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { private List<NumberPattern> getNumberPattern(String pattern) { int i = pattern.indexOf(';'); if (i == -1) { return Arrays.asList( parseNumberPattern(pattern), parseNumberPattern("-" + pattern)); } return Arrays.asList( parseNumberPattern(pattern.substring(0, i)), parseNumberPattern(pattern.substring(i+1))); } }
public class class_name { private List<NumberPattern> getNumberPattern(String pattern) { int i = pattern.indexOf(';'); if (i == -1) { return Arrays.asList( parseNumberPattern(pattern), parseNumberPattern("-" + pattern)); // depends on control dependency: [if], data = [none] } return Arrays.asList( parseNumberPattern(pattern.substring(0, i)), parseNumberPattern(pattern.substring(i+1))); } }
public class class_name { public boolean isIncluded(Element e) { if (e == null) { return false; } if (includedVisitor == null) { includedVisitor = new IncludedVisitor(); } return includedVisitor.visit(e); } }
public class class_name { public boolean isIncluded(Element e) { if (e == null) { return false; // depends on control dependency: [if], data = [none] } if (includedVisitor == null) { includedVisitor = new IncludedVisitor(); // depends on control dependency: [if], data = [none] } return includedVisitor.visit(e); } }
public class class_name { public void put(Serializable key, Object value, CacheType cacheType) { if (enabled) { super.put(key, value, cacheType); } } }
public class class_name { public void put(Serializable key, Object value, CacheType cacheType) { if (enabled) { super.put(key, value, cacheType); // depends on control dependency: [if], data = [none] } } }
public class class_name { private INodeFileUnderConstruction unprotectedAddFile(long inodeId, String path, PermissionStatus permissions, short replication, long modificationTime, long atime, long preferredBlockSize, String clientName, String clientMachine) { INodeFileUnderConstruction newNode = new INodeFileUnderConstruction( inodeId, permissions, replication, preferredBlockSize, modificationTime, clientName, clientMachine, null); try { newNode = addNode(path, newNode, 0, false); } catch (IOException e) { return null; } return newNode; } }
public class class_name { private INodeFileUnderConstruction unprotectedAddFile(long inodeId, String path, PermissionStatus permissions, short replication, long modificationTime, long atime, long preferredBlockSize, String clientName, String clientMachine) { INodeFileUnderConstruction newNode = new INodeFileUnderConstruction( inodeId, permissions, replication, preferredBlockSize, modificationTime, clientName, clientMachine, null); try { newNode = addNode(path, newNode, 0, false); // depends on control dependency: [try], data = [none] } catch (IOException e) { return null; } // depends on control dependency: [catch], data = [none] return newNode; } }
public class class_name { public void put(CommsByteBuffer msgBuffer, short msgBatch, boolean lastInBatch, boolean chunk) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "put", new Object[]{msgBuffer, msgBatch, lastInBatch, chunk}); QueueData queueData = null; // If this data represents a chunk we need to read the flags from the buffer. This // will indicate to us whether we need to create some new queue data to stash on the // queue or if (chunk) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Dealing with a chunked message"); // Get the flags from the buffer byte flags = msgBuffer.get(); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Flags:", ""+flags); // Is this the first chunk? if ((flags & CommsConstants.CHUNKED_MESSAGE_FIRST) == CommsConstants.CHUNKED_MESSAGE_FIRST) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "First chunk received"); // If it is, create some new queue data to place on the queue with the initial // chunk queueData = new QueueData(this, lastInBatch, chunk, msgBuffer); // Put the data to the queue queue.put(queueData, msgBatch); } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Middle / Last chunk received"); // Otherwise, we need to append to the chunks already collected. We do this by // finding the chunk to append to. This will be the last message on the queue // (i.e. at the back). This works for all cases as an async consumer cannot be // driven concurrently (so the last incomplete message on the queue will be the // one we want). boolean lastChunk = ((flags & CommsConstants.CHUNKED_MESSAGE_LAST) == CommsConstants.CHUNKED_MESSAGE_LAST); queue.appendToLastMessage(msgBuffer, lastChunk); } } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Dealing with the entire message"); queueData = new QueueData(this, lastInBatch, chunk, msgBuffer); // Put the data to the queue queue.put(queueData, msgBatch); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "put"); } }
public class class_name { public void put(CommsByteBuffer msgBuffer, short msgBatch, boolean lastInBatch, boolean chunk) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "put", new Object[]{msgBuffer, msgBatch, lastInBatch, chunk}); QueueData queueData = null; // If this data represents a chunk we need to read the flags from the buffer. This // will indicate to us whether we need to create some new queue data to stash on the // queue or if (chunk) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Dealing with a chunked message"); // Get the flags from the buffer byte flags = msgBuffer.get(); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Flags:", ""+flags); // Is this the first chunk? if ((flags & CommsConstants.CHUNKED_MESSAGE_FIRST) == CommsConstants.CHUNKED_MESSAGE_FIRST) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "First chunk received"); // If it is, create some new queue data to place on the queue with the initial // chunk queueData = new QueueData(this, lastInBatch, chunk, msgBuffer); // depends on control dependency: [if], data = [none] // Put the data to the queue queue.put(queueData, msgBatch); // depends on control dependency: [if], data = [none] } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Middle / Last chunk received"); // Otherwise, we need to append to the chunks already collected. We do this by // finding the chunk to append to. This will be the last message on the queue // (i.e. at the back). This works for all cases as an async consumer cannot be // driven concurrently (so the last incomplete message on the queue will be the // one we want). boolean lastChunk = ((flags & CommsConstants.CHUNKED_MESSAGE_LAST) == CommsConstants.CHUNKED_MESSAGE_LAST); queue.appendToLastMessage(msgBuffer, lastChunk); // depends on control dependency: [if], data = [none] } } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Dealing with the entire message"); queueData = new QueueData(this, lastInBatch, chunk, msgBuffer); // depends on control dependency: [if], data = [none] // Put the data to the queue queue.put(queueData, msgBatch); // depends on control dependency: [if], data = [none] } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "put"); } }
public class class_name { public static void main(String[] args) throws Exception { boolean valid = true; boolean requiredArguments = false; TileFormatType tileType = null; String imageFormat = null; boolean rawImage = false; File geoPackageFile = null; String tileTable = null; File outputDirectory = null; Integer width = null; Integer height = null; for (int i = 0; valid && i < args.length; i++) { String arg = args[i]; // Handle optional arguments if (arg.startsWith(ARGUMENT_PREFIX)) { String argument = arg.substring(ARGUMENT_PREFIX.length()); switch (argument) { case ARGUMENT_TILE_TYPE: if (i < args.length) { String tiletypeString = args[++i].toUpperCase(); try { tileType = TileFormatType.valueOf(tiletypeString); } catch (IllegalArgumentException e) { valid = false; System.out .println("Error: Image Tile Type argument '" + arg + "' must be followed by a valid tile format type. Invalid: " + tiletypeString); } } else { valid = false; System.out .println("Error: Tile Type argument '" + arg + "' must be followed by a tile type (geopackage, standard, tms)"); } break; case ARGUMENT_IMAGE_FORMAT: if (i < args.length) { imageFormat = args[++i]; } else { valid = false; System.out.println("Error: Image Format argument '" + arg + "' must be followed by a image format"); } break; case ARGUMENT_RAW_IMAGE: rawImage = true; break; case ARGUMENT_IMAGE_WIDTH: if (i < args.length) { String widthString = args[++i]; try { width = Integer.valueOf(widthString); } catch (NumberFormatException e) { valid = false; System.out .println("Error: Image Width argument '" + arg + "' must be followed by a valid width in pixels. Invalid: " + widthString); } } else { valid = false; System.out .println("Error: Image Width argument '" + arg + "' must be followed by a image width in pixels"); } break; case ARGUMENT_IMAGE_HEIGHT: if (i < args.length) { String heightString = args[++i]; try { height = Integer.valueOf(heightString); } catch (NumberFormatException e) { valid = false; System.out .println("Error: Image Height argument '" + arg + "' must be followed by a valid height in pixels. Invalid: " + heightString); } } else { valid = false; System.out .println("Error: Image Height argument '" + arg + "' must be followed by a height width in pixels"); } break; default: valid = false; System.out.println("Error: Unsupported arg: '" + arg + "'"); } } else { // Set required arguments in order if (geoPackageFile == null) { geoPackageFile = new File(arg); } else if (tileTable == null) { tileTable = arg; } else if (outputDirectory == null) { outputDirectory = new File(arg); requiredArguments = true; } else { valid = false; System.out.println("Error: Unsupported extra argument: " + arg); } } } if (!valid || !requiredArguments) { printUsage(); } else { // Write the tiles try { writeTiles(geoPackageFile, tileTable, outputDirectory, imageFormat, width, height, tileType, rawImage); } catch (Exception e) { printUsage(); throw e; } } } }
public class class_name { public static void main(String[] args) throws Exception { boolean valid = true; boolean requiredArguments = false; TileFormatType tileType = null; String imageFormat = null; boolean rawImage = false; File geoPackageFile = null; String tileTable = null; File outputDirectory = null; Integer width = null; Integer height = null; for (int i = 0; valid && i < args.length; i++) { String arg = args[i]; // Handle optional arguments if (arg.startsWith(ARGUMENT_PREFIX)) { String argument = arg.substring(ARGUMENT_PREFIX.length()); switch (argument) { case ARGUMENT_TILE_TYPE: if (i < args.length) { String tiletypeString = args[++i].toUpperCase(); try { tileType = TileFormatType.valueOf(tiletypeString); // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException e) { valid = false; System.out .println("Error: Image Tile Type argument '" + arg + "' must be followed by a valid tile format type. Invalid: " + tiletypeString); } // depends on control dependency: [catch], data = [none] } else { valid = false; // depends on control dependency: [if], data = [none] System.out .println("Error: Tile Type argument '" + arg + "' must be followed by a tile type (geopackage, standard, tms)"); // depends on control dependency: [if], data = [none] } break; case ARGUMENT_IMAGE_FORMAT: if (i < args.length) { imageFormat = args[++i]; // depends on control dependency: [if], data = [none] } else { valid = false; // depends on control dependency: [if], data = [none] System.out.println("Error: Image Format argument '" + arg + "' must be followed by a image format"); // depends on control dependency: [if], data = [none] } break; case ARGUMENT_RAW_IMAGE: rawImage = true; break; case ARGUMENT_IMAGE_WIDTH: if (i < args.length) { String widthString = args[++i]; try { width = Integer.valueOf(widthString); // depends on control dependency: [try], data = [none] } catch (NumberFormatException e) { valid = false; System.out .println("Error: Image Width argument '" + arg + "' must be followed by a valid width in pixels. Invalid: " + widthString); } // depends on control dependency: [catch], data = [none] } else { valid = false; // depends on control dependency: [if], data = [none] System.out .println("Error: Image Width argument '" + arg + "' must be followed by a image width in pixels"); // depends on control dependency: [if], data = [none] } break; case ARGUMENT_IMAGE_HEIGHT: if (i < args.length) { String heightString = args[++i]; try { height = Integer.valueOf(heightString); // depends on control dependency: [try], data = [none] } catch (NumberFormatException e) { valid = false; System.out .println("Error: Image Height argument '" + arg + "' must be followed by a valid height in pixels. Invalid: " + heightString); } // depends on control dependency: [catch], data = [none] } else { valid = false; // depends on control dependency: [if], data = [none] System.out .println("Error: Image Height argument '" + arg + "' must be followed by a height width in pixels"); // depends on control dependency: [if], data = [none] } break; default: valid = false; System.out.println("Error: Unsupported arg: '" + arg + "'"); } } else { // Set required arguments in order if (geoPackageFile == null) { geoPackageFile = new File(arg); // depends on control dependency: [if], data = [none] } else if (tileTable == null) { tileTable = arg; // depends on control dependency: [if], data = [none] } else if (outputDirectory == null) { outputDirectory = new File(arg); // depends on control dependency: [if], data = [none] requiredArguments = true; // depends on control dependency: [if], data = [none] } else { valid = false; // depends on control dependency: [if], data = [none] System.out.println("Error: Unsupported extra argument: " + arg); // depends on control dependency: [if], data = [none] } } } if (!valid || !requiredArguments) { printUsage(); } else { // Write the tiles try { writeTiles(geoPackageFile, tileTable, outputDirectory, imageFormat, width, height, tileType, rawImage); } catch (Exception e) { printUsage(); throw e; } } } }
public class class_name { public static void forceDelete(File file) { if (file.exists()) { // If the File instance to delete is a directory, delete all it's // contents. if (file.isDirectory()) { for (File contentFile : file.listFiles()) { forceDelete(contentFile); } } if (file.delete()) { log.d("File " + file.getPath() + " was succesfully deleted."); } else { log.w("File " + file.getPath() + " couldn't be deleted."); } } } }
public class class_name { public static void forceDelete(File file) { if (file.exists()) { // If the File instance to delete is a directory, delete all it's // contents. if (file.isDirectory()) { for (File contentFile : file.listFiles()) { forceDelete(contentFile); // depends on control dependency: [for], data = [contentFile] } } if (file.delete()) { log.d("File " + file.getPath() + " was succesfully deleted."); // depends on control dependency: [if], data = [none] } else { log.w("File " + file.getPath() + " couldn't be deleted."); // depends on control dependency: [if], data = [none] } } } }
public class class_name { private boolean transfer(long total, GlobusInputStream in, GlobusOutputStream out) throws IOException { byte [] buffer = new byte[bufferSize]; int bytes = 0; long totalBytes = total; long transferedBytes = 0; if (total == -1) { while( (bytes = in.read(buffer)) != -1) { out.write(buffer, 0, bytes); out.flush(); if (listeners != null) { transferedBytes += bytes; fireUrlTransferProgressEvent(totalBytes, transferedBytes); } if (isCanceled()) return false; } } else { while ( total != 0 ) { bytes = bufferSize; if (total < bufferSize) bytes = (int)total; bytes = in.read(buffer); out.write(buffer, 0, bytes); out.flush(); total -= bytes; if (listeners != null) { transferedBytes += bytes; fireUrlTransferProgressEvent(totalBytes, transferedBytes); } if (isCanceled()) return false; } } return true; } }
public class class_name { private boolean transfer(long total, GlobusInputStream in, GlobusOutputStream out) throws IOException { byte [] buffer = new byte[bufferSize]; int bytes = 0; long totalBytes = total; long transferedBytes = 0; if (total == -1) { while( (bytes = in.read(buffer)) != -1) { out.write(buffer, 0, bytes); out.flush(); if (listeners != null) { transferedBytes += bytes; // depends on control dependency: [if], data = [none] fireUrlTransferProgressEvent(totalBytes, transferedBytes); // depends on control dependency: [if], data = [none] } if (isCanceled()) return false; } } else { while ( total != 0 ) { bytes = bufferSize; if (total < bufferSize) bytes = (int)total; bytes = in.read(buffer); out.write(buffer, 0, bytes); out.flush(); total -= bytes; if (listeners != null) { transferedBytes += bytes; fireUrlTransferProgressEvent(totalBytes, transferedBytes); } if (isCanceled()) return false; } } return true; } }
public class class_name { @SuppressWarnings("unchecked") private static void setMapParam(Field field, List<?> values) { try { // Find Map method: put(Object, Object) Class<?> fieldClass = field.getType(); Method addMethod = fieldClass.getMethod("put", Object.class, Object.class); // Add each map key/value to field value for (Object subParam : values) { if (subParam instanceof Map) { Map<String, ?> map = (Map<String, ?>)subParam; for (String key : map.keySet()) { Object value = map.get(key); if (value instanceof List) { // Contains a single element, which is a key/value map value = ((List<?>)value).get(0); } addMethod.invoke(field.get(config), key, value); } } else { throw new RuntimeException("Unexpected collection parameter type for '" + field.getName() + ":" + subParam); } } } catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { throw new RuntimeException("Error setting configuration parameter '" + field.getName() + "'", e); } } }
public class class_name { @SuppressWarnings("unchecked") private static void setMapParam(Field field, List<?> values) { try { // Find Map method: put(Object, Object) Class<?> fieldClass = field.getType(); Method addMethod = fieldClass.getMethod("put", Object.class, Object.class); // Add each map key/value to field value for (Object subParam : values) { if (subParam instanceof Map) { Map<String, ?> map = (Map<String, ?>)subParam; for (String key : map.keySet()) { Object value = map.get(key); if (value instanceof List) { // Contains a single element, which is a key/value map value = ((List<?>)value).get(0); // depends on control dependency: [if], data = [none] } addMethod.invoke(field.get(config), key, value); // depends on control dependency: [for], data = [key] } } else { throw new RuntimeException("Unexpected collection parameter type for '" + field.getName() + ":" + subParam); } } } catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException | IllegalAccessException e) { throw new RuntimeException("Error setting configuration parameter '" + field.getName() + "'", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public void setChildren(Tree[] children) { if (children == null) { daughterTrees = EMPTY_TREE_ARRAY; } else { daughterTrees = children; } } }
public class class_name { @Override public void setChildren(Tree[] children) { if (children == null) { daughterTrees = EMPTY_TREE_ARRAY; // depends on control dependency: [if], data = [none] } else { daughterTrees = children; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String decrypt(CharSequence data, CharSequence cipherKey) { final int dataLen = data.length(); final int cipherKeyLen = cipherKey.length(); final char[] clearArray = new char[dataLen]; for (int i = 0; i < dataLen; i++) { for (int t = 0; t < cipherKeyLen; t++) { if (t + i * cipherKeyLen < dataLen) { final char dataChar = data.charAt(t + i * cipherKeyLen); final char cipherKeyChar = cipherKey.charAt(t); if (dataChar - cipherKeyChar >= 0) { clearArray[t + i * cipherKeyLen] = (char) ((dataChar - cipherKeyChar) % 95 + 32); } else { clearArray[t + i * cipherKeyLen] = (char) ((dataChar - cipherKeyChar + 95) % 95 + 32); } } } } return String.valueOf(clearArray); } }
public class class_name { public static String decrypt(CharSequence data, CharSequence cipherKey) { final int dataLen = data.length(); final int cipherKeyLen = cipherKey.length(); final char[] clearArray = new char[dataLen]; for (int i = 0; i < dataLen; i++) { for (int t = 0; t < cipherKeyLen; t++) { if (t + i * cipherKeyLen < dataLen) { final char dataChar = data.charAt(t + i * cipherKeyLen); final char cipherKeyChar = cipherKey.charAt(t); if (dataChar - cipherKeyChar >= 0) { clearArray[t + i * cipherKeyLen] = (char) ((dataChar - cipherKeyChar) % 95 + 32); // depends on control dependency: [if], data = [(dataChar - cipherKeyChar] } else { clearArray[t + i * cipherKeyLen] = (char) ((dataChar - cipherKeyChar + 95) % 95 + 32); // depends on control dependency: [if], data = [(dataChar - cipherKeyChar] } } } } return String.valueOf(clearArray); } }
public class class_name { public static RelationMetadataProcessor getRelationMetadataProcessor(Field relationField, KunderaMetadata kunderaMetadata) { RelationMetadataProcessor relProcessor = null; // OneToOne if (relationField.isAnnotationPresent(OneToOne.class)) { relProcessor = new OneToOneRelationMetadataProcessor(kunderaMetadata); } // OneToMany else if (relationField.isAnnotationPresent(OneToMany.class)) { relProcessor = new OneToManyRelationMetadataProcessor(kunderaMetadata); } // ManyToOne else if (relationField.isAnnotationPresent(ManyToOne.class)) { relProcessor = new ManyToOneRelationMetadataProcessor(kunderaMetadata); } // ManyToMany else if (relationField.isAnnotationPresent(ManyToMany.class)) { relProcessor = new ManyToManyRelationMetadataProcessor(kunderaMetadata); } return relProcessor; } }
public class class_name { public static RelationMetadataProcessor getRelationMetadataProcessor(Field relationField, KunderaMetadata kunderaMetadata) { RelationMetadataProcessor relProcessor = null; // OneToOne if (relationField.isAnnotationPresent(OneToOne.class)) { relProcessor = new OneToOneRelationMetadataProcessor(kunderaMetadata); // depends on control dependency: [if], data = [none] } // OneToMany else if (relationField.isAnnotationPresent(OneToMany.class)) { relProcessor = new OneToManyRelationMetadataProcessor(kunderaMetadata); // depends on control dependency: [if], data = [none] } // ManyToOne else if (relationField.isAnnotationPresent(ManyToOne.class)) { relProcessor = new ManyToOneRelationMetadataProcessor(kunderaMetadata); // depends on control dependency: [if], data = [none] } // ManyToMany else if (relationField.isAnnotationPresent(ManyToMany.class)) { relProcessor = new ManyToManyRelationMetadataProcessor(kunderaMetadata); // depends on control dependency: [if], data = [none] } return relProcessor; } }
public class class_name { public static String last(String string, char separator) { if(string == null) { return null; } if(string.isEmpty()) { return ""; } return string.substring(string.lastIndexOf(separator) + 1); } }
public class class_name { public static String last(String string, char separator) { if(string == null) { return null; // depends on control dependency: [if], data = [none] } if(string.isEmpty()) { return ""; // depends on control dependency: [if], data = [none] } return string.substring(string.lastIndexOf(separator) + 1); } }
public class class_name { @Override public Map<String, Object> toSource() { Map<String, Object> sourceMap = new HashMap<>(); if (createdAt != null) { addFieldToSource(sourceMap, "createdAt", createdAt); } if (docId != null) { addFieldToSource(sourceMap, "docId", docId); } if (queryId != null) { addFieldToSource(sourceMap, "queryId", queryId); } if (url != null) { addFieldToSource(sourceMap, "url", url); } if (userInfoId != null) { addFieldToSource(sourceMap, "userInfoId", userInfoId); } return sourceMap; } }
public class class_name { @Override public Map<String, Object> toSource() { Map<String, Object> sourceMap = new HashMap<>(); if (createdAt != null) { addFieldToSource(sourceMap, "createdAt", createdAt); // depends on control dependency: [if], data = [none] } if (docId != null) { addFieldToSource(sourceMap, "docId", docId); // depends on control dependency: [if], data = [none] } if (queryId != null) { addFieldToSource(sourceMap, "queryId", queryId); // depends on control dependency: [if], data = [none] } if (url != null) { addFieldToSource(sourceMap, "url", url); // depends on control dependency: [if], data = [none] } if (userInfoId != null) { addFieldToSource(sourceMap, "userInfoId", userInfoId); // depends on control dependency: [if], data = [none] } return sourceMap; } }
public class class_name { public Set<Artifact> filterArtifacts( Set<Artifact> dependencies ) { if ( includes == null && excludes == null ) { return dependencies; } AndArtifactFilter filter = new AndArtifactFilter( ); if ( includes != null ) { filter.add( new StrictPatternIncludesArtifactFilter( includes ) ); } if ( excludes != null ) { filter.add( new StrictPatternExcludesArtifactFilter( excludes ) ); } Set<Artifact> result = new HashSet<Artifact>(); for ( Artifact artifact : dependencies ) { if ( filter.include( artifact ) ) { result.add( artifact ); } } return result; } }
public class class_name { public Set<Artifact> filterArtifacts( Set<Artifact> dependencies ) { if ( includes == null && excludes == null ) { return dependencies; // depends on control dependency: [if], data = [none] } AndArtifactFilter filter = new AndArtifactFilter( ); if ( includes != null ) { filter.add( new StrictPatternIncludesArtifactFilter( includes ) ); // depends on control dependency: [if], data = [( includes] } if ( excludes != null ) { filter.add( new StrictPatternExcludesArtifactFilter( excludes ) ); // depends on control dependency: [if], data = [( excludes] } Set<Artifact> result = new HashSet<Artifact>(); for ( Artifact artifact : dependencies ) { if ( filter.include( artifact ) ) { result.add( artifact ); // depends on control dependency: [if], data = [none] } } return result; } }
public class class_name { public int nextNode() { int nextNode = DTM.NULL; AxesWalker walker = wi().getLastUsedWalker(); while (true) { if (null == walker) break; nextNode = walker.getNextNode(); if (DTM.NULL == nextNode) { walker = walker.m_prevWalker; } else { if (walker.acceptNode(nextNode) != DTMIterator.FILTER_ACCEPT) { continue; } if (null == walker.m_nextWalker) { wi().setLastUsedWalker(walker); // return walker.returnNextNode(nextNode); break; } else { AxesWalker prev = walker; walker = walker.m_nextWalker; walker.setRoot(nextNode); walker.m_prevWalker = prev; continue; } } // if(null != nextNode) } // while(null != walker) return nextNode; } }
public class class_name { public int nextNode() { int nextNode = DTM.NULL; AxesWalker walker = wi().getLastUsedWalker(); while (true) { if (null == walker) break; nextNode = walker.getNextNode(); // depends on control dependency: [while], data = [none] if (DTM.NULL == nextNode) { walker = walker.m_prevWalker; // depends on control dependency: [if], data = [none] } else { if (walker.acceptNode(nextNode) != DTMIterator.FILTER_ACCEPT) { continue; } if (null == walker.m_nextWalker) { wi().setLastUsedWalker(walker); // depends on control dependency: [if], data = [none] // return walker.returnNextNode(nextNode); break; } else { AxesWalker prev = walker; walker = walker.m_nextWalker; // depends on control dependency: [if], data = [none] walker.setRoot(nextNode); // depends on control dependency: [if], data = [none] walker.m_prevWalker = prev; // depends on control dependency: [if], data = [none] continue; } } // if(null != nextNode) } // while(null != walker) return nextNode; } }
public class class_name { private void buildDirectives(PatternCacheControl patternCacheControl) { for (Map.Entry<Directive, String> entry : patternCacheControl.getDirectives().entrySet()) { Directive key = entry.getKey(); String value = entry.getValue(); switch (key) { case MAX_AGE: case MAX_AGE_MPLUS: maxAgeDirectives.put(key, value); break; default: if (value.equals(EMPTY_STRING_VALUE)) { staticDirectives.append(key.getName() + DIRECTIVES_SEPARATOR); break; } staticDirectives.append(key.getName() + EQUALS_STRING + value + DIRECTIVES_SEPARATOR); } } } }
public class class_name { private void buildDirectives(PatternCacheControl patternCacheControl) { for (Map.Entry<Directive, String> entry : patternCacheControl.getDirectives().entrySet()) { Directive key = entry.getKey(); String value = entry.getValue(); switch (key) { case MAX_AGE: case MAX_AGE_MPLUS: maxAgeDirectives.put(key, value); break; default: if (value.equals(EMPTY_STRING_VALUE)) { staticDirectives.append(key.getName() + DIRECTIVES_SEPARATOR); // depends on control dependency: [if], data = [none] break; } staticDirectives.append(key.getName() + EQUALS_STRING + value + DIRECTIVES_SEPARATOR); } } } }
public class class_name { public Array readVariable(Variable v2, Section section) throws IOException, InvalidRangeException { // not sure why timeRange isn't used...will comment out // for now // TODO: use timeRange in readVariable //Range timeRange = null; Range bandRange = null; Range geoXRange = null; Range geoYRange = null; Array dataArray; if (section == null) { dataArray = Array.factory(v2.getDataType(), v2.getShape()); } else if (section.getRank() > 0) { if (section.getRank() > 3) { //timeRange = (Range) section.getRange(0); bandRange = section.getRange(1); geoYRange = section.getRange(2); geoXRange = section.getRange(3); } else if (section.getRank() > 2) { //timeRange = (Range) section.getRange(0); geoYRange = section.getRange(1); geoXRange = section.getRange(2); } else if (section.getRank() > 1) { geoYRange = section.getRange(0); geoXRange = section.getRange(1); } dataArray = Array.factory(v2.getDataType(), section.getShape()); } else { String strRank = Integer.toString(section.getRank()); String msg = "Invalid Rank: " + strRank + ". Must be > 0."; throw new IndexOutOfBoundsException(msg); } String varname = v2.getFullName(); Index dataIndex = dataArray.getIndex(); if (varname.equals("latitude") || varname.equals("longitude")) { double[][] pixel = new double[2][1]; double[][] latLon; assert geoXRange != null; assert geoYRange != null; // Use Range object, which calculates requested i, j // values and incorporates stride for (int i = 0; i < geoXRange.length(); i++) { for (int j = 0; j < geoYRange.length(); j++) { pixel[0][0] = (double) geoXRange.element(i); pixel[1][0] = (double) geoYRange.element(j); latLon = nav.toLatLon(pixel); if (varname.equals("lat")) { dataArray.setFloat(dataIndex.set(j, i), (float) (latLon[0][0])); } else { dataArray.setFloat(dataIndex.set(j, i), (float) (latLon[1][0])); } } } } if (varname.equals("image")) { try { int[][] pixelData; if (bandRange != null) { for (int k = 0; k < bandRange.length(); k++) { int bandIndex = bandRange.element(k) + 1; // band numbers in McIDAS are 1 based for (int j = 0; j < geoYRange.length(); j++) { for (int i = 0; i < geoXRange.length(); i++) { pixelData = af.getData(geoYRange.element(j), geoXRange.element(i), 1, 1, bandIndex); dataArray.setInt(dataIndex.set(0, k, j, i), (pixelData[0][0])); } } } } else { assert geoXRange != null; assert geoYRange != null; for (int j = 0; j < geoYRange.length(); j++) { for (int i = 0; i < geoXRange.length(); i++) { pixelData = af.getData(geoYRange.element(j), geoXRange.element(i), 1, 1); dataArray.setInt(dataIndex.set(0, j, i), (pixelData[0][0])); } } } } catch (AreaFileException afe) { throw new IOException(afe.toString()); } } return dataArray; } }
public class class_name { public Array readVariable(Variable v2, Section section) throws IOException, InvalidRangeException { // not sure why timeRange isn't used...will comment out // for now // TODO: use timeRange in readVariable //Range timeRange = null; Range bandRange = null; Range geoXRange = null; Range geoYRange = null; Array dataArray; if (section == null) { dataArray = Array.factory(v2.getDataType(), v2.getShape()); } else if (section.getRank() > 0) { if (section.getRank() > 3) { //timeRange = (Range) section.getRange(0); bandRange = section.getRange(1); // depends on control dependency: [if], data = [none] geoYRange = section.getRange(2); // depends on control dependency: [if], data = [none] geoXRange = section.getRange(3); // depends on control dependency: [if], data = [3)] } else if (section.getRank() > 2) { //timeRange = (Range) section.getRange(0); geoYRange = section.getRange(1); // depends on control dependency: [if], data = [none] geoXRange = section.getRange(2); // depends on control dependency: [if], data = [2)] } else if (section.getRank() > 1) { geoYRange = section.getRange(0); // depends on control dependency: [if], data = [none] geoXRange = section.getRange(1); // depends on control dependency: [if], data = [1)] } dataArray = Array.factory(v2.getDataType(), section.getShape()); } else { String strRank = Integer.toString(section.getRank()); String msg = "Invalid Rank: " + strRank + ". Must be > 0."; throw new IndexOutOfBoundsException(msg); } String varname = v2.getFullName(); Index dataIndex = dataArray.getIndex(); if (varname.equals("latitude") || varname.equals("longitude")) { double[][] pixel = new double[2][1]; double[][] latLon; assert geoXRange != null; assert geoYRange != null; // Use Range object, which calculates requested i, j // values and incorporates stride for (int i = 0; i < geoXRange.length(); i++) { for (int j = 0; j < geoYRange.length(); j++) { pixel[0][0] = (double) geoXRange.element(i); pixel[1][0] = (double) geoYRange.element(j); latLon = nav.toLatLon(pixel); if (varname.equals("lat")) { dataArray.setFloat(dataIndex.set(j, i), (float) (latLon[0][0])); } else { dataArray.setFloat(dataIndex.set(j, i), (float) (latLon[1][0])); } } } } if (varname.equals("image")) { try { int[][] pixelData; if (bandRange != null) { for (int k = 0; k < bandRange.length(); k++) { int bandIndex = bandRange.element(k) + 1; // band numbers in McIDAS are 1 based for (int j = 0; j < geoYRange.length(); j++) { for (int i = 0; i < geoXRange.length(); i++) { pixelData = af.getData(geoYRange.element(j), geoXRange.element(i), 1, 1, bandIndex); dataArray.setInt(dataIndex.set(0, k, j, i), (pixelData[0][0])); } } } } else { assert geoXRange != null; assert geoYRange != null; for (int j = 0; j < geoYRange.length(); j++) { for (int i = 0; i < geoXRange.length(); i++) { pixelData = af.getData(geoYRange.element(j), geoXRange.element(i), 1, 1); dataArray.setInt(dataIndex.set(0, j, i), (pixelData[0][0])); } } } } catch (AreaFileException afe) { throw new IOException(afe.toString()); } } return dataArray; } }
public class class_name { public static Text[] toTextArray(Document doc, Object o) throws PageException { // Node[] if (o instanceof Node[]) { Node[] nodes = (Node[]) o; if (_isAllOfSameType(nodes, Node.TEXT_NODE)) return (Text[]) nodes; Text[] textes = new Text[nodes.length]; for (int i = 0; i < nodes.length; i++) { textes[i] = toText(doc, nodes[i]); } return textes; } // Collection else if (o instanceof Collection) { Collection coll = (Collection) o; Iterator<Object> it = coll.valueIterator(); List<Text> textes = new ArrayList<Text>(); while (it.hasNext()) { textes.add(toText(doc, it.next())); } return textes.toArray(new Text[textes.size()]); } // Node Map and List Node[] nodes = _toNodeArray(doc, o); if (nodes != null) return toTextArray(doc, nodes); // Single Text Node try { return new Text[] { toText(doc, o) }; } catch (ExpressionException e) { throw new XMLException("can't cast Object of type " + Caster.toClassName(o) + " to a XML Text Array"); } } }
public class class_name { public static Text[] toTextArray(Document doc, Object o) throws PageException { // Node[] if (o instanceof Node[]) { Node[] nodes = (Node[]) o; if (_isAllOfSameType(nodes, Node.TEXT_NODE)) return (Text[]) nodes; Text[] textes = new Text[nodes.length]; for (int i = 0; i < nodes.length; i++) { textes[i] = toText(doc, nodes[i]); // depends on control dependency: [for], data = [i] } return textes; } // Collection else if (o instanceof Collection) { Collection coll = (Collection) o; Iterator<Object> it = coll.valueIterator(); List<Text> textes = new ArrayList<Text>(); while (it.hasNext()) { textes.add(toText(doc, it.next())); // depends on control dependency: [while], data = [none] } return textes.toArray(new Text[textes.size()]); } // Node Map and List Node[] nodes = _toNodeArray(doc, o); if (nodes != null) return toTextArray(doc, nodes); // Single Text Node try { return new Text[] { toText(doc, o) }; } catch (ExpressionException e) { throw new XMLException("can't cast Object of type " + Caster.toClassName(o) + " to a XML Text Array"); } } }
public class class_name { public List<Flow> getFlowsForStatus(String cluster, Flow.Status status, int limit, String user, byte[] startRow) throws IOException { byte[] rowPrefix = ByteUtil.join(Constants.SEP_BYTES, Bytes.toBytes(cluster), status.code(), Constants.EMPTY_BYTES); if (startRow == null) { startRow = rowPrefix; } Scan scan = new Scan(startRow); FilterList filters = new FilterList(FilterList.Operator.MUST_PASS_ALL); // early out when prefix ends filters.addFilter(new WhileMatchFilter(new PrefixFilter(rowPrefix))); if (user != null) { SingleColumnValueFilter userFilter = new SingleColumnValueFilter( Constants.INFO_FAM_BYTES, USER_NAME_COL_BYTES, CompareFilter.CompareOp.EQUAL, Bytes.toBytes(user)); userFilter.setFilterIfMissing(true); filters.addFilter(userFilter); } scan.setFilter(filters); // TODO: need to constrain this by timerange as well to prevent unlimited // scans // get back the results in a single response scan.setCaching(limit); List<Flow> results = new ArrayList<Flow>(limit); ResultScanner scanner = null; Table flowQueueTable = null; try { flowQueueTable = hbaseConnection .getTable(TableName.valueOf(Constants.FLOW_QUEUE_TABLE)); scanner = flowQueueTable.getScanner(scan); int cnt = 0; for (Result r : scanner) { Flow flow = createFlowFromResult(r); if (flow != null) { cnt++; results.add(flow); } if (cnt >= limit) { break; } } } finally { try { if (scanner != null) { scanner.close(); } } finally { if (flowQueueTable != null) { flowQueueTable.close(); } } } return results; } }
public class class_name { public List<Flow> getFlowsForStatus(String cluster, Flow.Status status, int limit, String user, byte[] startRow) throws IOException { byte[] rowPrefix = ByteUtil.join(Constants.SEP_BYTES, Bytes.toBytes(cluster), status.code(), Constants.EMPTY_BYTES); if (startRow == null) { startRow = rowPrefix; } Scan scan = new Scan(startRow); FilterList filters = new FilterList(FilterList.Operator.MUST_PASS_ALL); // early out when prefix ends filters.addFilter(new WhileMatchFilter(new PrefixFilter(rowPrefix))); if (user != null) { SingleColumnValueFilter userFilter = new SingleColumnValueFilter( Constants.INFO_FAM_BYTES, USER_NAME_COL_BYTES, CompareFilter.CompareOp.EQUAL, Bytes.toBytes(user)); userFilter.setFilterIfMissing(true); filters.addFilter(userFilter); } scan.setFilter(filters); // TODO: need to constrain this by timerange as well to prevent unlimited // scans // get back the results in a single response scan.setCaching(limit); List<Flow> results = new ArrayList<Flow>(limit); ResultScanner scanner = null; Table flowQueueTable = null; try { flowQueueTable = hbaseConnection .getTable(TableName.valueOf(Constants.FLOW_QUEUE_TABLE)); scanner = flowQueueTable.getScanner(scan); int cnt = 0; for (Result r : scanner) { Flow flow = createFlowFromResult(r); if (flow != null) { cnt++; // depends on control dependency: [if], data = [none] results.add(flow); // depends on control dependency: [if], data = [(flow] } if (cnt >= limit) { break; } } } finally { try { if (scanner != null) { scanner.close(); // depends on control dependency: [if], data = [none] } } finally { if (flowQueueTable != null) { flowQueueTable.close(); // depends on control dependency: [if], data = [none] } } } return results; } }
public class class_name { private static boolean isIn(char c, char[] chars) { if (chars != null) { for (char current : chars) { if (current == c) { return true; } } } return false; } }
public class class_name { private static boolean isIn(char c, char[] chars) { if (chars != null) { for (char current : chars) { if (current == c) { return true; // depends on control dependency: [if], data = [none] } } } return false; } }
public class class_name { protected List<String> preprocess(String document) { List<Term> termList = segment.seg(document); ListIterator<Term> listIterator = termList.listIterator(); while (listIterator.hasNext()) { Term term = listIterator.next(); if (CoreStopWordDictionary.contains(term.word) || term.nature.startsWith("w") ) { listIterator.remove(); } } List<String> wordList = new ArrayList<String>(termList.size()); for (Term term : termList) { wordList.add(term.word); } return wordList; } }
public class class_name { protected List<String> preprocess(String document) { List<Term> termList = segment.seg(document); ListIterator<Term> listIterator = termList.listIterator(); while (listIterator.hasNext()) { Term term = listIterator.next(); if (CoreStopWordDictionary.contains(term.word) || term.nature.startsWith("w") ) { listIterator.remove(); // depends on control dependency: [if], data = [none] } } List<String> wordList = new ArrayList<String>(termList.size()); for (Term term : termList) { wordList.add(term.word); // depends on control dependency: [for], data = [term] } return wordList; } }
public class class_name { private synchronized Class<?> getClass(String className) throws Exception { // see if we need to invalidate the class ClassInformation classInfo = classInformation.get(className); File classFile = new File(classInfo.pluginPath); if (classFile.lastModified() > classInfo.lastModified) { logger.info("Class {} has been modified, reloading", className); logger.info("Thread ID: {}", Thread.currentThread().getId()); classInfo.loaded = false; classInformation.put(className, classInfo); // also cleanup anything in methodInformation with this className so it gets reloaded Iterator<Map.Entry<String, com.groupon.odo.proxylib.models.Method>> iter = methodInformation.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, com.groupon.odo.proxylib.models.Method> entry = iter.next(); if (entry.getKey().startsWith(className)) { iter.remove(); } } } if (!classInfo.loaded) { loadClass(className); } return classInfo.loadedClass; } }
public class class_name { private synchronized Class<?> getClass(String className) throws Exception { // see if we need to invalidate the class ClassInformation classInfo = classInformation.get(className); File classFile = new File(classInfo.pluginPath); if (classFile.lastModified() > classInfo.lastModified) { logger.info("Class {} has been modified, reloading", className); logger.info("Thread ID: {}", Thread.currentThread().getId()); classInfo.loaded = false; classInformation.put(className, classInfo); // also cleanup anything in methodInformation with this className so it gets reloaded Iterator<Map.Entry<String, com.groupon.odo.proxylib.models.Method>> iter = methodInformation.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, com.groupon.odo.proxylib.models.Method> entry = iter.next(); if (entry.getKey().startsWith(className)) { iter.remove(); // depends on control dependency: [if], data = [none] } } } if (!classInfo.loaded) { loadClass(className); } return classInfo.loadedClass; } }
public class class_name { public void processTopicAdditionalInfo(final BuildData buildData, final SpecTopic specTopic, final Document document) throws BuildProcessingException { // First check if we should even bother processing any additional info based on build data if (!shouldAddAdditionalInfo(buildData, specTopic)) return; final List<Node> invalidNodes = XMLUtilities.getChildNodes(document.getDocumentElement(), "section"); // Only add injections if the topic doesn't contain any invalid nodes. The reason for this is that adding any links to topics // that contain <section> will cause the XML to become invalid. Unfortunately there isn't any way around this. if (invalidNodes == null || invalidNodes.size() == 0) { final Element rootEle = getRootAdditionalInfoElement(document, document.getDocumentElement()); if (buildData.getBuildOptions().getInsertEditorLinks() && specTopic.getTopicType() != TopicType.AUTHOR_GROUP) { processTopicEditorLinks(buildData, specTopic, document, rootEle); } // Only include a bugzilla link for normal topics if (buildData.getBuildOptions().getInsertBugLinks() && specTopic.getTopicType() == TopicType.NORMAL) { processTopicBugLink(buildData, specTopic, document, rootEle); } } } }
public class class_name { public void processTopicAdditionalInfo(final BuildData buildData, final SpecTopic specTopic, final Document document) throws BuildProcessingException { // First check if we should even bother processing any additional info based on build data if (!shouldAddAdditionalInfo(buildData, specTopic)) return; final List<Node> invalidNodes = XMLUtilities.getChildNodes(document.getDocumentElement(), "section"); // Only add injections if the topic doesn't contain any invalid nodes. The reason for this is that adding any links to topics // that contain <section> will cause the XML to become invalid. Unfortunately there isn't any way around this. if (invalidNodes == null || invalidNodes.size() == 0) { final Element rootEle = getRootAdditionalInfoElement(document, document.getDocumentElement()); if (buildData.getBuildOptions().getInsertEditorLinks() && specTopic.getTopicType() != TopicType.AUTHOR_GROUP) { processTopicEditorLinks(buildData, specTopic, document, rootEle); // depends on control dependency: [if], data = [none] } // Only include a bugzilla link for normal topics if (buildData.getBuildOptions().getInsertBugLinks() && specTopic.getTopicType() == TopicType.NORMAL) { processTopicBugLink(buildData, specTopic, document, rootEle); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public void marshall(InstanceResizePolicy instanceResizePolicy, ProtocolMarshaller protocolMarshaller) { if (instanceResizePolicy == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(instanceResizePolicy.getInstancesToTerminate(), INSTANCESTOTERMINATE_BINDING); protocolMarshaller.marshall(instanceResizePolicy.getInstancesToProtect(), INSTANCESTOPROTECT_BINDING); protocolMarshaller.marshall(instanceResizePolicy.getInstanceTerminationTimeout(), INSTANCETERMINATIONTIMEOUT_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(InstanceResizePolicy instanceResizePolicy, ProtocolMarshaller protocolMarshaller) { if (instanceResizePolicy == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(instanceResizePolicy.getInstancesToTerminate(), INSTANCESTOTERMINATE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(instanceResizePolicy.getInstancesToProtect(), INSTANCESTOPROTECT_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(instanceResizePolicy.getInstanceTerminationTimeout(), INSTANCETERMINATIONTIMEOUT_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public void push (Runnable task) { while (true) { final long _base = UNSAFE.getLongVolatile (this, OFFS_BASE); final long _top = top; if (_top == _base + mask) { throw new RejectedExecutionExceptionWithoutStacktrace ("Queue overflow"); } final long taskOffset = taskOffset (_top); if (UNSAFE.compareAndSwapObject (tasks, taskOffset, null, task)) { // if the publishing thread is interrupted here, other publishers will effectively do a spin wait if (!UNSAFE.compareAndSwapLong (this, OFFS_TOP, _top, _top+1)) { // there was a buffer wrap-around in the meantime --> undo the CAS 'put' operation and try again UNSAFE.putObjectVolatile (tasks, taskOffset, null); continue; } if (_top - _base <= 1) { pool.onAvailableTask (); } break; } } } }
public class class_name { @Override public void push (Runnable task) { while (true) { final long _base = UNSAFE.getLongVolatile (this, OFFS_BASE); final long _top = top; if (_top == _base + mask) { throw new RejectedExecutionExceptionWithoutStacktrace ("Queue overflow"); } final long taskOffset = taskOffset (_top); if (UNSAFE.compareAndSwapObject (tasks, taskOffset, null, task)) { // if the publishing thread is interrupted here, other publishers will effectively do a spin wait if (!UNSAFE.compareAndSwapLong (this, OFFS_TOP, _top, _top+1)) { // there was a buffer wrap-around in the meantime --> undo the CAS 'put' operation and try again UNSAFE.putObjectVolatile (tasks, taskOffset, null); // depends on control dependency: [if], data = [none] continue; } if (_top - _base <= 1) { pool.onAvailableTask (); // depends on control dependency: [if], data = [none] } break; } } } }
public class class_name { private Method findSetter(Method []methods, String getterName, Class< ? > arg) { String setterName = "set" + getterName.substring(INT_VALUE); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (!method.getName().equals(setterName)) { continue; } if (!method.getReturnType().equals(void.class)) { continue; } Class< ? > []params = method.getParameterTypes(); if (params.length == 1 && params[0].equals(arg)) { return method; } } return null; } }
public class class_name { private Method findSetter(Method []methods, String getterName, Class< ? > arg) { String setterName = "set" + getterName.substring(INT_VALUE); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (!method.getName().equals(setterName)) { continue; } if (!method.getReturnType().equals(void.class)) { continue; } Class< ? > []params = method.getParameterTypes(); if (params.length == 1 && params[0].equals(arg)) { return method; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { @Override public boolean setAttributes(IAttributeStore values) { if (values != null) { return setAttributes(values.getAttributes()); } return false; } }
public class class_name { @Override public boolean setAttributes(IAttributeStore values) { if (values != null) { return setAttributes(values.getAttributes()); // depends on control dependency: [if], data = [(values] } return false; } }
public class class_name { protected void checkTimeouts() { long now = System.currentTimeMillis(); // Check timeouted promises PendingPromise pending; Iterator<PendingPromise> i = promises.values().iterator(); boolean removed = false; while (i.hasNext()) { pending = i.next(); if (pending.timeoutAt > 0 && now >= pending.timeoutAt) { // Action is unknown at this location pending.promise.complete(new RequestTimeoutError(this.nodeID, pending.action)); i.remove(); removed = true; } } // Check timeouted request streams IncomingStream stream; long timeoutAt; Iterator<IncomingStream> j = requestStreams.values().iterator(); while (j.hasNext()) { stream = j.next(); timeoutAt = stream.getTimeoutAt(); if (timeoutAt > 0 && now >= timeoutAt) { stream.error(new RequestTimeoutError(this.nodeID, "unknown")); requestStreamWriteLock.lock(); try { j.remove(); } finally { requestStreamWriteLock.unlock(); } removed = true; } } // Check timeouted response streams j = responseStreams.values().iterator(); while (j.hasNext()) { stream = j.next(); timeoutAt = stream.getTimeoutAt(); if (timeoutAt > 0 && now >= timeoutAt) { stream.error(new RequestTimeoutError(nodeID, "unknown")); responseStreamWriteLock.lock(); try { j.remove(); } finally { responseStreamWriteLock.unlock(); } removed = true; } } // Reschedule if (removed) { scheduler.execute(() -> { reschedule(Long.MAX_VALUE); }); } else { prevTimeoutAt.set(0); } } }
public class class_name { protected void checkTimeouts() { long now = System.currentTimeMillis(); // Check timeouted promises PendingPromise pending; Iterator<PendingPromise> i = promises.values().iterator(); boolean removed = false; while (i.hasNext()) { pending = i.next(); // depends on control dependency: [while], data = [none] if (pending.timeoutAt > 0 && now >= pending.timeoutAt) { // Action is unknown at this location pending.promise.complete(new RequestTimeoutError(this.nodeID, pending.action)); // depends on control dependency: [if], data = [none] i.remove(); // depends on control dependency: [if], data = [none] removed = true; // depends on control dependency: [if], data = [none] } } // Check timeouted request streams IncomingStream stream; long timeoutAt; Iterator<IncomingStream> j = requestStreams.values().iterator(); while (j.hasNext()) { stream = j.next(); // depends on control dependency: [while], data = [none] timeoutAt = stream.getTimeoutAt(); // depends on control dependency: [while], data = [none] if (timeoutAt > 0 && now >= timeoutAt) { stream.error(new RequestTimeoutError(this.nodeID, "unknown")); // depends on control dependency: [if], data = [none] requestStreamWriteLock.lock(); // depends on control dependency: [if], data = [none] try { j.remove(); // depends on control dependency: [try], data = [none] } finally { requestStreamWriteLock.unlock(); } removed = true; // depends on control dependency: [if], data = [none] } } // Check timeouted response streams j = responseStreams.values().iterator(); while (j.hasNext()) { stream = j.next(); // depends on control dependency: [while], data = [none] timeoutAt = stream.getTimeoutAt(); // depends on control dependency: [while], data = [none] if (timeoutAt > 0 && now >= timeoutAt) { stream.error(new RequestTimeoutError(nodeID, "unknown")); // depends on control dependency: [if], data = [none] responseStreamWriteLock.lock(); // depends on control dependency: [if], data = [none] try { j.remove(); // depends on control dependency: [try], data = [none] } finally { responseStreamWriteLock.unlock(); } removed = true; // depends on control dependency: [if], data = [none] } } // Reschedule if (removed) { scheduler.execute(() -> { reschedule(Long.MAX_VALUE); // depends on control dependency: [if], data = [none] }); } else { prevTimeoutAt.set(0); } } }
public class class_name { public static void initLogConfig(String logConfigpath) { try { LoggerContext context =(LoggerContext)LogManager.getContext(false); if(context!=null) { context.setConfigLocation(new File(logConfigpath).toURI()); context.reconfigure();//重新初始化Log4j2的配置上下文 }else { ConfigurationSource source = new ConfigurationSource(new FileInputStream(logConfigpath)); Configurator.initialize(null, source); } Logger log=LoggerFactory.getLogger(Log4jUtil.class); log.info("日志配置初始化完成:"+logConfigpath); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
public class class_name { public static void initLogConfig(String logConfigpath) { try { LoggerContext context =(LoggerContext)LogManager.getContext(false); if(context!=null) { context.setConfigLocation(new File(logConfigpath).toURI()); // depends on control dependency: [if], data = [none] context.reconfigure();//重新初始化Log4j2的配置上下文 // depends on control dependency: [if], data = [none] }else { ConfigurationSource source = new ConfigurationSource(new FileInputStream(logConfigpath)); Configurator.initialize(null, source); // depends on control dependency: [if], data = [none] } Logger log=LoggerFactory.getLogger(Log4jUtil.class); log.info("日志配置初始化完成:"+logConfigpath); // depends on control dependency: [try], data = [none] } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // depends on control dependency: [catch], data = [none] e.printStackTrace(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public ContainerModel getContainer() { if (_container == null) { _container = (ContainerModel)getFirstChildModel(CONTAINER); } return _container; } }
public class class_name { @Override public ContainerModel getContainer() { if (_container == null) { _container = (ContainerModel)getFirstChildModel(CONTAINER); // depends on control dependency: [if], data = [none] } return _container; } }
public class class_name { public Set<String> parseRemoveFormatters(I_CmsXmlContentLocation node) { Set<String> removeFormatters = new HashSet<String>(); for (I_CmsXmlContentValueLocation removeLoc : node.getSubValues( N_REMOVE_FORMATTERS + "/" + N_REMOVE_FORMATTER)) { CmsXmlVfsFileValue value = (CmsXmlVfsFileValue)removeLoc.getValue(); CmsLink link = value.getLink(m_cms); if (link != null) { removeFormatters.add(link.getStructureId().toString()); } } return removeFormatters; } }
public class class_name { public Set<String> parseRemoveFormatters(I_CmsXmlContentLocation node) { Set<String> removeFormatters = new HashSet<String>(); for (I_CmsXmlContentValueLocation removeLoc : node.getSubValues( N_REMOVE_FORMATTERS + "/" + N_REMOVE_FORMATTER)) { CmsXmlVfsFileValue value = (CmsXmlVfsFileValue)removeLoc.getValue(); CmsLink link = value.getLink(m_cms); if (link != null) { removeFormatters.add(link.getStructureId().toString()); // depends on control dependency: [if], data = [(link] } } return removeFormatters; } }
public class class_name { public boolean isLast() { Object isLast = getHeader(WebSocketMessageHeaders.WEB_SOCKET_IS_LAST); if (isLast != null) { if (isLast instanceof String) { return Boolean.valueOf(isLast.toString()); } else { return (Boolean) isLast; } } return true; } }
public class class_name { public boolean isLast() { Object isLast = getHeader(WebSocketMessageHeaders.WEB_SOCKET_IS_LAST); if (isLast != null) { if (isLast instanceof String) { return Boolean.valueOf(isLast.toString()); // depends on control dependency: [if], data = [none] } else { return (Boolean) isLast; // depends on control dependency: [if], data = [none] } } return true; } }
public class class_name { @Override public void initialize(final Instance _instance, final Store _store) throws EFapsException { super.initialize(_instance, _store); try { final InitialContext ctx = new InitialContext(); this.repository = (Repository) ctx.lookup(getStore().getProperty(Store.PROPERTY_JNDINAME)); if (JCRStoreResource.LOG.isDebugEnabled()) { final String name = this.repository.getDescriptor(Repository.REP_NAME_DESC); JCRStoreResource.LOG.debug("Successfully retrieved '{}' repository from JNDI", new Object[]{ name }); } } catch (final NamingException e) { throw new EFapsException(JCRStoreResource.class, "initialize.NamingException", e); } } }
public class class_name { @Override public void initialize(final Instance _instance, final Store _store) throws EFapsException { super.initialize(_instance, _store); try { final InitialContext ctx = new InitialContext(); this.repository = (Repository) ctx.lookup(getStore().getProperty(Store.PROPERTY_JNDINAME)); if (JCRStoreResource.LOG.isDebugEnabled()) { final String name = this.repository.getDescriptor(Repository.REP_NAME_DESC); JCRStoreResource.LOG.debug("Successfully retrieved '{}' repository from JNDI", new Object[]{ name }); // depends on control dependency: [if], data = [none] } } catch (final NamingException e) { throw new EFapsException(JCRStoreResource.class, "initialize.NamingException", e); } } }
public class class_name { public static DCache getConfiguredCache(String cacheName) { final String methodName = "getConfiguredCache()"; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, methodName + " input cacheName=" + cacheName); } DCache cacheOut = null; if (coreCacheEnabled == false) { // DYNA1003E=DYNA1003E: WebSphere Dynamic Cache instance named {0} can not be initialized because of error // {1}. Tr.error(tc, "DYNA1003E", new Object[] { cacheName, "Core Cache Service has not been started." }); } else { cacheOut = getCache(cacheName); if (cacheOut == null) { CacheConfig config = getCacheService().getCacheInstanceConfig(cacheName); if (config == null) { // DYNA1004E=DYNA1004E: WebSphere Dynamic Cache instance named {0} can not be initialized because it // is not configured. // DYNA1004E.explanation=This message indicates the named WebSphere Dynamic Cache instance can not // be initialized. The named instance is not avaliable. // DYNA1004E.useraction=Use the WebSphere Administrative Console to configure a cache instance // resource named {0}. Tr.error(tc, "DYNA1004E", new Object[] { cacheName }); cacheOut = null; } else { cacheOut = createCache(config.cacheName, config); } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, methodName + " output cacheName=" + (cacheOut != null ? cacheOut.getCacheName() : "null")); } return cacheOut; } }
public class class_name { public static DCache getConfiguredCache(String cacheName) { final String methodName = "getConfiguredCache()"; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, methodName + " input cacheName=" + cacheName); // depends on control dependency: [if], data = [none] } DCache cacheOut = null; if (coreCacheEnabled == false) { // DYNA1003E=DYNA1003E: WebSphere Dynamic Cache instance named {0} can not be initialized because of error // {1}. Tr.error(tc, "DYNA1003E", new Object[] { cacheName, "Core Cache Service has not been started." }); // depends on control dependency: [if], data = [none] } else { cacheOut = getCache(cacheName); // depends on control dependency: [if], data = [none] if (cacheOut == null) { CacheConfig config = getCacheService().getCacheInstanceConfig(cacheName); if (config == null) { // DYNA1004E=DYNA1004E: WebSphere Dynamic Cache instance named {0} can not be initialized because it // is not configured. // DYNA1004E.explanation=This message indicates the named WebSphere Dynamic Cache instance can not // be initialized. The named instance is not avaliable. // DYNA1004E.useraction=Use the WebSphere Administrative Console to configure a cache instance // resource named {0}. Tr.error(tc, "DYNA1004E", new Object[] { cacheName }); // depends on control dependency: [if], data = [none] cacheOut = null; // depends on control dependency: [if], data = [none] } else { cacheOut = createCache(config.cacheName, config); // depends on control dependency: [if], data = [(config] } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, methodName + " output cacheName=" + (cacheOut != null ? cacheOut.getCacheName() : "null")); // depends on control dependency: [if], data = [none] } return cacheOut; } }
public class class_name { private static boolean exclude(String host, java.nio.file.Path path) { List<PathMatcher> exclusions = getExcludes(host); if (exclusions == null && host != null) { exclusions = getExcludes(null); // check global config } if (exclusions != null) { for (PathMatcher matcher : exclusions) { if (matcher.matches(path)) return true; } } return false; } }
public class class_name { private static boolean exclude(String host, java.nio.file.Path path) { List<PathMatcher> exclusions = getExcludes(host); if (exclusions == null && host != null) { exclusions = getExcludes(null); // check global config // depends on control dependency: [if], data = [none] } if (exclusions != null) { for (PathMatcher matcher : exclusions) { if (matcher.matches(path)) return true; } } return false; } }
public class class_name { @Override @InterfaceAudience.Private public void beginReplicating() { // If we're still waiting to create the remote db, do nothing now. (This method will be // re-invoked after that request finishes; see -maybeCreateRemoteDB above.) Log.d(TAG, "%s: beginReplicating() called", this); // reset doneBeginReplicating doneBeginReplicating = false; // If we're still waiting to create the remote db, do nothing now. (This method will be // re-invoked after that request finishes; see maybeCreateRemoteDB() above.) if (creatingTarget) { Log.d(TAG, "%s: creatingTarget == true, doing nothing", this); return; } pendingSequences = Collections.synchronizedSortedSet(new TreeSet<Long>()); try { maxPendingSequence = Long.parseLong(lastSequence); } catch (NumberFormatException e) { Log.w(TAG, "Error converting lastSequence: %s to long. Using 0", lastSequence); maxPendingSequence = new Long(0); } filter = compilePushReplicationFilter(); if (filterName != null && filter == null) { Log.w(TAG, "%s: No ReplicationFilter registered for filter '%s'; ignoring", this, filterName); } // Now listen for future changes (in continuous mode): if (isContinuous() && isRunning()) { observing = true; db.addChangeListener(this); } // Process existing changes since the last push: long lastSequenceLong = 0; if (lastSequence != null) { lastSequenceLong = Long.parseLong(lastSequence); } ChangesOptions options = new ChangesOptions(); options.setIncludeConflicts(true); Log.d(TAG, "%s: Getting changes since %d", this, lastSequenceLong); final RevisionList changes = db.changesSince(lastSequenceLong, options, filter, filterParams); if (changes.size() > 0) { Log.d(TAG, "%s: Queuing %d changes since %d", this, changes.size(), lastSequenceLong); // NOTE: Needs to submit changes into inbox from RemoteRequest thread for beginReplication. // RemoteRequest thread is observed by pendingFuture, if using other thread to // submit changes into inbox, there are chance both inbox and pendingFutures are // empty. submitRevisions(changes); } else { Log.d(TAG, "%s: No changes since %d", this, lastSequenceLong); } // process queued changes by `changed()` callback synchronized (changesLock) { for (RevisionInternal rev : queueChanges) { if (!changes.contains(rev)) { pauseOrResume(); waitIfPaused(); addToInbox(rev); } } doneBeginReplicating = true; } } }
public class class_name { @Override @InterfaceAudience.Private public void beginReplicating() { // If we're still waiting to create the remote db, do nothing now. (This method will be // re-invoked after that request finishes; see -maybeCreateRemoteDB above.) Log.d(TAG, "%s: beginReplicating() called", this); // reset doneBeginReplicating doneBeginReplicating = false; // If we're still waiting to create the remote db, do nothing now. (This method will be // re-invoked after that request finishes; see maybeCreateRemoteDB() above.) if (creatingTarget) { Log.d(TAG, "%s: creatingTarget == true, doing nothing", this); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } pendingSequences = Collections.synchronizedSortedSet(new TreeSet<Long>()); try { maxPendingSequence = Long.parseLong(lastSequence); // depends on control dependency: [try], data = [none] } catch (NumberFormatException e) { Log.w(TAG, "Error converting lastSequence: %s to long. Using 0", lastSequence); maxPendingSequence = new Long(0); } // depends on control dependency: [catch], data = [none] filter = compilePushReplicationFilter(); if (filterName != null && filter == null) { Log.w(TAG, "%s: No ReplicationFilter registered for filter '%s'; ignoring", this, filterName); // depends on control dependency: [if], data = [none] } // Now listen for future changes (in continuous mode): if (isContinuous() && isRunning()) { observing = true; // depends on control dependency: [if], data = [none] db.addChangeListener(this); // depends on control dependency: [if], data = [none] } // Process existing changes since the last push: long lastSequenceLong = 0; if (lastSequence != null) { lastSequenceLong = Long.parseLong(lastSequence); // depends on control dependency: [if], data = [(lastSequence] } ChangesOptions options = new ChangesOptions(); options.setIncludeConflicts(true); Log.d(TAG, "%s: Getting changes since %d", this, lastSequenceLong); final RevisionList changes = db.changesSince(lastSequenceLong, options, filter, filterParams); if (changes.size() > 0) { Log.d(TAG, "%s: Queuing %d changes since %d", this, changes.size(), lastSequenceLong); // depends on control dependency: [if], data = [none] // NOTE: Needs to submit changes into inbox from RemoteRequest thread for beginReplication. // RemoteRequest thread is observed by pendingFuture, if using other thread to // submit changes into inbox, there are chance both inbox and pendingFutures are // empty. submitRevisions(changes); // depends on control dependency: [if], data = [none] } else { Log.d(TAG, "%s: No changes since %d", this, lastSequenceLong); // depends on control dependency: [if], data = [none] } // process queued changes by `changed()` callback synchronized (changesLock) { for (RevisionInternal rev : queueChanges) { if (!changes.contains(rev)) { pauseOrResume(); // depends on control dependency: [if], data = [none] waitIfPaused(); // depends on control dependency: [if], data = [none] addToInbox(rev); // depends on control dependency: [if], data = [none] } } doneBeginReplicating = true; } } }
public class class_name { public CloudhopperBuilder systemType(String... systemType) { for (String s : systemType) { if (s != null) { systemTypes.add(s); } } return this; } }
public class class_name { public CloudhopperBuilder systemType(String... systemType) { for (String s : systemType) { if (s != null) { systemTypes.add(s); // depends on control dependency: [if], data = [(s] } } return this; } }
public class class_name { @Override public void start() { synchronized (this) { try { while (state == ComponentStatus.INITIALIZING) { wait(); } if (state != ComponentStatus.INSTANTIATED) { return; } state = ComponentStatus.INITIALIZING; } catch (InterruptedException e) { throw new CacheException("Interrupted waiting for the component registry to start"); } } try { preStart(); internalStart(); synchronized (this) { state = ComponentStatus.RUNNING; notifyAll(); } postStart(); } catch (Throwable t) { synchronized (this) { state = ComponentStatus.FAILED; notifyAll(); } try { stop(); } catch (Throwable t1) { t.addSuppressed(t1); } handleLifecycleTransitionFailure(t); } } }
public class class_name { @Override public void start() { synchronized (this) { try { while (state == ComponentStatus.INITIALIZING) { wait(); // depends on control dependency: [while], data = [none] } if (state != ComponentStatus.INSTANTIATED) { return; // depends on control dependency: [if], data = [none] } state = ComponentStatus.INITIALIZING; // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { throw new CacheException("Interrupted waiting for the component registry to start"); } // depends on control dependency: [catch], data = [none] } try { preStart(); // depends on control dependency: [try], data = [none] internalStart(); // depends on control dependency: [try], data = [none] synchronized (this) { // depends on control dependency: [try], data = [none] state = ComponentStatus.RUNNING; notifyAll(); } postStart(); // depends on control dependency: [try], data = [none] } catch (Throwable t) { synchronized (this) { state = ComponentStatus.FAILED; notifyAll(); } try { stop(); // depends on control dependency: [try], data = [none] } catch (Throwable t1) { t.addSuppressed(t1); } // depends on control dependency: [catch], data = [none] handleLifecycleTransitionFailure(t); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public boolean reallocateMsgs() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "reallocateMsgs"); boolean success = true; // Reallocate the messages on the outputhandler to spread the load over // the localisations try { if (getOutputHandler() instanceof PtoPOutputHandler) { ((PtoPOutputHandler)getOutputHandler()).reallocateMsgs(getDestinationHandler(), false, false); } else success = false; } catch (SIException e) { // No FFDC code needed success = false; } if (success) { // If non-empty, then do not delete yet long itemCount = -1; long availableCount = -1; long removingCount = -1; try { itemCount = getStatistics().getTotalItemCount(); availableCount = getStatistics().getAvailableItemCount(); removingCount = getStatistics().getRemovingItemCount(); } catch(MessageStoreException e) { // FFDC FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.store.itemstreams.PtoPXmitMsgsItemStream.reallocateMsgs", "1:160:1.56", this); SibTr.exception(tc, e); } if (itemCount > 0) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Messages remain on stream: " + itemCount + " : " + availableCount + " : " + removingCount); success = false; } else { if (isToBeDeleted() || destinationHandler.isToBeDeleted()) { ExternalAutoCommitTransaction transaction = getDestinationHandler(). getTxManager(). createAutoCommitTransaction(); try { removeItemStream(transaction, NO_LOCK_ID); } catch (MessageStoreException e) { // MessageStoreException shouldn't occur so FFDC. FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.store.itemstreams.PtoPXmitMsgsItemStream.reallocateMsgs", "1:193:1.56", this); SibTr.exception(tc, e); success = false; } } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "reallocateMsgs", new Boolean(success)); return success; } }
public class class_name { public boolean reallocateMsgs() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "reallocateMsgs"); boolean success = true; // Reallocate the messages on the outputhandler to spread the load over // the localisations try { if (getOutputHandler() instanceof PtoPOutputHandler) { ((PtoPOutputHandler)getOutputHandler()).reallocateMsgs(getDestinationHandler(), false, false); // depends on control dependency: [if], data = [none] } else success = false; } catch (SIException e) { // No FFDC code needed success = false; } // depends on control dependency: [catch], data = [none] if (success) { // If non-empty, then do not delete yet long itemCount = -1; long availableCount = -1; long removingCount = -1; try { itemCount = getStatistics().getTotalItemCount(); // depends on control dependency: [try], data = [none] availableCount = getStatistics().getAvailableItemCount(); // depends on control dependency: [try], data = [none] removingCount = getStatistics().getRemovingItemCount(); // depends on control dependency: [try], data = [none] } catch(MessageStoreException e) { // FFDC FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.store.itemstreams.PtoPXmitMsgsItemStream.reallocateMsgs", "1:160:1.56", this); SibTr.exception(tc, e); } // depends on control dependency: [catch], data = [none] if (itemCount > 0) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Messages remain on stream: " + itemCount + " : " + availableCount + " : " + removingCount); success = false; // depends on control dependency: [if], data = [none] } else { if (isToBeDeleted() || destinationHandler.isToBeDeleted()) { ExternalAutoCommitTransaction transaction = getDestinationHandler(). getTxManager(). createAutoCommitTransaction(); try { removeItemStream(transaction, NO_LOCK_ID); // depends on control dependency: [try], data = [none] } catch (MessageStoreException e) { // MessageStoreException shouldn't occur so FFDC. FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.store.itemstreams.PtoPXmitMsgsItemStream.reallocateMsgs", "1:193:1.56", this); SibTr.exception(tc, e); success = false; } // depends on control dependency: [catch], data = [none] } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "reallocateMsgs", new Boolean(success)); return success; } }
public class class_name { public void marshall(KinesisSettings kinesisSettings, ProtocolMarshaller protocolMarshaller) { if (kinesisSettings == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(kinesisSettings.getStreamArn(), STREAMARN_BINDING); protocolMarshaller.marshall(kinesisSettings.getMessageFormat(), MESSAGEFORMAT_BINDING); protocolMarshaller.marshall(kinesisSettings.getServiceAccessRoleArn(), SERVICEACCESSROLEARN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(KinesisSettings kinesisSettings, ProtocolMarshaller protocolMarshaller) { if (kinesisSettings == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(kinesisSettings.getStreamArn(), STREAMARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(kinesisSettings.getMessageFormat(), MESSAGEFORMAT_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(kinesisSettings.getServiceAccessRoleArn(), SERVICEACCESSROLEARN_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void trimIds() { // typical case shortcut if (idToSymbol.containsKey(nextId - 1)) { return; } int max = -1; for (IntObjectCursor<String> cursor : idToSymbol) { max = Math.max(max, cursor.key); } nextId = max + 1; } }
public class class_name { public void trimIds() { // typical case shortcut if (idToSymbol.containsKey(nextId - 1)) { return; // depends on control dependency: [if], data = [none] } int max = -1; for (IntObjectCursor<String> cursor : idToSymbol) { max = Math.max(max, cursor.key); // depends on control dependency: [for], data = [cursor] } nextId = max + 1; } }
public class class_name { public static List<CommerceUserSegmentEntry> toModels( CommerceUserSegmentEntrySoap[] soapModels) { if (soapModels == null) { return null; } List<CommerceUserSegmentEntry> models = new ArrayList<CommerceUserSegmentEntry>(soapModels.length); for (CommerceUserSegmentEntrySoap soapModel : soapModels) { models.add(toModel(soapModel)); } return models; } }
public class class_name { public static List<CommerceUserSegmentEntry> toModels( CommerceUserSegmentEntrySoap[] soapModels) { if (soapModels == null) { return null; // depends on control dependency: [if], data = [none] } List<CommerceUserSegmentEntry> models = new ArrayList<CommerceUserSegmentEntry>(soapModels.length); for (CommerceUserSegmentEntrySoap soapModel : soapModels) { models.add(toModel(soapModel)); // depends on control dependency: [for], data = [soapModel] } return models; } }
public class class_name { private void emitLogHeader(Context context, String mapredTaskId) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); Text textId = new Text(mapredTaskId); for (Map.Entry<String, String> entry: conf) { StringBuilder sb = new StringBuilder(); sb.append(entry.getKey()); sb.append("="); sb.append(entry.getValue()); context.write(textId, new Text(sb.toString())); } context.write(textId, new Text("----- Properties -----")); String[] plist = { "mapred.local.dir", "mapred.child.java.opts", }; for (String k : plist) { String v = conf.get(k); if (v == null) { v = "(null)"; } context.write(textId, new Text(k + " " + v)); } String userDir = System.getProperty("user.dir"); context.write(textId, new Text("user.dir " + userDir)); try { java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost(); context.write(textId, new Text("hostname " + localMachine.getHostName())); } catch (java.net.UnknownHostException uhe) { // handle exception } } }
public class class_name { private void emitLogHeader(Context context, String mapredTaskId) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); Text textId = new Text(mapredTaskId); for (Map.Entry<String, String> entry: conf) { StringBuilder sb = new StringBuilder(); sb.append(entry.getKey()); sb.append("="); sb.append(entry.getValue()); context.write(textId, new Text(sb.toString())); } context.write(textId, new Text("----- Properties -----")); String[] plist = { "mapred.local.dir", "mapred.child.java.opts", }; for (String k : plist) { String v = conf.get(k); if (v == null) { v = "(null)"; // depends on control dependency: [if], data = [null)] } context.write(textId, new Text(k + " " + v)); } String userDir = System.getProperty("user.dir"); context.write(textId, new Text("user.dir " + userDir)); try { java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost(); context.write(textId, new Text("hostname " + localMachine.getHostName())); } catch (java.net.UnknownHostException uhe) { // handle exception } } }
public class class_name { private List<String> parseComment(List<String> content, String propertyName) { List<String> comments = new ArrayList<>(); String commentEnd = content.get(annotationIndex - 1).trim(); if (commentEnd.equals("*/")) { int startCommentIndex = -1; for (int index = annotationIndex - 1; index >= 0; index--) { String line = content.get(index).trim(); if (line.equals("/**")) { startCommentIndex = index + 1; break; } } if (startCommentIndex == -1) { throw new BeanCodeGenException("Unable to locate comment start at line " + annotationIndex, beanParser.getFile(), annotationIndex); } if (startCommentIndex < annotationIndex - 1) { for (int i = startCommentIndex; i < annotationIndex - 1; i++) { String commentLine = content.get(i).trim(); if (commentLine.startsWith("*")) { commentLine = commentLine.substring(1).trim(); } if (commentLine.startsWith("@return") == false && commentLine.startsWith("@param") == false && commentLine.startsWith("@throws") == false && commentLine.startsWith("@exception") == false) { comments.add(commentLine); } } String firstLine = comments.get(0); if (firstLine.length() > 0) { comments.set(0, firstLine.substring(0, 1).toLowerCase(Locale.ENGLISH) + firstLine.substring(1)); } else { comments.remove(0); } } } else if (commentEnd.startsWith("/**") && commentEnd.endsWith("*/")) { int startPos = commentEnd.indexOf("/**") + 3; int endPos = commentEnd.lastIndexOf("*/"); String comment = commentEnd.substring(startPos, endPos).trim(); if (comment.length() > 0) { comments.add(comment.substring(0, 1).toLowerCase(Locale.ENGLISH) + comment.substring(1)); } } if (comments.size() == 0) { comments.add("the " + propertyName + "."); } return comments; } }
public class class_name { private List<String> parseComment(List<String> content, String propertyName) { List<String> comments = new ArrayList<>(); String commentEnd = content.get(annotationIndex - 1).trim(); if (commentEnd.equals("*/")) { int startCommentIndex = -1; for (int index = annotationIndex - 1; index >= 0; index--) { String line = content.get(index).trim(); if (line.equals("/**")) { startCommentIndex = index + 1; break; } } if (startCommentIndex == -1) { throw new BeanCodeGenException("Unable to locate comment start at line " + annotationIndex, beanParser.getFile(), annotationIndex); } if (startCommentIndex < annotationIndex - 1) { for (int i = startCommentIndex; i < annotationIndex - 1; i++) { String commentLine = content.get(i).trim(); if (commentLine.startsWith("*")) { commentLine = commentLine.substring(1).trim(); } if (commentLine.startsWith("@return") == false && commentLine.startsWith("@param") == false && commentLine.startsWith("@throws") == false && commentLine.startsWith("@exception") == false) { comments.add(commentLine); } } String firstLine = comments.get(0); if (firstLine.length() > 0) { comments.set(0, firstLine.substring(0, 1).toLowerCase(Locale.ENGLISH) + firstLine.substring(1)); } else { comments.remove(0); } } } else if (commentEnd.startsWith("/**") && commentEnd.endsWith("*/")) { int startPos = commentEnd.indexOf("/**") + 3; int endPos = commentEnd.lastIndexOf("*/"); String comment = commentEnd.substring(startPos, endPos).trim(); if (comment.length() > 0) { comments.add(comment.substring(0, 1).toLowerCase(Locale.ENGLISH) + comment.substring(1)); // depends on control dependency: [if], data = [none] } } if (comments.size() == 0) { comments.add("the " + propertyName + "."); // depends on control dependency: [if], data = [none] } return comments; // depends on control dependency: [for], data = [none] } }
public class class_name { public ISharedObject getSharedObject(IScope scope, String name, boolean persistent) { if (!hasSharedObject(scope, name)) { createSharedObject(scope, name, persistent); } return getSharedObject(scope, name); } }
public class class_name { public ISharedObject getSharedObject(IScope scope, String name, boolean persistent) { if (!hasSharedObject(scope, name)) { createSharedObject(scope, name, persistent); // depends on control dependency: [if], data = [none] } return getSharedObject(scope, name); } }
public class class_name { public void marshall(FrameCaptureGroupSettings frameCaptureGroupSettings, ProtocolMarshaller protocolMarshaller) { if (frameCaptureGroupSettings == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(frameCaptureGroupSettings.getDestination(), DESTINATION_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(FrameCaptureGroupSettings frameCaptureGroupSettings, ProtocolMarshaller protocolMarshaller) { if (frameCaptureGroupSettings == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(frameCaptureGroupSettings.getDestination(), DESTINATION_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static IEntitySerializer getSerializer(final String serializeFormat) throws SerializationException { IEntitySerializer serializer = null; if (isValidSerializeFormat(serializeFormat)) { if (serializeFormat.equalsIgnoreCase(XML_SERIALIZE_FORMAT)) { serializer = new XMLSerializer(); } else if (serializeFormat.equalsIgnoreCase(JSON_SERIALIZE_FORMAT)) { serializer = new JSONSerializer(); } } return serializer; } }
public class class_name { public static IEntitySerializer getSerializer(final String serializeFormat) throws SerializationException { IEntitySerializer serializer = null; if (isValidSerializeFormat(serializeFormat)) { if (serializeFormat.equalsIgnoreCase(XML_SERIALIZE_FORMAT)) { serializer = new XMLSerializer(); // depends on control dependency: [if], data = [none] } else if (serializeFormat.equalsIgnoreCase(JSON_SERIALIZE_FORMAT)) { serializer = new JSONSerializer(); // depends on control dependency: [if], data = [none] } } return serializer; } }
public class class_name { private void processCommandLine(final Sheet sheet, final Cell cell, final String line, final List<ConfigCommand> cList, final int sheetRightCol) { int nameEndIndex = line.indexOf(TieConstants.ATTR_PREFIX, TieConstants.COMMAND_PREFIX.length()); if (nameEndIndex < 0) { String errMsg = "Failed to parse command line [" + line + "]. Expected '" + TieConstants.ATTR_PREFIX + "' symbol."; LOG.severe(errMsg); throw new IllegalStateException(errMsg); } String commandName = line.substring(TieConstants.COMMAND_PREFIX.length(), nameEndIndex).trim(); Map<String, String> attrMap = buildAttrMap(line, nameEndIndex); ConfigCommand configCommand = createConfigCommand(sheet, cell, sheetRightCol, commandName, attrMap); if (configCommand != null) { cList.add(configCommand); } } }
public class class_name { private void processCommandLine(final Sheet sheet, final Cell cell, final String line, final List<ConfigCommand> cList, final int sheetRightCol) { int nameEndIndex = line.indexOf(TieConstants.ATTR_PREFIX, TieConstants.COMMAND_PREFIX.length()); if (nameEndIndex < 0) { String errMsg = "Failed to parse command line [" + line + "]. Expected '" + TieConstants.ATTR_PREFIX + "' symbol."; // depends on control dependency: [if], data = [none] LOG.severe(errMsg); // depends on control dependency: [if], data = [none] throw new IllegalStateException(errMsg); } String commandName = line.substring(TieConstants.COMMAND_PREFIX.length(), nameEndIndex).trim(); Map<String, String> attrMap = buildAttrMap(line, nameEndIndex); ConfigCommand configCommand = createConfigCommand(sheet, cell, sheetRightCol, commandName, attrMap); if (configCommand != null) { cList.add(configCommand); // depends on control dependency: [if], data = [(configCommand] } } }
public class class_name { public Cursor<Series> getSeries(Filter filter) { URI uri = null; try { URIBuilder builder = new URIBuilder(String.format("/%s/series/", API_VERSION)); addFilterToURI(builder, filter); uri = builder.build(); } catch (URISyntaxException e) { String message = String.format("Could not build URI with input - filter: %s", filter); throw new IllegalArgumentException(message, e); } Cursor<Series> cursor = new SeriesCursor(uri, this); return cursor; } }
public class class_name { public Cursor<Series> getSeries(Filter filter) { URI uri = null; try { URIBuilder builder = new URIBuilder(String.format("/%s/series/", API_VERSION)); addFilterToURI(builder, filter); // depends on control dependency: [try], data = [none] uri = builder.build(); // depends on control dependency: [try], data = [none] } catch (URISyntaxException e) { String message = String.format("Could not build URI with input - filter: %s", filter); throw new IllegalArgumentException(message, e); } // depends on control dependency: [catch], data = [none] Cursor<Series> cursor = new SeriesCursor(uri, this); return cursor; } }
public class class_name { public Server getServerById(final String id) { for (Server server : SERVERS) { if (server.getId().equals(id)) { return server; } } return null; } }
public class class_name { public Server getServerById(final String id) { for (Server server : SERVERS) { if (server.getId().equals(id)) { return server; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { private JsonNode applyShapeModifier(JsonNode node, ShapeModifier modifier) { if (node == null || modifier == null) { return node; } if (modifier.getExclude() == null && modifier.getModify() == null) { return node; } if (!node.isObject()) return node; final ObjectNode obj = (ObjectNode) node; ObjectNode modified = MAPPER.createObjectNode(); // Filter any excluded members final List<String> excludes = modifier.getExclude() != null ? modifier.getExclude() : Collections.emptyList(); obj.fieldNames().forEachRemaining(m -> { if (!excludes.contains(m)) { modified.set(m, obj.get(m)); } }); // Apply property renames final List<Map<String, ShapeModifier_ModifyModel>> modify = modifier.getModify() != null ? modifier.getModify() : Collections.emptyList(); modify.forEach(memberMods -> memberMods.entrySet().forEach(memberMod -> { String memberName = memberMod.getKey(); ShapeModifier_ModifyModel modelModify = memberMod.getValue(); if (modelModify.getEmitPropertyName() != null) { String newName = modelModify.getEmitPropertyName(); modified.set(newName, modified.get(memberName)); modified.remove(memberName); memberName = newName; } }) ); return modified; } }
public class class_name { private JsonNode applyShapeModifier(JsonNode node, ShapeModifier modifier) { if (node == null || modifier == null) { return node; // depends on control dependency: [if], data = [none] } if (modifier.getExclude() == null && modifier.getModify() == null) { return node; // depends on control dependency: [if], data = [none] } if (!node.isObject()) return node; final ObjectNode obj = (ObjectNode) node; ObjectNode modified = MAPPER.createObjectNode(); // Filter any excluded members final List<String> excludes = modifier.getExclude() != null ? modifier.getExclude() : Collections.emptyList(); obj.fieldNames().forEachRemaining(m -> { if (!excludes.contains(m)) { modified.set(m, obj.get(m)); } }); // Apply property renames final List<Map<String, ShapeModifier_ModifyModel>> modify = modifier.getModify() != null ? modifier.getModify() : Collections.emptyList(); modify.forEach(memberMods -> memberMods.entrySet().forEach(memberMod -> { String memberName = memberMod.getKey(); ShapeModifier_ModifyModel modelModify = memberMod.getValue(); if (modelModify.getEmitPropertyName() != null) { String newName = modelModify.getEmitPropertyName(); modified.set(newName, modified.get(memberName)); modified.remove(memberName); memberName = newName; } }) ); return modified; } }
public class class_name { private Map<String, String> buildLocalesMap() { TreeMap<String, String> localesMap = new TreeMap<String, String>(); Iterator<Locale> it = OpenCms.getLocaleManager().getAvailableLocales().iterator(); while (it.hasNext()) { Locale locale = it.next(); localesMap.put(locale.toString(), locale.getDisplayName(getWorkplaceLocale())); } return localesMap; } }
public class class_name { private Map<String, String> buildLocalesMap() { TreeMap<String, String> localesMap = new TreeMap<String, String>(); Iterator<Locale> it = OpenCms.getLocaleManager().getAvailableLocales().iterator(); while (it.hasNext()) { Locale locale = it.next(); localesMap.put(locale.toString(), locale.getDisplayName(getWorkplaceLocale())); // depends on control dependency: [while], data = [none] } return localesMap; } }
public class class_name { public void backupAndRestore(Context ctx, SQLiteDatabase db) { if (backupAllTablesToCsv(ctx, db, null)) { dropAndCreate(db); restoreAllTablesFromCsv(ctx, db, null); } else { throw new RuntimeException("Backup of " + getDatabaseName() + " failed, aborting upgrade"); } } }
public class class_name { public void backupAndRestore(Context ctx, SQLiteDatabase db) { if (backupAllTablesToCsv(ctx, db, null)) { dropAndCreate(db); // depends on control dependency: [if], data = [none] restoreAllTablesFromCsv(ctx, db, null); // depends on control dependency: [if], data = [none] } else { throw new RuntimeException("Backup of " + getDatabaseName() + " failed, aborting upgrade"); } } }
public class class_name { public void exclude(String formatName) { for (int i = 0; i < count; i++) { md[i].exclude(formatName); } } }
public class class_name { public void exclude(String formatName) { for (int i = 0; i < count; i++) { md[i].exclude(formatName); // depends on control dependency: [for], data = [i] } } }
public class class_name { private boolean isBeingDereferenced(final DetailAST pLiteralNew) { boolean result = false; final DetailAST parent = pLiteralNew.getParent(); if (parent.getType() == TokenTypes.DOT && (pLiteralNew.getNextSibling() != null || parent.getParent().getType() == TokenTypes.DOT)) { result = true; } return result; } }
public class class_name { private boolean isBeingDereferenced(final DetailAST pLiteralNew) { boolean result = false; final DetailAST parent = pLiteralNew.getParent(); if (parent.getType() == TokenTypes.DOT && (pLiteralNew.getNextSibling() != null || parent.getParent().getType() == TokenTypes.DOT)) { result = true; // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { public GriddedTile query(String tableName, long tileId) { GriddedTile griddedTile = null; try { QueryBuilder<GriddedTile, Long> qb = queryBuilder(); qb.where().eq(GriddedTile.COLUMN_TABLE_NAME, tableName).and() .eq(GriddedTile.COLUMN_TABLE_ID, tileId); PreparedQuery<GriddedTile> query = qb.prepare(); griddedTile = queryForFirst(query); } catch (SQLException e) { throw new GeoPackageException( "Failed to query for Gridded Tile objects by Table Name: " + tableName + ", Tile Id: " + tileId, e); } return griddedTile; } }
public class class_name { public GriddedTile query(String tableName, long tileId) { GriddedTile griddedTile = null; try { QueryBuilder<GriddedTile, Long> qb = queryBuilder(); qb.where().eq(GriddedTile.COLUMN_TABLE_NAME, tableName).and() .eq(GriddedTile.COLUMN_TABLE_ID, tileId); // depends on control dependency: [try], data = [none] PreparedQuery<GriddedTile> query = qb.prepare(); griddedTile = queryForFirst(query); // depends on control dependency: [try], data = [none] } catch (SQLException e) { throw new GeoPackageException( "Failed to query for Gridded Tile objects by Table Name: " + tableName + ", Tile Id: " + tileId, e); } // depends on control dependency: [catch], data = [none] return griddedTile; } }
public class class_name { @Override public EEnum getIfcOutletTypeEnum() { if (ifcOutletTypeEnumEEnum == null) { ifcOutletTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(1025); } return ifcOutletTypeEnumEEnum; } }
public class class_name { @Override public EEnum getIfcOutletTypeEnum() { if (ifcOutletTypeEnumEEnum == null) { ifcOutletTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(1025); // depends on control dependency: [if], data = [none] } return ifcOutletTypeEnumEEnum; } }
public class class_name { @Override protected String doBuildColumnString(String dm) { StringBuilder sb = new StringBuilder(); sb.append(dm).append(createdBy); sb.append(dm).append(createdTime); sb.append(dm).append(expiredTime); sb.append(dm).append(name); sb.append(dm).append(parameterName); sb.append(dm).append(permissions); sb.append(dm).append(token); sb.append(dm).append(updatedBy); sb.append(dm).append(updatedTime); if (sb.length() > dm.length()) { sb.delete(0, dm.length()); } sb.insert(0, "{").append("}"); return sb.toString(); } }
public class class_name { @Override protected String doBuildColumnString(String dm) { StringBuilder sb = new StringBuilder(); sb.append(dm).append(createdBy); sb.append(dm).append(createdTime); sb.append(dm).append(expiredTime); sb.append(dm).append(name); sb.append(dm).append(parameterName); sb.append(dm).append(permissions); sb.append(dm).append(token); sb.append(dm).append(updatedBy); sb.append(dm).append(updatedTime); if (sb.length() > dm.length()) { sb.delete(0, dm.length()); // depends on control dependency: [if], data = [dm.length())] } sb.insert(0, "{").append("}"); return sb.toString(); } }