Example usage for java.util Scanner useDelimiter

List of usage examples for java.util Scanner useDelimiter

Introduction

In this page you can find the example usage for java.util Scanner useDelimiter.

Prototype

public Scanner useDelimiter(String pattern) 

Source Link

Document

Sets this scanner's delimiting pattern to a pattern constructed from the specified String .

Usage

From source file:org.apache.openaz.xacml.std.json.JSONResponse.java

/**
 * Read characters from the given <code>InputStream</code> and parse them into an XACML
 * {@link org.apache.openaz.xacml.api.Request} object.
 *
 * @param is/* w  w w.  ja  v  a  2s  .co  m*/
 * @return
 * @throws JSONStructureException
 */
public static Response load(InputStream is) throws JSONStructureException {

    // TODO - ASSUME that order of members within an object does not matter (Different from XML, in JSON
    // everything is handled as Maps so order does not matter)

    // ensure shorthand map is set up
    if (shorthandMap == null) {
        initShorthandMap();
    }

    // ensure that we have an instance of the DataTypeFactory for generating AttributeValues by DataType
    if (dataTypeFactory == null) {
        try {
            dataTypeFactory = DataTypeFactory.newInstance();
            if (dataTypeFactory == null) {
                throw new NullPointerException("No DataTypeFactory found");
            }
        } catch (FactoryException e) {
            throw new JSONStructureException("Unable to find DataTypeFactory, e=" + e);
        }
    }

    // create a new Response object to be filled in
    StdMutableResponse stdMutableResponse = null;

    String json = null;
    ObjectMapper mapper = null;
    try {

        // read the inputStream into a buffer (trick found online scans entire input looking for
        // end-of-file)
        java.util.Scanner scanner = new java.util.Scanner(is);
        scanner.useDelimiter("\\A");
        json = scanner.hasNext() ? scanner.next() : "";
        scanner.close();

        mapper = new ObjectMapper().setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

        // TODO - ASSUME that any duplicated component is a bad thing (probably indicating an error in the
        // incoming JSON)
        mapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true);

        Map<?, ?> root = mapper.readValue(json, Map.class);

        //
        // Does the Response exist?
        //
        List<?> resultList = (List<?>) root.remove("Response");
        if (resultList == null) {
            throw new JSONStructureException("No \"Response\" property found.");
        }

        checkUnknown("Top-level message", root);

        stdMutableResponse = new StdMutableResponse();

        // handle each Result object
        for (int resultIndex = 0; resultIndex < resultList.size(); resultIndex++) {
            // each item should be a Map<?,?> containing a Result, otherwise it is an error
            Object resultObj = resultList.get(resultIndex);
            if (resultObj == null || !(resultObj instanceof Map)) {
                throw new JSONStructureException(
                        "Response contains null Result or list instead of Result object");
            }

            StdMutableResult stdMutableResult = new StdMutableResult();

            Map<?, ?> resultMap = (Map<?, ?>) resultObj;

            // Must have a Decision
            Object decisionObject = resultMap.remove("Decision");
            if (decisionObject == null) {
                throw new JSONStructureException("Result must have Decision");
            }
            Decision decision = Decision.get(decisionObject.toString());
            if (decision == null) {
                throw new JSONStructureException(
                        "Unknown value for Decision: '" + decisionObject.toString() + "'");
            }
            stdMutableResult.setDecision(decision);

            // may have Status
            Object statusObject = resultMap.remove("Status");
            if (statusObject != null) {
                if (!(statusObject instanceof Map)) {
                    throw new JSONStructureException(
                            "Status must be an object, not type '" + statusObject.getClass().getName() + "'");
                }
                StdMutableStatus stdMutableStatus = new StdMutableStatus();
                Map<?, ?> statusMap = (Map<?, ?>) statusObject;

                // optional message
                Object messageObject = statusMap.remove("StatusMessage");
                if (messageObject != null) {
                    stdMutableStatus.setStatusMessage(messageObject.toString());
                }

                // optional detail
                Object detailObject = statusMap.remove("StatusDetail");
                if (detailObject != null) {
                    StdMutableStatusDetail statusDetail = new StdMutableStatusDetail();
                    // TODO - PROBLEM: The JSON spec says only that the status Detail is raw XML rather
                    // than a JSON object. Therefore we cannot discriminate what is inside the string we
                    // just got.
                    // TODO Fortunately there is only one thing it can be: a MissingAttributeDetail.
                    // TODO Unfortunately the MissingAttributeDetail contains multiple optional elements
                    // including 0 or more values, which makes it non-trivial to parse the XML
                    // representation.
                    // TODO Unfortunately the JSON spec does not say how the XML is formatted
                    // (with/without whitespace, etc).

                    //
                    // First of all, the String is possible escaped.
                    //
                    // The meaning of "escaped" is defined in section 4.2.3.1 in the JSON spec
                    //
                    String unescapedContent = detailObject.toString().replace("\\\"", "\"");
                    unescapedContent = unescapedContent.replace("\\\\", "\\");

                    // need to add a root element so that the MissingAttributeDetail elements are findable
                    unescapedContent = "<ROOT>" + unescapedContent + "</ROOT>";

                    // logger.info("Escaped content: \n" + unescapedContent);
                    Document doc = null;
                    try (InputStream bis = new ByteArrayInputStream(unescapedContent.getBytes("UTF-8"))) {
                        doc = DOMUtil.loadDocument(bis);
                    } catch (Exception ex) {
                        throw new JSONStructureException(
                                "Unable to parse Content '" + detailObject.toString() + "'");
                    }

                    // ASSUME that this can only be an array of MissingAttributeDetail. Example:
                    // <MissingAttributeDetail
                    // Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"
                    // AttributeId="urn:att:xacml:resource:application:motsid"
                    // DataType="http://www.w3.org/2001/XMLSchema#integer">
                    // <AttributeValue
                    // DataType="http://www.w3.org/2001/XMLSchema#integer">56</AttributeValue>
                    // </MissingAttributeDetail>"
                    Element docElement = doc.getDocumentElement();
                    NodeList missingAttributeDetailList = docElement
                            .getElementsByTagName("MissingAttributeDetail");
                    for (int madNodeIndex = 0; madNodeIndex < missingAttributeDetailList
                            .getLength(); madNodeIndex++) {
                        Node madNode = missingAttributeDetailList.item(madNodeIndex);
                        StdMutableMissingAttributeDetail mutableMAD = new StdMutableMissingAttributeDetail();

                        NamedNodeMap attributeMap = madNode.getAttributes();
                        Node attributeNode = attributeMap.getNamedItem("AttributeId");
                        if (attributeNode == null) {
                            throw new JSONStructureException("MissingAttributeDetail missing AttributeId");
                        }
                        mutableMAD.setAttributeId(new IdentifierImpl(attributeNode.getNodeValue()));
                        Node categoryNode = attributeMap.getNamedItem("Category");
                        if (categoryNode == null) {
                            throw new JSONStructureException("MissingAttributeDetail missing Category");
                        }
                        mutableMAD.setCategory(new IdentifierImpl(categoryNode.getNodeValue()));
                        Node dataTypeNode = attributeMap.getNamedItem("DataType");
                        if (dataTypeNode == null) {
                            throw new JSONStructureException("MissingAttributeDetail missing DataType");
                        }
                        mutableMAD.setDataTypeId(new IdentifierImpl(dataTypeNode.getNodeValue()));
                        Node issuerNode = attributeMap.getNamedItem("Issuer");
                        if (issuerNode != null) {
                            mutableMAD.setIssuer(issuerNode.getNodeValue());
                        }

                        // get any value elements
                        NodeList childNodeList = madNode.getChildNodes();
                        for (int childIndex = 0; childIndex < childNodeList.getLength(); childIndex++) {
                            Node childNode = childNodeList.item(childIndex);
                            if (!childNode.getNodeName().equals("AttributeValue")) {
                                continue;
                            }
                            Node childDataTypeNode = childNode.getAttributes().getNamedItem("DataType");
                            if (childDataTypeNode == null) {
                                throw new JSONStructureException(
                                        "MissingAttributeDetail contains AttributeValue '"
                                                + childNode.getNodeValue() + "' with no DataType");
                            }
                            String dataType = childDataTypeNode.getNodeValue();
                            // this probably is not a shorthand, but look it up anyway. The full Ids are
                            // in the table too.
                            Identifier valueDataTypeId = shorthandMap.get(dataType);
                            if (valueDataTypeId == null) {
                                throw new JSONStructureException(
                                        "MissingAttibuteDetail contains AttributeValue with unknown DataType="
                                                + dataType);
                            }
                            // if Id is known then it is reasonable to do the following without checking
                            DataType<?> valueDataType = dataTypeFactory.getDataType(valueDataTypeId);
                            AttributeValue<?> attributeValue;
                            try {
                                // for some reason the value may be the value of a child of this node
                                // rather than the value of this node itself.
                                Node valueNode = childNode;
                                if (valueNode.hasChildNodes()) {
                                    valueNode = valueNode.getFirstChild();
                                }
                                attributeValue = valueDataType.createAttributeValue(valueNode.getNodeValue());
                            } catch (Exception ex) {
                                throw new JSONStructureException(
                                        "Unable to create AttributeValue from MissingAttributeDetail AttributeValue '"
                                                + childNode.getNodeValue() + "', error was: "
                                                + ex.getMessage());
                            }
                            mutableMAD.addAttributeValue(attributeValue);
                        }

                        statusDetail.addMissingAttributeDetail(mutableMAD);
                    }

                    stdMutableStatus.setStatusDetail(statusDetail);
                }

                // optional StatusCode which may contain recursive child StatusCode
                Object statusCodeObject = statusMap.remove("StatusCode");
                if (statusCodeObject != null) {
                    if (!(statusCodeObject instanceof Map)) {
                        throw new JSONStructureException("StatusCode must be object");
                    }
                    StatusCode statusCode = parseStatusCode((Map<?, ?>) statusCodeObject);
                    stdMutableStatus.setStatusCode(statusCode);
                }

                checkUnknown("Status", statusMap);

                stdMutableResult.setStatus(stdMutableStatus);
            }

            // may have Obligations
            Object obligationsObject = resultMap.remove("Obligations");
            if (obligationsObject != null) {
                parseObligationsOrAdvice(obligationsObject, stdMutableResult, true);
            }

            // may have Advice
            Object adviceObject = resultMap.remove("AssociatedAdvice");
            if (adviceObject != null) {
                parseObligationsOrAdvice(adviceObject, stdMutableResult, false);
            }

            // may have Category (a.k.a Attributes)
            // TODO - POSSIBLE NAME CHANGE - XML core calls this "Attributes", but name in JSON standard
            // is questionable.
            // TODO The variables here are named "Attributes" because that is the internal name in our
            // objects (based on the Core spec).
            Object attributesObject = resultMap.remove("Category");
            if (attributesObject != null) {
                if (!(attributesObject instanceof List)) {
                    throw new JSONStructureException("Category must be list");
                }
                List<?> attributesList = (List<?>) attributesObject;

                for (Object categoryObject : attributesList) {
                    if (categoryObject == null || !(categoryObject instanceof Map)) {
                        throw new JSONStructureException("Category array item must be object");
                    }
                    Map<?, ?> categoryMap = (Map<?, ?>) categoryObject;
                    StdMutableAttributeCategory stdMutableAttributeCategory = new StdMutableAttributeCategory();

                    // mandatory CategoryId
                    Object categoryIdObject = categoryMap.remove("CategoryId");
                    if (categoryIdObject == null) {
                        throw new JSONStructureException("Category array item must contain CategoryId");
                    }
                    Identifier categoryId = new IdentifierImpl(categoryIdObject.toString());

                    stdMutableAttributeCategory.setCategory(categoryId);

                    // optional Attributes
                    Object attributeListObject = categoryMap.remove("Attribute");
                    if (attributeListObject != null) {
                        if (!(attributeListObject instanceof List)) {
                            throw new JSONStructureException("Category memeber Attribute must be list");
                        }
                        List<?> attributeList = (List<?>) attributeListObject;
                        // get each attribute and add to category
                        for (Object attributeMapObject : attributeList) {
                            if (attributeMapObject == null || !(attributeMapObject instanceof Map)) {
                                throw new JSONStructureException(
                                        "Category member Attribute list item must be object");
                            }
                            Map<?, ?> attributeMap = (Map<?, ?>) attributeMapObject;

                            StdMutableAttribute stdMutableAttribute = new StdMutableAttribute();

                            // optional IncludeInResult
                            // TODO - Odd situation!!: We are reading a string representing a Result which
                            // includes Attributes.
                            // TODO In this case, what does it mean if "IncludeInResult=false"?
                            // TODO The Attribute is obviously included in this Result because it is in
                            // the file/string we are reading.
                            // TODO Our choice: Always include the Attribute. If the IncludeInResult is
                            // included in the input, set it's value in the object as directed.
                            // TODO This may cause mismatches between a Result read in and a new text
                            // generated from the internal Result object.
                            Object includeInResultObject = attributeMap.remove("IncludeInResult");
                            // the fact that the attribute is in the input means this should be true
                            stdMutableAttribute.setIncludeInResults(true);
                            if (includeInResultObject != null) {
                                // need to check the value in the input
                                try {
                                    boolean include = DataTypes.DT_BOOLEAN.convert(includeInResultObject)
                                            .booleanValue();
                                    // set the value in the object exactly as directed, whether it makes
                                    // sense or not
                                    stdMutableAttribute.setIncludeInResults(include);
                                } catch (DataTypeException e) {
                                    throw new JSONStructureException(
                                            "Category member Attribute list item has IncludeInResult value '"
                                                    + includeInResultObject.toString()
                                                    + "' which is not boolean");
                                }
                            }

                            // category is not part of Attribute in spec - it is used internally to link
                            // attribute to Category
                            stdMutableAttribute.setCategory(categoryId);

                            // mandatory Id
                            Object aaIdObject = attributeMap.remove("AttributeId");
                            if (aaIdObject == null) {
                                throw new JSONStructureException(
                                        "Category member Attribute list item missing AttributeId");
                            }
                            stdMutableAttribute.setAttributeId(new IdentifierImpl(aaIdObject.toString()));

                            // get the optional DataType so we know what to do with the mandatory value
                            Object dataTypeObject = attributeMap.remove("DataType");
                            Identifier dataTypeId = null;
                            if (dataTypeObject != null) {
                                dataTypeId = shorthandMap.get(dataTypeObject.toString());
                                // if there was a DataType given it must be a real one
                                if (dataTypeId == null) {
                                    throw new JSONStructureException(
                                            "Category member Attribute list item has unknown DataType='"
                                                    + dataTypeObject.toString() + "'");
                                }
                            } else {
                                // if DataType not given, use String
                                dataTypeId = DataTypes.DT_STRING.getId();
                            }

                            // mandatory Value
                            Object valueObject = attributeMap.remove("Value");
                            if (valueObject == null) {
                                throw new JSONStructureException(
                                        "Category member Attribute list item missing Value");
                            }
                            AttributeValue<?> attributeValue = null;
                            try {
                                DataType<?> dataType = new StdDataTypeFactory().getDataType(dataTypeId);
                                if (dataType == DataTypes.DT_XPATHEXPRESSION) {
                                    // XPAthExpressions are complex data types that need special
                                    // translation from the JSON form to the internal form
                                    attributeValue = convertMapToXPathExpression(valueObject);

                                } else {
                                    // everything other than XPathExpressions are simple values that the
                                    // DataTypes know how to handle
                                    attributeValue = dataType.createAttributeValue(valueObject);
                                }
                            } catch (DataTypeException e) {
                                throw new JSONStructureException("Category member Attribute list item Value='"
                                        + valueObject.toString() + "' not of type '" + dataTypeId + "'");
                            }
                            stdMutableAttribute.addValue(attributeValue);

                            // optional Issuer
                            Object issuerObject = attributeMap.remove("Issuer");
                            if (issuerObject != null) {
                                stdMutableAttribute.setIssuer(issuerObject.toString());
                            }

                            checkUnknown("Category Attribute list item", attributeMap);
                            stdMutableAttributeCategory.add(stdMutableAttribute);
                        }
                    }

                    checkUnknown("Category", categoryMap);

                    // if none of the attributes are returned, do not return the category either
                    if (stdMutableAttributeCategory.getAttributes().size() > 0) {
                        stdMutableResult.addAttributeCategory(stdMutableAttributeCategory);
                    }
                }
            }

            // may have PolicyIdentifierList
            Object policyIdObject = resultMap.remove("PolicyIdentifier");
            if (policyIdObject != null) {
                if (!(policyIdObject instanceof Map)) {
                    throw new JSONStructureException("PolicyIdentifier must be object");
                }
                Map<?, ?> policyIdMap = (Map<?, ?>) policyIdObject;

                // optional PolicyIdReference list
                Object policyIdReferenceObject = policyIdMap.remove("PolicyIdReference");
                if (policyIdReferenceObject != null) {
                    parseIdReferences(policyIdReferenceObject, stdMutableResult, false);
                }

                // optional PolicySetIdReferenceList
                Object policySetIdReferenceObject = policyIdMap.remove("PolicySetIdReference");
                if (policySetIdReferenceObject != null) {
                    parseIdReferences(policySetIdReferenceObject, stdMutableResult, true);
                }

                checkUnknown("PolicyIdentifier", policyIdMap);

            }

            checkUnknown("Result", resultMap);

            // add this result to the Response
            stdMutableResponse.add(stdMutableResult);

        }

        return stdMutableResponse;

    } catch (JsonParseException e) {
        throw new JSONStructureException("Unable to parse JSON '" + json + "', exception: " + e, e);
    } catch (JsonMappingException e) {
        throw new JSONStructureException("Unable to map JSON '" + json + "', exception: " + e, e);
    } catch (IOException e) {
        throw new JSONStructureException("Unable to read JSON input, exception: " + e, e);
    }

    // all done
    // return new StdRequest(stdMutableRequest);

    // throw new JSONStructureException("JSONResponse load string and load from file not implemented");
}

From source file:com.amazon.sqs.javamessaging.AmazonSQSExtendedClient.java

private String getTextFromS3(String s3BucketName, String s3Key) {
    GetObjectRequest getObjectRequest = new GetObjectRequest(s3BucketName, s3Key);
    String embeddedText = null;//from w  w w  .  ja va 2 s  .c o m
    S3Object obj = null;
    try {
        obj = clientConfiguration.getAmazonS3Client().getObject(getObjectRequest);
    } catch (AmazonServiceException e) {
        String errorMessage = "Failed to get the S3 object which contains the message payload. Message was not received.";
        LOG.error(errorMessage, e);
        throw new AmazonServiceException(errorMessage, e);
    } catch (AmazonClientException e) {
        String errorMessage = "Failed to get the S3 object which contains the message payload. Message was not received.";
        LOG.error(errorMessage, e);
        throw new AmazonClientException(errorMessage, e);
    }
    try {
        InputStream objContent = obj.getObjectContent();
        java.util.Scanner objContentScanner = new java.util.Scanner(objContent, "UTF-8");
        objContentScanner.useDelimiter("\\A");
        embeddedText = objContentScanner.hasNext() ? objContentScanner.next() : "";
        objContentScanner.close();
        objContent.close();
    } catch (IOException e) {
        String errorMessage = "Failure when handling the message which was read from S3 object. Message was not received.";
        LOG.error(errorMessage, e);
        throw new AmazonClientException(errorMessage, e);
    }
    return embeddedText;
}

From source file:support.plus.reportit.rv.FragmentActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fragment);

    Toolbar toolbar = (Toolbar) findViewById(R.id.fragment_toolbar);
    setSupportActionBar(toolbar);/*from   ww w .j a v a 2  s .  com*/
    toolbar.setTitle("");
    toolbar.setNavigationIcon(R.drawable.ic_back);

    Intent intent = getIntent();

    createCustomAnimation();

    String intfilename = intent.getStringExtra("filename");
    final int weekID = getIntent().getIntExtra("weekID", 0);

    SharedPreferences prefLast = getSharedPreferences("lastSaved", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefLast.edit();
    editor.putString("intfilename", intfilename);
    editor.putInt("weekID", weekID);
    editor.commit();

    TextView filenameText = (TextView) findViewById(R.id.filename);
    final EditText filetag = (EditText) findViewById(R.id.filetag);
    TextView fileauthorboss = (TextView) findViewById(R.id.fileauthorboss);
    Button bStartDate = (Button) findViewById(R.id.bStartDate);
    final EditText filenumber = (EditText) findViewById(R.id.filenumber);
    Button bEndDate = (Button) findViewById(R.id.bEndDate);
    final TextView startDate = (TextView) findViewById(R.id.startDate);
    final TextView endDate = (TextView) findViewById(R.id.endDate);

    bStartDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final SharedPreferences pref = getApplicationContext().getSharedPreferences("buttonsPressed",
                    MODE_APPEND);
            SharedPreferences.Editor editor = pref.edit();
            editor.putBoolean("bstartpressed", true);
            editor.commit();
            DialogFragment newFragment = new DatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");
        }
    });

    bEndDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final SharedPreferences pref = getApplicationContext().getSharedPreferences("buttonsPressed",
                    MODE_PRIVATE);
            SharedPreferences.Editor editor = pref.edit();
            editor.putBoolean("bendpressed", true);
            editor.commit();
            DialogFragment newFragment = new DatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");
        }
    });

    try {
        File mydirectory = new File(Environment.getExternalStorageDirectory() + File.separator + "ReportIt");
        boolean success = true;
        if (!mydirectory.exists()) {
            success = mydirectory.mkdir();
        }
        if (success) {
            File reportsdirectory = new File(Environment.getExternalStorageDirectory() + File.separator
                    + "ReportIt" + File.separator + "Exported PDF's");
            boolean success2 = true;
            if (!reportsdirectory.exists()) {
                success2 = reportsdirectory.mkdir();
            }

        }

    } catch (Exception e) {
    }

    // Declaration weekdays editfields
    // Monday
    final EditText mondayText1 = (EditText) findViewById(R.id.mondayText1);
    final EditText mondayText2 = (EditText) findViewById(R.id.mondayText2);
    final EditText mondayText3 = (EditText) findViewById(R.id.mondayText3);
    final EditText mondayText4 = (EditText) findViewById(R.id.mondayText4);
    final EditText mondayText5 = (EditText) findViewById(R.id.mondayText5);
    final EditText mondayText6 = (EditText) findViewById(R.id.mondayText6);

    final EditText mondayTextTime1 = (EditText) findViewById(R.id.mondayTextTime1);
    final EditText mondayTextTime2 = (EditText) findViewById(R.id.mondayTextTime2);
    final EditText mondayTextTime3 = (EditText) findViewById(R.id.mondayTextTime3);
    final EditText mondayTextTime4 = (EditText) findViewById(R.id.mondayTextTime4);
    final EditText mondayTextTime5 = (EditText) findViewById(R.id.mondayTextTime5);
    final EditText mondayTextTime6 = (EditText) findViewById(R.id.mondayTextTime6);
    // End monday ---- Start tuesday
    final EditText tuesdayText1 = (EditText) findViewById(R.id.tuesdayText1);
    final EditText tuesdayText2 = (EditText) findViewById(R.id.tuesdayText2);
    final EditText tuesdayText3 = (EditText) findViewById(R.id.tuesdayText3);
    final EditText tuesdayText4 = (EditText) findViewById(R.id.tuesdayText4);
    final EditText tuesdayText5 = (EditText) findViewById(R.id.tuesdayText5);
    final EditText tuesdayText6 = (EditText) findViewById(R.id.tuesdayText6);

    final EditText tuesdayTextTime1 = (EditText) findViewById(R.id.tuesdayTextTime1);
    final EditText tuesdayTextTime2 = (EditText) findViewById(R.id.tuesdayTextTime2);
    final EditText tuesdayTextTime3 = (EditText) findViewById(R.id.tuesdayTextTime3);
    final EditText tuesdayTextTime4 = (EditText) findViewById(R.id.tuesdayTextTime4);
    final EditText tuesdayTextTime5 = (EditText) findViewById(R.id.tuesdayTextTime5);
    final EditText tuesdayTextTime6 = (EditText) findViewById(R.id.tuesdayTextTime6);
    // End tuesday ---- Start wednesday
    final EditText wednesdayText1 = (EditText) findViewById(R.id.wednesdayText1);
    final EditText wednesdayText2 = (EditText) findViewById(R.id.wednesdayText2);
    final EditText wednesdayText3 = (EditText) findViewById(R.id.wednesdayText3);
    final EditText wednesdayText4 = (EditText) findViewById(R.id.wednesdayText4);
    final EditText wednesdayText5 = (EditText) findViewById(R.id.wednesdayText5);
    final EditText wednesdayText6 = (EditText) findViewById(R.id.wednesdayText6);

    final EditText wednesdayTextTime1 = (EditText) findViewById(R.id.wednesdayTextTime1);
    final EditText wednesdayTextTime2 = (EditText) findViewById(R.id.wednesdayTextTime2);
    final EditText wednesdayTextTime3 = (EditText) findViewById(R.id.wednesdayTextTime3);
    final EditText wednesdayTextTime4 = (EditText) findViewById(R.id.wednesdayTextTime4);
    final EditText wednesdayTextTime5 = (EditText) findViewById(R.id.wednesdayTextTime5);
    final EditText wednesdayTextTime6 = (EditText) findViewById(R.id.wednesdayTextTime6);
    // End wednesday ---- Start thursday
    final EditText thursdayText1 = (EditText) findViewById(R.id.thursdayText1);
    final EditText thursdayText2 = (EditText) findViewById(R.id.thursdayText2);
    final EditText thursdayText3 = (EditText) findViewById(R.id.thursdayText3);
    final EditText thursdayText4 = (EditText) findViewById(R.id.thursdayText4);
    final EditText thursdayText5 = (EditText) findViewById(R.id.thursdayText5);
    final EditText thursdayText6 = (EditText) findViewById(R.id.thursdayText6);

    final EditText thursdayTextTime1 = (EditText) findViewById(R.id.thursdayTextTime1);
    final EditText thursdayTextTime2 = (EditText) findViewById(R.id.thursdayTextTime2);
    final EditText thursdayTextTime3 = (EditText) findViewById(R.id.thursdayTextTime3);
    final EditText thursdayTextTime4 = (EditText) findViewById(R.id.thursdayTextTime4);
    final EditText thursdayTextTime5 = (EditText) findViewById(R.id.thursdayTextTime5);
    final EditText thursdayTextTime6 = (EditText) findViewById(R.id.thursdayTextTime6);
    // End thursday ---- Start friday
    final EditText fridayText1 = (EditText) findViewById(R.id.fridayText1);
    final EditText fridayText2 = (EditText) findViewById(R.id.fridayText2);
    final EditText fridayText3 = (EditText) findViewById(R.id.fridayText3);
    final EditText fridayText4 = (EditText) findViewById(R.id.fridayText4);
    final EditText fridayText5 = (EditText) findViewById(R.id.fridayText5);
    final EditText fridayText6 = (EditText) findViewById(R.id.fridayText6);

    final EditText fridayTextTime1 = (EditText) findViewById(R.id.fridayTextTime1);
    final EditText fridayTextTime2 = (EditText) findViewById(R.id.fridayTextTime2);
    final EditText fridayTextTime3 = (EditText) findViewById(R.id.fridayTextTime3);
    final EditText fridayTextTime4 = (EditText) findViewById(R.id.fridayTextTime4);
    final EditText fridayTextTime5 = (EditText) findViewById(R.id.fridayTextTime5);
    final EditText fridayTextTime6 = (EditText) findViewById(R.id.fridayTextTime6);
    // End of friday and declaration weekdays editfields

    filenameText.setText(String.valueOf(cutName(intfilename)));

    com.github.clans.fab.FloatingActionButton bexport_pdf = (com.github.clans.fab.FloatingActionButton) findViewById(
            R.id.export_pdf);
    com.github.clans.fab.FloatingActionButton bexport_rtf = (com.github.clans.fab.FloatingActionButton) findViewById(
            R.id.export_rtf);
    com.github.clans.fab.FloatingActionButton bshare_email = (com.github.clans.fab.FloatingActionButton) findViewById(
            R.id.share_email);

    if (bexport_pdf != null) {
        bexport_pdf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int weekID = getIntent().getIntExtra("weekID", 0);
                String filename = String.valueOf(AllReportsRV.itemTexte.get(weekID));
                String RESULT = Environment.getExternalStorageDirectory() + File.separator + "ReportIt"
                        + File.separator + "Exported PDF's" + File.separator + cutName(filename)
                        + getString(R.string.pdf_extension);

                export_pdf_class export_pdf_class = new export_pdf_class(FragmentActivity.this,
                        FragmentActivity.this, weekID, RESULT);

            }
        });
    }

    if (bshare_email != null) {
        bshare_email.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int weekID = getIntent().getIntExtra("weekID", 0);
                String filename = String.valueOf(AllReportsRV.itemTexte.get(weekID));
                String RESULT = Environment.getExternalStorageDirectory() + File.separator + "ReportIt"
                        + File.separator + "Exported PDF's" + File.separator + cutName(filename)
                        + getString(R.string.pdf_extension);

                export_email_class export_email_class = new export_email_class(FragmentActivity.this,
                        FragmentActivity.this, weekID, RESULT);

            }
        });
    }

    if (bexport_rtf != null) {
        bexport_rtf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(FragmentActivity.this, "Coming soon", Toast.LENGTH_LONG).show();
            }
        });
    }

    final SharedPreferences pref = getApplicationContext().getSharedPreferences("userData", MODE_APPEND);
    String TextuserBossNameString = pref.getString("userBoss", "");
    fileauthorboss.setText(getString(R.string.instructor) + String.valueOf(TextuserBossNameString));

    StringBuilder textCatched = new StringBuilder();

    String filename = intfilename;
    Scanner read = null;
    try {
        read = new Scanner(new File(Environment.getExternalStorageDirectory() + File.separator
                + "/ReportIt/Reports" + File.separator + cutName(filename)));

        read.useDelimiter(";;");
        String start, start2, start3, start4, start5;

        while (read.hasNext()) {
            start = read.next();
            filenumber.setText(read.next().toString());
            filetag.setText(read.next().toString());
            startDate.setText(read.next().toString());
            endDate.setText(read.next().toString());
            mondayText1.setText(read.next().toString());
            mondayTextTime1.setText(read.next().toString());
            mondayText2.setText(read.next().toString());
            mondayTextTime2.setText(read.next().toString());
            mondayText3.setText(read.next().toString());
            mondayTextTime3.setText(read.next().toString());
            mondayText4.setText(read.next().toString());
            mondayTextTime4.setText(read.next().toString());
            mondayText5.setText(read.next().toString());
            mondayTextTime5.setText(read.next().toString());
            mondayText6.setText(read.next().toString());
            mondayTextTime6.setText(read.next().toString());

            read.nextLine();
            start2 = read.next();
            tuesdayText1.setText(read.next().toString());
            tuesdayTextTime1.setText(read.next().toString());
            tuesdayText2.setText(read.next().toString());
            tuesdayTextTime2.setText(read.next().toString());
            tuesdayText3.setText(read.next().toString());
            tuesdayTextTime3.setText(read.next().toString());
            tuesdayText4.setText(read.next().toString());
            tuesdayTextTime4.setText(read.next().toString());
            tuesdayText5.setText(read.next().toString());
            tuesdayTextTime5.setText(read.next().toString());
            tuesdayText6.setText(read.next().toString());
            tuesdayTextTime6.setText(read.next().toString());

            read.nextLine();
            start3 = read.next();
            wednesdayText1.setText(read.next().toString());
            wednesdayTextTime1.setText(read.next().toString());
            wednesdayText2.setText(read.next().toString());
            wednesdayTextTime2.setText(read.next().toString());
            wednesdayText3.setText(read.next().toString());
            wednesdayTextTime3.setText(read.next().toString());
            wednesdayText4.setText(read.next().toString());
            wednesdayTextTime4.setText(read.next().toString());
            wednesdayText5.setText(read.next().toString());
            wednesdayTextTime5.setText(read.next().toString());
            wednesdayText6.setText(read.next().toString());
            wednesdayTextTime6.setText(read.next().toString());

            read.nextLine();
            start4 = read.next();
            thursdayText1.setText(read.next().toString());
            thursdayTextTime1.setText(read.next().toString());
            thursdayText2.setText(read.next().toString());
            thursdayTextTime2.setText(read.next().toString());
            thursdayText3.setText(read.next().toString());
            thursdayTextTime3.setText(read.next().toString());
            thursdayText4.setText(read.next().toString());
            thursdayTextTime4.setText(read.next().toString());
            thursdayText5.setText(read.next().toString());
            thursdayTextTime5.setText(read.next().toString());
            thursdayText6.setText(read.next().toString());
            thursdayTextTime6.setText(read.next().toString());

            read.nextLine();
            start5 = read.next();
            fridayText1.setText(read.next().toString());
            fridayTextTime1.setText(read.next().toString());
            fridayText2.setText(read.next().toString());
            fridayTextTime2.setText(read.next().toString());
            fridayText3.setText(read.next().toString());
            fridayTextTime3.setText(read.next().toString());
            fridayText4.setText(read.next().toString());
            fridayTextTime4.setText(read.next().toString());
            fridayText5.setText(read.next().toString());
            fridayTextTime5.setText(read.next().toString());
            fridayText6.setText(read.next().toString());
            fridayTextTime6.setText(read.next().toString());

        }
        read.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

From source file:gdsc.smlm.ij.plugins.SpotAnalysis.java

private boolean resultsWithinBounds(Rectangle bounds) {
    if (resultsWindowShowing()) {
        float minx = bounds.x;
        float maxx = minx + bounds.width;
        float miny = bounds.y;
        float maxy = miny + bounds.height;

        for (int i = 0; i < resultsWindow.getTextPanel().getLineCount(); i++) {
            String line = resultsWindow.getTextPanel().getLine(i);
            Scanner s = new Scanner(line);
            s.useDelimiter("\t");
            s.nextInt();/*from   w ww.  jav a 2 s  .c o  m*/
            float cx = s.nextFloat(); // cx
            float cy = s.nextFloat(); // cy
            s.close();
            if (cx >= minx && cx <= maxx && cy >= miny && cy <= maxy) {
                return true;
            }
        }
    }
    return false;
}

From source file:com.axelor.studio.service.builder.FormBuilderService.java

private Iterator<ViewPanel> sortPanels(List<ViewPanel> viewPanelList) {

    Collections.sort(viewPanelList, new Comparator<ViewPanel>() {

        @Override/*ww w  .  j av a  2 s.c  om*/
        public int compare(ViewPanel panel1, ViewPanel panel2) {
            Scanner scan1 = new Scanner(panel1.getPanelLevel());
            Scanner scan2 = new Scanner(panel2.getPanelLevel());
            scan1.useDelimiter("\\.");
            scan2.useDelimiter("\\.");
            try {
                while (scan1.hasNextInt() && scan2.hasNextInt()) {
                    int v1 = scan1.nextInt();
                    int v2 = scan2.nextInt();
                    if (v1 < v2) {
                        return -1;
                    } else if (v1 > v2) {
                        return 1;
                    }
                }

                if (scan2.hasNextInt()) {
                    return -1;
                }
                if (scan1.hasNextInt()) {
                    return 1;
                }

                return 0;
            } finally {
                scan1.close();
                scan2.close();
            }

        }
    });

    return viewPanelList.iterator();
}

From source file:gdsc.smlm.ij.plugins.SpotAnalysis.java

private void saveTraces() {
    if (!onFrames.isEmpty() && updated) {
        GenericDialog gd = new GenericDialog(TITLE);
        gd.enableYesNoCancel();/*from   w w  w  .  j a  va 2  s  .c  om*/
        gd.hideCancelButton();
        gd.addMessage("The list contains unsaved selected frames.\n \nDo you want to continue?");
        gd.showDialog();
        if (!gd.wasOKed())
            return;
    }

    // For all spots in the results window, get the ID and then save the traces to memory
    if (!resultsWindowShowing())
        return;

    // Create a results set in memory
    MemoryPeakResults results = new MemoryPeakResults();
    results.setName(TITLE);
    results.begin();
    MemoryPeakResults.addResults(results);

    ArrayList<TraceResult> traceResults = new ArrayList<TraceResult>(
            resultsWindow.getTextPanel().getLineCount());
    for (int i = 0; i < resultsWindow.getTextPanel().getLineCount(); i++) {
        String line = resultsWindow.getTextPanel().getLine(i);
        Scanner s = new Scanner(line);
        s.useDelimiter("\t");
        int id = s.nextInt();
        s.nextDouble(); // cx
        s.nextDouble(); // cy
        double signal = s.nextDouble();
        s.close();

        Trace trace = traces.get(id);
        if (trace != null) {
            results.addAll(trace.getPoints());
            traceResults.add(new TraceResult(new Spot(id, signal), trace));
        }
    }

    results.end();

    saveTracesToFile(traceResults);

    IJ.showStatus("Saved traces");
}

From source file:com.joey.software.MoorFLSI.RepeatImageTextReader.java

public void loadTextData(File file) {
    try {//  www . j a va2s.com
        RandomAccessFile in = new RandomAccessFile(file, "r");

        // Skip header
        in.readLine();
        in.readLine();
        in.readLine();

        // Skip Subject Information
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        String startTimeInput = in.readLine();
        String commentsInput = in.readLine();

        String data = in.readLine();
        while (!data.startsWith("2) System Configuration")) {
            commentsInput += data;
            data = in.readLine();
        }
        // System configuration

        // in.readLine();
        in.readLine();
        String timeCounstantInput = in.readLine();
        String cameraGainInput = in.readLine();
        String exposureTimeInput = in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        String resolutionInput = in.readLine();

        // Time Data
        in.readLine();
        String timeDataInput = in.readLine();
        String totalImagesInput = in.readLine();
        in.readLine();
        in.readLine();
        // in.readLine();
        // System.out.println(in.readLine());
        // in.readLine();

        // Parse important Size

        high = (new Scanner(resolutionInput.split(":")[1])).nextInt();
        wide = (new Scanner(resolutionInput.split(",")[1])).nextInt();
        int tot = 1;
        try {
            tot = (new Scanner(totalImagesInput.split(":")[1])).nextInt();
        } catch (Exception e) {

        }
        System.out.println(wide + "," + high);
        // Parse timeInformation
        SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss (dd/MM/yy)");
        Date startTime = null;
        try {
            startTime = format.parse(startTimeInput.split(": ")[1]);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String[] frameTimeData = timeDataInput.split("information:")[1].split(",");

        Date[] timeInfo = new Date[tot];
        for (int i = 0; i < frameTimeData.length - 1; i++) {
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(startTime);
            String dat = (frameTimeData[i]);
            String[] timeVals = dat.split(":");

            int hour = Integer.parseInt(StringOperations.removeNonNumber(timeVals[0]));
            int min = Integer.parseInt(StringOperations.removeNonNumber(timeVals[1]));
            int sec = Integer.parseInt(StringOperations.removeNonNumber(timeVals[2]));
            int msec = Integer.parseInt(StringOperations.removeNonNumber(timeVals[3]));

            cal.add(Calendar.HOUR_OF_DAY, hour);
            cal.add(Calendar.MINUTE, min);
            cal.add(Calendar.SECOND, sec);
            cal.add(Calendar.MILLISECOND, msec);
            timeInfo[i] = cal.getTime();
        }

        // Parse Image Data
        /*
         * Close Random access file and switch to scanner first store pos
         * then move to correct point.
         */
        long pos = in.getFilePointer();
        in.close();

        FileInputStream fIn = new FileInputStream(file);
        fIn.skip(pos);

        BufferedInputStream bIn = new BufferedInputStream(fIn);
        Scanner sIn = new Scanner(bIn);

        short[][][] holder = new short[tot][wide][high];

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        StatusBarPanel stat = new StatusBarPanel();
        stat.setMaximum(high);
        f.getContentPane().setLayout(new BorderLayout());
        f.getContentPane().add(stat, BorderLayout.CENTER);
        f.setSize(200, 60);
        f.setVisible(true);

        for (int i = 0; i < tot; i++) {
            // Skip over the heading values
            stat.setStatusMessage("Loading " + i + " of " + tot);
            sIn.useDelimiter("\n");
            sIn.next();
            sIn.next();
            sIn.next();
            if (i != 0) {
                sIn.next();
            }
            sIn.reset();
            for (int y = 0; y < high; y++) {
                stat.setValue(y);
                sIn.nextInt();
                for (int x = 0; x < wide; x++) {
                    holder[i][x][y] = sIn.nextShort();
                }

            }
            addData(timeInfo[i], holder[i]);
        }

        // FrameFactroy.getFrame(new DynamicRangeImage(data[0]));
        // Start Image Data

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

public void subsetFile(InputStream in, String outfile, List<Integer> columns, Long numCases, String delimiter) {
    try {/* ww w .ja  v a  2s .  c o m*/
        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\n");

        BufferedWriter out = new BufferedWriter(new FileWriter(outfile));
        for (long caseIndex = 0; caseIndex < numCases; caseIndex++) {
            if (scanner.hasNext()) {
                String[] line = (scanner.next()).split(delimiter, -1);
                List<String> ln = new ArrayList<String>();
                for (Integer i : columns) {
                    ln.add(line[i]);
                }
                out.write(StringUtils.join(ln, "\t") + "\n");
            } else {
                throw new RuntimeException("Tab file has fewer rows than the determined number of cases.");
            }
        }

        while (scanner.hasNext()) {
            if (!"".equals(scanner.next())) {
                throw new RuntimeException(
                        "Tab file has extra nonempty rows than the determined number of cases.");

            }
        }

        scanner.close();
        out.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.cohorte.ecf.provider.jabsorb.host.JabsorbHttpSession.java

/**
 * Sends a POST request to the session URL with the given content
 * // w ww  . ja v  a  2s . c o m
 * @param aRequestContent
 *            Request content
 * @return The result page
 * @throws ClientError
 *             Something wrong happened
 */
protected String getUrlPostResult(final byte[] aRequestContent) {

    // Open a connection
    HttpURLConnection httpConnection = null;
    Scanner scanner = null;
    try {
        // Open the connection and cast it
        final URLConnection connection = pUrl.openConnection();
        if (!(connection instanceof HttpURLConnection)) {
            throw new ClientError("Unknown URL connection for : " + pUrl);
        }

        httpConnection = (HttpURLConnection) connection;

        // Make the connection writable (POST)
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoOutput(true);

        // Set up the headers
        httpConnection.addRequestProperty("Content-Type", JSON_CONTENT_TYPE);
        httpConnection.addRequestProperty("Content-Length", Integer.toString(aRequestContent.length));

        // Set POST data
        httpConnection.getOutputStream().write(aRequestContent);

        // Wait for an answer
        final int responseCode = httpConnection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new ClientError("Got HTTP Status " + responseCode + " for URL " + pUrl);
        }

        // Use a scanner to read the response content See here for more
        // information:
        // http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
        scanner = new Scanner(connection.getInputStream());
        scanner.useDelimiter("\\A");
        return scanner.next();

    } catch (final IOException e) {
        // Convert error class
        throw new ClientError(e);

    } finally {
        // In any case, free the connection
        if (httpConnection != null) {
            httpConnection.disconnect();
        }

        // ... and close the scanner
        if (scanner != null) {
            scanner.close();
        }
    }
}

From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

private File generateRotatedImage(File tabfile, int varcount, int casecount) throws IOException {
    // TODO: throw exceptions if bad file, zero varcount, etc. ...

    String fileName = tabfile.getAbsolutePath();
    String rotatedImageFileName = fileName + ".90d";

    int MAX_OUTPUT_STREAMS = 32;
    int MAX_BUFFERED_BYTES = 10 * 1024 * 1024; // 10 MB - for now?
    int MAX_COLUMN_BUFFER = 8 * 1024;

    // offsetHeader will contain the byte offsets of the individual column 
    // vectors in the final rotated image file
    byte[] offsetHeader = new byte[varcount * 8];
    int[] bufferedSizes = new int[varcount];
    long[] cachedfileSizes = new long[varcount];
    File[] columnTempFiles = new File[varcount];

    for (int i = 0; i < varcount; i++) {
        bufferedSizes[i] = 0;//from  www  . j a  v  a 2s.c  om
        cachedfileSizes[i] = 0;
    }

    // TODO: adjust MAX_COLUMN_BUFFER here, so that the total size is 
    // no more than MAX_BUFFERED_BYTES (but no less than 1024 maybe?)

    byte[][] bufferedColumns = new byte[varcount][MAX_COLUMN_BUFFER];

    // read the tab-delimited file: 

    FileInputStream tabfileStream = new FileInputStream(tabfile);

    Scanner scanner = new Scanner(tabfileStream);
    scanner.useDelimiter("\\n");

    for (int caseindex = 0; caseindex < casecount; caseindex++) {
        if (scanner.hasNext()) {
            String[] line = (scanner.next()).split("\t", -1);
            // TODO: throw an exception if there are fewer tab-delimited 
            // tokens than the number of variables specified. 
            String token = "";
            int tokensize = 0;
            for (int varindex = 0; varindex < varcount; varindex++) {
                // TODO: figure out the safest way to convert strings to 
                // bytes here. Is it going to be safer to use getBytes("UTF8")?
                // we are already making the assumption that the values 
                // in the tab file are in UTF8. -- L.A.
                token = line[varindex] + "\n";
                tokensize = token.getBytes().length;
                if (bufferedSizes[varindex] + tokensize > MAX_COLUMN_BUFFER) {
                    // fill the buffer and dump its contents into the temp file:
                    // (do note that there may be *several* MAX_COLUMN_BUFFERs
                    // worth of bytes in the token!)

                    int tokenoffset = 0;

                    if (bufferedSizes[varindex] != MAX_COLUMN_BUFFER) {
                        tokenoffset = MAX_COLUMN_BUFFER - bufferedSizes[varindex];
                        System.arraycopy(token.getBytes(), 0, bufferedColumns[varindex],
                                bufferedSizes[varindex], tokenoffset);
                    } // (otherwise the buffer is already full, and we should 
                      // simply dump it into the temp file, without adding any 
                      // extra bytes to it)

                    File bufferTempFile = columnTempFiles[varindex];
                    if (bufferTempFile == null) {
                        bufferTempFile = File.createTempFile("columnBufferFile", "bytes");
                        columnTempFiles[varindex] = bufferTempFile;
                    }

                    // *append* the contents of the buffer to the end of the
                    // temp file, if already exists:
                    BufferedOutputStream outputStream = new BufferedOutputStream(
                            new FileOutputStream(bufferTempFile, true));
                    outputStream.write(bufferedColumns[varindex], 0, MAX_COLUMN_BUFFER);
                    cachedfileSizes[varindex] += MAX_COLUMN_BUFFER;

                    // keep writing MAX_COLUMN_BUFFER-size chunks of bytes into 
                    // the temp file, for as long as there's more than MAX_COLUMN_BUFFER
                    // bytes left in the token:

                    while (tokensize - tokenoffset > MAX_COLUMN_BUFFER) {
                        outputStream.write(token.getBytes(), tokenoffset, MAX_COLUMN_BUFFER);
                        cachedfileSizes[varindex] += MAX_COLUMN_BUFFER;
                        tokenoffset += MAX_COLUMN_BUFFER;
                    }

                    outputStream.close();

                    // buffer the remaining bytes and reset the buffered 
                    // byte counter: 

                    System.arraycopy(token.getBytes(), tokenoffset, bufferedColumns[varindex], 0,
                            tokensize - tokenoffset);

                    bufferedSizes[varindex] = tokensize - tokenoffset;

                } else {
                    // continue buffering
                    System.arraycopy(token.getBytes(), 0, bufferedColumns[varindex], bufferedSizes[varindex],
                            tokensize);
                    bufferedSizes[varindex] += tokensize;
                }
            }
        } else {
            scanner.close();
            throw new IOException("Tab file has fewer rows than the stored number of cases!");
        }

    }

    // OK, we've created the individual byte vectors of the tab file columns;
    // they may be partially saved in temp files and/or in memory.
    // We now need to go through all these buffers and create the final 
    // rotated image file. 

    BufferedOutputStream finalOut = new BufferedOutputStream(
            new FileOutputStream(new File(rotatedImageFileName)));

    // but first we should create the offset header and write it out into 
    // the final file; because it should be at the head, doh!

    long columnOffset = varcount * 8;
    // (this is the offset of the first column vector; it is equal to the
    // size of the offset header, i.e. varcount * 8 bytes)

    for (int varindex = 0; varindex < varcount; varindex++) {
        long totalColumnBytes = cachedfileSizes[varindex] + bufferedSizes[varindex];
        columnOffset += totalColumnBytes;
        //totalColumnBytes;
        byte[] columnOffsetByteArray = ByteBuffer.allocate(8).putLong(columnOffset).array();
        System.arraycopy(columnOffsetByteArray, 0, offsetHeader, varindex * 8, 8);
    }

    finalOut.write(offsetHeader, 0, varcount * 8);

    for (int varindex = 0; varindex < varcount; varindex++) {
        long cachedBytesRead = 0;

        // check if there is a cached temp file:

        File cachedTempFile = columnTempFiles[varindex];
        if (cachedTempFile != null) {
            byte[] cachedBytes = new byte[MAX_COLUMN_BUFFER];
            BufferedInputStream cachedIn = new BufferedInputStream(new FileInputStream(cachedTempFile));
            int readlen = 0;
            while ((readlen = cachedIn.read(cachedBytes)) > -1) {
                finalOut.write(cachedBytes, 0, readlen);
                cachedBytesRead += readlen;
            }
            cachedIn.close();
            // delete the temp file: 
            cachedTempFile.delete();

        }

        if (cachedBytesRead != cachedfileSizes[varindex]) {
            finalOut.close();
            throw new IOException("Could not read the correct number of bytes cached for column " + varindex
                    + "; " + cachedfileSizes[varindex] + " bytes expected, " + cachedBytesRead + " read.");
        }

        // then check if there are any bytes buffered for this column:

        if (bufferedSizes[varindex] > 0) {
            finalOut.write(bufferedColumns[varindex], 0, bufferedSizes[varindex]);
        }

    }

    finalOut.close();
    return new File(rotatedImageFileName);

}