Java Code Examples for java.io.PipedInputStream#connect()

The following examples show how to use java.io.PipedInputStream#connect() . 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: MicrophoneInputStream.java    From android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiates a new microphone input stream.
 *
 * @param opusEncoded the opus encoded
 */
public MicrophoneInputStream(boolean opusEncoded) {
  captureThread = new MicrophoneCaptureThread(this, opusEncoded);
  if (opusEncoded == true) {
    CONTENT_TYPE = ContentType.OPUS;
  } else {
    CONTENT_TYPE = ContentType.RAW;
  }
  os = new PipedOutputStream();
  is = new PipedInputStream();
  try {
    is.connect(os);
  } catch (IOException e) {
    Log.e(TAG, e.getMessage());
  }
  captureThread.start();
}
 
Example 2
Source File: LauncherTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Before public void setup() throws IOException {
	PipedInputStream inClient = new PipedInputStream();
	PipedOutputStream outClient = new PipedOutputStream();
	PipedInputStream inServer = new PipedInputStream();
	PipedOutputStream outServer = new PipedOutputStream();
	
	inClient.connect(outServer);
	outClient.connect(inServer);
	server = new AssertingEndpoint();
	serverLauncher = LSPLauncher.createServerLauncher(ServiceEndpoints.toServiceObject(server, LanguageServer.class), inServer, outServer);
	serverListening = serverLauncher.startListening();
	
	client = new AssertingEndpoint();
	clientLauncher = LSPLauncher.createClientLauncher(ServiceEndpoints.toServiceObject(client, LanguageClient.class), inClient, outClient);
	clientListening = clientLauncher.startListening();
	
	Logger logger = Logger.getLogger(StreamMessageProducer.class.getName());
	logLevel = logger.getLevel();
	logger.setLevel(Level.SEVERE);
}
 
Example 3
Source File: SupportBundleManager.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * Return InputStream from which a new generated resource bundle can be retrieved.
 */
public SupportBundle generateNewBundle(List<String> generatorNames, BundleType bundleType) throws IOException {
  List<BundleContentGeneratorDefinition> defs = getRequestedDefinitions(generatorNames);

  PipedInputStream inputStream = new PipedInputStream();
  PipedOutputStream outputStream = new PipedOutputStream();
  inputStream.connect(outputStream);
  ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);

  executor.submit(() -> generateNewBundleInternal(defs, bundleType, zipOutputStream));

  String bundleName = generateBundleName(bundleType);
  String bundleKey = generateBundleDate(bundleType) + "/" + bundleName;

  return new SupportBundle(
    bundleKey,
    bundleName,
    inputStream
  );
}
 
Example 4
Source File: ClientImpl.java    From datamill with ISC License 6 votes vote down vote up
private CloseableHttpResponse doWithEntity(Body body, CloseableHttpClient httpClient, HttpUriRequest request) throws IOException {
    if (!(request instanceof HttpEntityEnclosingRequestBase)) {
        throw new IllegalArgumentException("Expecting to write an body for a request type that does not support it!");
    }

    PipedOutputStream pipedOutputStream = buildPipedOutputStream();
    PipedInputStream pipedInputStream = buildPipedInputStream();

    pipedInputStream.connect(pipedOutputStream);

    BasicHttpEntity httpEntity = new BasicHttpEntity();
    httpEntity.setContent(pipedInputStream);
    ((HttpEntityEnclosingRequestBase) request).setEntity(httpEntity);

    writeEntityOutOverConnection(body, pipedOutputStream);

    return doExecute(httpClient, request);
}
 
Example 5
Source File: DockerMultiplexedInputStreamTest.java    From docker-plugin with MIT License 5 votes vote down vote up
public DemuxTester() throws IOException {
    feeder = new PipedOutputStream();

    feeder_input_stream = new PipedInputStream();
    feeder_input_stream.connect(feeder);
    
    stream = new DockerMultiplexedInputStream(feeder_input_stream);
    sink = new ByteArrayOutputStream();
    eof = false;
    exc = null;

    thread = new Thread(this);
    thread.start();
}
 
Example 6
Source File: ReplaceInStringExample.java    From ExpectIt with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    PipedInputStream pipedInputStream = new PipedInputStream();
    PipedOutputStream pipedOutputStream = new PipedOutputStream();

    System.out.println("Connecting pipes");
    pipedInputStream.connect(pipedOutputStream);

    System.out.println("Building expect");
    Expect expect = new ExpectBuilder()
            .withInputs(pipedInputStream)
            .withTimeout(30, TimeUnit.SECONDS)
            .withExceptionOnFailure()
            .withInputFilters(myFilter())
            .build();

    System.out.println("Writing data to output");
    for (int i = 0; i < 1500; i++) {
        pipedOutputStream.write("removeSome text hereremove\n".getBytes());
    }
    pipedOutputStream.write("done\n".getBytes());

    System.out.println("Flushing output");
    pipedOutputStream.flush();

    System.out.println("Waiting for 'done'");
    Result r = expect.expect(Matchers.contains("done"));

    System.out.println("Printing data");
    System.out.println(r.getBefore());

    System.out.println("Done");

    expect.close();
}
 
Example 7
Source File: DownloadSchema.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@ApiResponses({@ApiResponse(code = 200, response = File.class, message = "")})
@GetMapping(path = "/slowInputStream")
public ResponseEntity<InputStream> slowInputStream() throws IOException {
  PipedInputStream in = new PipedInputStream();
  PipedOutputStream out = new PipedOutputStream();
  in.connect(out);

  slowInputStreamThread = new Thread(() -> {
    Thread.currentThread().setName("download thread");
    byte[] bytes = "1".getBytes();
    for (; ; ) {
      try {
        out.write(bytes);
        out.flush();
        Thread.sleep(1000);
      } catch (Throwable e) {
        break;
      }
    }
    try {
      out.close();
    } catch (final IOException ioe) {
      // ignore
    }
  });
  slowInputStreamThread.start();

  ResponseEntity<InputStream> responseEntity = ResponseEntity
      .ok()
      .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE)
      .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=slowInputStream.txt")
      .body(in);
  return responseEntity;
}
 
Example 8
Source File: HttpUrlConnectionImpl.java    From whiskey with Apache License 2.0 5 votes vote down vote up
@Override
public OutputStream getOutputStream() throws IOException {

    PipedOutputStream out = new PipedOutputStream();
    PipedInputStream in = new PipedInputStream();
    in.connect(out);
    requestBuilder.body(in);
    return out;
}
 
Example 9
Source File: SchematronValidatingParser.java    From teamengine with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an org.w3c.dom.Document element to an java.io.InputStream.
 * 
 * @param edoc
 *            The org.w3c.dom.Document to be converted
 * @return The InputStream value of the passed doument
 */
public InputStream DocumentToInputStream(org.w3c.dom.Document edoc)
        throws IOException {

    final org.w3c.dom.Document doc = edoc;
    final PipedOutputStream pos = new PipedOutputStream();
    PipedInputStream pis = new PipedInputStream();
    pis.connect(pos);

    (new Thread(new Runnable() {

        public void run() {
            // Use the Transformer.transform() method to save the Document
            // to a StreamResult
            try {
                TransformerFactory tFactory = TransformerFactory.newInstance();
                  // Fortify Mod: prevent external entity injection 
                tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                Transformer transformer = tFactory.newTransformer();
                transformer.setOutputProperty("encoding", "ISO-8859-1");
                transformer.setOutputProperty("indent", "yes");
                transformer.transform(new DOMSource(doc), new StreamResult(
                        pos));
            } catch (Exception _ex) {
                throw new RuntimeException(
                        "Failed to tranform org.w3c.dom.Document to PipedOutputStream",
                        _ex);
            } finally {
                try {
                    pos.close();
                } catch (IOException e) {

                }
            }
        }
    }, "MyClassName.convert(org.w3c.dom.Document edoc)")).start();

    return pis;
}
 
Example 10
Source File: ExtendableConcurrentMessageProcessorTest.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test that an adopter making use of these APIs is able to 
 * identify which client is making any given request. 
 */
@Test
public void testIdentifyClientRequest() throws Exception {
	// create client side
	PipedInputStream in = new PipedInputStream();
	PipedOutputStream out = new PipedOutputStream();
	PipedInputStream in2 = new PipedInputStream();
	PipedOutputStream out2 = new PipedOutputStream();
	
	in.connect(out2);
	out.connect(in2);
	
	MyClient client = new MyClientImpl();
	Launcher<MyServer> clientSideLauncher = Launcher.createLauncher(client, MyServer.class, in, out);
	
	// create server side
	MyServer server = new MyServerImpl();
	MessageContextStore<MyClient> contextStore = new MessageContextStore<>();
	Launcher<MyClient> serverSideLauncher = createLauncher(createBuilder(contextStore), server, MyClient.class, in2, out2);
	
	TestContextWrapper.setMap(contextStore);
	
	clientSideLauncher.startListening();
	serverSideLauncher.startListening();
	
	CompletableFuture<MyParam> fooFuture = clientSideLauncher.getRemoteProxy().askServer(new MyParam("FOO"));
	CompletableFuture<MyParam> barFuture = serverSideLauncher.getRemoteProxy().askClient(new MyParam("BAR"));
	
	Assert.assertEquals("FOO", fooFuture.get(TIMEOUT, TimeUnit.MILLISECONDS).value);
	Assert.assertEquals("BAR", barFuture.get(TIMEOUT, TimeUnit.MILLISECONDS).value);
	Assert.assertFalse(TestContextWrapper.error);
}
 
Example 11
Source File: TestStandardLoadBalanceProtocol.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testEofWritingContent() throws IOException {
    final StandardLoadBalanceProtocol protocol = new StandardLoadBalanceProtocol(flowFileRepo, contentRepo, provenanceRepo, flowController, ALWAYS_AUTHORIZED);

    final PipedInputStream serverInput = new PipedInputStream();
    final PipedOutputStream serverContentSource = new PipedOutputStream();
    serverInput.connect(serverContentSource);

    final ByteArrayOutputStream serverOutput = new ByteArrayOutputStream();

    // Write connection ID
    final Checksum checksum = new CRC32();
    final OutputStream checkedOutput = new CheckedOutputStream(serverContentSource, checksum);
    final DataOutputStream dos = new DataOutputStream(checkedOutput);
    dos.writeUTF("unit-test-connection-id");

    final Map<String, String> attributes = new HashMap<>();
    attributes.put("uuid", "unit-test-id");

    dos.write(CHECK_SPACE);
    dos.write(MORE_FLOWFILES);
    writeAttributes(attributes, dos);

    // Indicate 45 byte data frame, then stop after 5 bytes.
    dos.write(DATA_FRAME_FOLLOWS);
    dos.writeShort(45);
    dos.write("hello".getBytes());
    dos.flush();
    dos.close();

    try {
        protocol.receiveFlowFiles(serverInput, serverOutput, "Unit Test", 1);
        Assert.fail("Expected EOFException but none was thrown");
    } catch (final EOFException e) {
        // expected
    }

    final byte[] serverResponse = serverOutput.toByteArray();
    assertEquals(1, serverResponse.length);
    assertEquals(SPACE_AVAILABLE, serverResponse[0]);

    assertEquals(1, claimContents.size());
    final byte[] firstFlowFileContent = claimContents.values().iterator().next();
    assertArrayEquals(new byte[0], firstFlowFileContent);

    Mockito.verify(flowFileRepo, times(0)).updateRepository(anyCollection());
    Mockito.verify(provenanceRepo, times(0)).registerEvents(anyList());
    Mockito.verify(flowFileQueue, times(0)).putAll(anyCollection());
    Mockito.verify(contentRepo, times(0)).incrementClaimaintCount(claimContents.keySet().iterator().next());
    Mockito.verify(contentRepo, times(0)).decrementClaimantCount(claimContents.keySet().iterator().next());
    Mockito.verify(contentRepo, times(1)).remove(claimContents.keySet().iterator().next());
}
 
Example 12
Source File: TestStandardLoadBalanceProtocol.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testBadChecksum() throws IOException {
    final StandardLoadBalanceProtocol protocol = new StandardLoadBalanceProtocol(flowFileRepo, contentRepo, provenanceRepo, flowController, ALWAYS_AUTHORIZED);

    final PipedInputStream serverInput = new PipedInputStream();
    final PipedOutputStream serverContentSource = new PipedOutputStream();
    serverInput.connect(serverContentSource);

    final ByteArrayOutputStream serverOutput = new ByteArrayOutputStream();

    // Write connection ID
    final Checksum checksum = new CRC32();
    final OutputStream checkedOutput = new CheckedOutputStream(serverContentSource, checksum);
    final DataOutputStream dos = new DataOutputStream(checkedOutput);
    dos.writeUTF("unit-test-connection-id");

    final Map<String, String> attributes = new HashMap<>();
    attributes.put("uuid", "unit-test-id");

    dos.write(CHECK_SPACE);
    dos.write(MORE_FLOWFILES);
    writeAttributes(attributes, dos);
    writeContent("hello".getBytes(), dos);
    dos.write(NO_MORE_FLOWFILES);

    dos.writeLong(1L); // Write bad checksum.
    dos.write(COMPLETE_TRANSACTION);

    try {
        protocol.receiveFlowFiles(serverInput, serverOutput, "Unit Test", 1);
        Assert.fail("Expected TransactionAbortedException but none was thrown");
    } catch (final TransactionAbortedException e) {
        // expected
    }

    final byte[] serverResponse = serverOutput.toByteArray();
    assertEquals(2, serverResponse.length);
    assertEquals(SPACE_AVAILABLE, serverResponse[0]);
    assertEquals(REJECT_CHECKSUM, serverResponse[1]);

    assertEquals(1, claimContents.size());
    final byte[] firstFlowFileContent = claimContents.values().iterator().next();
    assertArrayEquals("hello".getBytes(), firstFlowFileContent);

    Mockito.verify(flowFileRepo, times(0)).updateRepository(anyCollection());
    Mockito.verify(provenanceRepo, times(0)).registerEvents(anyList());
    Mockito.verify(flowFileQueue, times(0)).putAll(anyCollection());
    Mockito.verify(contentRepo, times(1)).incrementClaimaintCount(claimContents.keySet().iterator().next());
    Mockito.verify(contentRepo, times(2)).decrementClaimantCount(claimContents.keySet().iterator().next());
    Mockito.verify(contentRepo, times(1)).remove(claimContents.keySet().iterator().next());
}
 
Example 13
Source File: TestStandardLoadBalanceProtocol.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testSimpleFlowFileTransaction() throws IOException {
    final StandardLoadBalanceProtocol protocol = new StandardLoadBalanceProtocol(flowFileRepo, contentRepo, provenanceRepo, flowController, ALWAYS_AUTHORIZED);

    final PipedInputStream serverInput = new PipedInputStream();
    final PipedOutputStream serverContentSource = new PipedOutputStream();
    serverInput.connect(serverContentSource);

    final ByteArrayOutputStream serverOutput = new ByteArrayOutputStream();

    // Write connection ID
    final Checksum checksum = new CRC32();
    final OutputStream checkedOutput = new CheckedOutputStream(serverContentSource, checksum);
    final DataOutputStream dos = new DataOutputStream(checkedOutput);
    dos.writeUTF("unit-test-connection-id");

    final Map<String, String> attributes = new HashMap<>();
    attributes.put("a", "A");
    attributes.put("uuid", "unit-test-id");
    attributes.put("b", "B");

    dos.write(CHECK_SPACE);
    dos.write(MORE_FLOWFILES);
    writeAttributes(attributes, dos);
    writeContent("hello".getBytes(), dos);
    dos.write(NO_MORE_FLOWFILES);

    dos.writeLong(checksum.getValue());
    dos.write(COMPLETE_TRANSACTION);

    protocol.receiveFlowFiles(serverInput, serverOutput, "Unit Test", 1);

    final byte[] serverResponse = serverOutput.toByteArray();
    assertEquals(3, serverResponse.length);
    assertEquals(SPACE_AVAILABLE, serverResponse[0]);
    assertEquals(CONFIRM_CHECKSUM, serverResponse[1]);
    assertEquals(CONFIRM_COMPLETE_TRANSACTION, serverResponse[2]);

    assertEquals(1, claimContents.size());
    final byte[] firstFlowFileContent = claimContents.values().iterator().next();
    assertArrayEquals("hello".getBytes(), firstFlowFileContent);

    Mockito.verify(flowFileRepo, times(1)).updateRepository(anyCollection());
    Mockito.verify(provenanceRepo, times(1)).registerEvents(anyList());
    Mockito.verify(flowFileQueue, times(0)).putAll(anyCollection());
    Mockito.verify(flowFileQueue, times(1)).receiveFromPeer(anyCollection());
}
 
Example 14
Source File: TestStandardLoadBalanceProtocol.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testAbortAfterChecksumConfirmation() throws IOException {
    final StandardLoadBalanceProtocol protocol = new StandardLoadBalanceProtocol(flowFileRepo, contentRepo, provenanceRepo, flowController, ALWAYS_AUTHORIZED);

    final PipedInputStream serverInput = new PipedInputStream();
    final PipedOutputStream serverContentSource = new PipedOutputStream();
    serverInput.connect(serverContentSource);

    final ByteArrayOutputStream serverOutput = new ByteArrayOutputStream();

    // Write connection ID
    final Checksum checksum = new CRC32();
    final OutputStream checkedOutput = new CheckedOutputStream(serverContentSource, checksum);
    final DataOutputStream dos = new DataOutputStream(checkedOutput);
    dos.writeUTF("unit-test-connection-id");

    final Map<String, String> attributes = new HashMap<>();
    attributes.put("uuid", "unit-test-id");

    dos.write(CHECK_SPACE);
    dos.write(MORE_FLOWFILES);
    writeAttributes(attributes, dos);
    writeContent("hello".getBytes(), dos);
    dos.write(NO_MORE_FLOWFILES);

    dos.writeLong(checksum.getValue());
    dos.write(ABORT_TRANSACTION);

    try {
        protocol.receiveFlowFiles(serverInput, serverOutput, "Unit Test", 1);
        Assert.fail("Expected TransactionAbortedException but none was thrown");
    } catch (final TransactionAbortedException e) {
        // expected
    }

    final byte[] serverResponse = serverOutput.toByteArray();
    assertEquals(2, serverResponse.length);
    assertEquals(SPACE_AVAILABLE, serverResponse[0]);
    assertEquals(CONFIRM_CHECKSUM, serverResponse[1]);

    assertEquals(1, claimContents.size());
    final byte[] firstFlowFileContent = claimContents.values().iterator().next();
    assertArrayEquals("hello".getBytes(), firstFlowFileContent);

    Mockito.verify(flowFileRepo, times(0)).updateRepository(anyCollection());
    Mockito.verify(provenanceRepo, times(0)).registerEvents(anyList());
    Mockito.verify(flowFileQueue, times(0)).putAll(anyCollection());
    Mockito.verify(contentRepo, times(1)).incrementClaimaintCount(claimContents.keySet().iterator().next());
    Mockito.verify(contentRepo, times(2)).decrementClaimantCount(claimContents.keySet().iterator().next());
    Mockito.verify(contentRepo, times(1)).remove(claimContents.keySet().iterator().next());
}
 
Example 15
Source File: PipedStream.java    From Dodder with MIT License 4 votes vote down vote up
public PipedStream() throws IOException {
	writeStream = new PipedOutputStream();
	readStream = new PipedInputStream(22 * 1024);
	readStream.connect(writeStream);
}
 
Example 16
Source File: TestStandardLoadBalanceProtocol.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testFlowFileNoContent() throws IOException {
    final StandardLoadBalanceProtocol protocol = new StandardLoadBalanceProtocol(flowFileRepo, contentRepo, provenanceRepo, flowController, ALWAYS_AUTHORIZED);

    final PipedInputStream serverInput = new PipedInputStream();
    final PipedOutputStream serverContentSource = new PipedOutputStream();
    serverInput.connect(serverContentSource);

    final ByteArrayOutputStream serverOutput = new ByteArrayOutputStream();

    // Write connection ID
    final Checksum checksum = new CRC32();
    final OutputStream checkedOutput = new CheckedOutputStream(serverContentSource, checksum);
    final DataOutputStream dos = new DataOutputStream(checkedOutput);
    dos.writeUTF("unit-test-connection-id");

    final Map<String, String> attributes = new HashMap<>();
    attributes.put("uuid", "unit-test-id");

    dos.write(CHECK_SPACE);
    dos.write(MORE_FLOWFILES);
    writeAttributes(attributes, dos);
    writeContent(null, dos);
    dos.write(NO_MORE_FLOWFILES);

    dos.writeLong(checksum.getValue());
    dos.write(COMPLETE_TRANSACTION);

    protocol.receiveFlowFiles(serverInput, serverOutput, "Unit Test", 1);

    final byte[] serverResponse = serverOutput.toByteArray();
    assertEquals(3, serverResponse.length);
    assertEquals(SPACE_AVAILABLE, serverResponse[0]);
    assertEquals(CONFIRM_CHECKSUM, serverResponse[1]);
    assertEquals(CONFIRM_COMPLETE_TRANSACTION, serverResponse[2]);

    assertEquals(1, claimContents.size());
    assertEquals(0, claimContents.values().iterator().next().length);

    Mockito.verify(flowFileRepo, times(1)).updateRepository(anyCollection());
    Mockito.verify(provenanceRepo, times(1)).registerEvents(anyList());
    Mockito.verify(flowFileQueue, times(0)).putAll(anyCollection());
    Mockito.verify(flowFileQueue, times(1)).receiveFromPeer(anyCollection());
}
 
Example 17
Source File: GopherClient.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
InputStream openStream(URL u) throws IOException {
   this.u = u;
   this.os = this.os;
   int i = 0;
   String s = u.getFile();
   int limit = s.length();

   char c;
   for(c = s.charAt(i); i < limit && c == '/'; ++i) {
      ;
   }

   this.gtype = c == '/' ? 49 : c;
   if (i < limit) {
      ++i;
   }

   this.gkey = s.substring(i);
   this.openServer(u.getHost(), u.getPort() <= 0 ? 70 : u.getPort());
   MessageHeader msgh = new MessageHeader();
   switch(this.gtype) {
   case 48:
   case 55:
      msgh.add("content-type", "text/plain");
      break;
   case 49:
      msgh.add("content-type", "text/html");
      break;
   case 73:
   case 103:
      msgh.add("content-type", "image/gif");
      break;
   default:
      msgh.add("content-type", "content/unknown");
   }

   i = this.gkey.indexOf(63);
   if (this.gtype != 55) {
      this.serverOutput.print(this.decodePercent(this.gkey) + "\r\n");
      this.serverOutput.flush();
   } else if (i >= 0) {
      this.serverOutput.print(this.decodePercent(this.gkey.substring(0, i) + "\t" + this.gkey.substring(i + 1) + "\r\n"));
      this.serverOutput.flush();
      msgh.add("content-type", "text/html");
   } else {
      msgh.add("content-type", "text/html");
   }

   this.connection.setProperties(msgh);
   if (msgh.findValue("content-type") == "text/html") {
      this.os = new PipedOutputStream();
      PipedInputStream ret = new PipedInputStream();
      ret.connect(this.os);
      (new Thread(this)).start();
      return ret;
   } else {
      return new GopherInputStream(this, this.serverInput);
   }
}
 
Example 18
Source File: GopherClient.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
InputStream openStream(URL u) throws IOException {
   this.u = u;
   this.os = this.os;
   int i = 0;
   String s = u.getFile();
   int limit = s.length();

   char c;
   for(c = s.charAt(i); i < limit && c == '/'; ++i) {
      ;
   }

   this.gtype = c == '/' ? 49 : c;
   if (i < limit) {
      ++i;
   }

   this.gkey = s.substring(i);
   this.openServer(u.getHost(), u.getPort() <= 0 ? 70 : u.getPort());
   MessageHeader msgh = new MessageHeader();
   switch(this.gtype) {
   case 48:
   case 55:
      msgh.add("content-type", "text/plain");
      break;
   case 49:
      msgh.add("content-type", "text/html");
      break;
   case 73:
   case 103:
      msgh.add("content-type", "image/gif");
      break;
   default:
      msgh.add("content-type", "content/unknown");
   }

   i = this.gkey.indexOf(63);
   if (this.gtype != 55) {
      this.serverOutput.print(this.decodePercent(this.gkey) + "\r\n");
      this.serverOutput.flush();
   } else if (i >= 0) {
      this.serverOutput.print(this.decodePercent(this.gkey.substring(0, i) + "\t" + this.gkey.substring(i + 1) + "\r\n"));
      this.serverOutput.flush();
      msgh.add("content-type", "text/html");
   } else {
      msgh.add("content-type", "text/html");
   }

   this.connection.setProperties(msgh);
   if (msgh.findValue("content-type") == "text/html") {
      this.os = new PipedOutputStream();
      PipedInputStream ret = new PipedInputStream();
      ret.connect(this.os);
      (new Thread(this)).start();
      return ret;
   } else {
      return new GopherInputStream(this, this.serverInput);
   }
}
 
Example 19
Source File: GopherClient.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
InputStream openStream(URL u) throws IOException {
   this.u = u;
   this.os = this.os;
   int i = 0;
   String s = u.getFile();
   int limit = s.length();

   char c;
   for(c = s.charAt(i); i < limit && c == '/'; ++i) {
   }

   this.gtype = c == '/' ? 49 : c;
   if (i < limit) {
      ++i;
   }

   this.gkey = s.substring(i);
   this.openServer(u.getHost(), u.getPort() <= 0 ? 70 : u.getPort());
   MessageHeader msgh = new MessageHeader();
   switch(this.gtype) {
   case 48:
   case 55:
      msgh.add("content-type", "text/plain");
      break;
   case 49:
      msgh.add("content-type", "text/html");
      break;
   case 73:
   case 103:
      msgh.add("content-type", "image/gif");
      break;
   default:
      msgh.add("content-type", "content/unknown");
   }

   i = this.gkey.indexOf(63);
   if (this.gtype != 55) {
      this.serverOutput.print(this.decodePercent(this.gkey) + "\r\n");
      this.serverOutput.flush();
   } else if (i >= 0) {
      this.serverOutput.print(this.decodePercent(this.gkey.substring(0, i) + "\t" + this.gkey.substring(i + 1) + "\r\n"));
      this.serverOutput.flush();
      msgh.add("content-type", "text/html");
   } else {
      msgh.add("content-type", "text/html");
   }

   this.connection.setProperties(msgh);
   if (msgh.findValue("content-type") == "text/html") {
      this.os = new PipedOutputStream();
      PipedInputStream ret = new PipedInputStream();
      ret.connect(this.os);
      (new Thread(this)).start();
      return ret;
   } else {
      return new GopherInputStream(this, this.serverInput);
   }
}
 
Example 20
Source File: GopherClient.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
InputStream openStream(URL u) throws IOException {
   this.u = u;
   this.os = this.os;
   int i = 0;
   String s = u.getFile();
   int limit = s.length();

   char c;
   for(c = s.charAt(i); i < limit && c == '/'; ++i) {
      ;
   }

   this.gtype = c == '/' ? 49 : c;
   if (i < limit) {
      ++i;
   }

   this.gkey = s.substring(i);
   this.openServer(u.getHost(), u.getPort() <= 0 ? 70 : u.getPort());
   MessageHeader msgh = new MessageHeader();
   switch(this.gtype) {
   case 48:
   case 55:
      msgh.add("content-type", "text/plain");
      break;
   case 49:
      msgh.add("content-type", "text/html");
      break;
   case 73:
   case 103:
      msgh.add("content-type", "image/gif");
      break;
   default:
      msgh.add("content-type", "content/unknown");
   }

   i = this.gkey.indexOf(63);
   if (this.gtype != 55) {
      this.serverOutput.print(this.decodePercent(this.gkey) + "\r\n");
      this.serverOutput.flush();
   } else if (i >= 0) {
      this.serverOutput.print(this.decodePercent(this.gkey.substring(0, i) + "\t" + this.gkey.substring(i + 1) + "\r\n"));
      this.serverOutput.flush();
      msgh.add("content-type", "text/html");
   } else {
      msgh.add("content-type", "text/html");
   }

   this.connection.setProperties(msgh);
   if (msgh.findValue("content-type") == "text/html") {
      this.os = new PipedOutputStream();
      PipedInputStream ret = new PipedInputStream();
      ret.connect(this.os);
      (new Thread(this)).start();
      return ret;
   } else {
      return new GopherInputStream(this, this.serverInput);
   }
}