Java Code Examples for java.io.OutputStreamWriter

The following examples show how to use java.io.OutputStreamWriter. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * 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 2
Source Project: tsml   Source File: ShapeletFilter.java    License: 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 3
Source Project: warp10-platform   Source File: EgressInteractiveHandler.java    License: 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 Project: cactoos   Source File: WriterAsOutputStreamTest.java    License: 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 5
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 6
Source Project: incubator-retired-pirk   Source File: HDFS.java    License: 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 7
Source Project: Flink-CEPplus   Source File: CsvInputFormatTest.java    License: 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 8
Source Project: ozark   Source File: HandlebarsViewEngine.java    License: 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 9
Source Project: FoxTelem   Source File: RawQueue.java    License: 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 10
Source Project: lams   Source File: AbstractFeedView.java    License: 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 11
Source Project: jpserve   Source File: PyExecutor.java    License: 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 12
Source Project: android-discourse   Source File: HttpResponseCache.java    License: 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 13
Source Project: TAB   Source File: ConfigurationFile.java    License: 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 14
/**
 * 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 15
Source Project: java-samples   Source File: MvsConsoleWrapper.java    License: 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 16
Source Project: netbeans   Source File: HintTestTest.java    License: 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 17
Source Project: cloud-opensource-java   Source File: DashboardMain.java    License: 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 18
Source Project: org.hl7.fhir.core   Source File: JsonParser.java    License: 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 19
Source Project: netbeans   Source File: PaletteItemTest.java    License: 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 20
Source Project: sentry-android   Source File: SentryEnvelopeItem.java    License: 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 21
Source Project: netbeans   Source File: CompletionContextTest.java    License: Apache License 2.0 5 votes vote down vote up
private void writeSourceFile() throws Exception {
    File f = new File(getWorkDir(), "source.fxml");
    FileObject dirFo = FileUtil.toFileObject(getWorkDir());
    OutputStream ostm = dirFo.createAndOpen("source.fxml");
    OutputStreamWriter wr = new OutputStreamWriter(ostm);
    wr.write(text);
    wr.flush();
    wr.close();
    
    sourceFO = dirFo.getFileObject("source.fxml");
}
 
Example 22
/**
 * Open an writer for the file, using the encoding (if any) given in the
 * doclet configuration.
 * The file must have been created with a location of
 * {@link DocumentationTool.Location#DOCUMENTATION_OUTPUT} and a corresponding relative path.
 */
public Writer openWriter() throws IOException, UnsupportedEncodingException {
    if (location != DocumentationTool.Location.DOCUMENTATION_OUTPUT)
        throw new IllegalStateException();

    createDirectoryForFile(file);
    FileOutputStream fos = new FileOutputStream(file);
    if (configuration.docencoding == null) {
        return new BufferedWriter(new OutputStreamWriter(fos));
    } else {
        return new BufferedWriter(new OutputStreamWriter(fos, configuration.docencoding));
    }
}
 
Example 23
Source Project: jstarcraft-core   Source File: CsvWriter.java    License: Apache License 2.0 5 votes vote down vote up
public CsvWriter(OutputStream outputStream, CodecDefinition definition) {
    super(definition);
    try {
        OutputStreamWriter buffer = new OutputStreamWriter(outputStream, StringUtility.CHARSET);
        this.outputStream = new CSVPrinter(buffer, FORMAT);
    } catch (Exception exception) {
        throw new RuntimeException(exception);
    }
}
 
Example 24
Source Project: delion   Source File: OmahaClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sends the request to the server.
 */
private void sendRequestToServer(HttpURLConnection urlConnection, String xml)
        throws RequestFailureException {
    try {
        OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
        OutputStreamWriter writer = new OutputStreamWriter(out);
        writer.write(xml, 0, xml.length());
        writer.close();
        checkServerResponseCode(urlConnection);
    } catch (IOException e) {
        throw new RequestFailureException("Failed to write request to server: ", e);
    }
}
 
Example 25
Source Project: BeFoot   Source File: Main.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	File in = new File("R.txt");
	File out = new File("public.xml");

	if (!in.exists()) {
		throw new NullPointerException("R.txt is not null.");
	}

	try {
		out.createNewFile();
	} catch (IOException e) {
		e.printStackTrace();
		return;
	}

	System.out.println(in.getAbsolutePath());
	System.out.println(out.getAbsolutePath());

	InputStreamReader read = new InputStreamReader(new FileInputStream(in));
	BufferedReader bufferedReader = new BufferedReader(read);

	OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(out));
	BufferedWriter bufferedWriter = new BufferedWriter(writer);

	Map<String, PublicLine> xml = new HashMap<>();
	buildXml(bufferedReader, xml);

	List<PublicLine> lines = new ArrayList<>();
	lines.addAll(xml.values());

	Collections.sort(lines);

	saveFile(lines, bufferedWriter);

	close(bufferedReader);
	close(bufferedWriter);

	System.out.println("End.");
}
 
Example 26
Source Project: scipio-erp   Source File: UtilPlist.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Writes model information in the Apple EOModelBundle format.
 *
 * For document structure and definition see: http://developer.apple.com/documentation/InternetWeb/Reference/WO_BundleReference/Articles/EOModelBundle.html
 *
 * @param eoModelMap
 * @param eomodeldFullPath
 * @param filename
 * @throws FileNotFoundException
 * @throws UnsupportedEncodingException
 */
public static void writePlistFile(Map<String, Object> eoModelMap, String eomodeldFullPath, String filename, boolean useXml) throws FileNotFoundException, UnsupportedEncodingException {
    try (PrintWriter plistWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(eomodeldFullPath, filename)), "UTF-8")))) {
        if (useXml) {
            plistWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            plistWriter.println("<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">");
            plistWriter.println("<plist version=\"1.0\">");
            writePlistPropertyMapXml(eoModelMap, 0, plistWriter);
            plistWriter.println("</plist>");
        } else {
            writePlistPropertyMap(eoModelMap, 0, plistWriter, false);
        }
    }
}
 
Example 27
public static void writeHttpContent(String content) {

        try {

            System.out.println(content);
            pw = new PrintWriter(new OutputStreamWriter(uc.getOutputStream()), true);
            pw.print(content);
            pw.flush();
            pw.close();
            br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String httpResp = br.readLine();
            Map<String, List<String>> headerFields = uc.getHeaderFields();
            if (headerFields.containsKey("Set-Cookie")) {
                List<String> header = headerFields.get("Set-Cookie");
                for (int i = 0; i < header.size(); i++) {
                    String tmp = header.get(i);
                    if (tmp.contains("skey")) {
                        skeycookie = tmp;
                    }
                    if (tmp.contains("user")) {
                        usercookie = tmp;
                    }
                }
            } else {
                System.out.println("shit");
            }
            System.out.println();
            skeycookie = skeycookie.substring(0, skeycookie.indexOf(";"));
            System.out.println(skeycookie);
            if (!usercookie.contains("user")) {
                login = false;
            } else {
                login = true;
                usercookie = usercookie.substring(0, usercookie.indexOf(";"));
                System.out.println(usercookie);
            }
        } catch (Exception e) {
            //System.out.println("ex " + e.toString());
        }
    }
 
Example 28
Source Project: submarine   Source File: ServiceSpecFileGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public static String generateJson(Service service) throws IOException {
  File serviceSpecFile = File.createTempFile(service.getName(), ".json");
  String buffer = jsonSerDeser.toJson(service);
  Writer w = new OutputStreamWriter(new FileOutputStream(serviceSpecFile),
      StandardCharsets.UTF_8);
  try (PrintWriter pw = new PrintWriter(w)) {
    pw.append(buffer);
  }
  return serviceSpecFile.getAbsolutePath();
}
 
Example 29
Source Project: netbeans   Source File: RunnerRestStopInstance.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void handleSend(HttpURLConnection hconn) throws IOException {
     OutputStreamWriter wr = new OutputStreamWriter(hconn.getOutputStream());
     CommandTarget cmd = (CommandTarget) command;
     StringBuilder data = new StringBuilder();
     data.append("instanceName=").append(cmd.target);
     
     wr.write(data.toString());
     wr.flush();
     wr.close();
}
 
Example 30
Source Project: openjdk-jdk9   Source File: Gen.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * We explicitly need to write ASCII files because that is what C
 * compilers understand.
 */
protected PrintWriter wrapWriter(OutputStream o) throws Util.Exit {
    try {
        return new PrintWriter(new OutputStreamWriter(o, "ISO8859_1"), true);
    } catch (UnsupportedEncodingException use) {
        util.bug("encoding.iso8859_1.not.found");
        return null; /* dead code */
    }
}