auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public TmfXmlPatternSegmentField(Element element) { fName = element.getAttribute(TmfXmlStrings.NAME); fType = element.getAttribute(TmfXmlStrings.TYPE); fConstantValue = element.getAttribute(TmfXmlStrings.VALUE); fStateValue = null; if (fConstantValue.isEmpty()) { Element elementFieldStateValue = (Element) element.getElementsByTagName(TmfXmlStrings.STATE_VALUE).item(0); if (elementFieldStateValue == null) { throw new IllegalArgumentException(); } fStateValue = fModelFactory.createStateValue(elementFieldStateValue, fContainer, new ArrayList<ITmfXmlStateAttribute>()); } }

Target:
public TmfXmlPatternSegmentField(Element element) { fName = element.getAttribute(TmfXmlStrings.NAME); fType = element.getAttribute(TmfXmlStrings.TYPE); String constantValue = element.getAttribute(TmfXmlStrings.VALUE); if (constantValue.isEmpty()) { fStateValue = null; Element elementFieldStateValue = (Element) element.getElementsByTagName(TmfXmlStrings.STATE_VALUE).item(0); if (elementFieldStateValue == null) { throw new IllegalArgumentException(); } fXmlStateValue = fModelFactory.createStateValue(elementFieldStateValue, fContainer, new ArrayList<ITmfXmlStateAttribute>()); } else { switch (fType) { case TmfXmlStrings.TYPE_INT: fStateValue = TmfStateValue.newValueInt(Integer.parseInt(constantValue)); break; case TmfXmlStrings.TYPE_LONG: fStateValue = TmfStateValue.newValueLong(Long.parseLong(constantValue)); break; case TmfXmlStrings.TYPE_STRING: fStateValue = TmfStateValue.newValueString(constantValue); break; case TmfXmlStrings.TYPE_NULL: fStateValue = TmfStateValue.nullValue(); break; default: throw new IllegalArgumentException("pattern segment field : invalid type of field"); } fXmlStateValue = null; } }
Source:
private void removeIdFromSelectedIds(Integer position) { Set<Integer> newSet = new HashSet<>(); for (Integer selectedPatientsId : selectedPatientPositions) { if(!selectedPatientsId.equals(position)){ newSet.add(selectedPatientsId); } } selectedPatientPositions = newSet; if (selectedPatientPositions.size() == 0 && isLongClicked && enableDownload) { enableDownload = false; if (actionMode != null) { MenuItem item = actionMode.getMenu().findItem(R.id.action_download); item.setEnabled(false); item.getIcon().setAlpha(128); } } }

Target:
private void removeIdFromSelectedIds(Integer position) { Set<Integer> newSet = new HashSet<>(); for (Integer selectedPatientsId : selectedPatientPositions) { if(!selectedPatientsId.equals(position)){ newSet.add(selectedPatientsId); } } selectedPatientPositions = newSet; if (selectedPatientPositions.size() == 0 && isLongClicked && enableDownload) toggleDownloadButton(); }
Source:
protected synchronized void updateStatsRow(Object rowKey, Object rowValues[]) { long currentTime = System.nanoTime(); long currentWaitTime; SiteTasker nextTask = m_tasks.peek(); if (nextTask == null) { currentWaitTime = 0; } else { currentWaitTime = currentTime - nextTask.getTimestamp(); } long maxWaitTimeInWindow = Math.max(currentWaitTime, m_recentMaxWaitTime); long totalWaitTimeInWindow = 0; long totalPollCountInWindow = 0; if (!m_historicalData.isEmpty()) { for (QueueStatus status : m_historicalData) { if (status.timestamp >= currentTime - m_maxWaitTimeWindowSize) { maxWaitTimeInWindow = Math.max(maxWaitTimeInWindow, status.maxWait); totalWaitTimeInWindow += status.totalWait; totalPollCountInWindow += status.pollCount; } } } rowValues[columnNameToIndex.get("CURRENT_DEPTH")] = m_depth; rowValues[columnNameToIndex.get("POLL_COUNT")] = totalPollCountInWindow; rowValues[columnNameToIndex.get("AVG_WAIT")] = totalWaitTimeInWindow / Math.max(1, totalPollCountInWindow); rowValues[columnNameToIndex.get("MAX_WAIT")] = maxWaitTimeInWindow; super.updateStatsRow(rowKey, rowValues); }

Target:
protected synchronized void updateStatsRow(Object rowKey, Object rowValues[]) { long currentTime = System.nanoTime(); long currentWaitTime; SiteTasker nextTask = m_tasks.peek(); if (nextTask == null) { currentWaitTime = 0; } else { currentWaitTime = currentTime - nextTask.getQueueOfferTime(); } long maxWaitTimeInWindow = Math.max(currentWaitTime, m_recentMaxWaitTime); long totalWaitTimeInWindow = 0; long totalPollCountInWindow = 0; if (!m_historicalData.isEmpty()) { for (QueueStatus status : m_historicalData) { if (status.timestamp >= currentTime - m_maxWaitTimeWindowSize) { maxWaitTimeInWindow = Math.max(maxWaitTimeInWindow, status.maxWait); totalWaitTimeInWindow += status.totalWait; totalPollCountInWindow += status.pollCount; } } } rowValues[columnNameToIndex.get("CURRENT_DEPTH")] = m_depth; rowValues[columnNameToIndex.get("POLL_COUNT")] = totalPollCountInWindow; rowValues[columnNameToIndex.get("AVG_WAIT")] = (totalWaitTimeInWindow / Math.max(1, totalPollCountInWindow)) / 1000; rowValues[columnNameToIndex.get("MAX_WAIT")] = maxWaitTimeInWindow / 1000; super.updateStatsRow(rowKey, rowValues); }
Source:
@Override public void start(Listener<RespT> responseListener, Metadata headers) { GrpcClientRequest request = new GrpcClientRequest(nameToKey, method, callOptions, delegate(), headers); Span span = handler.handleSendWithParent(request, invocationContext); spanRef.set(span); responseListener = new TracingClientCallListener<>( responseListener, invocationContext, spanRef, request ); try (Scope scope = currentTraceContext.maybeScope(span.context())) { super.start(responseListener, headers); } catch (Throwable e) { propagateIfFatal(e); spanRef.getAndSet(null); if (span != null) span.error(e).finish(); throw e; } }

Target:
@Override public void start(Listener<RespT> responseListener, Metadata headers) { GrpcClientRequest request = new GrpcClientRequest(nameToKey, method, callOptions, delegate(), headers); Span span = handler.handleSendWithParent(request, invocationContext); spanRef.set(span); responseListener = new TracingClientCallListener<>( responseListener, invocationContext, spanRef, request ); try (Scope scope = currentTraceContext.maybeScope(span.context())) { super.start(responseListener, headers); } catch (Throwable e) { propagateIfFatal(e); spanRef.set(null); if (span != null) span.error(e).finish(); throw e; } }
Source:
public Response sendLogoutRequest(@QueryParam("EncryptedNameIdTime") String encryptedNameIdTime) { String nameIdTime = encryptionService.decrypt(encryptedNameIdTime); String[] nameIdTimeArray = StringUtils.split(nameIdTime, "\n"); if (nameIdTimeArray.length == 2) { try { String name = nameIdTimeArray[0]; Long time = Long.parseLong(nameIdTimeArray[1]); if (System.currentTimeMillis() - time > logOutPageTimeOut) { String msg = String.format( "Logout request was older than %sms old so it was rejected. Please refresh page and request again.", logOutPageTimeOut); LOGGER.info(msg); return buildLogoutResponse(msg); } SecurityToken IdpSecToken = getIdpSecurityToken(); if (IdpSecToken == null) { LOGGER.info("Unable to logout. Please try again."); return buildLogoutResponse("Unable to logout. Please try again."); } List<String> sessionIndexes = new SecurityAssertionImpl(IdpSecToken) .getAuthnStatements() .stream() .filter(Objects::nonNull) .map(AuthnStatement::getSessionIndex) .collect(Collectors.toList()); logout(); LogoutRequest logoutRequest = logoutMessage.buildLogoutRequest(name, getEntityId(), sessionIndexes); String relayState = relayStates.encode(name); return getLogoutRequest(relayState, logoutRequest); } catch (RuntimeException e) { LOGGER.info(UNABLE_TO_CREATE_LOGOUT_REQUEST, e); return buildLogoutResponse(UNABLE_TO_CREATE_LOGOUT_REQUEST); } } else { LOGGER.info(UNABLE_TO_DECRYPT_LOGOUT_REQUEST); return buildLogoutResponse(UNABLE_TO_DECRYPT_LOGOUT_REQUEST); } }

Target:
public Response sendLogoutRequest(@QueryParam("EncryptedNameIdTime") String encryptedNameIdTime) { String nameIdTime = encryptionService.decrypt(encryptedNameIdTime); String[] nameIdTimeArray = StringUtils.split(nameIdTime, "\n"); if (nameIdTimeArray.length == 2) { try { String name = nameIdTimeArray[0]; Long time = Long.parseLong(nameIdTimeArray[1]); if (System.currentTimeMillis() - time > logOutPageTimeOut) { String msg = String.format( "Logout request was older than %sms old so it was rejected. Please refresh page and request again.", logOutPageTimeOut); LOGGER.info(msg); return buildLogoutResponse(msg); } SecurityToken idpSecToken = getIdpSecurityToken(); if (idpSecToken == null) { LOGGER.info("Unable to logout. Please try again."); return buildLogoutResponse("Unable to logout. Please try again."); } List<String> sessionIndexes = new SecurityAssertionImpl(idpSecToken) .getAuthnStatements() .stream() .filter(Objects::nonNull) .map(AuthnStatement::getSessionIndex) .collect(Collectors.toList()); logout(); LogoutRequest logoutRequest = logoutMessage.buildLogoutRequest(name, getEntityId(), sessionIndexes); String relayState = relayStates.encode(name); return getLogoutRequest(relayState, logoutRequest); } catch (RuntimeException e) { LOGGER.info(UNABLE_TO_CREATE_LOGOUT_REQUEST, e); return buildLogoutResponse(UNABLE_TO_CREATE_LOGOUT_REQUEST); } } else { LOGGER.info(UNABLE_TO_DECRYPT_LOGOUT_REQUEST); return buildLogoutResponse(UNABLE_TO_DECRYPT_LOGOUT_REQUEST); } }
Source:
protected boolean applyDecorator(View view, RecyclerView parent) { RecyclerView.Adapter adapter = parent.getAdapter(); int position = parent.getChildAdapterPosition(view); int size = adapter.getItemCount(); return size - 1 != position && adapter.getItemViewType(position + 1) == HEADER_TYPE; }

Target:
protected boolean applyDecorator(View view, RecyclerView parent) { RecyclerView.Adapter adapter = parent.getAdapter(); int position = parent.getChildAdapterPosition(view); return adapter.getItemViewType(position + 1) == HEADER_TYPE; }
Source:
public void buildShellScriptAfterDisconnect() throws Exception { story.then( s -> { Node node = TestUtils.createSwarmClient( story.j, processDestroyer, tmpDir.newFolder()); WorkflowJob project = story.j.createProject(WorkflowJob.class); project.setConcurrentBuild(false); project.setDefinition(new CpsFlowDefinition(getFlow(node, 1), true)); WorkflowRun build = project.scheduleBuild2(0).waitForStart(); SemaphoreStep.waitForStart("wait-0/1", build); tearDown(); TestUtils.createSwarmClient( node.getNodeName(), story.j, processDestroyer, tmpDir.newFolder()); SemaphoreStep.success("wait-0/1", null); story.j.waitForCompletion(build); story.j.assertLogContains("ON_SWARM_CLIENT=true", build); story.j.assertBuildStatusSuccess(build); tearDown(); }); }

Target:
public void buildShellScriptAfterDisconnect() throws Exception { story.then( s -> { Node node = TestUtils.createSwarmClient(story.j, processDestroyer, temporaryFolder); WorkflowJob project = story.j.createProject(WorkflowJob.class); project.setConcurrentBuild(false); project.setDefinition(new CpsFlowDefinition(getFlow(node, 1), true)); WorkflowRun build = project.scheduleBuild2(0).waitForStart(); SemaphoreStep.waitForStart("wait-0/1", build); tearDown(); TestUtils.createSwarmClient( node.getNodeName(), story.j, processDestroyer, temporaryFolder); SemaphoreStep.success("wait-0/1", null); story.j.assertBuildStatusSuccess(story.j.waitForCompletion(build)); story.j.assertLogContains("ON_SWARM_CLIENT=true", build); tearDown(); }); }
Source:
public static CommandRequest payForOrder(UserId userId, OrderId orderId) { final BillingInfo billingInfo = BillingInfo.newBuilder().setInfo("Payment info is here.").build(); final PayForOrder command = PayForOrder.newBuilder() .setOrderId(orderId) .setBillingInfo(billingInfo) .build(); return newCommandRequest(userId, command); }

Target:
public static CommandRequest payForOrder(UserId userId, OrderId orderId) { final BillingInfo billingInfo = BillingInfo.newBuilder().setInfo("Payment info is here.").build(); final PayForOrder command = PayForOrder.newBuilder() .setOrderId(orderId) .setBillingInfo(billingInfo) .build(); final CommandRequest result = newCommandRequest(userId, command); return result; }
Source:
public Schema capture() throws SQLException { LOGGER.debug("Capturing schema"); ArrayList<Database> databases = new ArrayList<>(); ResultSet rs = connection.createStatement().executeQuery( "SELECT SCHEMA_NAME, DEFAULT_CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.SCHEMATA" ); while (rs.next()) { String dbName = rs.getString("SCHEMA_NAME"); String charset = rs.getString("DEFAULT_CHARACTER_SET_NAME"); if (includeDatabases.size() > 0 && !includeDatabases.contains(dbName)) continue; if (IGNORED_DATABASES.contains(dbName)) continue; Database db = new Database(dbName, charset); databases.add(db); } rs.close(); int size = databases.size(); LOGGER.debug("Augmenting " + size + " databases with tables"); int counter = 1; for (Database db : databases) { LOGGER.debug(counter + "/" + size + " Augmenting " + db.getName()); long start = System.currentTimeMillis(); captureDatabase(db); long end = System.currentTimeMillis(); LOGGER.debug(counter + "/" + size + " Augmented " + db.getName() + " after " + (end - start) + "ms"); counter++; } LOGGER.debug("Databases Augmented!"); return new Schema(databases, captureDefaultCharset(), this.sensitivity); }

Target:
public Schema capture() throws SQLException { LOGGER.debug("Capturing schemas..."); ArrayList<Database> databases = new ArrayList<>(); ResultSet rs = connection.createStatement().executeQuery( "SELECT SCHEMA_NAME, DEFAULT_CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.SCHEMATA" ); while (rs.next()) { String dbName = rs.getString("SCHEMA_NAME"); String charset = rs.getString("DEFAULT_CHARACTER_SET_NAME"); if (includeDatabases.size() > 0 && !includeDatabases.contains(dbName)) continue; if (IGNORED_DATABASES.contains(dbName)) continue; Database db = new Database(dbName, charset); databases.add(db); } rs.close(); int size = databases.size(); LOGGER.debug("Starting schema capture of " + size + " databases..."); int counter = 1; for (Database db : databases) { LOGGER.debug(counter + "/" + size + " Capturing " + db.getName() + "..."); captureDatabase(db); counter++; } LOGGER.debug(size + " database schemas captured!"); return new Schema(databases, captureDefaultCharset(), this.sensitivity); }
Source:
public void shouldInterleaveChargesAndRefundsIfFeatureEnabled() throws Exception { addChargeAndCardDetails(CREATED, "ref-1", now().minusDays(2)); String externalChargeId = addChargeAndCardDetails(CAPTURED, "ref-3", now().minusDays(1)); Long chargeId = Long.parseLong(StringUtils.removeStart(externalChargeId, "charge")); createNewRefundWith(REFUND_SUBMITTED, 10L, chargeId, "refund_ref"); addChargeAndCardDetails(AUTHORISATION_READY, "ref-2", now()); ValidatableResponse response = getChargeApi .withAccountId(accountId) .withQueryParam("from_date", DateTimeUtils.toUTCDateTimeString(now().minusDays(1))) .withQueryParam("to_date", DateTimeUtils.toUTCDateTimeString(now().plusDays(1))) .withHeader(HttpHeaders.ACCEPT, APPLICATION_JSON) .withHeader(FEATURES_HEADER, FEATURE_REFUNDS_IN_TX_LIST) .getTransactions() .statusCode(OK.getStatusCode()) .contentType(JSON) .body("results.size()", is(3)) .body("results[0].transaction_type", is("charge")) .body("results[1].transaction_type", is("charge")) .body("results[2].transaction_type", is("refund") ); }

Target:
public void shouldInterleaveChargesAndRefundsIfFeatureEnabled() throws Exception { addChargeAndCardDetails(CREATED, "ref-1", now().minusDays(2)); String externalChargeId = addChargeAndCardDetails(CAPTURED, "ref-3", now().minusDays(1)); Long chargeId = Long.parseLong(StringUtils.removeStart(externalChargeId, "charge")); createNewRefundWith(REFUND_SUBMITTED, 10L, chargeId, "refund_ref"); addChargeAndCardDetails(AUTHORISATION_READY, "ref-2", now()); ValidatableResponse response = getChargeApi .withAccountId(accountId) .withQueryParam("from_date", DateTimeUtils.toUTCDateTimeString(now().minusDays(1))) .withQueryParam("to_date", DateTimeUtils.toUTCDateTimeString(now().plusDays(1))) .withHeader(HttpHeaders.ACCEPT, APPLICATION_JSON) .withHeader(FEATURES_HEADER, FEATURE_REFUNDS_IN_TX_LIST) .getTransactions() .statusCode(OK.getStatusCode()) .contentType(JSON) .body("results.size()", is(3)) .body("results[0].transaction_type", is("charge")) .body("results[1].transaction_type", is("refund")) .body("results[2].transaction_type", is("charge") ); }
Source:
public Multihash put(byte[] data, boolean isRaw, TransactionId tid, PublicKeyHash owner) { Histogram.Timer writeTimer = writeTimerLog.labels("write").startTimer(); Multihash hash = new Multihash(Multihash.Type.sha2_256, Hash.sha256(data)); Cid cid = new Cid(1, isRaw ? Cid.Codec.Raw : Cid.Codec.DagCbor, hash.type, hash.getHash()); String key = hashToKey(cid); try { transactions.addBlock(cid, tid, owner); String s3Key = folder + key; Map<String, String> extraHeaders = new TreeMap<>(); extraHeaders.put("Content-Type", "application/octet-stream"); extraHeaders.put("User-Agent", "Bond, James Bond"); boolean hashContent = true; String contentHash = hashContent ? ArrayOps.bytesToHex(hash.getHash()) : "UNSIGNED-PAYLOAD"; PresignedUrl putUrl = S3Request.preSignPut(s3Key, data.length, contentHash, false, ZonedDateTime.now(), host, extraHeaders, region, accessKeyId, secretKey); HttpUtil.put(putUrl, data); return cid; } catch (IOException e) { LOG.log(Level.SEVERE, e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } finally { writeTimer.observeDuration(); } }

Target:
public Multihash put(byte[] data, boolean isRaw, TransactionId tid, PublicKeyHash owner) { Histogram.Timer writeTimer = writeTimerLog.labels("write").startTimer(); Multihash hash = new Multihash(Multihash.Type.sha2_256, Hash.sha256(data)); Cid cid = new Cid(1, isRaw ? Cid.Codec.Raw : Cid.Codec.DagCbor, hash.type, hash.getHash()); String key = hashToKey(cid); try { transactions.addBlock(cid, tid, owner); String s3Key = folder + key; Map<String, String> extraHeaders = new TreeMap<>(); extraHeaders.put("Content-Type", "application/octet-stream"); boolean hashContent = true; String contentHash = hashContent ? ArrayOps.bytesToHex(hash.getHash()) : "UNSIGNED-PAYLOAD"; PresignedUrl putUrl = S3Request.preSignPut(s3Key, data.length, contentHash, false, ZonedDateTime.now(), host, extraHeaders, region, accessKeyId, secretKey); HttpUtil.put(putUrl, data); return cid; } catch (IOException e) { LOG.log(Level.SEVERE, e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } finally { writeTimer.observeDuration(); } }
Source:
public ActionResult execute() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String studentEmail = getNonNullRequestParamValue(Const.ParamsNames.STUDENT_EMAIL); String emailType = getNonNullRequestParamValue(Const.ParamsNames.EMAIL_TYPE); String feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); CourseAttributes course = logic.getCourse(courseId); Assumption.assertNotNull(course); StudentAttributes student = logic.getStudentForEmail(courseId, studentEmail); Assumption.assertNotNull(student); EmailWrapper email; if (emailType.equals(EmailType.STUDENT_COURSE_JOIN.name())) { email = emailGenerator.generateStudentCourseJoinEmail(course, student); } else if (emailType.equals(EmailType.FEEDBACK_SESSION_REMINDER.name())) { if (feedbackSessionName == null) { throw new InvalidHttpParameterException("Feedback session name not specified"); } FeedbackSessionAttributes feedbackSession = logic.getFeedbackSession(feedbackSessionName, courseId); email = emailGenerator.generateFeedbackSessionStudentReminderEmail(feedbackSession, student); } else { throw new InvalidHttpParameterException("Unknown emailType " + emailType); } return new JsonResult(new EmailData(email)); }

Target:
public ActionResult execute() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String studentEmail = getNonNullRequestParamValue(Const.ParamsNames.STUDENT_EMAIL); String emailType = getNonNullRequestParamValue(Const.ParamsNames.EMAIL_TYPE); String feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); CourseAttributes course = logic.getCourse(courseId); Assumption.assertNotNull(course); StudentAttributes student = logic.getStudentForEmail(courseId, studentEmail); Assumption.assertNotNull(student); EmailWrapper email; if (emailType.equals(EmailType.STUDENT_COURSE_JOIN.name())) { email = emailGenerator.generateStudentCourseJoinEmail(course, student); } else if (emailType.equals(EmailType.FEEDBACK_SESSION_REMINDER.name())) { if (feedbackSessionName == null) { throw new InvalidHttpParameterException("Feedback session name not specified"); } FeedbackSessionAttributes feedbackSession = logic.getFeedbackSession(feedbackSessionName, courseId); email = emailGenerator.generateFeedbackSessionStudentReminderEmail(feedbackSession, student); } else { throw new InvalidHttpParameterException("Email type " + emailType + " not accepted"); } return new JsonResult(new EmailData(email)); }
Source:
public void testGetStrippedVdsUniqueIdWithUnacceptedChars() { RegisterVdsParameters paramsMock = getQueryParameters(); when(paramsMock.getVdsUniqueId()).thenReturn("Test_^123^"); String result = getQuery().getStrippedVdsUniqueId(); assertEquals("Test_123", result); }

Target:
public void testGetStrippedVdsUniqueIdWithUnacceptedChars() { RegisterVdsParameters paramsMock = getQueryParameters(); when(paramsMock.getVdsUniqueId()).thenReturn("Test_^123^"); String result = getQuery().getStrippedVdsUniqueId(); assertEquals("Vds id doesn't equal to the expected value", "Test_123", result); }
Source:
public void testPipetteAfterBrushOnSingleLayer() { onDrawingSurfaceView() .perform(touchAt(DrawingSurfaceLocationProvider.MIDDLE)); onDrawingSurfaceView() .checkPixelColor(Color.BLACK, BitmapLocationProvider.MIDDLE); onColorPickerView() .performOpenColorPicker(); onView(allOf(withId(R.id.color_picker_tab_icon), withBackground(R.drawable.ic_color_picker_tab_rgba))).perform(click()); onView(withId(R.id.color_picker_color_rgb_hex)).perform(replaceText("#00000000")); onColorPickerView() .onOkButton() .perform(click()); onToolProperties() .checkMatchesColor(Color.TRANSPARENT); onToolBarView() .performSelectTool(ToolType.PIPETTE); onDrawingSurfaceView() .perform(touchAt(DrawingSurfaceLocationProvider.MIDDLE)); onToolProperties() .checkMatchesColor(Color.BLACK); }

Target:
public void testPipetteAfterBrushOnSingleLayer() { onDrawingSurfaceView() .perform(touchAt(DrawingSurfaceLocationProvider.MIDDLE)); onDrawingSurfaceView() .checkPixelColor(Color.BLACK, BitmapLocationProvider.MIDDLE); onToolProperties() .setColorResource(R.color.pocketpaint_color_picker_transparent) .checkMatchesColor(Color.TRANSPARENT); onToolBarView() .performSelectTool(ToolType.PIPETTE); onDrawingSurfaceView() .perform(touchAt(DrawingSurfaceLocationProvider.MIDDLE)); onToolProperties() .checkMatchesColor(Color.BLACK); }
Source:
public By buildBy() { assertValidAnnotations(); By defaultBy = buildDefaultBy(); By mobileNativeBy = buildMobileNativeBy(); if (defaultBy == null) defaultBy = new ByIdOrName(((Field) annotatedElementContainer.getAnnotated()).getName()); if (mobileNativeBy == null) mobileNativeBy = defaultBy; Map<ContentType, By> contentMap = new HashMap<>(); contentMap.put(ContentType.HTML_OR_DEFAULT, defaultBy); contentMap.put(ContentType.NATIVE_MOBILE_SPECIFIC, mobileNativeBy); return new ContentMappedBy(contentMap); }

Target:
public By buildBy() { assertValidAnnotations(); By defaultBy = buildDefaultBy(); By mobileNativeBy = buildMobileNativeBy(); if (defaultBy == null) { defaultBy = new ByIdOrName(((Field) annotatedElementContainer.getAnnotated()).getName()); } if (mobileNativeBy == null) { mobileNativeBy = defaultBy; } Map<ContentType, By> contentMap = new HashMap<>(); contentMap.put(ContentType.HTML_OR_DEFAULT, defaultBy); contentMap.put(ContentType.NATIVE_MOBILE_SPECIFIC, mobileNativeBy); return new ContentMappedBy(contentMap); }
Source:
public IntegrationGraphCorsConfigurer(String path, String[] allowedOrigins) { this.path = path; this.allowedOrigins = allowedOrigins; }

Target:
private IntegrationGraphCorsConfigurer(String path, String[] allowedOrigins) { this.path = path; this.allowedOrigins = allowedOrigins; }
Source:
public String getValue(String key) { if (key.startsWith(CLASSPATH)) { final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); String classpathResource = key.substring(CLASSPATH.length(), key.length() - 1); final URL resource = contextClassLoader.getResource(classpathResource); if (resource == null) { logger.warning(String.format("Resource %s is not find in classspath and it is not replaced.", classpathResource)); return null; } return resource.toString(); } return null; }

Target:
public String getValue(String key) { if (key.startsWith(CLASSPATH)) { final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); String classpathResource = key.substring(CLASSPATH.length(), key.length() - 1); final URL resource = contextClassLoader.getResource(classpathResource); if (resource == null) { logger.warning(String.format("Resource %s is not found on the classspath so the property %s is not replaced.", classpathResource, key)); return null; } return resource.toString(); } return null; }
Source:
private String getDescription( Method paramMethod ) { if( paramMethod.isAnnotationPresent( Hidden.class ) ) { return ""; } Description description = paramMethod.getAnnotation( Description.class ); if( description != null ) { return description.value(); } As as = paramMethod.getAnnotation( As.class ); return ReflectionUtil .newInstance( as == null ? DefaultAsProvider.class : as.provider() ) .as( as, paramMethod ); }

Target:
private String getDescription( Method paramMethod ) { if( paramMethod.isAnnotationPresent( Hidden.class ) ) { return ""; } Description description = paramMethod.getAnnotation( Description.class ); if( description != null ) { return description.value(); } As as = paramMethod.getAnnotation( As.class ); AsProvider provider = as != null ? ReflectionUtil.newInstance( as.provider() ) : new DefaultAsProvider(); return provider.as( as, paramMethod ); }
Source:
default long getVolume() { try { if (getClass().getMethod("getArea").getDeclaringClass().equals(this.getClass())) { throw new IllegalStateException("Class " + getClass().getName() + " must override either getVolume or getArea."); } } catch (NoSuchMethodException e) { e.printStackTrace(); } return getArea(); }

Target:
default long getVolume() { try { if (getClass().getMethod("getArea").getDeclaringClass().equals(RegionSelector.class)) { throw new IllegalStateException("Class " + getClass().getName() + " must override getVolume."); } } catch (NoSuchMethodException e) { throw new AssertionError(e); } return getArea(); }
Source:
private static void loadLatestStitchPseudoComponents() { try { URL stitchConnectorURL = new URL(STITCH_DATA_CONNECTOR_JSON_URL); HttpsURLConnection con = (HttpsURLConnection) stitchConnectorURL.openConnection(); InputStream ins = con.getInputStream(); String resourceString = IOUtils.toString(ins, "UTF-8"); ins.close(); readFromJsonString(resourceString); } catch (IOException | JSONException e) { loadDefaultStitchConnectorList(); } }

Target:
private static void loadLatestStitchPseudoComponents() { try { URL stitchConnectorURL = new URL(STITCH_DATA_CONNECTOR_JSON_URL); HttpsURLConnection urlc = (HttpsURLConnection) stitchConnectorURL.openConnection(); urlc.setConnectTimeout(2000); urlc.setReadTimeout(2000); InputStream ins = urlc.getInputStream(); String resourceString = IOUtils.toString(ins, "UTF-8"); ins.close(); readFromJsonString(resourceString); } catch (IOException | JSONException e) { loadDefaultStitchConnectorList(); } }
Source:
public List<Item> findAllByCrfVersionId(Integer crfVersionId) { String query = "select distinct i.* from item i, item_form_metadata ifm " + "where i.item_id= ifm.item_id " + "and ifm.crf_version_id=?"; org.hibernate.Query q = getCurrentSession().createSQLQuery(query).addEntity(Item.class); q.setParameter(0, crfVersionId.intValue()); return (List<Item>) q.list(); }

Target:
public List<Item> findAllByCrfVersionId(Integer crfVersionId) { Query q = getCurrentSession().createSQLQuery(findAllByCrfVersionIdQuery).addEntity(Item.class); q.setInteger("crfversionid", crfVersionId.intValue()); return (List<Item>) q.list(); }
Source:
private void verifyCheckpoint(Set<Container> containers) { }

Target:
private void verifyCheckpoint(Set<Container> containers) throws CloudStorageException { long maxDeleteTimestamp = containers.stream().max(Comparator.comparing(Container::getDeleteTriggerTime)).get().getDeleteTriggerTime(); Assert.assertEquals(azureContainerCompactor.getLatestContainerDeletionTime(), maxDeleteTimestamp); }
Source:
public void init(boolean waitTillFinished) throws SiteContextInitializationException { if (state == State.CREATED) { publishEvent(new SiteContextCreatedEvent(this)); Runnable initTask = () -> { SiteContext.setCurrent(this); try { logger.info("--------------------------------------------------"); logger.info("<Initializing context site: " + siteName + ">"); logger.info("--------------------------------------------------"); if (cacheWarmer != null) { cacheWarmer.warmUpCache(this, false); } buildGraphQLSchema(); executeInitScript(); state = State.INITIALIZED; logger.info("--------------------------------------------------"); logger.info("</Initializing context site: " + siteName + ">"); logger.info("--------------------------------------------------"); publishEvent(new SiteContextInitializedEvent(this)); initializationLatch.countDown(); } finally { SiteContext.clear(); } }; if (waitTillFinished) { Future<?> future = maintenanceTaskExecutor.submit(initTask); try { future.get(); } catch (InterruptedException | ExecutionException e) { throw new SiteContextInitializationException("Error while waiting for context init", e); } } else { maintenanceTaskExecutor.execute(initTask); } } }

Target:
public void init(boolean waitTillFinished) throws SiteContextInitializationException { if (state == State.CREATED) { publishEvent(new SiteContextCreatedEvent(this)); Runnable initTask = () -> { SiteContext.setCurrent(this); try { logger.info("--------------------------------------------------"); logger.info("<Initializing context site: " + siteName + ">"); logger.info("--------------------------------------------------"); if (cacheWarmer != null) { cacheWarmer.warmUpCache(this, false); } buildGraphQLSchema(); executeInitScript(); state = State.INITIALIZED; logger.info("--------------------------------------------------"); logger.info("</Initializing context site: " + siteName + ">"); logger.info("--------------------------------------------------"); publishEvent(new SiteContextInitializedEvent(this)); } finally { initializationLatch.countDown(); SiteContext.clear(); } }; if (waitTillFinished) { Future<?> future = maintenanceTaskExecutor.submit(initTask); try { future.get(); } catch (InterruptedException | ExecutionException e) { throw new SiteContextInitializationException("Error while waiting for context init", e); } } else { maintenanceTaskExecutor.execute(initTask); } } }
Source:
public void testSameInstanceForSameForceReturnValues() { RemoteCache<String, String> rcDontForceReturn = remoteCacheManager.getCache(false); RemoteCache<String, String> rcDontForceReturn2 = remoteCacheManager.getCache(false); assert rcDontForceReturn == rcDontForceReturn2; RemoteCache<String, String> rcForceReturn = remoteCacheManager.getCache(true); RemoteCache<String, String> rcForceReturn2 = remoteCacheManager.getCache(true); assert rcForceReturn == rcForceReturn2; }

Target:
public void testSameInstanceForSameForceReturnValues() { RemoteCache<String, String> rcDontForceReturn = remoteCacheManager.getCache(false); RemoteCache<String, String> rcDontForceReturn2 = remoteCacheManager.getCache(false); assertSame("RemoteCache instances should be the same", rcDontForceReturn, rcDontForceReturn2); RemoteCache<String, String> rcForceReturn = remoteCacheManager.getCache(true); RemoteCache<String, String> rcForceReturn2 = remoteCacheManager.getCache(true); assertSame("RemoteCache instances should be the same", rcForceReturn, rcForceReturn2); }
Source:
public BlobStore createInstance(TileLayerDispatcher layers, LockProvider lockProvider) throws StorageException { checkNotNull(layers); checkState(getName() != null); checkState( isEnabled(), "Can't call S3BlobStoreConfig.createInstance() is blob store is not enabled"); return new AzureBlobStore(this, layers, lockProvider); }

Target:
public BlobStore createInstance(TileLayerDispatcher layers, LockProvider lockProvider) throws StorageException { checkNotNull(layers); checkState(getName() != null); checkState( isEnabled(), "Can't call AzureBlobStoreConfig.createInstance() is blob store is not enabled"); return new AzureBlobStore(this, layers, lockProvider); }
Source:
public ClusterParticipant getClusterParticipant() throws IOException { if (clusterParticipant == null) { clusterParticipant = helixClusterAgentsFactory.getClusterParticipant(); } return clusterParticipant; }

Target:
public ClusterParticipant getClusterParticipant() throws IOException { if (clusterParticipantRef.get() == null) { ClusterParticipant clusterParticipant = new ClusterParticipant() { @Override public void participate(List<AmbryHealthReport> ambryHealthReports) { } @Override public void close() { } @Override public boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { return false; } @Override public boolean setReplicaStoppedState(List<ReplicaId> replicaIds, boolean markStop) { return false; } @Override public List<String> getSealedReplicas() { return Collections.emptyList(); } @Override public List<String> getStoppedReplicas() { return Collections.emptyList(); } @Override public void registerPartitionStateChangeListener(StateModelListenerType listenerType, PartitionStateChangeListener partitionStateChangeListener) { } @Override public ReplicaSyncUpManager getReplicaSyncUpManager() { return null; } @Override public boolean updateDataNodeInfoInCluster(ReplicaId replicaId, boolean shouldExist) { return false; } }; clusterParticipantRef.compareAndSet(null, clusterParticipant); } return clusterParticipantRef.get(); }
Source:
public boolean isDeprecated() { AttributeDefinition def = StyleResolver.getAttributeDefinition(mySourceTheme.getConfiguration(), myItemResourceValue); String doc = (def == null) ? null : def.getDocValue(null); return (doc != null && StringUtil.containsIgnoreCase(doc, "deprecated")); }

Target:
public boolean isDeprecated() { AttributeDefinition def = StyleResolver.getAttributeDefinition(mySourceTheme.getConfiguration(), myItemResourceValue); String doc = (def == null) ? null : def.getDocValue(null); return (doc != null && StringUtil.containsIgnoreCase(doc, DEPRECATED)); }
Source:
public List<WellKnownImage> get() { Iterable<StandardDrive> standardDrives = filter(api.listStandardDriveInfo(), new Predicate<StandardDrive>() { @Override public boolean apply(StandardDrive input) { return MediaType.DISK == input.getMedia(); } }); return newArrayList(transform(standardDrives, standardDriveToWellKnownImage)); }

Target:
public List<WellKnownImage> get() { ImmutableList.Builder<WellKnownImage> images = ImmutableList.builder(); for (StandardDrive drive : api.listStandardDriveInfo()) { if (drive.getMedia() == MediaType.DISK) { images.add(standardDriveToWellKnownImage.apply(drive)); } } return images.build(); }
Source:
FileStream open(final String path) throws IOException { final URL base = httpObjectsUrl; final URL u = new URL(base, path); final HttpConnection c = httpOpen(u); switch (HttpSupport.response(c)) { case HttpConnection.HTTP_OK: final InputStream in = openInputStream(c); if (!ENCODING_GZIP.equals(c.getHeaderField(HDR_CONTENT_ENCODING))) { final int len = c.getContentLength(); return new FileStream(in, len); } return new FileStream(in); case HttpConnection.HTTP_NOT_FOUND: throw new FileNotFoundException(u.toString()); default: throw new IOException(u.toString() + ": " + HttpSupport.response(c) + " " + c.getResponseMessage()); } }

Target:
FileStream open(final String path) throws IOException { final URL base = httpObjectsUrl; final URL u = new URL(base, path); final HttpConnection c = httpOpen(u); switch (HttpSupport.response(c)) { case HttpConnection.HTTP_OK: final InputStream in = openInputStream(c); if (!isGzipContent(c)) { final int len = c.getContentLength(); return new FileStream(in, len); } return new FileStream(in); case HttpConnection.HTTP_NOT_FOUND: throw new FileNotFoundException(u.toString()); default: throw new IOException(u.toString() + ": " + HttpSupport.response(c) + " " + c.getResponseMessage()); } }
Source:
public String toString() { ImmutableList.Builder<String> listBuilder = ImmutableList.builder(); listBuilder.add("StartpointKey") .add(systemStreamPartition.getSystem()) .add(systemStreamPartition.getStream()) .add(Integer.toString(systemStreamPartition.getPartition().getPartitionId())); if (taskName != null && StringUtils.isNotBlank(taskName.getTaskName())) { listBuilder.add(taskName.getTaskName()); } return String.join(":", listBuilder.build()); }

Target:
public String toString() { return Objects.toStringHelper(this).toString(); }
Source:
public Map<String, Object> toMap() { Map<String, Object> map = super.toMap(); map.put("pid", getPid()); map.put("hostAddress", getHostAddress()); map.put("name", getName()); map.put("logicalConnectionUid", getLogicalConnectionUid()); map.put("vmId", getVmId()); map.put("clientId", getClientId()); map.put("hostName", getHostName()); map.put("clientReportedAddress", this.clientReportedAddress != null ? this.clientReportedAddress : "UNKNOWN"); map.put("tags", getTags()); map.put("version", version != null ? version : "UNKNOWN"); map.put("connections", connectionStream().sorted(Comparator.comparing(AbstractNode::getId)).map(Connection::toMap).collect(Collectors.toList())); map.put("managementRegistry", getManagementRegistry().map(ManagementRegistry::toMap).orElse(null)); return map; }

Target:
public Map<String, Object> toMap() { Map<String, Object> map = super.toMap(); map.put("pid", getPid()); map.put("hostAddress", getHostAddress()); map.put("name", getName()); map.put("logicalConnectionUid", getLogicalConnectionUid()); map.put("vmId", getVmId()); map.put("clientId", getClientId()); map.put("hostName", getHostName()); map.put("tags", getTags()); map.put("properties", getProperties()); map.put("connections", connectionStream().sorted(Comparator.comparing(AbstractNode::getId)).map(Connection::toMap).collect(Collectors.toList())); map.put("managementRegistry", getManagementRegistry().map(ManagementRegistry::toMap).orElse(null)); return map; }
Source:
public boolean onLogin() throws LoginException { byte[] token = getToken(); GSSContext gssContext = acceptToken(token); validateAccess(gssContext); try { _name = gssContext.getSrcName().toString(); } catch (GSSException e) { throw new FailedLoginException("Failed to get a name. " + e.getMessage()); } return true; }

Target:
public boolean onLogin() throws LoginException { byte[] token = getToken(); GSSContext gssContext = acceptToken(token); registerRoles(gssContext); try { _name = gssContext.getSrcName().toString(); } catch (GSSException e) { throw new FailedLoginException("Failed to get a name. " + e.getMessage()); } return true; }
Source:
protected ToStringHelper string() { return Objects.toStringHelper(this) .add("addr", addr).add("version", version).add("macAddr", macAddr).add("type", type); }

Target:
protected ToStringHelper string() { return Objects.toStringHelper(this) .add("addr", addr).add("version", version).add("macAddr", macAddr.or("")).add("type", type.or("")); }
Source:
void translate(final TableScan tableScan, final TranslatorContext context) { StreamGraph streamGraph = context.getStreamGraph(); List<String> tableNameParts = tableScan.getTable().getQualifiedName(); String sourceName = SqlIOConfig.getSourceFromSourceParts(tableNameParts); Validate.isTrue(relMsgConverters.containsKey(sourceName), String.format("Unknown source %s", sourceName)); SqlIOConfig sqlIOConfig = systemStreamConfig.get(sourceName); final String systemName = sqlIOConfig.getSystemName(); final String streamName = sqlIOConfig.getStreamName(); KVSerde<Object, Object> noOpKVSerde = KVSerde.of(new NoOpSerde<>(), new NoOpSerde<>()); GenericInputDescriptor<KV<Object, Object>> inputStreamDescriptor = GenericInputDescriptor.from(streamName, systemName, noOpKVSerde); MessageStream<KV<Object, Object>> inputStream = streamGraph.getInputStream(inputStreamDescriptor); MessageStream<SamzaSqlRelMessage> samzaSqlRelMessageStream = inputStream.map(new ScanMapFunction(sourceName)); context.registerMessageStream(tableScan.getId(), samzaSqlRelMessageStream); }

Target:
void translate(final TableScan tableScan, final TranslatorContext context) { StreamGraph streamGraph = context.getStreamGraph(); List<String> tableNameParts = tableScan.getTable().getQualifiedName(); String sourceName = SqlIOConfig.getSourceFromSourceParts(tableNameParts); Validate.isTrue(relMsgConverters.containsKey(sourceName), String.format("Unknown source %s", sourceName)); SqlIOConfig sqlIOConfig = systemStreamConfig.get(sourceName); final String systemName = sqlIOConfig.getSystemName(); final String streamName = sqlIOConfig.getStreamName(); KVSerde<Object, Object> noOpKVSerde = KVSerde.of(new NoOpSerde<>(), new NoOpSerde<>()); DelegatingSystemDescriptor sd = context.getSystemDescriptors().computeIfAbsent(systemName, DelegatingSystemDescriptor::new); GenericInputDescriptor<KV<Object, Object>> isd = sd.getInputDescriptor(streamName, noOpKVSerde); MessageStream<KV<Object, Object>> inputStream = streamGraph.getInputStream(isd); MessageStream<SamzaSqlRelMessage> samzaSqlRelMessageStream = inputStream.map(new ScanMapFunction(sourceName)); context.registerMessageStream(tableScan.getId(), samzaSqlRelMessageStream); }
Source:
public void synchronizeGroupsStructures() { if(perunBl.isPerunReadOnly()) { log.debug("This instance is just read only so skip synchronization of groups structures."); return; } if (synchronizeGroupsStructuresRunning.compareAndSet(false, true)) { try { log.debug("Synchronizer starting synchronizing the groups structures"); this.perunBl.getGroupsManagerBl().synchronizeGroupsStructures(this.sess); if (!synchronizeGroupsStructuresRunning.compareAndSet(true, false)) { log.error("Synchronizer: group structure synchronization out of sync, resetting."); synchronizeGroupsStructuresRunning.set(false); } } catch (InternalErrorException e) { log.error("Cannot synchronize groups structures:", e); synchronizeGroupsStructuresRunning.set(false); } } else { log.debug("Synchronizer: group structure synchronization currently running."); } }

Target:
public void synchronizeGroupsStructures() { if(perunBl.isPerunReadOnly()) { log.warn("This instance is just read only so skip synchronization of groups structures."); return; } if (synchronizeGroupsStructuresRunning.compareAndSet(false, true)) { try { log.debug("Synchronizer starting synchronizing the groups structures"); this.perunBl.getGroupsManagerBl().synchronizeGroupsStructures(this.sess); synchronizeGroupsStructuresRunning.set(false); } catch (InternalErrorException e) { log.error("Cannot synchronize groups structures:", e); synchronizeGroupsStructuresRunning.set(false); } } else { log.debug("Synchronizer: group structure synchronization currently running."); } }
Source:
public void setInput(IEditorInput input) { super.setInput(input); if (getGraphicalViewer() != null) { getGraphicalViewer().setSelection(new StructuredSelection()); } DRepresentation representation = getRepresentation(); if (representation instanceof DSemanticDecorator) { DSemanticDecorator dSemanticDecorator = (DSemanticDecorator) representation; DRepresentationPermissionStatusQuery dRepresentationPermissionStatusQuery = new DRepresentationPermissionStatusQuery(dSemanticDecorator); IPermissionAuthority permissionAuthority = getPermissionAuthority(); LockStatus lockStatus = LockStatus.NOT_LOCKED; LockStatus dSemanticDecoratorLockStatus = permissionAuthority.getLockStatus(dSemanticDecorator); if (dSemanticDecoratorLockStatus != LockStatus.NOT_LOCKED) { lockStatus = dSemanticDecoratorLockStatus; } int associatedSessionListenerEvent = dRepresentationPermissionStatusQuery.getAssociatedSessionListenerEvent(lockStatus); notify(associatedSessionListenerEvent); } if (diagramHeaderComposite != null && !diagramHeaderComposite.isDisposed()) { diagramHeaderComposite.rebuildHeaderSection(); } if (gmfDiagramUpdater != null) { gmfDiagramUpdater.dispose(); } EObject element = getDiagram().getElement(); if (element instanceof DDiagram) { gmfDiagramUpdater = new GMFDiagramUpdater(getSession(), (DDiagram) element); } }

Target:
public void setInput(IEditorInput input) { super.setInput(input); if (getGraphicalViewer() != null) { getGraphicalViewer().setSelection(new StructuredSelection()); } DRepresentation representation = getRepresentation(); if (representation instanceof DSemanticDecorator) { DSemanticDecorator dSemanticDecorator = (DSemanticDecorator) representation; DRepresentationPermissionStatusQuery dRepresentationPermissionStatusQuery = new DRepresentationPermissionStatusQuery(dSemanticDecorator); IPermissionAuthority permissionAuthority = getPermissionAuthority(); LockStatus lockStatus = LockStatus.NOT_LOCKED; LockStatus dSemanticDecoratorLockStatus = permissionAuthority.getLockStatus(dSemanticDecorator); if (dSemanticDecoratorLockStatus != LockStatus.NOT_LOCKED) { lockStatus = dSemanticDecoratorLockStatus; } int associatedSessionListenerEvent = dRepresentationPermissionStatusQuery.getAssociatedSessionListenerEvent(lockStatus); notify(associatedSessionListenerEvent); } if (diagramHeaderComposite != null && !diagramHeaderComposite.isDisposed()) { diagramHeaderComposite.rebuildHeaderSection(); } if (gmfDiagramUpdater != null) { gmfDiagramUpdater.dispose(); } if (representation instanceof DDiagram) { gmfDiagramUpdater = new GMFDiagramUpdater(getSession(), (DDiagram) representation); } }
Source:
public void test() throws Exception { Study study = Study.create(); study.setName("Name"); study.setShortName("ShortName"); study.setIdentifier("id"); study.setSponsorName("SponsorName"); study.setSupportEmail("support@email.com"); study.setTechnicalEmail("tech@email.com"); study.setConsentNotificationEmail("consent@email.com,consent2@email.com"); SmsTemplate template = new SmsTemplate("${studyShortName} ${url} ${supportEmail}"); SmsMessageProvider provider = new SmsMessageProvider.Builder() .withStudy(study) .withPhone(TestConstants.PHONE) .withSmsTemplate(template) .withToken("url", "some-url").build(); PublishRequest request = provider.getSmsRequest(); assertEquals("ShortName some-url support@email.com", request.getMessage()); assertEquals(study.getShortName(), request.getMessageAttributes().get(BridgeConstants.SENDER_ID).getStringValue()); assertEquals(BridgeConstants.SMS_TYPE_TRANSACTIONAL, request.getMessageAttributes().get(BridgeConstants.SMS_TYPE).getStringValue()); }

Target:
public void test() throws Exception { Study study = Study.create(); study.setName("Name"); study.setShortName("ShortName"); study.setIdentifier("id"); study.setSponsorName("SponsorName"); study.setSupportEmail("support@email.com"); study.setTechnicalEmail("tech@email.com"); study.setConsentNotificationEmail("consent@email.com,consent2@email.com"); SmsTemplate template = new SmsTemplate("${studyShortName} ${url} ${supportEmail} ${expirationPeriod}"); SmsMessageProvider provider = new SmsMessageProvider.Builder() .withStudy(study) .withPhone(TestConstants.PHONE) .withSmsTemplate(template) .withExpirationPeriod("expirationPeriod", 60*60*4) .withToken("url", "some-url").build(); PublishRequest request = provider.getSmsRequest(); assertEquals("ShortName some-url support@email.com 4 hours", request.getMessage()); assertEquals(study.getShortName(), request.getMessageAttributes().get(BridgeConstants.SENDER_ID).getStringValue()); assertEquals(BridgeConstants.SMS_TYPE_TRANSACTIONAL, request.getMessageAttributes().get(BridgeConstants.SMS_TYPE).getStringValue()); assertEquals("some-url", provider.getTokenMap().get("url")); assertEquals("4 hours", provider.getTokenMap().get("expirationPeriod")); assertEquals("Name", provider.getTokenMap().get("studyName")); assertEquals("ShortName", provider.getTokenMap().get("studyShortName")); assertEquals("id", provider.getTokenMap().get("studyId")); assertEquals("SponsorName", provider.getTokenMap().get("sponsorName")); assertEquals("support@email.com", provider.getTokenMap().get("supportEmail")); assertEquals("tech@email.com", provider.getTokenMap().get("technicalEmail")); assertEquals("consent@email.com", provider.getTokenMap().get("consentEmail")); }