Java Code Examples for java.nio.ByteBuffer.flip()

The following are Jave code examples for showing how to use flip() of the java.nio.ByteBuffer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: an2linuxclient   File: TlsHelper.java   View Source Code Vote up 6 votes
public static byte[] tlsDecrypt(SSLEngine tlsEngine,
                                ByteBuffer appDataBuf,
                                ByteBuffer netDataBuf,
                                byte[] netData){
    try {
        appDataBuf.clear();
        netDataBuf.clear();
        netDataBuf.put(netData);
        netDataBuf.flip();
        int consumed = tlsEngine.unwrap(netDataBuf, appDataBuf).bytesConsumed();
        while (consumed < netData.length){
            consumed += tlsEngine.unwrap(netDataBuf, appDataBuf).bytesConsumed();
        }
        appDataBuf.flip();
        byte[] appData = new byte[appDataBuf.limit()];
        appDataBuf.get(appData);
        return appData;
    } catch (SSLException e){
        Log.e("TlsHelper", "tlsDecrypt");
        Log.e("StackTrace", Log.getStackTraceString(e));
        return null;
    }
}
 
Example 2
Project: incubator-netbeans   File: FileMapStorage.java   View Source Code Vote up 6 votes
/**
 * Dispose of a ByteBuffer which has been acquired for writing by one of
 * the write methods, writing its contents to the file.
 */
public int write (ByteBuffer bb) throws IOException {
    synchronized (this) {
        if (bb == buffer) {
            buffer = null;
        }
    }
    int position = size();
    int byteCount = bb.position();
    bb.flip();
    FileChannel channel = writeChannel();
    if (channel.isOpen()) { //If a thread was terminated while writing, it will be closed
        Thread.interrupted(); // #186629: must clear interrupt flag or channel will be broken
        channel.write (bb);
        synchronized (this) {
            bytesWritten += byteCount;
            outstandingBufferCount--;
        }
    }
    return position;
}
 
Example 3
Project: directory-ldap-api   File: CertGenerationRequestTest.java   View Source Code Vote up 6 votes
@Test
public void testDecodeEmptySequence()
{
    Asn1Decoder decoder = new Asn1Decoder();

    ByteBuffer bb = ByteBuffer.allocate( 2 );

    bb.put( new byte[]
        { 0x30, 0x00 } ); // CertGenerateObject ::= SEQUENCE {

    CertGenerationContainer container = new CertGenerationContainer();
    bb.flip();

    try
    {
        decoder.decode( bb, container );
        // The PDU with an empty sequence is not allowed
        fail();
    }
    catch ( DecoderException e )
    {
        assertTrue( true );
    }
}
 
Example 4
Project: directory-ldap-api   File: PagedSearchControlTest.java   View Source Code Vote up 5 votes
/**
 * Test encoding of a PagedSearchControl.
 */
@Test
public void testEncodePagedSearchControl() throws Exception
{
    ByteBuffer bb = ByteBuffer.allocate( 0x0B );
    bb.put( new byte[]
        {
            0x30, 0x09, // realSearchControlValue ::= SEQUENCE {
            0x02,
            0x01,
            0x20, // size INTEGER,
            0x04,
            0x04,
            't',
            'e',
            's',
            't' // cookie OCTET STRING,
    } );
    bb.flip();

    PagedResultsDecorator decorator = new PagedResultsDecorator( codec );

    PagedResults pagedSearch = ( PagedResults ) decorator.decode( bb.array() );

    assertEquals( 32, pagedSearch.getSize() );
    assertTrue( Arrays.equals( Strings.getBytesUtf8( "test" ),
        pagedSearch.getCookie() ) );

    bb.flip();

    PagedResultsDecorator ctrl = new PagedResultsDecorator( codec );
    ctrl.setSize( 32 );
    ctrl.setCookie( Strings.getBytesUtf8( "test" ) );

    ByteBuffer buffer = ctrl.encode( ByteBuffer.allocate( ctrl.computeLength() ) );
    String decoded = Strings.dumpBytes( buffer.array() );
    String expected = Strings.dumpBytes( bb.array() );
    assertEquals( expected, decoded );
}
 
Example 5
Project: directory-ldap-api   File: AbandonRequestTest.java   View Source Code Vote up 5 votes
/**
 * Test the decoding of a AbandonRequest with a bad Message Id
 */
@Test
public void testDecodeAbandonRequestBadMessageId()
{
    Asn1Decoder ldapDecoder = new Asn1Decoder();

    ByteBuffer stream = ByteBuffer.allocate( 0x0B );
    stream.put( new byte[]
        { 0x30, 0x09, // LDAPMessage ::=SEQUENCE {
            0x02,
            0x01,
            0x01, // messageID MessageID
            0x50,
            0x01,
            ( byte ) 0xFF // CHOICE { ..., abandonRequest AbandonRequest,...
        // AbandonRequest ::= [APPLICATION 16] MessageID
    } );

    stream.flip();

    // Allocate a LdapMessageContainer Container
    LdapMessageContainer<MessageDecorator<? extends Message>> ldapMessageContainer =
        new LdapMessageContainer<MessageDecorator<? extends Message>>( codec );

    // Decode the PDU
    try
    {
        ldapDecoder.decode( stream, ldapMessageContainer );
    }
    catch ( DecoderException de )
    {
        assertTrue( true );
        return;
    }

    fail( "We should not reach this point" );
}
 
Example 6
Project: ddpush   File: ClientStatMachine.java   View Source Code Vote up 5 votes
private void gen0x11Message(ClientMessage cm, ArrayList<ServerMessage> smList) throws Exception{
	if(message0x11 == 0){
		return;
	}
	byte[] data = new byte[Constant.SERVER_MESSAGE_MIN_LENGTH+8];//13 bytes
	ByteBuffer bb = ByteBuffer.wrap(data);
	bb.put((byte)1);//version
	bb.put(cm.getData()[1]);//app id
	bb.put((byte)ClientStatMachine.CMD_0x11);//cmd
	bb.putShort((short)8);//length 8
	bb.putLong(message0x11);
	bb.flip();
	ServerMessage sm = new ServerMessage(cm.getSocketAddress(), data);
	smList.add(sm);
}
 
Example 7
Project: directory-ldap-api   File: PagedSearchControlTest.java   View Source Code Vote up 5 votes
/**
 * Test encoding of a PagedSearchControl with a negative size
 */
@Test
public void testEncodePagedSearchControlNegativeSize() throws Exception
{
    ByteBuffer bb = ByteBuffer.allocate( 0x0b );
    bb.put( new byte[]
        {
            0x30, 0x09, // realSearchControlValue ::= SEQUENCE {
            0x02,
            0x01,
            ( byte ) 0xFF, // size INTEGER,
            0x04,
            0x04,
            't',
            'e',
            's',
            't' // cookie OCTET STRING,
    } );
    bb.flip();

    PagedResultsDecorator decorator = new PagedResultsDecorator( codec );

    PagedResults pagedSearch = ( PagedResults ) decorator.decode( bb.array() );

    assertEquals( Integer.MAX_VALUE, pagedSearch.getSize() );
    assertTrue( Arrays.equals( Strings.getBytesUtf8( "test" ),
        pagedSearch.getCookie() ) );

    bb.flip();

    PagedResultsDecorator ctrl = new PagedResultsDecorator( codec );
    ctrl.setSize( -1 );
    ctrl.setCookie( Strings.getBytesUtf8( "test" ) );

    ByteBuffer buffer = ctrl.encode( ByteBuffer.allocate( ctrl.computeLength() ) );
    String decoded = Strings.dumpBytes( buffer.array() );
    String expected = Strings.dumpBytes( bb.array() );
    assertEquals( expected, decoded );
}
 
Example 8
Project: openjdk-jdk10   File: EchoService.java   View Source Code Vote up 5 votes
private static void doIt(SocketChannel sc, int closeAfter, int delay) throws IOException {
    ByteBuffer bb = ByteBuffer.allocate(1024);
    int total = 0;
    for (;;) {
        bb.clear();
        int n = sc.read(bb);
        if (n < 0) {
            break;
        }
        total += n;

        // echo
        bb.flip();
        sc.write(bb);

        // close after X bytes?
        if (closeAfter > 0 && total >= closeAfter) {
            break;
        }
    }

    sc.close();
    if (delay > 0) {
        try {
            Thread.currentThread().sleep(delay);
        } catch (InterruptedException x) { }
    }
}
 
Example 9
Project: openjdk-jdk10   File: PipeChannel.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {
    for (int x=0; x<100; x++) {
        SelectorProvider sp = SelectorProvider.provider();
        Pipe p = sp.openPipe();
        Pipe.SinkChannel sink = p.sink();
        Pipe.SourceChannel source = p.source();

        ByteBuffer outgoingdata = ByteBuffer.allocateDirect(10);
        byte[] someBytes = new byte[10];
        generator.nextBytes(someBytes);
        outgoingdata.put(someBytes);
        outgoingdata.flip();

        int totalWritten = 0;
        while (totalWritten < 10) {
            int written = sink.write(outgoingdata);
            if (written < 0)
                throw new Exception("Write failed");
            totalWritten += written;
        }

        ByteBuffer incomingdata = ByteBuffer.allocateDirect(10);
        int totalRead = 0;
        do {
            int bytesRead = source.read(incomingdata);
            if (bytesRead > 0)
                totalRead += bytesRead;
        } while(totalRead < 10);

        for(int i=0; i<10; i++)
            if (outgoingdata.get(i) != incomingdata.get(i))
                throw new Exception("Pipe failed");
        sink.close();
        source.close();
    }
}
 
Example 10
Project: directory-ldap-api   File: SubEntryControlTest.java   View Source Code Vote up 5 votes
/**
 * Test the decoding of a SubEntryControl with a false visibility
 */
@Test
public void testDecodeSubEntryVisibilityFalse() throws Exception
{
    ByteBuffer bb = ByteBuffer.allocate( 0x03 );
    bb.put( new byte[]
        {
            0x01, 0x01, 0x00 // Visibility ::= BOOLEAN
    } );
    bb.flip();

    SubentriesDecorator decorator = new SubentriesDecorator( codec );

    Subentries subentries = ( Subentries ) decorator.decode( bb.array() );

    assertFalse( subentries.isVisible() );

    // test encoding
    try
    {
        ByteBuffer buffer = decorator.encode( ByteBuffer.allocate( decorator.computeLength() ) );
        String expected = Strings.dumpBytes( bb.array() );
        String decoded = Strings.dumpBytes( buffer.array() );
        assertEquals( expected, decoded );
    }
    catch ( EncoderException e )
    {
        fail( e.getMessage() );
    }
}
 
Example 11
Project: spark_deep   File: NioServer.java   View Source Code Vote up 5 votes
public static void handleWrite(SelectionKey key) throws IOException {
	ByteBuffer buf = (ByteBuffer) key.attachment();
	buf.flip();
	SocketChannel sc = (SocketChannel) key.channel();
	while (buf.hasRemaining()) {
		sc.write(buf);
	}
	buf.compact();
}
 
Example 12
Project: ChessMaster   File: RenderUtil.java   View Source Code Vote up 4 votes
static short createIndexBuffer(ByteBuffer buffer, int[] indices) {

		for (int idx : indices) {
			buffer.putShort((short) idx);
		}

		if (buffer.remaining() != 0) {
			throw new RuntimeException("ByteBuffer size and number of arguments do not match");
		}

		buffer.flip();

		BGFXMemory ibhMem = bgfx_make_ref(buffer);

		return bgfx_create_index_buffer(ibhMem, BGFX_BUFFER_NONE);
	}
 
Example 13
Project: jdk8u-jdk   File: Pwrite.java   View Source Code Vote up 4 votes
private static void genericTest() throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.setLength(4);

    blah = File.createTempFile("blah", null);
    blah.deleteOnExit();
    initTestFile(blah);

    RandomAccessFile raf = new RandomAccessFile(blah, "rw");
    FileChannel c = raf.getChannel();

    for (int x=0; x<100; x++) {
        long offset = generator.nextInt(1000);
        ByteBuffer bleck = ByteBuffer.allocateDirect(4);

        // Write known sequence out
        for (byte i=0; i<4; i++) {
            bleck.put(i);
        }
        bleck.flip();
        long originalPosition = c.position();
        int totalWritten = 0;
        while (totalWritten < 4) {
            int written = c.write(bleck, offset);
            if (written < 0)
                throw new Exception("Read failed");
            totalWritten += written;
        }

        long newPosition = c.position();

        // Ensure that file pointer position has not changed
        if (originalPosition != newPosition)
            throw new Exception("File position modified");

        // Attempt to read sequence back in
        bleck = ByteBuffer.allocateDirect(4);
        originalPosition = c.position();
        int totalRead = 0;
        while (totalRead < 4) {
            int read = c.read(bleck, offset);
            if (read < 0)
                throw new Exception("Read failed");
            totalRead += read;
        }
        newPosition = c.position();

        // Ensure that file pointer position has not changed
        if (originalPosition != newPosition)
            throw new Exception("File position modified");

        for (byte i=0; i<4; i++) {
            if (bleck.get(i) != i)
                throw new Exception("Write test failed");
        }
    }
    c.close();
    raf.close();
    blah.delete();
}
 
Example 14
Project: apfloat   File: DiskDataStorage.java   View Source Code Vote up 4 votes
public void transferTo(WritableByteChannel out, long position, long size)
    throws ApfloatRuntimeException
{
    try
    {
        if (out instanceof FileChannel)
        {
            // Optimized transferTo() between two FileChannels
            while (size > 0)
            {
                long count = getFileChannel().transferTo(position, size, out);
                position += count;
                size -= count;
                assert (size >= 0);
            }
        }
        else
        {
            // The DiskChannel transferTo() uses an 8kB buffer, which is too small and inefficient
            // So we use a similar mechanism but with a custom buffer size
            ByteBuffer buffer = getDirectByteBuffer();
            while (size > 0)
            {
                buffer.clear();
                int readCount = (int) Math.min(size, buffer.capacity());
                buffer.limit(readCount);
                readCount = getFileChannel().read(buffer, position);
                buffer.flip();
                while (readCount > 0)
                {
                    int writeCount = out.write(buffer);
                    position += writeCount;
                    size -= writeCount;
                    readCount -= writeCount;
                }
                assert (readCount == 0);
                assert (size >= 0);
            }
        }
    }
    catch (IOException ioe)
    {
        throw new BackingStorageException("Unable to read from file \"" + getFilename() + '\"', ioe);
    }
}
 
Example 15
Project: directory-ldap-api   File: PasswordModifyRequestTest.java   View Source Code Vote up 4 votes
/**
 * Test the decoding of a PasswordModifyRequest with a user identity, and oldPassword and
 * and a newPassword
 */
@Test
public void testDecodePasswordModifyRequestUserIdentityValueOldPasswordValueNewPasswordValue()
{
    Asn1Decoder decoder = new Asn1Decoder();
    ByteBuffer bb = ByteBuffer.allocate( 0x14 );
    bb.put( new byte[]
        { 0x30, 0x12, // PasswordModifyRequest ::= SEQUENCE {
            ( byte ) 0x80,
            0x04, // userIdentity    [0]  OCTET STRING OPTIONAL
            'a',
            'b',
            'c',
            'd',
            ( byte ) 0x81,
            0x04, // oldPassword    [1]  OCTET STRING OPTIONAL
            'e',
            'f',
            'g',
            'h',
            ( byte ) 0x82, // newPassword    [2]  OCTET STRING OPTIONAL
            0x04,
            'i',
            'j',
            'k',
            'l'
    } );

    String decodedPdu = Strings.dumpBytes( bb.array() );
    bb.flip();

    PasswordModifyRequestContainer container = new PasswordModifyRequestContainer();

    try
    {
        decoder.decode( bb, container );
    }
    catch ( DecoderException de )
    {
        de.printStackTrace();
        fail( de.getMessage() );
    }

    PasswordModifyRequest pwdModifyRequest = container.getPwdModifyRequest();
    assertNotNull( pwdModifyRequest.getUserIdentity() );
    assertEquals( "abcd", Strings.utf8ToString( pwdModifyRequest.getUserIdentity() ) );
    assertNotNull( pwdModifyRequest.getOldPassword() );
    assertEquals( "efgh", Strings.utf8ToString( pwdModifyRequest.getOldPassword() ) );
    assertNotNull( pwdModifyRequest.getNewPassword() );
    assertEquals( "ijkl", Strings.utf8ToString( pwdModifyRequest.getNewPassword() ) );

    // Check the length
    assertEquals( 0x14, ( ( PasswordModifyRequestDecorator ) pwdModifyRequest ).computeLengthInternal() );

    // Check the encoding
    try
    {
        ByteBuffer bb1 = ( ( PasswordModifyRequestDecorator ) pwdModifyRequest ).encodeInternal();

        String encodedPdu = Strings.dumpBytes( bb1.array() );

        assertEquals( encodedPdu, decodedPdu );
    }
    catch ( EncoderException ee )
    {
        ee.printStackTrace();
        fail( ee.getMessage() );
    }
}
 
Example 16
Project: directory-ldap-api   File: LdapDecoderTest.java   View Source Code Vote up 4 votes
/**
 * Test the decoding of a partial PDU
 */
@Test
public void testDecodePartial()
{

    Asn1Decoder ldapDecoder = new Asn1Decoder();

    ByteBuffer stream = ByteBuffer.allocate( 16 );
    stream.put( new byte[]
        { 0x30, 0x33, // LDAPMessage ::=SEQUENCE {
            0x02,
            0x01,
            0x01, // messageID MessageID
            0x60,
            0x2E, // CHOICE { ..., bindRequest BindRequest, ...
            // BindRequest ::= APPLICATION[0] SEQUENCE {
            0x02,
            0x01,
            0x03, // version INTEGER (1..127),
            0x04,
            0x1F, // name LDAPDN,
            'u',
            'i',
            'd',
            '=' } );

    stream.flip();

    // Allocate a LdapMessage Container
    LdapMessageContainer<BindRequestDecorator> container = new LdapMessageContainer<BindRequestDecorator>( codec );

    // Decode a BindRequest PDU
    try
    {
        ldapDecoder.decode( stream, container );
    }
    catch ( DecoderException de )
    {
        de.printStackTrace();
        fail( de.getMessage() );
    }

    assertEquals( TLVStateEnum.VALUE_STATE_PENDING, container.getState() );

    // Check the decoded PDU
    BindRequest bindRequest = container.getMessage();

    assertEquals( 1, bindRequest.getMessageId() );
    assertTrue( bindRequest.isVersion3() );
    assertEquals( null, bindRequest.getName() );
    assertTrue( bindRequest.isSimple() );
}
 
Example 17
Project: directory-ldap-api   File: SyncInfoValueControlTest.java   View Source Code Vote up 4 votes
/**
 * Test the decoding of a SyncInfoValue control, syncIdSet choice, no cookie
 * a refreshDeletes flag, an empty UUID set
 */
@Test
public void testDecodeSyncInfoValueControlSyncIdSetNoCookieRefreshDeletesEmptySet() throws Exception
{
    ByteBuffer bb = ByteBuffer.allocate( 0x07 );
    bb.put( new byte[]
        {
            ( byte ) 0xA3, 0x05, // syncInfoValue ::= CHOICE {
                                 //     syncIdSet [3] SEQUENCE {
            0x01,
            0x01,
            0x10, //         refreshDeletes BOOLEAN DEFAULT FALSE,
            0x31,
            0x00, //         syncUUIDs SET OF syncUUID
        } );
    bb.flip();

    SyncInfoValue decorator = new SyncInfoValueDecorator( codec );

    decorator.setType( SynchronizationInfoEnum.SYNC_ID_SET );

    SyncInfoValue syncInfoValue = ( SyncInfoValue ) ( ( SyncInfoValueDecorator ) decorator ).decode( bb.array() );

    assertEquals( SynchronizationInfoEnum.SYNC_ID_SET, syncInfoValue.getType() );
    assertEquals( "", Strings.utf8ToString( syncInfoValue.getCookie() ) );
    assertTrue( syncInfoValue.isRefreshDeletes() );
    assertEquals( 0, syncInfoValue.getSyncUUIDs().size() );

    // Check the encoding
    try
    {
        ByteBuffer buffer = ByteBuffer.allocate( 0x07 );
        buffer.put( new byte[]
            {
                ( byte ) 0xA3, 0x05, // syncInfoValue ::= CHOICE {
                                     //     syncIdSet [3] SEQUENCE {
                0x01,
                0x01,
                ( byte ) 0xFF, //         refreshDeletes BOOLEAN DEFAULT FALSE,
                0x31,
                0x00, //         syncUUIDs SET OF syncUUID
            } );
        buffer.flip();

        ByteBuffer encoded = ( ( SyncInfoValueDecorator ) syncInfoValue ).encode( ByteBuffer
            .allocate( ( ( SyncInfoValueDecorator ) syncInfoValue ).computeLength() ) );
        assertEquals( Strings.dumpBytes( buffer.array() ), Strings.dumpBytes( encoded.array() ) );
    }
    catch ( EncoderException ee )
    {
        fail();
    }
}
 
Example 18
Project: directory-ldap-api   File: ExtendedResponseTest.java   View Source Code Vote up 4 votes
/**
 * Test the decoding of a ExtendedRequest with no name
 */
@Test
public void testDecodeExtendedRequestNoName()
{
    Asn1Decoder ldapDecoder = new Asn1Decoder();

    ByteBuffer stream = ByteBuffer.allocate( 0x0E );

    stream.put( new byte[]
        { 0x30, 0x0C, // LDAPMessage ::= SEQUENCE {
            0x02,
            0x01,
            0x01, // messageID MessageID
            // CHOICE { ..., extendedResp Response, ...
            0x78,
            0x07, // ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
            // COMPONENTS OF LDAPResult,
            0x0A,
            0x01,
            0x00, // LDAPResult ::= SEQUENCE {
            // resultCode ENUMERATED {
            // success (0), ...
            // },
            0x04,
            0x00, // matchedDN LDAPDN,
            0x04,
            0x00 // errorMessage LDAPString,
        // referral [3] Referral OPTIONAL }
        // responseName [0] LDAPOID,
    } );

    String decodedPdu = Strings.dumpBytes( stream.array() );
    stream.flip();

    // Allocate a LdapMessage Container
    LdapMessageContainer<ExtendedResponseDecorator<?>> container =
        new LdapMessageContainer<ExtendedResponseDecorator<?>>( codec );

    // Decode the ExtendedResponse PDU
    try
    {
        ldapDecoder.decode( stream, container );
    }
    catch ( DecoderException de )
    {
        de.printStackTrace();
        fail( de.getMessage() );
    }

    // Check the decoded ExtendedResponse PDU
    ExtendedResponse extendedResponse = container.getMessage();

    assertEquals( 1, extendedResponse.getMessageId() );
    assertEquals( ResultCodeEnum.SUCCESS, extendedResponse.getLdapResult().getResultCode() );
    assertEquals( "", extendedResponse.getLdapResult().getMatchedDn().getName() );
    assertEquals( "", extendedResponse.getLdapResult().getDiagnosticMessage() );

    // Check the encoding
    try
    {
        ByteBuffer bb = encoder.encodeMessage( extendedResponse );

        // Check the length
        assertEquals( 0x0E, bb.limit() );

        String encodedPdu = Strings.dumpBytes( bb.array() );

        assertEquals( encodedPdu, decodedPdu );
    }
    catch ( EncoderException ee )
    {
        ee.printStackTrace();
        fail( ee.getMessage() );
    }
}
 
Example 19
Project: dubbocloud   File: LogTelnetHandler.java   View Source Code Vote up 4 votes
public String telnet(Channel channel, String message) {
    long size = 0 ;
    File file = LoggerFactory.getFile();
    StringBuffer buf = new StringBuffer();
    if (message == null || message.trim().length() == 0) {
        buf.append("EXAMPLE: log error / log 100");
    }else {
        String str[] = message.split(" ");
        if (! StringUtils.isInteger(str[0])){
            LoggerFactory.setLevel(Level.valueOf(message.toUpperCase()));
        } else {
            int SHOW_LOG_LENGTH = Integer.parseInt(str[0]);
            
            if (file != null && file.exists()) {
                try{
                    FileInputStream fis = new FileInputStream(file);
                    try {
                     FileChannel filechannel = fis.getChannel();
                     try {
                      size = filechannel.size();
                      ByteBuffer bb;
                      if (size <= SHOW_LOG_LENGTH) {
                          bb = ByteBuffer.allocate((int) size);
                          filechannel.read(bb, 0);
                      } else {
                          int pos = (int) (size - SHOW_LOG_LENGTH);
                          bb = ByteBuffer.allocate(SHOW_LOG_LENGTH);
                          filechannel.read(bb, pos);
                      }
                      bb.flip();
                      String content = new String(bb.array()).replace("<", "&lt;")
                      .replace(">", "&gt;").replace("\n", "<br/><br/>");
                      buf.append("\r\ncontent:"+content);
                      
                      buf.append("\r\nmodified:"+(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                      .format(new Date(file.lastModified()))));
                      buf.append("\r\nsize:"+size +"\r\n");
                     } finally {
                     	filechannel.close();
                     }
                    } finally {
                    	fis.close();
                    }
                }catch (Exception e) {
                    buf.append(e.getMessage());
                }
            }else {
                size = 0;
                buf.append("\r\nMESSAGE: log file not exists or log appender is console .");
            }
        }
    }
    buf.append("\r\nCURRENT LOG LEVEL:"+ LoggerFactory.getLevel())
    .append("\r\nCURRENT LOG APPENDER:"+ (file == null ? "console" : file.getAbsolutePath()));
    return buf.toString();
}
 
Example 20
Project: directory-ldap-api   File: LdapResultTest.java   View Source Code Vote up 4 votes
/**
 * Test the decoding of a AddResponse with a valid LdapResult
 */
@Test
public void testDecodeAddResponseEmptyResultCodeOK()
{
    Asn1Decoder ldapDecoder = new Asn1Decoder();

    ByteBuffer stream = ByteBuffer.allocate( 0x0E );

    stream.put( new byte[]
        { 0x30, 0x0C, // LDAPMessage ::=SEQUENCE {
            0x02,
            0x01,
            0x01, // messageID MessageID
            0x69,
            0x07, // CHOICE { ..., addResponse AddResponse, ...
            0x0A,
            0x01,
            0x00, // resultCode success
            0x04,
            0x00, // Empty matched Dn
            0x04,
            0x00 // Empty errorMessage
    } );

    String decodedPdu = Strings.dumpBytes( stream.array() );
    stream.flip();

    // Allocate a LdapMessage Container
    LdapMessageContainer<AddResponseDecorator> container =
        new LdapMessageContainer<AddResponseDecorator>( codec );

    // Decode the AddResponse PDU
    try
    {
        ldapDecoder.decode( stream, container );
    }
    catch ( DecoderException de )
    {
        de.printStackTrace();
        fail( de.getMessage() );
    }

    // Check the decoded AddResponse
    AddResponse addResponse = container.getMessage();

    assertEquals( 1, addResponse.getMessageId() );
    assertEquals( ResultCodeEnum.SUCCESS, addResponse.getLdapResult().getResultCode() );
    assertEquals( "", addResponse.getLdapResult().getMatchedDn().getName() );
    assertEquals( "", addResponse.getLdapResult().getDiagnosticMessage() );

    try
    {
        ByteBuffer bb = encoder.encodeMessage( addResponse );

        // Check the length
        assertEquals( 0x0E, bb.limit() );

        String encodedPdu = Strings.dumpBytes( bb.array() );

        assertEquals( encodedPdu, decodedPdu );
    }
    catch ( EncoderException ee )
    {
        ee.printStackTrace();
        fail( ee.getMessage() );
    }
}