auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static HtsgetErrorResponse parse(final String s) { final HtsgetErrorResponse resp = new HtsgetErrorResponse(); final mjson.Json j = mjson.Json.read(s); final mjson.Json htsget = j.at("htsget"); final mjson.Json errorJson = htsget.at("error"); if (errorJson != null) { resp.error = errorJson.asString(); } final mjson.Json messageJson = htsget.at("message"); if (errorJson != null) { resp.message = messageJson.asString(); } return resp; }

Target:
public static HtsgetErrorResponse parse(final String s) { final mjson.Json j = mjson.Json.read(s); final mjson.Json htsget = j.at("htsget"); if (htsget == null) { throw new IllegalStateException(new HtsgetMalformedResponseException("No htsget key found in response")); } final mjson.Json errorJson = htsget.at("error"); final mjson.Json messageJson = htsget.at("message"); return new HtsgetErrorResponse( errorJson == null ? null : errorJson.asString(), messageJson == null ? null : messageJson.asString()); }
Source:
public void persistTags(String sessionId, SessionMetaDataStorage metaDataStorage) { Set<TagEntity> tags = new HashSet<TagEntity>(); for (TagEntity tagEntity : metaDataStorage.getTagsForSaveOrUpdate()) { try { getHibernateTemplate().saveOrUpdate(tagEntity); } catch (HibernateException e ) { log.error("Cannot add new tag: {}", tagEntity.getName()); e.printStackTrace(); } } List<TagEntity> sessionTagList = getHibernateTemplate().find("from TagEntity"); for (String tagName : metaDataStorage.getSessionTags()) { for (TagEntity tagEntity : sessionTagList) { if (tagEntity.getName().equals(tagName)) tags.add(tagEntity); } } if (!tags.isEmpty()) { List<SessionData> sessionsById = getHibernateTemplate().find("from SessionData s where s.sessionId=?", sessionId); for (SessionData sessionData : sessionsById) { sessionData.setTags(tags); getHibernateTemplate().saveOrUpdate(sessionData); } } else log.info("No tags for mark session {}", sessionId); }

Target:
public void persistTags(String sessionId, SessionMetaDataStorage metaDataStorage) { Set<TagEntity> sessionTagList = new HashSet<TagEntity>(); for (TagEntity tagEntity : metaDataStorage.getTagsForSaveOrUpdate()) { try { getHibernateTemplate().saveOrUpdate(tagEntity); } catch (HibernateException e) { log.error("Cannot add new tag", e); } } sessionTagList.addAll(getHibernateTemplate().findByNamedParam("select tags from TagEntity as tags " + "where tags.name in (:sTagsName)", "sTagsName", metaDataStorage.getSessionTags())); if (!sessionTagList.isEmpty()) { List<SessionData> sessionsById = getHibernateTemplate().find("from SessionData s where s.sessionId=?", sessionId); for (SessionData sessionData : sessionsById) { sessionData.setTags(sessionTagList); getHibernateTemplate().saveOrUpdate(sessionData); } } else log.info("No tags for mark session {}", sessionId); }
Source:
private static List<PeerDiscovery> buildDiscoveries(NetworkParameters params, String[] seeds) { List<PeerDiscovery> discoveries = new ArrayList<PeerDiscovery>(seeds != null ? seeds.length : 0); for (String seed : seeds) discoveries.add(new DnsSeedDiscovery(params, seed)); return discoveries; }

Target:
private static List<PeerDiscovery> buildDiscoveries(NetworkParameters params, String[] seeds) { List<PeerDiscovery> discoveries = new ArrayList<PeerDiscovery>(); if (seeds != null) for (String seed : seeds) discoveries.add(new DnsSeedDiscovery(params, seed)); return discoveries; }
Source:
public static void checkTransactionExists(TransactionManager tm, boolean isExpectTransaction) { try { Transaction tx = tm.getTransaction(); if(!isExpectTransaction && tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION) { throw new RuntimeException("We do not expect transaction would be active - we haven't activated it in BMT bean"); } else if (isExpectTransaction && (tx == null || tx.getStatus() != Status.STATUS_ACTIVE)) { throw new RuntimeException("We do expect tranaction would be active - we have alredy activated it in BMT bean"); } } catch (SystemException e) { throw new RuntimeException("Cannot get the current transaction from injected TransationManager!", e); } }

Target:
public static void checkTransactionExists(TransactionManager tm, boolean isExpectTransaction) { try { Transaction tx = tm.getTransaction(); if(!isExpectTransaction && tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION) { Assert.fail("We do not expect transaction would be active - we haven't activated it in BMT bean"); } else if (isExpectTransaction && (tx == null || tx.getStatus() != Status.STATUS_ACTIVE)) { Assert.fail("We do expect tranaction would be active - we have alredy activated it in BMT bean"); } } catch (SystemException e) { throw new RuntimeException("Cannot get the current transaction from injected TransationManager!", e); } }
Source:
public static void init(IdentityManager testIdentityManager) { config = new Config(); objectMapper = new ObjectMapper(); objectWriterPrettyPrinter = objectMapper.writerWithDefaultPrettyPrinter(); identityManager = testIdentityManager; }

Target:
public static void init(IdentityManager testIdentityManager) { config = new Config(); objectMapper = new ObjectMapper(); identityManager = testIdentityManager; }
Source:
private Runnable addSecondaryWhenPrimaryIsNonNull(final MongoDBServer secondary) { return new Runnable() { @Override public void run() { Boolean isAvailable = secondary.getAttribute(MongoDBServer.SERVICE_UP); MongoDBServer primary = getPrimary(); if (isAvailable && primary != null) { primary.getClient().addMemberToReplicaSet(secondary, nextMemberId.incrementAndGet()); } else { executor.schedule(this, 3, TimeUnit.SECONDS); } } }; }

Target:
private Runnable addSecondaryWhenPrimaryIsNonNull(final MongoDBServer secondary) { return new Runnable() { @Override public void run() { Boolean isAvailable = secondary.getAttribute(MongoDBServer.SERVICE_UP); MongoDBServer primary = getPrimary(); if (isAvailable && primary != null) { primary.getClient().addMemberToReplicaSet(secondary, nextMemberId.incrementAndGet()); if (LOG.isInfoEnabled()) { LOG.info("{} added to replica set {}", secondary, getReplicaSetName()); } } else { if (LOG.isTraceEnabled()) { LOG.trace("Rescheduling addition of member to replica set {}: service_up={}, primary={}", new Object[]{secondary, getReplicaSetName(), isAvailable, primary}); } executor.schedule(this, 3, TimeUnit.SECONDS); } } }; }
Source:
public void isItemIndexChanged() { TreeItem oldItem = mock(TreeItem.class); when(tree.getItemByUuid(ITEM_UUID)).thenReturn(oldItem); when(oldItem.getLabel()).thenReturn(NAME); when(item.getParentItem()).thenReturn(parentItem); when(item.getUuid()).thenReturn("INDEX_CHANGED"); when(oldItem.getParentItem()).thenReturn(parentItem); when(oldItem.getUuid()).thenReturn(ITEM_UUID); when(parentItem.getUuid()).thenReturn(PARENT_UUID); when(parentItem.getChildCount()).thenReturn(2); when(parentItem.getChild(eq(0))).thenReturn(item); when(parentItem.getChild(eq(1))).thenReturn(oldItem); assertTrue(testedTreeExplorerView.isItemChanged(ITEM_UUID, PARENT_UUID, NAME, OptionalInt.of(0))); assertFalse(testedTreeExplorerView.isItemChanged(ITEM_UUID, PARENT_UUID, NAME, OptionalInt.of(1))); assertTrue(testedTreeExplorerView.isItemChanged(ITEM_UUID, PARENT_UUID, NAME, OptionalInt.of(2))); }

Target:
public void isItemIndexChanged() { TreeItem oldItem = mockOldItem(); when(item.getUuid()).thenReturn("INDEX_CHANGED"); when(parentItem.getChildCount()).thenReturn(2); when(parentItem.getChild(eq(0))).thenReturn(item); when(parentItem.getChild(eq(1))).thenReturn(oldItem); assertTrue(testedTreeExplorerView.isItemChanged(ITEM_UUID, PARENT_UUID, NAME, OptionalInt.of(0))); assertFalse(testedTreeExplorerView.isItemChanged(ITEM_UUID, PARENT_UUID, NAME, OptionalInt.of(1))); assertTrue(testedTreeExplorerView.isItemChanged(ITEM_UUID, PARENT_UUID, NAME, OptionalInt.of(2))); }
Source:
private CompletableFuture<Boolean> openRepository(String repoId, boolean isPrimaryRepository) { assert Utility.isWellFormedRepoId(repoId); if (isPrimaryRepository) prefs.setLastViewedRepository(repoId); if (isAlreadyOpen(repoId) || models.isRepositoryPending(repoId)) { if (isPrimaryRepository) refreshUI(); return Futures.unit(false); } models.queuePendingRepository(repoId); return isRepositoryValid(repoId).thenCompose(valid -> { if (!valid) { return Futures.unit(false); } else { logger.info("Opening " + repoId); UI.status.displayMessage("Opening " + repoId); Platform.runLater(() -> UI.events.triggerEvent(new RepoOpeningEvent(repoId, isPrimaryRepository))); return repoOpControl.openRepository(repoId) .thenApply(models::addPending) .thenRun(this::refreshUI) .thenRun(() -> Platform.runLater(() -> UI.events.triggerEvent(new RepoOpenedEvent(repoId, isPrimaryRepository)) ) ) .thenCompose(n -> getRateLimitResetTime()) .thenApply(this::updateRemainingRate) .thenApply(rateLimits -> true) .exceptionally(withResult(false)); } }); }

Target:
private CompletableFuture<Boolean> openRepository(String repoId, boolean isPrimaryRepository) { assert Utility.isWellFormedRepoId(repoId); if (isPrimaryRepository) prefs.setLastViewedRepository(repoId); if (isAlreadyOpen(repoId) || models.isRepositoryPending(repoId)) { if (isPrimaryRepository) refreshUI(); return Futures.unit(false); } models.queuePendingRepository(repoId); return isRepositoryValid(repoId).thenCompose(valid -> { if (!valid) { return Futures.unit(false); } logger.info("Opening " + repoId); UI.status.displayMessage("Opening " + repoId); Platform.runLater(() -> UI.events.triggerEvent(new RepoOpeningEvent(repoId, isPrimaryRepository))); return repoOpControl.openRepository(repoId) .thenApply(models::addPending) .thenRun(this::refreshUI) .thenRun(() -> Platform.runLater(() -> UI.events.triggerEvent(new RepoOpenedEvent(repoId, isPrimaryRepository)) ) ) .thenCompose(n -> getRateLimitResetTime()) .thenApply(this::updateRemainingRate) .thenApply(rateLimits -> true) .exceptionally(withResult(false)); }); }
Source:
public void validateInput() throws RequiredFieldException { documentName = et_document_name.getEditableText().toString(); if (documentName.length() == 0 || documentName.equals("")) throw new RequiredFieldException(getResources().getString(R.string.name), getString(R.string.message_field_required)); documentDescription = et_document_description.getEditableText().toString(); if (documentDescription.length() == 0 || documentDescription.equals("")) throw new RequiredFieldException(getResources().getString(R.string.description), getString(R.string.message_field_required)); if (documentAction == getResources().getString(R.string.update_document)) { updatedDocument = document; updatedDocument.setName(documentName); updatedDocument.setDescription(documentDescription); updatedDocument.setFileName(fileChoosen.getName()); updatedDocument.setSize(fileChoosen.length()); mDocumentDialogPresenter.updateDocument(entityType, entityId, document.getId(), documentName, documentDescription, fileChoosen); } else if (documentAction == getResources().getString(R.string.upload_document)) { createdDocument = new Document(); createdDocument.setName(documentName); createdDocument.setDescription(documentDescription); createdDocument.setFileName(fileChoosen.getName()); createdDocument.setParentEntityType(entityType); createdDocument.setParentEntityId(entityId); createdDocument.setSize(fileChoosen.length()); mDocumentDialogPresenter.createDocument(entityType, entityId, documentName, documentDescription, fileChoosen); } }

Target:
public void validateInput() throws RequiredFieldException { documentName = et_document_name.getEditableText().toString(); if (documentName.length() == 0 || documentName.equals("")) throw new RequiredFieldException(getResources().getString(R.string.name), getString(R.string.message_field_required)); documentDescription = et_document_description.getEditableText().toString(); if (documentDescription.length() == 0 || documentDescription.equals("")) throw new RequiredFieldException(getResources().getString(R.string.description), getString(R.string.message_field_required)); if (documentAction.equals(getResources().getString(R.string.update_document))) { updatedDocument = document; addBasicInfo(updatedDocument, documentName, documentDescription, fileChoosen.getName(), fileChoosen.length()); mDocumentDialogPresenter.updateDocument(entityType, entityId, document.getId(), documentName, documentDescription, fileChoosen); } else if (documentAction.equals(getResources().getString(R.string.upload_document))) { createdDocument = new Document(); addBasicInfo(createdDocument, documentName, documentDescription, fileChoosen.getName(), fileChoosen.length()); createdDocument.setParentEntityType(entityType); createdDocument.setParentEntityId(entityId); mDocumentDialogPresenter.createDocument(entityType, entityId, documentName, documentDescription, fileChoosen); } }
Source:
private String[] cgitUntracked() throws Exception { FS fs = db.getFS(); ProcessBuilder builder = fs.runInShell("git", new String[] { "ls-files", "--others", "--exclude-standard", "-o" }); builder.directory(db.getWorkTree()); builder.environment().put("HOME", fs.userHome().getAbsolutePath()); ExecutionResult result = fs.execute(builder, new ByteArrayInputStream(new byte[0])); String errorOut = toString(result.getStderr()); assertEquals("External git failed", "exit 0\n", "exit " + result.getRc() + '\n' + errorOut); try (BufferedReader r = new BufferedReader(new InputStreamReader( new BufferedInputStream(result.getStdout().openInputStream()), Constants.CHARSET))) { return r.lines().toArray(String[]::new); } }

Target:
private String[] cgitUntracked() throws Exception { FS fs = db.getFS(); ProcessBuilder builder = fs.runInShell("git", new String[] { "ls-files", "--exclude-standard", "-o" }); builder.directory(db.getWorkTree()); builder.environment().put("HOME", fs.userHome().getAbsolutePath()); ExecutionResult result = fs.execute(builder, new ByteArrayInputStream(new byte[0])); String errorOut = toString(result.getStderr()); assertEquals("External git failed", "exit 0\n", "exit " + result.getRc() + '\n' + errorOut); try (BufferedReader r = new BufferedReader(new InputStreamReader( new BufferedInputStream(result.getStdout().openInputStream()), Constants.CHARSET))) { return r.lines().toArray(String[]::new); } }
Source:
private void verifyRedirectToWelcomeStrangerPage(AppUrl url, String unregUsername) { printUrl(url.toAbsoluteString()); currentPage.navigateTo(url); AssertHelper.assertContainsRegex("{*}" + unregUsername + "{*}Ooops! Your Google account is not known to TEAMMATES{*}", currentPage.getPageSource()); }

Target:
private void verifyRedirectToWelcomeStrangerPage(AppUrl url, String unregUsername) { printUrl(url.toAbsoluteString()); currentPage.navigateTo(url); AssertHelper.assertContainsRegex( unregUsername + "{*}Ooops! Your Google account is not known to TEAMMATES", currentPage.getPageSource()); }
Source:
protected void setUsernameInDrawer(RelativeLayout navigationDrawerLayout, Account account) { if (navigationDrawerLayout != null && getAccount() != null) { TextView username = (TextView) navigationDrawerLayout.findViewById(R.id.drawer_username); int lastAtPos = account.name.lastIndexOf("@"); username.setText(account.name.substring(0, lastAtPos)); } }

Target:
protected void setUsernameInDrawer(RelativeLayout navigationDrawerLayout, Account account) { if (navigationDrawerLayout != null && account != null) { TextView username = (TextView) navigationDrawerLayout.findViewById(R.id.drawer_username); int lastAtPos = account.name.lastIndexOf("@"); username.setText(account.name.substring(0, lastAtPos)); } }
Source:
public Object getParent(Object element) { if (element instanceof FileDiffRegion || element instanceof Folder) { return parents.get(element); } return null; }

Target:
public Object getParent(Object element) { return parents.get(element); }
Source:
private boolean validateMetaConstraint(ValidationContext<?> validationContext, ValueContext<?, Object> valueContext, Object parent, MetaConstraint<?> metaConstraint) { ValueContext.ValueState<Object> originalValueState = valueContext.getCurrentValueState(); valueContext.appendNode( metaConstraint.getLocation() ); boolean success = true; if ( isValidationRequired( validationContext, valueContext, metaConstraint ) ) { Object valueToValidate = null; if ( parent != null ) { valueToValidate = valueContext.getValue( parent, metaConstraint.getLocation() ); valueContext.setCurrentValidatedValue( valueToValidate ); } success = metaConstraint.validateConstraint( validationContext, valueContext ); validationContext.markConstraintProcessed( valueContext.getCurrentBean(), valueContext.getPropertyPath(), metaConstraint ); } valueContext.resetValueState( originalValueState ); return success; }

Target:
private boolean validateMetaConstraint(ValidationContext<?> validationContext, ValueContext<?, Object> valueContext, Object parent, MetaConstraint<?> metaConstraint) { ValueContext.ValueState<Object> originalValueState = valueContext.getCurrentValueState(); valueContext.appendNode( metaConstraint.getLocation() ); boolean success = true; if ( isValidationRequired( validationContext, valueContext, metaConstraint ) ) { if ( parent != null ) { valueContext.setCurrentValidatedValue( valueContext.getValue( parent, metaConstraint.getLocation() ) ); } success = metaConstraint.validateConstraint( validationContext, valueContext ); validationContext.markConstraintProcessed( valueContext.getCurrentBean(), valueContext.getPropertyPath(), metaConstraint ); } valueContext.resetValueState( originalValueState ); return success; }
Source:
protected void runInternal() { try { wbqCapacityCounter().incrementBackup(transactionId, getPartitionId()); } catch (ReachedMaxSizeException e) { throw new TransactionException(e); } if (!recordStore.txnLock(getKey(), lockOwner, threadId, getCallId(), LOCK_TTL_MILLIS, true)) { wbqCapacityCounter().decrement(transactionId, getPartitionId()); throw new TransactionException("Lock is not owned by the transaction! Caller: " + lockOwner + ", Owner: " + recordStore.getLockOwnerInfo(getKey())); } }

Target:
protected void runInternal() { wbqCapacityCounter().increment(transactionId, true); if (!recordStore.txnLock(getKey(), lockOwnerUuid, threadId, getCallId(), LOCK_TTL_MILLIS, true)) { wbqCapacityCounter().decrement(transactionId); throw new TransactionException("Lock is not owned by the transaction! Caller: " + lockOwnerUuid + ", Owner: " + recordStore.getLockOwnerInfo(getKey())); } }
Source:
private static void saveResults(String filename, Map<Integer, CorefChain> chains) throws IOException { FileWriter fout = new FileWriter(filename); BufferedWriter bout = new BufferedWriter(fout); Map<Integer, CorefChain> sorted = new TreeMap<>(chains); for (Map.Entry<Integer, CorefChain> entry : sorted.entrySet()) { saveKey(bout, entry.getKey(), entry.getValue()); } bout.flush(); bout.close(); fout.close(); }

Target:
private static void saveResults(String filename, Map<Integer, CorefChain> chains) throws IOException { FileWriter fout = new FileWriter(filename); BufferedWriter bout = new BufferedWriter(fout); List<Integer> keys = new ArrayList<>(chains.keySet()); Collections.sort(keys); for (Integer key : keys) { saveKey(bout, key, chains.get(key)); } bout.flush(); bout.close(); fout.close(); }
Source:
void poll(RequestRegistrationCallback<GetOperation> requestRegistrationCallback) { Iterator<Map.Entry<Integer, GetRequestInfo>> inFlightRequestsIterator = correlationIdToGetRequestInfo.entrySet().iterator(); while (inFlightRequestsIterator.hasNext()) { Map.Entry<Integer, GetRequestInfo> entry = inFlightRequestsIterator.next(); if (time.milliseconds() - entry.getValue().startTimeMs > routerConfig.routerRequestTimeoutMs) { operationTracker.onResponse(entry.getValue().replicaId, false); setOperationException( new RouterException("Timed out waiting for responses", RouterErrorCode.OperationTimedOut)); inFlightRequestsIterator.remove(); } else { break; } } checkAndMaybeComplete(); if (isOperationComplete()) { return; } Iterator<ReplicaId> replicaIterator = operationTracker.getReplicaIterator(); while (replicaIterator.hasNext()) { ReplicaId replicaId = replicaIterator.next(); String hostname = replicaId.getDataNodeId().getHostname(); Port port = new Port(replicaId.getDataNodeId().getPort(), PortType.PLAINTEXT); GetRequest getRequest = createGetRequest(blobId, getOperationFlag()); RequestInfo request = new RequestInfo(hostname, port, getRequest); int correlationId = getRequest.getCorrelationId(); correlationIdToGetRequestInfo.put(correlationId, new GetRequestInfo(replicaId, time.milliseconds())); requestRegistrationCallback.registerRequestToSend(this, request); replicaIterator.remove(); } }

Target:
void poll(RequestRegistrationCallback<GetOperation> requestRegistrationCallback) { cleanupExpiredInFlightRequests(); checkAndMaybeComplete(); if (!isOperationComplete()) { fetchRequests(requestRegistrationCallback); } }
Source:
public static Map<String, Object> deserializeStateMap(final Map<String, Object> serializedStateMap) { final Map<String, Object> result = new HashMap<>(); for (final Map.Entry<String, Object> mapEntry : serializedStateMap.entrySet()) { final Object state = mapEntry.getValue(); if (state instanceof ByteBuffer) { final Object deserializedState = deserializeState((ByteBuffer)state); if (deserializedState == null) { throw new RuntimeException("Error while deserializing the operator state."); } else { result.put(mapEntry.getKey(), deserializedState); } } else { result.put(mapEntry.getKey(), state); } } return result; }

Target:
public static Map<String, Object> deserializeStateMap(final Map<String, Object> serializedStateMap) throws RuntimeException { final Map<String, Object> result = new HashMap<>(); for (final Map.Entry<String, Object> mapEntry : serializedStateMap.entrySet()) { final Object state = mapEntry.getValue(); if (state instanceof ByteBuffer) { try { final Object deserializedState = deserializeState((ByteBuffer)state); result.put(mapEntry.getKey(), deserializedState); } catch (final RuntimeException e) { throw e; } } else { result.put(mapEntry.getKey(), state); } } return result; }
Source:
private ObjectNode _createMappingsNode() { ObjectMapper mapper = new ObjectMapper(); ObjectNode propertiesNode = mapper.createObjectNode(); propertiesNode.put(RecordType.SCOPE.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.METRIC.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.TAGK.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.TAGV.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.NAMESPACE.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.RETENTION_DISCOVERY.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put("mts", _createFieldNodeNoAnalyzer(FIELD_TYPE_DATE)); ObjectNode typeNode = mapper.createObjectNode(); typeNode.put("properties", propertiesNode); ObjectNode mappingsNode = mapper.createObjectNode(); mappingsNode.put(TYPE_NAME, typeNode); return mappingsNode; }

Target:
private ObjectNode _createMappingsNode() { ObjectMapper mapper = new ObjectMapper(); ObjectNode propertiesNode = mapper.createObjectNode(); propertiesNode.put(RecordType.SCOPE.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.METRIC.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.TAGK.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.TAGV.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.NAMESPACE.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.RETENTION_DISCOVERY.getName(), _createFieldNode(FIELD_TYPE_INTEGER)); propertiesNode.put("mts", _createFieldNodeNoAnalyzer(FIELD_TYPE_DATE)); ObjectNode typeNode = mapper.createObjectNode(); typeNode.put("properties", propertiesNode); ObjectNode mappingsNode = mapper.createObjectNode(); mappingsNode.put(TYPE_NAME, typeNode); return mappingsNode; }
Source:
protected VDS checkForActiveVds() { List<VDS> hosts = getVdsDAO().getAllForStoragePoolAndStatus(getStoragePool().getId(), VDSStatus.Up); if (!hosts.isEmpty()) { try { return hosts.get(SecureRandom.getInstance("SHA1PRNG").nextInt(hosts.size())); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_IN_POOL); return null; }

Target:
protected VDS checkForActiveVds() { List<VDS> hosts = getVdsDAO().getAllForStoragePoolAndStatus(getStoragePool().getId(), VDSStatus.Up); if (!hosts.isEmpty()) { return hosts.get(new Random().nextInt(hosts.size())); } addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_IN_POOL); return null; }
Source:
public void importCertificate(Certificate cert) throws Exception { final Map<String, String> trustStoreProperties = cmHelper.getTrustStoreSystemProperties(); String storeType = trustStoreProperties.get(TRUST_STORE_TYPE_KEY); final String storeLoc = trustStoreProperties.get(TRUST_STORE_KEY); final String passkey = trustStoreProperties.get(TRUST_STORE_PASSWORD_KEY); if (storeType == null) { LOG.warn("{} is not defined. Switch to use JKS by default", TRUST_STORE_TYPE_KEY); storeType = JKS_TYPE; } if (StringUtils.isNotBlank(passkey) && !(JKS_TYPE.equals(storeType) && storeLoc == null) && cert != null) { addCertificateToTrustStore(cert); } else { LOG.info("importCertificate -- validation failed"); if (JKS_TYPE.equals(storeType) && storeLoc == null) { LOG.error("{} is not defined.", TRUST_STORE_KEY); } if (StringUtils.isBlank(passkey)) { LOG.error("invalid password"); } if (null == cert) { LOG.error("Certificate is null"); } } }

Target:
public void importCertificate(Certificate cert) throws CertificateManagerException { final Map<String, String> trustStoreProperties = cmHelper.getTrustStoreSystemProperties(); String storeType = trustStoreProperties.get(TRUST_STORE_TYPE_KEY); final String storeLoc = trustStoreProperties.get(TRUST_STORE_KEY); final String passkey = trustStoreProperties.get(TRUST_STORE_PASSWORD_KEY); if (storeType == null) { LOG.warn("{} is not defined. Switch to use JKS by default", TRUST_STORE_TYPE_KEY); storeType = JKS_TYPE; } if (StringUtils.isNotBlank(passkey) && !(JKS_TYPE.equals(storeType) && storeLoc == null) && cert != null) { addCertificateToTrustStore(cert); } else { LOG.info("importCertificate -- validation failed"); if (JKS_TYPE.equals(storeType) && storeLoc == null) { LOG.error("{} is not defined.", TRUST_STORE_KEY); } if (StringUtils.isBlank(passkey)) { LOG.error("invalid password"); } if (null == cert) { LOG.error("Certificate is null"); } } }
Source:
public void post(Object event) { EventHandlerMethod[] handlers = byEventBaked.get( event.getClass() ); if ( handlers != null ) { for ( int i = 0; i < handlers.length; i++ ) { try { handlers[i].invoke( event ); } catch ( IllegalAccessException ex ) { throw new Error( "Method became inaccessible: " + event, ex ); } catch ( IllegalArgumentException ex ) { throw new Error( "Method rejected target/argument: " + event, ex ); } catch ( InvocationTargetException ex ) { logger.log( Level.WARNING, MessageFormat.format( "Error dispatching event {0} to listener {1}", event, handlers[i].getListener() ), ex.getCause() ); } } } }

Target:
public void post(Object event) { EventHandlerMethod[] handlers = byEventBaked.get( event.getClass() ); if ( handlers != null ) { for ( EventHandlerMethod method : handlers ) { try { method.invoke( event ); } catch ( IllegalAccessException ex ) { throw new Error( "Method became inaccessible: " + event, ex ); } catch ( IllegalArgumentException ex ) { throw new Error( "Method rejected target/argument: " + event, ex ); } catch ( InvocationTargetException ex ) { logger.log( Level.WARNING, MessageFormat.format( "Error dispatching event {0} to listener {1}", event, method.getListener() ), ex.getCause() ); } } } }
Source:
public static Function<Resource, TreeSet<Long>> resourceToPortSet() { return new Function<Resource, TreeSet<Long>>() { @Override @NotNull public TreeSet<Long> apply(@Nullable Resource resource) { return resourceValueRange(Optional.fromNullable(resource)); } }; }

Target:
public static Function<Resource, TreeSet<Long>> resourceToPortSet() { return ResourceToPortSet.INSTANCE; }
Source:
private static String executeProcess(final CliCommandBuilder commandBuilder, final boolean logFailure, final Map<String, String> env) { Process cliProc = null; try { cliProc = Launcher.of(commandBuilder) .addEnvironmentVariables(env) .launch(); } catch (IOException e) { fail("Failed to start CLI process: " + e.getLocalizedMessage()); } final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteArrayOutputStream err = new ByteArrayOutputStream(); CustomCLIExecutor.ConsoleConsumer.start(cliProc.getInputStream(), out); CustomCLIExecutor.ConsoleConsumer.start(cliProc.getErrorStream(), err); int exitCode = Integer.MIN_VALUE; try { boolean finished = cliProc.waitFor(CLI_PROC_TIMEOUT, TimeUnit.MILLISECONDS); if (finished) { exitCode = cliProc.exitValue(); } else { LOGGER.info("A timeout has occurred while invoking CLI command."); } } catch (InterruptedException e1) { Assert.fail("Interupted while waiting. Error Message" + e1.getMessage()); } finally { cliProc.destroyForcibly(); } String cliOutput = null; try { cliOutput = out.toString(StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { fail("UTF8 charset doesn't exist"); } if (logFailure && exitCode != 0) { LOGGER.info("Command's output: '" + cliOutput + "'"); if (err.size() > 0) { LOGGER.info("Command's error log: '" + err.toString() + "'"); } else { LOGGER.info("No output data for the command."); } } return exitCode + ": " + cliOutput; }

Target:
private static String executeProcess(final CliCommandBuilder commandBuilder, final boolean logFailure, final Map<String, String> env) { Process cliProc = null; try { cliProc = Launcher.of(commandBuilder) .addEnvironmentVariables(env) .launch(); } catch (IOException e) { fail("Failed to start CLI process: " + e.getLocalizedMessage()); } final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteArrayOutputStream err = new ByteArrayOutputStream(); CustomCLIExecutor.ConsoleConsumer.start(cliProc.getInputStream(), out); CustomCLIExecutor.ConsoleConsumer.start(cliProc.getErrorStream(), err); int exitCode = Integer.MIN_VALUE; try { boolean finished = cliProc.waitFor(CLI_PROC_TIMEOUT, TimeUnit.MILLISECONDS); if (finished) { exitCode = cliProc.exitValue(); } else { LOGGER.info("A timeout has occurred while invoking CLI command."); } } catch (InterruptedException e1) { Assert.fail("Interupted while waiting. Error Message" + e1.getMessage()); } finally { cliProc.destroyForcibly(); } final String cliOutput = out.toString(); if (logFailure && exitCode != 0) { LOGGER.info("Command's output: '" + cliOutput + "'"); if (err.size() > 0) { LOGGER.info("Command's error log: '" + err.toString() + "'"); } else { LOGGER.info("No output data for the command."); } } return exitCode + ": " + cliOutput; }
Source:
private BestPossibleStateOutput compute(ClusterEvent event, Map<String, Resource> resourceMap, CurrentStateOutput currentStateOutput) { ClusterDataCache cache = event.getAttribute("ClusterDataCache"); BestPossibleStateOutput output = new BestPossibleStateOutput(); JobRebalancer.resetActiveTaskCount(cache.getLiveInstances().keySet(), currentStateOutput); PriorityQueue<JobResourcePriority> jobResourceQueue = new PriorityQueue<JobResourcePriority>(); TaskDriver taskDriver = null; for (Resource resource : resourceMap.values()) { IdealState idealState = cache.getIdealState(resource.getResourceName()); if (idealState != null && idealState.getRebalancerClassName() != null && idealState.getRebalancerClassName().equals(JobRebalancer.class.getName())) { if (taskDriver == null) { taskDriver = new TaskDriver((HelixManager) event.getAttribute("helixmanager")); } jobResourceQueue.add(new JobResourcePriority(resource, taskDriver)); } else { computeResourceBestPossibleState(event, cache, currentStateOutput, resource, output); } } Iterator<JobResourcePriority> itr = jobResourceQueue.iterator(); while (itr.hasNext()) { computeResourceBestPossibleState(event, cache, currentStateOutput, itr.next()._resource, output); } return output; }

Target:
private BestPossibleStateOutput compute(ClusterEvent event, Map<String, Resource> resourceMap, CurrentStateOutput currentStateOutput) { ClusterDataCache cache = event.getAttribute("ClusterDataCache"); BestPossibleStateOutput output = new BestPossibleStateOutput(); PriorityQueue<ResourcePriority> resourcePriorityQueue = new PriorityQueue<ResourcePriority>(); for (Resource resource : resourceMap.values()) { resourcePriorityQueue.add(new ResourcePriority(resource, cache.getIdealState(resource.getResourceName()), (HelixManager) event.getAttribute("helixmanager"))); } Iterator<ResourcePriority> itr = resourcePriorityQueue.iterator(); while (itr.hasNext()) { computeResourceBestPossibleState(event, cache, currentStateOutput, itr.next()._resource, output); } return output; }
Source:
private RowExpression not(RowExpression expression) { return call("not", metadata.getFunctionManager().lookupFunction("not", fromTypes(BOOLEAN)), BOOLEAN, expression); }

Target:
private RowExpression not(RowExpression expression) { return call("not", new FunctionResolution(metadata.getFunctionManager()).notFunction(), BOOLEAN, expression); }
Source:
public static PassthroughServer remove(URI uri) { URI keyURI = createKey(uri); ServerDescriptor serverDescriptor = SERVERS.remove(keyURI); if (serverDescriptor != null) { for (Connection connection : serverDescriptor.getConnections().keySet()) { try { LOGGER.warn("Force close {}", formatConnectionId(connection)); connection.close(); } catch (AssertionError e) { } catch (IOException e) { } } PassthroughConnection connection = serverDescriptor.server.connectNewClient("destroy-connection"); for(Entry entry : serverDescriptor.knownEntities.entrySet()) { @SuppressWarnings("unchecked") Class<? extends Entity> type = (Class) entry.getKey(); List args = (List)entry.getValue(); Long version = (Long)args.get(0); String stringArg = (String)args.get(1); try { EntityRef entityRef = connection.getEntityRef(type, version, stringArg); entityRef.destroy(); } catch (EntityNotProvidedException ex) { LOGGER.error("Entity destroy failed: ", ex); } catch (EntityNotFoundException ex) { LOGGER.error("Entity destroy failed: ", ex); } catch (PermanentEntityException e) { LOGGER.error("Entity destroy failed (permanent???): ", e); } } serverDescriptor.server.stop(); LOGGER.info("Stopped PassthroughServer at {}", keyURI); return serverDescriptor.server; } else { return null; } }

Target:
public static PassthroughServer remove(URI uri) { URI keyURI = createKey(uri); ServerDescriptor serverDescriptor = SERVERS.remove(keyURI); if (serverDescriptor != null) { for (Connection connection : serverDescriptor.getConnections().keySet()) { try { LOGGER.warn("Force close {}", formatConnectionId(connection)); connection.close(); } catch (AssertionError e) { } catch (IOException e) { } } PassthroughConnection connection = serverDescriptor.server.connectNewClient("destroy-connection"); for(Entry entry : serverDescriptor.knownEntities.entrySet()) { @SuppressWarnings("unchecked") Class<? extends Entity> type = (Class) entry.getKey(); List args = (List)entry.getValue(); Long version = (Long)args.get(0); String stringArg = (String)args.get(1); try { EntityRef entityRef = connection.getEntityRef(type, version, stringArg); entityRef.destroy(); } catch (EntityNotProvidedException ex) { LOGGER.error("Entity destroy failed: ", ex); } catch (EntityNotFoundException ex) { LOGGER.error("Entity destroy failed: ", ex); } catch (PermanentEntityException ex) { LOGGER.error("Entity destroy failed (permanent???): ", ex); } } serverDescriptor.server.stop(); LOGGER.info("Stopped PassthroughServer at {}", keyURI); return serverDescriptor.server; } else { return null; } }
Source:
public Person updatePerson(Config config, Person person) { String requestJson = buildGsonWithUpdatePersonAdapter().toJson(person); String responseJson = postForJson(config, requestJson, "/person/{uuid}", person.getUuid()); return (Person) JsonUtils.readJson(responseJson, Person.class); }

Target:
public Person updatePerson(Config config, Person person) { String requestJson = buildGsonWithUpdatePersonAdapter().toJson(person); String responseJson = postForJson(config, requestJson, "/person/{uuid}?v=full", person.getUuid()); return (Person) JsonUtils.readJson(responseJson, Person.class); }
Source:
public DlmsDevice convertTo(final SmartMeteringDevice source, final Type<DlmsDevice> destinationType) { final DlmsDevice dlmsDevice = new DlmsDevice(); dlmsDevice.setDeviceIdentification(source.getDeviceIdentification()); dlmsDevice.setCommunicationMethod(source.getCommunicationMethod()); dlmsDevice.setCommunicationProvider(source.getCommunicationProvider()); dlmsDevice.setIccId(source.getICCId()); dlmsDevice.setHls3Active(source.isHLS3Active()); dlmsDevice.setHls4Active(source.isHLS4Active()); dlmsDevice.setHls5Active(source.isHLS5Active()); if (source.getMasterKey() != null) { final SecurityKey masterKey = new SecurityKey(); masterKey.setSecurityKeyType(SecurityKeyType.E_METER_MASTER); masterKey.setSecurityKey(source.getMasterKey()); masterKey.setValidFrom(source.getDeliveryDate()); dlmsDevice.addSecurityKey(masterKey); } if (source.getAuthenticationKey() != null) { final SecurityKey authenticationKey = new SecurityKey(); authenticationKey.setSecurityKeyType(SecurityKeyType.E_METER_AUTHENTICATION); authenticationKey.setSecurityKey(source.getAuthenticationKey()); authenticationKey.setValidFrom(source.getDeliveryDate()); dlmsDevice.addSecurityKey(authenticationKey); } if (source.getGlobalEncryptionUnicastKey() != null) { final SecurityKey encryptionKey = new SecurityKey(); encryptionKey.setSecurityKeyType(SecurityKeyType.E_METER_ENCRYPTION); encryptionKey.setSecurityKey(source.getGlobalEncryptionUnicastKey()); encryptionKey.setValidFrom(source.getDeliveryDate()); dlmsDevice.addSecurityKey(encryptionKey); } return dlmsDevice; }

Target:
public DlmsDevice convertTo(final SmartMeteringDevice source, final Type<DlmsDevice> destinationType) { final DlmsDevice dlmsDevice = new DlmsDevice(); dlmsDevice.setDeviceIdentification(source.getDeviceIdentification()); dlmsDevice.setCommunicationMethod(source.getCommunicationMethod()); dlmsDevice.setCommunicationProvider(source.getCommunicationProvider()); dlmsDevice.setIccId(source.getICCId()); dlmsDevice.setHls3Active(source.isHLS3Active()); dlmsDevice.setHls4Active(source.isHLS4Active()); dlmsDevice.setHls5Active(source.isHLS5Active()); if (source.getMasterKey() != null) { dlmsDevice.addSecurityKey(new SecurityKey(dlmsDevice, SecurityKeyType.E_METER_MASTER, source.getMasterKey(), source.getDeliveryDate(), null)); } if (source.getAuthenticationKey() != null) { dlmsDevice.addSecurityKey(new SecurityKey(dlmsDevice, SecurityKeyType.E_METER_AUTHENTICATION, source .getAuthenticationKey(), source.getDeliveryDate(), null)); } if (source.getGlobalEncryptionUnicastKey() != null) { dlmsDevice.addSecurityKey(new SecurityKey(dlmsDevice, SecurityKeyType.E_METER_ENCRYPTION, source .getGlobalEncryptionUnicastKey(), source.getDeliveryDate(), null)); } return dlmsDevice; }
Source:
public void testSerializationComplex() { TDigest digest = new TDigest(); addAll(digest, asList(0, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7)); TDigest deserialized = TDigest.deserialize(digest.serialize()); assertEquals(deserialized.getMin(), digest.getMin()); assertEquals(deserialized.getMax(), digest.getMax()); assertEquals(deserialized.getCount(), digest.getCount()); for (double quantile = 0; quantile <= 1; quantile += 0.1) { assertEquals(deserialized.valueAt(quantile), digest.valueAt(quantile)); } }

Target:
public void testSerializationComplex() { TDigest digest = new TDigest(); addAll(digest, asList(0, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7)); TDigest deserialized = TDigest.deserialize(digest.serialize()); assertSimilar(deserialized, digest); for (double quantile = 0; quantile <= 1; quantile += 0.1) { assertEquals(deserialized.valueAt(quantile), digest.valueAt(quantile)); } }
Source:
private static boolean isOptional(ExpressionTree expression) { return expression.symbolType().is(Optional.class.getName()) && !expression.is(Tree.Kind.NULL_LITERAL); }

Target:
private static boolean isOptional(ExpressionTree expression) { return expression.symbolType().is(OPTIONAL) && !isNull(expression); }
Source:
public void close() { closeAsync().awaitUninterruptibly(); }

Target:
public void close() { try { closeAsync().await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } }
Source:
public int compare(Repository db, FileElement localFile, FileElement remoteFile, String mergedFilePath, String toolName, BooleanOption prompt, BooleanOption gui, BooleanOption trustExitCode) throws DiffToolException { int rc = 0; IDiffTool tool = guessTool(toolName, gui); try { File workingDir = db.getWorkTree(); String localFilePath = localFile.getFile(workingDir).getPath(); String remoteFilePath = remoteFile.getFile(workingDir).getPath(); String command = tool.getCommand(); command = command.replace("$LOCAL", localFilePath); command = command.replace("$REMOTE", remoteFilePath); command = command.replace("$MERGED", mergedFilePath); Map<String, String> env = new TreeMap<>(); env.put(Constants.GIT_DIR_KEY, db.getDirectory().getAbsolutePath()); env.put("LOCAL", localFilePath); env.put("REMOTE", remoteFilePath); env.put("MERGED", mergedFilePath); ExecutionResult result = CommandExecutor.run(db.getFS(), command, workingDir, env); rc = result.getRc(); if (rc != 0) { boolean trust = config.isTrustExitCode(); if (trustExitCode.isDefined()) { trust = trustExitCode.toBoolean(); } if (trust) { throw new DiffToolException( new String(result.getStderr().toByteArray())); } } } catch (Exception e) { throw new DiffToolException(e); } finally { localFile.cleanTemporaries(); remoteFile.cleanTemporaries(); } return rc; }

Target:
public ExecutionResult compare(Repository db, FileElement localFile, FileElement remoteFile, String mergedFilePath, String toolName, BooleanOption prompt, BooleanOption gui, BooleanOption trustExitCode) throws ToolException { IDiffTool tool = guessTool(toolName, gui); try { File workingDir = db.getWorkTree(); String localFilePath = localFile.getFile().getPath(); String remoteFilePath = remoteFile.getFile().getPath(); String command = tool.getCommand(); command = command.replace("$LOCAL", localFilePath); command = command.replace("$REMOTE", remoteFilePath); command = command.replace("$MERGED", mergedFilePath); Map<String, String> env = new TreeMap<>(); env.put(Constants.GIT_DIR_KEY, db.getDirectory().getAbsolutePath()); env.put("LOCAL", localFilePath); env.put("REMOTE", remoteFilePath); env.put("MERGED", mergedFilePath); boolean trust = config.isTrustExitCode(); if (trustExitCode.isDefined()) { trust = trustExitCode.toBoolean(); } CommandExecutor cmdExec = new CommandExecutor(db.getFS(), trust); return cmdExec.run(command, workingDir, env); } catch (IOException | InterruptedException e) { throw new ToolException(e); } finally { localFile.cleanTemporaries(); remoteFile.cleanTemporaries(); } }
Source:
private GridData createServerUrlField(final ScrolledForm form) { Label labelUrl = new Label(form.getBody(), SWT.NULL); labelUrl.setText(Messages.ServerLocationWizardPage_label_host); serverUrlText = new Text(form.getBody(), SWT.BORDER | SWT.SINGLE); GridData urlGd = new GridData(GridData.FILL_HORIZONTAL); GridData gd = urlGd; gd.horizontalSpan = 2; serverUrlText.setLayoutData(gd); if (edit) { serverUrlText.setText(StringUtils.defaultString(server.getHost())); } else { serverUrlText.setText(DEFAULT_URL_SUGGESTION); } serverUrlText.setFocus(); serverUrlText.setSelection(serverUrlText.getText().length()); serverUrlText.addModifyListener(e -> { if (!edit && !serverIdManuallyChanged) { try { URL url = new URL(serverUrlText.getText()); serverIdText.removeModifyListener(idModifyListener); serverIdText.setText(StringUtils.substringBefore(url.getHost(), ".")); serverIdText.addModifyListener(idModifyListener); } catch (MalformedURLException e1) { } } dialogChanged(); }); return urlGd; }

Target:
private void createServerUrlField(final ScrolledForm form) { Label labelUrl = new Label(form.getBody(), SWT.NULL); labelUrl.setText(Messages.ServerLocationWizardPage_label_host); serverUrlText = new Text(form.getBody(), SWT.BORDER | SWT.SINGLE); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; serverUrlText.setLayoutData(gd); if (edit) { serverUrlText.setText(StringUtils.defaultString(server.getHost())); } else { serverUrlText.setText(DEFAULT_URL_SUGGESTION); } serverUrlText.setFocus(); serverUrlText.setSelection(serverUrlText.getText().length()); serverUrlText.addModifyListener(e -> { if (!edit && !serverIdManuallyChanged) { try { URL url = new URL(serverUrlText.getText()); serverIdText.removeModifyListener(idModifyListener); serverIdText.setText(StringUtils.substringBefore(url.getHost(), ".")); serverIdText.addModifyListener(idModifyListener); } catch (MalformedURLException e1) { } } dialogChanged(); }); }
Source:
private String constructParametersString(DetailAST methodDefToken) { StringBuilder sb = new StringBuilder(); final DetailAST parametersToken = methodDefToken.findFirstToken(TokenTypes.PARAMETERS); for (DetailAST ast = parametersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { if (ast.getType() != TokenTypes.PARAMETER_DEF) { continue; } final DetailAST typeToken = ast.findFirstToken(TokenTypes.TYPE); final DetailAST identToken = typeToken.findFirstToken(TokenTypes.IDENT); String parameterType = ""; if (identToken != null) { parameterType = identToken.getText(); } else { DetailAST arrayDeclarator = typeToken.findFirstToken(TokenTypes.ARRAY_DECLARATOR); if (arrayDeclarator == null) { parameterType = typeToken.getFirstChild().getText(); } DetailAST arrayDeclaratorIterator = arrayDeclarator; while (arrayDeclaratorIterator != null) { DetailAST temp = arrayDeclaratorIterator.findFirstToken(TokenTypes.ARRAY_DECLARATOR); if (temp == null) { parameterType = arrayDeclaratorIterator.getFirstChild().getText(); break; } arrayDeclaratorIterator = temp; } } sb.append(parameterType).append("-"); } int size = sb.length(); if (size == 0) { return null; } return sb.substring(0, size - 1); }

Target:
private String constructParametersString(DetailAST methodDefToken) { final StringBuilder sb = new StringBuilder(); final DetailAST parametersToken = methodDefToken.findFirstToken(TokenTypes.PARAMETERS); for (DetailAST ast = parametersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { if (ast.getType() != TokenTypes.PARAMETER_DEF) { continue; } final DetailAST typeToken = ast.findFirstToken(TokenTypes.TYPE); final DetailAST identToken = typeToken.findFirstToken(TokenTypes.IDENT); String parameterType = ""; if (identToken != null) { parameterType = identToken.getText(); } else { DetailAST arrayDeclarator = typeToken.findFirstToken(TokenTypes.ARRAY_DECLARATOR); if (arrayDeclarator == null) { parameterType = typeToken.getFirstChild().getText(); } DetailAST arrayDeclaratorIterator = arrayDeclarator; while (arrayDeclaratorIterator != null) { DetailAST temp = arrayDeclaratorIterator.findFirstToken(TokenTypes.ARRAY_DECLARATOR); if (temp == null) { parameterType = arrayDeclaratorIterator.getFirstChild().getText(); break; } arrayDeclaratorIterator = temp; } } sb.append(parameterType).append("-"); } int size = sb.length(); if (size == 0) { return null; } return sb.substring(0, size - 1); }