auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
boolean isDuplicatedIntervalEvent(AuditEvent newAuditEvent) { if (newAuditEvent.isIntervalAuditEventType()) { for (AuditEvent aev : auditEvents) { if (aev.isIntervalAuditEventType() && newAuditEvent.getAuditEventType().equals(aev.getAuditEventType()) && newAuditEvent.getNode().equals(aev.getNode())) { return true; } } } return false; }

Target:
private boolean isDuplicatedIntervalEvent(AuditEvent newAuditEvent) { if (newAuditEvent.isIntervalAuditEventType()) { for (AuditEvent aev : auditEvents) { if (aev.isIntervalAuditEventType() && newAuditEvent.getAuditEventType().equals(aev.getAuditEventType()) && newAuditEvent.getFormIndex().equals(aev.getFormIndex())) { return true; } } } return false; }
Source:
@Test public void smokes() throws Exception { assertRoundTrip("test"); assertRoundTrip("."); assertRoundTrip(".."); assertRoundTrip("test/foo"); assertRoundTrip("test%bar"); assertRoundTrip("test #1"); }

Target:
public void smokes() throws Exception { assertRoundTrip("test"); assertRoundTrip("."); assertRoundTrip(".."); assertRoundTrip("test/foo"); assertRoundTrip("test%bar"); assertRoundTrip("test #1"); }
Source:
private Map<String, String[]> getQueryParameters(String queryString) { Map<String, String[]> queryParameters = new HashMap<>(); if (StringUtils.isEmpty(queryString)) { return queryParameters; } String[] parameters = queryString.split(QUERY_SEPERATOR); for (String parameter : parameters) { String[] keyValuePair = parameter.split(EQUAL); String[] values = queryParameters.get(keyValuePair[0]); values = (String[]) ArrayUtils.add(values, keyValuePair.length == 1 ? "" : keyValuePair[1]); queryParameters.put(keyValuePair[0], values); } return queryParameters; }

Target:
private Map<String, String[]> getQueryParameters(String queryString) { Map<String, String[]> queryParameters = new HashMap<>(); if (StringUtils.isEmpty(queryString)) { return queryParameters; } String[] parameters = queryString.split(SPLITTING_CHAR); for (String parameter : parameters) { String[] keyValuePair = parameter.split(PADDING_CHAR); String[] values = queryParameters.get(keyValuePair[0]); values = (String[]) ArrayUtils.add(values, keyValuePair.length == 1 ? "" : keyValuePair[1]); queryParameters.put(keyValuePair[0], values); } return queryParameters; }
Source:
public boolean isCompatible(Bundle bundle, IPath prefixedPath) { URL url = FileLocator.find(bundle, prefixedPath.append(SearchIndex.DEPENDENCIES_VERSION_FILENAME), null); if (url == null) { HelpBasePlugin.logError( prefixedPath.append(SearchIndex.DEPENDENCIES_VERSION_FILENAME) + " file missing from help index \"" + path + "\" of plugin " + getPluginId(), null); return false; } try (InputStream in = ProxyUtil.getStream(url)) { Properties prop = new Properties(); prop.load(in); String lucene = prop .getProperty(SearchIndex.DEPENDENCIES_KEY_LUCENE); String analyzer = prop .getProperty(SearchIndex.DEPENDENCIES_KEY_ANALYZER); if (!targetIndex.isLuceneCompatible(lucene) || !targetIndex.isAnalyzerCompatible(analyzer)) { HelpBasePlugin.logWarning( "Unable to consume Lucene index from bundle " + bundle.toString() + ". Index should be rebuilt with Lucene 6.1.", null); return false; } } catch (MalformedURLException mue) { return false; } catch (IOException ioe) { HelpBasePlugin.logError( "IOException accessing prebuilt index.", ioe); } return true; }

Target:
public boolean isCompatible(Bundle bundle, IPath prefixedPath) { URL url = FileLocator.find(bundle, prefixedPath.append(SearchIndex.DEPENDENCIES_VERSION_FILENAME), null); if (url == null) { HelpBasePlugin.logError( prefixedPath.append(SearchIndex.DEPENDENCIES_VERSION_FILENAME) + " file missing from help index \"" + path + "\" of plugin " + getPluginId(), null); return false; } try (InputStream in = ProxyUtil.getStream(url)) { Properties prop = new Properties(); prop.load(in); String lucene = prop .getProperty(SearchIndex.DEPENDENCIES_KEY_LUCENE); String analyzer = prop .getProperty(SearchIndex.DEPENDENCIES_KEY_ANALYZER); if (!targetIndex.isLuceneCompatible(lucene) || !targetIndex.isAnalyzerCompatible(analyzer)) { String message = "Not able to consume Lucene index from bundle " + bundle.toString() + ". The index should be rebuilt with Lucene 6.1."; Status warningStatus = new Status(IStatus.WARNING, HelpBasePlugin.PLUGIN_ID, IStatus.OK, message, null); HelpBasePlugin.logStatus(warningStatus); return false; } } catch (MalformedURLException mue) { return false; } catch (IOException ioe) { HelpBasePlugin.logError( "IOException accessing prebuilt index.", ioe); } return true; }
Source:
public RssUpdate parseUpdate(String content){ if(!StringUtils.isEmptyOrNull(content)) { content = content.replaceAll("</?div>(\\n)?", ""); String[] parts = content.split("\n", 3); if (parts.length == 3) { return new RssUpdate(parts[0], parts[1], parts[2]); } } return null; }

Target:
public RssUpdate parseUpdate(String content){ if (!StringUtils.isEmptyOrNull(content)) { String[] parts = content.split("\n", 3); if (parts.length == 3) { return new RssUpdate(parts[0], parts[1], parts[2]); } } return null; }
Source:
private CreateWsResponse doHandle(CreateRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { OrganizationDto organization = support.getOrganization(dbSession, ofNullable(request.getOrganization()) .orElseGet(defaultOrganizationProvider.get()::getKey)); userSession.checkPermission(PROVISION_PROJECTS, organization); String visibility = request.getVisibility(); Boolean changeToPrivate = visibility == null ? dbClient.organizationDao().getNewProjectPrivate(dbSession, organization) : "private".equals(visibility); ComponentDto componentDto = componentUpdater.create(dbSession, newComponentBuilder() .setOrganizationUuid(organization.getUuid()) .setKey(request.getKey()) .setName(request.getName()) .setBranch(request.getBranch()) .setPrivate(changeToPrivate) .setQualifier(PROJECT) .build(), userSession.isLoggedIn() ? userSession.getUserId() : null); return toCreateResponse(componentDto); } }

Target:
private CreateWsResponse doHandle(CreateRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { OrganizationDto organization = support.getOrganization(dbSession, ofNullable(request.getOrganization()) .orElseGet(defaultOrganizationProvider.get()::getKey)); userSession.checkPermission(PROVISION_PROJECTS, organization); String visibility = request.getVisibility(); Boolean changeToPrivate = visibility == null ? dbClient.organizationDao().getNewProjectPrivate(dbSession, organization) : "private".equals(visibility); support.checkCanUpdateProjectsVisibility(organization, changeToPrivate); ComponentDto componentDto = componentUpdater.create(dbSession, newComponentBuilder() .setOrganizationUuid(organization.getUuid()) .setKey(request.getKey()) .setName(request.getName()) .setBranch(request.getBranch()) .setPrivate(changeToPrivate) .setQualifier(PROJECT) .build(), userSession.isLoggedIn() ? userSession.getUserId() : null); return toCreateResponse(componentDto); } }
Source:
public static String composeObjectId(AuditLogableBase logable, AuditLogType logType) { return composeObjectId(logable, logType, logable.getUserId()); }

Target:
private String composeObjectId(AuditLogableBase logable, AuditLogType logType) { return composeObjectId(logable, logType, logable.getUserId()); }
Source:
public void onApplicationEvent(UpdateFailedEvent event) { long autoscaleClusterId = event.getClusterId(); Cluster cluster = clusterService.findById(autoscaleClusterId); if (cluster == null) { return; } MDCBuilder.buildMdcContext(cluster); LOGGER.debug("Analysing Cluster Status '{}' ", cluster.getStackCrn()); StackV4Response stackResponse = getStackById(cluster.getStackCrn()); String stackStatus = getStackStatus(stackResponse); if (stackResponse == null || stackStatus.startsWith(STOPPED_STATUSES_PREFIX)) { LOGGER.debug("Suspending cluster '{}', Cloudbreak stack status '{}'", cluster.getStackCrn(), stackStatus); suspendCluster(cluster); return; } if (stackStatus.equalsIgnoreCase(DELETE_STATUS)) { clusterService.removeById(autoscaleClusterId); LOGGER.debug("Delete cluster '{}', Cloudbreak stack status '{}'.", cluster.getStackCrn(), stackStatus); return; } Integer failed = updateFailures.get(autoscaleClusterId); if (failed == null) { LOGGER.debug("New failed cluster : [{}]", cluster.getStackCrn()); updateFailures.put(autoscaleClusterId, 1); } else if (RETRY_THRESHOLD - 1 == failed) { Status clusterStatus = stackResponse.getCluster().getStatus(); if (stackStatus.equals(AVAILABLE) && clusterStatus != null && clusterStatus.name().equals(AVAILABLE)) { LOGGER.debug("Suspend cluster monitoring for cluster '{}' due to failing update attempts and Cloudbreak stack status '{}'", cluster.getStackCrn(), stackStatus); } else { LOGGER.debug("Suspend cluster monitoring for cluster '{}'", cluster.getStackCrn()); } suspendCluster(cluster); updateFailures.remove(autoscaleClusterId); } else { int value = failed + 1; LOGGER.debug("Increase failed count[{}] for cluster id: [{}]", value, cluster.getStackCrn()); updateFailures.put(autoscaleClusterId, value); } }

Target:
public void onApplicationEvent(UpdateFailedEvent event) { long autoscaleClusterId = event.getClusterId(); Cluster cluster = clusterService.findById(autoscaleClusterId); if (cluster == null) { return; } MDCBuilder.buildMdcContext(cluster); Integer failed = Optional.ofNullable(updateFailures.get(autoscaleClusterId)) .map(failedCount -> failedCount + 1) .orElse(1); if (failed < RETRY_THRESHOLD) { updateFailures.put(autoscaleClusterId, failed); LOGGER.debug("Increased failed count '{}' for cluster '{}'", failed, cluster.getStackCrn()); } else { suspendCluster(cluster); updateFailures.remove(autoscaleClusterId); LOGGER.debug("Suspended cluster monitoring for cluster '{}' due to failing update attempts", cluster.getStackCrn()); } }
Source:
public void setInformationStatus(RemoteServerState remoteServerState) { text.setText(""); String panelContent = ""; if (remoteServerState.getActualState() == RemoteServerState.State.OK || remoteServerState.getActualState() == RemoteServerState.State.NO_CREDIT) { panelContent = addLine(panelContent, "Connected as " + remoteServerState.getRealName()); panelContent = addLine(panelContent, "(email: " + remoteServerState.getEmail() + ")"); if (remoteServerState.getCredit() > 0) { panelContent = addLine(panelContent, "Your credit balance: " + creditFormatter(remoteServerState.getCredit())); } else { panelContent = addLine(panelContent, "Your credit: <font color=\"red\">" + creditFormatter(remoteServerState.getCredit()) + " </font>"); } if (!remoteServerState.isEmailConfirmed()) { panelContent = addLine(panelContent, "Email is not confirmed."); } } if (remoteServerState.getActualState() == RemoteServerState.State.UNKNOWN) { panelContent = addLine(panelContent, "Datacloud is not configured."); panelContent = addLine(panelContent, "You can set your credentials in"); panelContent = addLine(panelContent, "<b>Options dialog - DataCloud</b>"); } if (remoteServerState.getActualState() == RemoteServerState.State.ERROR) { panelContent = addLine(panelContent, "Cannot connect as " + remoteServerState.getEmail()); panelContent = addLine(panelContent, "<font color=\"red\">" + remoteServerState.getErrorMessage() + " </font>"); } text.setText(panelContent); }

Target:
public void setInformationStatus(RemoteServerState remoteServerState) { text.setText(""); String panelContent = ""; if (remoteServerState.getActualState() == RemoteServerState.State.OK || remoteServerState.getActualState() == RemoteServerState.State.NO_CREDIT) { panelContent = addLine(panelContent, "Connected as " + remoteServerState.getRealName()); panelContent = addLine(panelContent, "(email: " + remoteServerState.getEmail() + ")"); if (remoteServerState.getCredit() > 0) { panelContent = addLine(panelContent, "Your credit balance: " + String.format("%,d", remoteServerState.getCredit())); } else { panelContent = addLine(panelContent, "Your credit: <font color=\"red\">" + String.format("%,d", remoteServerState.getCredit()) + " </font>"); } if (!remoteServerState.isEmailConfirmed()) { panelContent = addLine(panelContent, "Email is not confirmed."); } } if (remoteServerState.getActualState() == RemoteServerState.State.NOT_CONNECTED) { panelContent = addLine(panelContent, "Datacloud is not configured."); panelContent = addLine(panelContent, "You can set your credentials in"); panelContent = addLine(panelContent, "<b>Options dialog - DataCloud</b>"); } if (remoteServerState.getActualState() == RemoteServerState.State.ERROR) { panelContent = addLine(panelContent, "Cannot connect as " + remoteServerState.getEmail()); panelContent = addLine(panelContent, "<font color=\"red\">" + remoteServerState.getErrorMessage() + " </font>"); } text.setText(panelContent); }
Source:
private Credential getCredential(FrameworkInfo.Builder finfo) { LOG.info("Checking for mesos authentication"); Credential credential = null; String principal = Optional.fromNullable((String) _conf.get(CONF_MESOS_PRINCIPAL)).orNull(); String secretFilename = Optional.fromNullable((String) _conf.get(CONF_MESOS_SECRET_FILE)).orNull(); if (principal != null) { finfo.setPrincipal(principal); Credential.Builder credentialBuilder = Credential.newBuilder(); credentialBuilder.setPrincipal(principal); if (StringUtils.isNotEmpty(secretFilename)) { try { credentialBuilder.setSecret(ByteString.readFrom(new FileInputStream(secretFilename)).toString()); } catch (FileNotFoundException ex) { LOG.error("Mesos authentication secret file was not found", ex); throw new RuntimeException(ex); } catch (IOException ex) { LOG.error("Error reading Mesos authentication secret file", ex); throw new RuntimeException(ex); } } credential = credentialBuilder.build(); } return credential; }

Target:
private Credential getCredential(FrameworkInfo.Builder finfo) { LOG.info("Checking for mesos authentication"); Credential credential = null; String principal = Optional.fromNullable((String) _conf.get(CONF_MESOS_PRINCIPAL)).orNull(); String secretFilename = Optional.fromNullable((String) _conf.get(CONF_MESOS_SECRET_FILE)).orNull(); if (principal != null) { finfo.setPrincipal(principal); Credential.Builder credentialBuilder = Credential.newBuilder(); credentialBuilder.setPrincipal(principal); if (StringUtils.isNotEmpty(secretFilename)) { try { credentialBuilder.setSecret(ByteString.readFrom(new FileInputStream(secretFilename))); } catch (FileNotFoundException ex) { LOG.error("Mesos authentication secret file was not found", ex); throw new RuntimeException(ex); } catch (IOException ex) { LOG.error("Error reading Mesos authentication secret file", ex); throw new RuntimeException(ex); } } credential = credentialBuilder.build(); } return credential; }
Source:
public List<IDValue> get( @PathParam("itemID") List<PathSegment> pathSegmentsList, @DefaultValue("10") @QueryParam("howMany") int howMany, @DefaultValue("0") @QueryParam("offset") int offset, @QueryParam("rescorerParams") List<String> rescorerParams) throws OryxServingException { check(pathSegmentsList.size() > 0, "Need atleast 1 item to determine similarity"); check(howMany > 0, "howMany must be positive"); check(offset >= 0, "offset must be non-negative"); ALSServingModel alsServingModel = getALSServingModel(); Collection<String> allItemIDs = alsServingModel.getAllItemIDs(); List<Pair<String,Double>> similarItemsList = new ArrayList<>(pathSegmentsList.size()); for (String itemID : allItemIDs) { double total = 0.0; float[] entryFeatures = alsServingModel.getItemVector(itemID); double entryFeaturesNorm = VectorMath.norm(entryFeatures); for (PathSegment pathSegment : pathSegmentsList) { String pathItem = pathSegment.getPath(); if (!pathItem.equalsIgnoreCase(itemID)) { float[] itemFeatures = alsServingModel.getItemVector(pathItem); double cosineSimilarity = VectorMath.dot(entryFeatures, itemFeatures) / (entryFeaturesNorm * VectorMath.norm(itemFeatures)); total += cosineSimilarity; } } double result = total / pathSegmentsList.size(); Preconditions.checkState(!(Double.isInfinite(result) || Double.isNaN(result)), "Bad similarity value"); similarItemsList.add(new Pair<>(itemID,result)); } similarItemsList = alsServingModel.topN(similarItemsList, howMany); check(similarItemsList != null, Response.Status.NOT_FOUND, "No similar items found"); return toIDValueResponse(similarItemsList, howMany, offset); }

Target:
public List<IDValue> get( @PathParam("itemID") List<PathSegment> pathSegmentsList, @DefaultValue("10") @QueryParam("howMany") int howMany, @DefaultValue("0") @QueryParam("offset") int offset, @QueryParam("rescorerParams") List<String> rescorerParams) throws OryxServingException { check(!pathSegmentsList.isEmpty() && pathSegmentsList.size() > 0, "Need atleast 1 item to determine similarity"); check(howMany > 0, "howMany must be positive"); check(offset >= 0, "offset must be non-negative"); ALSServingModel alsServingModel = getALSServingModel(); List<float[]> itemFeaturesList = new ArrayList<>(pathSegmentsList.size()); for (PathSegment pathSegment : pathSegmentsList) { float[] itemVector = alsServingModel.getItemVector(pathSegment.getPath()); if (itemVector != null) { itemFeaturesList.add(itemVector); } } List<Pair<String,Double>> topIDCosines = alsServingModel.topN( new CosineAverageFunction(itemFeaturesList), howMany + offset, null); return toIDValueResponse(topIDCosines, howMany, offset); }
Source:
public static Properties loadProperties(File file){ Properties prop = new Properties(); InputStream input = null; try { input = new FileInputStream(file); prop.load(input); return prop; } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }

Target:
public static Properties loadProperties(File file) throws IOException{ Properties prop = new Properties(); InputStream input = null; try { input = new FileInputStream(file); prop.load(input); return prop; } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Source:
public PagedIterable<GHRepository> listRepositories(final int pageSize, final RepositoryType repoType) { return new PagedIterable<GHRepository>() { public PagedIterator<GHRepository> iterator() { return new PagedIterator<GHRepository>(root.retrieve().asIterator("/user/repos?per_page=" + pageSize + "&type=" + repoType.toString().toLowerCase(), GHRepository[].class)) { @Override protected void wrapUp(GHRepository[] page) { for (GHRepository c : page) c.wrap(root); } }; } }; }

Target:
public PagedIterable<GHRepository> listRepositories(final int pageSize, final RepositoryType repoType) { return new PagedIterable<GHRepository>() { public PagedIterator<GHRepository> iterator() { return new PagedIterator<GHRepository>(root.retrieve().asIterator("/user/repos?per_page=" + pageSize + "&type=" + repoType.name().toLowerCase(), GHRepository[].class)) { @Override protected void wrapUp(GHRepository[] page) { for (GHRepository c : page) c.wrap(root); } }; } }; }
Source:
@Override protected String getDescription(MBeanInfo info) { String str = super.getDescription(info); MXBeanDescription desc = U.getAnnotation(getMBeanInterface(), MXBeanDescription.class); if (desc != null) { str = desc.value(); assert str != null; assert !str.trim().isEmpty(); assert Character.isUpperCase(str.charAt(0)) : str; assert str.charAt(str.length() - 1) == '.' : str; } return str; }

Target:
@Override protected String getDescription(MBeanInfo info) { String str = super.getDescription(info); MXBeanDescription desc = U.getAnnotation(getMBeanInterface(), MXBeanDescription.class); if (desc != null) { str = desc.value(); assert str != null; assert !str.trim().isEmpty(); assert Character.isUpperCase(str.charAt(0)) : DESC_MUST_START_WITH_UPP_CASE + str; assert str.charAt(str.length() - 1) == '.' : DESC_MUST_END_WITH_PERIOD + str; } return str; }
Source:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { context.addStep(new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { ServiceController<KeytabService> serviceController = ManagementUtil.getKeytabService(context, operation); KeytabService keytabService = serviceController.getService().getValue(); SubjectIdentity si = null; try { si = keytabService.createSubjectIdentity(false); ModelNode result = context.getResult(); result.get(SUBJECT).set(si.getSubject().toString()); } catch (LoginException e) { throw SECURITY_LOGGER.unableToObtainTGT(e); } finally { if (si != null) { si.logout(); } } context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); } }, Stage.RUNTIME); context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); }

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { context.readResource(PathAddress.EMPTY_ADDRESS, false); context.addStep(new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { ServiceController<KeytabService> serviceController = ManagementUtil.getKeytabService(context, operation); KeytabService keytabService = serviceController.getService().getValue(); SubjectIdentity si = null; try { si = keytabService.createSubjectIdentity(false); ModelNode result = context.getResult(); result.get(SUBJECT).set(si.getSubject().toString()); } catch (LoginException e) { throw SECURITY_LOGGER.unableToObtainTGT(e); } finally { if (si != null) { si.logout(); } } context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); } }, Stage.RUNTIME); context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); }
Source:
public List<Condition> getActiveConditions(Patient patient) { Query query = sessionFactory.getCurrentSession().createQuery( "from Condition c where c.patient.patientId = :patientId and c.voided = false and c.endDate is null order " + "by c.dateCreated desc"); query.setInteger("patientId", patient.getId()); return query.list(); }

Target:
public List<Condition> getActiveConditions(Patient patient) { Query query = sessionFactory.getCurrentSession().createQuery( "from Condition c where c.patient.patientId = :patientId and c.voided = false and c.endDate is null order " + "by c.onsetDate desc"); query.setInteger("patientId", patient.getId()); return query.list(); }
Source:
public void onSuccess() { log.debug("Command succeeded, releasing macs {}.", Arrays.toString(super.macs.toArray())); releaseMacs(); }

Target:
public void onSuccess() { log.debug("Command succeeded, releasing macs {}.", super.macs); releaseMacs(); }
Source:
public boolean isModification() throws CoreException { return (Boolean.valueOf(this.getMarker().getAttribute(MODIFICATION, "true"))) .booleanValue(); }

Target:
public boolean isModification() throws CoreException { return Boolean.parseBoolean( this.getMarker().getAttribute(MODIFICATION, "true")); }
Source:
public static void main(String[] args) { ISelectionStatusValidator validator= new ISelectionStatusValidator() { @Override public IStatus validate(Object[] selection) { if (selection != null && selection.length == 1) { return new StatusInfo(); } else { StatusInfo status= new StatusInfo(); status.setError("Single selection"); return status; } } }; Random random= new Random(); ILabelProvider elementRenderer= new org.eclipse.jface.viewers.LabelProvider() { @Override public String getText(Object element) { return element.toString(); } }; int nPages= 3; Object[][] elements= new Object[nPages][]; for (int i= 0; i < nPages; i++) { int size= random.nextInt(15); elements[i]= new String[size]; for (int k= 0; k < size; k++) { elements[i][k]= "elem-" + i + "-" + k; } } Display display= new Display(); MultiElementListSelectionDialog d= new MultiElementListSelectionDialog(new Shell(display), elementRenderer); d.setTitle("Title"); d.setIgnoreCase(true); d.setMessage("this is a message"); d.setValidator(validator); d.setElements(elements); d.open(); Object[] res= d.getResult(); if (res != null) { for (Object re : res) { System.out.println(re); } } }

Target:
public static void main(String[] args) { ISelectionStatusValidator validator= new ISelectionStatusValidator() { @Override public IStatus validate(Object[] selection) { if (selection != null && selection.length == 1) { return new StatusInfo(); } else { StatusInfo status= new StatusInfo(); status.setError("Single selection"); return status; } } }; Random random= new Random(); ILabelProvider elementRenderer= new org.eclipse.jface.viewers.LabelProvider() { @Override public String getText(Object element) { return element.toString(); } }; int nPages= 3; Object[][] elements= new Object[nPages][]; for (int i= 0; i < nPages; i++) { int size= random.nextInt(15); elements[i]= new String[size]; for (int k= 0; k < size; k++) { elements[i][k]= "elem-" + i + "-" + k; } } Display display= new Display(); MultiElementListSelectionDialog d= new MultiElementListSelectionDialog(new Shell(display), elementRenderer); d.setTitle("Title"); d.setIgnoreCase(true); d.setMessage("this is a message"); d.setValidator(validator); d.setElements(elements); d.open(); Object[] res= d.getResult(); if (res != null) { for (Object obj : res) { System.out.println(obj); } } }
Source:
public void prepareRun(StageSubmitterContext context) throws Exception { super.prepareRun(context); context.record( TransformLineageRecorderUtils.oneToOneIn(TransformLineageRecorderUtils.getFields(outSchema), "encode", "Encode the input fields based on specified encoder.")); }

Target:
public void prepareRun(StageSubmitterContext context) throws Exception { super.prepareRun(context); parseConfiguration(config.encode, context.getFailureCollector()); List<String> inFields = TransformLineageRecorderUtils.getFields(context.getInputSchema()); List<String> outFields = TransformLineageRecorderUtils.getFields(context.getOutputSchema()); List<String> identityFields = outFields.stream() .filter(field -> !encodeMap.containsKey(field) || encodeMap.get(field) == EncodeType.NONE) .collect(Collectors.toList()); List<String> processedFields = new ArrayList<>(outFields); processedFields.removeAll(identityFields); List<String> droppedFields = new ArrayList<>(inFields); droppedFields.removeAll(outFields); List<FieldOperation> output = new ArrayList<>(); output.addAll(TransformLineageRecorderUtils.generateOneToOnes(processedFields, "encode", "Encoded the input fields based on expected encoder.")); output.addAll(TransformLineageRecorderUtils.generateDrops(droppedFields)); output.addAll(TransformLineageRecorderUtils.generateOneToOnes(identityFields, "identity", TransformLineageRecorderUtils.IDENTITY_TRANSFORM_DESCRIPTION)); context.record(output); }
Source:
public void empty_file_should_raise_no_issue() throws Exception { analyseSingleFile(context, "empty.php"); assertThat(context.allIssues()).as("No issue must be raised").hasSize(0); }

Target:
public void empty_file_should_raise_no_issue() throws Exception { sensor = createSensorWithParsingErrorCheckActivated(); analyseSingleFile(context, "empty.php"); assertThat(context.allIssues()).as("No issue must be raised").hasSize(0); }
Source:
public void preProcess(BindContext context) { preProcessIndex++; if (preProcessIndex < operations.size()) { operations.get(preProcessIndex).preProcess(context, this); } }

Target:
private boolean preProcess(BindContext context) { for (BindOperation operation : operations) { log.debug("Starting preprocess of {}", operation.getClass().getSimpleName()); if (operation.preProcess(context)) { log.debug("Finished preprocess of {}", operation.getClass().getSimpleName()); } else { log.error("Skipped chain in preprocess of operation {}", operation.getClass().getSimpleName()); return false; } } return true; }
Source:
public boolean sameObject(DocFormRequestKey other) { System.out.println("compare " + this); System.out.println("with " + other); return (this.classRef != null) && (this.objNb != null) && (this.objNb >= 0) && ObjectUtils.equals(this.classRef, other.classRef) && ObjectUtils.equals(this.objNb, other.objNb); }

Target:
public boolean sameObject(DocFormRequestKey other) { return (this.classRef != null) && (this.objNb != null) && (this.objNb >= 0) && ObjectUtils.equals(this.classRef, other.classRef) && ObjectUtils.equals(this.objNb, other.objNb); }
Source:
private static List<ITimeGraphState> getKernelStates(CallStackDepth callStackDepth, Collection<ISegment> states, Collection<Long> times) { List<ITimeGraphState> eventList = new ArrayList<>(states.size()); for (ISegment state : states) { if (!(state instanceof ICalledFunction)) { eventList.add(new TimeGraphState(state.getStart(), state.getLength(), Integer.MIN_VALUE)); continue; } ICalledFunction function = (ICalledFunction) state; Iterator<ProcessStatusInterval> kernelStatuses = callStackDepth.getCallStack().getKernelStatuses(function, times); while (kernelStatuses.hasNext()) { ProcessStatusInterval status = kernelStatuses.next(); eventList.add(new TimeGraphState(status.getStart(), status.getLength() + 1, status.getProcessStatus().getStateValue().unboxLong(), status.getProcessStatus().name())); } } return eventList; }

Target:
private static List<ITimeGraphState> getKernelStates(CallStackDepth callStackDepth, Collection<ISegment> states, Collection<Long> times) { List<ITimeGraphState> eventList = new ArrayList<>(states.size()); for (ISegment state : states) { if (!(state instanceof ICalledFunction)) { eventList.add(new TimeGraphState(state.getStart(), state.getLength(), Integer.MIN_VALUE)); continue; } ICalledFunction function = (ICalledFunction) state; Iterable<ProcessStatusInterval> kernelStatuses = callStackDepth.getCallStack().getKernelStatuses(function, times); for (ProcessStatusInterval status : kernelStatuses) { eventList.add(new TimeGraphState(status.getStart(), status.getLength() + 1, status.getProcessStatus().getStateValue().unboxLong(), status.getProcessStatus().name())); } } return eventList; }
Source:
public static ArtifactType getType(Long id) { return getTypeById(id); }

Target:
public static ArtifactType getType(Long id) { if (id == null) { throw new OseeArgumentException("[%s] is not a valid guid", id); } ArtifactType artifactType = getCache().getByGuid(id); if (artifactType == null) { getCacheService().reloadTypes(); artifactType = getCache().getByGuid(id); if (artifactType == null) { throw new OseeTypeDoesNotExist("Artifact type [%s] is not available.", id); } } return artifactType; }
Source:
public boolean isRecommendationEnabled(String tenantDomain) { if (recommendationEnvironment != null) { if (recommendationEnvironment.isApplyForAllTenants()) { return true; } else { try { org.json.JSONObject tenantConfig; Cache tenantConfigCache = CacheProvider.getTenantConfigCache(); String cacheName = tenantDomain + "_" + APIConstants.TENANT_CONFIG_CACHE_NAME; if (tenantConfigCache.containsKey(cacheName)) { tenantConfig = (org.json.JSONObject) tenantConfigCache.get(cacheName); } else { String content = apimRegistryService .getConfigRegistryResourceContent(tenantDomain, APIConstants.API_TENANT_CONF_LOCATION); tenantConfig = new org.json.JSONObject(content); tenantConfigCache.put(cacheName, tenantConfig); } if (tenantConfig.has(APIConstants.API_TENANT_CONF_ENABLE_RECOMMENDATION_KEY)) { Object value = tenantConfig.get(APIConstants.API_TENANT_CONF_ENABLE_RECOMMENDATION_KEY); return Boolean.parseBoolean(value.toString()); } } catch (UserStoreException | RegistryException e) { log.error("Error occurred when getting API tenant config from registry", e); } } } return false; }

Target:
public boolean isRecommendationEnabled(String tenantDomain) { return APIUtil.isRecommendationEnabled(tenantDomain); }
Source:
public final synchronized byte[] encode(Object val) throws IOException { if (val == null) { return null; } if (val instanceof byte[]) { byte[] arrayValue = (byte[]) val; byte[] encodedValue = new byte[arrayValue.length + 1]; encodedValue[0] = ID_NULL_ENCODER; System.arraycopy(arrayValue, 0, encodedValue, 1, arrayValue.length); return encodedValue; } else { final ByteArrayOutputStream bos = new InitiallyReusableByteArrayOutputStream(getReusableByteBuffer()); final ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(val); return bos.toByteArray(); } }

Target:
public final byte[] encode(Object val) throws IOException { if (val == null) { return null; } if (val instanceof byte[]) { byte[] arrayValue = (byte[]) val; byte[] encodedValue = new byte[arrayValue.length + 1]; encodedValue[0] = ID_NULL_ENCODER; System.arraycopy(arrayValue, 0, encodedValue, 1, arrayValue.length); return encodedValue; } else { bufferLock.lock(); try { final ByteArrayOutputStream bos = new InitiallyReusableByteArrayOutputStream(getReusableByteBuffer()); final ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(val); return bos.toByteArray(); } finally { bufferLock.unlock(); } } }
Source:
private Map setupPySparkEnv() throws IOException{ Map env = EnvironmentUtils.getProcEnvironment(); if (!env.containsKey("PYTHONPATH")) { SparkConf conf = getSparkConf(); env.put("PYTHONPATH", conf.get("spark.files").replaceAll(",", ":")); } return env; }

Target:
private Map setupPySparkEnv() throws IOException{ Map env = EnvironmentUtils.getProcEnvironment(); if (!env.containsKey("PYTHONPATH")) { SparkConf conf = getSparkConf(); env.put("PYTHONPATH", conf.get("spark.submit.pyFiles").replaceAll(",", ":")); } return env; }
Source:
public void testObtainProductInstanceName() throws Exception { ProductInstallatorSdcImpl installator = new ProductInstallatorSdcImpl(); installator.setSDCClient(sdcClient); installator.setSystemPropertiesProvider(systemPropertiesProvider); installator.setProductReleaseManager(productReleaseManager); installator.setSDCUtil(sDCUtil); installator.setTierInstanceManager(tierInstanceManager); expectedProductInstance.setName("deploytm-contextbrokr-1_mongos_2.2.3"); String name = installator.getProductInstanceName(data, expectedProductInstance); assertEquals(name, "FIWARE.customers.60b4125450fc4a109f50357894ba2e28.services.deploytm.vees.contextbrokr.replicas.1_mongos_2.2.3"); }

Target:
public void testObtainProductInstanceName() throws Exception { ProductInstallatorSdcImpl installator = new ProductInstallatorSdcImpl(); installator.setSDCClient(sdcClient); installator.setSystemPropertiesProvider(systemPropertiesProvider); installator.setProductReleaseManager(productReleaseManager); installator.setSDCUtil(sDCUtil); installator.setTierInstanceManager(tierInstanceManager); expectedProductInstance.setName("deploytm-contextbrokr-1_mongos_2.2.3"); String name = installator.getProductInstanceName(data, expectedProductInstance); assertEquals(name, "FIWARE.customers.60b4125450fc4a109f50357894ba2e28.services." + "deploytm.vees.contextbrokr.replicas.1_mongos_2.2.3"); }
Source:
protected MutableBoundedValue<Integer> constructValue(Integer defaultValue) { return new SpongeBoundedValue<Integer>(this.getKey(), defaultValue, intComparator(), defaultValue, defaultValue); }

Target:
protected MutableBoundedValue<Integer> constructValue(Integer defaultValue) { return new SpongeBoundedValue<Integer>(this.getKey(), defaultValue, intComparator(), 0, Integer.MAX_VALUE, defaultValue); }
Source:
public JInvocation getSuperPutExtraInvocation(TypeMirror elementType, JVar extraParam, JFieldVar extraKeyField) { JExpression extraParameterArg = extraParam; if (elementType.getKind() == TypeKind.DECLARED) { Elements elementUtils = environment.getProcessingEnvironment().getElementUtils(); TypeMirror parcelableType = elementUtils.getTypeElement(PARCELABLE).asType(); if (typeUtils.isSubtype(elementType, parcelableType)) { TypeMirror serializableType = elementUtils.getTypeElement(SERIALIZABLE).asType(); if (typeUtils.isSubtype(elementType, serializableType)) { extraParameterArg = cast(environment.getClasses().PARCELABLE, extraParameterArg); } } else if (!BundleHelper.METHOD_SUFFIX_BY_TYPE_NAME.containsKey(elementType.toString()) && annotationHelper.isParcelType(elementType)) { extraParameterArg = environment.getCodeModel().ref("org.parceler.Parcels").staticInvoke("wrap").arg(extraParameterArg); } else { TypeMirror stringType = elementUtils.getTypeElement(STRING).asType(); if (!typeUtils.isSubtype(elementType, stringType)) { extraParameterArg = cast(environment.getClasses().SERIALIZABLE, extraParameterArg); } } } return _super().invoke("extra").arg(extraKeyField).arg(extraParameterArg); }

Target:
public JInvocation getSuperPutExtraInvocation(TypeMirror elementType, JVar extraParam, JFieldVar extraKeyField) { IJExpression extraParameterArg = extraParam; if (elementType.getKind() == TypeKind.DECLARED) { Elements elementUtils = environment.getProcessingEnvironment().getElementUtils(); TypeMirror parcelableType = elementUtils.getTypeElement(PARCELABLE).asType(); if (typeUtils.isSubtype(elementType, parcelableType)) { TypeMirror serializableType = elementUtils.getTypeElement(SERIALIZABLE).asType(); if (typeUtils.isSubtype(elementType, serializableType)) { extraParameterArg = cast(environment.getClasses().PARCELABLE, extraParameterArg); } } else if (!BundleHelper.METHOD_SUFFIX_BY_TYPE_NAME.containsKey(elementType.toString()) && parcelerHelper.isParcelType(elementType)) { extraParameterArg = environment.getCodeModel().ref(CanonicalNameConstants.PARCELS_UTILITY_CLASS).staticInvoke("wrap").arg(extraParameterArg); } else { TypeMirror stringType = elementUtils.getTypeElement(STRING).asType(); if (!typeUtils.isSubtype(elementType, stringType)) { extraParameterArg = cast(environment.getClasses().SERIALIZABLE, extraParameterArg); } } } return _super().invoke("extra").arg(extraKeyField).arg(extraParameterArg); }
Source:
public void testOctagonTree() { OGCGeometryWrapper octagonA = new OGCGeometryWrapper(POLYGON_A); OGCGeometryWrapper octagonB = new OGCGeometryWrapper(POLYGON_B); OGCGeometryWrapper pointX = new OGCGeometryWrapper(POINT_X); OGCGeometryWrapper pointY = new OGCGeometryWrapper(POINT_Y); OGCGeometryWrapper pointZ = new OGCGeometryWrapper(POINT_Z); OGCGeometryWrapper pointW = new OGCGeometryWrapper(POINT_W); Flatbush rtree = new Flatbush<OGCGeometryWrapper>(new OGCGeometryWrapper[] {octagonA, octagonB}); List<OGCGeometryWrapper> resultsX = rtree.findIntersections(pointX.getExtent()); assertEquals(resultsX, Arrays.asList(octagonA)); List<OGCGeometryWrapper> resultsY = rtree.findIntersections(pointY.getExtent()); resultsY.sort(Comparator.naturalOrder()); assertEquals(resultsY, Arrays.asList(octagonA, octagonB)); List<OGCGeometryWrapper> resultsZ = rtree.findIntersections(pointZ.getExtent()); assertEquals(resultsZ, Arrays.asList(octagonB)); List<OGCGeometryWrapper> resultsW = rtree.findIntersections(pointW.getExtent()); assertTrue(resultsW.isEmpty()); }

Target:
public void testOctagonTree() { OGCGeometryWrapper octagonA = new OGCGeometryWrapper(POLYGON_A); OGCGeometryWrapper octagonB = new OGCGeometryWrapper(POLYGON_B); OGCGeometryWrapper pointX = new OGCGeometryWrapper(POINT_X); OGCGeometryWrapper pointY = new OGCGeometryWrapper(POINT_Y); OGCGeometryWrapper pointZ = new OGCGeometryWrapper(POINT_Z); OGCGeometryWrapper pointW = new OGCGeometryWrapper(POINT_W); Flatbush<OGCGeometryWrapper> rtree = new Flatbush<>(new OGCGeometryWrapper[] {octagonA, octagonB}); assertEquals(findIntersections(rtree, pointX.getExtent()), ImmutableList.of(octagonA)); List<OGCGeometryWrapper> results = findIntersections(rtree, pointY.getExtent()); assertEqualsSorted(results, ImmutableList.of(octagonA, octagonB), Comparator.naturalOrder()); assertEquals(findIntersections(rtree, pointZ.getExtent()), ImmutableList.of(octagonB)); assertEquals(findIntersections(rtree, pointW.getExtent()), ImmutableList.of()); }
Source:
public static PersistenceStrategy<?, ?, ?> getPerTableStrategy(EmbeddedCacheManager externalCacheManager, URL configUrl, JtaPlatform platform, Set<EntityKeyMetadata> entityTypes, Set<AssociationKeyMetadata> associationTypes, Set<IdSourceKeyMetadata> idSourceTypes) { PerTableKeyProvider keyProvider = new PerTableKeyProvider(); PerTableCacheManager cacheManager = externalCacheManager != null ? new PerTableCacheManager( externalCacheManager, entityTypes, associationTypes, idSourceTypes ) : new PerTableCacheManager( configUrl, platform, entityTypes, associationTypes, idSourceTypes ); return new PersistenceStrategy<PersistentEntityKey, PersistentAssociationKey, PersistentIdSourceKey>( cacheManager, keyProvider ); }

Target:
private static PersistenceStrategy<?, ?, ?> getPerTableStrategy( EmbeddedCacheManager externalCacheManager, URL configUrl, JtaPlatform platform, Set<EntityKeyMetadata> entityTypes, Set<AssociationKeyMetadata> associationTypes, Set<IdSourceKeyMetadata> idSourceTypes) { PerTableKeyProvider keyProvider = new PerTableKeyProvider(); PerTableCacheManager cacheManager = externalCacheManager != null ? new PerTableCacheManager( externalCacheManager, entityTypes, associationTypes, idSourceTypes ) : new PerTableCacheManager( configUrl, platform, entityTypes, associationTypes, idSourceTypes ); return new PersistenceStrategy<PersistentEntityKey, PersistentAssociationKey, PersistentIdSourceKey>( cacheManager, keyProvider ); }
Source:
public List<String> getNames() { final Iterable<DataSourceWithSegmentSpec> sourceSpecs = query.getDataSources(); return StreamSupport.stream(sourceSpecs.spliterator(), false) .flatMap(spec -> spec.getDataSource().getNames().stream()) .collect(Collectors.toList()); }

Target:
public List<String> getNames() { return query.getDataSources().stream() .flatMap(spec -> spec.getDataSource().getNames().stream()) .collect(Collectors.toList()); }
Source:
public synchronized void startup() throws DatastreamException { if (_coordinator != null) { _coordinator.start(); } try { _nettyLauncher.start(); _isStarted = true; } catch (IOException ex) { String errorMessage = "Failed to start netty."; LOG.error(errorMessage, ex); throw new DatastreamException(errorMessage, ex); } }

Target:
public synchronized void startup() throws DatastreamException { if (_coordinator != null) { _coordinator.start(); } try { _nettyLauncher.start(); _isStarted = true; } catch (IOException ex) { String errorMessage = "Failed to start netty."; ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, ex); } }
Source:
public void testDeleteRunningWorkflowForcefully() throws Exception { String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = new Workflow.Builder(workflowName); JobConfig.Builder jobBuilder0 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100000")); JobConfig.Builder jobBuilder1 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100000")); JobConfig.Builder jobBuilder2 = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG) .setMaxAttemptsPerTask(1).setWorkflow(workflowName) .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100000")); builder.addParentChildDependency("JOB0", "JOB1"); builder.addParentChildDependency("JOB0", "JOB2"); builder.addJob("JOB0", jobBuilder0); builder.addJob("JOB1", jobBuilder1); builder.addJob("JOB2", jobBuilder2); _driver.start(builder.build()); boolean isWorkflowRunning = TestHelper.verify(() -> { WorkflowContext wCtx1 = _driver.getWorkflowContext(workflowName); return (wCtx1 != null && wCtx1.getWorkflowState() == TaskState.IN_PROGRESS); }, 60 * 1000); Assert.assertTrue(isWorkflowRunning); Assert.assertNotNull(_driver.getWorkflowConfig(workflowName)); Assert.assertNotNull(_driver.getWorkflowContext(workflowName)); Assert.assertNotNull(admin.getResourceIdealState(CLUSTER_NAME, workflowName)); admin.enableCluster(CLUSTER_NAME, false); Thread.sleep(Disable_Delay); _driver.delete(workflowName, true); Thread.sleep(DELETE_DELAY); admin.enableCluster(CLUSTER_NAME, true); Assert.assertNull(_driver.getWorkflowConfig(workflowName)); Assert.assertNull(_driver.getWorkflowContext(workflowName)); Assert.assertNull(admin.getResourceIdealState(CLUSTER_NAME, workflowName)); }

Target:
public void testDeleteRunningWorkflowForcefully() throws Exception { String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = createCustomWorkflow(workflowName, LONG_EXECUTION_TIME, "0"); _driver.start(builder.build()); _driver.pollForWorkflowState(workflowName, TaskState.IN_PROGRESS); _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, "JOB0"), TaskState.IN_PROGRESS); Assert.assertNotNull(_driver.getWorkflowConfig(workflowName)); Assert.assertNotNull(_driver.getWorkflowContext(workflowName)); Assert.assertNotNull(_admin.getResourceIdealState(CLUSTER_NAME, workflowName)); _controller.syncStop(); _driver.delete(workflowName, true); boolean isWorkflowDeleted = TestHelper.verify(() -> { WorkflowConfig wfcfg = _driver.getWorkflowConfig(workflowName); WorkflowContext wfctx = _driver.getWorkflowContext(workflowName); IdealState is = _admin.getResourceIdealState(CLUSTER_NAME, workflowName); return (wfcfg == null && wfctx == null && is == null); }, 60 * 1000); Assert.assertTrue(isWorkflowDeleted); }
Source:
public void connect( final String tokenKeyName, final String token, final String tokenSignature, final String customAuthorizer, final AWSIotMqttClientStatusCallback statusCallback) { if (tokenKeyName == null || token == null || tokenSignature == null) { throw new IllegalArgumentException("tokenKeyName/token/tokenSignature cannot be null"); } this.userStatusCallback = statusCallback; if (connectionState != MqttManagerConnectionState.Disconnected) { userConnectionCallback(); return; } authMode = AuthenticationMode.CUSTOM_AUTH; String endpointWithHttpPort = getEndpointWithHttpPort(); LOGGER.debug("MQTT broker endpoint: " + endpointWithHttpPort); try { if (mqttClient == null) { mqttClient = new MqttAsyncClient( "wss://" + endpointWithHttpPort + "/mqtt", mqttClientId, new MemoryPersistence()); } customWebsocketHeaders = new Properties(); customWebsocketHeaders.setProperty("X-Amz-CustomAuthorizer-Name", customAuthorizer); customWebsocketHeaders.setProperty("X-Amz-CustomAuthorizer-Signature", tokenSignature); customWebsocketHeaders.setProperty(tokenKeyName, token); final MqttConnectOptions options = new MqttConnectOptions(); if (mqttLWT != null) { options.setWill(mqttLWT.getTopic(), mqttLWT.getMessage().getBytes(), mqttLWT.getQos().asInt(), false); } options.setCustomWebSocketHeaders(customWebsocketHeaders); mqttConnect(options); } catch (final MqttException e) { connectionState = MqttManagerConnectionState.Disconnected; userConnectionCallback(new AmazonClientException("An error occurred in the MQTT client.", e)); } }

Target:
public void connect( final String tokenKeyName, final String token, final String tokenSignature, final String customAuthorizer, final AWSIotMqttClientStatusCallback statusCallback) { if (tokenKeyName == null || token == null || tokenSignature == null) { throw new IllegalArgumentException("tokenKeyName/token/tokenSignature cannot be null"); } this.userStatusCallback = statusCallback; if (!MqttManagerConnectionState.Disconnected.equals(connectionState)) { userConnectionCallback(); return; } authMode = AuthenticationMode.CUSTOM_AUTH; String endpointWithHttpPort = getEndpointWithHttpPort(); LOGGER.debug("MQTT broker endpoint: " + endpointWithHttpPort); try { if (mqttClient == null) { mqttClient = new MqttAsyncClient( "wss://" + endpointWithHttpPort + "/mqtt", mqttClientId, new MemoryPersistence()); } customWebsocketHeaders.setProperty("X-Amz-CustomAuthorizer-Name", customAuthorizer); customWebsocketHeaders.setProperty("X-Amz-CustomAuthorizer-Signature", tokenSignature); customWebsocketHeaders.setProperty(tokenKeyName, token); final MqttConnectOptions options = new MqttConnectOptions(); if (mqttLWT != null) { options.setWill(mqttLWT.getTopic(), mqttLWT.getMessage().getBytes(), mqttLWT.getQos().asInt(), false); } options.setCustomWebSocketHeaders(customWebsocketHeaders); mqttConnect(options); } catch (final MqttException e) { connectionState = MqttManagerConnectionState.Disconnected; userConnectionCallback(new AmazonClientException("An error occurred in the MQTT client.", e)); } }