auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String createTaskInStory(@PathParam("projectName") String projectName, @PathParam("storyId") long storyId, @QueryParam("username") String username, @QueryParam("password") String password, String taskJson) { InformationDecoder decoder = new InformationDecoder(); String newtaskId = ""; try { decoder.decode(username, password); decoder.decodeProjectName(projectName); mTaskWebService = new TaskWebService(decoder.getDecodeUserName(), decoder.getDecodePwd(), decoder.getDecodeProjectName()); newtaskId = mTaskWebService.createTaskInStory(storyId, taskJson); } catch (IOException e) { System.out .println("class: TaskWebServiceController, " + "method: createTaskInStory, " + "api:InformationDecoder, " + "exception: " + e.toString()); e.printStackTrace(); } catch (LogonException e) { System.out.println("class: TaskWebServiceController, " + "method: createTaskInStory, " + "exception: " + e.toString()); e.printStackTrace(); } catch (JSONException e) { System.out.println("class: TaskWebServiceController, " + "method: createTaskInStory, " + "exception: " + e.toString()); e.printStackTrace(); } return newtaskId; }

Target:
public String createTaskInStory(@PathParam("projectName") String projectName, @PathParam("storyId") long storyId, @QueryParam("username") String username, @QueryParam("password") String password, String taskJson) { InformationDecoder decoder = new InformationDecoder(); String newTaskId = ""; try { decoder.decode(username, password); decoder.decodeProjectName(projectName); mTaskWebService = new TaskWebService(decoder.getDecodeUsername(), decoder.getDecodePwd(), decoder.getDecodeProjectName()); newTaskId = mTaskWebService.createTaskInStory(storyId, taskJson); } catch (IOException e) { System.out .println("class: TaskWebServiceController, " + "method: createTaskInStory, " + "api:InformationDecoder, " + "exception: " + e.toString()); e.printStackTrace(); } catch (LogonException e) { System.out.println("class: TaskWebServiceController, " + "method: createTaskInStory, " + "exception: " + e.toString()); e.printStackTrace(); } catch (JSONException e) { System.out.println("class: TaskWebServiceController, " + "method: createTaskInStory, " + "exception: " + e.toString()); e.printStackTrace(); } return newTaskId; }
Source:
public void placeNewOrder(Market currentMarket, String symbol, int volume, double price, OrderType orderType) throws StockMarketExpection { if (price > cashInHand) { throw new StockMarketExpection( "Stock price is larger than cash in hand."); } if (orderType == OrderType.BUY) { if (OrderUtility.isAlreadyPresent(ordersPlaced, new BuyOrder( symbol, volume, price, this))) throw new StockMarketExpection( "Trader is trying to place two orders for the same stock."); } else { if (OrderUtility.isAlreadyPresent(ordersPlaced, new SellOrder( symbol, volume, price, this))) throw new StockMarketExpection( "Trader is trying to place two orders for the same stock."); } if (orderType == OrderType.SELL) { boolean ownsStock = false; for (int i = 0; i < position.size(); i++) { if (position.get(i).getSymbol().equals(symbol)) ownsStock = true; } if (!ownsStock) throw new StockMarketExpection( "Trader is trying to sell a stock that he doesn't own."); } if (orderType == OrderType.BUY) { Order newOrder = new BuyOrder(symbol, volume, price, this); position.add(new Stock("", newOrder.getStockSymbol(), price)); ordersPlaced.add(newOrder); currentMarket.addOrder(newOrder); } else { Order newOrder = new SellOrder(symbol, volume, price, this); position.add(new Stock("", newOrder.getStockSymbol(), price)); ordersPlaced.add(newOrder); currentMarket.addOrder(newOrder); } }

Target:
public void placeNewOrder(Market currentMarket, String symbol, int volume, double price, OrderType orderType) throws StockMarketExpection { if (price > cashInHand) { throw new StockMarketExpection( "Stock price is larger than cash in hand."); } if (orderType == OrderType.BUY) { if (OrderUtility.isAlreadyPresent(ordersPlaced, new BuyOrder( symbol, volume, price, this))) throw new StockMarketExpection( "Trader is trying to place two orders for the same stock."); Order newOrder = new BuyOrder(symbol, volume, price, this); position.add(new Stock("", newOrder.getStockSymbol(), price)); ordersPlaced.add(newOrder); currentMarket.addOrder(newOrder); } else { if (OrderUtility.isAlreadyPresent(ordersPlaced, new SellOrder( symbol, volume, price, this))) throw new StockMarketExpection( "Trader is trying to place two orders for the same stock."); boolean ownsStock = false; for (int i = 0; i < position.size(); i++) { if (position.get(i).getSymbol().equals(symbol)) ownsStock = true; } if (!ownsStock) throw new StockMarketExpection( "Trader is trying to sell a stock that he doesn't own."); } }
Source:
protected void handleGet(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { Matcher matcher = GET_JOB_EXECUTION_INFO_PATTERN.matcher(req.getRequestURI()); if(matcher.matches()) { String executionId = matcher.group(1); String jobDefinitionId = matcher.group(3); logger.info("Getting execution details of job in execution {}.", jobDefinitionId, executionId); Optional<JobExecution> jobExecution; try { jobExecution = executorService.getJobExecution(executionId, jobDefinitionId, session.getUser().getUserId()); } catch (CloudFlowException e) { sendErrorResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DEFAULT_500_ERROR_MESSAGE); return; } if(jobExecution.isPresent()) { sendResponse(resp, HttpServletResponse.SC_OK, toJsonMap(jobExecution.get())); } else { sendErrorResponse(resp, HttpServletResponse.SC_NOT_FOUND, String.format("Execution %s not found or doesn't have job with id %s.", executionId, jobDefinitionId)); } return; } }

Target:
protected void handleGet(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { Map<String, String> templateVariableToValue = new HashMap<>(); if (GET_JOB_EXECUTION_INFO_URI.match(req.getRequestURI(), templateVariableToValue)) { final String executionId = templateVariableToValue.get("executionId"); final String jobDefinitionId = templateVariableToValue.get("jobDefinitionId"); try { Integer.parseInt(executionId); Integer.parseInt(jobDefinitionId); } catch (NumberFormatException e) { sendErrorResponse(resp, HttpServletResponse.SC_BAD_REQUEST, "Invalid execution id" + " or job definition id."); return; } logger.info("Getting execution details of job in execution {}.", jobDefinitionId, executionId); JobExecution jobExecution; try { jobExecution = executorService.getJobExecution(executionId, templateVariableToValue.get( "jobPath"), session.getUser().getUserId()); } catch (CloudFlowNotFoundException e) { sendErrorResponse(resp, HttpServletResponse.SC_NOT_FOUND, e.getMessage()); return; } catch (CloudFlowException e) { sendErrorResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DEFAULT_500_ERROR_MESSAGE); return; } sendResponse(resp, HttpServletResponse.SC_OK, toJsonMap(jobExecution)); return; } }
Source:
public boolean processMessage(Message msg) { if (super.processMessage(msg) == HANDLED) { return HANDLED; } switch (msg.what) { case CONNECT_WIRED_HEADSET: sendInternalMessage(SWITCH_HEADSET); return HANDLED; case CONNECT_BLUETOOTH: if (!mHasUserExplicitlyLeftBluetooth) { sendInternalMessage(SWITCH_BLUETOOTH); } else { Log.i(this, "Not switching to BT route from speaker because user has " + "explicitly disconnected."); updateSystemAudioState(); } return HANDLED; case DISCONNECT_BLUETOOTH: updateSystemAudioState(); return HANDLED; case DISCONNECT_WIRED_HEADSET: updateSystemAudioState(); return HANDLED; case BT_AUDIO_DISCONNECT: return HANDLED; case CONNECT_DOCK: return HANDLED; case DISCONNECT_DOCK: if (!mCallsManager.hasVideoCall()) { sendInternalMessage(SWITCH_BASELINE_ROUTE); } return HANDLED; default: return NOT_HANDLED; } }

Target:
public boolean processMessage(Message msg) { if (super.processMessage(msg) == HANDLED) { return HANDLED; } switch (msg.what) { case CONNECT_WIRED_HEADSET: sendInternalMessage(SWITCH_HEADSET); return HANDLED; case CONNECT_BLUETOOTH: if (!mHasUserExplicitlyLeftBluetooth) { sendInternalMessage(SWITCH_BLUETOOTH); } else { Log.i(this, "Not switching to BT route from speaker because user has " + "explicitly disconnected."); updateSystemAudioState(); } return HANDLED; case DISCONNECT_BLUETOOTH: updateSystemAudioState(); return HANDLED; case DISCONNECT_WIRED_HEADSET: updateSystemAudioState(); return HANDLED; case BT_AUDIO_DISCONNECT: return HANDLED; case CONNECT_DOCK: return HANDLED; case DISCONNECT_DOCK: sendInternalMessage(SWITCH_BASELINE_ROUTE); return HANDLED; default: return NOT_HANDLED; } }
Source:
private List<ModuleConfig> deserializeModules(JsonObject configJson) { List<ModuleConfig> modules = new ArrayList<>(); JsonArray modulesFromJson = configJson.get("modules") == null ? null : configJson.get("modules").getAsJsonArray(); if (modulesFromJson != null) { for (JsonElement jsonElement : modulesFromJson) { modules.add(deserializeModule(jsonElement)); } } return modules; }

Target:
private List<ModuleConfig> deserializeModules(JsonObject configJson) { JsonArray modulesFromJson = configJson.get("modules") == null ? null : configJson.get("modules").getAsJsonArray(); if (modulesFromJson == null) { return Collections.emptyList(); } List<ModuleConfig> modules = new ArrayList<>(modulesFromJson.size()); for (JsonElement jsonElement : modulesFromJson) { modules.add(deserializeModule(jsonElement)); } return modules; }
Source:
public synchronized void notifyBarrierReceived(CheckpointBarrier barrier, InputChannelInfo channelInfo) throws IOException { long barrierId = barrier.getId(); int channelIndex = handler.getFlattenedChannelIndex(channelInfo); LOG.error("{}: Received barrier from channel ({}) @ {}.", handler.taskName, channelIndex, storeNewBuffers[channelIndex], barrierId); if (currentReceivedCheckpointId < barrierId) { handleNewCheckpoint(barrier); handler.executeInTaskThread(() -> handler.notifyCheckpoint(barrier), "notifyCheckpoint"); } if (barrierId == currentReceivedCheckpointId && storeNewBuffers[channelIndex]) { storeNewBuffers[channelIndex] = false; if (++numBarriersReceived == numOpenChannels) { allBarriersReceivedFuture.complete(null); } } }

Target:
public synchronized void notifyBarrierReceived(CheckpointBarrier barrier, InputChannelInfo channelInfo) throws IOException { long barrierId = barrier.getId(); if (currentReceivedCheckpointId < barrierId) { handleNewCheckpoint(barrier); handler.executeInTaskThread(() -> handler.notifyCheckpoint(barrier), "notifyCheckpoint"); } int channelIndex = handler.getFlattenedChannelIndex(channelInfo); if (barrierId == currentReceivedCheckpointId && storeNewBuffers[channelIndex]) { if (LOG.isDebugEnabled()) { LOG.debug("{}: Received barrier from channel @ {}.", handler.taskName, channelIndex, barrierId); } storeNewBuffers[channelIndex] = false; if (++numBarriersReceived == numOpenChannels) { allBarriersReceivedFuture.complete(null); } } }
Source:
protected QueryKeys<FeedbackResponseComment> getEntityQueryKeys(FeedbackResponseCommentAttributes attributes) { Long id = attributes.getId(); if (id != null) { return getEntityQueryKeys(id); } return load() .filter("courseId =", attributes.courseId) .filter("feedbackResponseId =", attributes.feedbackResponseId) .filter("createdAt =", TimeHelper.convertInstantToDate(attributes.createdAt)) .filter("giverEmail =", attributes.commentGiver) .keys(); }

Target:
protected QueryKeys<FeedbackResponseComment> getEntityQueryKeys(FeedbackResponseCommentAttributes attributes) { Long id = attributes.getId(); if (id != null) { return getEntityQueryKeys(id); } return load() .filter("feedbackResponseId =", attributes.feedbackResponseId) .filter("createdAt =", TimeHelper.convertInstantToDate(attributes.createdAt)) .filter("giverEmail =", attributes.commentGiver) .keys(); }
Source:
public void goToweb (View view) { String url = "<LINK_0>"; link(url); }

Target:
public void goToweb (View view) { link("<LINK_0>"); }
Source:
public InputStreamWithHints openNextWithHints() throws IOException { if (!iterator.hasNext()) { return null; } String key = iterator.next(); final GetObjectRequest request = new GetObjectRequest(bucket, key); S3Object object = new DefaultRetryable<S3Object>(format("Getting object '%s'", request.getKey())) { @Override public S3Object call() { return client.getObject(request); } }.executeWithCheckedException(retryExec, IOException.class); long objectSize = object.getObjectMetadata().getContentLength(); InputStream inputStream = new ResumableInputStream(object.getObjectContent(), new S3InputStreamReopener(client, request, objectSize, retryExec)); return new InputStreamWithHints(inputStream, String.format("s3://%s/%s", bucket, key)); }

Target:
public InputStreamWithHints openNextWithHints() throws IOException { if (!iterator.hasNext()) { return null; } final String key = iterator.next(); final GetObjectRequest request = new GetObjectRequest(bucket, key); S3Object object = new DefaultRetryable<S3Object>(format("Getting object '%s'", request.getKey())) { @Override public S3Object call() { return client.getObject(request); } }.executeWithCheckedException(retryExec, IOException.class); long objectSize = object.getObjectMetadata().getContentLength(); InputStream inputStream = new ResumableInputStream(object.getObjectContent(), new S3InputStreamReopener(client, request, objectSize, retryExec)); return new InputStreamWithHints(inputStream, String.format("s3://%s/%s", bucket, key)); }
Source:
public HuobiDepthResult( @JsonProperty("status") String status, @JsonProperty("ts") Date ts, @JsonProperty("tick") HuobiDepth tick, @JsonProperty("ch") String ch, @JsonProperty("err-code") String errCode, @JsonProperty("err-msg") String errMsg) { super(status, errCode, errMsg, tick); this.ts = ts; this.ch = ch; getResult().setTs(ts); }

Target:
public HuobiDepthResult( @JsonProperty("status") String status, @JsonProperty("ts") Date ts, @JsonProperty("tick") HuobiDepth tick, @JsonProperty("ch") String ch, @JsonProperty("err-code") String errCode, @JsonProperty("err-msg") String errMsg) { super(status, errCode, errMsg, tick); }
Source:
public PropertyManager reload() { try { putProperty(PROPMGR_DEVICE_ID, SCHEME_IMEI, deviceDetailsProvider.getDeviceId()); putProperty(PROPMGR_PHONE_NUMBER, SCHEME_TEL, deviceDetailsProvider.getLine1Number()); } catch (SecurityException e) { Timber.e(e); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); initUserDefined(prefs, KEY_METADATA_USERNAME, PROPMGR_USERNAME, SCHEME_USERNAME); initUserDefined(prefs, KEY_METADATA_PHONENUMBER, PROPMGR_PHONE_NUMBER, SCHEME_TEL); initUserDefined(prefs, KEY_METADATA_EMAIL, PROPMGR_EMAIL, SCHEME_MAILTO); if (getSingularProperty(PROPMGR_USERNAME) == null || getSingularProperty(PROPMGR_USERNAME).isEmpty()) { putProperty(PROPMGR_USERNAME, SCHEME_USERNAME, (String) GeneralSharedPreferences.getInstance().get(KEY_USERNAME)); } return this; }

Target:
public PropertyManager reload() { try { putProperty(PROPMGR_DEVICE_ID, "", deviceDetailsProvider.getDeviceId()); putProperty(PROPMGR_PHONE_NUMBER, SCHEME_TEL, deviceDetailsProvider.getLine1Number()); } catch (SecurityException e) { Timber.e(e); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); initUserDefined(prefs, KEY_METADATA_USERNAME, PROPMGR_USERNAME, SCHEME_USERNAME); initUserDefined(prefs, KEY_METADATA_PHONENUMBER, PROPMGR_PHONE_NUMBER, SCHEME_TEL); initUserDefined(prefs, KEY_METADATA_EMAIL, PROPMGR_EMAIL, SCHEME_MAILTO); if (getSingularProperty(PROPMGR_USERNAME) == null || getSingularProperty(PROPMGR_USERNAME).isEmpty()) { putProperty(PROPMGR_USERNAME, SCHEME_USERNAME, (String) GeneralSharedPreferences.getInstance().get(KEY_USERNAME)); } return this; }
Source:
public InputStream getInputStream() { if (logToFile || logToStderr) { inputStream = new FilterInputStream(provider.getInputStream()) { @Override public int read(byte[] b, int off, int len) throws IOException { int bytes = super.read(b, off, len); byte[] payload = new byte[bytes]; System.arraycopy(b, off, payload, 0, bytes); if (logToStderr) { System.err.println(id + " to LSP4E:" + new String(payload)); } if (logToFile) { log("\n" + id + " to LSP4E:" + new String(payload)); } return bytes; } }; } else { inputStream = provider.getInputStream(); } return inputStream; }

Target:
public InputStream getInputStream() { inputStream = provider.getInputStream(); if (inputStream != null) { inputStream = new FilterInputStream(inputStream) { @Override public int read(byte[] b, int off, int len) throws IOException { int bytes = super.read(b, off, len); byte[] payload = new byte[bytes]; System.arraycopy(b, off, payload, 0, bytes); if (logToStderr) { System.err.println(id + " to LSP4E:" + new String(payload)); } if (logToFile) { log("\n" + id + " to LSP4E:" + new String(payload)); } return bytes; } }; } return inputStream; }
Source:
public Exercise call() throws Exception { logger.info("Checking adaptive exercises availability"); Exercise exercise = tmcServerCommunicationTaskFactory.getAdaptiveExercise().call(); if (exercise == null) { return null; } try { exercise.setCourseName(TmcSettingsHolder.get().getCurrentCourse().get().getName()); } catch (Exception e) { exercise.setCourseName("None"); } exercise.setReturnable(true); exercise.setAdaptive(true); byte[] zipb = tmcServerCommunicationTaskFactory.getDownloadingExerciseZipTask(exercise).call(); Progress progress = new Progress(1); extractProject(zipb, exercise, progress); return exercise; }

Target:
public Exercise call() throws Exception { logger.info("Checking adaptive exercises availability"); Exercise exercise = tmcServerCommunicationTaskFactory.getAdaptiveExercise().call(); if (exercise == null) { return null; } try { exercise.setCourseName(TmcSettingsHolder.get().getCurrentCourse().get().getName()); } catch (Exception e) { logger.warn("Setting course name failed, setting it to 'None'.", e); exercise.setCourseName("None"); } exercise.setReturnable(true); exercise.setAdaptive(true); byte[] zipb = tmcServerCommunicationTaskFactory.getDownloadingExerciseZipTask(exercise).call(); Progress progress = new Progress(1); extractProject(zipb, exercise, progress); return exercise; }
Source:
public JSONObject generatePayload(String fileUrl, String password, String fileLocation) { JSONObject payload = new JSONObject(); try { payload.put("fileURL", fileUrl); payload.put("ftpPassword", password); payload.put("fileLocation", fileLocation); } catch (JSONException e) { Log.e(TAG, "JSON Exception in preparing payload. " + e.getLocalizedMessage()); } return payload; }

Target:
public JSONObject generatePayload(String fileUrl, String password, String fileLocation) { JSONObject payload = new JSONObject(); try { payload.put(org.wso2.iot.agent.utils.Constants.FileTransfer.FILE_URL, fileUrl); payload.put(org.wso2.iot.agent.utils.Constants.FileTransfer.FTP_PASSWORD, password); payload.put(org.wso2.iot.agent.utils.Constants.FileTransfer.FILE_LOCATION, fileLocation); } catch (JSONException e) { Log.e(TAG, "JSON Exception in preparing payload. " + e.getLocalizedMessage()); } return payload; }
Source:
static boolean isValid(byte code) { return code >= 0 && code <= 7; }

Target:
static boolean isValid(byte code) { return code >= 0 && code < MAX_CODE; }
Source:
public boolean deleteMetaDataFile() { try { Files.delete(Paths.get(metaFile.getCanonicalPath())); LOGGER.log(Level.DEBUG, "Metadata file deleted!"); return true; } catch (IOException e) { LOGGER.log(Level.ERROR, "Metadata file could not be deleted!"); return false; } }

Target:
public boolean deleteMetaDataFile() { try { Files.delete(Paths.get(metaFile.getCanonicalPath())); if (LOGGER.isDebugEnabled()){ LOGGER.log(Level.DEBUG, "Metadata file deleted!"); } return true; } catch (IOException e) { if (LOGGER.isTraceEnabled()){ LOGGER.log(Level.ERROR, "Metadata file could not be deleted!"); } return false; } }
Source:
private String getFixedCommitMsgWithChangeId(String errMsg, RevCommit c) { final String changeId = "Change-Id:"; StringBuilder sb = new StringBuilder(); sb.append("ERROR: ").append(errMsg); sb.append("\n"); sb.append("Suggestion for commit message:\n"); if (c.getFullMessage().indexOf(changeId)==-1) { sb.append(c.getFullMessage()); sb.append("\n"); sb.append(changeId).append(" I").append(c.name()); } else { String lines[] = c.getFullMessage().trim().split("\n"); String lastLine = lines.length > 0 ? lines[lines.length - 1] : ""; if (lastLine.indexOf(changeId)==0) { for (int i = 0; i < lines.length - 1; i++) { sb.append(lines[i]); sb.append("\n"); } sb.append("\n"); sb.append(lastLine); } else { sb.append(c.getFullMessage()); sb.append("\n"); sb.append(changeId).append(" I").append(c.name()); sb.append("\nHint: A potential Change-Id was found, but it was not in the footer of the commit message."); } } String host; if (canonicalWebUrl != null) { try { host = new URL(canonicalWebUrl).getHost(); } catch (MalformedURLException e) { host = SystemReader.getInstance().getHostname(); } } else { host = SystemReader.getInstance().getHostname(); } sb.append("\n"); sb.append("Hint: To automatically add a Change-Id to commit messages, install the commit-msg hook:\n"); sb.append(" $ scp -p -P 29418 " + currentUser.getUserName() + "@" + host + ":hooks/commit-msg .git/hooks/"); return sb.toString(); }

Target:
private String getFixedCommitMsgWithChangeId(String errMsg, RevCommit c) { final String changeId = "Change-Id:"; StringBuilder sb = new StringBuilder(); sb.append("ERROR: ").append(errMsg); sb.append("\n"); sb.append("Suggestion for commit message:\n"); if (c.getFullMessage().indexOf(changeId)==-1) { sb.append(c.getFullMessage()); sb.append("\n"); sb.append(changeId).append(" I").append(c.name()); } else { String lines[] = c.getFullMessage().trim().split("\n"); String lastLine = lines.length > 0 ? lines[lines.length - 1] : ""; if (lastLine.indexOf(changeId)==0) { for (int i = 0; i < lines.length - 1; i++) { sb.append(lines[i]); sb.append("\n"); } sb.append("\n"); sb.append(lastLine); } else { sb.append(c.getFullMessage()); sb.append("\n"); sb.append(changeId).append(" I").append(c.name()); sb.append("\nHint: A potential Change-Id was found, but it was not in the footer of the commit message."); } } sb.append("\n"); sb.append("Hint: To automatically add a Change-Id to commit messages, install the commit-msg hook:\n"); sb.append(getCommitMessageHookInstallationHint()); return sb.toString(); }
Source:
public List<Payment> getAccountPayments(final UUID accountId, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext) throws PaymentApiException { return paymentProcessor.getAccountPayments(accountId, withPluginInfo, tenantContext, internalCallContextFactory.createInternalTenantContext(accountId, tenantContext)); }

Target:
public List<Payment> getAccountPayments(final UUID accountId, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext) throws PaymentApiException { return paymentProcessor.getAccountPayments(accountId, withPluginInfo, withAttempts, tenantContext, internalCallContextFactory.createInternalTenantContext(accountId, tenantContext)); }
Source:
public void switchLanguage(String langCodeCombined) throws IOException { String[] languageCode = langCodeCombined.split("_"); Locale locale; if (languageCode.length == 2) { locale = new Locale(languageCode[0], languageCode[1]); } else { locale = new Locale(languageCode[0]); } try { User user = serviceManager.getUserService().getById(serviceManager.getUserService().getAuthenticatedUser().getId()); user.setLanguage(locale.toString()); serviceManager.getUserService().save(user); } catch (DataException e) { logger.error("Error in saving user : " + e.getMessage()); } catch (DAOException e) { logger.error("Error in retrieving user" + e.getMessage()); } FacesContext context = FacesContext.getCurrentInstance(); context.getViewRoot().setLocale(locale); context.getExternalContext().getSessionMap().put(SESSION_LOCALE_FIELD_ID, locale); context.getExternalContext() .redirect(((HttpServletRequest) context.getExternalContext().getRequest()).getRequestURI()); }

Target:
public void switchLanguage(String langCodeCombined) throws IOException { String[] languageCode = langCodeCombined.split("_"); Locale locale; if (languageCode.length == 2) { locale = new Locale(languageCode[0], languageCode[1]); } else { locale = new Locale(languageCode[0]); } try { User user = serviceManager.getUserService().getById(serviceManager.getUserService().getAuthenticatedUser().getId()); user.setLanguage(locale.toString()); serviceManager.getUserService().save(user); } catch (DataException e) { Helper.setErrorMessage("Error in saving user", logger, e); } catch (DAOException e) { Helper.setErrorMessage("Error in retrieving user", logger, e); } FacesContext context = FacesContext.getCurrentInstance(); context.getViewRoot().setLocale(locale); context.getExternalContext().getSessionMap().put(SESSION_LOCALE_FIELD_ID, locale); context.getExternalContext() .redirect(((HttpServletRequest) context.getExternalContext().getRequest()).getRequestURI()); }
Source:
@Test public void multipartPartOptional() throws Exception { try { new Helper() .setMethod("POST") .setHasBody() .setUrl("<LINK_0>") .setPath("/foo/bar/") .setMultipart() .addPart("ping", null) .build(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("Multipart part must not be null: ping."); } }

Target:
@Test public void multipartPartOptional() throws Exception { try { new Helper() .setMethod("POST") .setHasBody() .setUrl("<LINK_0>") .setPath("/foo/bar/") .setMultipart() .addPart("ping", null) .build(); fail("Null multipart part is not allowed."); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("Multipart part must not be null: ping."); } }
Source:
public boolean hasResponseInCache() { return mResponses.size() > 0; }

Target:
public boolean hasResponseInCache() { return !mResponses.isEmpty(); }
Source:
public void testCompressedEncodingDecodingFields() { this.batch.setProtocol(Protocol.VERSION_1); EmbeddedChannel channel = new EmbeddedChannel(new CompressedBatchEncoder(), new BeatsParser()); channel.writeOutbound(this.batch); Object o = channel.readOutbound(); channel.writeInbound(o); Batch decodedBatch = (Batch) channel.readInbound(); assertMessages(this.batch, decodedBatch); }

Target:
public void testCompressedEncodingDecodingFields() { this.batch.setProtocol(Protocol.VERSION_1); Batch decodedBatch = decodeCompressedBatch(); assertMessages(this.batch, decodedBatch); }
Source:
protected void initCampaigns() { campaigns = new ArrayList<SwrveBaseCampaign>(); campaignsState = new HashMap<Integer, SwrveCampaignState>(); try { String campaignsFromCache = cachedLocalStorage.getSecureCacheEntryForUser(userId, CAMPAIGN_CATEGORY, getUniqueKey()); if (!SwrveHelper.isNullOrEmpty(campaignsFromCache)) { JSONObject campaignsJson = new JSONObject(campaignsFromCache); String campaignsStateFromCache = cachedLocalStorage.getCacheEntryForUser(userId, CAMPAIGNS_STATE_CATEGORY); if (!SwrveHelper.isNullOrEmpty(campaignsStateFromCache)) { JSONObject campaignsStateJson = new JSONObject(campaignsStateFromCache); Iterator<String> campaignIdIterator = campaignsStateJson.keys(); while(campaignIdIterator.hasNext()) { String campaignIdStr = campaignIdIterator.next(); try { int campaignId = Integer.parseInt(campaignIdStr); SwrveCampaignState campaignState = new SwrveCampaignState(campaignsStateJson.getJSONObject(campaignIdStr)); campaignsState.put(campaignId, campaignState); } catch(Exception exp) { SwrveLogger.e(LOG_TAG, "Could not load state for campaign " + campaignIdStr, exp); } } } updateCampaigns(campaignsJson, campaignsState); SwrveLogger.i(LOG_TAG, "Loaded campaigns from cache."); } else { invalidateETag(); } } catch (JSONException e) { invalidateETag(); SwrveLogger.e(LOG_TAG, "Invalid json in cache, cannot load campaigns", e); } catch (SecurityException e) { invalidateETag(); SwrveLogger.e(LOG_TAG, "Signature validation failed when trying to load campaigns from cache.", e); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("name", "Swrve.signature_invalid"); queueEvent("event", parameters, null, false); } }

Target:
protected void initCampaigns() { campaigns = new ArrayList<SwrveBaseCampaign>(); campaignsState = new HashMap<Integer, SwrveCampaignState>(); try { String campaignsFromCache = cachedLocalStorage.getSecureCacheEntryForUser(userId, CAMPAIGN_CATEGORY, getUniqueKey()); if (!SwrveHelper.isNullOrEmpty(campaignsFromCache)) { JSONObject campaignsJson = new JSONObject(campaignsFromCache); loadCampaignsStateFromCache(); updateCampaigns(campaignsJson, campaignsState); SwrveLogger.i(LOG_TAG, "Loaded campaigns from cache."); } else { invalidateETag(); } } catch (JSONException e) { invalidateETag(); SwrveLogger.e(LOG_TAG, "Invalid json in cache, cannot load campaigns", e); } catch (SecurityException e) { invalidateETag(); SwrveLogger.e(LOG_TAG, "Signature validation failed when trying to load campaigns from cache.", e); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("name", "Swrve.signature_invalid"); queueEvent("event", parameters, null, false); } }
Source:
private void generatePreparedStatements() { Map<Long, String> stringsWithoutPKAndExistsClauses = generatePreparedStatementsQueryStrings(); String ifExistsClause = " IF EXISTS"; Map<Long, String> finalSetOfQueryStrings = new HashMap<>(); for (Long currentIndexPos : stringsWithoutPKAndExistsClauses.keySet()) { StringBuilder aQueryStub = new StringBuilder(stringsWithoutPKAndExistsClauses.get(currentIndexPos)); buildWhereClauseForPrimaryKeys(aQueryStub); finalSetOfQueryStrings.put(currentIndexPos + getSlotIndexForMutationContextPreparedStatement(EnumSet.of(OperationContext.IF_EXISTS_CHECK_ABSENT)), aQueryStub.toString()); if (counterColumns.size() == 0) { finalSetOfQueryStrings.put(currentIndexPos + getSlotIndexForMutationContextPreparedStatement(EnumSet.of( OperationContext.IF_EXISTS_CHECK_PRESENT)), aQueryStub.toString() + ifExistsClause); } } for (Long currentIndexPos : finalSetOfQueryStrings.keySet()) { String currentQueryStr = finalSetOfQueryStrings.get(currentIndexPos); LOG.info("Registering query support for " + currentQueryStr); PreparedStatement preparedStatementForThisQuery = session.prepare(currentQueryStr); preparedStatementTypes.put(currentIndexPos, preparedStatementForThisQuery); } }

Target:
private void generatePreparedStatements() { cassandraPreparedStatementGenerationUtil = new CassandraPreparedStatementGenerator( pkColumnNames, counterColumns, listColumns, mapColumns, setColumns, columnDefinitions); cassandraPreparedStatementGenerationUtil.generatePreparedStatements(session, preparedStatementTypes, connectionStateManager.getKeyspaceName(), connectionStateManager.getTableName()); }
Source:
public static void register(AggregationImplModule mod) { for (var supportedType : DataTypes.PRIMITIVE_TYPES) { mod.register( Signature.aggregate( NAME, supportedType.getTypeSignature(), supportedType.getTypeSignature()), args -> { var arg = args.get(0); var info = new FunctionInfo( new FunctionIdent(NAME, args), arg, FunctionInfo.Type.AGGREGATE ); if (arg instanceof FixedWidthType) { return new FixedMinimumAggregation(info); } else { return new VariableMinimumAggregation(info); } } ); } }

Target:
public static void register(AggregationImplModule mod) { for (var supportedType : DataTypes.PRIMITIVE_TYPES) { var fixedWidthType = supportedType instanceof FixedWidthType; mod.register( Signature.aggregate( NAME, supportedType.getTypeSignature(), supportedType.getTypeSignature()), args -> { var arg = args.get(0); var info = new FunctionInfo( new FunctionIdent(NAME, args), arg, FunctionInfo.Type.AGGREGATE ); return fixedWidthType ? new FixedMinimumAggregation(info) : new VariableMinimumAggregation(info); } ); } }
Source:
public EnrolmentPeriodInClasses getClassesEnrollmentPeriod(ExecutionSemester executionSemester) { for (final EnrolmentPeriod enrolmentPeriod : this.getEnrolmentPeriodsSet()) { if (enrolmentPeriod.isForClasses() && enrolmentPeriod.getExecutionPeriod() == executionSemester) { return (EnrolmentPeriodInClasses) enrolmentPeriod; } } return null; }

Target:
public Optional<EnrolmentPeriod> getClassesEnrollmentPeriod(ExecutionSemester executionSemester) { return getEnrolmentPeriodsSet().stream().filter(ep -> ep.isForClasses() && ep.getExecutionPeriod() == executionSemester) .findAny(); }
Source:
public Account build() throws JSONException { checkAccountIdInContainers(); checkRequiredFields(version); switch (version) { case ACCOUNT_METADATA_VERSION_1: if (id == null) { throw new IllegalStateException("Cannot build account, id is not set"); } if (name == null) { throw new IllegalStateException("Cannot build account, name is not set"); } if (status == null) { throw new IllegalStateException("Cannot build account, status is not set"); } JSONObject jsonMetadata = new JSONObject(); jsonMetadata.put(ACCOUNT_METADATA_VERSION_KEY, version); jsonMetadata.put(ACCOUNT_ID_KEY, id); jsonMetadata.put(ACCOUNT_NAME_KEY, name); jsonMetadata.put(ACCOUNT_STATUS_KEY, status); JSONArray containerArray = new JSONArray(); for (Container container : idToContainerMetadataMap.values()) { containerArray.put(container.toJson()); } jsonMetadata.put(CONTAINERS_KEY, containerArray); return new Account(jsonMetadata); default: throw new IllegalStateException("Unsupported account metadata version=" + version); } }

Target:
public Account build() throws JSONException { return new Account(id, name, status, idToContainerMetadataMap.values()); }
Source:
public void onStart() throws Exception { try { startDispatcherServices(); } catch (Exception e) { final DispatcherException exception = new DispatcherException(String.format("Could not start the Dispatcher %s", getAddress()), e); onFatalError(exception); throw exception; } this.dispatcherBootstrap = this.dispatcherBootstrapFactory.apply(shutDownFuture::completeExceptionally); this.dispatcherBootstrap.initialize(this, this.getRpcService().getScheduledExecutor()); }

Target:
public void onStart() throws Exception { try { startDispatcherServices(); } catch (Throwable t) { final DispatcherException exception = new DispatcherException(String.format("Could not start the Dispatcher %s", getAddress()), t); onFatalError(exception); throw exception; } startRecoveredJobs(); this.dispatcherBootstrap = this.dispatcherBootstrapFactory.create( getSelfGateway(DispatcherGateway.class), this.getRpcService().getScheduledExecutor() , this::onFatalError); }
Source:
private View.OnClickListener validateAndSubmit() { return new View.OnClickListener() { @Override public void onClick(View view) { boolean hasErrors = false; if (mTitleField.getText().toString().length() == 0) { setEmpty("Title", mTitleField); hasErrors = true; } if (mDescriptionField.getText().toString().length() == 0) { setEmpty("Description", mDescriptionField); hasErrors = true; } if (mMiniSite == null) { setEmpty("Minisite", mDescriptionField); hasErrors = true; } if (mDate == null) { setEmpty("Deadline", mDescriptionField); hasErrors = true; } if (mUser == null) { setEmpty("User", mDescriptionField); hasErrors = true; } if (hasErrors) return; submitListener(); } }; }

Target:
private void validateAndSubmit() { boolean hasErrors = false; if (mTitleField.getText().toString().length() == 0) { setEmpty("Title", mTitleField); hasErrors = true; } if (mDescriptionField.getText().toString().length() == 0) { setEmpty("Description", mDescriptionField); hasErrors = true; } if (mMiniSite == null) { setEmpty("Minisite", mDescriptionField); hasErrors = true; } if (mDate == null) { setEmpty("Deadline", mDescriptionField); hasErrors = true; } if (hasErrors) return; submitListener(); }
Source:
private List<HdfsProducer.SplitStrategy> getSplitStrategies(Map<String, Object> hdfsSettings) { List<HdfsProducer.SplitStrategy> strategies = new ArrayList<>(); splitStrategy = getString(hdfsSettings, "splitStrategy", kerberosNamedNodes); if (nonNull(splitStrategy)) { String[] strstrategies = splitStrategy.split(","); for (String strstrategy : strstrategies) { String[] tokens = strstrategy.split(":"); if (tokens.length != 2) { throw new IllegalArgumentException("Wrong Split Strategy [splitStrategy" + "=" + splitStrategy + "]"); } HdfsProducer.SplitStrategyType sst = HdfsProducer.SplitStrategyType.valueOf(tokens[0]); long ssv = Long.parseLong(tokens[1]); strategies.add(new HdfsProducer.SplitStrategy(sst, ssv)); } } return strategies; }

Target:
private List<HdfsProducer.SplitStrategy> getSplitStrategies(Map<String, Object> hdfsSettings) { List<HdfsProducer.SplitStrategy> strategies = new ArrayList<>(); splitStrategy = getString(hdfsSettings, "splitStrategy", kerberosNamedNodes); if (isNotEmpty(splitStrategy)) { String[] strstrategies = splitStrategy.split(","); for (String strstrategy : strstrategies) { String[] tokens = strstrategy.split(":"); if (tokens.length != 2) { throw new IllegalArgumentException("Wrong Split Strategy [splitStrategy" + "=" + splitStrategy + "]"); } HdfsProducer.SplitStrategyType sst = HdfsProducer.SplitStrategyType.valueOf(tokens[0]); long ssv = Long.parseLong(tokens[1]); strategies.add(new HdfsProducer.SplitStrategy(sst, ssv)); } } return strategies; }
Source:
private ScrollPane getCitationsPane() { Text titleText = new Text(Localization.lang("Citations found")); titleText.getStyleClass().add("latex-citations-title-text"); VBox citationsBox = new VBox(20.0, titleText); citationsBox.getChildren().addAll(graphicCitationList); ScrollPane citationsPane = new ScrollPane(); citationsPane.setContent(citationsBox); return citationsPane; }

Target:
private ScrollPane getCitationsPane() { Text titleText = new Text(Localization.lang("Citations found")); titleText.getStyleClass().add("recommendation-heading"); VBox citationsBox = new VBox(20, titleText); Path basePath = viewModel.directoryProperty().get(); citationsBox.getChildren().addAll(viewModel.getCitationList().stream().map( citation -> citation.getDisplayGraphic(basePath, Optional.empty())).collect(Collectors.toList())); ScrollPane citationsPane = new ScrollPane(); citationsPane.setContent(citationsBox); return citationsPane; }
Source:
private void addOrUpdateClusterConfig(Guid clusterId, String paramName, String paramValue) { GlusterVolumeSnapshotConfig param = new GlusterVolumeSnapshotConfig(); param.setClusterId(clusterId); param.setVolumeId(null); param.setParamName(paramName); param.setParamValue(paramValue); GlusterVolumeSnapshotConfig existingParamDetail = getGlusterVolumeSnapshotConfigDao().getConfigByClusterIdAndName(clusterId, paramName); if (existingParamDetail == null) { getGlusterVolumeSnapshotConfigDao().save(param); } else { getGlusterVolumeSnapshotConfigDao().updateConfigByClusterIdAndName(clusterId, paramName, paramValue); } }

Target:
private void addOrUpdateClusterConfig(Guid clusterId, String paramName, String paramValue) { GlusterVolumeSnapshotConfig param = new GlusterVolumeSnapshotConfig(); param.setClusterId(clusterId); param.setVolumeId(null); param.setParamName(paramName); param.setParamValue(paramValue); GlusterVolumeSnapshotConfig existingParamDetail = getGlusterVolumeSnapshotConfigDao().getConfigByClusterIdAndName(clusterId, paramName); if (existingParamDetail == null) { getGlusterVolumeSnapshotConfigDao().save(param); } else if (!(existingParamDetail.getParamValue().equals(paramValue))) { getGlusterVolumeSnapshotConfigDao().updateConfigByClusterIdAndName(clusterId, paramName, paramValue); } }
Source:
public static Expression transformInlineConstants(final Expression exp) { if (exp instanceof PropertyExpression) { PropertyExpression pe = (PropertyExpression) exp; if (pe.getObjectExpression() instanceof ClassExpression) { ClassExpression ce = (ClassExpression) pe.getObjectExpression(); ClassNode type = ce.getType(); FieldNode field = ClassNodeUtils.getField(type, pe.getPropertyAsString()); if (type.isEnum() && field != null && field.isEnum()) return exp; Expression constant = findConstant(field); if (constant != null) return constant; } } else if (exp instanceof BinaryExpression) { BinaryExpression be = (BinaryExpression) exp; Expression lhs = transformInlineConstants(be.getLeftExpression()); Expression rhs = transformInlineConstants(be.getRightExpression()); if (lhs instanceof ConstantExpression && rhs instanceof ConstantExpression && lhs.getType().equals(ClassHelper.STRING_TYPE) && rhs.getType().equals(ClassHelper.STRING_TYPE)) { return configure(be, new ConstantExpression(lhs.getText() + rhs.getText())); } be.setLeftExpression(lhs); be.setRightExpression(rhs); return be; } else if (exp instanceof ListExpression) { ListExpression origList = (ListExpression) exp; ListExpression newList = new ListExpression(); boolean changed = false; for (Expression e : origList.getExpressions()) { Expression transformed = transformInlineConstants(e); newList.addExpression(transformed); if (transformed != e) changed = true; } if (changed) { newList.setSourcePosition(origList); return newList; } return origList; } return exp; }

Target:
public static Expression transformInlineConstants(final Expression exp) { if (exp instanceof PropertyExpression) { PropertyExpression pe = (PropertyExpression) exp; if (pe.getObjectExpression() instanceof ClassExpression) { ClassExpression ce = (ClassExpression) pe.getObjectExpression(); ClassNode type = ce.getType(); FieldNode field = ClassNodeUtils.getField(type, pe.getPropertyAsString()); if (type.isEnum() && field != null && field.isEnum()) return exp; Expression constant = findConstant(field); if (constant != null) return constant; } } else if (exp instanceof BinaryExpression) { BinaryExpression be = (BinaryExpression) exp; Expression lhs = transformInlineConstants(be.getLeftExpression()); Expression rhs = transformInlineConstants(be.getRightExpression()); if (be.getOperation().getType() == PLUS && lhs instanceof ConstantExpression && rhs instanceof ConstantExpression && lhs.getType().equals(ClassHelper.STRING_TYPE) && rhs.getType().equals(ClassHelper.STRING_TYPE)) { return configure(be, new ConstantExpression(lhs.getText() + rhs.getText())); } be.setLeftExpression(lhs); be.setRightExpression(rhs); return be; } else if (exp instanceof ListExpression) { ListExpression origList = (ListExpression) exp; ListExpression newList = new ListExpression(); boolean changed = false; for (Expression e : origList.getExpressions()) { Expression transformed = transformInlineConstants(e); newList.addExpression(transformed); if (transformed != e) changed = true; } if (changed) { newList.setSourcePosition(origList); return newList; } return origList; } return exp; }
Source:
protected boolean loadValues(IMemento memento) { editorName = memento.getString(IWorkbenchConstants.TAG_LABEL); imageFilename = memento.getString(IWorkbenchConstants.TAG_IMAGE); className = memento.getString(IWorkbenchConstants.TAG_CLASS); launcherName = memento.getString(IWorkbenchConstants.TAG_LAUNCHER); fileName = memento.getString(IWorkbenchConstants.TAG_FILE); id = Util.safeString(memento.getString(IWorkbenchConstants.TAG_ID)); pluginIdentifier = memento.getString(IWorkbenchConstants.TAG_PLUGIN); Integer openModeInt = memento .getInteger(IWorkbenchConstants.TAG_OPEN_MODE); if (openModeInt != null) { openMode = openModeInt.intValue(); } else { boolean internal = Boolean.valueOf(memento .getString(IWorkbenchConstants.TAG_INTERNAL)) .booleanValue(); boolean openInPlace = Boolean.valueOf(memento .getString(IWorkbenchConstants.TAG_OPEN_IN_PLACE)) .booleanValue(); if (internal) { openMode = OPEN_INTERNAL; } else { if (openInPlace) { openMode = OPEN_INPLACE; } else { openMode = OPEN_EXTERNAL; } } } if (openMode != OPEN_EXTERNAL && openMode != OPEN_INTERNAL && openMode != OPEN_INPLACE) { WorkbenchPlugin .log("Ignoring editor descriptor with invalid openMode: " + this); return false; } String programName = memento .getString(IWorkbenchConstants.TAG_PROGRAM_NAME); if (programName != null) { this.program = findProgram(programName); } return true; }

Target:
protected boolean loadValues(IMemento memento) { editorName = memento.getString(IWorkbenchConstants.TAG_LABEL); imageFilename = memento.getString(IWorkbenchConstants.TAG_IMAGE); className = memento.getString(IWorkbenchConstants.TAG_CLASS); launcherName = memento.getString(IWorkbenchConstants.TAG_LAUNCHER); fileName = memento.getString(IWorkbenchConstants.TAG_FILE); id = Util.safeString(memento.getString(IWorkbenchConstants.TAG_ID)); pluginIdentifier = memento.getString(IWorkbenchConstants.TAG_PLUGIN); Integer openModeInt = memento .getInteger(IWorkbenchConstants.TAG_OPEN_MODE); if (openModeInt != null) { openMode = openModeInt.intValue(); } else { boolean internal = Boolean.parseBoolean(memento .getString(IWorkbenchConstants.TAG_INTERNAL)); boolean openInPlace = Boolean.parseBoolean(memento .getString(IWorkbenchConstants.TAG_OPEN_IN_PLACE)); if (internal) { openMode = OPEN_INTERNAL; } else { if (openInPlace) { openMode = OPEN_INPLACE; } else { openMode = OPEN_EXTERNAL; } } } if (openMode != OPEN_EXTERNAL && openMode != OPEN_INTERNAL && openMode != OPEN_INPLACE) { WorkbenchPlugin .log("Ignoring editor descriptor with invalid openMode: " + this); return false; } String programName = memento .getString(IWorkbenchConstants.TAG_PROGRAM_NAME); if (programName != null) { this.program = findProgram(programName); } return true; }
Source:
public void themeDesigner001_selectThemeFromFirstPage(){ WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); SpecialThemeDesignerPageObject designer = new SpecialThemeDesignerPageObject(driver); designer.openSpecialDesignerPage(wikiURL); designer.selectTab(PageContent.themeTab); themeName = designer.selectTheme(3); designer.verifyThemeSelected(themeName); }

Target:
public void themeDesigner001_selectThemeFromFirstPage(){ WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); SpecialThemeDesignerPageObject designer = new SpecialThemeDesignerPageObject(driver); designer.openSpecialDesignerPage(wikiURL); designer.selectTab(Tab.Theme); themeName = designer.selectTheme(3); designer.verifyThemeSelected(themeName); }
Source:
public static String getStringValue(Object object) { String rtn = null; if (null == object) { } else if (object instanceof Clob) { try { int size = (int) ((Clob) object).length(); rtn = ((Clob) object).getSubString(1, size); } catch (SQLException e) { LOG.info(e.getLocalizedMessage()); } } else if (object instanceof Timestamp){ try { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); rtn = df.format(object); } catch (Exception e) { LOG.info(e.getLocalizedMessage()); } } else { rtn = object.toString(); } return rtn; }

Target:
public static String getStringValue(Object object) { String rtn = null; if (null == object) { } else if (object instanceof Clob) { try { int size = (int) ((Clob) object).length(); rtn = ((Clob) object).getSubString(1, size); } catch (SQLException e) { LOG.info(e.getLocalizedMessage()); } } else { rtn = object.toString(); } return rtn; }
Source:
private static String serialize(Object obj) throws IOException { ObjectMapper mapper = new ObjectMapper() .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE); mapper.getSerializationConfig().addMixInAnnotations(ExtMap.class, JsonExtMapMixIn.class); return mapper.writeValueAsString(obj); }

Target:
private static String serialize(Object obj) throws IOException { return mapper.writeValueAsString(obj); }