List of usage examples for java.util Formatter Formatter
public Formatter(OutputStream os)
From source file:httpmultiplexer.httpproxy.ProxyServlet.java
/** * Encodes characters in the query or fragment part of the URI. * * <p>/* ww w . ja v a 2s.co m*/ * Unfortunately, an incoming URI sometimes has characters disallowed by the * spec. HttpClient insists that the outgoing proxied request has a valid * URI because it uses Java's {@link URI}. To be more forgiving, we must * escape the problematic characters. See the URI class for the spec. * * @param in example: name=value&foo=bar#fragment */ protected static CharSequence encodeUriQuery(CharSequence in) { //Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things. StringBuilder outBuf = null; Formatter formatter = null; for (int i = 0; i < in.length(); i++) { char c = in.charAt(i); boolean escape = true; if (c < 128) { if (asciiQueryChars.get((int) c)) { escape = false; } } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii escape = false; } if (!escape) { if (outBuf != null) { outBuf.append(c); } } else { //escape if (outBuf == null) { outBuf = new StringBuilder(in.length() + 5 * 3); outBuf.append(in, 0, i); formatter = new Formatter(outBuf); } //leading %, 0 padded, width 2, capital hex formatter.format("%%%02X", (int) c);//TODO } } return outBuf != null ? outBuf : in; }
From source file:bookkeepr.jettyhandlers.CandidateHandler.java
public void handle(String path, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { if (path.startsWith("/cand/")) { ((Request) request).setHandled(true); if (path.startsWith("/cand/lists")) { if (request.getMethod().equals("GET")) { if (path.startsWith("/cand/lists/from/")) { long targetId = Long.parseLong(path.substring(17), 16); if (dbMan.getType(new DummyIdAble(targetId)) == TypeIdManager .getTypeFromClass(Psrxml.class)) { CandListSelectionRequest req = new CandListSelectionRequest(); req.setAcceptPsrxmlIds(new long[] { targetId }); XMLWriter.write(response.getOutputStream(), candMan.getCandidateLists(req)); } else if (dbMan.getType(new DummyIdAble(targetId)) == TypeIdManager .getTypeFromClass(Processing.class)) { CandListSelectionRequest req = new CandListSelectionRequest(); req.setAcceptProcessingIds(new long[] { targetId }); XMLWriter.write(response.getOutputStream(), candMan.getCandidateLists(req)); } else { response.sendError(400, "Bad GET request for /cand/lists/from/..."); return; }// w w w .j a va 2s.co m } else { CandidateListIndex idx = new CandidateListIndex(); List<IdAble> list = dbMan .getAllOfType(TypeIdManager.getTypeFromClass(CandidateListStub.class)); for (IdAble stub : list) { idx.addCandidateListStub((CandidateListStub) stub); } OutputStream out = response.getOutputStream(); String hdr = request.getHeader("Accept-Encoding"); if (hdr != null && hdr.contains("gzip")) { // if the host supports gzip encoding, gzip the output for quick transfer speed. out = new GZIPOutputStream(out); response.setHeader("Content-Encoding", "gzip"); } XMLWriter.write(out, idx); out.close(); return; } } else if (request.getMethod().equals("POST")) { try { XMLAble xmlable = XMLReader.read(request.getInputStream()); if (xmlable instanceof CandListSelectionRequest) { CandListSelectionRequest req = (CandListSelectionRequest) xmlable; OutputStream out = response.getOutputStream(); String hdr = request.getHeader("Accept-Encoding"); if (hdr != null && hdr.contains("gzip")) { // if the host supports gzip encoding, gzip the output for quick transfer speed. out = new GZIPOutputStream(out); response.setHeader("Content-Encoding", "gzip"); } XMLWriter.write(out, candMan.getCandidateLists(req)); out.close(); } else { response.sendError(400, "Bad POST request for /cand/lists"); return; } } catch (SAXException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE, null, ex); } } else if (request.getMethod().equals("DELETE")) { String[] elems = path.substring(1).split("/"); if (elems.length < 3) { response.sendError(400, "Bad DELETE request for /cand/lists/{clistId}"); return; } final long clistId = Long.parseLong(elems[2], 16); CandidateListStub cls = (CandidateListStub) dbMan.getById(clistId); if (cls == null) { response.sendError(404, "Bad ClistID requested for deletion (no such candlist)"); Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING, "Bad ClistID requested for deletion (no such candlist)"); return; } try { this.candMan.deleteCandidateListAndCands(cls); response.setStatus(202); } catch (BookKeeprException ex) { response.sendError(500, "Could not delete candidate list as requested"); Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING, "Could not delete candidate list as requested", ex); return; } } else { response.sendError(400, "Bad non-GET/non-POST/non-DELETE request for /cand/lists"); return; } } else if (path.startsWith("/cand/viewed")) { if (request.getMethod().equals("GET")) { ViewedCandidatesIndex idx = new ViewedCandidatesIndex(); List<IdAble> list = dbMan.getAllOfType(TypeIdManager.getTypeFromClass(ViewedCandidates.class)); for (IdAble stub : list) { idx.addViewedCandidates((ViewedCandidates) stub); } OutputStream out = response.getOutputStream(); String hdr = request.getHeader("Accept-Encoding"); if (hdr != null && hdr.contains("gzip")) { // if the host supports gzip encoding, gzip the output for quick transfer speed. out = new GZIPOutputStream(out); response.setHeader("Content-Encoding", "gzip"); } XMLWriter.write(out, idx); out.close(); return; } else if (request.getMethod().equals("POST")) { ViewedCandidates newViewed = null; try { XMLAble xmlable = XMLReader.read(request.getInputStream()); if (xmlable instanceof ViewedCandidates) { newViewed = (ViewedCandidates) xmlable; } else { response.sendError(400, "Bad Content type in request /cand/viewed"); return; } } catch (SAXException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO, "Bad XML in client request to POST new viewed cands"); response.sendError(400, "Bad XML in request /cand/viewed"); return; } IdAble idable = this.dbMan.getById(newViewed.getId()); if (idable instanceof ViewedCandidates) { newViewed.append(((ViewedCandidates) idable)); } else { newViewed.setId(0); } Session session = new Session(); this.dbMan.add(newViewed, session); try { this.dbMan.save(session); } catch (BookKeeprException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE, "Error saving viewed cands to database", ex); response.sendError(500, "Error saving viewed cands to database"); return; } OutputStream out = response.getOutputStream(); String hdr = request.getHeader("Accept-Encoding"); if (hdr != null && hdr.contains("gzip")) { // if the host supports gzip encoding, gzip the output for quick transfer speed. out = new GZIPOutputStream(out); response.setHeader("Content-Encoding", "gzip"); } XMLWriter.write(out, newViewed); out.close(); return; } else { response.sendError(400, "Bad non-GET/POST request /cand/viewed"); return; } } else if (path.startsWith("/cand/psrcat")) { if (request.getMethod().equals("GET")) { String[] elems = path.substring(1).split("/"); if (elems.length > 2) { try { long id = Long.parseLong(elems[2], 16); ClassifiedCandidate cand = (ClassifiedCandidate) dbMan.getById(id); String str = cand.getPsrcatEntry().toString(); response.setContentType("text/plain"); OutputStream out = response.getOutputStream(); String hdr = request.getHeader("Accept-Encoding"); if (hdr != null && hdr.contains("gzip")) { // if the host supports gzip encoding, gzip the output for quick transfer speed. out = new GZIPOutputStream(out); response.setHeader("Content-Encoding", "gzip"); } PrintWriter wr = new PrintWriter(out); wr.write(str); wr.close(); out.close(); } catch (ClassCastException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING, "Invalid candidate id passed to /cand/psrcat", ex); response.sendError(400, "Bad id in request for /cand/psrcat"); } } else { response.sendError(400, "Bad request for /cand/psrcat"); } } else { response.sendError(400, "Bad non-GET request for /cand/psrcat"); } } else if (path.startsWith("/cand/classified")) { if (request.getMethod().equals("GET")) { String[] elems = path.substring(1).split("/"); ClassifiedCandidateIndex idx = new ClassifiedCandidateIndex(); List<IdAble> list = dbMan .getAllOfType(TypeIdManager.getTypeFromClass(ClassifiedCandidate.class)); if (elems.length > 2) { int cl = Integer.parseInt(elems[2]); for (IdAble stub : list) { if (((ClassifiedCandidate) stub).getCandClassInt() == cl) { idx.addClassifiedCandidate((ClassifiedCandidate) stub); } } } else { for (IdAble stub : list) { idx.addClassifiedCandidate((ClassifiedCandidate) stub); } } OutputStream out = response.getOutputStream(); String hdr = request.getHeader("Accept-Encoding"); if (hdr != null && hdr.contains("gzip")) { // if the host supports gzip encoding, gzip the output for quick transfer speed. out = new GZIPOutputStream(out); response.setHeader("Content-Encoding", "gzip"); } XMLWriter.write(out, idx); out.close(); return; } else if (request.getMethod().equals("POST")) { // post a CandidateSelectRequest ClassifiedCandidateSelectRequest ccsreq = null; try { XMLAble xmlable = XMLReader.read(request.getInputStream()); if (xmlable instanceof ClassifiedCandidateSelectRequest) { ccsreq = (ClassifiedCandidateSelectRequest) xmlable; } else { response.sendError(400, "Bad item posted to /cand/classified for Searching"); return; } } catch (SAXException ex) { response.sendError(400, "Bad item posted to /cand/classified for Searching"); return; } // reply with the searched index ClassifiedCandidateIndex idx = candMan.searchCandidates(ccsreq); OutputStream out = response.getOutputStream(); String hdr = request.getHeader("Accept-Encoding"); if (hdr != null && hdr.contains("gzip")) { // if the host supports gzip encoding, gzip the output for quick transfer speed. out = new GZIPOutputStream(out); response.setHeader("Content-Encoding", "gzip"); } XMLWriter.write(out, idx); out.close(); } else { response.sendError(400, "Bad non-POST/GET request /cand/classified"); return; } } else if (path.startsWith("/cand/newclassified")) { if (request.getMethod().equals("POST")) { ClassifiedCandidate cand = null; try { XMLAble xmlable = XMLReader.read(request.getInputStream()); if (xmlable instanceof ClassifiedCandidate) { cand = (ClassifiedCandidate) xmlable; } else { response.sendError(400, "Bad item posted to /cand/newclassified for Classifying"); return; } } catch (SAXException ex) { response.sendError(400, "Bad item posted to /cand/newclassified for Classifying"); return; } cand.setId(0); Session session = new Session(); dbMan.add(cand, session); try { dbMan.save(session); } catch (BookKeeprException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE, "error saving database when adding new classified cand", ex); response.sendError(500, "error saving database when adding new classified cand"); } OutputStream out = response.getOutputStream(); String hdr = request.getHeader("Accept-Encoding"); if (hdr != null && hdr.contains("gzip")) { // if the host supports gzip encoding, gzip the output for quick transfer speed. out = new GZIPOutputStream(out); response.setHeader("Content-Encoding", "gzip"); } XMLWriter.write(out, cand); out.close(); return; } else { response.sendError(400, "Bad non-POST request /cand/newclassified"); return; } } else if (path.startsWith("/cand/add/")) { // assume that 'add' is not an ID, since it would have server and type = 0, which is invalid. if (request.getMethod().equals("POST")) { String[] elems = path.substring(1).split("/"); if (elems.length < 4) { response.sendError(400, "Bad URL for /cand/add/{psrxmlId}/{procId}"); return; } final long psrxmlId = Long.parseLong(elems[2], 16); final long procId = Long.parseLong(elems[3], 16); if (dbMan.getById(procId) == null) { response.sendError(400, "Bad URL for /cand/add/{psrxmlId}/{procId}. ProcId " + Long.toHexString(procId) + " does not exist!"); return; } if (dbMan.getById(psrxmlId) == null) { response.sendError(400, "Bad URL for /cand/add/{psrxmlId}/{procId}. PsrxmlId " + Long.toHexString(psrxmlId) + " does not exist!"); return; } synchronized (this) { if (nAddSubmitted > 2) { // too many jobs on. to prevent memory overload, end the session! response.setHeader("Retry-After", "60"); response.sendError(503); return; } else { //increment the workload counter nAddSubmitted++; } } final ArrayList<RawCandidate> rawCands = new ArrayList<RawCandidate>(); if (request.getContentType().equals("application/x-tar")) { TarInputStream tarin = new TarInputStream(request.getInputStream()); while (true) { // loop over all entries in the tar file. TarEntry tarEntry = tarin.getNextEntry(); if (tarEntry == null) { break; } else { } InputStream inStream; /* * There is some complication as the XML reader * closes the input stream when it is done, but we * don't want to do that as it closes the entire tar * * So we define a 'UnclosableInputStream' that ignores * the close() command. * * If we have a gzipped xml file, we should pass * through a gzip input stream too. */ if (tarEntry.getName().endsWith(".gz")) { inStream = new UncloseableInputStream(new GZIPInputStream(tarin)); } else { inStream = new UncloseableInputStream(tarin); } try { // parse the xml document. XMLAble xmlable = (XMLAble) XMLReader.read(inStream); if (xmlable instanceof RawCandidate) { rawCands.add((RawCandidate) xmlable); } else { response.sendError(400, "POSTed tar file MUST only contain raw candidates."); return; } } catch (SAXException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING, null, ex); response.sendError(400, "POSTed tar file MUST only contain vaild xml candidates."); return; } } // finaly, we can close the tar stream. tarin.close(); Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO, "Received " + rawCands.size() + " raw candidates for processing from " + request.getRemoteAddr()); final BackgroundedTask bgtask = new BackgroundedTask("AddRawCandidates"); bgtask.setTarget(new Runnable() { public void run() { candMan.addRawCandidates(rawCands, psrxmlId, procId); synchronized (CandidateHandler.this) { // decriment the counter for how many workloads are left to do. CandidateHandler.this.nAddSubmitted--; } } }); bookkeepr.getBackgroundTaskRunner().offer(bgtask); StringBuffer buf = new StringBuffer(); Formatter formatter = new Formatter(buf); formatter.format("%s/%s/%d", bookkeepr.getConfig().getExternalUrl(), "tasks", bgtask.getId()); response.setStatus(303); response.addHeader("Location", buf.toString()); return; } else { response.sendError(400, "Must POST application/x-tar type documents to this URL"); } } else { response.sendError(400, "Bad non-POST request /cand/add"); return; } } else { // see if we are requesting and ID. long targetId = 0; String[] elems = path.substring(1).split("/"); // try and make an int from the passed value. try { if (elems.length < 2) { response.sendError(400, "Bad URL for /cand/{id}"); return; } targetId = Long.parseLong(elems[1], 16); } catch (NumberFormatException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO, "Recieved request for bad id " + elems[1]); response.sendError(400, "Submitted URI was malformed\nMessage was '" + ex.getMessage() + "'"); return; } IdAble idable = dbMan.getById(targetId); if (idable == null) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO, "Recieved request for non-existing ID " + Long.toHexString(targetId)); response.sendError(400, "Submitted request was for non-existing ID " + Long.toHexString(targetId)); return; } if (idable instanceof CandidateListStub) { if (request.getMethod().equals("GET")) { int origin = dbMan.getOrigin(idable); if (dbMan.getOriginId() == origin) { // request for a local item... response.setHeader("Content-Encoding", "gzip"); outputToInput( new FileInputStream(candMan.getCandidateListFile((CandidateListStub) idable)), response.getOutputStream()); } else { HttpClient httpclient = bookkeepr.checkoutHttpClient(); try { // request for a remote item... BookkeeprHost host = bookkeepr.getConfig().getBookkeeprHost(origin); String targetpath = host.getUrl() + path; HttpGet httpreq = new HttpGet(targetpath); HttpResponse httpresp = httpclient.execute(httpreq); for (Header head : httpresp.getAllHeaders()) { if (head.getName().equalsIgnoreCase("transfer-encoding")) { continue; } response.setHeader(head.getName(), head.getValue()); } response.setStatus(httpresp.getStatusLine().getStatusCode()); httpresp.getEntity().writeTo(response.getOutputStream()); } catch (URISyntaxException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING, "Bad uri specified for remote candidate", ex); response.sendError(500, "Bad uri specified for remote candidate"); } catch (HttpException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING, "Could not make a httpreqest for remote Candidate", ex); response.sendError(500, "Could not make a httpreqest for remote Candidate"); } catch (IOException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING, "Could not make a httpreqest for remote Candidate", ex); response.sendError(500, "Could not make a httpreqest for remote Candidate"); } bookkeepr.returnHttpClient(httpclient); // if (host != null) { // response.setStatus(301); // response.addHeader("Location", host.getUrl() + path); // } else { // response.sendError(500, "Cannot find a bookkeepr server for origin id " + origin); // } } } else { response.sendError(400, "Bad non-GET request for a candidate list"); return; } } else if (idable instanceof ClassifiedCandidate) { // /cand/{id} if (request.getMethod().equals("POST")) { // int origin = dbMan.getOrigin(idable); // if (dbMan.getOriginId() == origin) { RawCandidateMatched stub = null; try { XMLAble xmlable = XMLReader.read(request.getInputStream()); if (xmlable instanceof RawCandidateMatched) { stub = (RawCandidateMatched) xmlable; } else { response.sendError(400, "Bad item posted to /cand/... for Classifying"); return; } } catch (SAXException ex) { response.sendError(400, "Bad item posted to /cand/... for Classifying"); return; } ClassifiedCandidate c = null; try { c = (ClassifiedCandidate) ((ClassifiedCandidate) idable).clone(); } catch (CloneNotSupportedException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE, null, ex); response.sendError(500, "Server error that cannot happen happened! Classified Candidates are Cloneable!"); return; } c.addRawCandidateMatched(stub); Session session = new Session(); dbMan.add(c, session); try { dbMan.save(session); } catch (BookKeeprException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING, "Error when saving database adding raw to classified cand", ex); response.sendError(500, "Error when saving database adding raw to classified cand"); } OutputStream out = response.getOutputStream(); String hdr = request.getHeader("Accept-Encoding"); if (hdr != null && hdr.contains("gzip")) { // if the host supports gzip encoding, gzip the output for quick transfer speed. out = new GZIPOutputStream(out); response.setHeader("Content-Encoding", "gzip"); } XMLWriter.write(out, c); out.close(); // OutputStream out = response.getOutputStream(); // String hdr = request.getHeader("Accept-Encoding"); // if (hdr != null && hdr.contains("gzip")) { // // if the host supports gzip encoding, gzip the output for quick transfer speed. // out = new GZIPOutputStream(out); // response.setHeader("Content-Encoding", "gzip"); // } // XMLWriter.write(out, idx); // out.close(); // } else { // // request for a remote item... // // currently re-direct to the remote server.. perhaps we should pass through? // BookkeeprHost host = bookkeepr.getConfig().getBookkeeprHost(origin); // if (host != null) { // response.setStatus(301); // response.addHeader("Location", host.getUrl() + path); // } else { // response.sendError(500, "Cannot find a bookkeepr server for origin id " + origin); // } // } } else { response.sendError(400, "Bad non-POST request for a classified candidate"); return; } } else if (idable instanceof RawCandidateStub) { if (request.getMethod().equals("GET")) { int origin = dbMan.getOrigin(idable); if (dbMan.getOriginId() == origin) { if (elems.length > 2) { try { int h = 600; int w = 800; String[] parts = elems[2].split("x|\\.png"); if (parts.length > 1) { try { h = Integer.parseInt(parts[1]); w = Integer.parseInt(parts[0]); } catch (NumberFormatException e) { h = 600; w = 800; } } RawCandidate cand = (RawCandidate) XMLReader .read(new GZIPInputStream(new FileInputStream( candMan.getRawCandidateFile((RawCandidateStub) idable)))); response.setContentType("image/png"); BufferedImage img = candMan.makeImageOf(cand, w, h); ImageIO.write(img, "png", response.getOutputStream()); return; } catch (SAXException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE, null, ex); } } // request for a local item... response.setHeader("Content-Encoding", "gzip"); outputToInput( new FileInputStream(candMan.getRawCandidateFile((RawCandidateStub) idable)), response.getOutputStream()); } else { HttpClient httpclient = bookkeepr.checkoutHttpClient(); try { // request for a remote item... BookkeeprHost host = bookkeepr.getConfig().getBookkeeprHost(origin); String targetpath = host.getUrl() + path; HttpGet httpreq = new HttpGet(targetpath); HttpResponse httpresp = httpclient.execute(httpreq); for (Header head : httpresp.getAllHeaders()) { if (head.getName().equalsIgnoreCase("transfer-encoding")) { continue; } response.setHeader(head.getName(), head.getValue()); } response.setStatus(httpresp.getStatusLine().getStatusCode()); httpresp.getEntity().writeTo(response.getOutputStream()); } catch (URISyntaxException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING, "Bad uri specified for remote candidate", ex); response.sendError(500, "Bad uri specified for remote candidate"); } catch (HttpException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING, "Could not make a httpreqest for remote Candidate", ex); response.sendError(500, "Could not make a httpreqest for remote Candidate"); } catch (IOException ex) { Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING, "Could not make a httpreqest for remote Candidate", ex); response.sendError(500, "Could not make a httpreqest for remote Candidate"); } bookkeepr.returnHttpClient(httpclient); } } else { response.sendError(400, "Bad non-GET request for a raw candidate"); return; } } else { Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO, "Recieved request for non-candidate ID " + targetId); response.sendError(400, "Submitted request was for non-candidate ID " + targetId); return; } } } }
From source file:fr.inrialpes.exmo.align.cli.GroupEval.java
public void printLATEX(Vector<Vector<Object>> result, PrintStream writer) { // variables for computing iterative harmonic means int expected = 0; // expected so far int foundVect[]; // found so far int correctVect[]; // correct so far long timeVect[]; // time so far Formatter formatter = new Formatter(writer); fsize = format.length();/*w w w .j a v a2 s . c o m*/ // JE: the h-means computation should be put out as well // Print the header writer.println("\\documentclass[11pt]{book}"); writer.println(); writer.println("\\begin{document}"); writer.println("\\date{today}"); writer.println(""); writer.println("\n%% Plot generated by GroupEval of alignapi"); writer.println("\\setlength{\\tabcolsep}{3pt} % May be changed"); writer.println("\\begin{table}"); writer.print("\\begin{tabular}{|l||"); for (int i = size; i > 0; i--) { for (int j = fsize; j > 0; j--) writer.print("c"); writer.print("|"); } writer.println("}"); writer.println("\\hline"); // For each file do a writer.print("algo"); // for each algo <td spancol='2'>name</td> for (String m : listAlgo) { writer.print(" & \\multicolumn{" + fsize + "}{c|}{" + m + "}"); } writer.println(" \\\\ \\hline"); writer.print("test"); // for each algo <td>Prec.</td><td>Rec.</td> for (String m : listAlgo) { for (int i = 0; i < fsize; i++) { writer.print(" & "); if (format.charAt(i) == 'p') { writer.print("Prec."); } else if (format.charAt(i) == 'f') { writer.print("FMeas."); } else if (format.charAt(i) == 'o') { writer.print("Over."); } else if (format.charAt(i) == 't') { writer.print("Time"); } else if (format.charAt(i) == 'r') { writer.print("Rec."); } } } writer.println(" \\\\ \\hline"); foundVect = new int[size]; correctVect = new int[size]; timeVect = new long[size]; for (int k = size - 1; k >= 0; k--) { foundVect[k] = 0; correctVect[k] = 0; timeVect[k] = 0; } for (Vector<Object> test : result) { int nexpected = -1; // Print the directory writer.print((String) test.get(0)); // For each record print the values Enumeration<Object> f = test.elements(); f.nextElement(); for (int k = 0; f.hasMoreElements(); k++) { PRecEvaluator eval = (PRecEvaluator) f.nextElement(); if (eval != null) { // iterative H-means computation if (nexpected == -1) { expected += eval.getExpected(); nexpected = 0; } foundVect[k] += eval.getFound(); correctVect[k] += eval.getCorrect(); timeVect[k] += eval.getTime(); for (int i = 0; i < fsize; i++) { writer.print(" & "); if (format.charAt(i) == 'p') { formatter.format("%1.2f", eval.getPrecision()); } else if (format.charAt(i) == 'f') { formatter.format("%1.2f", eval.getFmeasure()); } else if (format.charAt(i) == 'o') { formatter.format("%1.2f", eval.getOverall()); } else if (format.charAt(i) == 't') { if (eval.getTime() == 0) { writer.print("-"); } else { formatter.format("%1.2f", eval.getTime()); } } else if (format.charAt(i) == 'r') { formatter.format("%1.2f", eval.getRecall()); } } } else { writer.print(" & \\multicolumn{" + fsize + "}{c|}{n/a}"); } } writer.println(" \\\\"); } writer.print("H-mean"); // Here we are computing a sheer average. // While in the column results we print NaN when the returned // alignment is empty, // here we use the real values, i.e., add 0 to both correctVect and // foundVect, so this is OK for computing the average. int k = 0; // ??? for (String m : listAlgo) { double precision = (double) correctVect[k] / foundVect[k]; double recall = (double) correctVect[k] / expected; for (int i = 0; i < fsize; i++) { writer.print(" & "); if (format.charAt(i) == 'p') { formatter.format("%1.2f", precision); } else if (format.charAt(i) == 'f') { formatter.format("%1.2f", 2 * precision * recall / (precision + recall)); } else if (format.charAt(i) == 'o') { formatter.format("%1.2f", recall * (2 - (1 / precision))); } else if (format.charAt(i) == 't') { if (timeVect[k] == 0) { writer.print("-"); } else { formatter.format("%1.2f", timeVect[k]); } } else if (format.charAt(i) == 'r') { formatter.format("%1.2f", recall); } } ; k++; } writer.println(" \\\\ \\hline"); writer.println("\\end{tabular}"); writer.println( "\\caption{Plot generated by GroupEval of alignapi \\protect\\footnote{n/a: result alignment not provided or not readable -- NaN: division per zero, likely due to empty alignment.}}"); writer.println("\\end{table}"); writer.println("\\end{document}"); }
From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.CFLibXmlUtil.java
public static String formatXmlString(String str) { final String S_ProcName = "formatXmlString"; if (str == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(CFLibXmlUtil.class, S_ProcName, 1, "str"); }//from ww w .ja v a 2s.c o m StringBuffer buff = new StringBuffer(); char ch; int idx; int len = str.length(); for (idx = 0; idx < len; idx++) { ch = str.charAt(idx); if (Character.isWhitespace(ch)) { buff.append(ch); } else { switch (ch) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '~': case '!': case '#': case '$': case '%': case '^': case '*': case '(': case ')': case '-': case '_': case '+': case '=': case '{': case '}': case '[': case ']': case ':': case ';': case ',': case '.': case '?': case '/': case '\\': case '|': buff.append(ch); break; case '\'': buff.append("'"); break; case '"': buff.append("""); break; case '&': buff.append("&"); break; case '<': buff.append("<"); break; case '>': buff.append(">"); break; default: if (!Character.isValidCodePoint(ch)) { throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(CFLibXmlUtil.class, S_ProcName, "Only valid code points can be formatted, ch is out of range"); } StringBuffer fmtbuff = new StringBuffer(); fmtbuff.append("&#"); Formatter fmt = new Formatter(fmtbuff); fmt.format("%1$d", ch); fmtbuff.append(";"); String tmp = fmtbuff.toString(); buff.append(tmp); fmt.close(); break; } } } String retval = buff.toString(); return (retval); }
From source file:com.itemanalysis.psychometrics.irt.model.Irm4PL.java
/** * A string representaiton of the item parameters. Mainly used for printing and debugging. * * @return a string of item parameters./*from ww w. ja va 2s .c o m*/ */ @Override public String toString() { StringBuilder sb = new StringBuilder(); Formatter f = new Formatter(sb); String name = ""; if (getName() != null) { name = getName().toString(); } f.format("%-18s", name); f.format("%2s", ""); f.format("%-3s", "L4"); f.format("%4s", ""); f.format("% 4.2f", getDiscrimination()); f.format("%1s", ""); f.format("(%4.2f)", getDiscriminationStdError()); f.format("%4s", ""); f.format("% 4.2f", getDifficulty()); f.format("%1s", ""); f.format("(%4.2f)", getDifficultyStdError()); f.format("%4s", ""); f.format("% 4.2f", getGuessing()); f.format("%1s", ""); f.format("(%4.2f)", getGuessingStdError()); f.format("%4s", ""); f.format("% 4.2f", getSlipping()); f.format("%1s", ""); f.format("(%4.2f)", getSlippingStdError()); f.format("%4s", ""); return f.toString(); // // // StringBuilder sb = new StringBuilder(); // Formatter f = new Formatter(sb); // // f.format("%10s", getName().toString());f.format("%2s", ": "); // f.format("%1s", "["); // f.format("% .6f", getDiscrimination()); f.format("%2s", ", "); // f.format("% .6f", getDifficulty()); f.format("%2s", ", "); // f.format("% .6f", getGuessing()); f.format("%2s", ", "); // f.format("% .6f", getSlipping());f.format("%1s", "]"); // f.format("%n"); // f.format("%10s", "");f.format("%2s", ""); // f.format("%1s", "("); // f.format("% .6f", getDiscriminationStdError()); f.format("%2s", ", "); // f.format("% .6f", getDifficultyStdError()); f.format("%2s", ", "); // f.format("% .6f", getGuessingStdError()); f.format("%2s", ", "); // f.format("% .6f", getSlippingStdError());f.format("%1s", ")"); // return f.toString(); }
From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.CFLibXmlUtil.java
public static String formatDate(Calendar cal) { final String S_ProcName = "formatDate"; if (cal == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(CFLibXmlUtil.class, S_ProcName, 1, "cal"); }/*from w ww . j ava 2s .co m*/ StringBuffer buff = new StringBuffer(); Formatter fmt = new Formatter(buff); fmt.format("%1$04d", cal.get(Calendar.YEAR)); buff.append('-'); fmt.format("%1$02d", cal.get(Calendar.MONTH) + 1); buff.append('-'); fmt.format("%1$02d", cal.get(Calendar.DAY_OF_MONTH)); String retval = buff.toString(); fmt.close(); return (retval); }
From source file:io.hops.hopsworks.api.kibana.ProxyServlet.java
/** * Encodes characters in the query or fragment part of the URI. * <p>/*from www.ja v a2 s .c om*/ * <p> * Unfortunately, an incoming URI sometimes has characters disallowed by the * spec. HttpClient * insists that the outgoing proxied request has a valid URI because it uses * Java's {@link URI}. * To be more forgiving, we must escape the problematic characters. See the * URI class for the * spec. * * @param in example: name=value&foo=bar#fragment */ protected static CharSequence encodeUriQuery(CharSequence in) { //Note that I can't simply use URI.java to encode because it will escape //pre-existing escaped things. StringBuilder outBuf = null; Formatter formatter = null; for (int i = 0; i < in.length(); i++) { char c = in.charAt(i); boolean escape = true; if (c < 128) { if (asciiQueryChars.get((int) c)) { escape = false; } } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii escape = false; } if (!escape) { if (outBuf != null) { outBuf.append(c); } } else { //escape if (outBuf == null) { outBuf = new StringBuilder(in.length() + 5 * 3); outBuf.append(in, 0, i); formatter = new Formatter(outBuf); } //leading %, 0 padded, width 2, capital hex formatter.format("%%%02X", (int) c);//TODO } } return outBuf != null ? outBuf : in; }
From source file:com.itemanalysis.psychometrics.irt.model.IrmGPCM.java
/** * Displays the item parameter values and standard errors. * * @return String representation of item parameter values and standard errors. */// www . j a va 2 s. co m public String toString() { StringBuilder sb = new StringBuilder(); Formatter f = new Formatter(sb); String name = getName().toString(); if (getName() != null) { name = getName().toString().substring(0, Math.min(18, name.length())); } else { name = ""; } f.format("%-18s", name); f.format("%2s", ""); f.format("%-3s", "PC1"); f.format("%4s", ""); f.format("% 4.2f", getDiscrimination()); f.format("%1s", ""); f.format("(%4.2f)", getDiscriminationStdError()); f.format("%4s", ""); double[] step = getStepParameters(); double[] stepSe = getStepStdError(); for (int k = 1; k < ncat; k++) { if (k > 1) f.format("%43s", ""); f.format("% 2.2f", step[k]); f.format("%1s", ""); f.format("(%2.2f)", stepSe[k]); if (k < ncatM1) f.format("%n"); } return f.toString(); // // // StringBuilder sb = new StringBuilder(); // Formatter f = new Formatter(sb); // // f.format("%10s", getName().toString());f.format("%2s", ": "); // f.format("%1s", "["); // f.format("% .6f", getDiscrimination()); f.format("%2s", ", "); // for(int k=1;k<ncat;k++){ // f.format("% .6f", step[k]);//Do not print first step parameter because fixed to zero. // if(k<ncatM1) f.format("%2s", ", "); // } // f.format("%1s", "]"); // f.format("%n"); // f.format("%10s", "");f.format("%2s", ""); // f.format("%1s", "("); // f.format("% .6f", getDiscriminationStdError()); f.format("%2s", ", "); // for(int k=1;k<ncat;k++){ // f.format("% .6f", stepStdError[k]);//Do not print first step parameter because fixed to zero. // if(k<ncatM1) f.format("%2s", ", "); // } // f.format("%1s", ")"); // // return f.toString(); }
From source file:com.richwareham.android.logallthethings.Camera2VideoFragment.java
private void startRecordingVideo() { if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) { return;//from w w w .j av a 2s .c om } try { closePreviewSession(); setUpMediaRecorder(); SurfaceTexture texture = mTextureView.getSurfaceTexture(); assert texture != null; texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD); List<Surface> surfaces = new ArrayList<>(); // Set up Surface for the camera preview Surface previewSurface = new Surface(texture); surfaces.add(previewSurface); mPreviewBuilder.addTarget(previewSurface); // Set up Surface for the MediaRecorder mRecorderSurface = mMediaRecorder.getSurface(); surfaces.add(mRecorderSurface); mPreviewBuilder.addTarget(mRecorderSurface); mLogOutputFormatter = new Formatter(new FileOutputStream(mNextLogAbsolutePrefix + ".csv")); mLogOutputFormatter.format("time_since_epoch_ms,sensor_time_ns,sensor_name,sensor_type,index,value\n"); logDatum(System.nanoTime(), "video", "capture_requested", 0, 0); // Start getting updates LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); // Start a capture session // Once the session starts, we can update the UI and start recording mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() { @Override public void onActive(@NonNull CameraCaptureSession cameraCaptureSession) { logDatum(System.nanoTime(), "video", "capture_active", 0, 0); } @Override public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) { mPreviewSession = cameraCaptureSession; updatePreview(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { // UI mButtonVideo.setText(R.string.stop); mIsRecordingVideo = true; // Start recording mMediaRecorder.start(); } }); logDatum(System.nanoTime(), "video", "capture_configured", 0, 0); } @Override public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) { Activity activity = getActivity(); if (null != activity) { Toast.makeText(activity, "Failed", Toast.LENGTH_SHORT).show(); } } }, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.CFLibXmlUtil.java
public static String formatTime(Calendar cal) { final String S_ProcName = "formatTime"; if (cal == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(CFLibXmlUtil.class, S_ProcName, 1, "cal"); }// w w w . ja v a2s . co m StringBuffer buff = new StringBuffer(); Formatter fmt = new Formatter(buff); fmt.format("%1$02d", cal.get(Calendar.HOUR_OF_DAY)); buff.append(':'); fmt.format("%1$02d", cal.get(Calendar.MINUTE)); buff.append(':'); fmt.format("%1$02d", cal.get(Calendar.SECOND)); String retval = buff.toString(); fmt.close(); return (retval); }