Examples of ByteBuffer


Examples of java.nio.ByteBuffer

       
        if ( expected_length == -1 && message.size() >= 4 ){
         
          byte[]  bytes = message.toByteArray();
         
          ByteBuffer  bb = ByteBuffer.wrap( bytes );
         
          expected_length = bb.getInt();
         
          message = new ByteArrayOutputStream();
         
          if ( bytes.length > 4 ){
           
View Full Code Here

Examples of java.nio.ByteBuffer

                  if (Logger.isEnabled())
                    Logger.log(new LogEvent(LOGID, "Incoming connection from ["
                        + connection + "] successfully routed to NAT CHECKER"));
 
                  try{
                    ByteBuffer  msg = getMessage();
 
                    Transport transport = connection.getTransport();
 
                    long  start = SystemTime.getCurrentTime();
 
                    while( msg.hasRemaining()){
 
                      transport.write( new ByteBuffer[]{ msg }, 0, 1 );
 
                      if ( msg.hasRemaining()){
 
                        long now = SystemTime.getCurrentTime();
 
                        if ( now < start ){
 
View Full Code Here

Examples of java.nio.ByteBuffer

      map.put( "check", check );

      byte[]  map_bytes = BEncoder.encode( map );

      ByteBuffer msg = ByteBuffer.allocate( 4 + map_bytes.length );

      msg.putInt( map_bytes.length );
      msg.put( map_bytes );

      msg.flip();
     
      return( msg );
    }
View Full Code Here

Examples of java.nio.ByteBuffer

      connection.connect();

    }else{
     
      try{
        ByteBuffer  buffer = ByteBuffer.allocate( 32*1024 );
           
        sts_engine.getKeys( buffer );
           
        buffer.flip();
       
        sent_keys = true;
       
        connection.connect( buffer );
       
View Full Code Here

Examples of java.nio.ByteBuffer

  {
    try{
      boolean  forward        = false;
      boolean  crypto_completed  = false;
     
      ByteBuffer  out_buffer = null;

      synchronized( this ){
   
        if ( crypto_complete.isReleasedForever()){
         
          forward  = true;
         
        }else{
         
            // basic sts flow:
            //   a -> puba -> b
            //   a <- pubb <- b
            //   a -> auta -> b
            //   a <- autb <- b
            //   a -> data -> b
         
            // optimised
         
            //  a -> puba      -> b
            //  a <- pubb + auta <- b
            //  a -> autb + data -> b
         
            // therefore can be one or two messages in the payload
            //     1 crypto
            //    2 crypto (pub + auth)
            //    crypto + data
         
            // initial a ->puba -> is done on first data send so data is ready for phase 3
         
          ByteBuffer  in_buffer = ByteBuffer.wrap( message.toByteArray());
         
          message.returnToPool();
           
            // piggyback pub key send
         
          if ( !sent_keys ){
           
              // we've received
              //    a -> puba -> b
              // reply with
              //    a <- puba + auta <- b
           
            out_buffer = ByteBuffer.allocate( 64*1024 );

              // write our keys
           
            sts_engine.getKeys( out_buffer );
         
            sent_keys  = true;
           
              // read their keys
           
            sts_engine.putKeys( in_buffer );
         
              // write our auth
           
            sts_engine.getAuth( out_buffer );
           
            sent_auth   = true;
           
          }else if ( !sent_auth ){
           
            out_buffer = ByteBuffer.allocate( 64*1024 );

            // we've received
            //    a <- puba + auta <- b
            // reply with
            //    a -> autb + data -> b

              // read their keys
           
            sts_engine.putKeys( in_buffer );

              // write our auth
           
            sts_engine.getAuth( out_buffer );

            sent_auth = true;
         
              // read their auth
           
            sts_engine.putAuth( in_buffer );

              // check we wanna talk to this person
           
            byte[]  rem_key = sts_engine.getRemotePublicKey();
           
            if ( !key_locator.accept(
                SESTSConnectionImpl.this,
                new SEPublicKeyImpl( my_public_key.getType(), rem_key ))){
             
              throw( new MessageException( "remote public key not accepted" ));
            }
             
            setupBlockCrypto();
           
            if ( pending_message != null ){
             
              byte[]  pending_bytes = pending_message.toByteArray();
             
              int  pending_size = pending_bytes.length;
             
              if ( outgoing_cipher != null ){
               
                pending_size =  (( pending_size + AES_KEY_SIZE_BYTES -1 )/AES_KEY_SIZE_BYTES)*AES_KEY_SIZE_BYTES;
               
                if ( pending_size == 0 ){
                 
                  pending_size = AES_KEY_SIZE_BYTES;
                }
              }
             
              if ( out_buffer.remaining() >= pending_size ){
               
                if ( outgoing_cipher != null ){
                 
                 
                  out_buffer.put( outgoing_cipher.doFinal( pending_bytes ));
                 
                }else{
               
                  out_buffer.put( pending_bytes );
                }
               
                  // don't deallocate the pending message, the original caller does this
                               
                pending_message  = null;
              }
            }
           
            crypto_completed  = true;
           
          }else{
              // we've received
              //    a -> autb + data -> b
           
              // read their auth
           
            sts_engine.putAuth( in_buffer );

              // check we wanna talk to this person
           
            byte[]  rem_key = sts_engine.getRemotePublicKey();
           
            if ( !key_locator.accept(
                SESTSConnectionImpl.this,
                new SEPublicKeyImpl( my_public_key.getType(), rem_key ))){
             
                // this is just here to prevent unwanted spew  during closedown process
             
              connection.closing();
             
              throw( new MessageException( "remote public key not accepted" ));
            }
           
            setupBlockCrypto();

            crypto_completed  = true;
           
              // pick up any remaining data for delivery
           
            if ( in_buffer.hasRemaining()){
             
              message = new PooledByteBufferImpl( new DirectByteBuffer( in_buffer.slice()));
             
              forward  = true;
            }
          }
        }
View Full Code Here

Examples of java.nio.ByteBuffer

      InputStream stream;

      try {
        byte[] bytes;
        ByteBuffer byteBuffer= encoder.encode(CharBuffer.wrap(document.get()));
        if (byteBuffer.hasArray())
          bytes= byteBuffer.array();
        else {
          bytes= new byte[byteBuffer.limit()];
          byteBuffer.get(bytes);
        }
        stream= new ByteArrayInputStream(bytes, 0, byteBuffer.limit());
      } catch (CharacterCodingException ex) {
        Assert.isTrue(ex instanceof UnmappableCharacterException);
        String message= "Charset mapping failed.";
        IStatus s= new Status(IStatus.ERROR, Plugin.PLUGIN_ID, EditorsUI.CHARSET_MAPPING_FAILED, message, null);
        throw new CoreException(s);
View Full Code Here

Examples of java.nio.ByteBuffer

      private ByteBuffer buffer = ByteBuffer.allocate(1 << 16);
     
      @Override
      public void writeDirect(byte[] bytes, int offset, int length) throws TeiidComponentException {
        if (getLength() + length > buffer.capacity()) {
          ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity() * 2 + length);
          buffer.position(0);
          newBuffer.put(buffer);
          buffer = newBuffer;
        }
        buffer.position((int)getLength());
        buffer.put(bytes, offset, length);
      }
View Full Code Here

Examples of java.nio.ByteBuffer

                public void run() {
                    Selector sel=null;
                    SocketChannel tmp;
                    Set ready_keys;
                    SelectionKey key;
                    ByteBuffer transfer_buf=ByteBuffer.allocate(BUFSIZE);

                    try {
                        sel=Selector.open();
                        in_channel.configureBlocking(false);
                        out_channel.configureBlocking(false);
View Full Code Here

Examples of net.matuschek.util.ByteBuffer

    // set document URL
    doc.setURL(u);

    // document buffer
    ByteBuffer buff = new ByteBuffer();

    // the connection to the HTTP server
    // HttpConnection httpConn = null;

    InputStream is = null;
    BufferedWriter bwrite = null;

    // get host
    host = u.getHost();
    if (host == null) {
      throw new HttpException("no host part in URL found");
    }

    // get address, if not using a proxy
    // if the client runs behind a proxy it is possible, that name
    // resolution for the internet is not possible
    if(! useProxy()) {
      try {
  addr = InetAddress.getByName(host);
      } catch (UnknownHostException e) {
  addr = null;
      }
      if (addr == null) {
  throw new HttpException("host part (" + host + ") does not resolve");
      }
    }

    // get path   
    path = u.getFile();
    if (path.equals("")) {
      path = "/";
    }
    // replace spaces
    path=path.replaceAll(" ","%20");

    // get protocol and port
    port = u.getPort();
    protocol = u.getProtocol().toLowerCase();
    if (protocol.equals("http")) {
      if (port == -1) {
  port = DEFAULT_HTTPPORT;
      }
    } else if (protocol.equals("https")) {
      if (port == -1) {
  port = DEFAULT_HTTPSPORT;
      }
      secureConnection=true;
    } else {
      throw new HttpException("protocol " + protocol + " not supported");
    }

    // if using the proxy, request path is the whole URL, otherwise only
    // the path part of the URL
    if (useProxy() && (! secureConnection)) {
      requestPath="http://"+host+path;
    } else {
      requestPath=path;
    }

    // get user info
    userinfo = u.getUserInfo();
    if (userinfo != null) {
     if (userinfo.equals("")) {
      userinfo=null;
     } else {
      // Store user info for this host
      userInfos.setProperty(host,userinfo);
     }
    } else {
     // do we hae a stored user info?
     userinfo=userInfos.getProperty(host);
    }


    if (callback != null) {
      callback.setHttpToolDocUrl(u.toString());
      callback.setHttpToolStatus(STATUS_CONNECTING);
    }

    // okay, we got all needed information, try to connect to the host
    try {
    if (httpConn == null) {
        // connect and initialize streams
        // timeout is stored in seconds in HttpTool, but
        // HttpConnection uses milliseconds
        if (secureConnection) {
      HttpsHelper helper = new HttpsHelper(proxyAddr,proxyPort,useProxy());
      httpConn = helper.createHttpsConnection(host,port);
        } else {
      if (useProxy()) {
        httpConn = HttpConnection.createConnection(proxyAddr,
                     proxyPort,
                     socketTimeout*1000);
      } else {
        httpConn = HttpConnection.createConnection(addr,
                     port,
                     socketTimeout*1000);
      }
        }
    }
 
      is = new LimitedBandwidthStream(
    new BufferedInputStream(httpConn.getInputStream(), 256),
          bandwidth);
      bwrite = new BufferedWriter(
           new OutputStreamWriter(httpConn.getOutputStream()));

      if (callback != null) {
  callback.setHttpToolStatus(STATUS_CONNECTED);
      }


      // write HTTP request
      // get or post ?
      if (method == HttpConstants.GET) {
  bwrite.write("GET ");
  bwrite.write(requestPath);
  if ((parameters != null)
      && (! parameters.equals(""))) {
    bwrite.write("?");
    bwrite.write(parameters);
  }

      } else if (method == HttpConstants.POST) {
  bwrite.write("POST " + requestPath);
      } else {
  throw new HttpException("HTTP method " + method + " not supported");
      }

      // last part of request line
      bwrite.write(" ");
      bwrite.write(HTTP_VERSION);
      bwrite.write("\r\n");

      // Referer header only if defined
      if (referer != null) {
  bwrite.write("Referer: " + referer + "\r\n");
      }

      // if cookies are enabled, write a Cookie: header
      if (cookiesEnabled) {
  String cookieString = cookieManager.cookiesForURL(u);
  if (cookieString != null) {
    bwrite.write("Cookie: ");
    bwrite.write(cookieString);
    bwrite.write("\r\n");
    log.debug("Cookie request header: "+cookieString);
  }
      }

      // Write other headers
      bwrite.write("Host: " + host + "\r\n");
      bwrite.write("User-Agent: " + agentName + "\r\n");
      bwrite.write("Accept: */*\r\n");
      if (ntlmAuthorizationInfo == null) {
        bwrite.write("Connection: close\r\n");
      } else {
    bwrite.write("Connection: keep-alive\r\n");
      }

      // Write "From:" header only if a fromAddress is defined
      if (fromAddress != null) {
  bwrite.write("From: "+fromAddress+"\r\n");
      }

      // if we have username and password, lets write an Authorization
      // header
      if (userinfo != null) {
  // special hack to support usernames with "@"
  // TO DO: find a better solution for this problem
  userinfo = userinfo.replace('%','@');
  bwrite.write("Authorization: Basic ");
  bwrite.write(Base64.encode(userinfo));
  bwrite.write("\r\n");
        log.debug(userinfo);
       
      }
     
      if (ntlmAuthorizationInfo != null) {
    bwrite.write("Authorization: NTLM ");
    bwrite.write(ntlmAuthorizationInfo);
    bwrite.write("\r\n");
      }
     

      // if there is a "If-Modified-Since" date, also write this header
      if (modifyDate != null) { 
  String dateStr = df.format(modifyDate);

  bwrite.write("If-Modified-Since: ");
  bwrite.write(dateStr);
  bwrite.write("\r\n");
  log.debug("If-Modified-Since header: "+dateStr)
      }

      // for a POST request we also need a content-length header
      if (method == HttpConstants.POST) {
  bwrite.write("Content-Type: application/x-www-form-urlencoded\r\n");
  bwrite.write("Content-Length: "+parameters.length()+"\r\n");
      }

      // finished headers
      bwrite.write("\r\n");
      // if this is a POST request, we have to add the POST parameters
      if (method == HttpConstants.POST) {
  bwrite.write(parameters);
      }
      bwrite.flush();
     
      if (callback != null) {
  callback.setHttpToolStatus(STATUS_RETRIEVING);
      }

      // read the first line (HTTP return code)
      while ((i = is.read()) != 10) {
  if (i == -1) {
    throw new HttpException("Could not get HTTP return code "+
          "(buffer content is "+buff.toString()+")");
  }
  buff.append((byte)i);
      }

      String httpCode = lineString(buff.getContent());
      buff.clean();
      doc.setHttpCode(httpCode);


      // read the HTTP headers
      boolean finishedHeaders = false;
      while (!finishedHeaders) {
  i = is.read();
  if (i == -1) {
    throw new HttpException("Could not read HTTP headers");
  }
  if (i >= 32) {
    buff.append((byte)i);
  }
  // HTTP header processing
  if (i == LF) {
    String line = lineString(buff.getContent());
   
    buff.clean();
    // empty line means "end of headers"
    if (line.trim().equals("")) {
      finishedHeaders = true;
    } else {
      HttpHeader head = new HttpHeader(line);
      doc.addHeader(head);

      if (cookiesEnabled
    && head.isSetCookie()) {
        try {
    Cookie cookie = new Cookie(head.toLine(),u);
    cookieManager.add(cookie);
    log.debug("Got a cookie "+cookie);
        } catch (CookieException e) {
    log.info("Could not interpret cookie: "+e.getMessage());
        }
      }

      // Content chunked ?
      if (head.getName().equalsIgnoreCase("Transfer-Encoding")
    && head.getValue().equalsIgnoreCase("chunked")) {
        chunkedEncoding = true;
      }

    }
  }
      }
      buff.clean();

      // if there is a DownloadRule, ask if we should download
      // the data
      if (downloadRules != null) {
    // if it is not allowed to download this URL, close socket
    // and return a null document
    boolean isNotModified = false;
    if (modifyDate != null) {
      HttpHeader lastModifiedHeader = doc.getHttpHeader("Last-Modified");
      if (lastModifiedHeader != null) {
        try {
          Date lastModifiedDate = df.parse(lastModifiedHeader.getValue());
          if (lastModifiedDate.compareTo(modifyDate) <= 0) {
            isNotModified = true;
          }
        } catch (ParseException e) {}
      }
    }
   
    if (! downloadRules.downloadAllowed(doc.getHttpHeader()) || isNotModified) {
      if (doc.isNotModified()) {
      log.info("If-Not-Modified successfull for: " + u);
      } else if (isNotModified) {
      log.info("Header indicates not modified for: " + u);
      } else {
      log.info("Download not allowed by download rule.");
      }
      // Close connection
      httpConn.close(); httpConn = null;
 
      if (callback != null) {
        callback.setHttpToolStatus(STATUS_DENIEDBYRULE);
      }
      return null;
    }
      }

     
      // if we got encoding "chunked", use the ChunkedInputStream
      if (chunkedEncoding) {
  chunkStream = new ChunkedInputStream(is);
      }
     

      // did we got an Content-Length header ?
      HttpHeader contentLength = doc.getHeader(HttpHeader.CONTENT_LENGTH);
      if (contentLength != null) {      
 
  try {
    docSize = Integer.parseInt(contentLength.getValue());
  } catch (NumberFormatException e) {
    log.error("Got a malformed Content-Length header from the server");
    docSize = -1;
  }

  // send information to callback
  if (callback != null) {
    callback.setHttpToolDocSize(docSize);
  }

  // initialize the byte buffer with the given document size
  // there is no need to increase the buffer size dynamically
  if (docSize > 0) {
    buff.setSize(docSize);
  }
      }

      // read data
      boolean finished = false;
      int count=0;

      while (! finished) {
 
  if (chunkedEncoding) {
    i = chunkStream.read();
  } else {
    i = is.read();
  }
 
  if (i == -1) {
    // this should only happen on HTTP/1.0 responses
    // without a Content-Length header
    finished = true;
  } else {
    buff.append((byte)i);
    count++;
  }


  // finished ?
  // there are other tests then wait until read gives us a -1:

  // if there was a Content-Length header stop after reading the
  // given number of bytes
  if (count == docSize) {
    finished = true;
  }
 
  // if it is a chunked stream we should use the isDone method
  // to look if we reached the end
  if (chunkedEncoding) {
    if (chunkStream.isDone()) {
      finished=true;
    }
  }
 

  // should we call the callback interface ?
  if (callback != null) {
    if (((buff.length() % updateInterval) == 0)
        || finished) {
      callback.setHttpToolDocCurrentSize(buff.length());
    }
  }

 
      }
     
      doc.setContent(buff.getContent());

      if (ntlmAuthorizationInfo == null) {
    // close everything
    //      bwrite.close();
    //      is.close();
View Full Code Here

Examples of net.yacy.kelondro.util.ByteBuffer

        final ByteArrayOutputStream keyStream = new ByteArrayOutputStream(512);
        byte[] key;
        byte[] multi_key;
        byte[] replacement;
        int bb;
        final ByteBuffer structure = new ByteBuffer();
        while (transferUntil(pis, out, hashChar)) {
            bb = pis.read();
            keyStream.reset();

            // #{
            if ((bb & 0xFF) == lcbr) { //multi
                if (transferUntil(pis, keyStream, mClose)) { //close tag
                    //multi_key =  "_" + keyStream.toString(); //for _Key
                    bb = pis.read();
                    if ((bb & 0xFF) != 10){ //kill newline
                        pis.unread(bb);
                    }
                    multi_key = keyStream.toByteArray(); //IMPORTANT: no prefix here
                    keyStream.reset(); //reset stream

                    //this needs multi_key without prefix
                    if (transferUntil(pis, keyStream, appendBytes(mOpen, slashChar, multi_key, mClose))){
                        bb = pis.read();
                        if((bb & 0xFF) != 10){ //kill newline
                            pis.unread(bb);
                        }

                        final byte[] text=keyStream.toByteArray(); //text between #{key}# an #{/key}#
                        int num=0;
                        final String patternKey = getPatternKey(prefix, multi_key);
                        if(pattern.containsKey(patternKey) && pattern.get(patternKey) != null){
                            try{
                                num=Integer.parseInt(pattern.get(patternKey)); // Key contains the iteration number as string
                            }catch(final NumberFormatException e){
                                num=0;
                            }
                        }

                        structure.append('<')
                                 .append(multi_key)
                                 .append(multi_num)
                                 .append(ASCII.getBytes(Integer.toString(num)))
                                 .append(close_quotetagn);
                        for(int i=0;i < num;i++) {
                            final PushbackInputStream pis2 = new PushbackInputStream(new ByteArrayInputStream(text));
                            //System.out.println("recursing with text(prefix="+ multi_key + "_" + i + "_" +"):"); //DEBUG
                            //System.out.println(text);
                            structure.append(writeTemplate(pis2, out, pattern, dflt, newPrefix(prefix,multi_key,i)));
                        }//for
                        structure.append(open_endtag).append(multi_key).append(close_tagn);
                    } else {//transferUntil
                        Log.logSevere("TEMPLATE", "No Close Key found for #{"+UTF8.String(multi_key)+"}#"); //prefix here?
                    }
                }

            // #(
            } else if ((bb & 0xFF) == lrbr) { //alternative
                int others=0;
                final ByteBuffer text= new ByteBuffer();

                transferUntil(pis, keyStream, aClose);
                key = keyStream.toByteArray(); //Caution: Key does not contain prefix

                keyStream.reset(); //clear

                boolean byName=false;
                int whichPattern=0;
                byte[] patternName = new byte[0];
                final String patternKey = getPatternKey(prefix, key);
                if(pattern.containsKey(patternKey) && pattern.get(patternKey) != null){
                    final String patternId=pattern.get(patternKey);
                    try{
                        whichPattern=Integer.parseInt(patternId); //index
                    }catch(final NumberFormatException e){
                        whichPattern=0;
                        byName=true;
                        patternName = UTF8.getBytes(patternId);
                    }
                }

                int currentPattern=0;
                boolean found=false;
                keyStream.reset(); //reset stream
                PushbackInputStream pis2;
                if (byName) {
                    //TODO: better Error Handling
                    transferUntil(pis, keyStream, appendBytes(PP, patternName, null, null));
                    if(pis.available()==0){
                        Log.logSevere("TEMPLATE", "No such Template: %%" + UTF8.String(patternName));
                        return structure.getBytes();
                    }
                    keyStream.reset();
                    transferUntil(pis, keyStream, dpdpa);
                    pis2 = new PushbackInputStream(new ByteArrayInputStream(keyStream.toByteArray()));
                    structure.append(writeTemplate(pis2, out, pattern, dflt, newPrefix(prefix,key)));
                    transferUntil(pis, keyStream, appendBytes(hash_brackopen_slash, key, brackclose_hash, null));
                    if(pis.available()==0){
                        Log.logSevere("TEMPLATE", "No Close Key found for #("+UTF8.String(key)+")# (by Name)");
                    }
                } else {
                    while(!found){
                        bb=pis.read(); // performance problem? trace always points to this line
                        if ((bb & 0xFF) == hashChar){
                            bb=pis.read();
                            if ((bb & 0xFF) == lrbr){
                                transferUntil(pis, keyStream, aClose);

                                //reached the end. output last string.
                                if (java.util.Arrays.equals(keyStream.toByteArray(),appendBytes(slashChar, key, null,null))) {
                                    pis2 = new PushbackInputStream(new ByteArrayInputStream(text.getBytes()));
                                    //this maybe the wrong, but its the last
                                    structure.append('<').append(key).append(alternative_which).append(ASCII.getBytes(Integer.toString(whichPattern))).append(ASCII.getBytes("\" found=\"0\">\n"));
                                    structure.append(writeTemplate(pis2, out, pattern, dflt, newPrefix(prefix,key)));
                                    structure.append(open_endtag).append(key).append(close_tagn);
                                    found=true;
                                }else if(others >0 && keyStream.toString().startsWith("/")){ //close nested
                                    others--;
                                    text.append(aOpen).append(keyStream.toByteArray()).append(brackclose_hash);
                                } else { //nested
                                    others++;
                                    text.append(aOpen).append(keyStream.toByteArray()).append(brackclose_hash);
                                }
                                keyStream.reset(); //reset stream
                                continue;
                            } //is not #(
                            pis.unread(bb);//is processed in next loop
                            bb = (hashChar);//will be added to text this loop
                            //text += "#";
                        }else if ((bb & 0xFF) == ':' && others==0){//ignore :: in nested Expressions
                            bb=pis.read();
                            if ((bb & 0xFF) == ':'){
                                if(currentPattern == whichPattern){ //found the pattern
                                    pis2 = new PushbackInputStream(new ByteArrayInputStream(text.getBytes()));
                                    structure.append('<').append(key).append(alternative_which).append(ASCII.getBytes(Integer.toString(whichPattern))).append(ASCII.getBytes("\" found=\"0\">\n"));
                                    structure.append(writeTemplate(pis2, out, pattern, dflt, newPrefix(prefix,key)));
                                    structure.append(open_endtag).append(key).append(close_tagn);

                                    transferUntil(pis, keyStream, appendBytes(hash_brackopen_slash, key, brackclose_hash,null));//to #(/key)#.

                                    found=true;
                                }
                                currentPattern++;
                                text.clear();
                                continue;
                            }
                            text.append(':');
                        }
                        if(!found){
                            text.append((byte)bb);/*
                            if(pis.available()==0){
                                serverLog.logSevere("TEMPLATE", "No Close Key found for #("+UTF8.String(key)+")# (by Index)");
                                found=true;
                            }*/
                        }
                    }//while
                }//if(byName) (else branch)

            // #[
            } else if ((bb & 0xFF) == lbr) { //normal
                if (transferUntil(pis, keyStream, pClose)) {
                    // pattern detected, write replacement
                    key = keyStream.toByteArray();
                    final String patternKey = getPatternKey(prefix, key);
                    replacement = replacePattern(patternKey, pattern, dflt); //replace
                    structure.append('<').append(key)
                            .append(ASCII.getBytes(" type=\"normal\">\n"));
                    structure.append(replacement);
                    structure.append(ASCII.getBytes("</")).append(key)
                            .append(close_tagn);

                    FileUtils.copy(replacement, out);
                } else {
                    // inconsistency, simply finalize this
                    FileUtils.copy(pis, out);
                    return structure.getBytes();
                }

            // #%
            } else if ((bb & 0xFF) == pcChar) { //include
                final ByteBuffer include = new ByteBuffer();
                keyStream.reset(); //reset stream
                if(transferUntil(pis, keyStream, iClose)){
                    byte[] filename = keyStream.toByteArray();
                    //if(filename.startsWith( Character.toString((char)lbr) ) && filename.endsWith( Character.toString((char)rbr) )){ //simple pattern for filename
                    if((filename[0] == lbr) && (filename[filename.length-1] == rbr)){ //simple pattern for filename
                        final byte[] newFilename = new byte[filename.length-2];
                        System.arraycopy(filename, 1, newFilename, 0, newFilename.length);
                        final String patternkey = getPatternKey(prefix, newFilename);
                        filename= replacePattern(patternkey, pattern, dflt);
                    }
                    if (filename.length > 0 && !java.util.Arrays.equals(filename, dflt)) {
                        BufferedReader br = null;
                        try{
                            //br = new BufferedReader(new InputStreamReader(new FileInputStream( filename ))); //Simple Include
                            br = new BufferedReader( new InputStreamReader(new FileInputStream( HTTPDFileHandler.getLocalizedFile(UTF8.String(filename))),"UTF-8") ); //YaCy (with Locales)
                            //Read the Include
                            String line = "";
                            while ((line = br.readLine()) != null) {
                                include.append(UTF8.getBytes(line)).append(ASCII.getBytes(de.anomic.server.serverCore.CRLF_STRING));
                            }
                        } catch (final IOException e) {
                            //file not found?
                            Log.logSevere("FILEHANDLER","Include Error with file " + UTF8.String(filename) + ": " + e.getMessage());
                        } finally {
                            if (br != null) try { br.close(); br=null; } catch (final Exception e) {}
                        }
                        final PushbackInputStream pis2 = new PushbackInputStream(new ByteArrayInputStream(include.getBytes()));
                        structure.append(ASCII.getBytes("<fileinclude file=\"")).append(filename).append(close_tagn);
                        structure.append(writeTemplate(pis2, out, pattern, dflt, prefix));
                        structure.append(ASCII.getBytes("</fileinclude>\n"));
                    }
                }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.