auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void shouldReturnFalseWhenForwardedIpAddressIsNotInAllowedIpAddresses() { final String forwardedIpAddresses = "1.1.1.1, 102.108.0.6"; final String payload = notificationPayloadForTransaction( payId, EPDQ_PAYMENT_REQUESTED); final boolean result = notificationService.handleNotificationFor(payload, forwardedIpAddresses); assertFalse(result); }

Target:
void shouldReturnFalseWhenForwardedIpAddressIsNotInAllowedIpAddresses() { final String forwardedIpAddresses = "1.1.1.1, 102.108.0.6"; final String payload = notificationPayloadForTransaction( payId, EPDQ_PAYMENT_REQUESTED); assertFalse(notificationService.handleNotificationFor(payload, forwardedIpAddresses)); }
Source:
public void setAction(Action action) { switch (action) { case ALLOW: setDeny(false); break; case DENY: setDeny(true); break; default: throw new IllegalArgumentException(); } }

Target:
public void setAction(Action action) { if (action == null) { throw new NullPointerException("action"); } setDeny(action == Action.DENY); }
Source:
public static boolean verify(String json, JsonPathVerify jsonPathVerify) { Object leftObject = jsonPathVerify.getLeft(); Object rightObject = jsonPathVerify.getRight(); if (jsonPathVerify.getLeft().matches("\\$.*")) { leftObject= JsonPath.read(json, jsonPathVerify.getLeft()); } if (jsonPathVerify.getRight().matches("\\$.*")) { rightObject = JsonPath.read(json, jsonPathVerify.getRight()); } boolean result; switch (jsonPathVerify.getOperator()) { case EQ: result = leftObject.toString().equals(rightObject.toString()); break; case LT: result = compareTo(leftObject.toString(), rightObject.toString()) < 0; break; case GR: result = compareTo(leftObject.toString(), rightObject.toString()) > 0; break; default: throw new IllegalStateException("Unsupported operator: " + jsonPathVerify.getOperator()); } return result; }

Target:
public static boolean verify(String json, JsonPathVerify jsonPathVerify) { Object leftObject = jsonPathVerify.getLeft(); Object rightObject = jsonPathVerify.getRight(); if (jsonPathVerify.getLeft().matches("\\$.*")) { leftObject= JsonPath.read(json, jsonPathVerify.getLeft()); } if (jsonPathVerify.getRight().matches("\\$.*")) { rightObject = JsonPath.read(json, jsonPathVerify.getRight()); } boolean result; switch (jsonPathVerify.getOperator()) { case EQ: result = leftObject.toString().equals(rightObject.toString()); break; case NE: result = !leftObject.toString().equals(rightObject.toString()); break; case LT: result = compareTo(leftObject.toString(), rightObject.toString()) < 0; break; case GT: result = compareTo(leftObject.toString(), rightObject.toString()) > 0; break; default: throw new IllegalStateException("Unsupported operator: " + jsonPathVerify.getOperator()); } return result; }
Source:
public void consume(Iterator<KeyMessage<String, String>> updateIterator) throws IOException { while (updateIterator.hasNext()) { KeyMessage<String, String> km = updateIterator.next(); String key = km.getKey(); String message = km.getMessage(); switch (key) { case "UP": if (model != null) { List<?> update = MAPPER.readValue(message, List.class); int id = Integer.parseInt(update.get(0).toString()); double[] vector = MAPPER.convertValue(update.get(1), double[].class); model.update(id, vector); } break; case "MODEL": PMML pmml; try { pmml = PMMLUtils.fromString(message); } catch (JAXBException e) { throw new IOException(e); } KMeansPMMLUtils.validatePMMLVsSchema(pmml, inputSchema); List<ClusterInfo> clusters = KMeansPMMLUtils.read(pmml); model = new KMeansServingModel(clusters, inputSchema); break; default: throw new IllegalStateException("Bad model " + message); } } }

Target:
public void consume(Iterator<KeyMessage<String, String>> updateIterator) throws IOException { while (updateIterator.hasNext()) { KeyMessage<String, String> km = updateIterator.next(); String key = km.getKey(); String message = km.getMessage(); switch (key) { case "UP": if (model == null) { continue; } List<?> update = MAPPER.readValue(message, List.class); int id = Integer.parseInt(update.get(0).toString()); double[] vector = MAPPER.convertValue(update.get(1), double[].class); model.update(id, vector); break; case "MODEL": PMML pmml; try { pmml = PMMLUtils.fromString(message); } catch (JAXBException e) { throw new IOException(e); } KMeansPMMLUtils.validatePMMLVsSchema(pmml, inputSchema); List<ClusterInfo> clusters = KMeansPMMLUtils.read(pmml); model = new KMeansServingModel(clusters, inputSchema); break; default: throw new IllegalStateException("Bad model " + message); } } }
Source:
protected Boolean doTaskBackground(String... params) { if(records == null){ return true; } Log.d(TAG, "Wiping sent form records"); for (FormRecord record : records) { record.logPendingDeletion(TAG, "we are about to initiate a wifi direct transfer"); FormRecordCleanupTask.wipeRecord(c, record); } Log.d(TAG, "Successfully wiped: " + records.length + " FormRecords."); return true; }

Target:
protected Boolean doTaskBackground(String... params) { if(records == null){ return true; } Log.d(TAG, "Wiping sent form records"); for (FormRecord record : records) { record.logPendingDeletion(TAG, "we have just completed a wifi direct transfer"); FormRecordCleanupTask.wipeRecord(c, record); } Log.d(TAG, "Successfully wiped: " + records.length + " FormRecords."); return true; }
Source:
private void close(final boolean clean) { if (state() == State.CREATED) { transitionTo(State.CLOSING); } else { if (state() == State.RUNNING) { if (clean) { commit(); } transitionTo(State.CLOSING); } if (state() == State.CLOSING || state() == State.RESTORING) { final boolean wipeStateStore = !clean && !eosDisabled; executeAndMaybeSwallow(clean, () -> StateManagerUtil.closeStateManager(log, logPrefix, clean, wipeStateStore, stateMgr, stateDirectory, TaskType.STANDBY), "state manager close", log); } else { throw new IllegalStateException("Illegal state " + state() + " while closing standby task " + id); } } closeTaskSensor.record(); transitionTo(State.CLOSED); }

Target:
private void close(final boolean clean) { if (state() == State.CREATED || state() == State.RUNNING) { if (clean) { stateMgr.checkpoint(Collections.emptyMap()); offsetSnapshotSinceLastCommit = new HashMap<>(stateMgr.changelogOffsets()); } final boolean wipeStateStore = !clean && eosEnabled; log.info("standby task clean {}, eos enabled {}", clean, eosEnabled); executeAndMaybeSwallow(clean, () -> StateManagerUtil.closeStateManager( log, logPrefix, clean, wipeStateStore, stateMgr, stateDirectory, TaskType.STANDBY), "state manager close", log ); } else { throw new IllegalStateException("Illegal state " + state() + " while closing standby task " + id); } closeTaskSensor.record(); transitionTo(State.CLOSED); }
Source:
public int compareTo(FileAndName o) { return getFile().compareTo(o.getFile()); }

Target:
public int compareTo(FileAndName o) { int retVal = getFile().compareTo(o.getFile()); if (retVal == 0) { if (getTraceTypeId() != null) { if (getTraceTypeId() != null) { if( o.getTraceTypeId() != null) { retVal = getTraceTypeId().compareTo(o.getTraceTypeId()); } } } } return retVal; }
Source:
private static ITmfEventField[] generatePacketFields(Packet packet) { List<ITmfEventField> fieldList = new ArrayList<>(); List<ITmfEventField> subfieldList = new ArrayList<>(); Packet localPacket = packet.getPacket(PcapProtocol.PCAP); while (localPacket != null) { subfieldList.clear(); for (Map.Entry<String, String> entry : localPacket.getFields().entrySet()) { String key = nullToEmptyString(entry.getKey()); String value = entry.getValue(); subfieldList.add(new TmfEventField(key, value, null)); } ITmfEventField[] subfieldArray = subfieldList.toArray(new ITmfEventField[subfieldList.size()]); fieldList.add(new PcapEventField(localPacket.getProtocol().getName(), EMPTY_STRING, subfieldArray, localPacket)); localPacket = localPacket.getChildPacket(); } ITmfEventField[] fieldArray = fieldList.toArray(new ITmfEventField[fieldList.size()]); if (fieldArray == null) { return EMPTY_FIELD_ARRAY; } return fieldArray; }

Target:
private static ITmfEventField[] generatePacketFields(Packet packet) { List<ITmfEventField> fieldList = new ArrayList<>(); List<ITmfEventField> subfieldList = new ArrayList<>(); Packet localPacket = packet.getPacket(PcapProtocol.PCAP); while (localPacket != null) { subfieldList.clear(); for (Map.Entry<String, String> entry : localPacket.getFields().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); subfieldList.add(new TmfEventField(nullToEmptyString(key), value, null)); } ITmfEventField[] subfieldArray = subfieldList.toArray(new ITmfEventField[subfieldList.size()]); fieldList.add(new PcapEventField(localPacket.getProtocol().getName(), EMPTY_STRING, subfieldArray, localPacket)); localPacket = localPacket.getChildPacket(); } ITmfEventField[] fieldArray = fieldList.toArray(new ITmfEventField[fieldList.size()]); if (fieldArray == null) { return EMPTY_FIELD_ARRAY; } return fieldArray; }
Source:
public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable { if (isUsingAsyncStore(ctx, command)) { checkMarshallable(command.getKey()); checkMarshallable(command.getFunction()); } return invokeNext(ctx, command); }

Target:
public Object visitReadWriteKeyCommand(InvocationContext ctx, ReadWriteKeyCommand command) throws Throwable { if (isUsingAsyncStore(ctx, command)) { checkMarshallable(command.getKey()); } return invokeNext(ctx, command); }
Source:
public double parRate(ResolvedSwap swap, RatesProvider provider) { ResolvedSwapLeg fixedLeg = fixedLeg(swap); Currency ccyFixedLeg = fixedLeg.getCurrency(); double otherLegsConvertedPv = 0.0; for (ResolvedSwapLeg leg : swap.getLegs()) { if (leg != fixedLeg) { double pvLocal = legPricer.presentValueInternal(leg, provider); otherLegsConvertedPv += (pvLocal * provider.fxRate(leg.getCurrency(), ccyFixedLeg)); } } double fixedLegEventsPv = legPricer.presentValueEventsInternal(fixedLeg, provider); if (fixedLeg.getPaymentPeriods().size() > 1) { double pvbpFixedLeg = legPricer.pvbp(fixedLeg, provider); return -(otherLegsConvertedPv + fixedLegEventsPv) / pvbpFixedLeg; } PaymentPeriod firstPeriod = fixedLeg.getPaymentPeriods().get(0); ArgChecker.isTrue(firstPeriod instanceof RatePaymentPeriod, "PaymentPeriod must be instance of RatePaymentPeriod"); RatePaymentPeriod payment = (RatePaymentPeriod) firstPeriod; if (payment.getAccrualPeriods().size() == 1) { double pvbpFixedLeg = legPricer.pvbp(fixedLeg, provider); return -(otherLegsConvertedPv + fixedLegEventsPv) / pvbpFixedLeg; } Triple<Boolean, Integer, Double> fixedCompounded = checkFixedCompounded(fixedLeg); double notional = payment.getNotional(); double df = provider.discountFactor(ccyFixedLeg, payment.getPaymentDate()); return Math.pow(-(otherLegsConvertedPv + fixedLegEventsPv) / (notional * df) + 1.0d, 1.0 / fixedCompounded.getSecond()) - 1.0d; }

Target:
public double parRate(ResolvedSwap swap, RatesProvider provider) { ResolvedSwapLeg fixedLeg = fixedLeg(swap); Currency ccyFixedLeg = fixedLeg.getCurrency(); double otherLegsConvertedPv = 0.0; for (ResolvedSwapLeg leg : swap.getLegs()) { if (leg != fixedLeg) { double pvLocal = legPricer.presentValueInternal(leg, provider); otherLegsConvertedPv += (pvLocal * provider.fxRate(leg.getCurrency(), ccyFixedLeg)); } } double fixedLegEventsPv = legPricer.presentValueEventsInternal(fixedLeg, provider); if (fixedLeg.getPaymentPeriods().size() > 1) { double pvbpFixedLeg = legPricer.pvbp(fixedLeg, provider); return -(otherLegsConvertedPv + fixedLegEventsPv) / pvbpFixedLeg; } PaymentPeriod firstPeriod = fixedLeg.getPaymentPeriods().get(0); ArgChecker.isTrue(firstPeriod instanceof RatePaymentPeriod, "PaymentPeriod must be instance of RatePaymentPeriod"); RatePaymentPeriod payment = (RatePaymentPeriod) firstPeriod; if (payment.getAccrualPeriods().size() == 1) { double pvbpFixedLeg = legPricer.pvbp(fixedLeg, provider); return -(otherLegsConvertedPv + fixedLegEventsPv) / pvbpFixedLeg; } Triple<Boolean, Integer, Double> fixedCompounded = checkFixedCompounded(fixedLeg); ArgChecker.isTrue(fixedCompounded.getFirst(), "Swap should have a fixed leg and for one payment it should be based on compunding witout spread."); double notional = payment.getNotional(); double df = provider.discountFactor(ccyFixedLeg, payment.getPaymentDate()); return Math.pow(-(otherLegsConvertedPv + fixedLegEventsPv) / (notional * df) + 1.0d, 1.0 / fixedCompounded.getSecond()) - 1.0d; }
Source:
protected List<MeasurementRow> extractExcelFileData(final Workbook workbook, final UserSelection userSelection, final Map<Integer, MeasurementVariable> variableIndexMap, final boolean discardInvalidValues) { final Sheet sheet = workbook.getSheetAt(userSelection.getSelectedSheet()); final List<MeasurementRow> rows = new ArrayList<MeasurementRow>(userSelection.getObservationRows()); for (int i = userSelection.getContentRowIndex(); i <= userSelection.getContentRowIndex() + userSelection.getObservationRows() - 1; i++) { final MeasurementRow row = new MeasurementRow(); row.setDataList(this.convertRow(sheet, i, variableIndexMap, discardInvalidValues, this.retrieveAvailableEntryTypes(this.contextUtil.getCurrentProgramUUID()))); rows.add(row); } return rows; }

Target:
protected List<MeasurementRow> extractExcelFileData(final Workbook workbook, final UserSelection userSelection, final Map<Integer, MeasurementVariable> variableIndexMap, final boolean discardInvalidValues) { final Sheet sheet = workbook.getSheetAt(userSelection.getSelectedSheet()); final List<MeasurementRow> rows = new ArrayList<>(userSelection.getObservationRows()); final Map<String, Integer> availableEntryTypes = this .retrieveAvailableEntryTypes(this.contextUtil.getCurrentProgramUUID()); for (int i = userSelection.getContentRowIndex(); i <= userSelection.getContentRowIndex() + userSelection.getObservationRows() - 1; i++) { final MeasurementRow row = new MeasurementRow(); row.setDataList(this.convertRow(sheet, i, variableIndexMap, discardInvalidValues, availableEntryTypes)); rows.add(row); } return rows; }
Source:
public void makeBucket(String bucketName) throws ErrorResponseException, IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidKeyException, InvalidResponseException, IOException, NoSuchAlgorithmException, RegionConflictException, XmlParserException { MakeBucketArgs.Builder makeBucketArgs = new MakeBucketArgs.Builder(); makeBucketArgs.bucket(bucketName); MakeBucketArgs args = makeBucketArgs.build(); this.makeBucket(args); }

Target:
public void makeBucket(String bucketName) throws ErrorResponseException, IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidKeyException, InvalidResponseException, IOException, NoSuchAlgorithmException, RegionConflictException, XmlParserException { this.makeBucket(new MakeBucketArgs.Builder().bucket(bucketName).build()); }
Source:
public RegistrationScreenInteractor observeRegistrationScreen() { final MainApplication app = MainApplication.instance(); final CharSequence title = ResourceUtil.getFormattedString(app.getResources(), R.string.register_title, "platform_name", app.getInjector().getInstance(Config.class).getPlatformName()); return this; }

Target:
public RegistrationScreenInteractor observeRegistrationScreen() { final MainApplication app = MainApplication.instance(); final CharSequence title = ResourceUtil.getFormattedString(app.getResources(), R.string.register_title, "platform_name", app.getInjector().getInstance(Config.class).getPlatformName()); onView(allOf(isInActionBar(), withText(title.toString()))).check(matches(isCompletelyDisplayed())); return this; }
Source:
public void testGetDirectAdmins() throws Exception { System.out.println(CLASS_NAME + "testGetDirectAdmins"); setUpSecurityTeams(); setUpUsers(); securityTeamsManagerEntry.addAdmin(sess, st0, u0); assertTrue(securityTeamsManagerEntry.getDirectAdmins(sess, st0).contains(u0)); }

Target:
public void testGetDirectAdmins() throws Exception { System.out.println(CLASS_NAME + "testGetDirectAdmins"); setUpSecurityTeams(); setUpUsers(); List<User> expected = setUpAdmins(u1, u2, setUpGroup(u3, u4)); expected.remove(u3); expected.remove(u4); List<User> actual = securityTeamsManagerEntry.getAdmins(sess, st0, true); Collections.sort(expected); Collections.sort(actual); assertEquals(expected, actual); }
Source:
public OnkyoConnection(String ip, int port) { this.ip = ip; this.port = port; connection = (EiscpInterface)new Eiscp(ip, port); }

Target:
public OnkyoConnection(String ip, int port) { this.ip = ip; this.port = port; connection = new Eiscp(ip, port); }
Source:
private int decompressDirectBuf() throws IOException { if (compressedDirectBufLen == 0) { return 0; } else { compressedDirectBuf.limit(compressedDirectBufLen).position(0); int size = Snappy.uncompress((ByteBuffer) compressedDirectBuf, (ByteBuffer) uncompressedDirectBuf); compressedDirectBufLen = 0; compressedDirectBuf.limit(compressedDirectBuf.capacity()).position(0); return size; } }

Target:
private int decompressDirectBuf() throws IOException { if (compressedDirectBufLen == 0) { return 0; } else { compressedDirectBuf.limit(compressedDirectBufLen).position(0); int size = Snappy.uncompress((ByteBuffer) compressedDirectBuf, (ByteBuffer) uncompressedDirectBuf); compressedDirectBufLen = 0; compressedDirectBuf.clear(); return size; } }
Source:
public ExternalConditionEval(ExternalCondition condition, Data data) { super(Type.EXTERNAL, condition.match(data.getValue()), data.getTimestamp(), data.getContext()); this.condition = condition; this.value = data.getValue(); this.typeValue = TypeValue.EVENT; }

Target:
public ExternalConditionEval(ExternalCondition condition, Data data) { super(Type.EXTERNAL, condition.match(data.getValue()), data.getTimestamp(), data.getContext()); this.condition = condition; this.value = data.getValue(); }
Source:
public CommentAttributes(Comment comment) { this.commentId = comment.getId(); this.courseId = comment.getCourseId(); this.giverEmail = comment.getGiverEmail(); this.recipientType = comment.getRecipientType(); this.status = comment.getStatus(); this.sendingState = comment.getSendingState() != null? comment.getSendingState() : CommentSendingState.SENT; this.showCommentTo = comment.getShowCommentTo(); this.showGiverNameTo = comment.getShowGiverNameTo(); this.showRecipientNameTo = comment.getShowRecipientNameTo(); this.recipients = comment.getRecipients(); this.createdAt = comment.getCreatedAt(); this.commentText = comment.getCommentText(); this.lastEditorEmail = comment.getLastEditorEmail(); this.lastEditedAt = comment.getLastEditedAt(); }

Target:
public CommentAttributes(Comment comment) { this.commentId = comment.getId(); this.courseId = comment.getCourseId(); this.giverEmail = comment.getGiverEmail(); this.recipientType = comment.getRecipientType(); this.status = comment.getStatus(); this.sendingState = comment.getSendingState() != null? comment.getSendingState() : CommentSendingState.SENT; this.showCommentTo = comment.getShowCommentTo(); this.showGiverNameTo = comment.getShowGiverNameTo(); this.showRecipientNameTo = comment.getShowRecipientNameTo(); this.recipients = comment.getRecipients(); this.createdAt = comment.getCreatedAt(); this.commentText = comment.getCommentText(); this.lastEditorEmail = comment.getLastEditorEmail() != null ? comment.getLastEditorEmail() : comment.getGiverEmail(); this.lastEditedAt = comment.getLastEditedAt() != null ? comment.getLastEditedAt() : comment.getCreatedAt(); }
Source:
public void select(E element) { int elementIndex = this.elements.indexOf(element); if (elementIndex >= 0) { mappedToggleButtons.get(elementIndex).fire(); } else { throw new IllegalArgumentException(String.format("Element %s doesn't exist", element.toString())); } }

Target:
public void select(E element) { this.select(this.elements.indexOf(element)); }
Source:
public static List<CitationStyle> discoverCitationStyles() { if (!STYLES.isEmpty()) { return STYLES; } URL url = CitationStyle.class.getResource("/modules/org.jabref/csl-styles"); Objects.requireNonNull(url); if (url == null) { return Collections.emptyList(); } try { URI uri = url.toURI(); LOGGER.debug("Uri " + uri); try (FileSystem fs = FileSystems.newFileSystem(uri, Collections.emptyMap())) { Path path = fs.getPath(STYLES_ROOT); STYLES.addAll(discoverCitationStylesInPath(path)); } catch (FileSystemAlreadyExistsException e) { try (FileSystem fs = FileSystems.getFileSystem(uri)) { Path path = fs.getPath(STYLES_ROOT); STYLES.addAll(discoverCitationStylesInPath(path)); } catch (FileSystemException ex) { LOGGER.error("Failed to discover csl styles ", ex); } } return STYLES; } catch (URISyntaxException | IOException e) { LOGGER.error("something went wrong while searching available CitationStyles. Are you running directly from source code?", e); return Collections.emptyList(); } }

Target:
public static List<CitationStyle> discoverCitationStyles() { if (!STYLES.isEmpty()) { return STYLES; } URL url = CitationStyle.class.getResource("csl-styles/academy-of-management-review.csl"); Objects.requireNonNull(url); if (url == null) { return Collections.emptyList(); } try { URI uri = url.toURI(); LOGGER.debug("Uri " + uri); System.out.println(uri); Path path = Path.of(uri).getParent(); STYLES.addAll(discoverCitationStylesInPath(path)); return STYLES; } catch (URISyntaxException | IOException e) { LOGGER.error("something went wrong while searching available CitationStyles. Are you running directly from source code?", e); return Collections.emptyList(); } }
Source:
static public PermissionRule allow(ProjectConfig project, String capabilityName, AccountGroup.UUID group) { PermissionRule rule = newRule(project, group); project.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true) .getPermission(capabilityName, true) .add(rule); return rule; }

Target:
public static PermissionRule allow(ProjectConfig project, String capabilityName, AccountGroup.UUID group) { PermissionRule rule = newRule(project, group); project.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true) .getPermission(capabilityName, true) .add(rule); return rule; }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mApp = (Gh4Application) getApplicationContext(); mActionBar = getSupportActionBar(); mActionBar.setTitle(mRepoOwner + "/" + mRepoName); mActionBar.setDisplayHomeAsUpEnabled(true); setContentShown(false); this.loadRepository().subscribe(o -> {}, e -> {}); if (Gh4Application.get().isAuthorized()) { this.isWatching(); this.isStarring(); } }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mActionBar = getSupportActionBar(); mActionBar.setTitle(mRepoOwner + "/" + mRepoName); mActionBar.setDisplayHomeAsUpEnabled(true); setContentShown(false); loadRepository(false); if (Gh4Application.get().isAuthorized()) { loadWatchingStatus(false); loadStarringStatus(false); } }
Source:
protected CellList<Bookmark> createDataDisplayWidget(BookmarkModelProvider modelProvider) { ApplicationTemplates templates = ClientGinjectorProvider.instance().getApplicationTemplates(); final CellList<Bookmark> display = new CellList<Bookmark>(new BookmarkListItemCell(templates)); display.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED); display.setKeyboardPagingPolicy(KeyboardPagingPolicy.INCREASE_RANGE); display.addDomHandler(new KeyDownHandler() { @Override @SuppressWarnings("unchecked") public void onKeyDown(KeyDownEvent event) { SingleSelectionModel<Bookmark> selectionModel = (SingleSelectionModel<Bookmark>) display.getSelectionModel(); if (selectionModel.getSelectedObject() != null) { Bookmark item = null; int index = display.getVisibleItems().indexOf(selectionModel.getSelectedObject()); int key = event.getNativeEvent().getKeyCode(); if (key == KeyCodes.KEY_UP) { item = display.getVisibleItems().get(index - 1); } else if (key == KeyCodes.KEY_DOWN) { item = display.getVisibleItems().get(index + 1); } if (item != null) { selectionModel.setSelected(item, true); event.stopPropagation(); event.preventDefault(); } } } }, KeyDownEvent.getType()); display.sinkEvents(Event.ONKEYDOWN); modelProvider.addDataDisplay(display); return display; }

Target:
protected CellList<Bookmark> createDataDisplayWidget(BookmarkModelProvider modelProvider) { ApplicationTemplates templates = ClientGinjectorProvider.instance().getApplicationTemplates(); CellList<Bookmark> display = new CellList<Bookmark>(new BookmarkListItemCell(templates)); display.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.BOUND_TO_SELECTION); display.setKeyboardPagingPolicy(KeyboardPagingPolicy.INCREASE_RANGE); modelProvider.addDataDisplay(display); return display; }
Source:
public void retriesOnExceptionTillCount() throws Exception { final int count = 3; final int delay = 1000; final Take take = Mockito.mock(Take.class); final Request req = new RqFake(RqMethod.GET); Mockito.when(take.act(Mockito.any(Request.class))).thenThrow( new IOException() ); final long startTime = System.currentTimeMillis(); try { new TkRetry(count, delay, take).act(req); } catch (final IOException exception) { MatcherAssert.assertThat( new Long(count * delay), Matchers.lessThanOrEqualTo( System.currentTimeMillis() - startTime ) ); throw exception; } }

Target:
public void retriesOnExceptionTillCount() throws Exception { final int count = Tv.THREE; final int delay = Tv.THOUSAND; final Take take = Mockito.mock(Take.class); Mockito .when(take.act(Mockito.any(Request.class))) .thenThrow(new IOException()); final long start = System.nanoTime(); try { new TkRetry(count, delay, take).act( new RqFake(RqMethod.GET) ); } catch (final IOException exception) { final long spent = System.nanoTime() - start; MatcherAssert.assertThat( new Long(count * delay - Tv.HUNDRED) * Tv.MILLION, Matchers.lessThanOrEqualTo(spent) ); throw exception; } }
Source:
public static void processMultipleFiles(ArrayList<File> specFiles) throws MOPException { String aspectName; if(options.outputDir == null){ options.outputDir = getTargetDir(specFiles); } if(options.aspectname != null) { aspectName = options.aspectname; } else { if(specFiles.size() == 1) { aspectName = Tool.getFileName(specFiles.get(0).getAbsolutePath()); } else { int suffixNumber = 0; File aspectFile; do{ suffixNumber++; aspectFile = new File(options.outputDir.getAbsolutePath() + File.separator + "MultiSpec_" + suffixNumber + "MonitorAspect.aj"); } while(aspectFile.exists()); aspectName = "MultiSpec_" + suffixNumber; } options.aspectname = aspectName; } MOPProcessor processor = new MOPProcessor(aspectName); MOPNameSpace.init(); ArrayList<MOPSpecFile> specs = new ArrayList<MOPSpecFile>(); for(File file : specFiles){ String specStr = SpecExtractor.process(file); MOPSpecFile spec = SpecExtractor.parse(specStr); writeFile(processor.generateRVFile(spec), file.getAbsolutePath(), ".rvm"); specs.add(spec); } MOPSpecFile combinedSpec = FileCombiner.combineSpecFiles(specs); writeCombinedAspectFile(processor.generateAJFile(combinedSpec), aspectName); }

Target:
public static void processMultipleFiles(ArrayList<File> specFiles) throws MOPException { String aspectName; if(options.outputDir == null){ options.outputDir = getTargetDir(specFiles); } if(options.aspectname != null) { aspectName = options.aspectname; } else { if(specFiles.size() == 1) { aspectName = Tool.getFileName(specFiles.get(0).getAbsolutePath()); } else { int suffixNumber = 0; File aspectFile; do{ suffixNumber++; aspectFile = new File(options.outputDir.getAbsolutePath() + File.separator + "MultiSpec_" + suffixNumber + AJ_FILE_SUFFIX); } while(aspectFile.exists()); aspectName = "MultiSpec_" + suffixNumber; } options.aspectname = aspectName; } MOPProcessor processor = new MOPProcessor(aspectName); MOPNameSpace.init(); ArrayList<MOPSpecFile> specs = new ArrayList<MOPSpecFile>(); for(File file : specFiles){ String specStr = SpecExtractor.process(file); MOPSpecFile spec = SpecExtractor.parse(specStr); writeFile(processor.generateRVFile(spec), file.getAbsolutePath(), RVM_FILE_SUFFIX); specs.add(spec); } MOPSpecFile combinedSpec = FileCombiner.combineSpecFiles(specs); writeCombinedAspectFile(processor.generateAJFile(combinedSpec), aspectName); }
Source:
protected String getJobStatusFieldColor(ListGridRecord record, int rowNum, int colNum, String base) { String fieldName = this.getFieldName(colNum); base = highlightRowHavingIssues(rowNum, base); if (fieldName.equals(STATE_ATTR.getName())) { try { switch (getJobStatus(record)) { case KILLED: return "color:#BE2D1C;font-weight:bold;" + base; case CANCELED: return "color:#C50000;font-weight:bold;" + base; case FAILED: return "color:#850003;" + base; case IN_ERROR: return "color:#E94504;font-weight:bold;" + base; case RUNNING: return "color:#1a8bba;font-weight:bold;" + base; case PENDING: return "color:#F0E130;font-weight:bold;" + base; case STALLED: return "color:#62cef7;" + base; case PAUSED: return "color:#ff9933;font-weight:bold;" + base; case FINISHED: return base; default: return base; } } catch (NullPointerException npe) { return base; } } return base; }

Target:
protected String getJobStatusFieldColor(ListGridRecord record, int rowNum, int colNum, String base) { String fieldName = this.getFieldName(colNum); base = highlightRowHavingIssues(rowNum, base); if (fieldName.equals(STATE_ATTR.getName())) { try { switch (getJobStatus(record)) { case KILLED: return "color:#BE2D1C;font-weight:bold;" + base; case CANCELED: return "color:#C50000;font-weight:bold;" + base; case FAILED: return "color:#850003;font-weight:bold;" + base; case IN_ERROR: return "color:#E94504;font-weight:bold;" + base; case RUNNING: return "color:#2051F4;font-weight:bold;" + base; case PENDING: return "color:#F0E130;" + base; case STALLED: return "color:#1B89B8;font-weight:bold;" + base; case PAUSED: return "color:#ff9933;font-weight:bold;" + base; case FINISHED: return base; default: return base; } } catch (NullPointerException npe) { return base; } } return base; }
Source:
public FEELFnResult<TemporalAccessor> invoke(@ParameterName( "date" ) Temporal date, @ParameterName( "time" ) Temporal time) { if ( date == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "date", "cannot be null")); } if ( !(date instanceof LocalDate) ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "date", "must be an instance of LocalDate")); } if ( time == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "time", "cannot be null")); } if ( !(time instanceof LocalTime || time instanceof OffsetTime) ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "time", "must be an instance of LocalTime or OffsetTime")); } if( time instanceof LocalTime ) { return FEELFnResult.ofResult( LocalDateTime.of( (LocalDate) date, (LocalTime) time ) ); } else { return FEELFnResult.ofResult( ZonedDateTime.of( (LocalDate) date, LocalTime.from( time ), ZoneOffset.from( time ) ) ); } }

Target:
public FEELFnResult<TemporalAccessor> invoke(@ParameterName( "date" ) Temporal date, @ParameterName( "time" ) Temporal time) { if ( date == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "date", "cannot be null")); } if ( !(date instanceof LocalDate) ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "date", "must be an instance of LocalDate")); } if ( time == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "time", "cannot be null")); } if ( !(time instanceof LocalTime || time instanceof OffsetTime) ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "time", "must be an instance of LocalTime or OffsetTime")); } try { if ( time instanceof LocalTime ) { return FEELFnResult.ofResult(LocalDateTime.of((LocalDate) date, (LocalTime) time)); } else { return FEELFnResult.ofResult(ZonedDateTime.of((LocalDate) date, LocalTime.from(time), ZoneOffset.from(time))); } } catch ( DateTimeException e ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "input parameters date-parsing exception", e)); } }
Source:
public KuduClientConfig setMasterAddresses(String... contactPoints) { this.masterAddresses = Arrays.asList(contactPoints); return this; }

Target:
public KuduClientConfig setMasterAddresses(String... contactPoints) { this.masterAddresses = ImmutableList.copyOf(contactPoints); return this; }
Source:
public static PreallocationType getPreallocationType(final Storage.ProvisioningType provisioningType){ switch (provisioningType){ case THIN: return PreallocationType.Off; case SPARSE: return PreallocationType.Metadata; case FAT: return PreallocationType.Full; default: throw new NotImplementedProvisioningTypeException(); } }

Target:
public static PreallocationType getPreallocationType(final Storage.ProvisioningType provisioningType){ switch (provisioningType){ case THIN: return PreallocationType.Off; case SPARSE: return PreallocationType.Metadata; case FAT: return PreallocationType.Full; default: throw new NotImplementedException(String.format("type %s not defined as member-value of PreallocationType", provisioningType)); } }
Source:
protected void notify(JobExecutionContext jobExecutionContext, String jobStatus) { try { StringBuilder mailMessageSubject = new StringBuilder(jobExecutionContext.getJobDetail().getGroup()).append(": ").append(jobExecutionContext.getJobDetail().getName()); BodyMailMessage mailMessage = new BodyMailMessage(); mailMessage.setFromAddress(emailService.getDefaultFromAddress()); if (jobExecutionContext.getMergedJobDataMap().containsKey(REQUESTOR_EMAIL_ADDRESS_KEY) && !StringUtils.isBlank(jobExecutionContext.getMergedJobDataMap().getString(REQUESTOR_EMAIL_ADDRESS_KEY))) { mailMessage.addToAddress(jobExecutionContext.getMergedJobDataMap().getString(REQUESTOR_EMAIL_ADDRESS_KEY)); } if (SchedulerService.FAILED_JOB_STATUS_CODE.equals(jobStatus) || SchedulerService.CANCELLED_JOB_STATUS_CODE.equals(jobStatus)) { mailMessage.addToAddress(emailService.getDefaultFromAddress()); } String url = SpringContext.getBean(ParameterService.class).getParameterValueAsString("KFS-SYS", "Batch", "BATCH_REPORTS_URL"); mailMessageSubject.append(": ").append(jobStatus); String messageText = MessageFormat.format(configurationService.getPropertyValueAsString(KFSKeyConstants.MESSAGE_BATCH_FILE_LOG_EMAIL_BODY), url); mailMessage.setMessage(messageText); if (mailMessage.getToAddresses().size() > 0) { mailMessage.setSubject(mailMessageSubject.toString()); emailService.sendMessage(mailMessage, false); } } catch (Exception iae) { LOG.error("Caught exception while trying to send job completion notification e-mail for " + jobExecutionContext.getJobDetail().getName(), iae); } }

Target:
protected void notify(JobExecutionContext jobExecutionContext, String jobStatus) { try { StringBuilder mailMessageSubject = new StringBuilder(jobExecutionContext.getJobDetail().getGroup()).append(": ").append(jobExecutionContext.getJobDetail().getName()); BodyMailMessage mailMessage = new BodyMailMessage(); mailMessage.setFromAddress(emailService.getDefaultFromAddress()); if (jobExecutionContext.getMergedJobDataMap().containsKey(REQUESTOR_EMAIL_ADDRESS_KEY) && !StringUtils.isBlank(jobExecutionContext.getMergedJobDataMap().getString(REQUESTOR_EMAIL_ADDRESS_KEY))) { mailMessage.addToAddress(jobExecutionContext.getMergedJobDataMap().getString(REQUESTOR_EMAIL_ADDRESS_KEY)); } if (SchedulerService.FAILED_JOB_STATUS_CODE.equals(jobStatus) || SchedulerService.CANCELLED_JOB_STATUS_CODE.equals(jobStatus)) { mailMessage.addToAddress(emailService.getDefaultToAddress()); } String url = SpringContext.getBean(ParameterService.class).getParameterValueAsString("KFS-SYS", "Batch", "BATCH_REPORTS_URL"); mailMessageSubject.append(": ").append(jobStatus); String messageText = MessageFormat.format(configurationService.getPropertyValueAsString(KFSKeyConstants.MESSAGE_BATCH_FILE_LOG_EMAIL_BODY), url); mailMessage.setMessage(messageText); if (mailMessage.getToAddresses().size() > 0) { mailMessage.setSubject(mailMessageSubject.toString()); emailService.sendMessage(mailMessage, false); } } catch (Exception iae) { LOG.error("Caught exception while trying to send job completion notification e-mail for " + jobExecutionContext.getJobDetail().getName(), iae); } }
Source:
private WebXml parseWebXml(ServletContext servletContext) { InputStream inputStream = servletContext.getResourceAsStream(webXmlPath); if (inputStream == null) { throw new IllegalStateException(String.format("Could not read %s!", webXmlPath)); } WebXmlParser parser = new WebXmlParser(false, false, true); WebXml webXml = new WebXml(); boolean success = parser.parseWebXml(new InputSource(inputStream), webXml, false); if (!success) { throw new IllegalStateException("Something went wrong registering precompiled JSPs"); } LOG.info("Parsed including servlets and servletMappings!", webXmlPath, webXml.getServlets().size(), webXml.getServletMappings().size()); return webXml; }

Target:
private WebXml parseWebXml(ServletContext servletContext) { final WebXml webXml = new WebXml(); try (InputStream inputStream = servletContext.getResourceAsStream(webXmlPath)) { if (inputStream == null) { throw new IllegalStateException(String.format("Could not read %s!", webXmlPath)); } final WebXmlParser parser = new WebXmlParser(false, false, true); final boolean success = parser.parseWebXml(new InputSource(inputStream), webXml, false); if (!success) { throw new IllegalStateException("Something went wrong registering precompiled JSPs"); } LOG.info("Parsed including servlets and servletMappings!", webXmlPath, webXml.getServlets().size(), webXml.getServletMappings().size()); } catch (IOException e) { throw new IllegalStateException("Could not close the web.xml input stream to precompile jsps"); } return webXml; }
Source:
void fixSshKeyOnWindows(File key) throws GitException { if (launcher.isUnix()) return; Path file = Paths.get(key.toURI()); AclFileAttributeView fileAttributeView = Files.getFileAttributeView(file, AclFileAttributeView.class); if (fileAttributeView == null) return; String username = getWindowsUserName(fileAttributeView); if (StringUtils.isBlank(username)) return; try { UserPrincipalLookupService userPrincipalLookupService = file.getFileSystem().getUserPrincipalLookupService(); UserPrincipal userPrincipal = userPrincipalLookupService.lookupPrincipalByName(username); AclEntry aclEntry = AclEntry.newBuilder() .setType(AclEntryType.ALLOW) .setPrincipal(userPrincipal) .setPermissions(ACL_ENTRY_PERMISSIONS) .build(); fileAttributeView.setAcl(Collections.singletonList(aclEntry)); } catch (IOException | UnsupportedOperationException e) { throw new GitException("Error updating file permission", e); } }

Target:
void fixSshKeyOnWindows(File key) throws GitException { if (launcher.isUnix()) return; Path file = Paths.get(key.toURI()); AclFileAttributeView fileAttributeView = Files.getFileAttributeView(file, AclFileAttributeView.class); if (fileAttributeView == null) return; String username = getWindowsUserName(fileAttributeView); if (StringUtils.isBlank(username)) return; try { UserPrincipalLookupService userPrincipalLookupService = file.getFileSystem().getUserPrincipalLookupService(); UserPrincipal userPrincipal = userPrincipalLookupService.lookupPrincipalByName(username); AclEntry aclEntry = AclEntry.newBuilder() .setType(AclEntryType.ALLOW) .setPrincipal(userPrincipal) .setPermissions(ACL_ENTRY_PERMISSIONS) .build(); fileAttributeView.setAcl(Collections.singletonList(aclEntry)); } catch (IOException | UnsupportedOperationException e) { throw new GitException("Error updating file permission for \"" + key.getAbsolutePath() + "\""); } }
Source:
IonManagedBinaryWriter(final _Private_IonManagedBinaryWriterBuilder builder, final OutputStream out) throws IOException { super(builder.optimization); symbols = new IonRawBinaryWriter( builder.provider, builder.symbolsBlockSize, out, WriteValueOptimization.NONE, StreamCloseMode.NO_CLOSE, StreamFlushMode.NO_FLUSH, builder.preallocationMode, builder.isFloatBinary32Enabled ); user = new IonRawBinaryWriter( builder.provider, builder.userBlockSize, out, WriteValueOptimization.NONE, StreamCloseMode.CLOSE, StreamFlushMode.FLUSH, builder.preallocationMode, builder.isFloatBinary32Enabled ); currentWriter = user; catalog = builder.catalog; if(builder.imports == null) { fallbackImports = new ArrayList<SymbolTable>(); } else { fallbackImports = new ArrayList(builder.imports); } if (builder.initialSymbolTable != null) { lstIndex = builder.initialSymbolTable.getImportedMaxId(); ArrayList temp = new ArrayList<String>(); final Iterator<String> symbolIter = builder.initialSymbolTable.iterateDeclaredSymbolNames(); while (symbolIter.hasNext()) { temp.add(symbolIter.next()); } lstWriter = new LSTWriter(new ArrayList(Arrays.asList(builder.initialSymbolTable.getImportedTables())), temp, catalog); lst = lstWriter.getSymbolTable(); lstIndex = lst.getImportedMaxId(); } else { lstWriter = new LSTWriter(fallbackImports, new ArrayList<String>(), catalog); lst = lstWriter.getSymbolTable(); lstIndex = lst.getImportedMaxId(); } maxSysId = lst.getSystemSymbolTable().getMaxId(); }

Target:
IonManagedBinaryWriter(final _Private_IonManagedBinaryWriterBuilder builder, final OutputStream out) throws IOException { super(builder.optimization); symbols = new IonRawBinaryWriter( builder.provider, builder.symbolsBlockSize, out, _Private_WriteValueOptimization.NONE, StreamCloseMode.NO_CLOSE, StreamFlushMode.NO_FLUSH, builder.preallocationMode, builder.isFloatBinary32Enabled ); user = new IonRawBinaryWriter( builder.provider, builder.userBlockSize, out, _Private_WriteValueOptimization.NONE, StreamCloseMode.CLOSE, StreamFlushMode.FLUSH, builder.preallocationMode, builder.isFloatBinary32Enabled ); currentWriter = user; catalog = builder.catalog; if(builder.imports == null) { fallbackImports = new ArrayList<SymbolTable>(); } else { fallbackImports = new ArrayList<SymbolTable>(builder.imports); } if (builder.initialSymbolTable != null) { lstIndex = builder.initialSymbolTable.getImportedMaxId(); ArrayList<String> temp = new ArrayList<String>(); final Iterator<String> symbolIter = builder.initialSymbolTable.iterateDeclaredSymbolNames(); while (symbolIter.hasNext()) { temp.add(symbolIter.next()); } lstWriter = new _Private_LSTWriter(new ArrayList(Arrays.asList(builder.initialSymbolTable.getImportedTables())), temp, catalog); lst = lstWriter.getSymbolTable(); lstIndex = lst.getImportedMaxId(); } else { lstWriter = new _Private_LSTWriter(fallbackImports, Collections.<String>emptyList(), catalog); lst = lstWriter.getSymbolTable(); lstIndex = lst.getImportedMaxId(); } maxSysId = lst.getSystemSymbolTable().getMaxId(); }
Source:
void testBingTileEncoding() { Random random = new Random(1491); for (int zoom = 0; zoom <= MAX_ZOOM_LEVEL; zoom++) { int numIterations = Math.min(1000, (int) Math.pow(4, zoom)); for (int iter = 0; iter < numIterations; iter++) { BingTile expected = BingTile.fromCoordinates( random.nextInt(1 << zoom), random.nextInt(1 << zoom), zoom); BingTile actual = BingTile.decode(expected.encode()); assertEquals(actual, expected); } } }

Target:
public void testBingTileEncoding() { for (int zoom = 0; zoom <= MAX_ZOOM_LEVEL; zoom++) { int maxValue = (1 << zoom) - 1; testEncodingRoundTrip(0, 0, zoom); testEncodingRoundTrip(0, maxValue, zoom); testEncodingRoundTrip(maxValue, 0, zoom); testEncodingRoundTrip(maxValue, maxValue, zoom); } }
Source:
public void setUpClass() throws Exception { mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault()); JcloudsLocation loc = (JcloudsLocation) mgmt.getLocationRegistry().resolve("jclouds:aws-ec2:us-west-2", ImmutableMap.of( "inboundPorts", ImmutableList.of(5985, 3389), "displayName", "AWS Oregon (Windows)", "imageNameRegex", ".*Windows.*2012.*", "hardwareId", "m3.medium", "useJcloudsSshInit", false)); machine = (JcloudsWinRmMachineLocation) loc.obtain(); }

Target:
public void setUpClass() throws Exception { mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault()); JcloudsLocation loc = (JcloudsLocation) mgmt.getLocationRegistry().resolve("jclouds:aws-ec2:us-west-2", ImmutableMap.<String, Object>builder() .put("inboundPorts", ImmutableList.of(5985, 3389)) .put("displayName", "AWS Oregon (Windows)") .put("imageOwner", "801119661308") .put("imageNameRegex", "Windows_Server-2012-R2_RTM-English-64Bit-Base-.*") .put("hardwareId", "m3.medium") .put("useJcloudsSshInit", false) .build()); machine = (JcloudsWinRmMachineLocation) loc.obtain(); }
Source:
public void setAgentConnected(boolean agentConnected) { this.agentConnected = agentConnected; }

Target:
protected void setAgentConnected(boolean agentConnected) { this.agentConnected = agentConnected; }
Source:
public void launchImageLibrary(final ReadableMap options, final Callback callback) { final Activity currentActivity = getCurrentActivity(); if (currentActivity == null) { responseHelper.invokeError(callback, "can't find current Activity"); return; } this.callback = callback; this.options = options; if (!permissionsCheck(currentActivity, callback, REQUEST_PERMISSIONS_FOR_LIBRARY)) { return; } parseOptions(this.options); int requestCode; Intent libraryIntent; if (pickVideo) { requestCode = REQUEST_LAUNCH_VIDEO_LIBRARY; libraryIntent = new Intent(Intent.ACTION_PICK); libraryIntent.setType("video/*"); } else { requestCode = REQUEST_LAUNCH_IMAGE_LIBRARY; libraryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); } if (libraryIntent.resolveActivity(reactContext.getPackageManager()) == null) { responseHelper.invokeError(callback, "Cannot launch photo library"); return; } try { currentActivity.startActivityForResult(Intent.createChooser(libraryIntent, "Choose gallery app"), requestCode); } catch (ActivityNotFoundException e) { e.printStackTrace(); responseHelper.invokeError(callback, "Cannot launch photo library"); } }

Target:
public void launchImageLibrary(final ReadableMap options, final Callback callback) { final Activity currentActivity = getCurrentActivity(); if (currentActivity == null) { responseHelper.invokeError(callback, "can't find current Activity"); return; } this.callback = callback; this.options = options; if (!permissionsCheck(currentActivity, callback, REQUEST_PERMISSIONS_FOR_LIBRARY)) { return; } parseOptions(this.options); int requestCode; Intent libraryIntent; if (pickVideo) { requestCode = REQUEST_LAUNCH_VIDEO_LIBRARY; libraryIntent = new Intent(Intent.ACTION_PICK); libraryIntent.setType("video/*"); } else { requestCode = REQUEST_LAUNCH_IMAGE_LIBRARY; libraryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); } if (libraryIntent.resolveActivity(reactContext.getPackageManager()) == null) { responseHelper.invokeError(callback, "Cannot launch photo library"); return; } try { String chooseWhichLibraryTitle = null; if (ReadableMapUtils.hasAndNotEmptyString(options, "chooseWhichLibraryTitle")) { chooseWhichLibraryTitle = options.getString("chooseWhichLibraryTitle"); } currentActivity.startActivityForResult(Intent.createChooser(libraryIntent, chooseWhichLibraryTitle), requestCode); } catch (ActivityNotFoundException e) { e.printStackTrace(); responseHelper.invokeError(callback, "Cannot launch photo library"); } }
Source:
private void evaluateGeoRepSessionStatus(CommandBase<?> rootCommand) { GlusterStorageSyncCommandParameters parameters = (GlusterStorageSyncCommandParameters) rootCommand.getParameters(); GlusterGeoRepSession session = geoRepDao.getById(parameters.getGeoRepSessionId()); if (session == null) { rootCommand.setCommandStatus(CommandStatus.FAILED); } switch (session.getStatus()) { case ACTIVE: boolean checkPointCompleted = true; for (GlusterGeoRepSessionDetails details : session.getSessionDetails()) { if (details.getCheckPointStatus().equals("COMPLETED")) { checkPointCompleted = true; } else { checkPointCompleted = false; } } if (checkPointCompleted) { invokeLiveMergeSnapshots(rootCommand, parameters); } case FAULTY: rootCommand.setCommandStatus(CommandStatus.FAILED); } }

Target:
private void evaluateGeoRepSessionStatus(CommandBase<?> rootCommand) { GlusterStorageSyncCommandParameters parameters = (GlusterStorageSyncCommandParameters) rootCommand.getParameters(); GlusterGeoRepSession session = geoRepDao.getById(parameters.getGeoRepSessionId()); if (session == null) { rootCommand.setCommandStatus(CommandStatus.FAILED); } switch (session.getStatus()) { case ACTIVE: if (session.isCheckPointCompleted()) { stopGeoRepSessionCommand(rootCommand, session); rootCommand.setCommandStatus(CommandStatus.SUCCEEDED); } case FAULTY: rootCommand.setCommandStatus(CommandStatus.FAILED); default: break; } }