List of usage examples for java.io Writer flush
public abstract void flush() throws IOException;
From source file:com.openkm.util.impexp.RepositoryExporter.java
/** * Export mail from OpenKM repository to filesystem. *///from www .ja v a 2 s .co m public static ImpExpStats exportMail(String token, String mailPath, String destPath, boolean metadata, Writer out, InfoDecorator deco) throws PathNotFoundException, RepositoryException, DatabaseException, IOException, AccessDeniedException, ParseException, NoSuchGroupException, MessagingException { MailModule mm = ModuleManager.getMailModule(); MetadataAdapter ma = MetadataAdapter.getInstance(token); Mail mailChild = mm.getProperties(token, mailPath); Gson gson = new Gson(); ImpExpStats stats = new ImpExpStats(); MimeMessage msg = MailUtils.create(token, mailChild); FileOutputStream fos = new FileOutputStream(destPath); msg.writeTo(fos); IOUtils.closeQuietly(fos); FileLogger.info(BASE_NAME, "Created document ''{0}''", mailChild.getPath()); // Metadata if (metadata) { MailMetadata mmd = ma.getMetadata(mailChild); String json = gson.toJson(mmd); fos = new FileOutputStream(destPath + Config.EXPORT_METADATA_EXT); IOUtils.write(json, fos); IOUtils.closeQuietly(fos); } if (out != null) { out.write(deco.print(mailChild.getPath(), mailChild.getSize(), null)); out.flush(); } // Stats stats.setSize(stats.getSize() + mailChild.getSize()); stats.setMails(stats.getMails() + 1); return stats; }
From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java
/** * Test that we can use a Java system property to configure the protocol * version on the agent.// w w w .j a va 2s . co m * * @throws Exception * When the test failed. */ @Test public void testSetTo11() throws Exception { System.setProperty(ZabbixAgent.PROTOCOL_PROPERTY, "1.1"); assertEquals("1.1", System.getProperty(ZabbixAgent.PROTOCOL_PROPERTY)); final Agent agent = new ZabbixAgent(); // give the agent some time to open the port Thread.sleep(100); final Socket socket = new Socket(InetAddress.getLocalHost(), ZabbixAgent.DEFAULT_PORT); final Writer out = new OutputStreamWriter(socket.getOutputStream()); out.write("system.property[java.version]\n"); out.flush(); final InputStream in = socket.getInputStream(); final byte[] buffer = new byte[1024]; in.read(buffer); final String version = System.getProperty("java.version"); assertEquals(version.charAt(0), buffer[0]); assertEquals(version.charAt(1), buffer[1]); assertEquals(version.charAt(2), buffer[2]); assertEquals(version.charAt(3), buffer[3]); // we'll take the rest for granted... socket.close(); agent.stop(); }
From source file:net.longfalcon.newsj.Nzb.java
private void _doWriteNZBforRelease(Release release, Directory nzbBaseDir) throws IOException, JAXBException { long releaseId = release.getId(); String releaseGuid = release.getGuid(); String releaseName = release.getName(); long startTime = System.currentTimeMillis(); Category category = release.getCategory(); String categoryName = null;//from w w w.j a v a 2s .c o m if (category != null) { categoryName = category.getTitle(); } net.longfalcon.newsj.xml.Nzb nzbRoot = new net.longfalcon.newsj.xml.Nzb(); nzbRoot.setXmlns(_XMLNS); Head head = new Head(); List<Meta> metaElements = head.getMeta(); Meta categoryMeta = new Meta(); categoryMeta.setType("category"); categoryMeta.setvalue(StringEscapeUtils.escapeXml11(categoryName)); Meta nameMeta = new Meta(); nameMeta.setType("name"); nameMeta.setvalue(StringEscapeUtils.escapeXml11(releaseName)); metaElements.add(categoryMeta); metaElements.add(nameMeta); nzbRoot.setHead(head); List<File> files = nzbRoot.getFile(); List<Binary> binaries = binaryDAO.findBinariesByReleaseId(releaseId); for (Binary binary : binaries) { File fileElement = new File(); fileElement.setPoster(StringEscapeUtils.escapeXml11(binary.getFromName())); fileElement.setDate(String.valueOf(binary.getDate().getTime())); String subjectString = String.format("%s (1/%s)", StringEscapeUtils.escapeXml11(binary.getName()), binary.getTotalParts()); fileElement.setSubject(subjectString); Groups groupsElement = new Groups(); List<Group> groups = groupsElement.getGroup(); net.longfalcon.newsj.model.Group group = groupDAO.findGroupByGroupId(binary.getGroupId()); Group groupElement = new Group(); groupElement.setvalue(group.getName()); groups.add(groupElement); // TODO: add XRef groups fileElement.setGroups(groupsElement); Segments segmentsElement = new Segments(); List<Segment> segments = segmentsElement.getSegment(); List<Object[]> messageIdSizePartNos = partDAO .findDistinctMessageIdSizeAndPartNumberByBinaryId(binary.getId()); for (Object[] messageIdSizePartNo : messageIdSizePartNos) { // messageIdSizePartNo is {String,Long,Integer} Segment segment = new Segment(); segment.setBytes(String.valueOf(messageIdSizePartNo[1])); segment.setNumber(String.valueOf(messageIdSizePartNo[2])); segment.setvalue(String.valueOf(messageIdSizePartNo[0])); segments.add(segment); } fileElement.setSegments(segmentsElement); files.add(fileElement); } long startFileWriteTime = System.currentTimeMillis(); FsFile fileHandle = getNzbFileHandle(release, nzbBaseDir); Writer writer = new OutputStreamWriter(fileHandle.getOutputStream(), Charset.forName("UTF-8")); getMarshaller().marshal(nzbRoot, writer); writer.write(String.format("<!-- generated by NewsJ %s -->", config.getReleaseVersion())); writer.flush(); writer.close(); Period totalTimePeriod = new Period(startTime, System.currentTimeMillis()); Period buildTimePeriod = new Period(startTime, startFileWriteTime); Period writeTimePeriod = new Period(startFileWriteTime, System.currentTimeMillis()); _log.info(String.format("Wrote NZB for %s in %s;\n build time: %s write time: %s", releaseName, _periodFormatter.print(totalTimePeriod), _periodFormatter.print(buildTimePeriod), _periodFormatter.print(writeTimePeriod))); }
From source file:it.jugpadova.controllers.EventController.java
@RequestMapping public ModelAndView json(HttpServletRequest req, HttpServletResponse res) throws Exception { try {// ww w . java 2 s . co m EventSearch eventSearch = buildEventSearch(req); List<Event> events = eventBo.search(eventSearch); String json = feedsBo.buildJson(events, Utilities.getBaseUrl(req), true); // flush it in the res res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0, no-store"); res.setHeader("Pragma", "public, no-cache"); res.setDateHeader("Expires", 0); res.setContentType("application/json"); res.setContentLength(json.getBytes().length); res.setCharacterEncoding("UTF-8"); ServletOutputStream resOutputStream = res.getOutputStream(); Writer writer = new OutputStreamWriter(resOutputStream, "UTF-8"); writer.write(json); writer.flush(); writer.close(); } catch (Exception exception) { logger.error("Error producing JSON", exception); throw exception; } return null; }
From source file:com.joliciel.csvLearner.features.BestFeatureFinder.java
public void writeFirstLine(Writer writer, int numFeatures) { try {//from w ww. j a va2 s.c o m writer.append(CSVFormatter.format("outcome") + ","); writer.append(CSVFormatter.format("total entropy") + ","); for (int i = 1; i <= numFeatures; i++) { writer.append(CSVFormatter.format(i) + ","); writer.append("gain,"); } writer.append("\n"); writer.flush(); } catch (IOException ioe) { throw new RuntimeException(ioe); } }
From source file:org.kurento.test.sanity.KurentoJsBase.java
private void createHtmlPages() { try {//from w ww . j a v a 2 s . c om final String outputFolder = new ClassPathResource("static").getFile().getAbsolutePath() + File.separator; Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); cfg.setClassForTemplateLoading(KurentoJsBase.class, "/templates/"); Template template = cfg.getTemplate("kurento-client.html.ftl"); Map<String, Object> data = new HashMap<String, Object>(); data.put("kurentoUrl", kurentoUrl); for (String lib : kurentoLibs) { Writer writer = new FileWriter(new File(outputFolder + lib + ".html")); data.put("kurentoLib", lib); if (lib.contains("utils")) { data.put("kurentoObject", "kurentoUtils"); } else { data.put("kurentoObject", "kurentoClient"); } template.process(data, writer); writer.flush(); writer.close(); } } catch (Exception e) { Assert.fail("Exception creating templates: " + e.getMessage()); } }
From source file:com.laxser.blitz.web.portal.impl.PipeImpl.java
private synchronized void doStart(Writer writer) throws IOException { if (this.out != null) { throw new IllegalStateException("has been started."); }//www .ja v a2s . c o m this.out = writer; if (logger.isDebugEnabled()) { logger.debug("start pipe " + getInvocation().getRequestPath().getUri()); } writer.flush(); latch = new CountDownLatch(windows.size()); state = 1; if (blocking != null) { for (Window window : blocking) { doFire(window); } blocking = null; } }
From source file:it.jugpadova.controllers.EventController.java
@RequestMapping public ModelAndView badge(HttpServletRequest req, HttpServletResponse res) throws Exception { try {//from w w w . jav a2 s . c om String locale = req.getParameter("lang"); if (StringUtils.isBlank(locale)) { locale = (String) req.getAttribute("lang"); } if (StringUtils.isBlank(locale)) { locale = "en"; } java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.DEFAULT, new Locale(locale)); String baseUrl = Utilities.getBaseUrl(req); EventSearch eventSearch = buildEventSearch(req); List<Event> events = eventBo.search(eventSearch); boolean showJUGName = Boolean.parseBoolean(req.getParameter("jeb_showJUGName")); boolean showCountry = Boolean.parseBoolean(req.getParameter("jeb_showCountry")); boolean showDescription = Boolean.parseBoolean(req.getParameter("jeb_showDescription")); boolean showParticipants = Boolean.parseBoolean(req.getParameter("jeb_showParticipants")); String badgeStyle = req.getParameter("jeb_style"); String result = eventBo.getBadgeCode(eventBo.getBadgeHtmlCode(events, dateFormat, baseUrl, showJUGName, showCountry, showDescription, showParticipants, badgeStyle, locale)); // flush it in the res res.setHeader("Cache-Control", "no-store"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); res.setContentType("text/javascript"); ServletOutputStream resOutputStream = res.getOutputStream(); Writer writer = new OutputStreamWriter(resOutputStream, "UTF-8"); writer.write(result); writer.flush(); writer.close(); } catch (Exception exception) { logger.error("Error producing badge", exception); throw exception; } return null; }
From source file:net.cit.tetrad.resource.MainResource.java
/** * sharding ?/*from w ww . j a va2s . c o m*/ * @param request * @param response * @param dto * @throws Exception */ @SuppressWarnings("unchecked") @RequestMapping("/shadingCheck.do") public void shadingCheck(HttpServletRequest request, HttpServletResponse response, CommonDto dto) throws Exception { log.debug("start - shadingCheck()"); try { List<ServerStatus> serverStatusList = daoForMongo.readServerStatus(PROCESS_MONGOS); List<Object> readMongolocks = new ArrayList<Object>(); boolean isExistShading = false; if (serverStatusList.size() != 0) { for (ServerStatus serverStatus : serverStatusList) { readMongolocks = comandService.collectionCommand(serverStatus.getDeviceCode(), "locks"); for (Object locksObj : readMongolocks) { Map<String, Object> locks = (Map<String, Object>) locksObj; if (locks.get("_id").equals("balancer") && locks.get("state").equals(2)) { //_id balancer? state 2 ? sharding isExistShading = true; break; } } if (isExistShading) break; } } String result = "false"; if (isExistShading) result = "true"; Writer writer = setResponse(response).getWriter(); writer.write(result); writer.flush(); } catch (Exception e) { log.error(e, e); } log.debug("end - shadingCheck()"); }
From source file:com.xhsoft.framework.common.utils.ClassUtil.java
/** * @param writer/*w ww . j a v a 2 s . c o m*/ * @param type * @param expression * @author lizj */ public static void write(final java.io.Writer writer, final Class<?> type, final String expression) { String name = null; String text = null; Method[] methods = type.getMethods(); try { for (int i = 0; i < methods.length; i++) { name = methods[i].getName(); if (name.startsWith("get") && methods[i].getParameterTypes().length < 1) { name = name.substring(3); name = java.beans.Introspector.decapitalize(name); text = expression; text = StringUtil.replace(text, "${name}", name); text = StringUtil.replace(text, "${endl}", "\r\n"); writer.write(text); } } writer.flush(); } catch (IOException e) { e.printStackTrace(); } }