java.io.OutputStreamWriter Java Examples

The following examples show how to use java.io.OutputStreamWriter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RawQueue.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Save a payload to the log file
 * @param frame
 * @param log
 * @throws IOException
 */
protected void save(Frame frame, String log) throws IOException {
	if (!Config.logFileDirectory.equalsIgnoreCase("")) {
		log = Config.logFileDirectory + File.separator + log;
	} 
	synchronized(this) { // make sure we have exlusive access to the file on disk, otherwise a removed frame can clash with this
		File aFile = new File(log );
		if(!aFile.exists()){
			aFile.createNewFile();
		}
		//Log.println("Saving: " + log);
		//use buffering and append to the existing file
		FileOutputStream dis = new FileOutputStream(log, true);
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(dis));

		try {
			frame.save(writer);
		} finally {
			writer.flush();
			writer.close();
		}

		writer.close();
		dis.close();
	}
}
 
Example #2
Source File: SentryEnvelopeItem.java    From sentry-android with MIT License 6 votes vote down vote up
public static @NotNull SentryEnvelopeItem fromSession(
    final @NotNull ISerializer serializer, final @NotNull Session session) throws IOException {
  Objects.requireNonNull(serializer, "ISerializer is required.");
  Objects.requireNonNull(session, "Session is required.");

  final CachedItem cachedItem =
      new CachedItem(
          () -> {
            try (final ByteArrayOutputStream stream = new ByteArrayOutputStream();
                final Writer writer = new BufferedWriter(new OutputStreamWriter(stream, UTF_8))) {
              serializer.serialize(session, writer);
              return stream.toByteArray();
            }
          });

  SentryEnvelopeItemHeader itemHeader =
      new SentryEnvelopeItemHeader(
          SentryItemType.Session, () -> cachedItem.getBytes().length, "application/json", null);

  return new SentryEnvelopeItem(itemHeader, () -> cachedItem.getBytes());
}
 
Example #3
Source File: EgressInteractiveHandler.java    From warp10-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  while (true) {
    try {
      Socket connectionSocket = this.serverSocket.accept();
      
      if (this.capacity <= this.connections.get()) {
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
        pw.println("// Maximum server capacity is reached (" + this.capacity + ").");
        pw.flush();
        LOG.error("Maximum server capacity is reached (" + this.capacity + ").");
        connectionSocket.close();
        continue;
      }
      
      this.connections.incrementAndGet();
      
      InteractiveProcessor processor = new InteractiveProcessor(this, connectionSocket, null, connectionSocket.getInputStream(), connectionSocket.getOutputStream());      
    } catch (IOException ioe) {          
    }
  }
}
 
Example #4
Source File: CodeWriter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Called by CodeModel to store the specified file.
 * The callee must allocate a storage to store the specified file.
 *
 * <p>
 * The returned stream will be closed before the next file is
 * stored. So the callee can assume that only one OutputStream
 * is active at any given time.
 *
 * @param   pkg
 *      The package of the file to be written.
 * @param   fileName
 *      File name without the path. Something like
 *      "Foo.java" or "Bar.properties"
 */
public Writer openSource( JPackage pkg, String fileName ) throws IOException {
    final OutputStreamWriter bw = encoding != null
            ? new OutputStreamWriter(openBinary(pkg,fileName), encoding)
            : new OutputStreamWriter(openBinary(pkg,fileName));

    // create writer
    try {
        return new UnicodeEscapeWriter(bw) {
            // can't change this signature to Encoder because
            // we can't have Encoder in method signature
            private final CharsetEncoder encoder = EncoderFactory.createEncoder(bw.getEncoding());
            @Override
            protected boolean requireEscaping(int ch) {
                // control characters
                if( ch<0x20 && " \t\r\n".indexOf(ch)==-1 )  return true;
                // check ASCII chars, for better performance
                if( ch<0x80 )       return false;

                return !encoder.canEncode((char)ch);
            }
        };
    } catch( Throwable t ) {
        return new UnicodeEscapeWriter(bw);
    }
}
 
Example #5
Source File: PaletteItemTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private FileObject createItemFileWithInLineDescription() throws Exception {
    FileObject fo = itemsFolder.createData(ITEM_FILE);
    FileLock lock = fo.lock();
    try {
        OutputStreamWriter writer = new OutputStreamWriter(fo.getOutputStream(lock), "UTF-8");
        try {
            writer.write("<?xml version='1.0' encoding='UTF-8'?>");
            writer.write("<!DOCTYPE editor_palette_item PUBLIC '-//NetBeans//Editor Palette Item 1.1//EN' 'http://www.netbeans.org/dtds/editor-palette-item-1_1.dtd'>");
            writer.write("<editor_palette_item version='1.1'>");
            writer.write("<body><![CDATA[" + BODY + "]]></body>");
            writer.write("<icon16 urlvalue='" + ICON16 + "' />");
            writer.write("<icon32 urlvalue='" + ICON32 + "' />");
            writer.write("<inline-description> <display-name>"
                    +NbBundle.getBundle(BUNDLE_NAME).getString(NAME_KEY)+"</display-name> <tooltip>"
                    +NbBundle.getBundle(BUNDLE_NAME).getString(TOOLTIP_KEY)+"</tooltip>  </inline-description>");
            writer.write("</editor_palette_item>");
        } finally {
            writer.close();
        }
    } finally {
        lock.releaseLock();
    }           
    return fo;
}
 
Example #6
Source File: JsonParser.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
@Override
public void compose(Element e, OutputStream stream, OutputStyle style, String identity) throws FHIRException, IOException {
	OutputStreamWriter osw = new OutputStreamWriter(stream, "UTF-8");
	if (style == OutputStyle.CANONICAL)
		json = new JsonCreatorCanonical(osw);
	else
		json = new JsonCreatorGson(osw);
	json.setIndent(style == OutputStyle.PRETTY ? "  " : "");
	json.beginObject();
	prop("resourceType", e.getType(), null);
	Set<String> done = new HashSet<String>();
	for (Element child : e.getChildren()) {
		compose(e.getName(), e, done, child);
	}
	json.endObject();
	json.finish();
	osw.flush();
}
 
Example #7
Source File: MvsConsoleWrapper.java    From java-samples with Apache License 2.0 6 votes vote down vote up
static void redirectSystemIn() throws Exception {
	// This starts the MvsConsole listener if it's not already started (by the JZOS Batch Launcher)
	if (!MvsConsole.isListening()) {
		MvsConsole.startMvsCommandListener();
	}

	PipedOutputStream pos = new PipedOutputStream();
	final Writer writer = new OutputStreamWriter(pos);   // use default file.encoding
	
	MvsConsole.registerMvsCommandCallback(
			new MvsCommandCallback() {
				public void handleStart(String parms) {};
				public void handleModify(String cmd) {
					try {
						writer.write(cmd + "\n");
						writer.flush();
					} catch (IOException ioe) {
						ioe.printStackTrace();
					}
				}
				public boolean handleStop() { return true; } // System.exit() 
			});
	PipedInputStream pis = new PipedInputStream(pos);
	System.setIn(pis);
}
 
Example #8
Source File: DashboardMain.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static Path generateVersionIndex(String groupId, String artifactId, List<String> versions)
    throws IOException, TemplateException, URISyntaxException {
  Path directory = outputDirectory(groupId, artifactId, "snapshot").getParent();
  directory.toFile().mkdirs();
  Path page = directory.resolve("index.html");

  Map<String, Object> templateData = new HashMap<>();
  templateData.put("versions", versions);
  templateData.put("groupId", groupId);
  templateData.put("artifactId", artifactId);

  File dashboardFile = page.toFile();
  try (Writer out =
      new OutputStreamWriter(new FileOutputStream(dashboardFile), StandardCharsets.UTF_8)) {
    Template dashboard = freemarkerConfiguration.getTemplate("/templates/version_index.ftl");
    dashboard.process(templateData, out);
  }

  copyResource(directory, "css/dashboard.css");

  return page;
}
 
Example #9
Source File: HintTestTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override protected void performRewrite(TransformationContext ctx) {
    try {
        FileObject resource = ctx.getWorkingCopy().getFileObject().getParent().getFileObject("test.txt");
        Assert.assertNotNull(resource);
        Reader r = new InputStreamReader(ctx.getResourceContent(resource), "UTF-8");
        ByteArrayOutputStream outData = new ByteArrayOutputStream();
        Writer w = new OutputStreamWriter(outData, "UTF-8");
        int read;

        while ((read = r.read()) != -1) {
            if (read != '\n') read++;
            w.write(read);
        }

        r.close();
        w.close();

        OutputStream out = ctx.getResourceOutput(resource);

        out.write(outData.toByteArray());

        out.close();
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #10
Source File: LolaSoundnessChecker.java    From codebase with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Calls the LoLA service with the given PNML under the given URL.
 * @param pnml of the Petri net
 * @param address - URL of the LoLA service 
 * @return text response from LoLA
 * @throws IOException 
 */
private static String callLola(String pnml, String address) throws IOException {
	URL url = new URL(address);
       URLConnection conn = url.openConnection();
       conn.setDoOutput(true);
       conn.setUseCaches(false);
       conn.setReadTimeout(TIMEOUT);
       OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
   
       // send pnml
       writer.write("input=" + URLEncoder.encode(pnml, "UTF-8"));
       writer.flush();
       
       // get the response
       StringBuffer answer = new StringBuffer();
       BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
       String line;
       while ((line = reader.readLine()) != null) {
           answer.append(line);
       }
       writer.close();
       reader.close();
       return answer.toString();
}
 
Example #11
Source File: WriterAsOutputStreamTest.java    From cactoos with MIT License 6 votes vote down vote up
@Test
public void writesToByteArray() {
    final String content = "Hello, товарищ! How are you?";
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new Assertion<>(
        "Can't copy Input to Writer",
        new TeeInput(
            new InputOf(content),
            new OutputTo(
                new WriterAsOutputStream(
                    new OutputStreamWriter(
                        baos, StandardCharsets.UTF_8
                    ),
                    StandardCharsets.UTF_8,
                    // @checkstyle MagicNumber (1 line)
                    13
                )
            )
        ),
        new InputHasContent(
            new TextOf(baos::toByteArray, StandardCharsets.UTF_8)
        )
    ).affirm();
}
 
Example #12
Source File: ConfigurationFile.java    From TAB with Apache License 2.0 6 votes vote down vote up
public void fixHeader() {
	if (header == null) return;
	try {
		List<String> content = Lists.newArrayList(header);
		content.addAll(readAllLines());
		file.delete();
		file.createNewFile();
		BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8"));
		for (String line : content) {
			buf.write(line + System.getProperty("line.separator"));
		}
		buf.close();
	} catch (Exception ex) {
		Shared.errorManager.criticalError("Failed to modify file " + file, ex);
	}
}
 
Example #13
Source File: HttpResponseCache.java    From android-discourse with Apache License 2.0 6 votes vote down vote up
public void writeTo(DiskLruCache.Editor editor) throws IOException {
    OutputStream out = editor.newOutputStream(ENTRY_METADATA);
    Writer writer = new BufferedWriter(new OutputStreamWriter(out, UTF_8));

    writer.write(uri + '\n');
    writer.write(requestMethod + '\n');
    writer.write(Integer.toString(varyHeaders.length()) + '\n');
    for (int i = 0; i < varyHeaders.length(); i++) {
        writer.write(varyHeaders.getFieldName(i) + ": " + varyHeaders.getValue(i) + '\n');
    }

    writer.write(responseHeaders.getStatusLine() + '\n');
    writer.write(Integer.toString(responseHeaders.length()) + '\n');
    for (int i = 0; i < responseHeaders.length(); i++) {
        writer.write(responseHeaders.getFieldName(i) + ": " + responseHeaders.getValue(i) + '\n');
    }

    if (isHttps()) {
        writer.write('\n');
        writer.write(cipherSuite + '\n');
        writeCertArray(writer, peerCertificates);
        writeCertArray(writer, localCertificates);
    }
    writer.close();
}
 
Example #14
Source File: NetezzaExportManualTest.java    From aliyun-maxcompute-data-collectors with Apache License 2.0 6 votes vote down vote up
protected void createExportFile(ColumnGenerator... extraCols)
  throws IOException {
  String ext = ".txt";

  Path tablePath = getTablePath();
  Path filePath = new Path(tablePath, "part0" + ext);

  Configuration conf = new Configuration();
  if (!BaseSqoopTestCase.isOnPhysicalCluster()) {
    conf.set(CommonArgs.FS_DEFAULT_NAME, CommonArgs.LOCAL_FS);
  }
  FileSystem fs = FileSystem.get(conf);
  fs.mkdirs(tablePath);
  OutputStream os = fs.create(filePath);

  BufferedWriter w = new BufferedWriter(new OutputStreamWriter(os));
  for (int i = 0; i < 3; i++) {
    String line = getRecordLine(i, extraCols);
    w.write(line);
    LOG.debug("Create Export file - Writing line : " + line);
  }
  w.close();
  os.close();
}
 
Example #15
Source File: HDFS.java    From incubator-retired-pirk with Apache License 2.0 6 votes vote down vote up
public static void writeFile(List<BigInteger> elements, FileSystem fs, Path path, boolean deleteOnExit)
{
  try
  {
    // create writer
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fs.create(path, true)));

    // write each element on a new line
    for (BigInteger element : elements)
    {
      bw.write(element.toString());
      bw.newLine();
    }
    bw.close();

    // delete file once the filesystem is closed
    if (deleteOnExit)
    {
      fs.deleteOnExit(path);
    }
  } catch (IOException e)
  {
    e.printStackTrace();
  }
}
 
Example #16
Source File: ShapeletFilter.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
protected void writeShapelets(ArrayList<Shapelet> kShapelets, OutputStreamWriter out){
    try {
        out.append("informationGain,seriesId,startPos,classVal,numChannels,dimension\n");
        for (Shapelet kShapelet : kShapelets) {
            out.append(kShapelet.qualityValue + "," + kShapelet.seriesId + "," + kShapelet.startPos + "," + kShapelet.classValue + "," + kShapelet.getNumDimensions() + "," + kShapelet.dimension+"\n");
            for (int i = 0; i < kShapelet.numDimensions; i++) {
                double[] shapeletContent = kShapelet.getContent().getShapeletContent(i);
                for (int j = 0; j < shapeletContent.length; j++) {
                    out.append(shapeletContent[j] + ",");
                }
                out.append("\n");
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(ShapeletFilter.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example #17
Source File: PyExecutor.java    From jpserve with MIT License 6 votes vote down vote up
private String streamToString(InputStream in) throws IOException, PyServeException {
	ByteArrayOutputStream bout = new ByteArrayOutputStream();
	OutputStreamWriter out = new OutputStreamWriter(bout);
	InputStreamReader input = new InputStreamReader(in);
	
	char[] buffer = new char[8192];
	
	long count = 0;
       int n = 0;
       while (-1 != (n = input.read(buffer))) {
           out.write(buffer, 0, n);
           count += n;
       }

       if (count > MAX_SCRIPT_SIZE) {
       	throw new PyServeException("Exceed the max script size limit (8M).");
       }
       out.flush();
       return bout.toString();		
}
 
Example #18
Source File: AbstractFeedView.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected final void renderMergedOutputModel(
		Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
		throws Exception {

	T wireFeed = newFeed();
	buildFeedMetadata(model, wireFeed, request);
	buildFeedEntries(model, wireFeed, request, response);

	setResponseContentType(request, response);
	if (!StringUtils.hasText(wireFeed.getEncoding())) {
		wireFeed.setEncoding("UTF-8");
	}

	WireFeedOutput feedOutput = new WireFeedOutput();
	ServletOutputStream out = response.getOutputStream();
	feedOutput.output(wireFeed, new OutputStreamWriter(out, wireFeed.getEncoding()));
	out.flush();
}
 
Example #19
Source File: CsvInputFormatTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Test
public void testPojoTypeWithMappingInformation() throws Exception {
	File tempFile = File.createTempFile("CsvReaderPojoType", "tmp");
	tempFile.deleteOnExit();
	tempFile.setWritable(true);

	OutputStreamWriter wrt = new OutputStreamWriter(new FileOutputStream(tempFile));
	wrt.write("123,3.123,AAA,BBB\n");
	wrt.write("456,1.123,BBB,AAA\n");
	wrt.close();

	@SuppressWarnings("unchecked")
	PojoTypeInfo<PojoItem> typeInfo = (PojoTypeInfo<PojoItem>) TypeExtractor.createTypeInfo(PojoItem.class);
	CsvInputFormat<PojoItem> inputFormat = new PojoCsvInputFormat<PojoItem>(new Path(tempFile.toURI().toString()), typeInfo, new String[]{"field1", "field3", "field2", "field4"});

	inputFormat.configure(new Configuration());
	FileInputSplit[] splits = inputFormat.createInputSplits(1);

	inputFormat.open(splits[0]);

	validatePojoItem(inputFormat);
}
 
Example #20
Source File: HandlebarsViewEngine.java    From ozark with Apache License 2.0 6 votes vote down vote up
@Override
public void processView(ViewEngineContext context) throws ViewEngineException {

    Map<String, Object> model = new HashMap<>(context.getModels().asMap());
    model.put("request", context.getRequest(HttpServletRequest.class));
    
    Charset charset = resolveCharsetAndSetContentType(context);

    try (Writer writer = new OutputStreamWriter(context.getOutputStream(), charset);
         
        InputStream resourceAsStream = servletContext.getResourceAsStream(resolveView(context));
        InputStreamReader in = new InputStreamReader(resourceAsStream, "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(in);) {

        String viewContent = bufferedReader.lines().collect(Collectors.joining());

        Template template = handlebars.compileInline(viewContent);
        template.apply(model, writer);
        
    } catch (IOException e) {
        throw new ViewEngineException(e);
    }
}
 
Example #21
Source File: DataHandler.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
/**
    * Write the object to the output stream.
    */
   public void writeTo(Object obj, String mimeType, OutputStream os)
					throws IOException {
if (dch != null)
    dch.writeTo(obj, mimeType, os);
else if (obj instanceof byte[])
    os.write((byte[])obj);
else if (obj instanceof String) {
    OutputStreamWriter osw = new OutputStreamWriter(os);
    osw.write((String)obj);
    osw.flush();
} else
    throw new UnsupportedDataTypeException(
			"no object DCH for MIME type " + this.mimeType);
   }
 
Example #22
Source File: MHtmlWriter.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/**
 * Exporte une JTable dans un fichier au format html.
 *
 * @param table
 *           MBasicTable
 * @param outputStream
 *           OutputStream
 * @param isSelection
 *           boolean
 * @throws IOException
 *            Erreur disque
 */
protected void writeHtml(final MBasicTable table, final OutputStream outputStream,
		final boolean isSelection) throws IOException {
	final Writer out = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);

	final String eol = isSelection ? "\n" : System.getProperty("line.separator");
	// eol = "\n" si sélection, "\r\n" sinon pour un fichier windows et "\n" pour un fichier unix

	out.write("<!-- Fichier genere par ");
	out.write(System.getProperty("user.name"));
	out.write(" le ");
	out.write(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG)
			.format(new Date()));
	out.write(" -->");
	out.write(eol);

	out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
	out.write("<html>");
	out.write(eol);
	final String title = buildTitle(table);
	writeHtmlHead(title, out, eol);
	out.write("<body>");
	out.write(eol);
	if (title != null) {
		out.write("<h3>");
		out.write(title);
		out.write("</h3>");
	}
	out.write(eol);

	writeHtmlTable(table, isSelection, out, eol);
	out.write("</body>");
	out.write(eol);
	out.write("</html>");
	out.flush();
}
 
Example #23
Source File: DslStepsDumper.java    From bromium with MIT License 5 votes vote down vote up
@Override
public void dump(TestScenarioSteps testScenarioSteps, String outputFile) throws IOException {
    File file = new File(outputFile);
    try (BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)))) {
        for (Map<String, String> step : testScenarioSteps) {
            List<SyntaxDefinitionConfiguration> syntaxDefinitions =
                    Optional.ofNullable(actionConfigurations.get(step.get(EVENT)))
                            .orElseThrow(() -> new IllegalStateException("The step "
                                    + step + "has an event that is not present in the configuration"
                                    + step.get(EVENT)))
                            .getSyntaxDefinitionConfigurationList();
            StringBuilder lineBuilder = new StringBuilder();
            lineBuilder.append(step.get(EVENT)).append(": ");

            for (SyntaxDefinitionConfiguration syntaxDefinition: syntaxDefinitions) {
                if (syntaxDefinition.getContent() != null) {
                    lineBuilder
                            .append(syntaxDefinition.getContent())
                            .append(' ');
                }

                if (syntaxDefinition.getExposedParameter() != null) {
                    lineBuilder
                            .append(step.get(syntaxDefinition.getExposedParameter()))
                            .append(' ');
                }
            }

            bufferedWriter.write(lineBuilder.toString());
            bufferedWriter.newLine();
        }
    }

}
 
Example #24
Source File: ElementHandleTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAnonymousFromSource() throws Exception {
    try (PrintWriter out = new PrintWriter ( new OutputStreamWriter (data.getOutputStream()))) {
        out.println ("public class Test {" +
                    "    public void test() {" +
                    "        Object o = new Object() {};" +
                    "    }" +
                     "}");
    }
    final JavaSource js = JavaSource.create(ClasspathInfo.create(ClassPathProviderImpl.getDefault().findClassPath(data,ClassPath.BOOT), ClassPathProviderImpl.getDefault().findClassPath(data, ClassPath.COMPILE), null), data);
    assertNotNull(js);
    AtomicBoolean didTest = new AtomicBoolean();

    js.runUserActionTask(new Task<CompilationController>() {
        public void run(CompilationController parameter) throws Exception {
            parameter.toPhase(JavaSource.Phase.RESOLVED);
            new TreePathScanner<Void, Void>() {
                @Override
                public Void visitNewClass(NewClassTree node, Void p) {
                    TreePath clazz = new TreePath(getCurrentPath(), node.getClassBody());
                    Element el = parameter.getTrees().getElement(clazz);
                    assertNotNull(el);
                    assertNotNull(ElementHandle.create(el).resolve(parameter));
                    didTest.set(true);
                    return super.visitNewClass(node, p);
                }
            }.scan(parameter.getCompilationUnit(), null);
        }
    }, true);

    assertTrue(didTest.get());
}
 
Example #25
Source File: TestLineRecordReaderJobs.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the input test file
 *
 * @param conf
 * @throws IOException
 */
public void createInputFile(Configuration conf) throws IOException {
  FileSystem localFs = FileSystem.getLocal(conf);
  Path file = new Path(inputDir, "test.txt");
  Writer writer = new OutputStreamWriter(localFs.create(file));
  writer.write("abc\ndef\t\nghi\njkl");
  writer.close();
}
 
Example #26
Source File: FastjsonHttpMessageConverter.java    From java-platform with Apache License 2.0 5 votes vote down vote up
@Override
protected void writeInternal(Object obj, Type type, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {
	Charset charset = getCharset(outputMessage.getHeaders());
	OutputStreamWriter out = new OutputStreamWriter(outputMessage.getBody(), charset);
	SerializeWriter writer = new SerializeWriter(out);
	JSONSerializer serializer = new JSONSerializer(writer, this.serializeConfig);
	serializer.config(SerializerFeature.DisableCircularReferenceDetect, true);

	RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
	if (requestAttributes instanceof ServletRequestAttributes) {
		Class<?> rootClass = filterClass(obj);
		if (rootClass != null) {
			String[] paths = ((ServletRequestAttributes) requestAttributes).getRequest()
					.getParameterValues("paths");
			if (paths != null && paths.length > 0) {
				rootClass = ClassUtils.getUserClass(rootClass);
				Map<Class<?>, PropertyPreFilter> propertyFilters = new HashMap<>();
				pathVisit(propertyFilters, Sets.newHashSet(paths), rootClass);

				for (Entry<Class<?>, PropertyPreFilter> entry : propertyFilters.entrySet()) {
					serializer.getPropertyPreFilters().add(entry.getValue());
				}
			} else {

				serializer.getPropertyFilters().add(DEFAULT_PROPERTY_FILTER);
			}
		} else {
			serializer.getPropertyFilters().add(DEFAULT_PROPERTY_FILTER);
		}
	}
	serializer.write(obj);
	writer.flush();
	out.close();
}
 
Example #27
Source File: StringUtil.java    From FancyBing with GNU General Public License v3.0 5 votes vote down vote up
/** Get default encoding. */
public static String getDefaultEncoding()
{
    String encoding = System.getProperty("file.encoding");
    // Java 1.5 docs for System.getProperties do not guarantee the
    // existance of file.encoding
    if (encoding != null)
        return encoding;
    OutputStreamWriter out =
        new OutputStreamWriter(new ByteArrayOutputStream());
    return out.getEncoding();
}
 
Example #28
Source File: TestNc4Iosp.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
String ncdumpdata(NetcdfDataset ncfile, String datasetname) {
  boolean ok = false;
  String dump = "";
  StringBuilder args = new StringBuilder("-strict -vall");
  if (datasetname != null) {
    args.append(" -datasetname ");
    args.append(datasetname);
  }

  // Dump the databuffer

  ok = false;
  try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, StandardCharsets.UTF_8)) {
    ok = ucar.nc2.NCdumpW.print(ncfile, args.toString(), outputStreamWriter, null);
    dump = byteArrayOutputStream.toString(StandardCharsets.UTF_8.name());
  } catch (IOException ioe) {
    ioe.printStackTrace();
    ok = false;
  }

  if (!ok) {
    System.err.println("NcdumpW failed");
    System.exit(1);
  }
  // return shortenFileName(sw.toString(), ncfile.getLocation());
  return dump;
}
 
Example #29
Source File: OpenFireTalk.java    From soapbox-race with GNU General Public License v2.0 5 votes vote down vote up
private void setReaderWriter() {
	try {
		reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
		writer = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #30
Source File: SurrogatesTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
void generateAndReadXml(String content) throws Exception {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    OutputStreamWriter streamWriter = new OutputStreamWriter(stream);
    XMLStreamWriter writer = factory.createXMLStreamWriter(streamWriter);

    // Generate xml with selected stream writer type
    generateXML(writer, content);
    String output = stream.toString();
    System.out.println("Generated xml: " + output);
    // Read generated xml with StAX parser
    readXML(output.getBytes(), content);
}