List of usage examples for java.lang NumberFormatException printStackTrace
public void printStackTrace()
From source file:me.bramhaag.discordselfbot.commands.fun.CommandTriggered.java
@Command(name = "triggered", aliases = { "trigger", "triggering" }, minArgs = 1) public void execute(@NonNull Message message, @NonNull TextChannel channel, @NonNull String[] args) { User user;/*from w w w . j a va2 s .c o m*/ String image = "triggered"; final String text; try { user = message.getJDA().getUserById(args[0].replaceAll("[^\\d.]", "")); } catch (NumberFormatException e) { Util.sendError(message, e.getMessage()); return; } if (user == null) { Util.sendError(message, "Invalid user!"); return; } if (args.length >= 3 && (args[1].equalsIgnoreCase("--image") || args[1].equals("-i"))) { image = args[2]; } if (args.length >= 2 && image == null) { text = StringUtils.join(args, 1, args.length); } else if (args.length >= 4 && image != null) { text = StringUtils.join(args, 4, args.length); } else { text = null; } message.editMessage("```Generating GIF...```").queue(); File avatar = new File("avatar_" + user.getId() + "_" + System.currentTimeMillis() + ".png"); try { ImageIO.write(Util.getImage(user.getAvatarUrl()), "png", avatar); } catch (IOException e) { e.printStackTrace(); Util.sendError(message, e.getMessage()); return; } File output = new File("triggered_" + user.getId() + "_" + System.currentTimeMillis() + ".gif"); File triggered = new File("assets/" + image + ".png"); String avatarPath = avatar.getAbsolutePath(); String triggeredPath = triggered.getAbsolutePath(); new Thread(() -> { try { Process generateGif = Runtime.getRuntime().exec((Bot.getConfig().getImagemagickPath() + " convert canvas:none -size 512x680 -resize 512x680! -draw \"image over -60,-60 640,640 \"\"{avatar}\"\"\" -draw \"image over 0,512 0,0 \"\"{triggered}\"\"\" " + "( canvas:none -size 512x680! -draw \"image over -45,-50 640,640 \"\"{avatar}\"\"\" -draw \"image over -5,512 0,0 \"\"{triggered}\"\"\" ) " + "( canvas:none -size 512x680! -draw \"image over -50,-45 640,640 \"\"{avatar}\"\"\" -draw \"image over -1,505 0,0 \"\"{triggered}\"\"\" ) " + "( canvas:none -size 512x680! -draw \"image over -45,-65 640,640 \"\"{avatar}\"\"\" -draw \"image over -5,530 0,0 \"\"{triggered}\"\"\" ) " + "-layers Optimize -set delay 2 " + output.getPath()).replace("{avatar}", avatarPath) .replace("{triggered}", triggeredPath)); generateGif.waitFor(); if (text != null) { Process addText = Runtime.getRuntime() .exec(String.format("%s convert %s -font Calibri -pointsize 60 caption:\"%s\" %s", Constants.MAGICK_PATH, output, text, output)); addText.waitFor(); } message.getChannel().sendFile(output, new MessageBuilder().append(" ").build()).queue(m -> { message.delete().queue(); Preconditions.checkState(avatar.delete(), String.format("File %s not deleted!", avatar.getName())); Preconditions.checkState(output.delete(), String.format("File %s not deleted!", output.getName())); }); } catch (IOException | InterruptedException e) { e.printStackTrace(); } }).start(); }
From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java
private void updateServerTimeDelta(HttpMethodBase method) { try {//ww w .j av a 2 s .com Header timestamp = method.getResponseHeader("X-Timestamp"); if (timestamp == null) return; long serverTime = Long.parseLong(timestamp.getValue()); serverTimeDelta = serverTime - getSystemTime(); } catch (NumberFormatException e) { e.printStackTrace(); } }
From source file:com.cellbots.communication.CustomHttpCommChannel.java
@Override public void listenForMessages(final long waitTimeBetweenPolling, final boolean returnStream) { if (inUrl == null || doDisconnect) return;//from www . j a va2 s.c o m stopReading = false; listenThread = new Thread(new Runnable() { @Override public void run() { Looper.prepare(); while (!stopReading) { try { if (waitTimeBetweenPolling >= 0) Thread.sleep(waitTimeBetweenPolling); if (commandUrl == null) { commandUrl = new URL(inUrl); } URLConnection cn = commandUrl.openConnection(); cn.connect(); if (returnStream) { if (mMessageListener != null) { mMessageListener.onMessage(new CommMessage(null, cn.getInputStream(), null, null, null, mChannelName, CommunicationManager.CHANNEL_HTTP)); } } else { BufferedReader rd = new BufferedReader(new InputStreamReader(cn.getInputStream()), 1024); String cmd = rd.readLine(); if (cmd != null && !cmd.equals(prevCmd) && mMessageListener != null) { prevCmd = cmd; // TODO (chaitanyag): Change this after we come // up with a better protocol. The first (space // separated) token in the command string could // be a timestamp. This is useful if the same // commands are sent back to back. For example, // the controller sends consecutive "hu" // (head up) commands to tilt the head up in // small increments. if (cmd.indexOf(' ') >= 0) { try { Long.parseLong(cmd.substring(0, cmd.indexOf(' '))); cmd = cmd.substring(cmd.indexOf(' ') + 1); } catch (NumberFormatException e) { } } mMessageListener.onMessage(new CommMessage(cmd, null, null, null, null, mChannelName, CommunicationManager.CHANNEL_HTTP)); } } if (waitTimeBetweenPolling < 0) { // Do not repeat this loop break; } } catch (MalformedURLException e) { Log.e(TAG, "Error processing URL: " + e.getMessage()); } catch (IOException e) { Log.e(TAG, "Error reading command from URL: " + commandUrl + " : " + e.getMessage()); } catch (InterruptedException e) { e.printStackTrace(); } } } }); listenThread.start(); }
From source file:cw.kop.autobackground.sources.SourceInfoFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle arguments = getArguments();//from w w w .j a v a 2 s . com sourcePosition = (Integer) arguments.get("position"); int colorFilterInt = AppSettings.getColorFilterInt(appContext); View view = inflater.inflate(R.layout.source_info_fragment, container, false); headerView = inflater.inflate(R.layout.source_info_header, null, false); settingsContainer = (RelativeLayout) headerView.findViewById(R.id.source_settings_container); sourceImage = (ImageView) headerView.findViewById(R.id.source_image); sourceTitle = (EditText) headerView.findViewById(R.id.source_title); sourcePrefix = (EditText) headerView.findViewById(R.id.source_data_prefix); sourceData = (EditText) headerView.findViewById(R.id.source_data); sourceSuffix = (EditText) headerView.findViewById(R.id.source_data_suffix); sourceNum = (EditText) headerView.findViewById(R.id.source_num); ViewGroup.LayoutParams params = sourceImage.getLayoutParams(); params.height = (int) ((container.getWidth() - 2f * getResources().getDimensionPixelSize(R.dimen.side_margin)) / 16f * 9); sourceImage.setLayoutParams(params); cancelButton = (Button) view.findViewById(R.id.cancel_button); saveButton = (Button) view.findViewById(R.id.save_button); sourcePrefix.setTextColor(colorFilterInt); sourceSuffix.setTextColor(colorFilterInt); cancelButton.setTextColor(colorFilterInt); saveButton.setTextColor(colorFilterInt); // Adjust alpha to get faded hint color from regular text color int hintColor = Color.argb(0x88, Color.red(colorFilterInt), Color.green(colorFilterInt), Color.blue(colorFilterInt)); sourceTitle.setHintTextColor(hintColor); sourceData.setHintTextColor(hintColor); sourceNum.setHintTextColor(hintColor); sourceData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (type) { case AppSettings.FOLDER: selectSource(getPositionOfType(AppSettings.FOLDER)); break; case AppSettings.GOOGLE_ALBUM: selectSource(getPositionOfType(AppSettings.GOOGLE_ALBUM)); break; } Log.i(TAG, "Data launched folder fragment"); } }); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); saveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { saveSource(); } }); sourceSpinnerText = (TextView) headerView.findViewById(R.id.source_spinner_text); sourceSpinner = (Spinner) headerView.findViewById(R.id.source_spinner); timePref = (CustomSwitchPreference) findPreference("source_time"); timePref.setChecked(arguments.getBoolean("use_time")); timePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (!(Boolean) newValue) { return true; } DialogFactory.TimeDialogListener startTimeListener = new DialogFactory.TimeDialogListener() { @Override public void onTimeSet(TimePicker view, int hour, int minute) { startHour = hour; startMinute = minute; DialogFactory.TimeDialogListener endTimeListener = new DialogFactory.TimeDialogListener() { @Override public void onTimeSet(TimePicker view, int hour, int minute) { endHour = hour; endMinute = minute; timePref.setSummary(String.format("Time active: %02d:%02d - %02d:%02d", startHour, startMinute, endHour, endMinute)); } }; DialogFactory.showTimeDialog(appContext, "End time?", endTimeListener, startHour, startMinute); } }; DialogFactory.showTimeDialog(appContext, "Start time?", startTimeListener, startHour, startMinute); return true; } }); if (savedInstanceState != null) { if (sourcePosition == -1) { sourceSpinner .setSelection(getPositionOfType(savedInstanceState.getString("type", AppSettings.WEBSITE))); } } if (sourcePosition == -1) { sourceImage.setVisibility(View.GONE); sourceSpinnerText.setVisibility(View.VISIBLE); sourceSpinner.setVisibility(View.VISIBLE); SourceSpinnerAdapter adapter = new SourceSpinnerAdapter(appContext, R.layout.spinner_row, Arrays.asList(getResources().getStringArray(R.array.source_menu))); sourceSpinner.setAdapter(adapter); sourceSpinner.setSelection(0); sourceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { selectSource(position); Log.i(TAG, "Spinner launched folder fragment"); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); type = AppSettings.WEBSITE; hint = "URL"; prefix = ""; suffix = ""; startHour = 0; startMinute = 0; endHour = 0; endMinute = 0; } else { sourceImage.setVisibility(View.VISIBLE); sourceSpinnerText.setVisibility(View.GONE); sourceSpinner.setVisibility(View.GONE); type = arguments.getString("type"); folderData = arguments.getString("data"); String data = folderData; hint = AppSettings.getSourceDataHint(type); prefix = AppSettings.getSourceDataPrefix(type); suffix = ""; switch (type) { case AppSettings.GOOGLE_ALBUM: sourceTitle.setFocusable(false); sourceData.setFocusable(false); sourceNum.setFocusable(false); case AppSettings.FOLDER: data = Arrays.toString(folderData.split(AppSettings.DATA_SPLITTER)); break; case AppSettings.TUMBLR_BLOG: suffix = ".tumblr.com"; break; } sourceTitle.setText(arguments.getString("title")); sourceNum.setText("" + arguments.getInt("num")); sourceData.setText(data); if (imageDrawable != null) { sourceImage.setImageDrawable(imageDrawable); } boolean showPreview = arguments.getBoolean("preview"); if (showPreview) { sourceImage.setVisibility(View.VISIBLE); } ((CustomSwitchPreference) findPreference("source_show_preview")).setChecked(showPreview); String[] timeArray = arguments.getString("time").split(":|[ -]+"); try { startHour = Integer.parseInt(timeArray[0]); startMinute = Integer.parseInt(timeArray[1]); endHour = Integer.parseInt(timeArray[2]); endMinute = Integer.parseInt(timeArray[3]); timePref.setSummary(String.format("Time active: %02d:%02d - %02d:%02d", startHour, startMinute, endHour, endMinute)); } catch (NumberFormatException e) { e.printStackTrace(); startHour = 0; startMinute = 0; endHour = 0; endMinute = 0; } } setDataWrappers(); sourceUse = (Switch) headerView.findViewById(R.id.source_use_switch); sourceUse.setChecked(arguments.getBoolean("use")); if (AppSettings.getTheme().equals(AppSettings.APP_LIGHT_THEME)) { view.setBackgroundColor(getResources().getColor(R.color.LIGHT_THEME_BACKGROUND)); } else { view.setBackgroundColor(getResources().getColor(R.color.DARK_THEME_BACKGROUND)); } ListView listView = (ListView) view.findViewById(android.R.id.list); listView.addHeaderView(headerView); if (savedInstanceState != null) { sourceTitle.setText(savedInstanceState.getString("title", "")); sourceData.setText(savedInstanceState.getString("data", "")); sourceNum.setText(savedInstanceState.getString("num", "")); } return view; }
From source file:fr.sanofi.fcl4transmart.controllers.listeners.clinicalData.SelectWMFListener.java
public boolean checkFormat(File file) { try {//from w w w . ja va2 s .c om BufferedReader br = new BufferedReader(new FileReader(file)); String line = br.readLine(); while ((line = br.readLine()) != null) { if (line.compareTo("") != 0) { String[] fields = line.split("\t", -1); //check columns number if (fields.length != 4) { this.selectWMFUI.displayMessage("Error:\nLines have not the right number of columns"); br.close(); return false; } //check raw file names if (!((ClinicalData) this.dataType).getRawFilesNames().contains(fields[0])) { this.selectWMFUI.displayMessage("Error:\ndata file '" + fields[0] + "' does not exist"); br.close(); return false; } //check that column number is set if (fields[1].compareTo("") == 0) { this.selectWMFUI.displayMessage("Error:\nColumns numbers have to be set"); br.close(); return false; } try { Integer.parseInt(fields[1]); } catch (NumberFormatException e) { this.selectWMFUI.displayMessage("Error:\nColumns numbers have to be numbers"); br.close(); return false; } //check that original data value is set if (fields[2].compareTo("") == 0) { this.selectWMFUI.displayMessage("Error:\nOriginal data values have to be set"); br.close(); return false; } //check that new data value is set if (fields[3].compareTo("") == 0) { this.selectWMFUI.displayMessage("Error:\nNew data values have to be set"); br.close(); return false; } } } br.close(); } catch (Exception e) { this.selectWMFUI.displayMessage("Error: " + e.getLocalizedMessage()); e.printStackTrace(); return false; } return true; }
From source file:neembuu.release1.externalImpl.linkhandler.YoutubeLinkHandlerProvider.java
private BasicLinkHandler.Builder linkYoutubeExtraction(TrialLinkHandler tlh, int retryCount) throws Exception { String url = tlh.getReferenceLinkString(); BasicLinkHandler.Builder linkHandlerBuilder = BasicLinkHandler.Builder.create(); try {/*w w w . j a v a 2s . c o m*/ DefaultHttpClient httpClient = NHttpClient.getNewInstance(); String requestUrl = "http://www.linkyoutube.com/watch/index.php?video=" + URLEncoder.encode(url, "UTF-8"); final String responseString = NHttpClientUtils.getData(requestUrl, httpClient); //Set the group name as the name of the video String nameOfVideo = getVideoName(url); String fileName = "text"; linkHandlerBuilder.setGroupName(nameOfVideo); long c_duration = -1; Document doc = Jsoup.parse(responseString); Elements elements = doc.select("#download_links a"); for (Element element : elements) { String singleUrl = element.attr("href"); fileName = element.text(); if (!singleUrl.equals("#")) { long length = NHttpClientUtils.calculateLength(singleUrl, httpClient); singleUrl = Utils.normalize(singleUrl); LOGGER.log(Level.INFO, "Normalized URL: " + singleUrl); if (length == 0) { length = NHttpClientUtils.calculateLength(singleUrl, httpClient); } //LOGGER.log(Level.INFO,"Length: " + length); if (length <= 0) { continue; /*skip this url*/ } BasicOnlineFile.Builder fileBuilder = linkHandlerBuilder.createFile(); try { // finding video/audio length String dur = StringUtils.stringBetweenTwoStrings(singleUrl, "dur=", "&"); long duration = (int) (Double.parseDouble(dur) * 1000); if (c_duration < 0) { c_duration = duration; } fileBuilder.putLongPropertyValue( PropertyProvider.LongProperty.MEDIA_DURATION_IN_MILLISECONDS, duration); LOGGER.log(Level.INFO, "dur=" + dur); } catch (NumberFormatException a) { // ignore } try { // finding the quality short name String type = fileName.substring(fileName.indexOf("(") + 1); type = type.substring(0, type.indexOf(")")); fileBuilder.putStringPropertyValue(PropertyProvider.StringProperty.VARIANT_DESCRIPTION, type); LOGGER.log(Level.INFO, "type=" + type); } catch (Exception a) { a.printStackTrace(); } fileName = nameOfVideo + " " + fileName; fileBuilder.setName(fileName).setUrl(singleUrl).setSize(length).next(); } } for (OnlineFile of : linkHandlerBuilder.getFiles()) { long dur = of.getPropertyProvider() .getLongPropertyValue(PropertyProvider.LongProperty.MEDIA_DURATION_IN_MILLISECONDS); if (dur < 0 && c_duration > 0 && of.getPropertyProvider() instanceof BasicPropertyProvider) { ((BasicPropertyProvider) of.getPropertyProvider()).putLongPropertyValue( PropertyProvider.LongProperty.MEDIA_DURATION_IN_MILLISECONDS, c_duration); } } } catch (Exception ex) { int retryLimit = ((YT_TLH) tlh).retryLimit; ex.printStackTrace(); LOGGER.log(Level.INFO, "retry no. = " + retryCount); if (retryCount > retryLimit) throw ex; return linkYoutubeExtraction(tlh, retryCount + 1); } return linkHandlerBuilder; }
From source file:io.github.jeremgamer.maintenance.Maintenance.java
@EventHandler(priority = EventPriority.HIGHEST) public void MaintenanceListPing(final ServerListPingEvent event) { if (maintenanceTime == true) { if (durationEnabled == true) { try { if (remainingMilliseconds / 60 / 1000 < 1) { event.setMotd(getConfig().getString("maintenanceWithDurationMOTDLessThanOneMinute") .replaceAll("&", "").replaceAll("<n>", "\n")); } else { event.setMotd(getConfig().getString("maintenanceWithDurationMOTD").replaceAll("&", "") .replaceAll("<n>", "\n") .replaceAll("<minutes>", String.valueOf(remainingMilliseconds / 60 / 1000))); }/* www . j ava 2 s. co m*/ } catch (NumberFormatException e) { getLogger().info(getConfig().getString("inputErrorDuration").replaceAll("&", "")); } } else { event.setMotd( getConfig().getString("maintenanceMOTD").replaceAll("&", "").replaceAll("<n>", "\n")); } try { event.setServerIcon(maintenanceIcon); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } try { maxPlayer = Integer .parseInt(getConfig().getString("maxPlayersOnMaintenance").replaceAll("&", "")); event.setMaxPlayers(maxPlayer); } catch (NumberFormatException e) { e.printStackTrace(); } } }
From source file:de.fau.amos.ChartRenderer.java
/** * //from ww w.j a va 2 s.com * Creates TimeSeriesCollection by querying energy data from database. * * @param granularity Accuracy of distinguishment of displayed values (Summarise data to hours, days, months, years). * @param startTime Start of queried period. * @param endTime End of queried period. * @param sumOrAvg Shall values be added or averaged. * @param groupParameters Controlpoints that are affected. * @param unit Sets Unit (kWh or kWh/TNF) * @return TimeSeriesCollection that privedes the basis for creation of a png-chart */ private TimeSeriesCollection createTimeCollection(String granularity, String startTime, String endTime, String sumOrAvg, String groupParameters, String unit) { //time series containing all data TimeSeriesCollection collection = new TimeSeriesCollection(); //split groupParameter string to get all queryed groups seperated groupParameters = groupParameters.replace("||", "splitHere"); String[] groups = groupParameters.split("splitHere"); //handle groups one after another for (int i = 0; i < groups.length; i++) { //get group name String groupName = groups[i].contains("'") ? groups[i].substring(0, groups[i].indexOf("'")) : groups[i]; groups[i] = groups[i].contains("'") ? groups[i].substring(groupName.length()) : ""; if (!groups[i].contains("|")) { continue; } //get used plants String plants = groups[i].substring(groups[i].indexOf("|") + 1); //prepare queryString groups[i] = groups[i].substring(0, groups[i].indexOf("|")); //generate series for group TimeSeries series = new TimeSeries(groupName); ResultSet rs = null; //skip group if nothing is selected to query if (groups[i].trim() != "") { if ("1".equals(unit)) { //query kWh rs = SQL.queryToResultSet("select * from (select round(" + sumOrAvg + "(gruppenWert),4), gruppenZeit from(select " + sumOrAvg + "(wert) as gruppenWert,control_point_name, zeit1 as gruppenZeit from (select " + sumOrAvg + "(value)as wert,control_point_name,date_trunc('" + granularity + "',measure_time)as zeit1 from measures inner join controlpoints on measures.controlpoint_id=controlpoints.controlpoints_id where measure_time >= '" + startTime + "' AND measure_time < '" + endTime + "' AND controlpoints_id in(" + groups[i] + ") group by measure_time,control_point_name)as data group by zeit1,control_point_name)as groupedByTime group by gruppenZeit)as result order by gruppenZeit" + ";"); } else if ("2".equals(unit)) { //query kWh/TNF (only as sum, not avg) rs = SQL.queryToResultSet( "select * from (select round(sum(gruppenWert)/(select sum(am) from(select sum(amount)as am,date_trunc('" + granularity + "',measure_time)as zeit from productiondata inner join controlpoints on productiondata.controlpoint_id=controlpoints.controlpoints_id " + "where productiondata.measure_time >= '" + startTime + "' AND productiondata.measure_time < '" + endTime + "' AND reference_point='t' AND plant_id in(" + plants + ") group by measure_time)as wat where zeit=gruppenZeit group by zeit order by zeit),4), gruppenZeit from(" + "select sum(wert) as gruppenWert,control_point_name, zeit1 as gruppenZeit from (select sum(value)as wert,control_point_name,date_trunc('" + granularity + "',measure_time)as zeit1 from measures inner join controlpoints on measures.controlpoint_id=controlpoints.controlpoints_id where measure_time >= '" + startTime + "' AND measure_time < '" + endTime + "' AND controlpoints_id in(" + groups[i] + ")group by measure_time,control_point_name)as data group by zeit1,control_point_name)as groupedByTime group by gruppenZeit)as result order by gruppenZeit" + ";"); } } if (rs != null) { try { while (rs.next()) { switch (granularity) { case "minute": series.add(new Minute(Integer.parseInt(rs.getString(2).substring(14, 16)), Integer.parseInt(rs.getString(2).substring(11, 13)), Integer.parseInt(rs.getString(2).substring(8, 10)), Integer.parseInt(rs.getString(2).substring(5, 7)), Integer.parseInt(rs.getString(2).substring(0, 4))), rs.getDouble(1)); break; case "day": series.add(new Day(Integer.parseInt(rs.getString(2).substring(8, 10)), Integer.parseInt(rs.getString(2).substring(5, 7)), Integer.parseInt(rs.getString(2).substring(0, 4))), rs.getDouble(1)); break; case "month": series.add(new Month(Integer.parseInt(rs.getString(2).substring(5, 7)), Integer.parseInt(rs.getString(2).substring(0, 4))), rs.getDouble(1)); break; case "year": series.add(new Year(Integer.parseInt(rs.getString(2).substring(0, 4))), rs.getDouble(1)); break; //default: day default: series.add(new Day(Integer.parseInt(rs.getString(2).substring(8, 10)), Integer.parseInt(rs.getString(2).substring(5, 7)), Integer.parseInt(rs.getString(2).substring(0, 4))), rs.getDouble(1)); } } rs.close(); } catch (NumberFormatException e) { } catch (SQLException e) { e.printStackTrace(); } } //Add the series to the collection collection.addSeries(series); } return collection; }
From source file:gpps.service.impl.ThirdPaySupportServiceImpl.java
@Override public void checkCash(Integer cashStreamId) throws IllegalOperationException { CashStream cashStream = cashStreamDao.find(cashStreamId); if (cashStream == null) return;//from ww w .j a va 2 s. c om if (cashStream.getAction() != CashStream.ACTION_CASH) throw new IllegalOperationException("????"); if (cashStream.getState() != CashStream.STATE_SUCCESS) throw new IllegalOperationException("?????"); String baseUrl = innerThirdPaySupportService.getBaseUrl(IInnerThirdPaySupportService.ACTION_ORDERQUERY); Map<String, String> params = new HashMap<String, String>(); params.put("PlatformMoneymoremore", innerThirdPaySupportService.getPlatformMoneymoremore()); params.put("Action", "2"); params.put("LoanNo", cashStream.getLoanNo()); StringBuilder sBuilder = new StringBuilder(); sBuilder.append(StringUtil.strFormat(params.get("PlatformMoneymoremore"))); sBuilder.append(StringUtil.strFormat(params.get("Action"))); sBuilder.append(StringUtil.strFormat(params.get("LoanNo"))); RsaHelper rsa = RsaHelper.getInstance(); params.put("SignInfo", rsa.signData(sBuilder.toString(), innerThirdPaySupportService.getPrivateKey())); String body = httpClientService.post(baseUrl, params); Gson gson = new Gson(); Map<String, String> returnParams = gson.fromJson(body, Map.class); try { String withdrawsState = returnParams.get("WithdrawsState"); String loanNo = returnParams.get("LoanNo"); if (withdrawsState.equals("2")) { // accountService.returnCash(Integer.parseInt(returnParams.get("OrderNo")), loanNo); } } catch (NumberFormatException e) { e.printStackTrace(); } catch (IllegalConvertException e) { e.printStackTrace(); } }
From source file:massbank.BatchSearchWorker.java
/** * T}t@C???iHTML`?j//from www .j a v a 2 s. c om * @param resultFile t@C * @param htmlFile YtpHTMLt@C */ private void createSummary(File resultFile, File htmlFile) { LineNumberReader in = null; PrintWriter out = null; try { //(1) t@C? String line; int cnt = 0; ArrayList<String> nameList = new ArrayList<String>(); ArrayList<String> top1LineList = new ArrayList<String>(); TreeSet<String> top1IdList = new TreeSet<String>(); in = new LineNumberReader(new FileReader(resultFile)); while ((line = in.readLine()) != null) { line = line.trim(); if (line.equals("")) { cnt = 0; } else { cnt++; if (cnt == 1) { nameList.add(line); } else if (cnt == 2) { if (line.equals("-1")) { top1LineList.add("Invalid"); } if (line.equals("0")) { top1LineList.add("0"); } } else if (cnt == 4) { String[] vals = line.split("\t"); String id = vals[0]; top1IdList.add(id); top1LineList.add(line); } } } //? http://www.massbank.jp/ T?[o??KEGG???s HashMap<String, ArrayList> massbank2mapList = new HashMap<String, ArrayList>(); //(2)p HashMap<String, String> massbank2keggList = new HashMap<String, String>(); //(2)p HashMap<String, ArrayList> map2keggList = new HashMap<String, ArrayList>(); //(3)p ArrayList<String> mapNameList = new ArrayList<String>(); //(4)p boolean isKeggReturn = false; // if (serverUrl.indexOf("www.massbank.jp") == -1) { // isKeggReturn = false; // } if (isKeggReturn) { //(2) KEGG ID, Map IDDB String where = "where MASSBANK in("; Iterator it = top1IdList.iterator(); while (it.hasNext()) { String id = (String) it.next(); where += "'" + id + "',"; } where = where.substring(0, where.length() - 1); where += ")"; String sql = "select MASSBANK, t1.KEGG, MAP from " + "(SELECT MASSBANK,KEGG FROM OTHER_DB_IDS " + where + ") t1, PATHWAY_CPDS t2" + " where t1.KEGG=t2.KEGG order by MAP,MASSBANK"; ArrayList<String> mapList = null; try { Class.forName("com.mysql.jdbc.Driver"); String connectUrl = "jdbc:mysql://localhost/MassBank_General"; Connection con = DriverManager.getConnection(connectUrl, "bird", "bird2006"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); String prevId = ""; while (rs.next()) { String id = rs.getString(1); String kegg = rs.getString(2); String map = rs.getString(3); if (!id.equals(prevId)) { if (!prevId.equals("")) { massbank2mapList.put(prevId, mapList); } mapList = new ArrayList<String>(); massbank2keggList.put(id, kegg); } mapList.add(map); prevId = id; } massbank2mapList.put(prevId, mapList); rs.close(); stmt.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } if (mapList != null) { //(3) Pathway Map?FtXg?? it = massbank2mapList.keySet().iterator(); while (it.hasNext()) { String id = (String) it.next(); String kegg = (String) massbank2keggList.get(id); ArrayList<String> list1 = massbank2mapList.get(id); for (int i = 0; i < list1.size(); i++) { String map = list1.get(i); ArrayList<String> list2 = null; if (map2keggList.containsKey(map)) { list2 = map2keggList.get(map); list2.add(kegg); } else { list2 = new ArrayList<String>(); list2.add(kegg); map2keggList.put(map, list2); } } } //(4) SOAPPathway Map?Ft?\bh?s it = map2keggList.keySet().iterator(); List<Callable<HashMap<String, String>>> tasks = new ArrayList(); while (it.hasNext()) { String map = (String) it.next(); mapNameList.add(map); ArrayList<String> list = map2keggList.get(map); String[] cpds = list.toArray(new String[] {}); Callable<HashMap<String, String>> task = new ColorPathway(map, cpds); tasks.add(task); } Collections.sort(mapNameList); // Xbhv?[10 ExecutorService exsv = Executors.newFixedThreadPool(10); List<Future<HashMap<String, String>>> results = exsv.invokeAll(tasks); // Pathway mapi[?? String saveRootPath = MassBankEnv.get(MassBankEnv.KEY_TOMCAT_APPTEMP_PATH) + "pathway"; File rootDir = new File(saveRootPath); if (!rootDir.exists()) { rootDir.mkdir(); } // String savePath = saveRootPath + File.separator + this.jobId; // File newDir = new File(savePath); // if ( !newDir.exists() ) { // newDir.mkdir(); // } //(6) Pathway mapURL for (Future<HashMap<String, String>> future : results) { HashMap<String, String> res = future.get(); it = res.keySet().iterator(); String map = (String) it.next(); String mapUrl = res.get(map); String filePath = saveRootPath + File.separator + this.jobId + "_" + map + ".png"; FileUtil.downloadFile(mapUrl, filePath); } } } //(7) ?o out = new PrintWriter(new BufferedWriter(new FileWriter(htmlFile))); // wb_?[?o String reqIonStr = "Both"; try { if (Integer.parseInt(this.ion) > 0) { reqIonStr = "Positive"; } else if (Integer.parseInt(this.ion) < 0) { reqIonStr = "Negative"; } } catch (NumberFormatException nfe) { nfe.printStackTrace(); } String title = "Summary of Batch Service Results"; out.println("<html>"); out.println("<head>"); out.println("<title>" + title + "</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>" + title + "</h1>"); out.println("<hr>"); out.println("<h3>Request Date : " + this.time + "</h3>"); out.println("Instrument Type : " + this.inst + "<br>"); out.println("MS Type : " + this.ms + "<br>"); out.println("Ion Mode : " + reqIonStr + "<br>"); out.println("<br>"); out.println("<hr>"); out.println("<table border=\"1\" cellspacing=\"0\" cellpadding=\"2\">"); String cols = String.valueOf(mapNameList.size()); out.println("<tr>"); out.println("<th bgcolor=\"LavenderBlush\" rowspan=\"1\">No.</th>"); out.println("<th bgcolor=\"LavenderBlush\" rowspan=\"1\">Query Name</th>"); out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Score</th>"); out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Hit</th>"); out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">MassBank ID</th>"); out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Record Title</th>"); out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Formula</th>"); out.println("<th bgcolor=\"LightCyan\" rowspan=\"1\">Exact Mass</th>"); if (isKeggReturn) { out.println("<th bgcolor=\"LightYellow\" rowspan=\"2\">KEGG ID</th>"); out.println( "<th bgcolor=\"LightYellow\" colspan=\"" + cols + "\">Colored Pathway Maps</th>"); } out.println("</tr>"); out.print("<tr bgcolor=\"moccasin\">"); for (int i = 0; i < mapNameList.size(); i++) { out.print("<th>MAP" + String.valueOf(i + 1) + "</th>"); } out.println("</tr>"); for (int i = 0; i < nameList.size(); i++) { out.println("<tr>"); String no = String.format("%5d", i + 1); no = no.replace(" ", " "); out.println("<td>" + no + "</td>"); // Query Name String queryName = nameList.get(i); out.println("<td nowrap>" + queryName + "</td>"); line = top1LineList.get(i); if (line.equals("0")) { if (isKeggReturn) { cols = String.valueOf(mapNameList.size() + 5); } else { cols = String.valueOf(6); } out.println("<td colspan=\"" + cols + "\">No Hit Record</td>"); } else if (line.equals("Invalid")) { if (isKeggReturn) { cols = String.valueOf(mapNameList.size() + 5); } else { cols = String.valueOf(4); } out.println("<td colspan=\"" + cols + "\">Invalid Query</td>"); } else { String[] data = formatLine(line); String id = data[0]; String recTitle = data[1]; String formula = data[2]; String emass = data[3]; String score = data[4]; String hit = data[5]; boolean isHiScore = false; if (Integer.parseInt(hit) >= 3 && Double.parseDouble(score) >= 0.8) { isHiScore = true; } // Score if (isHiScore) { out.println("<td><b>" + score + "</b></td>"); } else { out.println("<td>" + score + "</td>"); } // hit peak if (isHiScore) { out.println("<td align=\"right\"><b>" + hit + "</b></td>"); } else { out.println("<td align=\"right\">" + hit + "</td>"); } // MassBank ID & Link out.println("<td><a href=\"" + serverUrl + "jsp/FwdRecord.jsp?id=" + id + "\" target=\"_blank\">" + id + "</td>"); // Record Title out.println("<td>" + recTitle + "</td>"); // Formula out.println("<td nowrap>" + formula + "</td>"); // Exact Mass out.println("<td nowrap>" + emass + "</td>"); // KEGG ID & Link if (isKeggReturn) { String keggLink = " -"; if (massbank2keggList.containsKey(id)) { String keggUrl = "http://www.genome.jp/dbget-bin/www_bget?"; String kegg = massbank2keggList.get(id); switch (kegg.charAt(0)) { case 'C': keggUrl += "cpd:" + kegg; break; case 'D': keggUrl += "dr:" + kegg; break; case 'G': keggUrl += "gl:" + kegg; break; } keggLink = "<a href=\"" + keggUrl + "\" target=\"_blank\">" + kegg + "</a>"; } out.println("<td>" + keggLink + "</td>"); // Pathway Map Link if (massbank2mapList.containsKey(id)) { ArrayList<String> list = massbank2mapList.get(id); for (int l1 = mapNameList.size() - 1; l1 >= 0; l1--) { boolean isFound = false; String map = ""; for (int l2 = list.size() - 1; l2 >= 0; l2--) { map = list.get(l2); if (map.equals(mapNameList.get(l1))) { isFound = true; break; } } if (isFound) { ArrayList<String> list2 = map2keggList.get(map); String mapUrl = serverUrl + "temp/pathway/" + this.jobId + "_" + map + ".png"; out.println("<td nowrap><a href=\"" + mapUrl + "\" target=\"_blank\">map:" + map + "(" + list2.size() + ")</a></td>"); } else { out.println("<td> -</td>"); } } } else { for (int l1 = mapNameList.size() - 1; l1 >= 0; l1--) { out.println("<td> -</td>"); } } } } out.println("</tr>"); } out.println("</table>"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { } if (out != null) { out.flush(); out.close(); } } }