Example usage for java.io PushbackReader read

List of usage examples for java.io PushbackReader read

Introduction

In this page you can find the example usage for java.io PushbackReader read.

Prototype

public int read() throws IOException 

Source Link

Document

Reads a single character.

Usage

From source file:Main.java

public static void main(String[] args) {

    String s = "from java2s.com";

    StringReader sr = new StringReader(s);

    // create a new PushBack reader based on our string reader
    PushbackReader pr = new PushbackReader(sr, 20);

    try {// w w w  .j  a  v a  2s .com
        // check if the reader is ready
        System.out.println(pr.ready());

        // read the first five chars
        for (int i = 0; i < 5; i++) {
            char c = (char) pr.read();
            System.out.println(c);
        }

        pr.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:net.panthema.BispanningGame.GraphString.java

static int readInt(PushbackReader pr) throws IOException {
    int c;//  w w  w  .  ja v a  2s  . c  om
    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    while ((c = pr.read()) != 0 && (Character.isDigit(c) || c == '-')) {
        ba.write(c);
    }
    pr.unread(c);
    try {
        return Integer.parseInt(ba.toString());
    } catch (NumberFormatException e) {
        throw (new IOException("Error in Graph String: integer format error"));
    }
}

From source file:net.panthema.BispanningGame.GraphString.java

public static MyGraph read_graph(String str) throws IOException {

    StringReader sr = new StringReader(str);
    PushbackReader pr = new PushbackReader(sr);

    MyGraph g = new MyGraph();

    if (pr.read() != 'V')
        throw (new IOException("Error in Graph String: format error"));

    int Vnum = readInt(pr);

    int Vdesc = pr.read();

    if (Vdesc == ':') {
        // read vertex list with positions
        for (int i = 0; i < Vnum; ++i) {

            if (pr.read() != 'i')
                throw (new IOException("Error in Graph String: format error"));

            Integer v = readInt(pr);
            g.addVertex(v);//from ww w . j a  v  a 2s .co m

            Double posx = null, posy = null;

            for (int p = pr.read(); p != '/'; p = pr.read()) {

                if (p == 'x') {
                    posx = (double) readInt(pr);
                } else if (p == 'y') {
                    posy = (double) readInt(pr);
                } else {
                    throw (new IOException("Error in Graph String: unknown attribute"));
                }
            }

            if (posx != null && posy != null) {
                if (g.mInitialLayout == null)
                    g.mInitialLayout = new StaticLayout<Integer, MyEdge>(g);

                g.mInitialLayout.setLocation(v, posx, posy);
            }
        }

        // read terminator of vertex list
        if (pr.read() != ';')
            throw (new IOException("Error in Graph String: format error"));
    } else if (Vdesc == ';') {
        // read anonymous vertex list
        for (int i = 0; i < Vnum; ++i) {
            g.addVertex(i);
        }
    } else {
        throw (new IOException("Error in Graph String: format error"));
    }

    // read edge list

    if (pr.read() != 'E')
        throw (new IOException("Error in Graph String: format error"));

    int Enum = readInt(pr);

    if (pr.read() != ':')
        throw (new IOException("Error in Graph String: format error"));

    for (int i = 0; i < Enum; ++i) {

        if (pr.read() != 'i')
            throw (new IOException("Error in Graph String: format error"));

        Integer ei = readInt(pr);
        MyEdge e = new MyEdge(ei);
        Integer tail = null, head = null;

        for (int p = pr.read(); p != '/'; p = pr.read()) {

            if (p == 't') {
                tail = readInt(pr);
            } else if (p == 'h') {
                head = readInt(pr);
            } else if (p == 'c') {
                e.color = readInt(pr);
            } else {
                throw (new IOException("Error in Graph String: unknown attribute"));
            }
        }

        if (tail == null || head == null)
            throw (new IOException("Error in Graph String: missing tail/head attributes"));

        g.addEdge(e, tail, head);
    }

    if (pr.read() != ';')
        throw (new IOException("Error in Graph String: format error"));

    return g;
}

From source file:ca.uhn.fhir.rest.method.MethodUtil.java

public static MethodOutcome process2xxResponse(FhirContext theContext, int theResponseStatusCode,
        String theResponseMimeType, Reader theResponseReader, Map<String, List<String>> theHeaders) {
    List<String> locationHeaders = new ArrayList<String>();
    List<String> lh = theHeaders.get(Constants.HEADER_LOCATION_LC);
    if (lh != null) {
        locationHeaders.addAll(lh);//from   w  w w  . j a v  a  2 s  .c  o  m
    }
    List<String> clh = theHeaders.get(Constants.HEADER_CONTENT_LOCATION_LC);
    if (clh != null) {
        locationHeaders.addAll(clh);
    }

    MethodOutcome retVal = new MethodOutcome();
    if (locationHeaders != null && locationHeaders.size() > 0) {
        String locationHeader = locationHeaders.get(0);
        BaseOutcomeReturningMethodBinding.parseContentLocation(theContext, retVal, locationHeader);
    }
    if (theResponseStatusCode != Constants.STATUS_HTTP_204_NO_CONTENT) {
        EncodingEnum ct = EncodingEnum.forContentType(theResponseMimeType);
        if (ct != null) {
            PushbackReader reader = new PushbackReader(theResponseReader);

            try {
                int firstByte = reader.read();
                if (firstByte == -1) {
                    BaseOutcomeReturningMethodBinding.ourLog.debug("No content in response, not going to read");
                    reader = null;
                } else {
                    reader.unread(firstByte);
                }
            } catch (IOException e) {
                BaseOutcomeReturningMethodBinding.ourLog.debug("No content in response, not going to read", e);
                reader = null;
            }

            if (reader != null) {
                IParser parser = ct.newParser(theContext);
                IBaseResource outcome = parser.parseResource(reader);
                if (outcome instanceof IBaseOperationOutcome) {
                    retVal.setOperationOutcome((IBaseOperationOutcome) outcome);
                } else {
                    retVal.setResource(outcome);
                }
            }

        } else {
            BaseOutcomeReturningMethodBinding.ourLog.debug("Ignoring response content of type: {}",
                    theResponseMimeType);
        }
    }
    return retVal;
}

From source file:com.ebuddy.cassandra.structure.StructureConverter.java

@SuppressWarnings("fallthrough")
private Object decodeBytes(byte[] bytes) {
    if (bytes.length == 0) {
        return "";
    }/*www. j a  va2 s  .  c  o m*/

    // look for header char to determine if a JSON object or legacy NestedProperties
    PushbackReader reader = new PushbackReader(
            new InputStreamReader(new ByteArrayInputStream(bytes), UTF8_CHARSET));

    try {
        int firstChar = reader.read();
        switch (firstChar) {
        case '\uFFFF':
            // legacy NestedProperties, obsolete and interpreted now as simply a JSON encoded Map or
            // beginning of a list terminator

            // if the second character is \uFFFF then this is a list terminator value and just return it
            int secondChar = reader.read();
            if (secondChar == '\uFFFF') {
                return Types.LIST_TERMINATOR_VALUE;
            }
            if (secondChar == -1) {
                throw new DataFormatException("Found header FFFF but no data");
            }
            reader.unread(secondChar);
            // fall through and read as a JSON object

        case HEADER_CHAR:
            try {
                return JSON_MAPPER.readValue(reader, Object.class);
            } catch (IOException e) {
                throw new DataFormatException("Could not parse JSON", e);
            }

        default:
            // if no special header, then bytes are just a string
            return new String(bytes, UTF8_CHARSET);
        }
    } catch (IOException ioe) {
        throw new DataFormatException("Could read data", ioe);
    }
}

From source file:com.googlecode.awsms.senders.vodafone.VodafoneWebSender.java

/**
 * Check if the user is logged in to www.vodafone.it
 * //from w  ww.  j a  va 2  s  .c  o m
 * @return true if the user is logged in, false otherwise
 * @throws Exception
 */
private boolean isLoggedIn() throws Exception {
    Log.d(TAG, "this.isLoggedIn()");
    Document document;

    try {
        HttpGet request = new HttpGet("https://www.vodafone.it/190/trilogy/jsp/utility/checkUser.jsp");
        HttpResponse response = httpClient.execute(request, httpContext);

        PushbackReader reader = new PushbackReader(new InputStreamReader(response.getEntity().getContent()));

        // fix wrong XML header 
        int first = reader.read();
        while (first != 60)
            first = reader.read();
        reader.unread(first);

        document = new SAXBuilder().build(reader);
        response.getEntity().consumeContent();

    } catch (JDOMException jdom) {
        throw new Exception(context.getString(R.string.WebSenderProtocolError));
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception(context.getString(R.string.WebSenderNetworkError));
    }

    Element root = document.getRootElement();
    Element child = root.getChild("logged-in");
    return child.getValue().equals("true");
}

From source file:com.googlecode.awsms.senders.vodafone.VodafoneWebSender.java

/**
 * Page to be visited before sending a message
 * //from   ww w  .  j a va  2 s  .c om
 * @throws Exception
 */
private void doPrecheck() throws Exception {
    Log.d(TAG, "this.doPrecheck()");
    Document document = null;

    try {
        HttpGet request = new HttpGet("https://www.vodafone.it/190/fsms/precheck.do?channel=VODAFONE_DW");
        HttpResponse response = httpClient.execute(request, httpContext);

        PushbackReader reader = new PushbackReader(new InputStreamReader(response.getEntity().getContent()));

        // fix wrong XML header 
        int first = reader.read();
        while (first != 60)
            first = reader.read();
        reader.unread(first);

        document = new SAXBuilder().build(reader);
        response.getEntity().consumeContent();

    } catch (JDOMException jdom) {
        throw new Exception(context.getString(R.string.WebSenderProtocolError));
    } catch (Exception e) {
        throw new Exception(context.getString(R.string.WebSenderNetworkError));
    }

    Element root = document.getRootElement();
    @SuppressWarnings("unchecked")
    List<Element> children = root.getChildren("e");
    int status = 0, errorcode = 0;
    for (Element child : children) {
        //      Log.d(TAG, child.getAttributeValue("n"));
        //      if (child.getAttributeValue("v") != null)
        //        Log.d(TAG, child.getAttributeValue("v"));
        //      if (child.getValue() != null)
        //        Log.d(TAG, child.getValue());
        if (child.getAttributeValue("n").equals("STATUS"))
            status = Integer.parseInt(child.getAttributeValue("v"));
        if (child.getAttributeValue("n").equals("ERRORCODE"))
            errorcode = Integer.parseInt(child.getAttributeValue("v"));
    }

    Log.d(TAG, "status code: " + status);
    Log.d(TAG, "error code: " + errorcode);
    if (status != 1)
        parseError(errorcode);
}

From source file:com.googlecode.awsms.senders.vodafone.VodafoneWebSender.java

/**
 * Prepare the message to be sent./*from  w w w .j a  v  a2s .  c  om*/
 * 
 * @param sms
 * @throws Exception
 * @returns false if CAPTCHA present
 */
private boolean doPrepare(WebSMS sms) throws Exception {
    Log.d(TAG, "this.doPrepare()");
    Document document;

    try {
        HttpPost request = new HttpPost("https://www.vodafone.it/190/fsms/prepare.do?channel=VODAFONE_DW");
        List<NameValuePair> requestData = new ArrayList<NameValuePair>();
        requestData.add(new BasicNameValuePair("receiverNumber", sms.getReceiverNumber()));
        requestData.add(new BasicNameValuePair("message", sms.getMessage()));
        request.setEntity(new UrlEncodedFormEntity(requestData, HTTP.UTF_8));
        HttpResponse response = httpClient.execute(request, httpContext);

        PushbackReader reader = new PushbackReader(new InputStreamReader(response.getEntity().getContent()));

        // fix wrong XML header 
        int first = reader.read();
        while (first != 60)
            first = reader.read();
        reader.unread(first);

        document = new SAXBuilder().build(reader);
        response.getEntity().consumeContent();

    } catch (JDOMException jdom) {
        throw new Exception(context.getString(R.string.WebSenderProtocolError));
    } catch (Exception e) {
        throw new Exception(context.getString(R.string.WebSenderNetworkError));
    }

    Element root = document.getRootElement();
    @SuppressWarnings("unchecked")
    List<Element> children = root.getChildren("e");
    int status = 0, errorcode = 0;
    for (Element child : children) {
        //      Log.d(TAG, child.getAttributeValue("n"));
        //      if (child.getAttributeValue("v") != null)
        //        Log.d(TAG, child.getAttributeValue("v"));
        //      if (child.getValue() != null)
        //        Log.d(TAG, child.getValue());
        if (child.getAttributeValue("n").equals("STATUS"))
            status = Integer.parseInt(child.getAttributeValue("v"));
        if (child.getAttributeValue("n").equals("ERRORCODE"))
            errorcode = Integer.parseInt(child.getAttributeValue("v"));
        if (child.getAttributeValue("n").equals("CODEIMG")) {
            sms.setCaptchaArray(Base64.decode(child.getValue()));
            return false;
        }
    }

    Log.d(TAG, "status code: " + status);
    Log.d(TAG, "error code: " + errorcode);
    if (status != 1)
        parseError(errorcode);

    return true;
}

From source file:com.googlecode.awsms.senders.vodafone.VodafoneWebSender.java

/**
 * Send the message (after decoding the CAPTCHA)
 * //from w ww  . ja  v a 2 s . co m
 * @param sms
 * @throws Exception
 * @returns false if CAPTCHA still present
 */
private boolean doSend(WebSMS sms) throws Exception {
    Log.d(TAG, "this.doSend()");
    Document document;

    try {
        HttpPost request = new HttpPost("https://www.vodafone.it/190/fsms/send.do?channel=VODAFONE_DW");
        List<NameValuePair> requestData = new ArrayList<NameValuePair>();
        requestData.add(new BasicNameValuePair("verifyCode", sms.getCaptcha()));
        requestData.add(new BasicNameValuePair("receiverNumber", sms.getReceiverNumber()));
        requestData.add(new BasicNameValuePair("message", sms.getMessage()));
        request.setEntity(new UrlEncodedFormEntity(requestData, HTTP.UTF_8));
        HttpResponse response = httpClient.execute(request, httpContext);

        PushbackReader reader = new PushbackReader(new InputStreamReader(response.getEntity().getContent()));

        // fix wrong XML header 
        int first = reader.read();
        while (first != 60)
            first = reader.read();
        reader.unread(first);

        document = new SAXBuilder().build(reader);
        response.getEntity().consumeContent();

    } catch (JDOMException jdom) {
        throw new Exception(context.getString(R.string.WebSenderProtocolError));
    } catch (Exception e) {
        throw new Exception(context.getString(R.string.WebSenderNetworkError));
    }

    Element root = document.getRootElement();
    @SuppressWarnings("unchecked")
    List<Element> children = root.getChildren("e");
    int status = 0, errorcode = 0;
    String returnmsg = null;
    for (Element child : children) {
        //      Log.d(TAG, child.getAttributeValue("n"));
        //      if (child.getAttributeValue("v") != null)
        //        Log.d(TAG, child.getAttributeValue("v"));
        //      if (child.getValue() != null)
        //        Log.d(TAG, child.getValue());
        if (child.getAttributeValue("n").equals("STATUS"))
            status = Integer.parseInt(child.getAttributeValue("v"));
        if (child.getAttributeValue("n").equals("ERRORCODE"))
            errorcode = Integer.parseInt(child.getAttributeValue("v"));
        if (child.getAttributeValue("n").equals("RETURNMSG"))
            returnmsg = child.getValue();
        if (child.getAttributeValue("n").equals("CODEIMG")) {
            sms.setCaptchaArray(Base64.decode(child.getValue()));
            return false;
        }
    }

    Log.d(TAG, "status code: " + status);
    Log.d(TAG, "error code: " + errorcode);
    Log.d(TAG, "return message: " + returnmsg);
    if (status != 1)
        parseError(errorcode);

    return true;
}