Example usage for java.io DataInputStream readLine

List of usage examples for java.io DataInputStream readLine

Introduction

In this page you can find the example usage for java.io DataInputStream readLine.

Prototype

@Deprecated
public final String readLine() throws IOException 

Source Link

Document

See the general contract of the readLine method of DataInput.

Usage

From source file:org.infoglue.igide.helper.http.HTTPTextDocumentListenerEngine.java

private void listen() {
    String errorMessage;/*from www.  ja  va  2s  .c o m*/
    boolean error;
    errorMessage = "";
    error = false;
    try {
        Logger.logConsole("Starting listen thread");
        URLConnection urlConn = url.openConnection();
        urlConn.setConnectTimeout(3000);
        urlConn.setRequestProperty("Connection", "Keep-Alive");
        urlConn.setReadTimeout(0);
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setAllowUserInteraction(false);
        if (urlConn.getHeaderFields().toString().indexOf("401 Unauthorized") > -1) {
            Logger.logConsole("User has no access to the CMS - closing connection");
            throw new AccessControlException("User has no access to the CMS - closing connection");
        }
        String boundary = urlConn.getHeaderField("boundary");
        DataInputStream input = new DataInputStream(urlConn.getInputStream());
        StringBuffer buf = new StringBuffer();
        if (listener != null)
            listener.onConnection(url);
        String str = null;
        while ((str = input.readLine()) != null) {
            if (str.indexOf("XMLNotificationWriter.ping") == -1) {
                if (str.equals(boundary)) {
                    String message = buf.toString();

                    // By checking there is more in the String than the XML declaration we assume the message is valid
                    if (message != null
                            && !message.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").equals("")) {
                        if (listener != null)
                            listener.recieveDocument(buf.toString());
                        else
                            Logger.logConsole((new StringBuilder("NEW DOCUMENT!!\r\n")).append(buf.toString())
                                    .append("\r\n").toString());
                    }
                    buf = new StringBuffer();
                } else {
                    buf.append(str);
                }
            }
        }
        input.close();
    } catch (MalformedURLException me) {
        error = true;
        errorMessage = (new StringBuilder("Faulty CMS-url:")).append(url).toString();
        if (listener != null)
            listener.onException(me);
        else
            System.err.println((new StringBuilder("MalformedURLException: ")).append(me).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (IOException ioe) {
        error = true;
        errorMessage = "Got an I/O-Exception talking to the CMS. Check that it is started and in valid state.";
        Logger.logConsole((new StringBuilder("ioe: ")).append(ioe.getMessage()).toString());
        if (listener != null)
            listener.onException(ioe);
        else
            Logger.logConsole((new StringBuilder("TextDocumentListener cannot connect to: "))
                    .append(url.toExternalForm()).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (AccessControlException ace) {
        error = true;
        errorMessage = "The user you tried to connect with did not have the correct access rights. Check that he/she has roles etc enough to access the CMS";
        Logger.logConsole((new StringBuilder("ioe: ")).append(ace.getMessage()).toString());
        if (listener != null)
            listener.onException(ace);
        else
            Logger.logConsole((new StringBuilder()).append(ace.getMessage()).toString());
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (Exception exception) {
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    } catch (Throwable e) {
        final String errorMessageFinal = errorMessage;
        Logger.logConsole(
                (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString());
        if (!error) {
            if (System.currentTimeMillis() - lastRetry > 20000L) {
                Logger.logConsole("Trying to restart the listener as it was a while since last...");
                lastRetry = System.currentTimeMillis();
                listen();
            }
        } else {
            try {
                if (listener != null)
                    listener.onEndConnection(url);
            } catch (Exception e2) {
                Logger.logConsole(
                        (new StringBuilder("Error ending connection:")).append(e2.getMessage()).toString());
            }
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openError(viewer.getControl().getShell(), "Error",
                            (new StringBuilder()).append(errorMessageFinal).toString());
                }
            });
        }
    }
}

From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java

@SuppressWarnings("deprecation")
public String runAsRoot(String command) {
    String output = new String();

    try {//from   w w  w  .  ja v a 2 s  .c  om
        Process p = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(p.getOutputStream());
        DataInputStream is = new DataInputStream(p.getInputStream());
        os.writeBytes(command + "\n");
        os.flush();

        String line = new String();
        while ((line = is.readLine()) != null) {
            output = output + line;
        }

        os.writeBytes("exit\n");
        os.flush();
    } catch (Throwable e) {
        Log.i(MyApp.TAG, e.getMessage().toString());
    }

    return output;
}

From source file:com.photon.phresco.framework.impl.CIManagerImpl.java

private void setSvnCredential(CIJob job) throws JDOMException, IOException {
    S_LOGGER.debug("Entering Method CIManagerImpl.setSvnCredential");
    try {/*from www  . j a va2  s. c o m*/
        InputStream credentialXml = PhrescoFrameworkFactory.getServiceManager().getCredentialXml();
        SvnProcessor processor = new SvnProcessor(credentialXml);
        DataInputStream in = new DataInputStream(credentialXml);
        while (in.available() != 0) {
            System.out.println(in.readLine());
        }

        in.close();
        processor.changeNodeValue("credentials/entry//userName", job.getUserName());
        processor.changeNodeValue("credentials/entry//password", job.getPassword());

        processor.writeStream(new File(Utility.getJenkinsHome() + File.separator + job.getName()));

        //jenkins home location
        String jenkinsJobHome = System.getenv(JENKINS_HOME);
        StringBuilder builder = new StringBuilder(jenkinsJobHome);
        builder.append(File.separator);

        processor.writeStream(new File(builder.toString() + CI_CREDENTIAL_XML));
    } catch (Exception e) {
        S_LOGGER.error(
                "Entered into the catch block of CIManagerImpl.setSvnCredential " + e.getLocalizedMessage());
    }
}

From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java

@SuppressWarnings("deprecation")
public String runAsUser(String command) {
    String output = new String();

    try {/*from  w w w.java 2 s  .  co  m*/
        Process p = Runtime.getRuntime().exec("sh");
        DataOutputStream os = new DataOutputStream(p.getOutputStream());
        DataInputStream is = new DataInputStream(p.getInputStream());

        os.writeBytes("exec " + command + "\n");
        os.flush();

        String line = new String();
        while ((line = is.readLine()) != null) {
            output = output + line;
        }

        // os.writeBytes("exit\n");
        os.flush();
        p.waitFor();

    } catch (Throwable e) {
        Log.i(MyApp.TAG, e.getMessage().toString());
    }

    return output;
}

From source file:com.photon.phresco.framework.impl.CIManagerImpl.java

public void setMailCredential(CIJob job) {
    S_LOGGER.debug("Entering Method CIManagerImpl.setMailCredential");
    try {/*from w  w w .j  av a 2s.  c o  m*/
        InputStream credentialXml = PhrescoFrameworkFactory.getServiceManager().getMailerXml();
        SvnProcessor processor = new SvnProcessor(credentialXml);
        DataInputStream in = new DataInputStream(credentialXml);
        while (in.available() != 0) {
            System.out.println(in.readLine());
        }

        in.close();
        // Mail have to with jenkins running email address
        InetAddress ownIP = InetAddress.getLocalHost();
        processor.changeNodeValue(CI_HUDSONURL, HTTP_PROTOCOL + PROTOCOL_POSTFIX + ownIP.getHostAddress()
                + COLON + job.getJenkinsPort() + FORWARD_SLASH + CI + FORWARD_SLASH);
        processor.changeNodeValue("smtpAuthUsername", job.getSenderEmailId());
        processor.changeNodeValue("smtpAuthPassword", job.getSenderEmailPassword());
        processor.changeNodeValue("adminAddress", job.getSenderEmailId());

        //jenkins home location
        String jenkinsJobHome = System.getenv(JENKINS_HOME);
        StringBuilder builder = new StringBuilder(jenkinsJobHome);
        builder.append(File.separator);

        processor.writeStream(new File(builder.toString() + CI_MAILER_XML));
    } catch (Exception e) {
        S_LOGGER.error(
                "Entered into the catch block of CIManagerImpl.setMailCredential " + e.getLocalizedMessage());
    }
}

From source file:cit360.sandbox.BackEndMenu.java

public static final void smtpExample() {
    // declaration section:
    // smtpClient: our client socket
    // os: output stream
    // is: input stream
    Socket smtpSocket = null;/* w ww . j  a v  a 2s  . c  om*/
    DataOutputStream os = null;
    DataInputStream is = null;
    // Initialization section:
    // Try to open a socket on port 25
    // Try to open input and output streams
    try {
        smtpSocket = new Socket("localhost", 25);
        os = new DataOutputStream(smtpSocket.getOutputStream());
        is = new DataInputStream(smtpSocket.getInputStream());
    } catch (UnknownHostException e) {
        System.err.println("Did not recognize server: localhost");
    } catch (IOException e) {
        System.err.println("Was not able to open I/O connection to: localhost");
    }
    // If everything has been initialized then we want to write some data
    // to the socket we have opened a connection to on port 25
    if (smtpSocket != null && os != null && is != null) {
        try {

            os.writeBytes("HELO\n");
            os.writeBytes("MAIL From: david.banks0889@gmail.com\n");
            os.writeBytes("RCPT To: david.banks0889@gmail.com\n");
            os.writeBytes("DATA\n");
            os.writeBytes("From: david.banks0889@gmail.com\n");
            os.writeBytes("Subject: TEST\n");
            os.writeBytes("Hi there\n"); // message body
            os.writeBytes("\n.\n");
            os.writeBytes("QUIT");
            // keep on reading from/to the socket till we receive the "Ok" from SMTP,
            // once we received that then we want to break.
            String responseLine;
            while ((responseLine = is.readLine()) != null) {
                System.out.println("Server: " + responseLine);
                if (responseLine.contains("Ok")) {
                    break;
                }
            }
            // clean up:
            // close the output stream
            // close the input stream
            // close the socket
            os.close();
            is.close();
            smtpSocket.close();
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
    }
}

From source file:test.security.ClassSecurityTest.java

public void testAccessDeniedBasicAuthenticationGetXML() throws Exception {
    Class cashKlass = Cash.class;

    if (enableCaGridLoginModule) {
        return;/*  w w  w .  j a v  a2s  . c om*/
    }

    try {
        String searchUrl = getServerURL() + "/GetXML?query=" + cashKlass.getName() + "&" + cashKlass.getName();
        URL url = new URL(searchUrl);
        URLConnection conn = url.openConnection();

        //String base64 = "/O=caBIG/OU=caGrid/OU=Training/OU=Dorian/CN=SDKUser2" + ":" + "Psat123!@#"; //user2 does not have access to the Cash class
        String base64 = "SKUser2" + ":" + "Psat123!@#"; //user2 does not have access to the Cash class
        conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(base64.getBytes())));

        File myFile = new File(cashKlass.getName() + "_test-getxml.xml");

        FileWriter myWriter = new FileWriter(myFile);
        DataInputStream dis = new DataInputStream(conn.getInputStream());

        String s, buffer = "";
        while ((s = (dis.readLine())) != null) {
            myWriter.write(s);
            buffer = buffer + s;
        }

        myWriter.close();

        assertTrue(buffer.indexOf("Access is denied") > 0);
        myFile.delete();

    } catch (Exception e) {
        System.out.println("Exception caught: " + e.getMessage());
        assertTrue(e.getMessage().indexOf("401") > 0); //Server returned HTTP response code: 401
        //fail(e.getMessage());
    }
}

From source file:com.lines.activitys.SettingsActivity.java

/**
 * Set the default selection of all spinners to their
 * /*from www .  j a  v a 2 s.c  om*/
 * @throws IOException
 */
private void populateSpinners() throws IOException {
    File settings = new File(Environment.getExternalStorageDirectory() + "/learnyourlines/.settings.sav");

    InputStream is;
    BufferedInputStream bis;
    DataInputStream dis;

    try {
        is = new FileInputStream(settings);
        bis = new BufferedInputStream(is);
        dis = new DataInputStream(bis);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    defaultScript = dis.readLine();
    for (int i = 0; i < mScripts.getCount(); i++) {
        if (mScripts.getItemAtPosition(i).toString().equals(defaultScript)) {
            mScripts.setSelection(i);
            break;
        }
    }

    defaultPrompts = dis.readLine();
    for (int i = 0; i < mPrompts.getCount(); i++) {
        if (mPrompts.getItemAtPosition(i).toString().equals(defaultPrompts)) {
            mPrompts.setSelection(i);
            break;
        }
    }

    defaultAuto = dis.readLine();
    for (int i = 0; i < mAuto.getCount(); i++) {
        if (mAuto.getItemAtPosition(i).toString().equals(defaultAuto)) {
            mAuto.setSelection(i);
            break;
        }
    }
}

From source file:test.security.ClassSecurityTest.java

/**
 * Uses Get XML query API, which takes a Detached  
 * Criteria object parameter./*from   ww w.j  a va 2  s. c  o m*/
 * Verifies that the results are returned 
 * Verifies size of the result set
 * Verifies that none of the attributes are null 
 * since user1 has access to all target class attributes
 * 
 * @throws Exception
 */
public void testBasicAuthenticationGetXML() throws Exception {
    if (enableCaGridLoginModule) {
        return;
    }
    Class bankKlass = Bank.class;

    try {
        String searchUrl = getServerURL() + "/GetXML?query=" + bankKlass.getName() + "&" + bankKlass.getName();
        URL url = new URL(searchUrl);
        URLConnection conn = url.openConnection();

        //String base64 = "/O=caBIG/OU=caGrid/OU=Training/OU=Dorian/CN=SDKUser1" + ":" + "Psat123!@#";
        String base64 = "SDKUser1" + ":" + "Psat123!@#";
        conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(base64.getBytes())));

        File myFile = new File(bankKlass.getName() + "_test-getxml.xml");
        FileWriter myWriter = new FileWriter(myFile);
        DataInputStream dis = new DataInputStream(conn.getInputStream());

        String s, buffer = null;
        while ((s = dis.readLine()) != null) {
            myWriter.write(s);
            buffer = buffer + s;
        }

        myWriter.close();

        assertTrue(buffer.indexOf("<recordCounter>4</recordCounter>") > 0);

        for (int i = 1; i <= 4; i++) {
            assertTrue(buffer.indexOf(
                    "name=\"gov.nih.nci.cacoresdk.domain.inheritance.childwithassociation.Bank\" recordNumber=\""
                            + i + "\"") > 0);
            assertTrue(buffer.indexOf("<field name=\"id\">" + i + "</field>") > 0);
            if (enableAttributeLevelSecurity) {
                //assertTrue(buffer.indexOf("<field name=\"name\">-</field>") > 0);
                assertTrue(buffer.indexOf("<field name=\"name\">Bank" + i + "</field>") > 0);
            } else {
                assertTrue(buffer.indexOf("<field name=\"name\">Bank" + i + "</field>") > 0);
            }

        }
        myFile.delete();
    } catch (Exception e) {
        fail("Exception caught: " + e.getMessage());
    }
}

From source file:com.wso2telco.PremiumInfoScopeTest.java

/**
 * Gets the token./*from ww  w  .j  ava 2 s .co m*/
 *
 * @param scope the scope
 * @return the token
 */
private String getToken(String scope) {
    Process curlProc;
    String outputString;
    DataInputStream curlIn = null;
    String access_token = null;
    String command = "curl -X POST -H Content-Type:application/x-www-form-urlencoded " + adminUrl
            + "/oauth2/token --insecure --data" + " client_id=" + client_id + "&" + "client_secret="
            + client_secret + "&grant_type=client_credentials&scope=" + scope;
    try {
        curlProc = Runtime.getRuntime().exec(command);

        curlIn = new DataInputStream(curlProc.getInputStream());

        while ((outputString = curlIn.readLine()) != null) {
            JSONObject obj = new JSONObject(outputString);
            access_token = obj.getString("access_token");
        }
    } catch (IOException e) {
        log.error(e);
    } catch (JSONException e) {
        log.error(e);
    }
    return access_token;

}