auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean validateWebhook(String receivedSignature, String payload) { StringCredentials webhookSecret = CredentialsProvider.findCredentialById(step.webhookSecretId, StringCredentials.class, getContextClass(Run.class)); CredentialsProvider.track(getContextClass(Run.class), webhookSecret); if (webhookSecret != null) { boolean isValidPayload = isValidSignature(receivedSignature, payload, webhookSecret.getSecret().getPlainText()); if (!isValidPayload) { log("The incoming webhook was verified using the configured webhook secret and was found to be invalid"); getContext().onFailure(new AbortException("Pipeline aborted due to failed webhook verification ")); } else { log("The incoming webhook was verified using the configured webhook secret and was found to be valid"); } return isValidPayload; } else { log("A webhook secret id was configured, but the corresponding credential could not be found"); getContext().onFailure(new AbortException("Pipeline aborted due to failed webhook verification")); return false; } }

Target:
private boolean validateWebhook(String receivedSignature, String payload) { StringCredentials webhookSecret = CredentialsProvider.findCredentialById(step.webhookSecretId, StringCredentials.class, getContextClass(Run.class)); CredentialsProvider.track(getContextClass(Run.class), webhookSecret); if (webhookSecret != null) { boolean isValidPayload = isValidSignature(receivedSignature, payload, webhookSecret.getSecret().getPlainText()); if (!isValidPayload) { log("The incoming webhook didn't match the configured webhook secret"); getContext().onFailure(new AbortException("Pipeline aborted due to failed webhook verification ")); } else { log("The incoming webhook matched the configured webhook secret"); } return isValidPayload; } else if (step.webhookSecretId != null && !step.webhookSecretId.isEmpty()) { log("A webhook secret id was configured, but the corresponding credential could not be found"); getContext().onFailure(new AbortException("Pipeline aborted due to failed webhook verification")); return false; } return true; }
Source:
public void handle(Request wsRequest, Response wsResponse) throws Exception { String query = wsRequest.param(PARAM_QUERY); String more = wsRequest.param(PARAM_MORE); List<String> recentlyBrowsedParam = wsRequest.paramAsStrings(PARAM_RECENTLY_BROWSED); Set<String> recentlyBrowsedKeys; if (recentlyBrowsedParam == null) { recentlyBrowsedKeys = emptySet(); } else { recentlyBrowsedKeys = recentlyBrowsedParam.stream().limit(MAXIMUM_RECENTLY_BROWSED).collect(Collectors.toSet()); } Set<String> favoriteKeys = favoriteFinder.list().stream().map(ComponentDto::getKey).collect(Collectors.toSet()); List<String> qualifiers = getQualifiers(more); SuggestionsWsResponse searchWsResponse; if (query == null) { searchWsResponse = suggestionsWithoutSearch(more, recentlyBrowsedKeys, favoriteKeys, qualifiers); } else { searchWsResponse = suggestionsFromSearch(query, more, recentlyBrowsedKeys, favoriteKeys, qualifiers); } writeProtobuf(searchWsResponse, wsRequest, wsResponse); }

Target:
public void handle(Request wsRequest, Response wsResponse) throws Exception { String query = wsRequest.param(PARAM_QUERY); String more = wsRequest.param(PARAM_MORE); Set<String> recentlyBrowsedKeys = getRecentlyBrowsedKeys(wsRequest); List<String> qualifiers = getQualifiers(more); int skip = more == null ? 0 : DEFAULT_LIMIT; int limit = more == null ? DEFAULT_LIMIT : EXTENDED_LIMIT; SuggestionsWsResponse searchWsResponse = loadSuggestions(query, skip, limit, recentlyBrowsedKeys, qualifiers); writeProtobuf(searchWsResponse, wsRequest, wsResponse); }
Source:
public ByteBuffer encrypt(byte[] input, int offset, int len){ try{ if(type == CryptByteBufferType.RijndaelPCFB){ return ByteBuffer.wrap(encryptPCFB.blockEncipher(input, offset, len)); } else if(type.cipherName == "RIJNDAEL"){ byte[] result = new byte[len]; blockCipher.encipher(extractSmallerArray(input, offset, len), result); return ByteBuffer.wrap(result); } else{ return ByteBuffer.wrap(encryptCipher.doFinal(input, offset, len)); } } catch (GeneralSecurityException e) { e.printStackTrace(); Logger.error(CryptByteBuffer.class, "Internal error; please report:", e); } return null; }

Target:
public ByteBuffer encrypt(byte[] input, int offset, int len){ try{ if(type == CryptByteBufferType.RijndaelPCFB){ return ByteBuffer.wrap(encryptPCFB.blockEncipher(input, offset, len)); } else if(type.cipherName.equals("RIJNDAEL")){ byte[] result = new byte[len]; blockCipher.encipher(extractSmallerArray(input, offset, len), result); return ByteBuffer.wrap(result); } else{ return ByteBuffer.wrap(encryptCipher.doFinal(input, offset, len)); } } catch (GeneralSecurityException e) { e.printStackTrace(); Logger.error(CryptByteBuffer.class, "Internal error; please report:", e); } return null; }
Source:
public Node<View<Decision>, ?> nodeFromDMN(final org.kie.dmn.model.api.Decision dmn) { @SuppressWarnings("unchecked") Node<View<Decision>, ?> node = (Node<View<Decision>, ?>) factoryManager.newElement(dmn.getId(), Decision.class).asNode(); Id id = new Id(dmn.getId()); Description description = DescriptionPropertyConverter.wbFromDMN(dmn.getDescription()); Name name = new Name(dmn.getName()); InformationItem informationItem = InformationItemPropertyConverter.wbFromDMN(dmn.getVariable()); Expression expression = ExpressionPropertyConverter.wbFromDMN(dmn.getExpression()); Decision decision = new Decision(id, description, name, new Question(), new AllowedAnswers(), informationItem, expression, new BackgroundSet(), new FontSet(), new RectangleDimensionsSet()); decision.setQuestion(new Question(dmn.getQuestion())); decision.setAllowedAnswers(new AllowedAnswers(dmn.getAllowedAnswers())); node.getContent().setDefinition(decision); if (informationItem != null) { informationItem.setParent(decision); } if (expression != null) { expression.setParent(decision); } return node; }

Target:
public Node<View<Decision>, ?> nodeFromDMN(final org.kie.dmn.model.api.Decision dmn) { @SuppressWarnings("unchecked") Node<View<Decision>, ?> node = (Node<View<Decision>, ?>) factoryManager.newElement(dmn.getId(), Decision.class).asNode(); Id id = new Id(dmn.getId()); Description description = DescriptionPropertyConverter.wbFromDMN(dmn.getDescription()); Name name = new Name(dmn.getName()); InformationItem informationItem = InformationItemPropertyConverter.wbFromDMN(dmn.getVariable()); Expression expression = ExpressionPropertyConverter.wbFromDMN(dmn.getExpression()); Decision decision = new Decision(id, description, name, new Question(), new AllowedAnswers(), informationItem, expression, new BackgroundSet(), new FontSet(), new RectangleDimensionsSet()); decision.setQuestion(QuestionPropertyConverter.wbFromDMN(dmn.getQuestion())); decision.setAllowedAnswers(AllowedAnswersPropertyConverter.wbFromDMN(dmn.getAllowedAnswers())); node.getContent().setDefinition(decision); if (informationItem != null) { informationItem.setParent(decision); } if (expression != null) { expression.setParent(decision); } return node; }
Source:
public void onMessage(Message message) { try { URLNotification notification = URLNotificationJSONConverter.parseJSON(new ByteArrayInputStream(message.getData())); receiveNotification(notification); if (!exceptionThrown || updateSequenceAfterException) { sequence = message.getSequence(); trackingFile.write( Json.createObjectBuilder() .add(NATSClient.SERVER_HOST_PROPERTY,client.getServerHost()) .add(NATSClient.SERVER_PORT_PROPERTY,client.getServerPort()) .add(NATSClient.CLUSTER_ID_PROPERTY,client.getClusterId()) .add(NATSClient.CLIENT_ID_PROPERTY,client.getClientId()) .add(NATSClient.SUBJECT_PROPERTY,subject) .add(SEQUENCE_PROPERTY,sequence) .build() ); } } catch (Exception e) { exceptionThrown = true; LOGGER.log(Level.WARNING, "[" + getName() + "] exception handling NATSStreaming message." + (!updateSequenceAfterException ? " Will no longer update sequence; restart PDL to reprocess.":"") + " Stack Trace: " + e); LOGGER.log(Level.FINE, "[" + getName() + "] Message: " + message.getData()); } }

Target:
public void onMessage(Message message) { try { URLNotification notification = URLNotificationJSONConverter.parseJSON(new ByteArrayInputStream(message.getData())); receiveNotification(notification); if (!exceptionThrown || updateSequenceAfterException) { sequence = message.getSequence(); writeTrackingFile(); } } catch (Exception e) { exceptionThrown = true; LOGGER.log(Level.WARNING, "[" + getName() + "] exception handling NATSStreaming message." + (!updateSequenceAfterException ? " Will no longer update sequence; restart PDL to reprocess.":"") + " Stack Trace: " + e); LOGGER.log(Level.FINE, "[" + getName() + "] Message: " + message.getData()); } }
Source:
public Config.ExporterStatus getSynapseExporterStatus() { return this.synapseExporterStatus; }

Target:
public ExporterStatus getSynapseExporterStatus() { return this.synapseExporterStatus; }
Source:
private void processHealthcheck(ServiceEvent event) { String[] splitted = event.getHealthcheckUuid().split("_"); HealthcheckInstanceHostMap hostMap = null; String uuid = null; if (splitted.length > 2) { hostMap = serviceDao.getHealthCheckInstanceUUID(splitted[0], splitted[1]); if (hostMap != null) { uuid = hostMap.getUuid(); } } else { uuid = splitted[0]; } if (uuid != null && event.getExternalTimestamp() != null) { healthcheckService.updateHealthcheck(uuid, event.getExternalTimestamp(), getHealthState(event.getReportedHealth())); } }

Target:
private void processHealthcheck(ServiceEvent event) { String[] splitted = event.getHealthcheckUuid().split("_"); HealthcheckInstanceHostMap hostMap = null; String uuid = null; if (splitted.length > 2) { hostMap = serviceDao.getHealthCheckInstanceUUID(splitted[0], splitted[1]); if (hostMap != null) { uuid = hostMap.getUuid(); } } else { uuid = splitted[0]; } if (uuid != null) { if(event.getExternalTimestamp() == null) { log.warn("ExternalTimestamp null for event hostMapUUID {}", event.getId(), uuid); return; } healthcheckService.updateHealthcheck(uuid, event.getExternalTimestamp(), getHealthState(event.getReportedHealth())); } }
Source:
public Object getAndReplace(Data key, Object value, ExpiryPolicy expiryPolicy, UUID source, int completionId) { long now = Clock.currentTimeMillis(); long startNano = isStatisticsEnabled() ? timer.nanos() : 0; boolean replaced = false; R record = records.get(key); expiryPolicy = getExpiryPolicy(record, expiryPolicy); boolean isExpired = record != null && record.isExpiredAt(now); try { Object obj = toValue(record); if (recordNotExistOrExpired(record, isExpired)) { obj = null; if (isEventsEnabled()) { publishEvent(createCacheCompleteEvent(toEventData(key), completionId)); } } else { replaced = updateRecordWithExpiry(key, value, record, expiryPolicy, now, false, completionId, source); } onReplace(key, null, value, expiryPolicy, source, false, record, isExpired, replaced); if (isStatisticsEnabled()) { statistics.addGetTimeNanos(timer.nanosElapsedSince(startNano)); if (obj != null) { statistics.increaseCacheHits(1); statistics.increaseCachePuts(1); statistics.addPutTimeNanos(timer.nanosElapsedSince(startNano)); } else { statistics.increaseCacheMisses(1); } } return obj; } catch (Throwable error) { onReplaceError(key, null, value, expiryPolicy, source, false, record, isExpired, replaced, error); throw ExceptionUtil.rethrow(error); } }

Target:
public Object getAndReplace(Data key, Object value, ExpiryPolicy expiryPolicy, UUID source, int completionId) { long now = Clock.currentTimeMillis(); long startNanos = isStatisticsEnabled() ? Timer.nanos() : 0; boolean replaced = false; R record = records.get(key); expiryPolicy = getExpiryPolicy(record, expiryPolicy); boolean isExpired = record != null && record.isExpiredAt(now); try { Object obj = toValue(record); if (recordNotExistOrExpired(record, isExpired)) { obj = null; if (isEventsEnabled()) { publishEvent(createCacheCompleteEvent(toEventData(key), completionId)); } } else { replaced = updateRecordWithExpiry(key, value, record, expiryPolicy, now, false, completionId, source); } onReplace(key, null, value, expiryPolicy, source, false, record, isExpired, replaced); if (isStatisticsEnabled()) { statistics.addGetTimeNanos(Timer.nanosElapsed(startNanos)); if (obj != null) { statistics.increaseCacheHits(1); statistics.increaseCachePuts(1); statistics.addPutTimeNanos(Timer.nanosElapsed(startNanos)); } else { statistics.increaseCacheMisses(1); } } return obj; } catch (Throwable error) { onReplaceError(key, null, value, expiryPolicy, source, false, record, isExpired, replaced, error); throw ExceptionUtil.rethrow(error); } }
Source:
public List<StreamsDatum> process(StreamsDatum entry) { StreamsDatum result = null; try { Object item = entry.getDocument(); ObjectNode node; LOGGER.debug("{} processing {}", STREAMS_ID, item.getClass()); if( item instanceof String ) { if( String.class.equals(outClass)) { result = entry; } else { node = (ObjectNode)mapper.readTree((String)item); Class inClass = TwitterEventClassifier.detectClass((String) item); Object out = convert(node, inClass, outClass); if( out != null && validate(out, outClass)) result = new StreamsDatum(out); } } else if( item instanceof ObjectNode ) { node = (ObjectNode)mapper.valueToTree(item); Class inClass = TwitterEventClassifier.detectClass(item.toString()); Object out = convert(node, inClass, outClass); if( out != null && validate(out, outClass)) result = new StreamsDatum(out); } } catch (Exception e) { e.printStackTrace(); } if( result != null ) return Lists.newArrayList(result); else return Lists.newArrayList(); }

Target:
public List<StreamsDatum> process(StreamsDatum entry) { StreamsDatum result = null; try { Object item = entry.getDocument(); ObjectNode node; LOGGER.debug("{} processing {}", STREAMS_ID, item.getClass()); if( item instanceof String ) { if( String.class.equals(outClass)) { result = entry; } else { node = (ObjectNode)mapper.readTree((String)item); Class inClass = TwitterEventClassifier.detectClass((String) item); Object out = convert(node, inClass, outClass); if( out != null && validate(out, outClass)) result = new StreamsDatum(out); } } else if( item instanceof ObjectNode ) { node = (ObjectNode)mapper.valueToTree(item); Class inClass = TwitterEventClassifier.detectClass(mapper.writeValueAsString(item)); Object out = convert(node, inClass, outClass); if( out != null && validate(out, outClass)) result = new StreamsDatum(out); } } catch (Exception e) { e.printStackTrace(); } if( result != null ) return Lists.newArrayList(result); else return Lists.newArrayList(); }
Source:
private static VertxOptions configureVertx(ClusterManager clusterManager) { VertxOptions options = new VertxOptions() .setClustered(true) .setClusterHost("192.168.1.56") .setClusterPort(17001) .setClusterManager(clusterManager); return options; }

Target:
private static VertxOptions configureVertx(ClusterManager clusterManager) { VertxOptions options = new VertxOptions() .setClustered(true) .setClusterManager(clusterManager); return options; }
Source:
public static Channel createChannel(final TransportOptions transportOptions, final ChannelOptions channelOptions, final ExecutorService executor, boolean createPool) { Preconditions.checkArgument( transportOptions.getTransport() == TransportOptions.BigtableTransports.HTTP2_NETTY_TLS, "Bigtable requires the NETTY_TLS transport."); int channelCount = createPool ? channelOptions.getChannelCount() : 1; long timeoutMs = channelOptions.getTimeoutMs(); Channel channels[] = new Channel[channelCount]; for (int i = 0; i < channelCount; i++) { ReconnectingChannel reconnectingChannel = createReconnectingChannel(transportOptions, executor, timeoutMs); channelOptions.addClientCloseHandler(reconnectingChannel); channels[i] = reconnectingChannel; } Channel channel = new ChannelPool(channels); return wrapChannel(channelOptions, executor, channel); }

Target:
public static CloseableChannel createChannel(final TransportOptions transportOptions, final ChannelOptions channelOptions, final ExecutorService executor, boolean createPool) { Preconditions.checkArgument( transportOptions.getTransport() == TransportOptions.BigtableTransports.HTTP2_NETTY_TLS, "Bigtable requires the NETTY_TLS transport."); int channelCount = channelOptions.getChannelCount(); long timeoutMs = channelOptions.getTimeoutMs(); CloseableChannel channel = null; if (channelCount > 1 && createPool) { CloseableChannel channels[] = new CloseableChannel[channelCount]; for (int i = 0; i < channelCount; i++) { CloseableChannel channelImpl = createRefreshingChannel(transportOptions, executor, timeoutMs); channels[i] = channelImpl; } CloseableChannel pooledChannel = new ChannelPool(channels); channel = pooledChannel; } else { channel = createRefreshingChannel(transportOptions, executor, timeoutMs); } return wrapChannel(channelOptions, executor, channel, createChannelClose(channel)); }
Source:
public void testInterpolationNoDataEdges() { int width = 2; int height = 2; SampleModel sm = new ComponentSampleModel(DataBuffer.TYPE_BYTE, width, height, 1, 2, new int[] {0}); TiledImage source = new TiledImage(0, 0, width, height, 0, 0, sm, PlanarImage.createColorModel(sm)); int noDataValue = 1; source.setSample(0, 0, 0, 255); source.setSample(0, 1, 0, 64); source.setSample(1, 0, 0, 32); source.setSample(1, 1, 0, noDataValue); RenderingHints hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER,BorderExtender.createInstance(BorderExtender.BORDER_COPY)); RenderedImage scaled = ScaleDescriptor.create(source, 32f, 32f, 0f, 0f, Interpolation.getInstance(Interpolation.INTERP_BILINEAR), null, null, RangeFactory.create(noDataValue, noDataValue), null, hints); Raster raster = scaled.getData(); int minX = raster.getMinX(); int minY = raster.getMinY(); int maxX = minX + raster.getWidth(); int maxY = minY + raster.getHeight(); int halfX = (minX + maxX) / 2; int halfY = (minY + maxY) / 2; for (int i = minY; i < maxY; i++) { for (int j = minX; j < maxX; j++) { int value = raster.getSample(j, i, 0); if (i > halfY && j > halfX) { assertTrue("Expected noData value but found different value", value == noDataValue); } else { assertTrue("Expected valid value but found nodata", value > 0); } } } }

Target:
public void testInterpolationNoDataEdges() { int width = 2; int height = 2; SampleModel sm = new ComponentSampleModel(DataBuffer.TYPE_BYTE, width, height, 1, 2, new int[] {0}); TiledImage source = new TiledImage(0, 0, width, height, 0, 0, sm, PlanarImage.createColorModel(sm)); int noDataValue = 1; source.setSample(0, 0, 0, 255); source.setSample(0, 1, 0, 64); source.setSample(1, 0, 0, 32); source.setSample(1, 1, 0, noDataValue); RenderingHints hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER,BorderExtender.createInstance(BorderExtender.BORDER_COPY)); RenderedImage scaled = ScaleDescriptor.create(source, 32f, 32f, 0f, 0f, Interpolation.getInstance(Interpolation.INTERP_BILINEAR), null, null, RangeFactory.create(noDataValue, noDataValue), null, hints); Raster raster = scaled.getData(); int minX = raster.getMinX(); int minY = raster.getMinY(); int maxX = minX + raster.getWidth(); int maxY = minY + raster.getHeight(); int halfX = (minX + maxX) / 2; int halfY = (minY + maxY) / 2; for (int i = minY; i < maxY; i++) { for (int j = minX; j < maxX; j++) { int value = raster.getSample(j, i, 0); if (i >= halfY && j >= halfX) { assertTrue("Expected noData value but found different value", value == noDataValue); } else { assertTrue("Expected valid value but found nodata", value != noDataValue); } } } }
Source:
public synchronized void addOrUpdate(final PromiseResolverBreakpoint bId) { FullSourceCoordinate coord = bId.getCoordinate(); BreakpointEnabling<PromiseResolverBreakpoint> existingBP = promiseResolverBreakpoints.get(coord); if (existingBP == null) { existingBP = new BreakpointEnabling<PromiseResolverBreakpoint>(bId); promiseResolverBreakpoints.put(coord, existingBP); } else { existingBP.setEnabled(bId.isEnabled()); } }

Target:
public synchronized void addOrUpdate(final PromiseResolverBreakpoint bId) { saveBreakpoint(bId, promiseResolverBreakpoints); }
Source:
public FactModelTuple retrieveFactModelTuple(Path path, String dmnPath) throws WrongDMNTypeException { DMNModel dmnModel = getDMNModel(path, dmnPath); SortedMap<String, FactModelTree> visibleFacts = new TreeMap<>(); SortedMap<String, FactModelTree> hiddenFacts = new TreeMap<>(); ErrorHolder errorHolder = new ErrorHolder(); Map<String, List<String>> genericTypeInfoMap = new HashMap<>(); for (InputDataNode input : dmnModel.getInputs()) { DMNType type = input.getType(); checkType(type, errorHolder, input.getName()); visibleFacts.put(input.getName(), createTopLevelFactModelTree(input.getName(), genericTypeInfoMap, type, hiddenFacts, FactModelTree.Type.INPUT)); } for (DecisionNode decision : dmnModel.getDecisions()) { DMNType type = decision.getResultType(); checkType(type, errorHolder, decision.getName()); visibleFacts.put(decision.getName(), createTopLevelFactModelTree(decision.getName(), genericTypeInfoMap, type, hiddenFacts, FactModelTree.Type.DECISION)); } FactModelTuple factModelTuple = new FactModelTuple(visibleFacts, hiddenFacts); errorHolder.getTopLevelCollection().forEach(factModelTuple::addTopLevelCollectionError); errorHolder.getMultipleNestedCollection().forEach(factModelTuple::addMultipleNestedCollectionError); errorHolder.getMultipleNestedObject().forEach(factModelTuple::addMultipleNestedObjectError); return factModelTuple; }

Target:
public FactModelTuple retrieveFactModelTuple(Path path, String dmnPath){ DMNModel dmnModel = getDMNModel(path, dmnPath); SortedMap<String, FactModelTree> visibleFacts = new TreeMap<>(); SortedMap<String, FactModelTree> hiddenFacts = new TreeMap<>(); ErrorHolder errorHolder = new ErrorHolder(); for (InputDataNode input : dmnModel.getInputs()) { DMNType type = input.getType(); checkTypeSupport(type, errorHolder, input.getName()); try { visibleFacts.put(input.getName(), createTopLevelFactModelTree(input.getName(), type, hiddenFacts, FactModelTree.Type.INPUT)); } catch (WrongDMNTypeException e) { throw ExceptionUtilities.handleException(e); } } for (DecisionNode decision : dmnModel.getDecisions()) { DMNType type = decision.getResultType(); checkTypeSupport(type, errorHolder, decision.getName()); try { visibleFacts.put(decision.getName(), createTopLevelFactModelTree(decision.getName(), type, hiddenFacts, FactModelTree.Type.DECISION)); } catch (WrongDMNTypeException e) { throw ExceptionUtilities.handleException(e); } } FactModelTuple factModelTuple = new FactModelTuple(visibleFacts, hiddenFacts); errorHolder.getTopLevelCollection().forEach(factModelTuple::addTopLevelCollectionError); errorHolder.getMultipleNestedCollection().forEach(factModelTuple::addMultipleNestedCollectionError); errorHolder.getMultipleNestedObject().forEach(factModelTuple::addMultipleNestedObjectError); return factModelTuple; }
Source:
public CompletableFuture<Void> deleteTableSnapshots(Pattern tableNamePattern, Pattern snapshotNamePattern) { return listTableSnapshots(tableNamePattern, snapshotNamePattern).thenApply(r->{ for (SnapshotDescription snapshotDescription : r) { deleteSnapshot(snapshotDescription.getName()); } return null; }); }

Target:
public CompletableFuture<Void> deleteTableSnapshots(Pattern tableNamePattern, Pattern snapshotNamePattern) { return listTableSnapshots(tableNamePattern, snapshotNamePattern).thenApply(response->{ for (SnapshotDescription snapshotDescription : response) { deleteSnapshot(snapshotDescription.getName()); } return null; }); }
Source:
public void shouldReturnIdentifierForLookupGeneratedIdentifier() { String className = GeneratedIdentifier.class.getSimpleName(); Map<String, String> lookupFields = new HashMap<>(); lookupFields.put(IDENTIFIER_SOURCE_NAME, "BAH"); GeneratedIdentifier generatedIdentifier = new GeneratedIdentifier(); generatedIdentifier.setValue("222"); when(identifierService.getLatestIdentifier(CONFIG_NAME, "BAH")).thenReturn(generatedIdentifier); Object object = taskDataProvider.lookup(className + '-' + CONFIG_NAME, "Generator source name", lookupFields); verify(identifierService).setLatestIdentifier(eq(CONFIG_NAME), eq("BAH"), eq(223L)); assertEquals(generatedIdentifier, object); }

Target:
public void shouldReturnIdentifierForLookupGeneratedIdentifier() { String className = GeneratedIdentifier.class.getSimpleName(); Map<String, String> lookupFields = new HashMap<>(); lookupFields.put(IDENTIFIER_SOURCE_NAME, IDENTIFIER_SOURCE_NAME_VALUE); GeneratedIdentifier generatedIdentifier = new GeneratedIdentifier(); generatedIdentifier.setValue("222"); when(identifierService.getLatestIdentifier(CONFIG_NAME, IDENTIFIER_SOURCE_NAME_VALUE)).thenReturn(generatedIdentifier); Object object = taskDataProvider.lookup(className + '-' + CONFIG_NAME, "Generator source name", lookupFields); verify(identifierService).setLatestIdentifier(eq(CONFIG_NAME), eq(IDENTIFIER_SOURCE_NAME_VALUE), eq(223L)); assertEquals(generatedIdentifier, object); }
Source:
public Object getValueAt(int row, int column) { try { Object value = super.getValueAt(row, column); if (value == null) { value = LabelUtils.NULL_LABEL; } return value; } catch (Exception e) { System.out.println("!!! " + e.getMessage()); return null; } }

Target:
public Object getValueAt(int row, int column) { Object value = super.getValueAt(row, column); if (value == null) { value = LabelUtils.NULL_LABEL; } return value; }
Source:
public void testPublicKeyCorrectlyCalculated() { BigInteger primeP = BigInteger.valueOf(23); BigInteger primeG = BigInteger.valueOf(5); BigInteger privateKey = BigInteger.valueOf(6); BigInteger expected = BigInteger.valueOf(8); assertEquals(expected, diffieHellman.publicKey(primeP, primeG, privateKey)); }

Target:
public void testPublicKeyCorrectlyCalculated() { BigInteger primeA = BigInteger.valueOf(23); BigInteger primeB = BigInteger.valueOf(5); BigInteger privateKey = BigInteger.valueOf(6); BigInteger expected = BigInteger.valueOf(8); assertEquals(expected, diffieHellman.publicKey(primeA, primeB, privateKey)); }
Source:
public void idle() { DispatchAttempt dispatchAttempt = sendQueue.remove(); Event event = dispatchAttempt.getEvent(); String address = dispatchAttempt.getAddress(); AuditLogEvent auditLogEvent; auditLogEvent = (AuditLogEvent) event; EventMessageContent message = new EventMessageContent(); message.prepareMessage(hostName, auditLogEvent, isBodyHtml); if (StringUtils.isEmpty(address)) { log.error("Address is empty, cannot distribute message." + event.getName()); return; } log.info(String.format("Send email to [%s]%n subject:%n [%s]", address, message.getMessageSubject())); if (log.isDebugEnabled()) { log.debug(String.format("body:%n [%s]", message.getMessageBody())); } String errorMessage = null; boolean success = false; try { mailSender.send(address, message.getMessageSubject(), message.getMessageBody()); setChanged(); notifyObservers(DispatchData.success(event, address, EventNotificationMethod.EMAIL)); success = true; } catch (MessagingException ex) { errorMessage = ex.getMessage(); } dispatchAttempt.setAttempts(dispatchAttempt.getAttempts() + 1); if (!success) { if (dispatchAttempt.getAttempts() < maxRetries) { sendQueue.add(dispatchAttempt); } else { setChanged(); notifyObservers(DispatchData.failure(event, address, EventNotificationMethod.EMAIL, errorMessage)); } } }

Target:
public void idle() { Iterator<DispatchAttempt> iterator = sendQueue.iterator(); while (iterator.hasNext()) { DispatchAttempt attempt = iterator.next(); try { doDispatch(attempt); notifyObservers(DispatchResult.success(attempt.event, attempt.address, EventNotificationMethod.EMAIL)); iterator.remove(); } catch (Exception ex) { attempt.attempts++; if (attempt.attempts >= ATTEMPTS) { notifyObservers(DispatchResult.failure(attempt.event, attempt.address, EventNotificationMethod.EMAIL, ex.getMessage())); iterator.remove(); } } } }
Source:
public void testRemoveFunctionExtension1() throws InterruptedException { log.info("RemoveFunctionExtension TestCase with test attributeExpressionExecutors length"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "\ndefine stream inputStream (symbol string, price long, volume long);"; String query = ("@info(name = 'query1') from inputStream select symbol,price, " + "map:create() as tmpMap insert into tmpStream;" + "@info(name = 'query2') from tmpStream select symbol,price,tmpMap, map:put(tmpMap,symbol,price) as map1" + " insert into outputStream;" + "@info(name = 'query3') from outputStream select map1, map:remove(map1) as map2" + " insert into outputStream2;" ); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); executionPlanRuntime.shutdown(); }

Target:
public void testRemoveFunctionExtension1() throws InterruptedException { log.info("RemoveFunctionExtension TestCase with test attributeExpressionExecutors length"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "\ndefine stream inputStream (symbol string, price long, volume long);"; String query = ("@info(name = 'query1') from inputStream select symbol,price, " + "map:create() as tmpMap insert into tmpStream;" + "@info(name = 'query2') from tmpStream select symbol,price,tmpMap, map:put(tmpMap,symbol,price)" + " as map1 insert into outputStream;" + "@info(name = 'query3') from outputStream select map1, map:remove(map1) as map2" + " insert into outputStream2;" ); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); executionPlanRuntime.start(); executionPlanRuntime.shutdown(); }
Source:
protected static Date getDeadlineDurationDate(String durationStr, int repeatCount) { try { if (DateTimeUtils.isRepeatable(durationStr)) { String[] repeatableParts = DateTimeUtils.parseISORepeatable(durationStr); String tempTimeDelay = repeatableParts[1]; String tempDateTimeStr = repeatableParts[2]; Date retDate; if (DateTimeUtils.isPeriod((tempDateTimeStr))) { retDate = new Date(DateTimeUtils.parseDateTime(tempTimeDelay) + repeatDuration(tempDateTimeStr, repeatCount)); } else { if(DateTimeUtils.isPeriod(tempTimeDelay)) { long firstRet = DateTimeUtils.parseDateTime(tempDateTimeStr) - Duration.parse(tempTimeDelay).toMillis(); retDate = new Date(firstRet + repeatDuration(tempTimeDelay, repeatCount)); } else { long duration = DateTimeUtils.parseDateTime(tempDateTimeStr) - DateTimeUtils.parseDateTime(tempTimeDelay); retDate = new Date(DateTimeUtils.parseDateTime(tempTimeDelay) + repeatDuration(duration, repeatCount)); } } return retDate; } else { if (DateTimeUtils.isPeriod((durationStr))) { return new Date(System.currentTimeMillis() + Duration.parse(durationStr).toMillis()); } else { return new Date(System.currentTimeMillis() + DateTimeUtils.parseDateAsDuration(durationStr)); } } } catch(Exception e) { throw new IllegalArgumentException("Unable to parse duration string: " + durationStr + " : " + e.getMessage()); } }

Target:
protected static Date getDeadlineDurationDate(String durationStr, int repeatCount) { try { if (DateTimeUtils.isRepeatable(durationStr)) { String[] repeatableParts = DateTimeUtils.parseISORepeatable(durationStr); String tempTimeDelay = repeatableParts[1]; String tempDateTimeStr = repeatableParts[2]; Date deadlineDate; if (DateTimeUtils.isPeriod((tempDateTimeStr))) { deadlineDate = new Date(DateTimeUtils.parseDateTime(tempTimeDelay) + DateTimeUtils.parseDuration(tempDateTimeStr) * repeatCount); } else if(DateTimeUtils.isPeriod(tempTimeDelay)) { long firstRet = DateTimeUtils.parseDateTime(tempDateTimeStr) - Duration.parse(tempTimeDelay).toMillis(); deadlineDate = new Date(firstRet + DateTimeUtils.parseDuration(tempTimeDelay) * repeatCount); } else { long duration = DateTimeUtils.parseDateTime(tempDateTimeStr) - DateTimeUtils.parseDateTime(tempTimeDelay); deadlineDate = new Date(DateTimeUtils.parseDateTime(tempTimeDelay) + duration * repeatCount); } return deadlineDate; } else { if (DateTimeUtils.isPeriod((durationStr))) { return new Date(System.currentTimeMillis() + Duration.parse(durationStr).toMillis()); } else { return new Date(System.currentTimeMillis() + DateTimeUtils.parseDateAsDuration(durationStr)); } } } catch(Exception e) { throw new IllegalArgumentException("Unable to parse duration string: " + durationStr + " : " + e.getMessage()); } }
Source:
public String generateDoc(PsiElement element, PsiElement originalElement) { if (element instanceof GoImportSpec) { element = ((GoImportSpec)element).getImportString().resolve(); } if (element instanceof GoNamedElement) { GoTopLevelDeclaration topLevel = PsiTreeUtil.getParentOfType(element, GoTopLevelDeclaration.class); Collection<PsiElement> children = PsiTreeUtil.findChildrenOfType(topLevel, element.getClass()); boolean alone = children.size() == 1 && children.iterator().next().equals(element); List<PsiComment> comments = getPreviousNonWsComment(alone ? topLevel : element); String result = "<pre>" + getSignature(element); result = result. replaceAll("\n", ""). replaceAll("\\s+", " "). replaceAll("\\(\\s", "("). replaceAll(",\\s\\)", ")"); if (!comments.isEmpty()) result += getCommentText(comments); return result + "</pre>"; } else if (element instanceof PsiDirectory) { String comments = getPackageComment(((PsiDirectory)element).findFile("doc.go")); if (comments != null) return comments; return getPackageComment(((PsiDirectory)element).findFile(((PsiDirectory)element).getName() + ".go")); } return null; }

Target:
public String generateDoc(PsiElement element, PsiElement originalElement) { if (element instanceof GoImportSpec) { element = ((GoImportSpec)element).getImportString().resolve(); } if (element instanceof GoNamedElement) { GoTopLevelDeclaration topLevel = PsiTreeUtil.getParentOfType(element, GoTopLevelDeclaration.class); Collection<PsiElement> children = PsiTreeUtil.findChildrenOfType(topLevel, element.getClass()); boolean alone = children.size() == 1 && children.iterator().next().equals(element); List<PsiComment> comments = getPreviousNonWsComment(alone ? topLevel : element); String result = getSignature(element); if (!comments.isEmpty()) result += getCommentText(comments); return result.length() > 0 ? "<pre>" + result + "</pre>" : ""; } else if (element instanceof PsiDirectory) { String comments = getPackageComment(((PsiDirectory)element).findFile("doc.go")); if (comments != null) return comments; return getPackageComment(((PsiDirectory)element).findFile(((PsiDirectory)element).getName() + ".go")); } return null; }
Source:
public Iterator<ChildReference> iterator( Name name, Context context ) { if (context != null && context.changes() != null) { return super.iterator(name, context); } else { return iterator(name); } }

Target:
public Iterator<ChildReference> iterator( Name name, Context context ) { if (context != null && context.changes() != null) { return super.iterator(name, context); } return iterator(name); }
Source:
@Override public boolean applicable(Context context) { TypeElement type = context.autoValueClass(); ParameterizedTypeName jsonAdapterType = ParameterizedTypeName.get( ADAPTER_CLASS_NAME, TypeName.get(type.asType())); TypeName returnedJsonAdapter = null; for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) { if (method.getModifiers().contains(Modifier.STATIC)) { TypeMirror rType = method.getReturnType(); TypeName returnType = TypeName.get(rType); if (returnType.equals(jsonAdapterType)) { return true; } if (returnType.equals(jsonAdapterType.rawType) || (returnType instanceof ParameterizedTypeName && ((ParameterizedTypeName) returnType).rawType.equals(jsonAdapterType.rawType))) { returnedJsonAdapter = returnType; } } } if (returnedJsonAdapter == null) { return false; } Messager messager = context.processingEnvironment().getMessager(); if (returnedJsonAdapter instanceof ParameterizedTypeName) { ParameterizedTypeName paramReturnType = (ParameterizedTypeName) returnedJsonAdapter; if (paramReturnType.typeArguments.get(0) instanceof ParameterizedTypeName) { return true; } else { TypeName argument = paramReturnType.typeArguments.get(0); messager.printMessage(Diagnostic.Kind.WARNING, String.format("Found static method returning JsonAdapter<%s> on %s class. " + "Skipping MoshiJsonAdapter generation.", argument, type)); } } else { messager.printMessage(Diagnostic.Kind.WARNING, "Found static method returning " + "JsonAdapter with no type arguments, skipping MoshiJsonAdapter generation."); } return false; }

Target:
@Override public boolean applicable(Context context) { TypeElement type = context.autoValueClass(); ParameterizedTypeName jsonAdapterType = ParameterizedTypeName.get( ADAPTER_CLASS_NAME, TypeName.get(type.asType())); TypeName returnedJsonAdapter = null; for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) { if (method.getModifiers().contains(Modifier.STATIC) && !method.getModifiers().contains(Modifier.PRIVATE)) { TypeMirror rType = method.getReturnType(); TypeName returnType = TypeName.get(rType); if (returnType.equals(jsonAdapterType)) { return true; } if (returnType.equals(jsonAdapterType.rawType) || (returnType instanceof ParameterizedTypeName && ((ParameterizedTypeName) returnType).rawType.equals(jsonAdapterType.rawType))) { returnedJsonAdapter = returnType; } } } if (returnedJsonAdapter == null) { return false; } Messager messager = context.processingEnvironment().getMessager(); if (returnedJsonAdapter instanceof ParameterizedTypeName) { ParameterizedTypeName paramReturnType = (ParameterizedTypeName) returnedJsonAdapter; if (paramReturnType.typeArguments.get(0) instanceof ParameterizedTypeName) { return true; } else { TypeName argument = paramReturnType.typeArguments.get(0); messager.printMessage(Diagnostic.Kind.WARNING, String.format("Found static method returning JsonAdapter<%s> on %s class. " + "Skipping MoshiJsonAdapter generation.", argument, type)); } } else { messager.printMessage(Diagnostic.Kind.WARNING, "Found static method returning " + "JsonAdapter with no type arguments, skipping MoshiJsonAdapter generation."); } return false; }
Source:
static LinkedHashMap<String, String> getKeyPropertyList(ObjectName mbeanName) { LinkedHashMap<String, String> output = new LinkedHashMap<String, String>(); String properties = mbeanName.getKeyPropertyListString(); Matcher match = PROPERTY_PATTERN.matcher(properties); while (match.lookingAt()) { output.put(match.group(1), match.group(2)); properties = properties.substring(match.end()); if (properties.startsWith(",")) properties = properties.substring(1); match.reset(properties); } return output; }

Target:
static LinkedHashMap<String, String> getKeyPropertyList(ObjectName mbeanName) { LinkedHashMap<String, String> output = new LinkedHashMap<String, String>(); String properties = mbeanName.getKeyPropertyListString(); Matcher match = PROPERTY_PATTERN.matcher(properties); while (match.lookingAt()) { output.put(match.group(1), match.group(2)); properties = properties.substring(match.end()); if (properties.startsWith(",")) { properties = properties.substring(1); } match.reset(properties); } return output; }
Source:
protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); setTitle(myTitle); }

Target:
protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); }
Source:
public void clickEdit() { clickAndWait(editLink); changeToMonoBook(); PageObjectLogging.log("clickEdit", "click on Edit link", true, driver); }

Target:
public void clickEdit() { clickAndWait(editLink); PageObjectLogging.log("clickEdit", "click on Edit link", true); }
Source:
public String escapeIdent(String ident) { try { StringBuilder buf = new StringBuilder(); escapeIdentifier(buf, ident); return buf.toString(); } catch (SQLException e) { throw new IllegalArgumentException("Invalid identifier name (contains \\0 character): " + ident); } }

Target:
public String escapeIdent(String ident) { try { StringBuilder buf = new StringBuilder(); escapeIdentifier(buf, ident); return buf.toString(); } catch (SQLException ex) { throw new IllegalArgumentException( String.format(ENGLISH, "Invalid identifier name (%s): %s", ex.getMessage(), ident)); } }
Source:
public void testNullPropertyWillNotBeAdded() { try { ServerConfiguration configuration = ConfigurationFileLoader.loadConfiguration(); configuration.setProperty("test-key", null); assertEquals(configuration.getProperty("test-key", null), null); assertEquals(configuration.getProperty("test-key", "a"), "a"); assertEquals(configuration.getProperty(TestConfigurationProvider.PROPERTY_3_NAME, null), null); assertFalse(configuration.getPropertyKeys().contains("test-key")); assertFalse(configuration.getPropertyKeys().contains(TestConfigurationProvider.PROPERTY_3_NAME)); } catch (Exception e) { fail("Error in test", e); } }

Target:
public void testNullPropertyWillNotBeAdded() { try { final ServerConfiguration configuration = ConfigurationFileLoader.loadConfiguration(); configuration.setProperty("test-key", null); assertEquals(configuration.getProperty("test-key", null), null); assertEquals(configuration.getProperty("test-key", "a"), "a"); assertEquals(configuration.getProperty(TestConfigurationProvider.PROPERTY_3_NAME, null), null); assertFalse(configuration.getPropertyKeys().contains("test-key")); assertFalse(configuration.getPropertyKeys().contains(TestConfigurationProvider.PROPERTY_3_NAME)); } catch (Exception e) { fail("Error in test", e); } }
Source:
public static String createSelectionPlaceholdersOfSize(int size) { String[] questionMarks = new String[size]; for (int i = 0; i < size; i++) { questionMarks[i] = "?"; } return StringUtils.join(Arrays.asList(questionMarks), ", "); }

Target:
public static String createSelectionPlaceholdersOfSize(int size) { if (size == 0) { return ""; } int sizeOfResult = size * 3 - 2; char[] result = new char[sizeOfResult]; for (int i = 0; i < sizeOfResult - 1; i += 3) { result[i] = '?'; result[i + 1] = ','; result[i + 2] = ' '; } result[sizeOfResult - 1] = '?'; return new String(result); }
Source:
default String describe(boolean pretty) { ScriptBuilder builder = new ScriptBuilder(pretty); builder .append("CREATE AGGREGATE ") .append(getKeyspace()) .append(".") .append(getSignature().getName()) .append("("); boolean first = true; for (int i = 0; i < getSignature().getParameterTypes().size(); i++) { if (first) { first = false; } else { builder.append(","); } DataType type = getSignature().getParameterTypes().get(i); builder.append(type.asCql(false, pretty)); } builder .append(")") .newLine() .append("SFUNC ") .append(getStateFuncSignature().getName()) .newLine() .append("STYPE ") .append(getStateType().asCql(false, pretty)); if (getFinalFuncSignature() != null) { builder.newLine().append("FINALFUNC ").append(getFinalFuncSignature().getName()); } if (getInitCond() != null) { builder.newLine().append("INITCOND ").append(formatInitCond()); } return builder.append(";").build(); }

Target:
default String describe(boolean pretty) { ScriptBuilder builder = new ScriptBuilder(pretty); builder .append("CREATE AGGREGATE ") .append(getKeyspace()) .append(".") .append(getSignature().getName()) .append("("); boolean first = true; for (int i = 0; i < getSignature().getParameterTypes().size(); i++) { if (first) { first = false; } else { builder.append(","); } DataType type = getSignature().getParameterTypes().get(i); builder.append(type.asCql(false, pretty)); } builder .increaseIndent() .append(")") .newLine() .append("SFUNC ") .append(getStateFuncSignature().getName()) .newLine() .append("STYPE ") .append(getStateType().asCql(false, pretty)); if (getFinalFuncSignature() != null) { builder.newLine().append("FINALFUNC ").append(getFinalFuncSignature().getName()); } if (getInitCond() != null) { builder.newLine().append("INITCOND ").append(formatInitCond()); } return builder.append(";").build(); }
Source:
public T blockingPeek() { fOutputLock.lock(); try { if (fOutputBuffer.isEmpty()) { fOutputBuffer = checkNotNull(fInnerQueue.take()); } return checkNotNull(fOutputBuffer.peekLast()); } catch (InterruptedException e) { Activator.instance().logError("Buffered queue interrupted", e); throw new IllegalStateException(); } finally { fOutputLock.unlock(); } }

Target:
public T blockingPeek() { fOutputLock.lock(); try { if (fOutputBuffer.isEmpty()) { fOutputBuffer = checkNotNull(fInnerQueue.take()); } return checkNotNull(fOutputBuffer.peek()); } catch (InterruptedException e) { Activator.instance().logError("Buffered queue interrupted", e); throw new IllegalStateException(); } finally { fOutputLock.unlock(); } }
Source:
private static String readInstanceId(Path path) { return readAllLines(path).get(0).split("instanceID=\"")[1].split("\"")[0]; }

Target:
private static String readInstanceId(Path path) { return readFirstLine(path).split("instanceID=\"")[1].split("\"")[0]; }
Source:
public static void afterClass() { TMP_DIRECTORY.delete(); }

Target:
public static void afterClass() { TMP_DIRECTORY.delete(); System.setProperty("java.io.tmpdir", ORIGINAL_TMP_DIRECTORY); }
Source:
public Optional<PlanNode> apply(PlanNode node, Context context) { if (!isPushAggregationThroughJoin(context.getSession())) { return Optional.empty(); } AggregationNode aggregationNode = (AggregationNode) node; PlanNode childNode = context.getLookup().resolve(aggregationNode.getSource()); if (!(childNode instanceof JoinNode)) { return Optional.empty(); } JoinNode joinNode = (JoinNode) childNode; if (aggregationNode.getStep() != PARTIAL || aggregationNode.getGroupingSets().size() != 1) { return Optional.empty(); } if (joinNode.getType() != JoinNode.Type.INNER || joinNode.getFilter().isPresent()) { return Optional.empty(); } if (allAggregationsOn(aggregationNode.getAggregations(), joinNode.getLeft().getOutputSymbols())) { return Optional.of(pushPartialToLeftChild(aggregationNode, joinNode)); } else if (allAggregationsOn(aggregationNode.getAggregations(), joinNode.getRight().getOutputSymbols())) { return Optional.of(pushPartialToRightChild(aggregationNode, joinNode)); } return Optional.empty(); }

Target:
public Optional<PlanNode> apply(PlanNode node, Context context) { if (!isPushAggregationThroughJoin(context.getSession())) { return Optional.empty(); } AggregationNode aggregationNode = (AggregationNode) node; if (aggregationNode.getStep() != PARTIAL || aggregationNode.getGroupingSets().size() != 1) { return Optional.empty(); } if (aggregationNode.getHashSymbol().isPresent()) { return Optional.empty(); } PlanNode childNode = context.getLookup().resolve(aggregationNode.getSource()); if (!(childNode instanceof JoinNode)) { return Optional.empty(); } JoinNode joinNode = (JoinNode) childNode; if (joinNode.getType() != JoinNode.Type.INNER) { return Optional.empty(); } if (allAggregationsOn(aggregationNode.getAggregations(), joinNode.getLeft().getOutputSymbols())) { return Optional.of(pushPartialToLeftChild(aggregationNode, joinNode, context)); } else if (allAggregationsOn(aggregationNode.getAggregations(), joinNode.getRight().getOutputSymbols())) { return Optional.of(pushPartialToRightChild(aggregationNode, joinNode, context)); } return Optional.empty(); }
Source:
private boolean isAllowedWifiConnected() { boolean wifiConnected = mDeviceStateHolder.isWifiConnected(); if (wifiConnected) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); Set<String> ssids = sp.getStringSet(PREF_SYNC_ONLY_WIFI_SSIDS, new HashSet<String>()); if (ssids == null || ssids.isEmpty()) { Log.d(TAG, "All SSIDs allowed for syncing"); return true; } else { String ssid = mDeviceStateHolder.getWifiSsid(); if (ssid != null) { if (ssids.contains(ssid)) { Log.d(TAG, "SSID " + ssid + " found in whitelist"); return true; } Log.i(TAG, "SSID " + ssid + " not whitelisted"); return false; } else { Log.w(TAG, "SSID unknown (yet), cannot check SSID whitelist. Disallowing sync."); return false; } } } Log.d(TAG, "Wifi not connected"); return false; }

Target:
private boolean isAllowedWifiConnected() { boolean wifiConnected = mDeviceStateHolder.isWifiConnected(); if (wifiConnected) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); Set<String> ssids = sp.getStringSet(PREF_SYNC_ONLY_WIFI_SSIDS, new HashSet<String>()); if (ssids.isEmpty()) { Log.d(TAG, "All SSIDs allowed for syncing"); return true; } else { String ssid = mDeviceStateHolder.getWifiSsid(); if (ssid != null) { if (ssids.contains(ssid)) { Log.d(TAG, "SSID " + ssid + " found in whitelist"); return true; } Log.i(TAG, "SSID " + ssid + " not whitelisted"); return false; } else { Log.w(TAG, "SSID unknown (yet), cannot check SSID whitelist. Disallowing sync."); return false; } } } Log.d(TAG, "Wifi not connected"); return false; }