List of usage examples for java.lang IllegalStateException IllegalStateException
public IllegalStateException(Throwable cause)
From source file:com.alibaba.dubbo.examples.redis.RedisConsumer.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String config = RedisConsumer.class.getPackage().getName().replace('.', '/') + "/redis-consumer.xml"; ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); context.start();// w w w . j a v a2 s.c o m Map<String, Object> cache = (Map<String, Object>) context.getBean("cache"); cache.remove("hello"); Object value = cache.get("hello"); System.out.println(value); if (value != null) { throw new IllegalStateException(value + " != null"); } cache.put("hello", "world"); value = cache.get("hello"); System.out.println(value); if (!"world".equals(value)) { throw new IllegalStateException(value + " != world"); } }
From source file:com.alibaba.dubbo.examples.memcached.MemcachedConsumer.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String config = MemcachedConsumer.class.getPackage().getName().replace('.', '/') + "/memcached-consumer.xml"; ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); context.start();/* w ww. j a v a2s . c om*/ Map<String, Object> cache = (Map<String, Object>) context.getBean("cache"); cache.remove("hello"); Object value = cache.get("hello"); System.out.println(value); if (value != null) { throw new IllegalStateException(value + " != null"); } cache.put("hello", "world"); value = cache.get("hello"); System.out.println(value); if (!"world".equals(value)) { throw new IllegalStateException(value + " != world"); } System.in.read(); }
From source file:com.music.tools.InstrumentExtractor.java
public static void main(String[] args) { Map<Integer, String> instrumentNames = new HashMap<>(); Field[] fields = ProgramChanges.class.getDeclaredFields(); try {// w w w. j a v a2s . c o m for (Field field : fields) { Integer value = (Integer) field.get(null); if (!instrumentNames.containsKey(value)) { instrumentNames.put(value, StringUtils.capitalize(field.getName().toLowerCase()).replace('_', ' ')); } } } catch (IllegalArgumentException | IllegalAccessException e) { throw new IllegalStateException(e); } Score score = new Score(); Read.midi(score, "C:\\Users\\bozho\\Downloads\\7938.midi"); for (Part part : score.getPartArray()) { System.out.println(part.getChannel() + " : " + part.getInstrument() + ": " + instrumentNames.get(part.getInstrument())); } }
From source file:com.kotcrab.vis.editor.Main.java
public static void main(String[] args) throws Exception { App.init();//from w w w .j av a2s .c om if (OsUtils.isMac()) System.setProperty("java.awt.headless", "true"); LaunchConfiguration launchConfig = new LaunchConfiguration(); //TODO: needs some better parser for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.equals("--scale-ui")) { launchConfig.scaleUIEnabled = true; continue; } if (arg.equals("--project")) { if (i + 1 >= args.length) { throw new IllegalStateException("Not enough parameters for --project <project path>"); } launchConfig.projectPath = args[i + 1]; i++; continue; } if (arg.equals("--scene")) { if (i + 1 >= args.length) { throw new IllegalStateException("Not enough parameters for --scene <scene path>"); } launchConfig.scenePath = args[i + 1]; i++; continue; } Log.warn("Unrecognized command line argument: " + arg); } launchConfig.verify(); editor = new Editor(launchConfig); Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration(); config.setWindowedMode(1280, 720); config.setWindowSizeLimits(1, 1, 9999, 9999); config.useVsync(true); config.setIdleFPS(2); config.setWindowListener(new Lwjgl3WindowAdapter() { @Override public boolean closeRequested() { editor.requestExit(); return false; } }); try { new Lwjgl3Application(editor, config); Log.dispose(); } catch (Exception e) { Log.exception(e); Log.fatal("Uncaught exception occurred, error report will be saved"); Log.flush(); if (App.eventBus != null) App.eventBus.post(new ExceptionEvent(e, true)); try { File crashReport = new CrashReporter(Log.getLogFile().file()).processReport(); if (new File(App.TOOL_CRASH_REPORTER_PATH).exists() == false) { Log.warn("Crash reporting tool not present, skipping crash report sending."); } else { CommandLine cmdLine = new CommandLine(PlatformUtils.getJavaBinPath()); cmdLine.addArgument("-jar"); cmdLine.addArgument(App.TOOL_CRASH_REPORTER_PATH); cmdLine.addArgument(ApplicationUtils.getRestartCommand().replace("\"", "%")); cmdLine.addArgument(crashReport.getAbsolutePath(), false); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(null, null, null)); executor.execute(cmdLine); } } catch (IOException ex) { ex.printStackTrace(); } Log.dispose(); System.exit(-3); } catch (ExceptionInInitializerError err) { if (OsUtils.isMac() && err.getCause() instanceof IllegalStateException) { if (ExceptionUtils.getStackTrace(err).contains("XstartOnFirstThread")) { System.out.println( "Application was not launched on first thread. Restarting with -XstartOnFirstThread, add VM argument -XstartOnFirstThread to avoid this."); ApplicationUtils.startNewInstance(); } } throw err; } }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step2ArgumentPairsSampling.java
public static void main(String[] args) throws Exception { String inputDir = args[0];/*w w w . j a v a 2 s.c o m*/ // /tmp File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs(); } // pseudo-random final Random random = new Random(1); int totalPairsCount = 0; // read all debates for (File file : IOHelper.listXmlFiles(new File(inputDir))) { Debate debate = DebateSerializer.deserializeFromXML(FileUtils.readFileToString(file, "utf-8")); // get two stances SortedSet<String> originalStances = debate.getStances(); // cleaning: some debate has three or more stances (data are inconsistent) // remove those with only one argument SortedSet<String> stances = new TreeSet<>(); for (String stance : originalStances) { if (debate.getArgumentsForStance(stance).size() > 1) { stances.add(stance); } } if (stances.size() != 2) { throw new IllegalStateException( "2 stances per debate expected, was " + stances.size() + ", " + stances); } // for each stance, get pseudo-random N arguments for (String stance : stances) { List<Argument> argumentsForStance = debate.getArgumentsForStance(stance); // shuffle Collections.shuffle(argumentsForStance, random); // and get max first N arguments List<Argument> selectedArguments = argumentsForStance.subList(0, argumentsForStance.size() < MAX_SELECTED_ARGUMENTS_PRO_SIDE ? argumentsForStance.size() : MAX_SELECTED_ARGUMENTS_PRO_SIDE); List<ArgumentPair> argumentPairs = new ArrayList<>(); // now create pairs for (int i = 0; i < selectedArguments.size(); i++) { for (int j = (i + 1); j < selectedArguments.size(); j++) { Argument arg1 = selectedArguments.get(i); Argument arg2 = selectedArguments.get(j); ArgumentPair argumentPair = new ArgumentPair(); argumentPair.setDebateMetaData(debate.getDebateMetaData()); // assign arg1 and arg2 pseudo-randomly // (not to have the same argument as arg1 all the time) if (random.nextBoolean()) { argumentPair.setArg1(arg1); argumentPair.setArg2(arg2); } else { argumentPair.setArg1(arg2); argumentPair.setArg2(arg1); } // set unique id argumentPair.setId(argumentPair.getArg1().getId() + "_" + argumentPair.getArg2().getId()); argumentPairs.add(argumentPair); } } String fileName = IOHelper.createFileName(debate.getDebateMetaData(), stance); File outputFile = new File(outputDir, fileName); // and save all sampled pairs into a XML file XStreamTools.toXML(argumentPairs, outputFile); System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile); totalPairsCount += argumentPairs.size(); } } System.out.println("Total pairs generated: " + totalPairsCount); }
From source file:com.github.xbn.examples.regexutil.non_xbn.BetweenLineMarkersButSkipFirstXmpl.java
public static final void main(String[] as_1RqdTxtFilePath) { Iterator<String> lineItr = null; try {/*from w w w . ja v a2 s.c o m*/ lineItr = FileUtils.lineIterator(new File(as_1RqdTxtFilePath[0])); //Throws npx if null } catch (IOException iox) { throw new RuntimeException("Attempting to open \"" + as_1RqdTxtFilePath[0] + "\"", iox); } catch (RuntimeException rx) { throw new RuntimeException("One required parameter: The path to the text file.", rx); } String LINE_SEP = System.getProperty("line.separator", "\n"); ArrayList<String> alsItems = new ArrayList<String>(); boolean bStartMark = false; boolean bLine1Skipped = false; StringBuilder sdCurrentItem = new StringBuilder(); while (lineItr.hasNext()) { String sLine = lineItr.next().trim(); if (!bStartMark) { if (sLine.startsWith(".START_SEQUENCE")) { bStartMark = true; continue; } throw new IllegalStateException("Start mark not found."); } if (!bLine1Skipped) { bLine1Skipped = true; continue; } else if (!sLine.equals(".END_SEQUENCE")) { sdCurrentItem.append(sLine).append(LINE_SEP); } else { alsItems.add(sdCurrentItem.toString()); sdCurrentItem.setLength(0); bStartMark = false; bLine1Skipped = false; continue; } } for (String s : alsItems) { System.out.println("----------"); System.out.print(s); } }
From source file:com.google.infrastructuredmap.MapAndMarkdownExtractorMain.java
public static void main(String[] args) throws IOException, ParseException { Options options = new Options(); options.addOption(ARG_KML, true, "path to KML input"); options.addOption(ARG_MARKDOWN, true, "path to Markdown input"); options.addOption(ARG_JSON_OUTPUT, true, "path to write json output"); options.addOption(ARG_JSONP, true, "JSONP template to wrap output JSON data"); CommandLineParser parser = new DefaultParser(); CommandLine cli = parser.parse(options, args); // Extract map features from the input KML. MapData data = null;/*w ww.j a va 2 s . c o m*/ try (InputStream in = openStream(cli.getOptionValue(ARG_KML))) { Kml kml = Kml.unmarshal(in); data = MapDataExtractor.extractMapData(kml); } // Extract project features from the input Markdown. Map<String, List<ProjectReference>> references = MarkdownReferenceExtractor .extractReferences(Paths.get(cli.getOptionValue(ARG_MARKDOWN))); for (MapFeature feature : data.features) { List<ProjectReference> referencesForId = references.get(feature.id); if (referencesForId == null) { throw new IllegalStateException("Unknown project reference: " + feature.id); } feature.projects = referencesForId; } // Write the resulting data to the output path. Gson gson = new Gson(); try (FileWriter out = new FileWriter(cli.getOptionValue(ARG_JSON_OUTPUT))) { String json = gson.toJson(data); if (cli.hasOption(ARG_JSONP)) { json = String.format(cli.getOptionValue(ARG_JSONP), json); } out.write(json); } }
From source file:com.github.fge.jsonschema.main.cli.Main.java
public static void main(final String... args) throws IOException, ProcessingException { final OptionParser parser = new OptionParser(); parser.accepts("help", "show this help").forHelp(); parser.acceptsAll(Arrays.asList("s", "brief"), "only show validation status (OK/NOT OK)"); parser.acceptsAll(Arrays.asList("q", "quiet"), "no output; exit with the relevant return code (see below)"); parser.accepts("syntax", "check the syntax of schema(s) given as argument(s)"); parser.accepts("fakeroot", "pretend that the current directory is absolute URI \"uri\"").withRequiredArg(); parser.formatHelpWith(HELP);/*from ww w . ja va 2 s.c o m*/ final OptionSet optionSet; final boolean isSyntax; final int requiredArgs; Reporter reporter = Reporters.DEFAULT; String fakeRoot = null; try { optionSet = parser.parse(args); } catch (OptionException e) { System.err.println("unrecognized option(s): " + CustomHelpFormatter.OPTIONS_JOINER.join(e.options())); parser.printHelpOn(System.err); System.exit(CMD_ERROR.get()); throw new IllegalStateException("WTF??"); } if (optionSet.has("help")) { parser.printHelpOn(System.out); System.exit(ALL_OK.get()); } if (optionSet.has("s") && optionSet.has("q")) { System.err.println("cannot specify both \"--brief\" and " + "\"--quiet\""); parser.printHelpOn(System.err); System.exit(CMD_ERROR.get()); } if (optionSet.has("fakeroot")) fakeRoot = (String) optionSet.valueOf("fakeroot"); isSyntax = optionSet.has("syntax"); requiredArgs = isSyntax ? 1 : 2; @SuppressWarnings("unchecked") final List<String> arguments = (List<String>) optionSet.nonOptionArguments(); if (arguments.size() < requiredArgs) { System.err.println("missing arguments"); parser.printHelpOn(System.err); System.exit(CMD_ERROR.get()); } final List<File> files = Lists.newArrayList(); for (final String target : arguments) files.add(new File(target).getCanonicalFile()); if (optionSet.has("brief")) reporter = Reporters.BRIEF; else if (optionSet.has("quiet")) { System.out.close(); System.err.close(); reporter = Reporters.QUIET; } new Main(fakeRoot).proceed(reporter, files, isSyntax); }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step5GoldLabelEstimator.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String inputDir = args[0];/*from w w w.j a va 2 s .c o m*/ File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs(); } // we will process only a subset first List<AnnotatedArgumentPair> allArgumentPairs = new ArrayList<>(); Collection<File> files = IOHelper.listXmlFiles(new File(inputDir)); for (File file : files) { allArgumentPairs.addAll((List<AnnotatedArgumentPair>) XStreamTools.getXStream().fromXML(file)); } // collect turkers and csv List<String> turkerIDs = extractAndSortTurkerIDs(allArgumentPairs); String preparedCSV = prepareCSV(allArgumentPairs, turkerIDs); // save CSV and run MACE Path tmpDir = Files.createTempDirectory("mace"); File maceInputFile = new File(tmpDir.toFile(), "input.csv"); FileUtils.writeStringToFile(maceInputFile, preparedCSV, "utf-8"); File outputPredictions = new File(tmpDir.toFile(), "predictions.txt"); File outputCompetence = new File(tmpDir.toFile(), "competence.txt"); // run MACE MACE.main(new String[] { "--iterations", "500", "--threshold", String.valueOf(MACE_THRESHOLD), "--restarts", "50", "--outputPredictions", outputPredictions.getAbsolutePath(), "--outputCompetence", outputCompetence.getAbsolutePath(), maceInputFile.getAbsolutePath() }); // read back the predictions and competence List<String> predictions = FileUtils.readLines(outputPredictions, "utf-8"); // check the output if (predictions.size() != allArgumentPairs.size()) { throw new IllegalStateException("Wrong size of the predicted file; expected " + allArgumentPairs.size() + " lines but was " + predictions.size()); } String competenceRaw = FileUtils.readFileToString(outputCompetence, "utf-8"); String[] competence = competenceRaw.split("\t"); if (competence.length != turkerIDs.size()) { throw new IllegalStateException( "Expected " + turkerIDs.size() + " competence number, got " + competence.length); } // rank turkers by competence Map<String, Double> turkerIDCompetenceMap = new TreeMap<>(); for (int i = 0; i < turkerIDs.size(); i++) { turkerIDCompetenceMap.put(turkerIDs.get(i), Double.valueOf(competence[i])); } // sort by value descending Map<String, Double> sortedCompetences = IOHelper.sortByValue(turkerIDCompetenceMap, false); System.out.println("Sorted turker competences: " + sortedCompetences); // assign the gold label and competence for (int i = 0; i < allArgumentPairs.size(); i++) { AnnotatedArgumentPair annotatedArgumentPair = allArgumentPairs.get(i); String goldLabel = predictions.get(i).trim(); // might be empty if (!goldLabel.isEmpty()) { // so far the gold label has format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal // strip now only the gold label annotatedArgumentPair.setGoldLabel(goldLabel); } // update turker competence for (AnnotatedArgumentPair.MTurkAssignment assignment : annotatedArgumentPair.mTurkAssignments) { String turkID = assignment.getTurkID(); int turkRank = getTurkerRank(turkID, sortedCompetences); assignment.setTurkRank(turkRank); double turkCompetence = turkerIDCompetenceMap.get(turkID); assignment.setTurkCompetence(turkCompetence); } } // now sort the data back according to their original file name Map<String, List<AnnotatedArgumentPair>> fileNameAnnotatedPairsMap = new HashMap<>(); for (AnnotatedArgumentPair argumentPair : allArgumentPairs) { String fileName = IOHelper.createFileName(argumentPair.getDebateMetaData(), argumentPair.getArg1().getStance()); if (!fileNameAnnotatedPairsMap.containsKey(fileName)) { fileNameAnnotatedPairsMap.put(fileName, new ArrayList<AnnotatedArgumentPair>()); } fileNameAnnotatedPairsMap.get(fileName).add(argumentPair); } // and save them to the output file for (Map.Entry<String, List<AnnotatedArgumentPair>> entry : fileNameAnnotatedPairsMap.entrySet()) { String fileName = entry.getKey(); List<AnnotatedArgumentPair> argumentPairs = entry.getValue(); File outputFile = new File(outputDir, fileName); // and save all sampled pairs into a XML file XStreamTools.toXML(argumentPairs, outputFile); System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile); } }
From source file:ClassVersionInfo.java
/** * Usage: ClassVersionInfo class-name// w w w . ja v a 2s. c om * * Locate the class name on the thread context class loader classpath and * print its version info. * * @param args * [0] = class-name */ public static void main(String[] args) throws Exception { if (args.length == 0) throw new IllegalStateException("Usage: ...ClassVersionInfo class-name"); ClassLoader loader = Thread.currentThread().getContextClassLoader(); ClassVersionInfo info = new ClassVersionInfo(args[0], loader); System.out.println(info); }