List of usage examples for java.util.concurrent.atomic AtomicInteger intValue
public int intValue()
From source file:org.apdplat.superword.system.AntiRobotFilter.java
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; if (request.getRequestURI().endsWith("/favicon.ico")) { chain.doFilter(req, resp);//from ww w . j a va2s . co m return; } if (servletContext == null) { servletContext = request.getServletContext(); } HttpServletResponse response = (HttpServletResponse) resp; response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); String userAgent = request.getHeader("User-Agent"); if (StringUtils.isBlank(userAgent) || userAgent.length() < 50 || userAgent.contains("Java") || userAgent.contains("bingbot") || userAgent.contains("360Spider") || userAgent.contains("HaosouSpider") || userAgent.contains("Googlebot")) { invalidCount++; response.getWriter().write( "Superword is a Java open source project dedicated in the study of English words analysis and auxiliary reading, including but not limited to, spelling similarity, definition similarity, pronunciation similarity, the transformation rules of the spelling, the prefix and the dynamic prefix, the suffix and the dynamic suffix, roots, compound words, text auxiliary reading, web page auxiliary reading, book auxiliary reading, etc.."); return; } HttpSession session = request.getSession(true); if (session.getAttribute("isHuman") == null) { AtomicInteger identifyCount = (AtomicInteger) session.getAttribute("identifyCount"); if (identifyCount == null) { identifyCount = new AtomicInteger(); session.setAttribute("identifyCount", identifyCount); } identifyCount.incrementAndGet(); if (identifyCount.intValue() > 200) { response.getWriter().write( "System has detected that you may not be a human, because you can't answer the question correctly."); return; } if (session.getAttribute("forward") == null) { session.setAttribute("forward", StringUtils.isBlank(request.getPathInfo()) ? "/" : request.getPathInfo()); } String _token = request.getParameter("token"); String _word = request.getParameter("word"); String _answer = request.getParameter("answer"); if (StringUtils.isNotBlank(_token) && StringUtils.isNotBlank(_word) && StringUtils.isNotBlank(_answer) && session.getAttribute("token") != null && session.getAttribute("token").toString().equals(_token) && session.getAttribute("quizItem") != null) { session.setAttribute("token", null); QuizItem quizItem = (QuizItem) session.getAttribute("quizItem"); if (_word.equals(quizItem.getWord().getWord())) { quizItem.setAnswer(_answer); if (quizItem.isRight()) { String path = session.getAttribute("forward").toString(); if (path.contains("identify.quiz")) { path = path.replace("identify.quiz", ""); } session.setAttribute("forward", null); session.setAttribute("isHuman", "true"); request.getRequestDispatcher(path).forward(request, response); return; } else { Set<String> wrongWordsInQuiz = (Set<String>) session.getAttribute("wrong_words_in_quiz"); if (wrongWordsInQuiz == null) { wrongWordsInQuiz = new HashSet<>(); session.setAttribute("wrong_words_in_quiz", wrongWordsInQuiz); } wrongWordsInQuiz.add(quizItem.getWord().getWord()); StringBuilder html = new StringBuilder(); html.append( "<h1>The meaning of red color font is your answer, but the right answer is the meaning of blue color font for the word <font color=\"red\">") .append(quizItem.getWord().getWord()).append(":</font></h1>"); html.append("<h2><ul>"); for (String option : quizItem.getMeanings()) { html.append("<li>"); if (option.equals(_answer)) { html.append("<font color=\"red\">").append(option).append("</font>"); } else if (option.equals(quizItem.getWord().getMeaning())) { html.append("<font color=\"blue\">").append(option).append("</font>"); } else { html.append(option); } html.append("</li>\n"); } html.append("</ul></h2>\n<h1><a href=\"").append(servletContext.getContextPath()) .append("\">Continue...</a></h1>\n"); response.getWriter().write(html.toString()); return; } } } QuizItem quizItem = QuizItem.buildIdentifyHumanQuiz(12); String token = UUID.randomUUID().toString(); session.setAttribute("quizItem", quizItem); session.setAttribute("token", token); StringBuilder html = new StringBuilder(); html.append("<h1>").append("Click the correct meaning for the word <font color=\"red\">") .append(quizItem.getWord().getWord()).append(":</font></h1>\n"); html.append("<h2><ul>"); for (String option : quizItem.getMeanings()) { html.append("<li>").append("<a href=\"").append(servletContext.getContextPath()) .append("/identify.quiz?word=").append(quizItem.getWord().getWord()).append("&token=") .append(token).append("&answer=").append(URLEncoder.encode(option, "utf-8")).append("\">") .append(option).append("</a></li>\n"); } html.append("</ul></h2>\n").append( "<h1>If you can't answer the question correctly, you won't have the permission to access the web site.") .append("</h1>"); response.getWriter().write(html.toString()); return; } String key = getKey(request); AtomicInteger count = (AtomicInteger) servletContext.getAttribute(key); if (count == null) { count = new AtomicInteger(); servletContext.setAttribute(key, count); } if (count.incrementAndGet() > limit) { response.getWriter().write( "System has detected that your IP visit is too frequent and has automatically forbidden your vist. We are sorry to bring inconvenience to you, please understand, please come back tomorrow. Bye Bye!"); return; } chain.doFilter(req, resp); }
From source file:org.dataconservancy.dcs.util.DigestNotificationOutputStreamTest.java
@Test public void listenerNotifiedOnceTest() throws IOException, NoSuchAlgorithmException { final AtomicInteger count = new AtomicInteger(0); final OutputStream s = new DigestNotificationOutputStream(new ByteArrayOutputStream(), MessageDigest.getInstance("MD5"), new DigestListener() { @Override//from ww w . ja v a 2 s . co m public void notify(byte[] digestValue) throws IOException { count.getAndIncrement(); } }); IOUtils.copy(new ByteArrayInputStream(CONTENT.getBytes()), s); assertEquals(0, count.intValue()); s.close(); assertEquals(1, count.intValue()); s.close(); assertEquals(1, count.intValue()); }
From source file:org.dataconservancy.dcs.util.DigestNotificationStreamTest.java
@Test public void listenerNotifiedOnceTest() throws IOException, NoSuchAlgorithmException { final AtomicInteger count = new AtomicInteger(0); final InputStream s = new DigestNotificationStream(new ByteArrayInputStream(CONTENT.getBytes()), MessageDigest.getInstance("MD5"), new DigestListener() { @Override/* w w w .j av a2 s .com*/ public void notify(byte[] digestValue) throws IOException { count.getAndIncrement(); } }); assertEquals(0, count.intValue()); IOUtils.copy(s, new NullOutputStream()); assertEquals(1, count.intValue()); s.close(); assertEquals(1, count.intValue()); }
From source file:org.languagetool.rules.spelling.morfologik.suggestions_ordering.SuggestionsOrdererTest.java
public static void main(String[] args) throws IOException { Map<String, JLanguageTool> ltMap = new HashMap<>(); Map<String, Rule> rules = new HashMap<>(); Map<String, SuggestionsOrderer> ordererMap = new HashMap<>(); final AtomicInteger numOriginalCorrect = new AtomicInteger(0), numReorderedCorrect = new AtomicInteger(0), numOtherCorrect = new AtomicInteger(0), numBothCorrect = new AtomicInteger(0), numTotalReorderings = new AtomicInteger(0), numMatches = new AtomicInteger(0); AtomicLong totalReorderingComputationTime = new AtomicLong(0), totalHunspellComputationTime = new AtomicLong(0); Runtime.getRuntime()// w w w . jav a2s.co m .addShutdownHook(new Thread(() -> System.out.printf( "%n**** Correct Suggestions ****%nBoth: %d / Original: %d / Reordered: %d / Other: %d%n" + "Average time per reordering: %fms / Average time in match(): %fms%n", numBothCorrect.intValue(), numOriginalCorrect.intValue(), numReorderedCorrect.intValue(), numOtherCorrect.intValue(), (double) totalReorderingComputationTime.get() / numTotalReorderings.get(), (double) totalHunspellComputationTime.get() / numMatches.get()))); SuggestionsOrdererConfig.setNgramsPath(args[1]); try (CSVParser parser = new CSVParser(new FileReader(args[0]), CSVFormat.DEFAULT.withFirstRecordAsHeader())) { for (CSVRecord record : parser) { String lang = record.get("language"); String covered = record.get("covered"); String replacement = record.get("replacement"); String sentenceStr = record.get("sentence"); if (lang.equals("auto") || !(lang.equals("en-US") || lang.equals("de-DE"))) { // TODO: debugging only continue; // TODO do language detection? } Language language = Languages.getLanguageForShortCode(lang); JLanguageTool lt = ltMap.computeIfAbsent(lang, langCode -> new JLanguageTool(language)); Rule spellerRule = rules.computeIfAbsent(lang, langCode -> lt.getAllRules().stream() .filter(Rule::isDictionaryBasedSpellingRule).findFirst().orElse(null)); if (spellerRule == null) { continue; } SuggestionsOrderer orderer = null; try { orderer = ordererMap.computeIfAbsent(lang, langCode -> new SuggestionsOrdererGSoC(language, null, spellerRule.getId())); } catch (RuntimeException ignored) { } if (orderer == null) { continue; } numMatches.incrementAndGet(); AnalyzedSentence sentence = lt.getAnalyzedSentence(sentenceStr); long startTime = System.currentTimeMillis(); RuleMatch[] matches = spellerRule.match(sentence); totalHunspellComputationTime.addAndGet(System.currentTimeMillis() - startTime); for (RuleMatch match : matches) { String matchedWord = sentence.getText().substring(match.getFromPos(), match.getToPos()); if (!matchedWord.equals(covered)) { //System.out.println("Other spelling error detected, ignoring: " + matchedWord + " / " + covered); continue; } List<String> original = match.getSuggestedReplacements(); SuggestionsOrdererConfig.setMLSuggestionsOrderingEnabled(true); numTotalReorderings.incrementAndGet(); startTime = System.currentTimeMillis(); List<String> reordered = orderer.orderSuggestionsUsingModel(original, matchedWord, sentence, match.getFromPos()); totalReorderingComputationTime.addAndGet(System.currentTimeMillis() - startTime); SuggestionsOrdererConfig.setMLSuggestionsOrderingEnabled(false); if (original.isEmpty() || reordered.isEmpty()) { continue; } String firstOriginal = original.get(0); String firstReordered = reordered.get(0); if (firstOriginal.equals(firstReordered)) { if (firstOriginal.equals(replacement)) { numBothCorrect.incrementAndGet(); } else { numOtherCorrect.incrementAndGet(); } //System.out.println("No change for match: " + matchedWord); } else { System.out.println("Ordering changed for match " + matchedWord + ", before: " + firstOriginal + ", after: " + firstReordered + ", choosen: " + replacement); if (firstOriginal.equals(replacement)) { numOriginalCorrect.incrementAndGet(); } else if (firstReordered.equals(replacement)) { numReorderedCorrect.incrementAndGet(); } else { numOtherCorrect.incrementAndGet(); } } } } } }
From source file:org.languagetool.rules.spelling.SuggestionsChangesTest.java
/*** * TODO: document/*from w ww . j ava 2s. c o m*/ * @throws IOException */ @Test public void testChanges() throws IOException { String correctionsFileLocation = System.getProperty("correctionsFileLocation"); assertNotEquals("needs corrections data", null, correctionsFileLocation); String testMode = System.getProperty("suggestionsTestMode"); assertThat(testMode, is(anyOf(equalTo("A"), equalTo("B"), equalTo("AB")))); if (testMode.equals("A") || testMode.equals("B")) { String modeValue = testMode.equals("A") ? "0" : "1"; System.setProperty("SuggestionsChangesTestAlternativeEnabled", modeValue); } String languagesValue = System.getProperty("languages"); Set<Language> languages = new HashSet<>(); if (languagesValue == null) { // default -> all languages languages.addAll(Languages.get()); } else { for (String langCode : languagesValue.split(",")) { languages.add(Languages.getLanguageForShortCode(langCode)); } } Random sampler = new Random(0); final float SAMPLE_RATE = 1f; Map<String, JLanguageTool> ltMap = new HashMap<>(); Map<String, Rule> rules = new HashMap<>(); final AtomicInteger numOriginalCorrect = new AtomicInteger(0), numReorderedCorrect = new AtomicInteger(0), numOtherCorrect = new AtomicInteger(0), numBothCorrect = new AtomicInteger(0), numMatches = new AtomicInteger(0), numCorrectSuggestion = new AtomicInteger(0), numTotal = new AtomicInteger(0); Runtime.getRuntime().addShutdownHook(new Thread(() -> { if (testMode.equals("AB")) { System.out.printf( "%n**** Correct Suggestions ****%nBoth: %d / Original: %d / Reordered: %d / Other: %d%n", numBothCorrect.intValue(), numOriginalCorrect.intValue(), numReorderedCorrect.intValue(), numOtherCorrect.intValue()); int total = numOriginalCorrect.intValue() + numReorderedCorrect.intValue() + numOtherCorrect.intValue() + numBothCorrect.intValue(); float accuracyA = (float) (numBothCorrect.intValue() + numOriginalCorrect.intValue()) / total; float accuracyB = (float) (numBothCorrect.intValue() + numReorderedCorrect.intValue()) / total; System.out.printf("**** Accuracy ****%nA: %f / B: %f%n", accuracyA, accuracyB); } else { String name = testMode.equals("A") ? "Original" : "Alternative"; int correct = numCorrectSuggestion.intValue(); int total = numTotal.intValue(); float percentage = 100f * ((float) correct / total); System.out.printf("%n**** Correct Suggestions ****%n %s: %d / %d (%f%%)%n", name, correct, total, percentage); } })); try (CSVParser parser = new CSVParser(new FileReader(correctionsFileLocation), CSVFormat.DEFAULT.withFirstRecordAsHeader())) { for (CSVRecord record : parser) { if (sampler.nextFloat() > SAMPLE_RATE) { continue; } String lang = record.get("language"); String covered = record.get("covered"); String replacement = record.get("replacement"); //String sentenceStr = record.get("sentence"); if (lang.equals("auto")) { continue; // TODO do language detection? } Language language = Languages.getLanguageForShortCode(lang); if (!languages.contains(language)) { continue; } JLanguageTool lt = ltMap.computeIfAbsent(lang, langCode -> { try { JLanguageTool tool = new JLanguageTool(language); tool.activateLanguageModelRules(new File("ngrams/")); return tool; } catch (IOException e) { throw new RuntimeException(e); } }); Rule spellerRule = rules.computeIfAbsent(lang, langCode -> lt.getAllRules().stream() .filter(Rule::isDictionaryBasedSpellingRule).findFirst().orElse(null)); if (spellerRule == null) { continue; } numMatches.incrementAndGet(); //AnalyzedSentence sentence = lt.getAnalyzedSentence(sentenceStr); AnalyzedSentence sentence = lt.getAnalyzedSentence(covered); if (testMode.equals("AB")) { System.setProperty("SuggestionsChangesTestAlternativeEnabled", "0"); RuleMatch[] originalMatches = spellerRule.match(sentence); System.setProperty("SuggestionsChangesTestAlternativeEnabled", "1"); RuleMatch[] alternativeMatches = spellerRule.match(sentence); assertEquals(originalMatches.length, alternativeMatches.length); for (int i = 0; i < originalMatches.length; i++) { RuleMatch original = originalMatches[i]; RuleMatch alternative = alternativeMatches[i]; String matchedWord = sentence.getText().substring(original.getFromPos(), original.getToPos()); String matchedWord2 = sentence.getText().substring(alternative.getFromPos(), alternative.getToPos()); assertEquals(matchedWord, matchedWord2); if (!matchedWord.equals(covered)) { //System.out.println("Other spelling error detected, ignoring: " + matchedWord + " / " + covered); continue; } List<String> originalSuggestions = original.getSuggestedReplacements(); List<String> alternativeSuggestions = alternative.getSuggestedReplacements(); if (originalSuggestions.size() == 0 || alternativeSuggestions.size() == 0) { continue; } String firstOriginal = originalSuggestions.get(0); String firstAlternative = alternativeSuggestions.get(0); if (firstOriginal.equals(firstAlternative)) { if (firstOriginal.equals(replacement)) { numBothCorrect.incrementAndGet(); } else { numOtherCorrect.incrementAndGet(); } System.out.println("No change for match: " + matchedWord); } else { String correct; if (firstOriginal.equals(replacement)) { numOriginalCorrect.incrementAndGet(); correct = "A"; } else if (firstAlternative.equals(replacement)) { numReorderedCorrect.incrementAndGet(); correct = "B"; } else { numOtherCorrect.incrementAndGet(); correct = "other"; } System.out.printf( "Ordering changed for match %s, before: %s, after: %s, choosen: %s, correct: %s%n", matchedWord, firstOriginal, firstAlternative, replacement, correct); } } } else { RuleMatch[] matches = spellerRule.match(sentence); for (RuleMatch match : matches) { String matchedWord = sentence.getText().substring(match.getFromPos(), match.getToPos()); if (!matchedWord.equals(covered)) { //System.out.println("Other spelling error detected, ignoring: " + matchedWord + " / " + covered); continue; } List<String> suggestions = match.getSuggestedReplacements(); if (suggestions.size() == 0) { continue; } String first = suggestions.get(0); numTotal.incrementAndGet(); System.out.printf("Correction for %s: %s %s / chosen: %s -> position %d%n", covered, first, suggestions.subList(1, Math.min(suggestions.size(), 5)), replacement, suggestions.indexOf(replacement)); if (first.equals(replacement)) { numCorrectSuggestion.incrementAndGet(); } } } } } }
From source file:org.mule.transport.sftp.AbstractSftpTestCase.java
/** Base method for executing tests... */ protected void executeBaseTest(String inputEndpointName, String sendUrl, String filename, final int size, String receivingTestComponentName, long timeout, String expectedFailingConnector, String serviceName) throws Exception { MuleClient client = new MuleClient(muleContext); // Do some cleaning so that the endpoint doesn't have any other files // We don't need to do this anymore since we are deleting and then creating // the directory for each test // cleanupRemoteFtpDirectory(client, inputEndpointName); final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger loopCount = new AtomicInteger(0); final AtomicInteger totalReceivedSize = new AtomicInteger(0); // Random byte that we want to send a lot of final int testByte = 42; EventCallback callback = new EventCallback() { @Override// w w w . j a va2 s.c om public void eventReceived(MuleEventContext context, Object component) throws Exception { if (logger.isInfoEnabled()) logger.info("called " + loopCount.incrementAndGet() + " times"); InputStream sftpInputStream = (InputStream) context.getMessage().getPayload(); BufferedInputStream bif = new BufferedInputStream(sftpInputStream); byte[] buffer = new byte[1024 * 4]; try { int n; while (-1 != (n = bif.read(buffer))) { totalReceivedSize.addAndGet(n); // Simple check to verify the data... for (byte b : buffer) { if (b != testByte) { fail("Incorrect received byte (was '" + b + "', expected '" + testByte + "'"); } } } } finally { bif.close(); } latch.countDown(); } }; getFunctionalTestComponent(receivingTestComponentName).setEventCallback(callback); final ValueHolder<Exception> exceptionHolder = new ValueHolder<Exception>(); if (expectedFailingConnector != null) { // Register an exception-listener on the connector that expects to fail // and count down the latch after saving the thrown exception muleContext.setExceptionListener(new SystemExceptionHandler() { @Override public void handleException(Exception e, RollbackSourceCallback rollbackMethod) { if (logger.isInfoEnabled()) logger.info("expected exception occurred: " + e, e); exceptionHolder.value = e; latch.countDown(); } @Override public void handleException(Exception exception) { handleException(exception, null); } }); if (serviceName != null && !(serviceName.length() == 0)) { muleContext.getRegistry().lookupService(serviceName) .setExceptionListener(new MessagingExceptionHandler() { @Override public MuleEvent handleException(Exception e, MuleEvent event) { if (logger.isInfoEnabled()) logger.info("expected exception occurred: " + e, e); exceptionHolder.value = e; latch.countDown(); return event; } }); } } // InputStream that generates the data without using a file InputStream os = new InputStream() { int totSize = 0; @Override public int read() throws IOException { totSize++; if (totSize <= size) { return testByte; } else { return -1; } } }; HashMap<String, String> props = new HashMap<String, String>(1); props.put(SftpConnector.PROPERTY_FILENAME, filename); props.put(SftpConnector.PROPERTY_ORIGINAL_FILENAME, filename); if (logger.isInfoEnabled()) logger.info(StringMessageUtils.getBoilerPlate( "Note! If this test fails due to timeout please add '-Dmule.test.timeoutSecs=XX' to the mvn command!")); executeBaseAssertionsBeforeCall(); // Send the content using stream client.dispatch(sendUrl, os, props); boolean workDone = latch.await(timeout, TimeUnit.MILLISECONDS); assertTrue("Test timed out. It took more than " + timeout + " milliseconds. If this error occurs the test probably needs a longer time out (on your computer/network)", workDone); // Rethrow any exception that we have caught in an exception-listener if (exceptionHolder.value != null) { throw exceptionHolder.value; } executeBaseAssertionsAfterCall(size, totalReceivedSize.intValue()); }
From source file:org.neo4j.browser.CannedCypherExecutionTest.java
@Test public void shouldBeAbleToExecuteAllTheCannedCypherQueriesContainedInStaticHtmlFiles() throws Exception { URL resourceLoc = getClass().getClassLoader().getResource("browser"); assertNotNull(resourceLoc);//w w w. j a va 2 s .c om final AtomicInteger explainCount = new AtomicInteger(0); final AtomicInteger executionCount = new AtomicInteger(0); Files.walkFileTree(Paths.get(resourceLoc.toURI()), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { final GraphDatabaseService database = new TestGraphDatabaseFactory().newImpermanentDatabase(); String fileName = file.getFileName().toString(); if (fileName.endsWith(".html")) { String content = FileUtils.readTextFile(file.toFile(), Charsets.UTF_8); Elements cypherElements = Jsoup.parse(content).select("pre.runnable") .not(".standalone-example"); for (Element cypherElement : cypherElements) { String statement = replaceAngularExpressions(cypherElement.text()); if (!statement.startsWith(":")) { if (shouldExplain(statement)) { try (Transaction transaction = database.beginTx()) { Iterable<Notification> actual = database.execute(prependExplain(statement)) .getNotifications(); boolean skipKnownInefficientCypher = !cypherElement.parent().select(".warn") .isEmpty(); if (skipKnownInefficientCypher) { List<Notification> targetCollection = new ArrayList<Notification>(); CollectionUtils.addAll(targetCollection, actual); CollectionUtils.filter(targetCollection, new org.apache.commons.collections4.Predicate<Notification>() { @Override public boolean evaluate(Notification notification) { return notification.getDescription() .contains(NotificationCode.CARTESIAN_PRODUCT .values().toString()); } }); assertThat( format("Query [%s] should only produce cartesian product " + "notifications. [%s]", statement, fileName), targetCollection, empty()); explainCount.incrementAndGet(); transaction.success(); } else { assertThat(format("Query [%s] should produce no notifications. [%s]", statement, fileName), actual, is(emptyIterable())); explainCount.incrementAndGet(); transaction.success(); } } catch (QueryExecutionException e) { throw new AssertionError( format("Failed to explain query [%s] in file [%s]", statement, file), e); } } try (Transaction transaction = database.beginTx()) { database.execute(statement); executionCount.incrementAndGet(); transaction.success(); } catch (QueryExecutionException e) { throw new AssertionError( format("Failed to execute query [%s] in file [%s]", statement, file), e); } } } } return FileVisitResult.CONTINUE; } }); assertTrue("Static files should contain at least one valid cypher statement", executionCount.intValue() >= 1); System.out.printf("Explained %s cypher statements extracted from HTML files, with no notifications.%n", explainCount); System.out.printf("Executed %s cypher statements extracted from HTML files, with no errors.%n", executionCount); }
From source file:org.polymap.biotop.model.importer.MdbImportOperation.java
protected IStatus doExecute(IProgressMonitor monitor, IAdaptable info) throws Exception { monitor.beginTask(getLabel(), 120);//from www . j a va 2 s. com Database db = Database.open(dbFile); try { SubMonitor sub = null; // BiotopComposite sub = new SubMonitor(monitor, 10); importBiotopdaten(db.getTable("Biotopdaten"), sub); // Pflanzen sub = new SubMonitor(monitor, 10); importEntity(db, sub, PflanzenArtComposite.class, "Nr_Planze", null); sub = new SubMonitor(monitor, 10); importValue(db, sub, PflanzeValue.class, new ValueCallback<PflanzeValue>() { public void fillValue(BiotopComposite biotop, PflanzeValue value) { Collection<PflanzeValue> coll = biotop.pflanzen().get(); coll.add(value); biotop.pflanzen().set(coll); } }); // Moose/Flechten/Pilze sub = new SubMonitor(monitor, 10); importEntity(db, sub, PilzArtComposite.class, "Nr_Art", null); sub = new SubMonitor(monitor, 10); importValue(db, sub, PilzValue.class, new ValueCallback<PilzValue>() { public void fillValue(BiotopComposite biotop, PilzValue value) { Collection<PilzValue> coll = biotop.pilze().get(); coll.add(value); biotop.pilze().set(coll); } }); // Tiere sub = new SubMonitor(monitor, 10); importEntity(db, sub, TierArtComposite.class, "Nr_Tier", null); sub = new SubMonitor(monitor, 10); importValue(db, sub, TierValue.class, new ValueCallback<TierValue>() { public void fillValue(BiotopComposite biotop, TierValue value) { Collection<TierValue> coll = biotop.tiere().get(); coll.add(value); biotop.tiere().set(coll); } }); // Gefhrdungen/Beeintrchtigungen sub = new SubMonitor(monitor, 10); importEntity(db, sub, StoerungsArtComposite.class, "Nr_Beeintrchtigung", null); sub = new SubMonitor(monitor, 10); importValue(db, sub, StoerungValue.class, new ValueCallback<StoerungValue>() { public void fillValue(BiotopComposite biotop, StoerungValue value) { Collection<StoerungValue> coll = biotop.stoerungen().get(); coll.add(value); biotop.stoerungen().set(coll); } }); // Wert(bestimmend) sub = new SubMonitor(monitor, 10); importEntity(db, sub, WertArtComposite.class, "Nr_Wertbestimmend", null); sub = new SubMonitor(monitor, 10); importValue(db, sub, WertValue.class, new ValueCallback<WertValue>() { public void fillValue(BiotopComposite biotop, WertValue value) { Collection<WertValue> coll = biotop.werterhaltend().get(); coll.add(value); biotop.werterhaltend().set(coll); } }); // Biotoptyp (als letztes damit Biotope vollstndig kopiert werden) sub = new SubMonitor(monitor, 10); importEntity(db, sub, BiotoptypArtComposite.class, "Nr_Biotoptyp", null); sub = new SubMonitor(monitor, 10); final AtomicInteger copied = new AtomicInteger(0); importValue(db, sub, BiotoptypValue.class, new ValueCallback<BiotoptypValue>() { public void fillValue(final BiotopComposite biotop, final BiotoptypValue value) { String unr = value.unternummer().get(); assert unr != null : "Value-Unternummer == null"; String bunr = biotop.unr().get(); assert bunr != null : "Biotop-Unternummer == null"; if (unr.equals(bunr)) { // set nummer if (biotop.biotoptypArtNr().get() == null) { biotop.biotoptypArtNr().set(value.biotoptypArtNr().get()); biotop.pflegeRueckstand().set(value.pflegerueckstand().get()); } // biotop exists -> copy biotop else { try { BiotopComposite copy = repo.newBiotop(new EntityCreator<BiotopComposite>() { public void create(BiotopComposite prototype) throws Exception { prototype.copyStateFrom(biotop); prototype.objnr().set(repo.biotopnummern.get().generate()); prototype.biotoptypArtNr().set(value.biotoptypArtNr().get()); prototype.pflegeRueckstand().set(value.pflegerueckstand().get()); } }); copied.incrementAndGet(); } catch (Exception e) { throw new RuntimeException(e); } } } } }); log.info("Copies of BiotopComposite: " + copied.intValue()); } finally { db.close(); db = null; } return Status.OK_STATUS; }
From source file:org.talend.repository.nosql.ui.common.AbstractNoSQLRetrieveSchemaForm.java
public void restoreCheckItems() { Map<TreeItem, AtomicInteger> checkedDBMap = new HashMap<TreeItem, AtomicInteger>(); TreeItem[] items = schemaTree.getItems(); for (TreeItem treeItem : items) { udpateItemsStatus(treeItem, checkedDBMap); }//from ww w . ja v a2s.c o m Iterator<Entry<TreeItem, AtomicInteger>> iter = checkedDBMap.entrySet().iterator(); while (iter.hasNext()) { Entry<TreeItem, AtomicInteger> entry = iter.next(); TreeItem item = entry.getKey(); AtomicInteger count = entry.getValue(); if (count.intValue() == 0 && item.getData() != null) { schemaViewer.collapseToLevel(item.getData(), 1); } } }
From source file:org.testdwr.plain.Test.java
public Verify checkScriptSessionListener(final JavascriptFunction progress1, final JavascriptFunction progress2) { final ServerContext serverContext = ServerContextFactory.get(); final String testPage = serverContext.getContextPath() + "/checkSession.html"; Verify verify = new Verify(); final int createdBefore = TestScriptSessionListener.created; final int createdBefore2 = Test2ScriptSessionListener.created; final int destroyedBefore = TestScriptSessionListener.destroyed; final int destroyedBefore2 = Test2ScriptSessionListener.destroyed; // At least one test window is open ... verify.isTrue("createdBefore > 0", createdBefore > 0); verify.isTrue("createdBefore2 > 0", createdBefore2 > 0); // Open a new window Window.open(testPage, "checkSession"); // We'll fill these in in the first cron, and use them in the second final AtomicInteger createdMid = new AtomicInteger(); final AtomicInteger createdMid2 = new AtomicInteger(); final AtomicInteger destroyedMid = new AtomicInteger(); final AtomicInteger destroyedMid2 = new AtomicInteger(); // Give it a second to open, check counters and close it ScheduledThreadPoolExecutor executorService = serverContext.getContainer() .getBean(ScheduledThreadPoolExecutor.class); executorService.schedule(new Runnable() { public void run() { createdMid.set(TestScriptSessionListener.created); createdMid2.set(Test2ScriptSessionListener.created); destroyedMid.set(TestScriptSessionListener.destroyed); destroyedMid2.set(Test2ScriptSessionListener.destroyed); Verify verify1 = new Verify(); verify1.isTrue("createdMid > createdBefore", createdMid.intValue() > createdBefore); verify1.isTrue("createdMid2 > createdBefore2", createdMid2.intValue() > createdBefore2); verify1.equals("destroyedMid == destroyedBefore", destroyedMid.intValue(), destroyedBefore); verify1.equals("destroyedMid2 == destroyedBefore2", destroyedMid2.intValue(), destroyedBefore2); // Find it and close it Browser.withPage(testPage, new Runnable() { public void run() { Window.close(); }//from w ww.j av a2 s. co m }); progress1.executeAndClose(verify1); } }, 1, TimeUnit.SECONDS); // Give it 2 seconds to open and be closed then check counters again executorService.schedule(new Runnable() { public void run() { int createdAfter = TestScriptSessionListener.created; int createdAfter2 = Test2ScriptSessionListener.created; int destroyedAfter = TestScriptSessionListener.destroyed; int destroyedAfter2 = Test2ScriptSessionListener.destroyed; Verify verify2 = new Verify(); verify2.equals("createdAfter == createdMid", createdAfter, createdMid.intValue()); verify2.equals("createdAfter2 == createdMid2", createdAfter2, createdMid2.intValue()); verify2.isTrue("destroyedAfter > destroyedMid", destroyedAfter > destroyedMid.intValue()); verify2.isTrue("destroyedAfter2 > destroyedMid2", destroyedAfter2 > destroyedMid2.intValue()); progress2.executeAndClose(verify2); } }, 2, TimeUnit.SECONDS); return verify; }