auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void write(SelectionKey key) throws IOException { long startTimeInMs = SystemTime.getInstance().milliseconds(); try { SocketChannel socketChannel = (SocketChannel) key.channel(); SocketServerResponse response = (SocketServerResponse) key.attachment(); Send responseSend = response.getPayload(); if (responseSend == null) { throw new IllegalStateException("Registered for write interest but no response attached to key."); } responseSend.writeTo(socketChannel); if (logger.isTraceEnabled()) { logger.trace("Bytes written to using key ", socketChannel.socket().getRemoteSocketAddress(), key); } if (responseSend.isSendComplete()) { if (logger.isTraceEnabled()) { logger.trace("Finished writing, registering for read on connection {}", socketChannel.socket().getRemoteSocketAddress()); } response.onSendComplete(); metrics.sendInFlight.dec(); key.attach(null); key.interestOps(SelectionKey.OP_READ); } else { if (logger.isTraceEnabled()) { logger.trace("Did not finish writing, registering for write again on connection {}", socketChannel.socket().getRemoteSocketAddress()); } key.interestOps(SelectionKey.OP_WRITE); wakeup(); } } finally { long writeTime = SystemTime.getInstance().milliseconds() - startTimeInMs; logger.trace("SocketServer write piece of data to channel time = {}", writeTime); } }

Target:
private void write(SelectionKey key) throws IOException { long startTimeToWriteInMs = SystemTime.getInstance().milliseconds(); try { SocketChannel socketChannel = (SocketChannel) key.channel(); SocketServerResponse response = (SocketServerResponse) key.attachment(); Send responseSend = response.getPayload(); if (responseSend == null) { throw new IllegalStateException("Registered for write interest but no response attached to key."); } responseSend.writeTo(socketChannel); if (logger.isTraceEnabled()) { logger.trace("Bytes written to using key ", socketChannel.socket().getRemoteSocketAddress(), key); } if (responseSend.isSendComplete()) { if (logger.isTraceEnabled()) { logger.trace("Finished writing, registering for read on connection {}", socketChannel.socket().getRemoteSocketAddress()); } response.onSendComplete(); metrics.sendInFlight.dec(); key.attach(null); key.interestOps(SelectionKey.OP_READ); } else { if (logger.isTraceEnabled()) { logger.trace("Did not finish writing, registering for write again on connection {}", socketChannel.socket().getRemoteSocketAddress()); } key.interestOps(SelectionKey.OP_WRITE); wakeup(); } } finally { long writeTime = SystemTime.getInstance().milliseconds() - startTimeToWriteInMs; logger.trace("SocketServer time spent on write per key = {}", writeTime); } }
Source:
public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof HttpURI)) return false; return toString().equals(o.toString()); }

Target:
public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof HttpURI)) return false; return asString().equals(((HttpURI)o).asString()); }
Source:
private AnnotationMirror standardizeDependentTypeAnnotation( FlowExpressionContext context, TreePath localScope, AnnotationMirror anno, boolean useLocalScope, boolean removeErroneousExpressions) { AnnotationBuilder builder = new AnnotationBuilder( factory.getProcessingEnv(), AnnotationUtils.annotationName(anno)); for (String value : getListOfExpressionElements(anno)) { List<String> expressionStrings = AnnotationUtils.getElementValueArray(anno, value, String.class, true); List<String> standardizedStrings = new ArrayList<>(); for (String expression : expressionStrings) { String standardized = standardizeString( expression, context, localScope, useLocalScope, removeErroneousExpressions); if (standardized == null) { assert removeErroneousExpressions; } else { standardizedStrings.add(standardized); } } builder.setValue(value, standardizedStrings); } return builder.build(); }

Target:
private AnnotationMirror standardizeDependentTypeAnnotation( FlowExpressionContext context, TreePath localScope, AnnotationMirror anno, boolean useLocalScope, boolean removeErroneousExpressions) { AnnotationBuilder builder = new AnnotationBuilder( factory.getProcessingEnv(), AnnotationUtils.annotationName(anno)); for (String value : getListOfExpressionElements(anno)) { List<String> expressionStrings = AnnotationUtils.getElementValueArray(anno, value, String.class, true); List<String> standardizedStrings = new ArrayList<>(); for (String expression : expressionStrings) { String standardized = standardizeString(expression, context, localScope, useLocalScope); if (removeErroneousExpressions && DependentTypesError.isExpressionError(standardized)) { } else { standardizedStrings.add(standardized); } } builder.setValue(value, standardizedStrings); } return builder.build(); }
Source:
public void showConflicts(final String projectPath, final List<String> paths, final AsyncCallback<List<String>> callback) { status(projectPath, paths, "infinity", false, false, false, false, false, new ArrayList<String>(), new AsyncRequestCallback<CLIOutputResponse>(dtoUnmarshallerFactory.newUnmarshaller(CLIOutputResponse.class)) { @Override protected void onSuccess(CLIOutputResponse result) { if (result != null) { List<String> conflictsList = parseConflictsList(result.getOutput()); callback.onSuccess(conflictsList); } else { callback.onFailure(new Exception("showConflicts : no SvnResponse.")); } } @Override protected void onFailure(Throwable exception) { callback.onFailure(exception); } }); }

Target:
public void showConflicts(final String projectPath, final List<String> paths, final AsyncCallback<List<String>> callback) { status(projectPath, paths, "infinity", false, false, false, false, false, Collections.<String>emptyList(), new AsyncRequestCallback<CLIOutputResponse>(dtoUnmarshallerFactory.newUnmarshaller(CLIOutputResponse.class)) { @Override protected void onSuccess(CLIOutputResponse result) { if (result != null) { List<String> conflictsList = parseConflictsList(result.getOutput()); callback.onSuccess(conflictsList); } else { callback.onFailure(new Exception("showConflicts : no SvnResponse.")); } } @Override protected void onFailure(Throwable exception) { callback.onFailure(exception); } }); }
Source:
private void registerDeviceDiscoveryService(LIRCBridgeHandler handler) { LIRCRemoteDiscoveryService discoveryService = new LIRCRemoteDiscoveryService(handler); discoveryService.activate(); this.discoveryServiceRegs.put(handler.getThing().getUID(), bundleContext .registerService(DiscoveryService.class.getName(), discoveryService, new Hashtable<String, Object>())); }

Target:
private void registerDeviceDiscoveryService(LIRCBridgeHandler handler) { LIRCRemoteDiscoveryService discoveryService = new LIRCRemoteDiscoveryService(handler); this.discoveryServiceRegs.put(handler.getThing().getUID(), bundleContext .registerService(DiscoveryService.class.getName(), discoveryService, new Hashtable<String, Object>())); }
Source:
private void cache(Class<? extends Resource> clazz, Map<String, ?> data, CanonicalUri uri) { Assert.notEmpty(data, "Resource data cannot be null or empty."); String href = hrefResolver.resolveHref(data, clazz, baseUrlResolver.getBaseUrl()); if (isDirectlyCacheable(clazz, data)) { Assert.notNull(href, "Resource data must contain an 'href' attribute."); Assert.isTrue(data.size() > 1, "Resource data must be materialized to be cached " + "(need more than just an 'href' attribute)."); } Map<String, Object> cacheValue = cacheMapInitializer.initialize(clazz, data, uri.getQuery()); for (Map.Entry<String, ?> entry : data.entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); cacheValue.put(name, value); } if (isDirectlyCacheable(clazz, cacheValue)) { Cache cache = getCache(clazz); String cacheKey = getCacheKey(href); Object previousCacheValue = cache.put(cacheKey, cacheValue); logger.debug("Caching object for key '{}', class: '{}', updated {}", cacheKey, clazz, previousCacheValue != null); } }

Target:
private void cache(Class<? extends Resource> clazz, Map<String, ?> data, CanonicalUri uri) { Assert.notEmpty(data, "Resource data cannot be null or empty."); String href = hrefResolver.resolveHref(data, clazz); if (isDirectlyCacheable(clazz, data)) { Assert.notNull(href, "Resource data must contain an 'href' attribute."); Assert.isTrue(data.size() > 0, "Resource data must be materialized to be cached " + "(need more at least one attribute)."); } Map<String, Object> cacheValue = cacheMapInitializer.initialize(clazz, data, uri.getQuery()); data.entrySet().forEach(entry -> cacheValue.put(entry.getKey(), entry.getValue()) ); if (isDirectlyCacheable(clazz, cacheValue)) { Cache cache = getCache(clazz); String cacheKey = getCacheKey(href); Object previousCacheValue = cache.put(cacheKey, cacheValue); logger.debug("Caching object for key '{}', class: '{}', updated {}", cacheKey, clazz, previousCacheValue != null); } }
Source:
private StringBuilder getEiscpMessage(String eiscpCmd) { logger.debug("Requested Command is " + eiscpCmd); StringBuilder sb = new StringBuilder(); sb.append("!"); sb.append("1"); sb.append(eiscpCmd); sb.append((char) 0x0D); logger.debug("Serial command is " + sb); return sb; }

Target:
private StringBuilder getEiscpMessage(String eiscpCmd) { logger.debug("Requested Command is '{}' ", eiscpCmd); StringBuilder sb = new StringBuilder(); sb.append("!"); sb.append("1"); sb.append(eiscpCmd); sb.append((char) 0x0D); logger.debug("Serial command is '{}'", sb); return sb; }
Source:
public boolean isEnabled() { final Repository repository = getRepository(); return repository != null && containsHead(repository); }

Target:
public boolean isEnabled() { final Repository repo = getRepository(); return repo != null && containsHead(repo); }
Source:
private Queue<ImageConfiguration> prepareStart(ServiceHub hub, QueryService queryService, RunService runService, Set<String> imageAliases) throws DockerAccessException, MojoExecutionException { final Queue<ImageConfiguration> imagesWaitingToStart = new ArrayDeque<>(); for (StartOrderResolver.Resolvable resolvable : runService.getImagesConfigsInOrder(queryService, getResolvedImages())) { final ImageConfiguration imageConfig = (ImageConfiguration) resolvable; String imageName = imageConfig.getName(); BuildService.BuildContext buildContext = getBuildContext(); hub.getBuildService().checkImageWithAutoPull(imageName, getConfiguredRegistry(imageConfig, pullRegistry), imageConfig.getBuildConfiguration() == null, buildContext); RunImageConfiguration runConfig = imageConfig.getRunConfiguration(); NetworkConfig config = runConfig.getNetworkingConfig(); if (autoCreateCustomNetworks && config.isCustomNetwork()) { runService.createCustomNetworkIfNotExistant(config.getCustomNetwork()); } imagesWaitingToStart.add(imageConfig); updateAliasesSet(imageAliases, imageConfig.getAlias()); } return imagesWaitingToStart; }

Target:
private Queue<ImageConfiguration> prepareStart(ServiceHub hub, QueryService queryService, RunService runService, Set<String> imageAliases) throws DockerAccessException, MojoExecutionException { final Queue<ImageConfiguration> imagesWaitingToStart = new ArrayDeque<>(); for (StartOrderResolver.Resolvable resolvable : runService.getImagesConfigsInOrder(queryService, getResolvedImages())) { final ImageConfiguration imageConfig = (ImageConfiguration) resolvable; String imageName = imageConfig.getName(); RegistryService.RegistryConfig registryConfig = getRegistryConfig(); hub.getRegistryService().checkImageWithAutoPull(imageName, getConfiguredRegistry(imageConfig, pullRegistry), imageConfig.getBuildConfiguration() == null, registryConfig); RunImageConfiguration runConfig = imageConfig.getRunConfiguration(); NetworkConfig config = runConfig.getNetworkingConfig(); if (autoCreateCustomNetworks && config.isCustomNetwork()) { runService.createCustomNetworkIfNotExistant(config.getCustomNetwork()); } imagesWaitingToStart.add(imageConfig); updateAliasesSet(imageAliases, imageConfig.getAlias()); } return imagesWaitingToStart; }
Source:
private static User getFromStoredData(UUID uniqueId) { File dataFile = getPlayerDataFile(uniqueId); if (dataFile == null) { return null; } Optional<org.spongepowered.api.profile.GameProfile> profile = getProfileFromServer(uniqueId); if (profile.isPresent()) { return create((GameProfile) profile.get()); } else { return null; } }

Target:
private static User getFromStoredData(UUID uniqueId) { File dataFile = getPlayerDataFile(uniqueId); if (dataFile == null) { return null; } Optional<org.spongepowered.api.profile.GameProfile> profile = getProfileFromServer(uniqueId); if (profile.isPresent()) { User user = create((GameProfile) profile.get()); try { ((SpongeUser) user).readFromNbt(CompressedStreamTools.readCompressed(new FileInputStream(dataFile))); } catch (IOException e) { SpongeHooks.logWarning("Corrupt user file {}. {}", dataFile, e); } return user; } else { return null; } }
Source:
public void updateResidentIdP(IdentityProvider identityProvider) throws IdentityProviderManagementException { try { String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); IdentityProviderManager.getInstance().updateResidentIdP(identityProvider, tenantDomain); } catch (IdentityProviderManagementException idpException) { log.error("Error while updating ResidentIdP", idpException); throw idpException; } }

Target:
public void updateResidentIdP(IdentityProvider identityProvider) throws IdentityProviderManagementException { String tenantDomain = ""; try { tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); IdentityProviderManager.getInstance().updateResidentIdP(identityProvider, tenantDomain); } catch (IdentityProviderManagementException idpException) { log.error("Error while updating ResidentIdP in tenantDomain : " + tenantDomain, idpException); throw idpException; } }
Source:
@Override public String extractUrl() { String url = ""; if (getIntent().getExtras() != null) { url = getIntent().getStringExtra(URL_KEY); } return url; }

Target:
@Override public String extractUrl() { return extractExtra(URL_KEY); }
Source:
private void cleanupBackupFiles() throws IOException { if (dataDirPath == null) { return; } File backupDir = dataDirPath.toFile(); FileFilter tempFileFilter = (File pathname) -> pathname.getName().startsWith("storeId"); File[] files = backupDir.listFiles(tempFileFilter); if (files != null) { for (File file : files) { File deleteFile = new File(MOUNT_PATH + file.getName() + File.separator + "compactionPolicyInfo.json"); logger.trace("Delete temp file {}", deleteFile.getName()); deleteFile(deleteFile.toPath()); } } }

Target:
private void cleanupBackupFiles() { if (dataDirPath == null) { return; } File backupDir = dataDirPath.toFile(); FileFilter tempFileFilter = (File pathname) -> pathname.getName().startsWith("storeId"); File[] files = backupDir.listFiles(tempFileFilter); if (files != null) { for (File file : files) { File deleteFile = new File(MOUNT_PATH + file.getName() + File.separator + "compactionPolicyInfo.json"); logger.trace("Delete temp file {}", deleteFile.getName()); deleteFile(deleteFile.toPath()); } } }
Source:
public static void main(String[] args) { final RestServer restServer; int exitCode = 0; try { final InvocationOptions options = new InvocationOptions(args); final Properties properties = Utils.loadProps(options.serverPropsFilePath); final VerifiableProperties verifiableProperties = new VerifiableProperties(properties); final ClusterMap clusterMap = new ClusterMapManager(options.hardwareLayoutFilePath, options.partitionLayoutFilePath, new ClusterMapConfig(verifiableProperties)); final SSLFactory sslFactory = new SSLFactory(new SSLConfig(verifiableProperties)); logger.info("Bootstrapping RestServer"); restServer = new RestServer(verifiableProperties, clusterMap, new LoggingNotificationSystem(), sslFactory); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { logger.info("Received shutdown signal. Shutting down RestServer"); restServer.shutdown(); } }); restServer.start(); restServer.awaitShutdown(); } catch (Exception e) { logger.error("Exception during bootstrap of RestServer", e); exitCode = 1; } logger.info("Exiting RestServerMain"); System.exit(exitCode); }

Target:
public static void main(String[] args) { final RestServer restServer; int exitCode = 0; try { final InvocationOptions options = new InvocationOptions(args); final Properties properties = Utils.loadProps(options.serverPropsFilePath); final VerifiableProperties verifiableProperties = new VerifiableProperties(properties); final ClusterMap clusterMap = new ClusterMapManager(options.hardwareLayoutFilePath, options.partitionLayoutFilePath, new ClusterMapConfig(verifiableProperties)); final SSLFactory sslFactory = getSSLFactoryIfRequired(verifiableProperties); logger.info("Bootstrapping RestServer"); restServer = new RestServer(verifiableProperties, clusterMap, new LoggingNotificationSystem(), sslFactory); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { logger.info("Received shutdown signal. Shutting down RestServer"); restServer.shutdown(); } }); restServer.start(); restServer.awaitShutdown(); } catch (Exception e) { logger.error("Exception during bootstrap of RestServer", e); exitCode = 1; } logger.info("Exiting RestServerMain"); System.exit(exitCode); }
Source:
private HashSet<String> getCurrentlyUsedRepo() { HashSet<String> currentlyUsedRepos = new HashSet<String>(); String defaultRepo = ui.logic.getDefaultRepo(); currentlyUsedRepos.add(defaultRepo); for(int i = 0; i < panels.getNumberOfPanels(); i++) { AbstractPanel currPanel = panels.getPanel(i); if (currPanel instanceof FilterPanel) { FilterPanel currFilterPanel = (FilterPanel) currPanel; FilterExpression panelExpression = currFilterPanel.getCurrentFilterExpression(); List<Qualifier> panelMetaQualifiers = panelExpression.find(Qualifier::isMetaQualifier); panelMetaQualifiers.forEach(metaQualifier -> { if (metaQualifier.getName().equals(Qualifier.REPO) && metaQualifier.getContent().isPresent()) { currentlyUsedRepos.add(metaQualifier.getContent().get()); } }); } } return currentlyUsedRepos; }

Target:
private HashSet<String> getCurrentlyUsedRepo() { HashSet<String> currentlyUsedRepos = new HashSet<>(); String defaultRepo = ui.logic.getDefaultRepo(); currentlyUsedRepos.add(defaultRepo); currentlyUsedRepos.addAll(panels.getRepositoriesReferencedOnAllPanels()); return currentlyUsedRepos; }
Source:
private ArgumentMatcher<Collection<GlusterVolumeOptionEntity>> areAddedOptions() { return new ArgumentMatcher<Collection<GlusterVolumeOptionEntity>>() { @Override public boolean matches(Object argument) { if (!(argument instanceof Collection<?>)) { return false; } @SuppressWarnings("unchecked") ArrayList<GlusterVolumeOptionEntity> optionsToAdd = (ArrayList<GlusterVolumeOptionEntity>) argument; existingReplVol.setOption(optionsToAdd.get(0)); return (optionsToAdd.size() == 1 && (optionsToAdd.get(0).getKey().equals(OPTION_AUTH_REJECT))); } }; }

Target:
private ArgumentMatcher<Collection<GlusterVolumeOptionEntity>> areAddedOptions() { return new ArgumentMatcher<Collection<GlusterVolumeOptionEntity>>() { @Override public boolean matches(Object argument) { if (!(argument instanceof ArrayList)) { return false; } @SuppressWarnings("unchecked") ArrayList<GlusterVolumeOptionEntity> optionsToAdd = (ArrayList<GlusterVolumeOptionEntity>) argument; existingReplVol.setOption(optionsToAdd.get(0)); return (optionsToAdd.size() == 1 && (optionsToAdd.get(0).getKey().equals(OPTION_AUTH_REJECT))); } }; }
Source:
public static PCollection<Variant> joinGvcfVariantsTransform( PCollection<SearchVariantsRequest> input, GenomicsFactory.OfflineAuth auth, String fields) { for (String field : REQUIRED_FIELDS) { Preconditions.checkState(fields.contains(field), "Required field missing: " + field + "Add this field to the list of Variants fields returned in the partial response."); } return joinGvcfVariants(input, auth, fields); }

Target:
public static PCollection<Variant> joinGvcfVariantsTransform( PCollection<SearchVariantsRequest> input, GenomicsFactory.OfflineAuth auth, String fields) { for (String field : REQUIRED_FIELDS) { Preconditions .checkState( fields.contains(field), "Required field missing: %s Add this field to the list of Variants fields returned in the partial response.", field); } return joinGvcfVariants(input, auth, fields); }
Source:
public void releaseBlockingChannel(BlockingChannel blockingChannel) { rwlock.readLock().lock(); try { if (blockingChannelActiveConnections.remove(blockingChannel)) { blockingChannelAvailableConnections.add(blockingChannel); logger.trace( "Adding connection to {}:{} back to pool. Current available connections Current active connections {}", blockingChannel.getRemoteHost(), blockingChannel.getRemotePort(), blockingChannelAvailableConnections.size(), blockingChannelActiveConnections.size()); } else { logger.error("Tried to add invalid connection. Channel does not belong in the active queue. Host port {}" + " channel host channel port {}", host, port, blockingChannel.getRemoteHost(), blockingChannel.getRemotePort()); } } finally { rwlock.readLock().unlock(); } }

Target:
public void releaseBlockingChannel(BlockingChannel blockingChannel) { rwlock.readLock().lock(); try { if (blockingChannelActiveConnections.remove(blockingChannel)) { blockingChannelAvailableConnections.add(blockingChannel); logger.trace( "Adding connection to {}:{} back to pool. Current available connections Current active connections {}", blockingChannel.getRemoteHost(), blockingChannel.getRemotePort(), blockingChannelAvailableConnections.size(), blockingChannelActiveConnections.size()); } else { logger.error("Tried to add invalid connection. Channel does not belong in the active queue. Host port {}" + " channel host channel port {}", host, port.getPort(), blockingChannel.getRemoteHost(), blockingChannel.getRemotePort()); } } finally { rwlock.readLock().unlock(); } }
Source:
public boolean unblock() { if (blocker != null) { if (client.send(blocker.buffer, blocker.dataOffset, blocker.length - (blocker.dataOffset - blocker.offset))) { blocker = null; } else { return false; } } return true; }

Target:
public boolean unblock() { if (blocker == null) { return true; } if (client.send(blocker.buffer, blocker.dataOffset, blocker.length - (blocker.dataOffset - blocker.offset))) { blocker = null; return true; } return false; }
Source:
public void init() { URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":2233"); testUrl = URL.valueOf("<LINK_0>"); abstractRegistry = new AbstractRegistry(url) { @Override public boolean isAvailable() { return false; } }; listener = urls -> notifySuccess = true; notifySuccess = false; LoggerFactory.setLevel(Level.INFO); Level level = LoggerFactory.getLevel(); }

Target:
public void init() { URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":2233"); testUrl = URL.valueOf("<LINK_0>"); mockUrl = new URL("dubbo", "127.0.0.0", 2200); parametersConsumer.put("application", "demo-consumer"); parametersConsumer.put("category", "consumer"); parametersConsumer.put("check", "false"); parametersConsumer.put("dubbo", "2.0.2"); parametersConsumer.put("interface", "org.apache.dubbo.demo.DemoService"); parametersConsumer.put("methods", "sayHello"); parametersConsumer.put("pid", "1676"); parametersConsumer.put("qos.port", "333333"); parametersConsumer.put("side", "consumer"); parametersConsumer.put("timestamp", String.valueOf(System.currentTimeMillis())); abstractRegistry = new AbstractRegistry(url) { @Override public boolean isAvailable() { return false; } }; listener = urls -> notifySuccess = true; notifySuccess = false; }
Source:
public void run() { try { while (wrapper.isAlive) { if (wrapper.waitForReplay) { Thread.sleep(100); } if (!this.offsetToCommit.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("Commit offsets {}", Joiner.on(';').withKeyValueSeparator("=").join(this.offsetToCommit)); } consumer.commitAsync(offsetToCommit, wrapper.ownerOperator); offsetToCommit.clear(); } try { ConsumerRecords<byte[], byte[]> records = consumer.poll(wrapper.ownerOperator.getConsumerTimeout()); for (ConsumerRecord<byte[], byte[]> record : records) { wrapper.putMessage(Pair.of(cluster, record)); } } catch (NoOffsetForPartitionException e) { AbstractKafkaInputOperator.InitialOffset io = AbstractKafkaInputOperator.InitialOffset.valueOf(wrapper.ownerOperator.getInitialOffset()); if (io == AbstractKafkaInputOperator.InitialOffset.APPLICATION_OR_EARLIEST || io == AbstractKafkaInputOperator.InitialOffset.EARLIEST) { consumer.seekToBeginning(e.partitions().toArray(new TopicPartition[0])); } else { consumer.seekToEnd(e.partitions().toArray(new TopicPartition[0])); } } catch (InterruptedException e) { throw new IllegalStateException("Consumer thread is interrupted unexpectedly", e); } } } catch (WakeupException we) { logger.info("The consumer is being stopped"); } catch (InterruptedException e) { DTThrowable.rethrow(e); } finally { consumer.close(); } }

Target:
public void run() { try { while (wrapper.isAlive) { if (wrapper.waitForReplay) { Thread.sleep(100); continue; } if (!this.offsetToCommit.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("Commit offsets {}", Joiner.on(';').withKeyValueSeparator("=").join(this.offsetToCommit)); } consumer.commitAsync(offsetToCommit, wrapper.ownerOperator); offsetToCommit.clear(); } try { ConsumerRecords<byte[], byte[]> records = consumer.poll(wrapper.ownerOperator.getConsumerTimeout()); for (ConsumerRecord<byte[], byte[]> record : records) { wrapper.putMessage(Pair.of(cluster, record)); } } catch (NoOffsetForPartitionException e) { AbstractKafkaInputOperator.InitialOffset io = AbstractKafkaInputOperator.InitialOffset.valueOf(wrapper.ownerOperator.getInitialOffset()); if (io == AbstractKafkaInputOperator.InitialOffset.APPLICATION_OR_EARLIEST || io == AbstractKafkaInputOperator.InitialOffset.EARLIEST) { consumer.seekToBeginning(e.partitions().toArray(new TopicPartition[0])); } else { consumer.seekToEnd(e.partitions().toArray(new TopicPartition[0])); } } catch (InterruptedException e) { throw new IllegalStateException("Consumer thread is interrupted unexpectedly", e); } } } catch (WakeupException we) { logger.info("The consumer is being stopped"); } catch (InterruptedException e) { DTThrowable.rethrow(e); } finally { consumer.close(); } }
Source:
protected Set<String> getNextNames(final String group, final Template template, int count) { Set<String> names = newLinkedHashSet(); if (!template.getOptions().getNodeNames().isEmpty()) { if (template.getOptions().getNodeNames().size() == count) { return ImmutableSet.copyOf(template.getOptions().getNodeNames()); } else if (template.getOptions().getNodeNames().size() > count) { return ImmutableSet.copyOf(Iterables.limit(template.getOptions().getNodeNames(), count)); } else { names.addAll(template.getOptions().getNodeNames()); } } Iterable<? extends ComputeMetadata> currentNodes = listNodesStrategy.listNodes(); int maxTries = 100; int currentTries = 0; while (names.size() < count && currentTries++ < maxTries) { final String name = namingConvention.createWithoutPrefix().uniqueNameForGroup(group); if (!any(currentNodes, new Predicate<ComputeMetadata>() { @Override public boolean apply(ComputeMetadata input) { return name.equals(input.getName()); } })) { names.add(name); } } return names; }

Target:
protected Set<String> getNextNames(final String group, final Template template, int count) { Set<String> names = newLinkedHashSet(); Set<String> nodeNames = template.getOptions().getNodeNames(); if (nodeNames.size() >= count) { return ImmutableSet.copyOf(Iterables.limit(nodeNames, count)); } else { names.addAll(nodeNames); } Iterable<? extends ComputeMetadata> currentNodes = listNodesStrategy.listNodes(); int maxTries = 100; int currentTries = 0; while (names.size() < count && currentTries++ < maxTries) { final String name = namingConvention.createWithoutPrefix().uniqueNameForGroup(group); if (!any(currentNodes, new Predicate<ComputeMetadata>() { @Override public boolean apply(ComputeMetadata input) { return name.equals(input.getName()); } })) { names.add(name); } } return names; }
Source:
public int compareTo(final ITmfTimestamp ts, final boolean withinPrecision) { if (ts == null) { return 1; } if (this == ts || (fValue == ts.getValue() && fScale == ts.getScale())) { return 0; } if ((fValue == BIG_BANG.getValue() && fScale == BIG_BANG.getScale()) || (ts.getValue() == BIG_CRUNCH.getValue() && ts.getScale() == BIG_CRUNCH.getScale())) { return -1; } if ((fValue == BIG_CRUNCH.getValue() && fScale == BIG_CRUNCH.getScale()) || (ts.getValue() == BIG_BANG.getValue() && ts.getScale() == BIG_BANG.getScale())) { return 1; } try { final ITmfTimestamp nts = ts.normalize(0, fScale); final long delta = fValue - nts.getValue(); int imprecision = fPrecision + nts.getPrecision(); if (!(imprecision == 0 && delta != 0)) { if ((delta == 0) || (withinPrecision && (Math.abs(delta) <= imprecision))) { return 0; } } return (delta > 0) ? 1 : -1; } catch (final ArithmeticException e) { final long value = ts.getValue(); if (fValue == 0 && value == 0) { return 0; } if (fValue < 0 && value >= 0) { return -1; } if (fValue >= 0 && value < 0) { return 1; } final int scale = ts.getScale(); return (fScale > scale) ? (fValue >= 0) ? 1 : -1 : (fValue >= 0) ? -1 : 1; } }

Target:
public int compareTo(final ITmfTimestamp ts, final boolean withinPrecision) { if (ts == null) { return 1; } if (this == ts || (fValue == ts.getValue() && fScale == ts.getScale())) { return 0; } if ((fValue == BIG_BANG.getValue() && fScale == BIG_BANG.getScale()) || (ts.getValue() == BIG_CRUNCH.getValue() && ts.getScale() == BIG_CRUNCH.getScale())) { return -1; } if ((fValue == BIG_CRUNCH.getValue() && fScale == BIG_CRUNCH.getScale()) || (ts.getValue() == BIG_BANG.getValue() && ts.getScale() == BIG_BANG.getScale())) { return 1; } try { final ITmfTimestamp nts = ts.normalize(0, fScale); final long delta = fValue - nts.getValue(); if (delta == 0) { return 0; } if (withinPrecision) { int imprecision = fPrecision + nts.getPrecision(); if (imprecision == 0 || (Math.abs(delta) <= imprecision)) { return 0; } } return (delta > 0) ? 1 : -1; } catch (final ArithmeticException e) { final long value = ts.getValue(); if (fValue == 0 && value == 0) { return 0; } if (fValue < 0 && value >= 0) { return -1; } if (fValue >= 0 && value < 0) { return 1; } final int scale = ts.getScale(); return (fScale > scale) ? (fValue >= 0) ? 1 : -1 : (fValue >= 0) ? -1 : 1; } }
Source:
public Map<ProjectVersionRef, String> translateVersions(List<ProjectVersionRef> projects) { final Map<ProjectVersionRef, String> result = new HashMap<>(); logger.debug("Translating versions: " + projects); final Queue<Task> queue = new ArrayDeque<>(); queue.add(new Task(projects, chunkSplitCount, endpointUrl)); while (!queue.isEmpty()) { Task task = queue.remove(); task.executeTranslate(); if (task.isSuccess()) { result.putAll(task.getResult()); } else { if (task.canSplit()) { logger.debug("Failed to translate versions, splitting and retrying. " + "Chunk size is " + task.getChunkSize()); queue.addAll(task.split()); } else { if (task.getStatus() > 0) throw new RestException("Cannot split and retry anymore. Last status was " + task.getStatus()); else throw new RestException("Cannot split and retry anymore. Cause: " + task.getException(), task.getException()); } } } return result; }

Target:
public Map<ProjectVersionRef, String> translateVersions( List<ProjectVersionRef> projects ) { final Map<ProjectVersionRef, String> result = new HashMap<>(); logger.debug( "Translating versions: " + projects ); final Queue<Task> queue = new ArrayDeque<>(); queue.add( new Task( projects, chunkSplitCount, endpointUrl ) ); while ( !queue.isEmpty() ) { Task task = queue.remove(); task.executeTranslate(); if ( task.isSuccess() ) { result.putAll( task.getResult() ); } else { if ( task.canSplit() ) { List<Task> tasks = task.split(); logger.debug( "Failed to translate versions, splitting and retrying. " + "Chunk was: " + task + ", new chunks are: " + tasks ); queue.addAll( tasks ); } else { if ( task.getStatus() > 0 ) throw new RestException( "Cannot split and retry anymore. Last status was " + task.getStatus() ); else throw new RestException( "Cannot split and retry anymore. Cause: " + task.getException(), task.getException() ); } } } return result; }
Source:
public RevCommit call() throws GitAPIException { RevCommit newHead = null; checkCallable(); RevWalk revWalk = new RevWalk(repo); try { Ref headRef = repo.getRef(Constants.HEAD); if (headRef == null) throw new NoHeadException( JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported); RevCommit headCommit = revWalk.lookupCommit(headRef.getObjectId()); for (Ref src : commits) { ObjectId srcObjectId = src.getPeeledObjectId(); if (srcObjectId == null) srcObjectId = src.getObjectId(); RevCommit srcCommit = revWalk.parseCommit(srcObjectId); if (srcCommit.getParentCount() != 1) { throw new InvalidCherryPickCommit( JGitText.get().canOnlyCherryPickCommitsWithOneParent); } RevCommit srcParent = revWalk.parseCommit(srcCommit .getParent(0)); ResolveMerger merger = (ResolveMerger) MergeStrategy.RESOLVE .newMerger(repo); merger.setWorkingTreeIterator(new FileTreeIterator(repo)); merger.setBase(srcParent.getTree()); if (merger.merge(headCommit, srcCommit)) { DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.getTree(), repo.lockDirCache(), merger.getResultTreeId()); dco.setFailOnConflict(true); dco.checkout(); newHead = new Git(getRepository()).commit() .setMessage(srcCommit.getFullMessage()) .setAuthor(srcCommit.getAuthorIdent()).call(); cherryPickedRefs.add(src); } else { return null; } } } catch (IOException e) { throw new JGitInternalException( MessageFormat.format( JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand, e), e); } finally { revWalk.release(); } return newHead; }

Target:
public RevCommit call() throws GitAPIException { RevCommit newHead = null; checkCallable(); RevWalk revWalk = new RevWalk(repo); try { Ref headRef = repo.getRef(Constants.HEAD); if (headRef == null) throw new NoHeadException( JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported); RevCommit headCommit = revWalk.parseCommit(headRef.getObjectId()); for (Ref src : commits) { ObjectId srcObjectId = src.getPeeledObjectId(); if (srcObjectId == null) srcObjectId = src.getObjectId(); RevCommit srcCommit = revWalk.parseCommit(srcObjectId); if (srcCommit.getParentCount() != 1) { throw new MultipleParentsNotAllowedException( JGitText.get().canOnlyCherryPickCommitsWithOneParent); } RevCommit srcParent = srcCommit.getParent(0); revWalk.parseHeaders(srcParent); ResolveMerger merger = (ResolveMerger) MergeStrategy.RESOLVE .newMerger(repo); merger.setWorkingTreeIterator(new FileTreeIterator(repo)); merger.setBase(srcParent.getTree()); if (merger.merge(headCommit, srcCommit)) { DirCacheCheckout dco = new DirCacheCheckout(repo, headCommit.getTree(), repo.lockDirCache(), merger.getResultTreeId()); dco.setFailOnConflict(true); dco.checkout(); newHead = new Git(getRepository()).commit() .setMessage(srcCommit.getFullMessage()) .setAuthor(srcCommit.getAuthorIdent()).call(); cherryPickedRefs.add(src); } else { return null; } } } catch (IOException e) { throw new JGitInternalException( MessageFormat.format( JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand, e), e); } finally { revWalk.release(); } return newHead; }
Source:
public void test() { final String contig = "chr1"; final int spacing = 100000; final double contamination = 0.05; final double alleleFrequency = 0.2; final int depth = 100; final List<PileupSummary> ps = new ArrayList<>(); for (int n = 0; n < 1000; n++) { int position = n * spacing; ps.add(n % 10 == 0 ? new PileupSummary(contig, position, (int) (depth*contamination), (int) (depth * (1 - contamination)), 0, alleleFrequency) : new PileupSummary(contig, position, depth / 2, depth/2, 1, alleleFrequency)); } for (int n = 1000; n < 1100; n++) { int position = n * spacing; ps.add(n % 10 == 0 ? new PileupSummary(contig, position, (int) (depth*contamination), (int) (depth * (1 - contamination)), 0, alleleFrequency) : new PileupSummary(contig, position, (int) 0.2 * depth, (int) (0.8 * depth), 1, alleleFrequency)); } final File psTable = createTempFile("pileups", ".table"); PileupSummary.writePileupSummaries(ps, psTable); final File contaminationTable = createTempFile("contamination", ".table"); final String[] args = { "-I", psTable.getAbsolutePath(), "-O", contaminationTable.getAbsolutePath(), }; runCommandLine(args); final double calculatedContamination = ContaminationRecord.readContaminationTable(contaminationTable).get(0).getContamination(); Assert.assertEquals(calculatedContamination, 0.05 / (1 - alleleFrequency), 0.01); }

Target:
public void test() { final String contig = "chr1"; final int spacing = 100000; final double contamination = 0.07; final double alleleFrequency = 0.2; final double refContamination = contamination * (1 - alleleFrequency); final int depth = 100; final List<PileupSummary> ps = new ArrayList<>(); for (int n = 0; n < 1000; n++) { int position = n * spacing; ps.add(n % 10 == 0 ? new PileupSummary(contig, position, (int) (depth*refContamination), (int) (depth * (1 - refContamination)), 0, alleleFrequency) : new PileupSummary(contig, position, depth / 2, depth/2, 1, alleleFrequency)); } for (int n = 1000; n < 1100; n++) { int position = n * spacing; ps.add(n % 10 == 0 ? new PileupSummary(contig, position, (int) (depth*refContamination), (int) (depth * (1 - refContamination)), 0, alleleFrequency) : new PileupSummary(contig, position, (int) 0.2 * depth, (int) (0.8 * depth), 1, alleleFrequency)); } final File psTable = createTempFile("pileups", ".table"); PileupSummary.writePileupSummaries(ps, psTable); final File contaminationTable = createTempFile("contamination", ".table"); final String[] args = { "-I", psTable.getAbsolutePath(), "-O", contaminationTable.getAbsolutePath(), }; runCommandLine(args); final double calculatedContamination = ContaminationRecord.readContaminationTable(contaminationTable).get(0).getContamination(); Assert.assertEquals(calculatedContamination, contamination, 0.01); }
Source:
public AsyncRequestResponseHandler getHandler() { int index = currIndex.getAndIncrement(); logger.trace("Monotonically increasing value was used to pick request handler at index {}", index, index % requestResponseHandlers.size()); return requestResponseHandlers.get(index % requestResponseHandlers.size()); }

Target:
public AsyncRequestResponseHandler getHandler() { int index = currIndex.getAndIncrement(); logger.trace("Monotonically increasing value was used to pick request handler at index {}", index, index % asyncRequestResponseHandlers.size()); return asyncRequestResponseHandlers.get(index % asyncRequestResponseHandlers.size()); }
Source:
Snapshot.Root chooseDeletedSnapshot() { final List<INodeDirectory> dirs = getSnapshottableDirs(); Collections.shuffle(dirs); for(INodeDirectory dir : dirs) { final Snapshot.Root root = chooseDeletedSnapshot(dir); if (root != null) { return root; } } return null; }

Target:
Snapshot.Root chooseDeletedSnapshot() { for(INodeDirectory dir : getSnapshottableDirsForGc()) { final Snapshot.Root root = chooseDeletedSnapshot(dir); if (root != null) { return root; } } return null; }
Source:
public FileSystemViewKeyInputFormat(FileSystemDataset<E> dataset, Configuration conf) { this.dataset = dataset; LOG.debug("Dataset: {}", dataset); Format format = dataset.getDescriptor().getFormat(); boolean isSpecific = SpecificRecord.class.isAssignableFrom(dataset.getType()); String readerSchema = conf.get("kite.readerSchema"); if (isSpecific && readerSchema == null) { readerSchema = SpecificData.get().getSchema(dataset.getType()).toString(); } if (Formats.AVRO.equals(format)) { setModel.invoke(conf, DataModelUtil.getDataModelForType(dataset.getType()).getClass()); if (readerSchema != null) { conf.set(AVRO_SCHEMA_INPUT_KEY, readerSchema); } } else if (Formats.PARQUET.equals(format)) { if (readerSchema != null) { AvroReadSupport.setAvroReadSchema(conf, new Schema.Parser().parse(readerSchema)); } } }

Target:
public FileSystemViewKeyInputFormat(FileSystemDataset<E> dataset, Configuration conf) { this.dataset = dataset; LOG.debug("Dataset: {}", dataset); Format format = dataset.getDescriptor().getFormat(); boolean isSpecific = SpecificRecord.class.isAssignableFrom(dataset.getType()); String readerSchema = conf.get(KITE_READER_SCHEMA); Preconditions.checkState(!isSpecific || readerSchema == null, "Illegal configuration: must not be set if dataset uses a specific type {}", KITE_READER_SCHEMA, dataset.getType()); if (isSpecific) { readerSchema = SpecificData.get().getSchema(dataset.getType()).toString(); } if (Formats.AVRO.equals(format)) { setModel.invoke(conf, DataModelUtil.getDataModelForType(dataset.getType()).getClass()); if (readerSchema != null) { conf.set(AVRO_SCHEMA_INPUT_KEY, readerSchema); } } else if (Formats.PARQUET.equals(format)) { if (readerSchema != null) { AvroReadSupport.setAvroReadSchema(conf, new Schema.Parser().parse(readerSchema)); } } }
Source:
public static GlobalMetricRegistriesAdapter getInstance() { if (INSTANCE == null) { INSTANCE = new GlobalMetricRegistriesAdapter(); } return INSTANCE; }

Target:
public static GlobalMetricRegistriesAdapter getInstance() { return INSTANCE; }
Source:
public void call_shouldNotMarkTransactionSuccessful_ifOptionSet_Fails() throws Exception { when(optionSetCall.execute()).thenReturn(errorResponse); Response response = metadataCall.call(); assertThat(response).isEqualTo(errorResponse); assertThat(response.code()).isEqualTo(HttpURLConnection.HTTP_CLIENT_TIMEOUT); verify(databaseAdapter, times(6)).beginNewTransaction(); verify(transaction, times(6)).end(); verify(transaction, atMost(5)).setSuccessful(); }

Target:
public void call_shouldNotMarkTransactionSuccessful_ifOptionSet_Fails() throws Exception { final int expectedTransactions = 6; when(optionSetCall.execute()).thenReturn(errorResponse); Response response = metadataCall.call(); assertThat(response).isEqualTo(errorResponse); assertThat(response.code()).isEqualTo(HttpURLConnection.HTTP_CLIENT_TIMEOUT); verify(databaseAdapter, times(expectedTransactions)).beginNewTransaction(); verify(transaction, times(expectedTransactions)).end(); verify(transaction, atMost(expectedTransactions - 1)).setSuccessful(); }
Source:
private <T extends Serializable> void sendMessageToLocalRegionSync(final T body) throws IOException { if ( sqs == null ) { logger.error( "SQS client is null, perhaps it failed to initialize successfully" ); return; } final String stringBody = toString( body ); if (logger.isDebugEnabled()) { logger.debug(" sendMessageToLocalRegion " + stringBody); } String url = getReadQueue().getUrl(); if ( logger.isTraceEnabled() ) { logger.trace( "Publishing Message...{} to url: {}", stringBody, url ); } SendMessageRequest messageRequest = new SendMessageRequest(url, stringBody); try { SendMessageResult result = sqs.sendMessage(messageRequest); if (logger.isTraceEnabled()) { logger.trace("Successfully published... messageID=[{}], arn=[{}]", result.getMessageId(), url); } } catch (Exception e) { logger.error("Failed to send this message {}. To this address {}. Error was ", messageRequest.getMessageBody(), url, e); sendMessageToLocalRegionAsync(body); } }

Target:
private <T extends Serializable> void sendMessageToLocalRegionSync(final T body) throws IOException { if ( sqs == null ) { logger.error( "SQS client is null, perhaps it failed to initialize successfully" ); return; } final String stringBody = toString( body ); if (logger.isDebugEnabled()) { logger.debug(" sendMessageToLocalRegion " + stringBody); } String url = getReadQueue().getUrl(); if ( logger.isTraceEnabled() ) { logger.trace( "Publishing Message...{} to url: {}", stringBody, url ); } SendMessageRequest messageRequest = new SendMessageRequest(url, stringBody); try { SendMessageResult result = sqs.sendMessage(messageRequest); if (logger.isTraceEnabled()) { logger.trace("Successfully published... messageID=[{}], arn=[{}]", result.getMessageId(), url); } } catch (Exception e) { logger.error(FAILED_TO_SEND_MESSAGE, messageRequest.getMessageBody(), url, e); sendMessageToLocalRegionAsync(body); } }
Source:
private static FunctionTree functionTree(CallExpressionTree tree, ProgramState currentState) { if (tree.callee().is(Kind.IDENTIFIER_REFERENCE)) { Symbol symbol = ((IdentifierTree) tree.callee()).symbol(); if (symbol != null) { SymbolicValue symbolicValue = currentState.getSymbolicValue(symbol); if (symbolicValue instanceof FunctionSymbolicValue) { return ((FunctionSymbolicValue) symbolicValue).getFunctionTree(); } } } return null; }

Target:
private static FunctionTree functionTree(CallExpressionTree tree, ProgramState currentState) { SymbolicValue calleeSV = currentState.peekStack(tree.arguments().parameters().size()); if (calleeSV instanceof FunctionSymbolicValue) { return ((FunctionSymbolicValue) calleeSV).getFunctionTree(); } return null; }
Source:
public void testPendingMutationsOnDDL() throws Exception { Connection conn = null; PhoenixConnection spy = null; try { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); props.setProperty(QueryServices.PENDING_MUTATIONS_DDL_THROW_ATTRIB, "true"); conn = DriverManager.getConnection(getUrl(), props); MutationState mutationState = mock(MutationState.class); when(mutationState.getNumRows()).thenReturn(1); spy = spy((PhoenixConnection) conn); doReturn(mutationState).when(spy).getMutationState(); spy.createStatement().execute("create table MUTATION_TEST1" + "( id1 UNSIGNED_INT not null primary key," + "appId1 VARCHAR)"); } finally { if (spy != null) { spy.close(); } } }

Target:
public void testPendingMutationsOnDDL() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); props.setProperty(QueryServices.PENDING_MUTATIONS_DDL_THROW_ATTRIB, "true"); try (Connection conn = DriverManager.getConnection(getUrl(), props); PhoenixConnection pConnSpy = spy((PhoenixConnection) conn)) { MutationState mutationState = mock(MutationState.class); when(mutationState.getNumRows()).thenReturn(1); doReturn(mutationState).when(pConnSpy).getMutationState(); exceptionRule.expect(SQLException.class); exceptionRule.expectMessage( SQLExceptionCode.CANNOT_PERFORM_DDL_WITH_PENDING_MUTATIONS.getMessage()); pConnSpy.createStatement().execute("create table MUTATION_TEST1" + "( id1 UNSIGNED_INT not null primary key," + "appId1 VARCHAR)"); } }
Source:
public boolean isInDiskCacheSync(final ImageRequest imageRequest) { final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest, null); final ImageRequest.CacheChoice cacheChoice = imageRequest.getCacheChoice(); if (cacheChoice == ImageRequest.CacheChoice.SMALL) { return mSmallImageBufferedDiskCache.diskCheckSync(cacheKey); } else { return mMainBufferedDiskCache.diskCheckSync(cacheKey); } }

Target:
public boolean isInDiskCacheSync(final ImageRequest imageRequest) { final CacheKey cacheKey = mCacheKeyFactory.getEncodedCacheKey(imageRequest, null); final ImageRequest.CacheChoice cacheChoice = imageRequest.getCacheChoice(); switch (cacheChoice) { case DEFAULT: return mMainBufferedDiskCache.diskCheckSync(cacheKey); case SMALL: return mSmallImageBufferedDiskCache.diskCheckSync(cacheKey); default: return false; } }
Source:
public static String getVideoPressVideoPosterFromURL(String videoUrl) { return videoUrl.substring(0, videoUrl.lastIndexOf(".")) + "_std.original.jpg"; }

Target:
public static String getVideoPressVideoPosterFromURL(String videoUrl) { String posterUrl = ""; if (videoUrl != null) { int filetypeLocation = videoUrl.lastIndexOf("."); if (filetypeLocation > 0) { posterUrl = videoUrl.substring(0, filetypeLocation) + "_std.original.jpg"; } } return posterUrl; }