List of usage examples for java.io Writer append
public Writer append(char c) throws IOException
From source file:com.joliciel.csvLearner.CSVEventListWriter.java
public void writeFile(GenericEvents events) { try {/*from www .ja v a 2 s .c om*/ LOG.debug("writeFile: " + file.getName()); file.delete(); file.createNewFile(); if (file.getName().endsWith(".zip")) isZip = true; Writer writer = null; ZipOutputStream zos = null; try { if (isZip) { zos = new ZipOutputStream(new FileOutputStream(file, false)); writer = new BufferedWriter(new OutputStreamWriter(zos)); } else { writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF8")); } Set<String> features = new TreeSet<String>(); if (!filePerEvent) { if (isZip) { zos.putNextEntry(new ZipEntry( file.getName().substring(0, file.getName().lastIndexOf('.')) + ".csv")); } for (GenericEvent event : events) { if (LOG.isTraceEnabled()) LOG.trace("Writing event: " + event.getIdentifier()); for (String feature : event.getFeatures()) { int classIndex = feature.indexOf(CSVLearner.NOMINAL_MARKER); if (classIndex < 0 || denominalise) features.add(feature); else features.add(feature.substring(0, classIndex)); } } writer.append("ID,"); if (includeOutcomes) writer.append("outcome,"); for (String feature : features) { writer.append(CSVFormatter.format(feature) + ","); } writer.append("\n"); writer.flush(); } for (GenericEvent event : events) { if (filePerEvent) { features = new TreeSet<String>(); for (String feature : event.getFeatures()) { int classIndex = feature.indexOf(CSVLearner.NOMINAL_MARKER); if (classIndex < 0 || denominalise) features.add(feature); else features.add(feature.substring(0, classIndex)); } if (isZip) zos.putNextEntry(new ZipEntry(event.getIdentifier() + ".csv")); writer.append("ID,"); if (includeOutcomes) writer.append("outcome,"); for (String feature : features) { writer.append(CSVFormatter.format(feature) + ","); } writer.append("\n"); writer.flush(); } writer.append(CSVFormatter.format(identifierPrefix + event.getIdentifier()) + ","); if (includeOutcomes) writer.append(CSVFormatter.format(event.getOutcome()) + ","); for (String feature : features) { Integer featureIndexObj = event.getFeatureIndex(feature); int featureIndex = featureIndexObj == null ? -1 : featureIndexObj.intValue(); if (featureIndex < 0) { writer.append(missingValueString + ","); } else { String eventFeature = event.getFeatures().get(featureIndex); if (!eventFeature.equals(feature)) { int classIndex = eventFeature.indexOf(CSVLearner.NOMINAL_MARKER); String clazz = eventFeature .substring(classIndex + CSVLearner.NOMINAL_MARKER.length()); writer.append(CSVFormatter.format(clazz) + ","); } else { double value = event.getWeights().get(featureIndex); writer.append(CSVFormatter.format(value) + ","); } } } writer.append("\n"); writer.flush(); if (filePerEvent && isZip) zos.closeEntry(); } if (!filePerEvent && isZip) zos.closeEntry(); } finally { if (zos != null) { zos.flush(); zos.close(); } if (writer != null) { writer.flush(); writer.close(); } } } catch (IOException ioe) { throw new RuntimeException(ioe); } }
From source file:ch.algotrader.starter.GoogleDailyDownloader.java
private void retrieve(HttpClient httpclient, String symbol, String startDate, String endDate, String exchange) throws IOException, HttpException, FileNotFoundException, ParseException { GetMethod fileGet = new GetMethod("https://www.google.com/finance/historical?q=" + exchange + ":" + symbol + "&output=csv&startdate=" + startDate + (endDate == null ? "" : "&endDate=" + endDate)); fileGet.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); try {/*from ww w . j ava2 s .co m*/ int status = httpclient.executeMethod(fileGet); if (status == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader( new InputStreamReader(fileGet.getResponseBodyAsStream())); File parent = new File("files" + File.separator + "google"); if (!parent.exists()) { FileUtils.forceMkdir(parent); } Writer writer = new OutputStreamWriter(new FileOutputStream(new File(parent, symbol + ".csv"))); try { reader.readLine(); String line; List<String> lines = new ArrayList<String>(); while ((line = reader.readLine()) != null) { String tokens[] = line.split(","); Date dateTime = fileFormat.parse(tokens[0]); StringBuffer buffer = new StringBuffer(); buffer.append( DateTimePatterns.LOCAL_DATE_TIME.format(DateTimeLegacy.toLocalDateTime(dateTime))); buffer.append(","); buffer.append(tokens[1].equals("-") ? "" : tokens[1]); buffer.append(","); buffer.append(tokens[2].equals("-") ? "" : tokens[2]); buffer.append(","); buffer.append(tokens[3].equals("-") ? "" : tokens[3]); buffer.append(","); buffer.append(tokens[4].equals("-") ? "" : tokens[4]); buffer.append(","); buffer.append(tokens[5]); buffer.append("\n"); lines.add(buffer.toString()); } writer.write("dateTime,open,high,low,close,vol\n"); // write in reverse order for (int i = lines.size() - 1; i > 0; i--) { writer.append(lines.get(i)); } } finally { reader.close(); writer.close(); } } } finally { fileGet.releaseConnection(); } }
From source file:azkaban.webapp.servlet.ProjectManagerServlet.java
private void handleCreate(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException { String projectName = hasParam(req, "name") ? getParam(req, "name") : null; String projectDescription = hasParam(req, "description") ? getParam(req, "description") : null; logger.info("Create project " + projectName); User user = session.getUser();//from w w w .j a v a 2s . c om String status = null; String action = null; String message = null; HashMap<String, Object> params = null; if (lockdownCreateProjects && !hasPermissionToCreateProject(user)) { message = "User " + user.getUserId() + " doesn't have permission to create projects."; logger.info(message); status = "error"; } else { try { projectManager.createProject(projectName, projectDescription, user); status = "success"; action = "redirect"; String redirect = "manager?project=" + projectName; params = new HashMap<String, Object>(); params.put("path", redirect); } catch (ProjectManagerException e) { message = e.getMessage(); status = "error"; } } String response = createJsonResponse(status, message, action, params); try { Writer write = resp.getWriter(); write.append(response); write.flush(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.redhat.rhn.frontend.taglibs.ListDisplayTag.java
private void renderSetButtons(Writer out) throws IOException { StringBuilder buf = new StringBuilder(); if (set != null) { if (showSetButtons) { buf.append("<span class=\"spacewalk-list-selection-btns\">"); buf.append(//from w ww . j a v a 2s. c o m addButtonTo(buf, RequestContext.DISPATCH, UPDATE_LIST_KEY, "update_list_key_id").render()); buf.append(" "); buf.append(addButtonTo(buf, RequestContext.DISPATCH, SELECT_ALL_KEY).render()); if (numItemsChecked > 0) { buf.append(" "); buf.append(addButtonTo(buf, RequestContext.DISPATCH, UNSELECT_ALL_KEY).render()); } buf.append("</span>"); } } out.append(buf.toString()); }
From source file:annis.visualizers.iframe.partitur.PartiturVisualizer.java
@Override public void writeOutput(VisualizerInput input, Writer writer) { try {/* w w w . j ava 2 s. c om*/ nodes = input.getResult().getGraph().getNodes(); token = input.getResult().getGraph().getTokens(); // get partitur PartiturParser partitur = new PartiturParser(input.getResult().getGraph(), input.getNamespace()); // check right to left boolean isRTL = checkRTL(input.getResult().getTokenList()); List<String> tierNames = new LinkedList<String>(partitur.getKnownTiers()); Collections.sort(tierNames); // get keys that are allowed to select LinkedHashSet<String> keys = new LinkedHashSet<String>(); String mapping = input.getMappings().getProperty("annos"); if (mapping == null) { // default to the alphabetical order keys.addAll(partitur.getNameslist()); } else { String[] splitted = mapping.split(","); for (int k = 0; k < splitted.length; k++) { String s = splitted[k].trim(); if (partitur.getNameslist().contains(s)) { keys.add(s); } } } writer.append( "<!DOCTYPE html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"); writer.append("<link href=\"" + input.getResourcePath("jbar.css") + "\" rel=\"stylesheet\" type=\"text/css\" >"); writer.append("<link href=\"" + input.getResourcePath("jquery.tooltip.css") + "\" rel=\"stylesheet\" type=\"text/css\" >"); writer.append("<link href=\"" + input.getResourcePath("jquery.noty.css") + "\" rel=\"stylesheet\" type=\"text/css\" >"); writer.append("<link href=\"" + input.getResourcePath("partitur.css") + "\" rel=\"stylesheet\" type=\"text/css\" >"); writer.append("<script src=\"" + input.getResourcePath("jquery-1.7.1.min.js") + "\"></script>"); writer.append("<script src=\"" + input.getResourcePath("jquery.jbar.js") + "\"></script>"); writer.append("<script src=\"" + input.getResourcePath("jquery.tooltip.min.js") + "\"></script>"); writer.append("<script src=\"" + input.getResourcePath("jquery.noty.js") + "\"></script>"); writer.append("<script>"); writer.append(convertToJavacSriptArray(new LinkedList<String>())); writer.append("\nvar levelNames = ["); int i = 0; for (String levelName : tierNames) { if (keys.contains(levelName)) { writer.append((i++ > 0 ? ", " : "") + "\"" + levelName + "\""); } } writer.append("];\n</script>"); writer.append("<script type=\"text/javascript\" src=\"" + input.getResourcePath("PartiturVisualizer.js") + "\"></script>"); writer.append("</head>"); writer.append("<body>\n"); writer.append("<ul id=\"toolbar\"></ul>"); writer.append("<div id=\"partiture\">"); if (isRTL) { writer.append("<table class=\"partitur_table\" dir=\"rtl\">\n"); } else { writer.append("<table class=\"partitur_table\")\">\n"); } for (String tier : keys) { List<String> indexlist = new ArrayList<String>(); for (List<PartiturParser.ResultElement> span : partitur.getResultlist()) { for (PartiturParser.ResultElement strr : span) { if (strr.getName().equals(tier) && !indexlist.contains(strr.getId())) { indexlist.add(strr.getId()); } } } String[] currentarray; //Saves annotation-ids of the current row while (!indexlist.isEmpty()) { //Create Rows until all Annotations fit in List<String> currentdontuselist = new LinkedList<String>(); //Lists all Annotations that should not be added to the current row writer.append("<tr class=\"level_" + tier + "\"><th>" + tier + "</th>"); //new row currentarray = new String[partitur.getResultlist().size()]; for (int iterator3 = 0; iterator3 < partitur.getResultlist().size(); iterator3++) { currentarray[iterator3] = null; } int spanCounter = 0; for (List<PartiturParser.ResultElement> span : partitur.getResultlist()) { //for each Token for (PartiturParser.ResultElement annotationelement : span) { // for each Annotation annotationelement of that Token if (indexlist.contains(annotationelement.getId()) && !currentdontuselist.contains(annotationelement.getId())) { boolean neu = false; //Should the Annotation be added? if (currentarray[spanCounter] == null) { indexlist.remove(annotationelement.getId()); currentarray[spanCounter] = annotationelement.getId(); neu = true; } //get all other annotationelement.id (earlier Ids => dontuselist) int span2Counter = 0; for (List<PartiturParser.ResultElement> span2 : partitur.getResultlist()) { for (PartiturParser.ResultElement strr2 : span2) { if (strr2.getId().equals(annotationelement.getId()) && neu) //{ { if (currentarray[span2Counter] == null) { currentarray[span2Counter] = annotationelement.getId(); } } if (span2Counter <= spanCounter && !currentdontuselist.contains(strr2.getId())) { currentdontuselist.add(strr2.getId()); } } span2Counter++; } //break; //Not needed? } } spanCounter++; } //Write Row int length = 1; for (int iterator5 = 0; iterator5 < currentarray.length; iterator5 += length) { StringBuffer tokenIdsArray = new StringBuffer(); StringBuffer eventIdsArray = new StringBuffer(); boolean unused = true; length = 1; if (currentarray[iterator5] == null) { //empty entry writer.append("<td></td>"); } else { PartiturParser.ResultElement element = null; HashSet<Integer> common = new HashSet<Integer>(); boolean found = false; int outputSpanCounter = 0; for (List<PartiturParser.ResultElement> outputSpan : partitur.getResultlist()) { for (PartiturParser.ResultElement strr : outputSpan) { if (strr.getId().equals(currentarray[iterator5])) { if (!found) { element = strr; } if (!common.contains(outputSpanCounter)) { common.add(outputSpanCounter); } found = true; if (unused) { tokenIdsArray.append("" + strr.getId() + "_" + outputSpanCounter); eventIdsArray .append(tier + "_" + strr.getId() + "_" + outputSpanCounter); unused = false; } else { tokenIdsArray.append("," + strr.getId() + "_" + outputSpanCounter); eventIdsArray.append( "," + tier + "_" + strr.getId() + "_" + outputSpanCounter); } } } outputSpanCounter++; } for (int iterator7 = iterator5 + 1; iterator7 < currentarray.length; iterator7++) { if (common.contains(iterator7)) { length++; } else { break; } } for (int iterator8 = 0; iterator8 < currentarray.length; iterator8++) { if (common.contains(iterator8)) { Long id = ((PartiturParser.Token) partitur.getToken().toArray()[iterator8]) .getId(); if (unused) { tokenIdsArray.append("" + id); eventIdsArray.append(tier + "_" + id); unused = false; } else { tokenIdsArray.append("," + id); eventIdsArray.append("," + tier + "_" + id); } } } String color = "black"; if (input.getMarkableExactMap().containsKey("" + element.getNodeId())) { color = input.getMarkableExactMap().get("" + element.getNodeId()); } if (found) { writer.append("<td class=\"single_event\" " + "id=\"event_" + tier + "_" + element.getId() + "_" + iterator5 + "\" " + "style=\"color:" + color + ";\" " + "colspan=" + length + " " + "annis:tokenIds=\"" + tokenIdsArray + "\" " + "annis:eventIds=\"" + eventIdsArray + "\" " + "title=\"" + partitur.namespaceForTier(tier) + ":" + tier + " = " + StringEscapeUtils.escapeXml(element.getValue()) + "\" " //tier =tier, event.getValue()= element.name + "onMouseOver=\"toggleAnnotation(this, true);\" " + "onMouseOut=\"toggleAnnotation(this, false);\" " + addTimeAttribute(element.getNodeId()) + ">" + element.getValue() + "</td>"); } else { writer.append("<td class=\"single_event\" >error</td>"); } } } writer.append("</tr>"); //finish row } } // add token itself writer.append("<tr><th>tok</th>"); for (PartiturParser.Token token : partitur.getToken()) { String color = "black"; if (input.getMarkableExactMap().containsKey("" + token.getId())) { color = input.getMarkableExactMap().get("" + token.getId()); } writer.append("<td class=\"tok\" style=\"color:" + color + ";\" " + "id=\"token_" + token.getId() + "\" " + ">" + token.getValue() + "</td>"); } writer.append("</tr>"); writer.append("</table>\n"); writer.append("</div>\n"); writer.append("</body></html>"); } catch (Exception ex) { log.error(null, ex); try { String annisLine = ""; for (int i = 0; i < ex.getStackTrace().length; i++) { if (ex.getStackTrace()[i].getClassName().startsWith("annis.")) { annisLine = ex.getStackTrace()[i].toString(); } } writer.append("<html><body>Error occured (" + ex.getClass().getName() + "): " + ex.getLocalizedMessage() + "<br/>" + annisLine + "</body></html>"); } catch (IOException ex1) { log.error(null, ex1); } } }
From source file:ca.uhn.hl7v2.testpanel.model.msg.Hl7V2MessageCollection.java
/** * Write the messages to an output stream *///from w ww .j ava 2s.c o m public void writeToFile(Writer theWriter, boolean theSelectedSaveStripComments, LineEndingsEnum theSelectedLineEndings) throws IOException { String toWrite = mySourceMessage; if (theSelectedSaveStripComments) { switch (myEncoding) { case ER_7: Pattern p = Pattern.compile("(^|\\r)\\s*#[^\\r]*"); Matcher m = p.matcher(toWrite); toWrite = m.replaceAll("").trim() + "\r"; p = Pattern.compile("\\r\\s*\\r"); m = p.matcher(toWrite); toWrite = m.replaceAll("\r"); break; } } toWrite = fixLineEndings(toWrite, theSelectedLineEndings); theWriter.append(toWrite); }
From source file:com.dell.asm.asmcore.asmmanager.app.AsmManagerApp.java
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) *///from w w w . j ava 2 s . c o m protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final Writer writer = response.getWriter(); writer.append("<html>"); writer.append("<body>"); writer.append("<center><h1>AsmManagerApp Servlet</h1></center>"); writer.append("<center><a href=\"DiscoveryRequest/?_wadl\">Discovery Service WADL</a></center>"); writer.append("<center><a href=\"credential/?_wadl\">Credential Service WADL</a></center>"); writer.append("<center><a href=\"DeviceConfigureRequest/?_wadl\">Configure Service WADL</a></center>"); writer.append("<center><a href=\"ManagedDevice/?_wadl\">Device Service WADL</a></center>"); writer.append( "<center><a href=\"InfrastructureTemplate/?_wadl\">Infrastructure Template Service WADL</a></center>"); writer.append("<center><a href=\"ServerTemplate/?_wadl\">Server Template Service WADL</a></center>"); writer.append("<center><a href=\"ServerProfile/?_wadl\">Server Profile Service WADL</a></center>"); writer.append("<center><a href=\"PuppetModule/?_wadl\">Puppet Module Service WADL</a></center>"); writer.append("<center><a href=\"ServiceTemplate/?_wadl\">Service Template Service WADL</a></center>"); writer.append("<center><a href=\"Deployment/?_wadl\">Deployment Service WADL</a></center>"); writer.append("<center><a href=\"PuppetDevice/?_wadl\">Puppet Device Service WADL</a></center>"); writer.append("<center><img src=\"images/giraffe5.png\" height=\"800\"; width=\"425\"></center>"); writer.append("</body>"); writer.append("</html>"); }
From source file:org.apache.hadoop.hbase.mob.compactions.PartitionedMobCompactor.java
/** * Compacts a partition of selected small mob files and all the del files in a batch. * @param request The compaction request. * @param partition A compaction partition. * @param table The current table.//www. j a v a 2 s. c o m * @param filesToCompact The files to be compacted. * @param batch The number of mob files to be compacted in a batch. * @param bulkloadPathOfPartition The directory where the bulkload column of the current * partition is saved. * @param bulkloadColumnPath The directory where the bulkload files of current partition * are saved. * @param newFiles The paths of new mob files after compactions. * @throws IOException */ private void compactMobFilesInBatch(PartitionedMobCompactionRequest request, CompactionPartition partition, Table table, List<StoreFile> filesToCompact, int batch, Path bulkloadPathOfPartition, Path bulkloadColumnPath, List<Path> newFiles) throws IOException { // open scanner to the selected mob files and del files. StoreScanner scanner = createScanner(filesToCompact, ScanType.COMPACT_DROP_DELETES); // the mob files to be compacted, not include the del files. List<StoreFile> mobFilesToCompact = filesToCompact.subList(0, batch); // Pair(maxSeqId, cellsCount) Pair<Long, Long> fileInfo = getFileInfo(mobFilesToCompact); // open writers for the mob files and new ref store files. Writer writer = null; Writer refFileWriter = null; Path filePath = null; Path refFilePath = null; long mobCells = 0; try { writer = MobUtils.createWriter(conf, fs, column, partition.getPartitionId().getDate(), tempPath, Long.MAX_VALUE, column.getCompactionCompression(), partition.getPartitionId().getStartKey(), compactionCacheConfig, cryptoContext); filePath = writer.getPath(); byte[] fileName = Bytes.toBytes(filePath.getName()); // create a temp file and open a writer for it in the bulkloadPath refFileWriter = MobUtils.createRefFileWriter(conf, fs, column, bulkloadColumnPath, fileInfo.getSecond().longValue(), compactionCacheConfig, cryptoContext); refFilePath = refFileWriter.getPath(); List<Cell> cells = new ArrayList<Cell>(); boolean hasMore = false; ScannerContext scannerContext = ScannerContext.newBuilder().setBatchLimit(compactionKVMax).build(); do { hasMore = scanner.next(cells, scannerContext); for (Cell cell : cells) { // write the mob cell to the mob file. writer.append(cell); // write the new reference cell to the store file. KeyValue reference = MobUtils.createMobRefKeyValue(cell, fileName, tableNameTag); refFileWriter.append(reference); mobCells++; } cells.clear(); } while (hasMore); } finally { // close the scanner. scanner.close(); // append metadata to the mob file, and close the mob file writer. closeMobFileWriter(writer, fileInfo.getFirst(), mobCells); // append metadata and bulkload info to the ref mob file, and close the writer. closeRefFileWriter(refFileWriter, fileInfo.getFirst(), request.selectionTime); } if (mobCells > 0) { // commit mob file MobUtils.commitFile(conf, fs, filePath, mobFamilyDir, compactionCacheConfig); // bulkload the ref file bulkloadRefFile(table, bulkloadPathOfPartition, filePath.getName()); newFiles.add(new Path(mobFamilyDir, filePath.getName())); } else { // remove the new files // the mob file is empty, delete it instead of committing. deletePath(filePath); // the ref file is empty, delete it instead of committing. deletePath(refFilePath); } // archive the old mob files, do not archive the del files. try { closeStoreFileReaders(mobFilesToCompact); MobUtils.removeMobFiles(conf, fs, tableName, mobTableDir, column.getName(), mobFilesToCompact); } catch (IOException e) { LOG.error("Failed to archive the files " + mobFilesToCompact, e); } }
From source file:com.redhat.rhn.frontend.taglibs.ListDisplayTagBase.java
protected void renderFilterBox(Writer out) throws IOException { LocalizationService ls = LocalizationService.getInstance(); HtmlTag tag = new HtmlTag("div"); tag.setAttribute("class", "spacewalk-filter-input input-group"); StringBuilder buf = new StringBuilder(); HtmlTag input = new HtmlTag("input"); input.setAttribute("type", "text"); input.setAttribute("class", "form-control"); input.setAttribute("name", RequestContext.FILTER_STRING); input.setAttribute("value", pageList.getFilterData()); String placeHolder = StringEscapeUtils .escapeHtml(ls.getMessage("message.filterby", ls.getMessage(filterBy))); input.setAttribute("placeholder", placeHolder); buf.append(input.render());/*from w ww. j ava 2 s.c o m*/ input = new HtmlTag("input"); input.setAttribute("type", "hidden"); input.setAttribute("name", RequestContext.PREVIOUS_FILTER_STRING); input.setAttribute("value", pageList.getFilterData()); buf.append(input.render()); HtmlTag btnSpan = new HtmlTag("span"); btnSpan.setAttribute("class", "input-group-btn"); HtmlTag btn = new HtmlTag("button"); btn.setAttribute("class", "btn btn-default"); btn.setAttribute("type", "submit"); btn.setAttribute("name", FILTER_DISPATCH); btn.setAttribute("value", ls.getMessage(RequestContext.FILTER_KEY)); IconTag icon = new IconTag("item-search"); btn.addBody(icon.render()); btnSpan.addBody(btn); buf.append(btnSpan.render()); tag.addBody(buf.toString()); out.append(tag.render()); }