List of usage examples for java.util Formatter Formatter
public Formatter()
From source file:com.diversityarrays.dalclient.DalUtil.java
/** * Computes the MD5 checksum of the bytes in the InputStream. * The input is close()d on exit./*from w w w . j av a 2 s . c o m*/ * @param input is the InputStream for which to compute the checksum * @return the MD5 checksum as a String of hexadecimal characters */ static public String computeMD5checksum(InputStream input) { DigestInputStream dis = null; Formatter formatter = null; try { MessageDigest md = MessageDigest.getInstance(DIGEST_MD5); dis = new DigestInputStream(input, md); while (-1 != dis.read()) ; byte[] digest = md.digest(); formatter = new Formatter(); for (byte b : digest) { formatter.format("%02x", b); //$NON-NLS-1$ } return formatter.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { if (dis != null) { try { dis.close(); } catch (IOException ignore) { } } if (formatter != null) { formatter.close(); } } }
From source file:edu.ku.brc.specify.tasks.subpane.LocalityMapperSubPane.java
/** * *//*w w w .j a v a2s . c om*/ protected void createUI() { kmlGen = new CollectingEventLocalityKMLGenerator(); this.collectingEvents = new ArrayList<CollectingEvent>(); CollectingEvent startCE = null; CollectingEvent endCE = null; Vector<Locality> localities = new Vector<Locality>(); Vector<String> labels = new Vector<String>(); for (Object obj : colEvents) { CollectingEvent collectingEvent = (CollectingEvent) obj; Locality locality = collectingEvent.getLocality(); if (locality == null || locality.getLatitude1() == null || locality.getLongitude1() == null) { continue; } collectingEvents.add(collectingEvent); kmlGen.addDataObj(collectingEvent, ""); if (collectingEvents.size() == 1) { startCE = collectingEvent; endCE = collectingEvent; } // XXX TODO FIX ME! if (startCE == null || endCE == null) { return; } // There may be an End Date that is further out than than the End Date of the last item // with the latest Start Date if (startCE.getStartDate().compareTo(collectingEvent.getStartDate()) > 1) { startCE = collectingEvent; } Calendar leftCal = endCE.getEndDate() != null ? endCE.getEndDate() : endCE.getStartDate(); Calendar rightCal = collectingEvent.getEndDate() != null ? collectingEvent.getEndDate() : collectingEvent.getStartDate(); if (leftCal.compareTo(rightCal) < 0) { endCE = collectingEvent; } Hashtable<String, Object> map = new Hashtable<String, Object>(); Set<CollectionObject> colObjs = collectingEvent.getCollectionObjects(); map.put("startDate", collectingEvent.getStartDate()); map.put("endDate", collectingEvent.getEndDate()); Set<Object> taxonNames = new HashSet<Object>(); for (CollectionObject co : colObjs) { for (Determination d : co.getDeterminations()) { if (d.isCurrentDet()) { //System.out.println(d.getTaxon().getName() + "("+co.getCountAmt()+")"); Taxon taxon = d.getPreferredTaxon(); if (taxon != null) { taxonNames.add(taxon.getName() + (co.getCountAmt() != null ? " (" + co.getCountAmt() + ")" : "")); if (taxon.getRankId() == 220) { Taxon genus = taxon.getParent(); if (genus.getRankId() == 180) { ImageGetter imgGetter = new ImageGetter(imageGetterList, imageMap, imageURLs, genus.getName(), taxon.getName()); imageGetterList.add(imgGetter); } } } break; } } } map.put("taxonItems", taxonNames); map.put("latitude1", locality.getLatitude1()); map.put("longitude1", locality.getLongitude1()); /* Calendar cal = collectingEvent.getStartDate(); if (cal != null) { labels.add(scrDateFormat.format(cal.getTime())); } else if (collectingEvent.getVerbatimDate() != null) { labels.add(collectingEvent.getVerbatimDate()); } else { labels.add(Integer.toString(collectingEvent.getCollectingEventId())); } */ labels.add(Integer.toString(collectingEvents.size())); localities.add(locality); valueList.add(map); } // XXX Fix me shouldn't be hard coded here to make it work localityMapper.setMaxMapWidth(515); localityMapper.setMaxMapHeight(375); Color arrow = new Color(220, 220, 220); localityMapper.setArrowColor(arrow); localityMapper.setDotColor(Color.WHITE); localityMapper.setDotSize(4); localityMapper.setLabelColor(Color.RED); int inx = 0; for (Locality locality : localities) { localityMapper.addLocationAndLabel(locality, labels != null ? labels.get(inx) : null); inx++; } localityMapper.setCurrentLoc(localities.get(0)); localityMapper.setCurrentLocColor(Color.RED); // XXX DEMO (Hard Coded 'null' means everyone would have one which may not be true) // "null" ViewSet name means it should use the default ViewIFace view = AppContextMgr.getInstance().getView("LocalityMapper"); // TODO WHERE's the ERROR checking ! multiView = new MultiView(null, null, view, AltViewIFace.CreationMode.VIEW, MultiView.NO_OPTIONS); multiView.setBorder( BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(new Color(138, 128, 128)), BorderFactory.createEmptyBorder(4, 4, 4, 4))); formViewObj = multiView.getCurrentViewAsFormViewObj(); formViewObj.getUIComponent().setBackground(Color.WHITE); imageJList = formViewObj.getCompById("taxonItems"); imageJList.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { String nameStr = (String) imageJList.getSelectedValue(); if (nameStr != null) { int index = nameStr.indexOf(" ("); if (index > -1) { nameStr = nameStr.substring(0, index); } } //System.out.println("Getting["+name+"]"); Image img = null; if (StringUtils.isNotEmpty(nameStr)) { img = imageMap.get(nameStr); // might return null ImageDisplay imgDisplay = formViewObj.getCompById("image"); if (img != null) { imgDisplay.setImage(new ImageIcon(img)); } else { imgDisplay.setImage((Image) null); } } } } }); // XXX TODO FIX ME! if (startCE == null || endCE == null) { return; } String startDateStr = scrDateFormat.format(startCE.getStartDate().getTime()); String endDateStr = scrDateFormat .format((endCE.getEndDate() != null ? endCE.getEndDate() : endCE.getStartDate()).getTime()); Formatter formatter = new Formatter(); titleLabel.setText(formatter .format(getResourceString("LocalityMapperTitle"), new Object[] { startDateStr, endDateStr }) .toString()); Font font = titleLabel.getFont(); titleLabel.setFont(new Font(font.getFontName(), Font.BOLD, font.getSize() + 2)); recordSetController = new ResultSetController(null, false, false, false, null, collectingEvents.size(), true); recordSetController.addListener(this); recordSetController.getPanel().setBackground(Color.WHITE); controlPanel = new ControlBarPanel(getBackground()); controlPanel.add(recordSetController.getPanel()); controlPanel.setRecordSetController(recordSetController); controlPanel.setBackground(Color.WHITE); googleBtn = new JButton(IconManager.getIcon("GoogleEarth", IconManager.STD_ICON_SIZE)); googleBtn.setMargin(new Insets(1, 1, 1, 1)); googleBtn.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); googleBtn.setSize(new Dimension(18, 18)); googleBtn.setPreferredSize(new Dimension(18, 18)); googleBtn.setMaximumSize(new Dimension(18, 18)); googleBtn.setFocusable(false); googleBtn.setBackground(Color.WHITE); controlPanel.addButtons(new JButton[] { googleBtn }, false); googleBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { try { UIRegistry.displayStatusBarText("Exporting Collecting Events in KML."); // XXX I18N kmlGen.setSpeciesToImageMapper(imageURLs); kmlGen.outputToFile(System.getProperty("user.home") + File.separator + "specify.kml"); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(LocalityMapperSubPane.class, ex); ex.printStackTrace(); } } }); addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) { // nothing } public void mouseMoved(MouseEvent e) { checkMouseLocation(e.getPoint(), false); } }); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { checkMouseLocation(e.getPoint(), true); } }); SwingUtilities.invokeLater(new Runnable() { public void run() { getLocalityMap(); } }); }
From source file:de.huxhorn.sulky.blobs.impl.BlobRepositoryImpl.java
private boolean valid(String id, File file) { if (!validating) { return true; }//from ww w. j av a 2s . co m MessageDigest digest = createMessageDigest(); FileInputStream input = null; try { input = new FileInputStream(file); DigestInputStream dis = new DigestInputStream(input, digest); for (;;) { if (dis.read() < 0) { break; } } byte[] hash = digest.digest(); Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } return formatter.toString().equals(id); } catch (IOException e) { // ignore... } finally { IOUtils.closeQuietly(input); } return false; }
From source file:com.flexive.war.beans.admin.main.ScriptBean.java
/** * Runs the given script code in the console *//*w w w . ja va 2 s.c om*/ public void runScriptInConsole() { FxScriptInfoEdit sinfo = currentData.sinfo; if (StringUtils.isBlank(sinfo.getCode())) { new FxFacesMsgErr("Script.err.noCodeProvided").addToContext(); } else { long start = System.currentTimeMillis(); try { result = ScriptConsoleBean.runScript(sinfo.getCode(), sinfo.getName(), false); } catch (Exception e) { final StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); final String msg = e.getCause() != null ? e.getCause().getMessage() : e.getMessage(); result = new Formatter().format("Exception caught: %s%n%s", msg, writer.getBuffer()); } finally { currentData.executionTime = System.currentTimeMillis() - start; } } }
From source file:de.huxhorn.sulky.blobs.impl.BlobRepositoryImpl.java
private String copyAndHash(InputStream input, File into) throws IOException { MessageDigest digest = createMessageDigest(); DigestInputStream dis = new DigestInputStream(input, digest); IOException ex;// w w w .j a va2 s . c o m FileOutputStream fos = null; try { fos = new FileOutputStream(into); IOUtils.copyLarge(dis, fos); byte[] hash = digest.digest(); Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } return formatter.toString(); } catch (IOException e) { ex = e; } finally { IOUtils.closeQuietly(dis); IOUtils.closeQuietly(fos); } if (logger.isWarnEnabled()) logger.warn("Couldn't retrieve data from input!", ex); deleteTempFile(into); throw ex; }
From source file:com.ideateam.plugin.Version.java
public static String getSHA1FromFileContent(String filename) throws NoSuchAlgorithmException, IOException { final MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); InputStream is = new BufferedInputStream(new FileInputStream(filename)); final byte[] buffer = new byte[1024]; for (int read = 0; (read = is.read(buffer)) != -1;) { messageDigest.update(buffer, 0, read); }/* w w w .ja va 2 s .c om*/ is.close(); // Convert the byte to hex format Formatter formatter = new Formatter(); for (final byte b : messageDigest.digest()) { formatter.format("%02x", b); } String res = formatter.toString(); formatter.close(); return res; }
From source file:fll.scheduler.SchedulerUI.java
/** * Run the scheduler and optionally the table optimizer. */// w ww . ja v a 2 s . c o m private void runScheduler() { try { saveScheduleDescription(); final SchedulerWorker worker = new SchedulerWorker(); // make sure the task doesn't start until the window is up _progressDialog.addComponentListener(new ComponentAdapter() { @Override public void componentShown(final ComponentEvent e) { _progressDialog.removeComponentListener(this); worker.execute(); } }); _progressDialog.setLocationRelativeTo(SchedulerUI.this); _progressDialog.setNote("Running Scheduler"); _progressDialog.setVisible(true); } catch (final IOException e) { final Formatter errorFormatter = new Formatter(); errorFormatter.format("Error reading description file: %s", e.getMessage()); LOGGER.error(errorFormatter, e); JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error Running Scheduler", JOptionPane.ERROR_MESSAGE); } catch (final ParseException e) { final Formatter errorFormatter = new Formatter(); errorFormatter.format("Error parsing description file: %s", e.getMessage()); LOGGER.error(errorFormatter, e); JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error Running Scheduler", JOptionPane.ERROR_MESSAGE); } catch (final InvalidParametersException e) { LOGGER.error(e.getMessage(), e); JOptionPane.showMessageDialog(SchedulerUI.this, e.getMessage(), "Error Running Scheduler", JOptionPane.ERROR_MESSAGE); } }
From source file:org.gumtree.vis.plot1d.KLogarithmicAxis.java
private List getAllTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) { // TODO Auto-generated method stub List ticks = new java.util.ArrayList(); Range range = getRange();//from w w w. j ava 2 s . co m //get lower bound value: double lowerBoundVal = range.getLowerBound(); //if small log values and lower bound value too small // then set to a small value (don't allow <= 0): if (this.smallLogFlag && lowerBoundVal < SMALL_LOG_VALUE) { lowerBoundVal = SMALL_LOG_VALUE; } //get upper bound value double upperBoundVal = range.getUpperBound(); //get log10 version of lower bound and round to integer: int iBegCount = (int) Math.rint(switchedLog10(lowerBoundVal)); //get log10 version of upper bound and round to integer: int iEndCount = (int) Math.rint(switchedLog10(upperBoundVal)); // if (iBegCount == iEndCount && iBegCount >= 0 if (iBegCount == iEndCount && Math.pow(10, iBegCount) > lowerBoundVal) { //only 1 power of 10 value, it's > 0 and its resulting // tick value will be larger than lower bound of data --iBegCount; //decrement to generate more ticks } int numberOfGrids = 0; int numberOfTicks = 0; NumberTick lastTick = null; double currentTickValue; String tickLabel; boolean zeroTickFlag = false; for (int i = iBegCount; i <= iEndCount; i++) { //for each power of 10 value; create ten ticks for (int j = 0; j < 10; ++j) { //for each tick to be displayed if (this.smallLogFlag) { //small log values in use; create numeric value for tick currentTickValue = Math.pow(10, i) + (Math.pow(10, i) * j); if (this.expTickLabelsFlag || (i < 0 && currentTickValue > 0.0 && currentTickValue < 1.0)) { //showing "1e#"-style ticks or negative exponent // generating tick value between 0 & 1; show fewer //first tick of series, or not too small a value and // one of first 3 ticks, or last tick to be displayed // set exact number of fractional digits to be shown // (no effect if showing "1e#"-style ticks): this.numberFormatterObj.setMaximumFractionDigits(-i); //create tick label (force use of fmt obj): tickLabel = makeTickLabel(currentTickValue, true); } else { //tick value not between 0 & 1 //show tick label if it's the first or last in // the set, or if it's 1-5; beyond that show // fewer as the values get larger: tickLabel = makeTickLabel(currentTickValue); } } else { //not small log values in use; allow for values <= 0 if (zeroTickFlag) { //if did zero tick last iter then --j; //decrement to do 1.0 tick now } //calculate power-of-ten value for tick: currentTickValue = (i >= 0) ? Math.pow(10, i) + (Math.pow(10, i) * j) : -(Math.pow(10, -i) - (Math.pow(10, -i - 1) * j)); if (!zeroTickFlag) { // did not do zero tick last iteration if (Math.abs(currentTickValue - 1.0) < 0.0001 && lowerBoundVal <= 0.0 && upperBoundVal >= 0.0) { //tick value is 1.0 and 0.0 is within data range currentTickValue = 0.0; //set tick value to zero zeroTickFlag = true; //indicate zero tick } } else { //did zero tick last iteration zeroTickFlag = false; //clear flag } //create tick label string: //show tick label if "1e#"-style and it's one // of the first two, if it's the first or last // in the set, or if it's 1-5; beyond that // show fewer as the values get larger: tickLabel = makeTickLabel(currentTickValue); } if (currentTickValue > upperBoundVal) { if (lastTick != null) { String lastTickText = lastTick.getText(); if (lastTickText == null || lastTickText.trim().length() == 0) { ticks.remove(lastTick); ticks.add(new NumberTick(lastTick.getValue(), createTickLabel(lastTick.getValue(), i - 1), lastTick.getTextAnchor(), lastTick.getRotationAnchor(), lastTick.getAngle())); } } if (ticks.size() < 2) { double definition = Math.abs(lowerBoundVal - upperBoundVal); int numberOfDigits = 0; if (definition >= 1) numberOfDigits = 0; else { numberOfDigits = (int) Math.ceil((-Math.log10(definition))); } if (definition < 2 * Math.pow(10, -numberOfDigits)) { numberOfDigits++; } double tickVal; tickVal = lowerBoundVal; if (definition > 1) tickLabel = Long.toString((long) Math.rint(tickVal)); else tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString(); ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.TOP_CENTER, TextAnchor.TOP_CENTER, 0.0)); tickVal = upperBoundVal; if (definition > 1) tickLabel = Long.toString((long) Math.rint(tickVal)); else tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString(); ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.TOP_CENTER, TextAnchor.TOP_CENTER, 0.0)); } return ticks; // if past highest data value then exit // method } if (currentTickValue >= lowerBoundVal - SMALL_LOG_VALUE) { //tick value not below lowest data value TextAnchor anchor = null; TextAnchor rotationAnchor = null; double angle = 0.0; if (isVerticalTickLabels()) { anchor = TextAnchor.CENTER_RIGHT; rotationAnchor = TextAnchor.CENTER_RIGHT; if (edge == RectangleEdge.TOP) { angle = Math.PI / 2.0; } else { angle = -Math.PI / 2.0; } } else { if (edge == RectangleEdge.TOP) { anchor = TextAnchor.BOTTOM_CENTER; rotationAnchor = TextAnchor.BOTTOM_CENTER; } else { anchor = TextAnchor.TOP_CENTER; rotationAnchor = TextAnchor.TOP_CENTER; } } lastTick = new NumberTick(new Double(currentTickValue), tickLabel, anchor, rotationAnchor, angle); ticks.add(lastTick); if (tickLabel != null && tickLabel.trim().length() > 0) numberOfTicks++; numberOfGrids++; } } } if (ticks.size() < 2) { double definition = Math.abs(lowerBoundVal - upperBoundVal); int numberOfDigits = 0; if (definition >= 1) numberOfDigits = 0; else { numberOfDigits = (int) Math.ceil((-Math.log10(definition))); } double tickVal; tickVal = lowerBoundVal; if (definition > 1) tickLabel = Long.toString((long) Math.rint(tickVal)); else tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString(); ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.TOP_CENTER, TextAnchor.TOP_CENTER, 0.0)); tickVal = upperBoundVal; if (definition > 1) tickLabel = Long.toString((long) Math.rint(tickVal)); else tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString(); ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.TOP_CENTER, TextAnchor.TOP_CENTER, 0.0)); } return ticks; }
From source file:net.ftb.util.DownloadUtils.java
public static String fileHash(File file, String type) throws IOException { if (!file.exists()) { return ""; }/*from w w w.j a va 2s. co m*/ if (type.equalsIgnoreCase("md5")) return fileMD5(file); if (type.equalsIgnoreCase("sha1")) return fileSHA(file); URL fileUrl = file.toURI().toURL(); MessageDigest dgest = null; try { dgest = MessageDigest.getInstance(type); } catch (NoSuchAlgorithmException e) { } InputStream str = fileUrl.openStream(); byte[] buffer = new byte[65536]; int readLen; while ((readLen = str.read(buffer, 0, buffer.length)) != -1) { dgest.update(buffer, 0, readLen); } str.close(); Formatter fmt = new Formatter(); for (byte b : dgest.digest()) { fmt.format("%02X", b); } String result = fmt.toString(); fmt.close(); return result; }
From source file:com.android.ddmuilib.net.NetworkPanel.java
/** * Find a {@link TrackedItem} that matches the requested UID and tag, or * create one if none exists./*www . j a v a 2 s. c o m*/ */ public TrackedItem findOrCreateTrackedItem(int uid, int tag) { // try searching for existing item for (TrackedItem item : mTrackedItems) { if (item.uid == uid && item.tag == tag) { return item; } } // nothing found; create new item final TrackedItem item = new TrackedItem(uid, tag); if (item.isTotal()) { item.color = TOTAL_COLOR; item.label = "Total"; } else { final int size = mTrackedItems.size(); item.color = nextSeriesColor(size); Formatter formatter = new Formatter(); item.label = "0x" + formatter.format("%08x", tag); formatter.close(); } // create color chip to display as legend in table item.colorImage = new Image(mDisplay, 20, 20); final GC gc = new GC(item.colorImage); gc.setBackground(new org.eclipse.swt.graphics.Color(mDisplay, item.color.getRed(), item.color.getGreen(), item.color.getBlue())); gc.fillRectangle(item.colorImage.getBounds()); gc.dispose(); mTrackedItems.add(item); return item; }