Example usage for java.net SocketException getMessage

List of usage examples for java.net SocketException getMessage

Introduction

In this page you can find the example usage for java.net SocketException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.apache.hadoop.net.TestNetUtils.java

/**
 * Test that we can't accidentally connect back to the connecting socket due
 * to a quirk in the TCP spec.//from   w w  w .j a  v  a2s  .c o m
 *
 * This is a regression test for HADOOP-6722.
 */
@Test
public void testAvoidLoopbackTcpSockets() throws Exception {
    Configuration conf = new Configuration();

    Socket socket = NetUtils.getDefaultSocketFactory(conf).createSocket();
    socket.bind(new InetSocketAddress("localhost", 0));
    System.err.println("local address: " + socket.getLocalAddress());
    System.err.println("local port: " + socket.getLocalPort());
    try {
        NetUtils.connect(socket, new InetSocketAddress(socket.getLocalAddress(), socket.getLocalPort()), 20000);
        socket.close();
        fail("Should not have connected");
    } catch (ConnectException ce) {
        System.err.println("Got exception: " + ce);
        assertTrue(ce.getMessage().contains("resulted in a loopback"));
    } catch (SocketException se) {
        // Some TCP stacks will actually throw their own Invalid argument
        // exception here. This is also OK.
        assertTrue(se.getMessage().contains("Invalid argument"));
    }
}

From source file:org.squidy.nodes.TUIOTokenListener.java

/**
 * //from   www.ja va  2  s.  c om
 */
protected void startOSCServer() {
    /*
     * try { oscPortOut = new
     * OSCPortOut(InetAddress.getByName(addressOutgoing), portOutgoing); }
     * catch (SocketException e) { throw new
     * ProcessException(e.getMessage(), e); } catch (UnknownHostException e)
     * { throw new ProcessException(e.getMessage(), e); }
     */
    try {
        oscPortIn = new OSCPortIn(portIncoming, endian);
    } catch (SocketException e) {
        throw new ProcessException(e.getMessage(), e);
    }

    oscPortIn.addListener("/tuio/2Dobj", new OSCListener() {

        /*
         * (non-Javadoc)
         * 
         * @see com.illposed.osc.OSCListener#acceptMessages(java.util.Date,
         * com.illposed.osc.OSCMessage[])
         */
        public void acceptMessages(Date time, OSCMessage[] messages) {

            List<DataPosition2D> tokens = new ArrayList<DataPosition2D>(1);

            int fseq = -1;
            for (OSCMessage message : messages) {
                Object[] arguments = message.getArguments();
                if ("fseq".equals(arguments[0])) {
                    fseq = (Integer) arguments[1];
                }
            }

            for (OSCMessage message : messages) {
                Object[] arguments = message.getArguments();

                if ("set".equals(arguments[0])) {

                    int sessionId = (Integer) arguments[1];
                    int markerId = (Integer) arguments[2];
                    float x = (Float) arguments[3];
                    float y = (Float) arguments[4];
                    float angle = (Float) arguments[5];
                    float movementVectorX = (Float) arguments[6];
                    float movementVectorY = (Float) arguments[7];
                    float rotationVector = (Float) arguments[8];
                    float motionAcceleration = (Float) arguments[9];
                    float rotationAcceleration = (Float) arguments[10];

                    DataPosition2D dataPosition2D = new DataPosition2D(TUIO.class, x, y);
                    dataPosition2D.setAttribute(TUIO_ORIGIN_ADDRESS, "/tuio/2Dobj");
                    dataPosition2D.setAttribute(DataConstant.FRAME_SEQUENCE_ID, fseq);
                    dataPosition2D.setAttribute(DataConstant.SESSION_ID, sessionId);
                    dataPosition2D.setAttribute(TUIO_MARKER_ID, markerId);
                    dataPosition2D.setAttribute(TUIO_MOVEMENT_VECTOR_X, movementVectorX);
                    dataPosition2D.setAttribute(TUIO_MOVEMENT_VECTOR_Y, movementVectorY);
                    dataPosition2D.setAttribute(TUIO_ROTATION_VECTOR_A, rotationVector);
                    dataPosition2D.setAttribute(TUIO_ANGLE_A, angle);
                    dataPosition2D.setAttribute(TUIO_ROTATION_ACCELERATION, rotationAcceleration);
                    dataPosition2D.setAttribute(TUIO_MOTION_ACCELERATION, motionAcceleration);
                    tokenUpdated = true;
                    tokenList.clear();
                    tokens.add(dataPosition2D);
                    tokenList.add(dataPosition2D);
                }
            }
            publish(tokens);
        }
    });

    oscPortIn.startListening();
}

From source file:com.rvl.android.getnzb.LocalNZB.java

public void uploadLocalFileFTP(String filename) {
    UPLOADFILENAME = filename;//from   w ww .j  av  a2  s .  co  m

    UPLOADDIALOG = ProgressDialog.show(this, "Please wait...", "Uploading '" + filename + "' to FTP server.");

    SharedPreferences prefs = GetNZB.preferences;
    if (prefs.getString("FTPHostname", "") == "") {
        uploadDialogHandler.sendEmptyMessage(0);
        Toast.makeText(this, "Upload to FTP server not possible. Please check FTP preferences.",
                Toast.LENGTH_LONG).show();
        return;
    }

    new Thread() {

        public void run() {
            SharedPreferences prefs = GetNZB.preferences;
            FTPClient ftp = new FTPClient();

            String replycode = "";
            String FTPHostname = prefs.getString("FTPHostname", "");
            String FTPUsername = prefs.getString("FTPUsername", "anonymous");
            String FTPPassword = prefs.getString("FTPPassword", "my@email.address");
            String FTPPort = prefs.getString("FTPPort", "21");
            String FTPUploadPath = prefs.getString("FTPUploadPath", "~/");
            if (!FTPUploadPath.matches("$/")) {
                Log.d(Tags.LOG, "Adding trailing slash");
                FTPUploadPath += "/";
            }
            String targetFile = FTPUploadPath + UPLOADFILENAME;

            try {

                ftp.connect(FTPHostname, Integer.parseInt(FTPPort));
                if (ftp.login(FTPUsername, FTPPassword)) {

                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                    ftp.enterLocalPassiveMode();
                    File file = new File(getFilesDir() + "/" + UPLOADFILENAME);
                    BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream(file));
                    Log.d(Tags.LOG, "Saving file to:" + targetFile);
                    if (ftp.storeFile(targetFile, buffIn)) {
                        Log.d(Tags.LOG, "FTP: File should be uploaded. Replycode: "
                                + Integer.toString(ftp.getReplyCode()));

                        isUploadedFTP = true;
                    } else {
                        Log.d(Tags.LOG, "FTP: Could not upload file  Replycode: "
                                + Integer.toString(ftp.getReplyCode()));
                        FTPErrorCode = Integer.toString(ftp.getReplyCode());
                        isUploadedFTP = false;
                    }

                    buffIn.close();
                    ftp.logout();
                    ftp.disconnect();

                } else {
                    Log.d(Tags.LOG, "No ftp login");
                }
            } catch (SocketException e) {
                Log.d(Tags.LOG, "ftp(): " + e.getMessage());
                return;
            } catch (IOException e) {
                Log.d(Tags.LOG, "ftp(): " + e.getMessage());
                return;
            }
            if (isUploadedFTP) {
                removeLocalNZBFile(UPLOADFILENAME);
            }

            UPLOADFILENAME = "";
            uploadDialogHandlerFTP.sendEmptyMessage(0);
        }

    }.start();
}

From source file:net.sf.firemox.network.Server.java

/**
 * If this thread was constructed using a separate <code>Runnable</code> run
 * object, then that <code>Runnable</code> object's <code>run</code>
 * method is called; otherwise, this method does nothing and returns.
 * <p>//from   www  .  ja v  a  2  s  .com
 * Subclasses of <code>Thread</code> should override this method.
 * 
 * @see java.lang.Thread#start()
 * @see java.lang.Thread#Thread(java.lang.ThreadGroup, java.lang.Runnable,
 *      java.lang.String)
 * @see java.lang.Runnable#run()
 */
@Override
public void run() {
    // Creating connection socket
    try {
        serverSocket = new ServerSocket(port, 1);
        // enable timeout
        serverSocket.setSoTimeout(2000);

        // accept any client
        clientSocket = null;
        LoaderConsole.beginTask(LanguageManager.getString("wiz_network.creatingconnection"), 2);
        while (clientSocket == null && !cancelling) {
            try {
                clientSocket = serverSocket.accept();
            } catch (SocketException timeout) {
                if (!"socket closed".equals(timeout.getMessage())) {
                    throw timeout;
                }
            } catch (SocketTimeoutException timeout) {
                /*
                 * timeout of 'accept()' method, nothing to do, we look if we're still
                 * running
                 */
            }
        }

        // stopping?
        if (cancelling) {
            Log.info(LanguageManager.getString("wiz_network.canceledcreation"));
            cancelConnexion();
            return;
        }

        // A client is connecting...
        LoaderConsole.beginTask(LanguageManager.getString("wiz_network.incomming") + " : "
                + clientSocket.getInetAddress().toString(), 5);

        // free these two sockets later
        outBin = clientSocket.getOutputStream();
        inBin = clientSocket.getInputStream();
        // socketListener = new SocketListener(inBin);

        if (passwd != null && passwd.length > 0) {
            // a password is needed to connect to this server
            MToolKit.writeString(outBin, STR_PASSWD);
            if (MToolKit.readString(inBin).equals(new String(passwd))) {
                MToolKit.writeString(outBin, STR_OK);
            } else {
                // wrong password, this client client will be disconnected
                MToolKit.writeString(outBin, STR_WRONGPASSWD);
                // close stream
                IOUtils.closeQuietly(inBin);
                IOUtils.closeQuietly(outBin);
                // free pointers
                outBin = null;
                inBin = null;
            }
        } else {
            MToolKit.writeString(outBin, STR_OK);
        }

        // check version of client
        String clientVersion = MToolKit.readString(inBin);
        if (IdConst.VERSION.equals(clientVersion)) {
            MToolKit.writeString(outBin, STR_OK);
        } else {
            // two different versions
            MToolKit.writeString(outBin, STR_WRONGVERSION);
            LoaderConsole.beginTask(LanguageManager.getString("wiz_network.differentversionClientpb") + " ("
                    + clientVersion + ")", 10);
            IOUtils.closeQuietly(inBin);
            IOUtils.closeQuietly(outBin);
            // free pointers
            outBin = null;
            inBin = null;
        }

        if (outBin != null) {

            // enter in the main loop
            // Opponent is ...
            String clientName = MToolKit.readString(inBin);
            LoaderConsole.beginTask(LanguageManager.getString("wiz_network.opponentis") + clientName, 10);
            // I am ...
            MToolKit.writeString(outBin, nickName);

            // exchange shared string settings
            ((You) StackManager.PLAYERS[0]).sendSettings(outBin);
            ((Opponent) StackManager.PLAYERS[1]).readSettings(clientName, nickName, inBin);

            // stopping?
            if (cancelling) {
                cancelConnexion();
                return;
            }

            // set and send the random seed
            long seed = MToolKit.random.nextLong();
            MToolKit.random.setSeed(seed);
            MToolKit.writeString(outBin, Long.toString(seed));
            Log.info("Seed = " + seed);

            // write mana use option
            PayMana.useMana = Configuration.getBoolean("useMana", true);
            MToolKit.writeString(outBin, PayMana.useMana ? "1" : "0");

            // write opponent response option
            WaitActivatedChoice.opponentResponse = Configuration.getBoolean("opponnentresponse", true);
            MToolKit.writeString(outBin, WaitActivatedChoice.opponentResponse ? "1" : "0");

            // Who starts?
            final StartingOption startingOption = StartingOption.values()[Configuration.getInt("whoStarts",
                    StartingOption.random.ordinal())];
            MToolKit.writeString(outBin, String.valueOf(Configuration.getInt("whoStarts", 0)));
            final boolean serverStarts;
            switch (startingOption) {
            case random:
            default:
                serverStarts = MToolKit.random.nextBoolean();
                break;
            case server:
                serverStarts = true;
                break;
            case client:
                serverStarts = false;
            }

            if (serverStarts) {
                // server begins
                LoaderConsole.beginTask(LanguageManager.getString("wiz_network.youwillstarts") + " (mode="
                        + startingOption.getLocaleValue() + ")", 15);
                StackManager.idActivePlayer = 0;
                StackManager.idCurrentPlayer = 0;
            } else {
                // client begins
                LoaderConsole.beginTask(LanguageManager.getString("wiz_network.opponentwillstart") + " (mode="
                        + startingOption.getLocaleValue() + ")", 15);
                StackManager.idActivePlayer = 1;
                StackManager.idCurrentPlayer = 1;
            }

            // load rules from the MDB file
            dbStream = MdbLoader.loadMDB(MToolKit.mdbFile, StackManager.idActivePlayer);
            TableTop.getInstance().initTbs();

            // receive and validate her/his deck
            LoaderConsole.beginTask(LanguageManager.getString("wiz_network.receivingdeck"), 25);
            readAndValidateOpponentDeck();

            // stopping?
            if (cancelling) {
                cancelConnexion();
                return;
            }

            // send our deck
            LoaderConsole.beginTask(LanguageManager.getString("wiz_network.sendingdeck"), 55);
            deck.send(outBin);
            StackManager.PLAYERS[0].zoneManager.giveCards(deck, dbStream);

            // stopping?
            if (cancelling) {
                cancelConnexion();
                return;
            }

            MToolKit.writeString(outBin, "%EOF%");

            // free resources
            outBin.flush();

            // stopping?
            if (cancelling) {
                cancelConnexion();
                return;
            }

            initBigPipe();
            MagicUIComponents.magicForm.initGame();
        }
    } catch (Throwable e) {
        NetworkActor.cancelling = true;
        LoaderConsole.endTask();
        cancelConnexion();
        JOptionPane.showMessageDialog(MagicUIComponents.magicForm,
                LanguageManager.getString("wiz_server.error") + " : " + e.getMessage(),
                LanguageManager.getString("error"), JOptionPane.WARNING_MESSAGE);
        Log.error(e);
        return;
    }
}

From source file:org.alfresco.web.app.servlet.BaseTemplateContentServlet.java

/**
 * Processes the template request using the current context i.e. no
 * authentication checks are made, it is presumed they have already
 * been done.//from   w ww . j ava 2s  .c o  m
 * 
 * @param req The HTTP request
 * @param res The HTTP response
 * @param redirectToLogin Flag to determine whether to redirect to the login
 *                        page if the user does not have the correct permissions
 */
protected void processTemplateRequest(HttpServletRequest req, HttpServletResponse res, boolean redirectToLogin)
        throws ServletException, IOException {
    Log logger = getLogger();
    String uri = req.getRequestURI();

    if (logger.isDebugEnabled()) {
        String queryString = req.getQueryString();
        logger.debug("Processing URL: " + uri
                + ((queryString != null && queryString.length() > 0) ? ("?" + queryString) : ""));
    }

    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();

    t.nextToken(); // skip servlet name

    NodeRef nodeRef = null;
    NodeRef templateRef = null;

    try {
        String contentPath = req.getParameter(ARG_CONTEXT_PATH);
        if (contentPath != null && contentPath.length() != 0) {
            // process the name based path to resolve the NodeRef
            PathRefInfo pathInfo = resolveNamePath(getServletContext(), contentPath);

            nodeRef = pathInfo.NodeRef;
        } else if (tokenCount > 3) {
            // get NodeRef to the content from the URL elements
            StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
            nodeRef = new NodeRef(storeRef, t.nextToken());
        }

        // get NodeRef to the template if supplied
        String templatePath = req.getParameter(ARG_TEMPLATE_PATH);
        if (templatePath != null && templatePath.length() != 0) {
            // process the name based path to resolve the NodeRef
            PathRefInfo pathInfo = resolveNamePath(getServletContext(), templatePath);

            templateRef = pathInfo.NodeRef;
        } else if (tokenCount >= 7) {
            StoreRef storeRef = new StoreRef(t.nextToken(), t.nextToken());
            templateRef = new NodeRef(storeRef, t.nextToken());
        }
    } catch (AccessDeniedException err) {
        if (redirectToLogin) {
            if (logger.isDebugEnabled())
                logger.debug("Redirecting to login page...");

            redirectToLoginPage(req, res, getServletContext());
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Returning 403 Forbidden error...");

            res.sendError(HttpServletResponse.SC_FORBIDDEN);
        }

        return;
    }

    // if no context is specified, use the template itself
    // TODO: should this default to something else?
    if (nodeRef == null && templateRef != null) {
        nodeRef = templateRef;
    }

    if (nodeRef == null) {
        throw new TemplateException("Not enough elements supplied in URL or no 'path' argument specified.");
    }

    // get the services we need to retrieve the content
    ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
    NodeService nodeService = serviceRegistry.getNodeService();
    TemplateService templateService = serviceRegistry.getTemplateService();
    PermissionService permissionService = serviceRegistry.getPermissionService();

    // check that the user has at least READ access on any nodes - else redirect to the login page
    if (permissionService.hasPermission(nodeRef, PermissionService.READ) == AccessStatus.DENIED
            || (templateRef != null && permissionService.hasPermission(templateRef,
                    PermissionService.READ) == AccessStatus.DENIED)) {
        if (redirectToLogin) {
            if (logger.isDebugEnabled())
                logger.debug("Redirecting to login page...");

            redirectToLoginPage(req, res, getServletContext());
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Returning 403 Forbidden error...");

            res.sendError(HttpServletResponse.SC_FORBIDDEN);
        }

        return;
    }

    String mimetype = MIMETYPE_HTML;
    if (req.getParameter(ARG_MIMETYPE) != null) {
        mimetype = req.getParameter(ARG_MIMETYPE);
    }
    res.setContentType(mimetype);

    try {
        UserTransaction txn = null;
        try {
            txn = serviceRegistry.getTransactionService().getUserTransaction(true);
            txn.begin();

            // if template not supplied, then use the default against the node
            if (templateRef == null) {
                if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_TEMPLATABLE)) {
                    templateRef = (NodeRef) nodeService.getProperty(nodeRef, ContentModel.PROP_TEMPLATE);
                }
                if (templateRef == null) {
                    throw new TemplateException(
                            "Template reference not set against node or not supplied in URL.");
                }
            }

            // create the model - put the supplied noderef in as space/document as appropriate
            Map<String, Object> model = getModel(serviceRegistry, req, templateRef, nodeRef);

            // process the template against the node content directly to the response output stream
            // assuming the repo is capable of streaming in chunks, this should allow large files
            // to be streamed directly to the browser response stream.
            try {
                templateService.processTemplate(templateRef.toString(), model, res.getWriter());

                // commit the transaction
                txn.commit();
            } catch (SocketException e) {
                if (e.getMessage().contains("ClientAbortException")) {
                    // the client cut the connection - our mission was accomplished apart from a little error message
                    logger.error("Client aborted stream read:\n   node: " + nodeRef + "\n   template: "
                            + templateRef);
                    try {
                        if (txn != null) {
                            txn.rollback();
                        }
                    } catch (Exception tex) {
                    }
                } else {
                    throw e;
                }
            } finally {
                res.getWriter().close();
            }
        } catch (Throwable txnErr) {
            try {
                if (txn != null) {
                    txn.rollback();
                }
            } catch (Exception tex) {
            }
            throw txnErr;
        }
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException("Error during template servlet processing: " + err.getMessage(),
                err);
    }
}

From source file:com.cws.esolutions.agent.processors.impl.ServiceCheckProcessorImpl.java

public ServiceCheckResponse runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException {
    final String methodName = IServiceCheckProcessor.CNAME
            + "#runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException";

    if (DEBUG) {/*from   w w  w . ja  v  a 2  s .c  o  m*/
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServiceCheckRequest: {}", request);
    }

    int exitCode = -1;
    Socket socket = null;
    File sourceFile = null;
    CommandLine command = null;
    BufferedWriter writer = null;
    ExecuteStreamHandler streamHandler = null;
    ByteArrayOutputStream outputStream = null;
    ServiceCheckResponse response = new ServiceCheckResponse();

    final DefaultExecutor executor = new DefaultExecutor();
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000);
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try {
        switch (request.getRequestType()) {
        case NETSTAT:
            sourceFile = scriptConfig.getScripts().get("netstat");

            if (DEBUG) {
                DEBUGGER.debug("sourceFile: {}", sourceFile);
            }

            if (!(sourceFile.canExecute())) {
                throw new ServiceCheckException(
                        "Script file either does not exist or cannot be executed. Cannot continue.");
            }

            command = CommandLine.parse(sourceFile.getAbsolutePath());

            if (request.getPortNumber() != 0) {
                command.addArgument(String.valueOf(request.getPortNumber()), true);
            }

            if (DEBUG) {
                DEBUGGER.debug("CommandLine: {}", command);
            }

            outputStream = new ByteArrayOutputStream();
            streamHandler = new PumpStreamHandler(outputStream);

            executor.setWatchdog(watchdog);
            executor.setStreamHandler(streamHandler);

            if (DEBUG) {
                DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
                DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
                DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
                DEBUGGER.debug("DefaultExecutor: {}", executor);
            }

            executor.execute(command, resultHandler);

            resultHandler.waitFor();
            exitCode = resultHandler.getExitValue();

            if (DEBUG) {
                DEBUGGER.debug("exitCode: {}", exitCode);
            }

            writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log"));
            writer.write(outputStream.toString());
            writer.flush();

            response.setResponseData(outputStream.toString());

            if (executor.isFailure(exitCode)) {
                response.setRequestStatus(AgentStatus.FAILURE);
            } else {
                response.setRequestStatus(AgentStatus.SUCCESS);
            }

            break;
        case REMOTEDATE:
            response.setRequestStatus(AgentStatus.SUCCESS);
            response.setResponseData(System.currentTimeMillis());

            break;
        case TELNET:
            response = new ServiceCheckResponse();

            int targetPort = request.getPortNumber();
            String targetServer = request.getTargetHost();

            if (DEBUG) {
                DEBUGGER.debug("Target port: {}", targetPort);
                DEBUGGER.debug("Target server: {}", targetServer);
            }

            if (targetPort == 0) {
                throw new ServiceCheckException("Target port number was not assigned. Cannot action request.");
            }

            final String CRLF = "\r\n";
            final String TERMINATE_TELNET = "^]";

            synchronized (new Object()) {
                InetSocketAddress socketAddress = new InetSocketAddress(targetServer, targetPort);

                socket = new Socket();
                socket.setSoTimeout(IServiceCheckProcessor.CONNECT_TIMEOUT);
                socket.setSoLinger(false, 0);
                socket.setKeepAlive(false);

                try {
                    socket.connect(socketAddress, IServiceCheckProcessor.CONNECT_TIMEOUT);

                    if (!(socket.isConnected())) {
                        throw new ConnectException("Failed to connect to host " + targetServer + " on port "
                                + request.getPortNumber());
                    }

                    PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);
                    pWriter.println(TERMINATE_TELNET + CRLF);
                    pWriter.flush();
                    pWriter.close();

                    response.setRequestStatus(AgentStatus.SUCCESS);
                    response.setResponseData("Telnet connection to " + targetServer + " on port "
                            + request.getPortNumber() + " successful.");
                } catch (ConnectException cx) {
                    response.setRequestStatus(AgentStatus.FAILURE);
                    response.setResponseData("Telnet connection to " + targetServer + " on port "
                            + request.getPortNumber() + " failed with message: " + cx.getMessage());
                }
            }

            break;
        case PROCESSLIST:
            sourceFile = scriptConfig.getScripts().get("processList");

            if (DEBUG) {
                DEBUGGER.debug("sourceFile: {}", sourceFile);
            }

            if (!(sourceFile.canExecute())) {
                throw new ServiceCheckException(
                        "Script file either does not exist or cannot be executed. Cannot continue.");
            }

            command = CommandLine.parse(sourceFile.getAbsolutePath());

            if (request.getPortNumber() != 0) {
                command.addArgument(String.valueOf(request.getPortNumber()), true);
            }

            if (DEBUG) {
                DEBUGGER.debug("CommandLine: {}", command);
            }

            outputStream = new ByteArrayOutputStream();
            streamHandler = new PumpStreamHandler(outputStream);

            executor.setWatchdog(watchdog);
            executor.setStreamHandler(streamHandler);

            if (DEBUG) {
                DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
                DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
                DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
                DEBUGGER.debug("DefaultExecutor: {}", executor);
            }

            executor.execute(command, resultHandler);

            resultHandler.waitFor();
            exitCode = resultHandler.getExitValue();

            if (DEBUG) {
                DEBUGGER.debug("exitCode: {}", exitCode);
            }

            writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log"));
            writer.write(outputStream.toString());
            writer.flush();

            response.setResponseData(outputStream.toString());

            if (executor.isFailure(exitCode)) {
                response.setRequestStatus(AgentStatus.FAILURE);
            } else {
                response.setRequestStatus(AgentStatus.SUCCESS);
            }

            break;
        default:
            // unknown operation
            throw new ServiceCheckException("No valid operation was specified");
        }
    } catch (UnknownHostException uhx) {
        ERROR_RECORDER.error(uhx.getMessage(), uhx);

        throw new ServiceCheckException(uhx.getMessage(), uhx);
    } catch (SocketException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new ServiceCheckException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new ServiceCheckException(iox.getMessage(), iox);
    } catch (InterruptedException ix) {
        ERROR_RECORDER.error(ix.getMessage(), ix);

        throw new ServiceCheckException(ix.getMessage(), ix);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }

            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return response;
}

From source file:com.kyne.webby.rtk.web.Connection.java

@Override
public void run() {
    InputStream in = null;/*from   w  w w .j  a  v a2s.c  o m*/
    try {
        in = this.clientSocket.getInputStream();
        String url = null;
        String params = null;

        final StringBuffer buff = new StringBuffer();
        final int b = in.read();
        if (b < 0) {
            return;
        }
        buff.appendCodePoint(b);
        while (0 != in.available()) {
            buff.appendCodePoint(in.read());
        }
        final String httpContent = buff.toString();
        final StringTokenizer tokenizer = new StringTokenizer(httpContent, "\n");
        final String firstLine = tokenizer.nextToken();
        final String[] splittedFirstLine = firstLine.split(" ");
        if (splittedFirstLine.length > 1) {
            final String requestUrl = (firstLine.split(" "))[1]; //GET /url?params HTTP/1.X   or   //POST /url HTTP/1.X
            final Matcher result = this.urlRegex.matcher(requestUrl);
            if (result.find()) {
                url = result.group(1);
                params = result.group(2);
            } else {
                LogHelper.warn("Invalid URL format : " + requestUrl);
            }
            if (httpContent.startsWith("POST")) {
                String lastLine = null;
                while (tokenizer.hasMoreTokens()) {
                    lastLine = tokenizer.nextToken();
                }
                params = "?" + lastLine;
            }
        } else {
            LogHelper.warn("Empty Request with HttpContent = " + httpContent);
        }

        final boolean isAllowedRessource;
        if (url == null) {
            LogHelper.warn("Null url " + url);
            isAllowedRessource = false;
        } else {
            isAllowedRessource = this.isRestrictedUrl(url) || this.isContextualCallUrl(url)
                    || this.webServer.isAllowedRessource(url) || this.isPredefinedUrl(url);
        }
        if (isAllowedRessource) {
            if (url != null && params != null) {
                this.handleRequest(url, params, this.clientSocket);
            }
        } else {
            this.handleRequest("/404", params, clientSocket); //Forward to 404
        }
    } catch (final SocketException e) {
        /* Pics or it didn't happen ! */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
                /**/ }
        }
    }
}

From source file:org.zaproxy.zap.extension.ascanrulesBeta.SQLInjectionPostgresql.java

/**
 * scans for SQL Injection vulnerabilities, using POSTGRES specific syntax. If it doesn't use
 * specifically POSTGRES syntax, it does not belong in here, but in SQLInjection
 *//*  ww  w . j  a v a 2 s  .co  m*/
@Override
public void scan(HttpMessage originalMessage, String paramName, String paramValue) {

    // DEBUG only
    // log.setLevel(org.apache.log4j.Level.DEBUG);
    // this.debugEnabled = true;

    try {
        // Timing Baseline check: we need to get the time that it took the original query, to
        // know if the time based check is working correctly..
        HttpMessage msgTimeBaseline = getNewMsg();
        long originalTimeStarted = System.currentTimeMillis();
        try {
            sendAndReceive(msgTimeBaseline, false); // do not follow redirects
        } catch (java.net.SocketTimeoutException e) {
            // to be expected occasionally, if the base query was one that contains some
            // parameters exploiting time based SQL injection?
            if (this.debugEnabled)
                log.debug("The Base Time Check timed out on [" + msgTimeBaseline.getRequestHeader().getMethod()
                        + "] URL [" + msgTimeBaseline.getRequestHeader().getURI().getURI() + "]");
        } catch (SocketException ex) {
            if (this.debugEnabled)
                log.debug("Caught " + ex.getClass().getName() + " " + ex.getMessage() + " when accessing: "
                        + msgTimeBaseline.getRequestHeader().getURI().toString());
            return; // No need to keep going
        }
        long originalTimeUsed = System.currentTimeMillis() - originalTimeStarted;
        // end of timing baseline check

        int countTimeBasedRequests = 0;

        if (this.debugEnabled)
            log.debug("Scanning URL [" + getBaseMsg().getRequestHeader().getMethod() + "] ["
                    + getBaseMsg().getRequestHeader().getURI() + "], field [" + paramName
                    + "] with original value [" + paramValue + "] for SQL Injection");

        // POSTGRES specific time based SQL injection checks
        for (int timeBasedSQLindex = 0; timeBasedSQLindex < SQL_POSTGRES_TIME_REPLACEMENTS.length && doTimeBased
                && countTimeBasedRequests < doTimeMaxRequests; timeBasedSQLindex++) {
            HttpMessage msgAttack = getNewMsg();
            String newTimeBasedInjectionValue = SQL_POSTGRES_TIME_REPLACEMENTS[timeBasedSQLindex]
                    .replace(ORIG_VALUE_TOKEN, paramValue).replace(SLEEP_TOKEN, Integer.toString(sleep));

            setParameter(msgAttack, paramName, newTimeBasedInjectionValue);

            // send it.
            long modifiedTimeStarted = System.currentTimeMillis();
            try {
                sendAndReceive(msgAttack, false); // do not follow redirects
                countTimeBasedRequests++;
            } catch (java.net.SocketTimeoutException e) {
                // this is to be expected, if we start sending slow queries to the database.
                // ignore it in this case.. and just get the time.
                if (this.debugEnabled)
                    log.debug("The time check query timed out on ["
                            + msgTimeBaseline.getRequestHeader().getMethod() + "] URL ["
                            + msgTimeBaseline.getRequestHeader().getURI().getURI() + "] on field: [" + paramName
                            + "]");
            } catch (SocketException ex) {
                if (this.debugEnabled)
                    log.debug("Caught " + ex.getClass().getName() + " " + ex.getMessage() + " when accessing: "
                            + msgTimeBaseline.getRequestHeader().getURI().toString());
                return; // No need to keep going
            }
            long modifiedTimeUsed = System.currentTimeMillis() - modifiedTimeStarted;

            if (this.debugEnabled)
                log.debug("Time Based SQL Injection test: [" + newTimeBasedInjectionValue + "] on field: ["
                        + paramName + "] with value [" + newTimeBasedInjectionValue + "] took "
                        + modifiedTimeUsed + "ms, where the original took " + originalTimeUsed + "ms");

            if (modifiedTimeUsed >= (originalTimeUsed + (sleep * 1000))) {
                // takes more than 5 (by default) extra seconds => likely time based SQL
                // injection. Raise it
                String extraInfo = Constant.messages.getString(
                        "ascanbeta.sqlinjection.alert.timebased.extrainfo", newTimeBasedInjectionValue,
                        modifiedTimeUsed, paramValue, originalTimeUsed);
                String attack = Constant.messages.getString("ascanbeta.sqlinjection.alert.booleanbased.attack",
                        paramName, newTimeBasedInjectionValue);

                // raise the alert
                bingo(Alert.RISK_HIGH, Alert.CONFIDENCE_MEDIUM, getName() + " - Time Based", getDescription(),
                        getBaseMsg().getRequestHeader().getURI().getURI(), // url
                        paramName, attack, extraInfo, getSolution(), msgAttack);

                if (log.isDebugEnabled()) {
                    log.debug("A likely Time Based SQL Injection Vulnerability has been found with ["
                            + msgAttack.getRequestHeader().getMethod() + "] URL ["
                            + msgAttack.getRequestHeader().getURI().getURI() + "] on field: [" + paramName
                            + "]");
                }
                return;
            } // query took longer than the amount of time we attempted to retard it by
        } // for each time based SQL index
          // end of check for time based SQL Injection

    } catch (InvalidRedirectLocationException e) {
        // Not an error, just means we probably attacked the redirect location
    } catch (Exception e) {
        // Do not try to internationalise this.. we need an error message in any event..
        // if it's in English, it's still better than not having it at all.
        log.error("An error occurred checking a url for POSTGRES SQL Injection vulnerabilities", e);
    }
}

From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java

protected boolean finalizeConnect(NIOClientSocketHandler clientHandler, SocketChannel channel,
        Selector selector) {/*from w  ww.ja va 2  s . c  o m*/
    try {
        // Finish the connection handshake
        channel.finishConnect();

        log.debug("[" + clientHandler.getId() + "] Connected to " + channel.socket().getInetAddress());

        // Unregister connect interest
        removeInterest(channel, SelectionKey.OP_CONNECT, selector);

        return true;
    } catch (SocketException e) {
        log.error("[" + clientHandler.getId() + "] Could not connect to remote server : " + e.getMessage());
        return false;
    } catch (Exception e) {
        log.error("[" + clientHandler.getId() + "] Could not finalize connection", e);
        return false;
    }
}