Search in sources :

Example 1 with Buffer

use of org.glassfish.grizzly.Buffer in project dubbo by alibaba.

the class GrizzlyCodecAdapter method handleWrite.

@Override
public NextAction handleWrite(FilterChainContext context) throws IOException {
    Connection<?> connection = context.getConnection();
    GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler);
    try {
        // Do not need to close
        ChannelBuffer channelBuffer = ChannelBuffers.dynamicBuffer(1024);
        Object msg = context.getMessage();
        codec.encode(channel, channelBuffer, msg);
        GrizzlyChannel.removeChannelIfDisconnectd(connection);
        Buffer buffer = connection.getTransport().getMemoryManager().allocate(channelBuffer.readableBytes());
        buffer.put(channelBuffer.toByteBuffer());
        buffer.flip();
        buffer.allowBufferDispose(true);
        context.setMessage(buffer);
    } finally {
        GrizzlyChannel.removeChannelIfDisconnectd(connection);
    }
    return context.getInvokeAction();
}
Also used : Buffer(org.glassfish.grizzly.Buffer) ChannelBuffer(com.alibaba.dubbo.remoting.buffer.ChannelBuffer) DynamicChannelBuffer(com.alibaba.dubbo.remoting.buffer.DynamicChannelBuffer) ChannelBuffer(com.alibaba.dubbo.remoting.buffer.ChannelBuffer) DynamicChannelBuffer(com.alibaba.dubbo.remoting.buffer.DynamicChannelBuffer)

Example 2 with Buffer

use of org.glassfish.grizzly.Buffer in project Payara by payara.

the class WSTCPProtocolFilter method handleRead.

@Override
public NextAction handleRead(final FilterChainContext ctx) throws IOException {
    final NIOConnection connection = (NIOConnection) ctx.getConnection();
    if (connector == null) {
        synchronized (sync) {
            if (connector == null) {
                final InetSocketAddress socketAddress = (InetSocketAddress) connection.getPeerAddress();
                final String host = socketAddress.getHostName();
                final int port = socketAddress.getPort();
                LOGGER.log(Level.INFO, LogUtils.SOAPTCP_PROTOCOL_INITIALIZED, port);
                connector = new Connector(host, port, module.getDelegate());
            }
        }
    }
    final Buffer buffer = ctx.getMessage();
    final ByteBuffer byteBuffer = buffer.toByteBuffer();
    final SocketChannel channel = (SocketChannel) connection.getChannel();
    connector.process(byteBuffer, channel);
    return ctx.getStopAction();
}
Also used : Buffer(org.glassfish.grizzly.Buffer) ByteBuffer(java.nio.ByteBuffer) SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) ByteBuffer(java.nio.ByteBuffer) NIOConnection(org.glassfish.grizzly.nio.NIOConnection)

Example 3 with Buffer

use of org.glassfish.grizzly.Buffer in project Payara by payara.

the class HttpProtocolFinder method find.

@Override
public Result find(final PUContext puContext, final FilterChainContext ctx) {
    final Connection connection = ctx.getConnection();
    final Buffer buffer = ctx.getMessage();
    final ParsingState parsingState = parsingStateAttribute.get(connection);
    final int limit = buffer.limit();
    int position;
    int state;
    if (parsingState == null) {
        position = buffer.position();
        state = 0;
    } else {
        position = parsingState.position;
        state = parsingState.state;
    }
    byte c = 0;
    byte c2;
    // Rule b - try to determine the context-root
    while (position < limit) {
        c2 = c;
        c = buffer.get(position++);
        // and the method
        _1: switch(state) {
            case 0:
                // Check method name
                for (int i = 0; i < METHOD_FIRST_LETTERS.length; i++) {
                    if (c == METHOD_FIRST_LETTERS[i]) {
                        state = 1;
                        break _1;
                    }
                }
                return Result.NOT_FOUND;
            case 1:
                // Search for first ' '
                if (c == 0x20) {
                    state = 2;
                }
                break;
            case 2:
                // Search for next ' '
                if (c == 0x20) {
                    state = 3;
                }
                break;
            case 3:
                // Check 'H' part of HTTP/
                if (c == 'H') {
                    state = 4;
                    break;
                }
                return Result.NOT_FOUND;
            case 4:
                // Search for P/ (part of HTTP/)
                if (c == 0x2f && c2 == 'P') {
                    // find SSL preprocessor
                    if (parsingState != null) {
                        parsingStateAttribute.remove(connection);
                    }
                    return Result.FOUND;
                }
                break;
            default:
                return Result.NOT_FOUND;
        }
    }
    if (position >= maxRequestLineSize) {
        return Result.NOT_FOUND;
    }
    if (parsingState == null) {
        parsingStateAttribute.set(connection, new ParsingState(position, state));
    } else {
        parsingState.position = position;
        parsingState.state = state;
    }
    return Result.NEED_MORE_DATA;
}
Also used : Buffer(org.glassfish.grizzly.Buffer) Connection(org.glassfish.grizzly.Connection)

Example 4 with Buffer

use of org.glassfish.grizzly.Buffer in project Payara by payara.

the class VirtualServer method addProbes.

/**
 * Sets all the monitoring probes used in the virtual server
 *
 * @param globalAccessLoggingEnabled
 * @see org.glassfish.grizzly.http.HttpProbe
 */
void addProbes(boolean globalAccessLoggingEnabled) {
    for (final NetworkListener listener : getGrizzlyNetworkListeners()) {
        try {
            final GrizzlyProxy proxy = (GrizzlyProxy) grizzlyService.lookupNetworkProxy(listener);
            if (proxy != null) {
                GenericGrizzlyListener grizzlyListener = (GenericGrizzlyListener) proxy.getUnderlyingListener();
                List<HttpCodecFilter> codecFilters = grizzlyListener.getFilters(HttpCodecFilter.class);
                if (codecFilters == null || codecFilters.isEmpty()) {
                    // if it's AJP listener - it's ok if we didn't find HttpCodecFilter
                    if (grizzlyListener.isAjpEnabled()) {
                        continue;
                    }
                    _logger.log(Level.SEVERE, LogFacade.CODE_FILTERS_NULL, new Object[] { listener.getName(), codecFilters });
                } else {
                    for (HttpCodecFilter codecFilter : codecFilters) {
                        if (codecFilter.getMonitoringConfig().getProbes().length == 0) {
                            HttpProbeImpl httpProbe = new HttpProbeImpl(listener, isAccessLoggingEnabled(globalAccessLoggingEnabled));
                            codecFilter.getMonitoringConfig().addProbes(httpProbe);
                        }
                    }
                }
                grizzlyListener.getTransport().getConnectionMonitoringConfig().addProbes(new ConnectionProbe.Adapter() {

                    RequestProbeProvider requestProbeProvider = webContainer.getRequestProbeProvider();

                    @Override
                    public void onReadEvent(Connection connection, Buffer data, int size) {
                        if (requestProbeProvider != null) {
                            requestProbeProvider.dataReceivedEvent(size, _id);
                        }
                    }

                    @Override
                    public void onWriteEvent(Connection connection, Buffer data, long size) {
                        if (requestProbeProvider != null) {
                            requestProbeProvider.dataSentEvent(size, _id);
                        }
                    }
                });
            } else {
                // check the listener is enabled before spitting out the SEVERE log
                if (Boolean.parseBoolean(listener.getEnabled())) {
                    _logger.log(Level.SEVERE, LogFacade.PROXY_NULL, new Object[] { listener.getName() });
                }
            }
        } catch (Exception ex) {
            _logger.log(Level.SEVERE, LogFacade.ADD_HTTP_PROBES_ERROR, ex);
        }
    }
}
Also used : Buffer(org.glassfish.grizzly.Buffer) GrizzlyProxy(com.sun.enterprise.v3.services.impl.GrizzlyProxy) GenericGrizzlyListener(org.glassfish.grizzly.config.GenericGrizzlyListener) Connection(org.glassfish.grizzly.Connection) HttpCodecFilter(org.glassfish.grizzly.http.HttpCodecFilter) LifecycleException(org.apache.catalina.LifecycleException) ConfigException(org.glassfish.embeddable.web.ConfigException) IOException(java.io.IOException) GlassFishException(org.glassfish.embeddable.GlassFishException) ConnectionProbe(org.glassfish.grizzly.ConnectionProbe) RequestProbeProvider(org.glassfish.web.admin.monitor.RequestProbeProvider) NetworkListener(org.glassfish.grizzly.config.dom.NetworkListener)

Example 5 with Buffer

use of org.glassfish.grizzly.Buffer in project Payara by payara.

the class AdminAdapter method doCommand.

private ActionReport doCommand(String requestURI, Request req, ActionReport report, Payload.Outbound outboundPayload, Subject subject) throws ProcessHttpCommandRequestException {
    if (!requestURI.startsWith(getContextRoot())) {
        String msg = adminStrings.getLocalString("adapter.panic", "Wrong request landed in AdminAdapter {0}", requestURI);
        report.setMessage(msg);
        LogHelper.getDefaultLogger().info(msg);
        return report;
    }
    // wbn handle no command and no slash-suffix
    String command = "";
    if (requestURI.length() > getContextRoot().length() + 1) {
        command = requestURI.substring(getContextRoot().length() + 1);
    }
    String scope = getScope(command);
    command = getCommandAfterScope(command);
    String qs = req.getQueryString();
    final ParameterMap parameters = extractParameters(qs);
    String passwordOptions = req.getHeader("X-passwords");
    if (passwordOptions != null) {
        decodePasswords(parameters, passwordOptions);
    }
    try {
        // If the upload option is present and false, this needs converting to a path
        String uploadValue = parameters.getOne("upload");
        if ("false".equalsIgnoreCase(uploadValue)) {
            Buffer contentBuffer = req.getInputBuffer().getBuffer();
            int capacity = contentBuffer.capacity();
            byte[] path = new byte[capacity];
            for (int i = 0; i < capacity; i++) {
                path[i] = contentBuffer.get(i);
            }
            // path as passed in
            parameters.add("path", new String(path));
            // remove to prevent exception as this is not a param in the command class
            parameters.remove("upload");
        }
        Payload.Inbound inboundPayload = PayloadImpl.Inbound.newInstance(req.getContentType(), req.getInputStream());
        if (aalogger.isLoggable(Level.FINE)) {
            aalogger.log(Level.FINE, "***** AdminAdapter {0}  *****", req.getMethod());
        }
        // or not the upload flag is set.
        if ("true".equalsIgnoreCase(uploadValue)) {
            // This is a file that needs to be extracted
            File extractLocation = new File(domain.getApplicationRoot() + File.separator + "upload-" + inboundPayload.hashCode() + File.separator);
            if (!extractLocation.mkdirs()) {
                aalogger.log(Level.WARNING, strings.getLocalString("payload.mkdirsFailed", "Attempt to create directories for {0} failed; no further information is available. Continuing.", extractLocation.getAbsolutePath()));
            }
            PayloadFilesManager.Perm permFileManager = new PayloadFilesManager.Perm(extractLocation, null, aalogger);
            permFileManager.processParts(inboundPayload);
            parameters.add("path", extractLocation.toString());
            parameters.remove("upload");
        }
        AdminCommand adminCommand = commandRunner.getCommand(scope, command, report, aalogger);
        if (adminCommand == null) {
            // maybe commandRunner already reported the failure?
            if (report.getActionExitCode() == ActionReport.ExitCode.FAILURE)
                return report;
            String message = adminStrings.getLocalString("adapter.command.notfound", "Command {0} not found", command);
            // cound't find command, not a big deal
            aalogger.log(Level.FINE, message);
            report.setMessage(message);
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return report;
        }
        // Validate admin command eTag
        String modelETag = req.getHeader(RemoteRestAdminCommand.COMMAND_MODEL_MATCH_HEADER);
        if (modelETag != null && !commandRunner.validateCommandModelETag(adminCommand, modelETag)) {
            String message = adminStrings.getLocalString("commandmodel.etag.invalid", "Cached command model for command {0} is invalid.", command);
            aalogger.log(Level.FINE, message);
            report.setMessage(message);
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            throw new ProcessHttpCommandRequestException(report, HttpStatus.PRECONDITION_FAILED_412);
        }
        // Execute
        if (validatePrivacy(adminCommand)) {
            // if (adminCommand.getClass().getAnnotation(Visibility.class).privacy().equals(visibility.privacy())) {
            // todo : needs to be changed, we should reuse adminCommand
            CommandRunner.CommandInvocation inv = commandRunner.getCommandInvocation(scope, command, report, subject, parameters.containsKey("notify"));
            inv.parameters(parameters).inbound(inboundPayload).outbound(outboundPayload).execute();
            try {
                // note it has become extraordinarily difficult to change the reporter!
                CommandRunnerImpl.ExecutionContext inv2 = (CommandRunnerImpl.ExecutionContext) inv;
                report = inv2.report();
            } catch (Exception e) {
            }
        } else {
            report.failure(aalogger, adminStrings.getLocalString("adapter.wrongprivacy", "Command {0} does not have {1} visibility", command, privacyClass.getSimpleName().toLowerCase(Locale.ENGLISH)), null);
            return report;
        }
    } catch (ProcessHttpCommandRequestException reqEx) {
        throw reqEx;
    } catch (Throwable t) {
        /*
             * Must put the error information into the report
             * for the client to see it.
             */
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setFailureCause(t);
        report.setMessage(t.getLocalizedMessage());
        report.setActionDescription("Last-chance AdminAdapter exception handler");
    }
    return report;
}
Also used : Buffer(org.glassfish.grizzly.Buffer) ParameterMap(org.glassfish.api.admin.ParameterMap) LoginException(javax.security.auth.login.LoginException) RemoteAdminAccessException(org.glassfish.internal.api.RemoteAdminAccessException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) Payload(org.glassfish.api.admin.Payload) RemoteRestAdminCommand(com.sun.enterprise.admin.remote.RemoteRestAdminCommand) AdminCommand(org.glassfish.api.admin.AdminCommand) PayloadFilesManager(org.glassfish.admin.payload.PayloadFilesManager) File(java.io.File) CommandRunner(org.glassfish.api.admin.CommandRunner)

Aggregations

Buffer (org.glassfish.grizzly.Buffer)11 IOException (java.io.IOException)4 ChannelBuffer (com.alibaba.dubbo.remoting.buffer.ChannelBuffer)2 DynamicChannelBuffer (com.alibaba.dubbo.remoting.buffer.DynamicChannelBuffer)2 ChannelBuffer (org.apache.dubbo.remoting.buffer.ChannelBuffer)2 DynamicChannelBuffer (org.apache.dubbo.remoting.buffer.DynamicChannelBuffer)2 Connection (org.glassfish.grizzly.Connection)2 Channel (com.alibaba.dubbo.remoting.Channel)1 RemoteRestAdminCommand (com.sun.enterprise.admin.remote.RemoteRestAdminCommand)1 GrizzlyProxy (com.sun.enterprise.v3.services.impl.GrizzlyProxy)1 File (java.io.File)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 InetSocketAddress (java.net.InetSocketAddress)1 ByteBuffer (java.nio.ByteBuffer)1 SocketChannel (java.nio.channels.SocketChannel)1 LoginException (javax.security.auth.login.LoginException)1 LifecycleException (org.apache.catalina.LifecycleException)1 Channel (org.apache.dubbo.remoting.Channel)1 PayloadFilesManager (org.glassfish.admin.payload.PayloadFilesManager)1 AdminCommand (org.glassfish.api.admin.AdminCommand)1