Example usage for java.lang IllegalStateException IllegalStateException

List of usage examples for java.lang IllegalStateException IllegalStateException

Introduction

In this page you can find the example usage for java.lang IllegalStateException IllegalStateException.

Prototype

public IllegalStateException(Throwable cause) 

Source Link

Document

Constructs a new exception with the specified cause and a detail message of (cause==null ?

Usage

From source file:Main.java

public static void invokeInEDTAndWait(Runnable runnable) throws Exception {
    if (SwingUtilities.isEventDispatchThread()) {
        runnable.run();//  w w w.j  a  va 2s.c  om
    } else {
        try {
            SwingUtilities.invokeAndWait(runnable);

        } catch (InvocationTargetException e) {
            Throwable targetException = e.getTargetException();
            if (targetException instanceof Exception)
                throw (Exception) targetException;
            if (targetException instanceof Error)
                throw (Error) targetException;
            throw new IllegalStateException(targetException);

        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step7CollectMTurkResults.java

public static void main(String[] args) throws Exception {
    // input dir - list of xml query containers
    // /home/user-ukp/research/data/dip/wp1-documents/step4-boiler-plate/
    File inputDir = new File(args[0] + "/");

    // MTurk result file

    // output dir
    File outputDir = new File(args[2]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();//from www  .  ja  v  a2  s.  com

    }

    // Folder with success files
    File mturkSuccessDir = new File(args[1]);

    Collection<File> files = FileUtils.listFiles(mturkSuccessDir, new String[] { "result" }, false);
    if (files.isEmpty()) {
        throw new IllegalArgumentException("Input folder is empty. " + mturkSuccessDir);
    }

    HashMap<String, List<MTurkAnnotation>> mturkAnnotations = new HashMap<>();

    // parsing all CSV files
    for (File mturkCSVResultFile : files) {
        System.out.println("Parsing " + mturkCSVResultFile.getName());

        MTurkOutputReader outputReader = new MTurkOutputReader(
                new HashSet<>(Arrays.asList("annotation", "workerid")), mturkCSVResultFile);

        // for fixing broken data input: for each hit, collect all sentence IDs
        Map<String, SortedSet<String>> hitSentences = new HashMap<>();

        // first iteration: collect the sentences
        for (Map<String, String> record : outputReader) {
            String hitID = record.get("hitid");
            if (!hitSentences.containsKey(hitID)) {
                hitSentences.put(hitID, new TreeSet<>());
            }

            String relevantSentences = record.get("Answer.relevant_sentences");
            String irrelevantSentences = record.get("Answer.irrelevant_sentences");

            if (relevantSentences != null) {
                hitSentences.get(hitID).addAll(Arrays.asList(relevantSentences.split(",")));
            }

            if (irrelevantSentences != null) {
                hitSentences.get(hitID).addAll(Arrays.asList(irrelevantSentences.split(",")));
            }
        }

        // and now second iteration
        for (Map<String, String> record : outputReader) {
            String hitID = record.get("hitid");
            String annotatorID = record.get("workerid");
            String acceptTime = record.get("assignmentaccepttime");
            String submitTime = record.get("assignmentsubmittime");
            String relevantSentences = record.get("Answer.relevant_sentences");
            String irrelevantSentences = record.get("Answer.irrelevant_sentences");
            String reject = record.get("reject");
            String filename[];
            String comment;
            String clueWeb;
            String[] relevant = {};
            String[] irrelevant = {};

            filename = record.get("annotation").split("_");
            String fileXml = filename[0];
            clueWeb = filename[1].trim();
            comment = record.get("Answer.comment");

            if (relevantSentences != null) {
                relevant = relevantSentences.split(",");
            }

            if (irrelevantSentences != null) {
                irrelevant = irrelevantSentences.split(",");
            }

            // sanitizing data: if both relevant and irrelevant are empty, that's a bug
            // we're gonna look up all sentences from this HIT and treat this assignment
            // as if there were only irrelevant ones
            if (relevant.length == 0 && irrelevant.length == 0) {
                SortedSet<String> strings = hitSentences.get(hitID);
                irrelevant = new String[strings.size()];
                strings.toArray(irrelevant);
            }

            if (reject != null) {
                System.out.println(" HIT " + hitID + " annotated by " + annotatorID + " was rejected ");
            } else {
                /*
                // relevant sentences is a comma-delimited string,
                // this regular expression is rather strange
                // it must contain digits, it might be that there is only one space or a comma or some other char
                // digits are the sentence ids. if relevant sentences do not contain digits then it is wrong
                if (relevantSentences.matches("^\\D*$") &&
                    irrelevantSentences.matches("^\\D*$")) {
                try {
                    throw new IllegalStateException(
                            "No annotations found for HIT " + hitID + " in " +
                                    fileXml + " for document " + clueWeb);
                }
                catch (IllegalStateException ex) {
                    ex.printStackTrace();
                }
                        
                }
                */
                MTurkAnnotation mturkAnnotation;
                try {
                    mturkAnnotation = new MTurkAnnotation(hitID, annotatorID, acceptTime, submitTime, comment,
                            clueWeb, relevant, irrelevant);
                } catch (IllegalArgumentException ex) {
                    throw new IllegalArgumentException("Record: " + record, ex);
                }

                List<MTurkAnnotation> listOfAnnotations = mturkAnnotations.get(fileXml);

                if (listOfAnnotations == null) {
                    listOfAnnotations = new ArrayList<>();
                }
                listOfAnnotations.add(mturkAnnotation);
                mturkAnnotations.put(fileXml, listOfAnnotations);
            }

        }
        //            parser.close();
    }

    // Debugging: output number of HITs of a query
    System.out.println("Accepted HITs for a query:");
    for (Map.Entry e : mturkAnnotations.entrySet()) {
        ArrayList<MTurkAnnotation> a = (ArrayList<MTurkAnnotation>) e.getValue();
        System.out.println(e.getKey() + " " + a.size());
    }

    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        String fileName = f.getName();
        List<MTurkAnnotation> listOfAnnotations = mturkAnnotations.get(fileName);

        if (listOfAnnotations == null || listOfAnnotations.isEmpty()) {
            throw new IllegalStateException("No annotations for " + f.getName());
        }

        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            for (MTurkAnnotation mtAnnotation : listOfAnnotations) {
                String clueWeb = mtAnnotation.clueWeb;
                if (rankedResults.clueWebID.equals(clueWeb)) {
                    List<QueryResultContainer.MTurkRelevanceVote> mTurkRelevanceVotes = rankedResults.mTurkRelevanceVotes;
                    QueryResultContainer.MTurkRelevanceVote relevanceVote = new QueryResultContainer.MTurkRelevanceVote();
                    String annotatorID = mtAnnotation.annotatorID;
                    String hitID = mtAnnotation.hitID;
                    String acceptTime = mtAnnotation.acceptTime;
                    String submitTime = mtAnnotation.submitTime;
                    String comment = mtAnnotation.comment;
                    String[] relevant = mtAnnotation.relevant;
                    String[] irrelevant = mtAnnotation.irrelevant;
                    relevanceVote.turkID = annotatorID.trim();
                    relevanceVote.hitID = hitID.trim();
                    relevanceVote.acceptTime = acceptTime.trim();
                    relevanceVote.submitTime = submitTime.trim();
                    relevanceVote.comment = comment != null ? comment.trim() : null;
                    if (relevant.length == 0 && irrelevant.length == 0) {
                        try {
                            throw new IllegalStateException("the length of the annotations is 0"
                                    + rankedResults.clueWebID + " for HIT " + relevanceVote.hitID);
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        }
                    }
                    for (String r : relevant) {
                        String sentenceId = r.trim();
                        if (!sentenceId.isEmpty() && sentenceId.matches("\\d+")) {
                            QueryResultContainer.SingleSentenceRelevanceVote singleSentenceVote = new QueryResultContainer.SingleSentenceRelevanceVote();
                            singleSentenceVote.sentenceID = sentenceId;
                            singleSentenceVote.relevant = "true";
                            relevanceVote.singleSentenceRelevanceVotes.add(singleSentenceVote);
                        }
                    }
                    for (String r : irrelevant) {
                        String sentenceId = r.trim();
                        if (!sentenceId.isEmpty() && sentenceId.matches("\\d+")) {
                            QueryResultContainer.SingleSentenceRelevanceVote singleSentenceVote = new QueryResultContainer.SingleSentenceRelevanceVote();
                            singleSentenceVote.sentenceID = sentenceId;
                            singleSentenceVote.relevant = "false";
                            relevanceVote.singleSentenceRelevanceVotes.add(singleSentenceVote);
                        }
                    }
                    mTurkRelevanceVotes.add(relevanceVote);
                }
            }

        }
        File outputFile = new File(outputDir, f.getName());
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }

}

From source file:Main.java

private static JComponent getOnlyComponent(Container owner, Class<?> clazz, boolean onlyVisible) {
    List<JComponent> list = getComponents(owner, clazz, onlyVisible);
    if (list.size() != 1)
        throw new IllegalStateException(
                "num " + (onlyVisible ? "visible " : "") + "compounds found " + list.size());
    return list.get(0);
}

From source file:Main.java

public static String getTextChild(Element element) {
    NodeList children = element.getChildNodes();
    String value = null;/*from w w w . j a v  a2 s  .c  o m*/
    for (int i = 0; i < children.getLength(); ++i) {
        Node child = children.item(i);
        if (child.getNodeType() == Node.TEXT_NODE) {
            if (null != value) {
                throw new IllegalStateException(
                        "Element " + elementToString(element) + " has more than one text child.");
            } else {
                value = child.getNodeValue();
            }
        }
    }
    return value;
}

From source file:Main.java

/**
 * invoke a setter method//from  w w w.  j  a  va  2 s .  com
 * 
 * @param setter
 * @param object
 * @param propValue
 */
public static void invokeSetter(Method setter, Object object, Object propValue) {
    if (setter == null) {
        throw new IllegalArgumentException("The setter method cannot be null");
    }

    if (object == null) {
        throw new IllegalArgumentException("The object cannot be null");
    }

    try {
        setter.setAccessible(true);
        setter.invoke(object, new Object[] { propValue });
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
    } catch (InvocationTargetException e) {
        throw new IllegalStateException(e);
    }
}

From source file:Main.java

private static void throwIfNotCalledOnMainThread() {
    if (!Looper.getMainLooper().isCurrentThread()) {
        throw new IllegalStateException("should be called from the main thread.");
    }/* www  .  j  a v a  2 s .c om*/
}

From source file:Main.java

public static Document loadXml(File sourceFile) {
    try {/*from w w  w  .  j a  va 2 s .c o m*/
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document baseSizeDoc = dBuilder.parse(sourceFile);

        baseSizeDoc.getDocumentElement().normalize();

        return baseSizeDoc;
    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }

    throw new IllegalStateException("Could not load xml file: " + sourceFile.getPath());
}

From source file:Main.java

/**
 * Return PITarget from Processing Instruction (PI) as defined in XML 1.0 Section 2.6 Processing Instructions <code>[16] PI ::= '&lt;?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'</code>
 *//*www. j  a v a 2 s.  c om*/
public static String getPITarget(final XmlPullParser pp) throws IllegalStateException {
    int eventType;

    try {
        eventType = pp.getEventType();
    } catch (final XmlPullParserException x) {
        // should never happen ...
        throw new IllegalStateException("could not determine parser state: " + x + pp.getPositionDescription());
    }

    if (eventType != XmlPullParser.PROCESSING_INSTRUCTION)
        throw new IllegalStateException("parser must be on processing instruction and not "
                + XmlPullParser.TYPES[eventType] + pp.getPositionDescription());

    final String PI = pp.getText();
    for (int i = 0; i < PI.length(); i++) {
        if (isS(PI.charAt(i))) {
            // assert i > 0
            return PI.substring(0, i);
        }
    }

    return PI;
}

From source file:Main.java

/**
 * Calculates an MD5 hash for a text./*from   www. j  av  a  2 s .  c o  m*/
 * 
 * @param dataToEncode
 *            The data to encode.
 * @return A text representation of a hexadecimal value of length 32.
 */
public static String messageDigestFive(final String dataToEncode) {
    MessageDigest m;
    try {
        m = MessageDigest.getInstance("MD5");
        byte[] data = dataToEncode.getBytes();
        m.update(data, 0, data.length);
        BigInteger i = new BigInteger(1, m.digest());
        return String.format("%1$032X", i);
    } catch (NoSuchAlgorithmException e) {
        // MD5 Should be supported by the runtime!
        throw new IllegalStateException(e);
    }
}

From source file:Main.java

/**
 * Return everything past PITarget and S from Processing Instruction (PI) as defined in
 * XML 1.0 Section 2.6 Processing Instructions
 *  <code>[16] PI ::= '&lt;?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'</code>
 *
 * <p><b>NOTE:</b> if there is no PI data it returns empty string.
 *///from   w  w  w . jav a2s .c  om
public static String getPIData(XmlPullParser pp) throws IllegalStateException {
    int eventType;
    try {
        eventType = pp.getEventType();
    } catch (XmlPullParserException ex) {
        // should never happen ...
        throw new IllegalStateException(
                "could not determine parser state: " + ex + pp.getPositionDescription());
    }
    if (eventType != XmlPullParser.PROCESSING_INSTRUCTION) {
        throw new IllegalStateException("parser must be on processing instruction and not "
                + XmlPullParser.TYPES[eventType] + pp.getPositionDescription());
    }
    final String PI = pp.getText();
    int pos = -1;
    for (int i = 0; i < PI.length(); i++) {
        if (isS(PI.charAt(i))) {
            pos = i;
        } else if (pos > 0) {
            return PI.substring(i);
        }
    }
    return "";

}