Example usage for java.util.function Consumer Consumer

List of usage examples for java.util.function Consumer Consumer

Introduction

In this page you can find the example usage for java.util.function Consumer Consumer.

Prototype

Consumer

Source Link

Usage

From source file:com.github.thesmartenergy.mdq.entities.Ontology.java

@PostConstruct
public void initialize() {
    try {//from w ww  . j a  v  a  2s  .  c o  m
        String dir = context.getRealPath("/WEB-INF/classes/");
        LOG.info(dir);
        LOG.info(context.getRealPath("/WEB-INF/classes"));
        LOG.info(context.getClassLoader().getResource("/").toString());
        LOG.info(context.getClassLoader().getResource("/").getPath());
        LOG.info(context.getClassLoader().getResource("/").toURI().toString());

        // initialize file manager
        fileManager = FileManager.makeGlobal();
        Locator loc = new LocatorFile(dir);
        Model conf = RDFDataMgr.loadModel(dir + "/configuration.ttl");
        LocationMapper mapper = new LocationMapper(conf);
        fileManager.addLocator(loc);
        fileManager.setLocationMapper(mapper);
        FileManager.setGlobalFileManager(fileManager);

        turtle = IOUtils.toString(fileManager.open(uri));
        Model model = ModelFactory.createDefaultModel().read(IOUtils.toInputStream(turtle), base, "TTL");
        model.listSubjects().forEachRemaining(new Consumer<Resource>() {
            @Override
            public void accept(Resource t) {
                if (!t.isURIResource()) {
                    return;
                }
                documents.put(t.getURI(), Ontology.this);
            }
        });
        documents.put(uri, this);

        // parse the SPARQL-Generate query and create plan
        String queryString = IOUtils.toString(fileManager.open(base + "query/Vocabulary"));
        PlanFactory factory = new PlanFactory(fileManager);
        RootPlan plan = factory.create(queryString);

        // parse each vocabulary
        File vocabDir = new File(Ontology.class.getResource("/vocab").toURI());
        for (File vocabFile : vocabDir.listFiles()) {
            // create the initial model
            Model vocabModel = ModelFactory.createDefaultModel();

            // create the initial binding
            String variable = "msg";
            String uri = "urn:iana:mime:application/json";
            String message = IOUtils.toString(new FileInputStream(vocabFile));
            QuerySolutionMap initialBinding = new QuerySolutionMap();
            TypeMapper typeMapper = TypeMapper.getInstance();
            RDFDatatype dt = typeMapper.getSafeTypeByName(uri);
            Node arqLiteral = NodeFactory.createLiteral(message, dt);
            RDFNode jenaLiteral = vocabModel.asRDFNode(arqLiteral);
            initialBinding.add(variable, jenaLiteral);

            // execute the plan
            plan.exec(initialBinding, vocabModel);

            //                File f = new File("C:/temp/mdq/out.ttl");
            //                OutputStream out = new FileOutputStream(f);
            //                vocabModel.write(out, "TTL"); 
            //                out.close();

            // get the uri of the vocabulary                
            Resource vocabResource = vocabModel
                    .listSubjectsWithProperty(
                            vocabModel.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
                            vocabModel.createResource("http://purl.org/vocommons/voaf#Vocabulary"))
                    .nextResource();

            // set the vocabulary
            final Vocabulary vocabularyDocument = new Vocabulary(this, vocabModel);
            documents.put(vocabResource.getURI(), vocabularyDocument);

            // get the uri of each of the resources defined by the vocabulary
            vocabModel.listSubjectsWithProperty(
                    vocabModel.createProperty("http://www.w3.org/2000/01/rdf-schema#isDefinedBy"),
                    vocabResource).forEachRemaining(new Consumer<Resource>() {
                        @Override
                        public void accept(Resource t) {
                            if (!t.isURIResource()) {
                                return;
                            }
                            documents.put(t.getURI(), vocabularyDocument);
                        }
                    });
        }
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, "error while initializing app ", ex);
        throw new RuntimeException("error while initializing app ", ex);
    }
}

From source file:de.burrotinto.jKabel.dispalyAS.DisplayK.java

@Bean(name = "trommeln")
public JMenu allTrommel(IDBWrapper db) {
    JMenu m = new JMenu("Trommeln");

    db.getAllKabeltypen().forEach(new Consumer<IKabeltypE>() {
        @Override/*from w  w  w  .  j av a  2  s.  c  om*/
        public void accept(IKabeltypE iKabeltypE) {
            iKabeltypE.getTrommeln().forEach(new Consumer<ITrommelE>() {
                @Override
                public void accept(ITrommelE iTrommelE) {
                    m.add(iTrommelE.getId() + " " + iTrommelE.getTrommelnummer());
                }
            });
        }
    });
    return m;
}

From source file:gov.va.isaac.workflow.engine.RemoteSynchronizer.java

/**
 * Request a remote synchronization. This call blocks until the operation is complete,
 * or the thread is interrupted.//from ww w  . ja v a  2s.co  m
 * 
 * @throws InterruptedException
 */
public SynchronizeResult blockingSynchronize() throws InterruptedException {
    log.info("Queuing a blocking sync request");
    final MutableObject<SynchronizeResult> result = new MutableObject<SynchronizeResult>();
    final CountDownLatch cdl = new CountDownLatch(1);
    Consumer<SynchronizeResult> callback = new Consumer<SynchronizeResult>() {
        @Override
        public void accept(SynchronizeResult t) {
            result.setValue(t);
            cdl.countDown();
        }
    };

    synchronize(callback);
    cdl.await();
    return result.getValue();
}

From source file:net.sf.mzmine.chartbasics.gestures.ChartGestureDragDiffHandler.java

/**
 * Handle PRESSED, DRAGGED, RELEASED events to generate drag diff events
 * //from   ww  w.  ja v  a  2 s  .co m
 * @return
 */
private Consumer<ChartGestureEvent> createConsumer() {
    return new Consumer<ChartGestureEvent>() {
        // variables
        boolean wasMouseZoomable = false;
        Point2D last = null, first = null;
        ChartGestureEvent startEvent = null, lastEvent = null;

        @Override
        public void accept(ChartGestureEvent event) {
            ChartViewWrapper chartPanel = event.getChartWrapper();
            JFreeChart chart = chartPanel.getChart();
            MouseEventWrapper e = event.getMouseEvent();

            // released?
            if (event.checkEvent(Event.RELEASED)) {
                chartPanel.setMouseZoomable(wasMouseZoomable);
                last = null;
            } else if (event.checkEvent(Event.PRESSED)) {
                // get data space coordinates
                last = chartPanel.mouseXYToPlotXY(e.getX(), e.getY());
                first = last;
                startEvent = event;
                lastEvent = event;
                if (last != null) {
                    wasMouseZoomable = chartPanel.isMouseZoomable();
                    chartPanel.setMouseZoomable(false);
                }
            } else if (event.checkEvent(Event.DRAGGED)) {
                if (last != null) {
                    // get data space coordinates
                    Point2D released = chartPanel.mouseXYToPlotXY(e.getX(), e.getY());
                    if (released != null) {
                        double offset = 0;
                        double start = 0;
                        // scroll x
                        if (getOrientation(event).equals(Orientation.HORIZONTAL)) {
                            offset = -(released.getX() - last.getX());
                            start = first.getX();
                        }
                        // scroll y
                        else {
                            offset = -(released.getY() - last.getY());
                            start = first.getY();
                        }

                        // new dragdiff event
                        ChartGestureDragDiffEvent dragEvent = new ChartGestureDragDiffEvent(startEvent,
                                lastEvent, event, start, offset, orient);
                        // scroll / zoom / do anything with this new event
                        // choose handler by key filter
                        for (int i = 0; i < dragDiffHandler.length; i++)
                            if (key[i].filter(event.getMouseEvent()))
                                dragDiffHandler[i].accept(dragEvent);
                        // set last event
                        lastEvent = event;
                        // save updated last
                        last = chartPanel.mouseXYToPlotXY(e.getX(), e.getY());
                    }
                }
            }
        }
    };
}

From source file:org.dspace.app.rest.repository.BrowseEntryLinkRepository.java

public Page<BrowseEntryRest> listBrowseEntries(HttpServletRequest request, String browseName, Pageable pageable,
        String projection) throws BrowseException, SQLException {
    // FIXME this should be bind automatically and available as method
    // argument//from w  w w  .java2  s  . co  m
    String scope = null;
    if (request != null) {
        scope = request.getParameter("scope");
    }

    Context context = obtainContext();
    BrowseEngine be = new BrowseEngine(context);
    BrowserScope bs = new BrowserScope(context);
    DSpaceObject scopeObj = null;
    if (scope != null) {
        UUID uuid = UUID.fromString(scope);
        scopeObj = communityService.find(context, uuid);
        if (scopeObj == null) {
            scopeObj = collectionService.find(context, uuid);
        }
    }

    // process the input, performing some inline validation
    final BrowseIndex bi;
    if (StringUtils.isNotEmpty(browseName)) {
        bi = BrowseIndex.getBrowseIndex(browseName);
    } else {
        bi = null;
    }
    if (bi == null) {
        throw new IllegalArgumentException("Unknown browse index");
    }
    if (!bi.isMetadataIndex()) {
        throw new IllegalStateException("The requested browse haven't metadata entries");
    }

    // set up a BrowseScope and start loading the values into it
    bs.setBrowseIndex(bi);
    Sort sort = null;
    if (pageable != null) {
        sort = pageable.getSort();
    }
    if (sort != null) {
        Iterator<Order> orders = sort.iterator();
        while (orders.hasNext()) {
            bs.setOrder(orders.next().getDirection().name());
        }
    }
    // bs.setFilterValue(value != null?value:authority);
    // bs.setFilterValueLang(valueLang);
    // bs.setJumpToItem(focus);
    // bs.setJumpToValue(valueFocus);
    // bs.setJumpToValueLang(valueFocusLang);
    // bs.setStartsWith(startsWith);
    if (pageable != null) {
        bs.setOffset(pageable.getOffset());
        bs.setResultsPerPage(pageable.getPageSize());
    }
    // bs.setEtAl(etAl);
    // bs.setAuthorityValue(authority);

    if (scopeObj != null) {
        bs.setBrowseContainer(scopeObj);
    }

    BrowseInfo binfo = be.browse(bs);
    Pageable pageResultInfo = new PageRequest((binfo.getStart() - 1) / binfo.getResultsPerPage(),
            binfo.getResultsPerPage());
    Page<BrowseEntryRest> page = new PageImpl<String[]>(Arrays.asList(binfo.getStringResults()), pageResultInfo,
            binfo.getTotal()).map(converter);
    page.forEach(new Consumer<BrowseEntryRest>() {
        @Override
        public void accept(BrowseEntryRest t) {
            t.setBrowseIndex(bixConverter.convert(bi));
        }
    });
    return page;
}

From source file:com.diversityarrays.kdxplore.trialdesign.RscriptFinderPanel.java

public RscriptFinderPanel(BackgroundRunner br, Component component, String initialScriptPath,
        Consumer<Either<Throwable, String>> onScriptPathChecked) {
    super(new BorderLayout());

    backgroundRunner = br;//  w w w .  ja  va  2 s  .  c o m
    this.onScriptPathChecked = onScriptPathChecked;

    scriptPathField.setText(initialScriptPath);
    scriptPathField.addMouseListener(clickAdapter);

    Box scriptPathBox = Box.createHorizontalBox();

    Consumer<Void> updateFindScriptButton = new Consumer<Void>() {
        @Override
        public void accept(Void t) {
            checkScriptPath.setEnabled(!scriptPathField.getText().trim().isEmpty());
        }
    };

    scriptPathBox.add(scriptPathField);
    scriptPathBox.add(new JButton(checkScriptPath));
    scriptPathField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            updateFindScriptButton.accept(null);
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            updateFindScriptButton.accept(null);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            updateFindScriptButton.accept(null);
        }
    });
    updateFindScriptButton.accept(null);

    add(scriptPathBox, BorderLayout.NORTH);
    if (component != null) {
        add(component, BorderLayout.CENTER);
    }
}

From source file:dk.dma.ais.decode.DecodeTest.java

@Test
public void simpleDecodeTest() throws IOException {
    try (AisPacketReader r = AisPacketReader.createFromSystemResource("small_example.txt", true)) {
        r.forEachRemaining(new Consumer<AisPacket>() {
            public void accept(AisPacket t) {
            }//w ww.  jav a  2  s .c  o m
        });
    }
}

From source file:com.qwazr.crawler.web.driver.PhantomJSBrowserDriver.java

private Map<String, String> getHeaders() {
    if (endEntry == null)
        return null;
    if (headers != null)
        return headers;
    List<Map<String, ?>> entries = (List<Map<String, ?>>) endEntry.get("headers");
    if (entries == null)
        return null;
    final Map<String, String> headers = new LinkedHashMap<>();
    entries.forEach(new Consumer<Map<String, ?>>() {
        @Override/* w  w  w  .j av  a 2  s. c  om*/
        public void accept(Map<String, ?> map) {
            Object name = map.get("name");
            Object value = map.get("value");
            if (name == null || value == null)
                return;
            headers.put(name.toString().trim().toLowerCase(), value.toString());
        }
    });
    return this.headers = headers;
}

From source file:dk.dma.ais.decode.DecodeTest.java

@Test
public void decodeWithCommentBlocks() throws IOException {
    try (AisPacketReader r = AisPacketReader.createFromSystemResource("small_cb_example.txt", false)) {
        r.forEachRemainingMessage(new Consumer<AisMessage>() {
            public void accept(AisMessage t) {
                System.out.println(t.getVdm().getCommentBlock());
            }/*w w w .  ja  va  2s . c  o m*/
        });
    }
}

From source file:com.vsthost.rnd.jdeoptim.diagnostics.Diagnostics.java

/**
 * Defines a signal to be emitted when an evolution has started.
 *///from  w w  w. j  av a 2 s.c om
public void evolutionStarted() {
    this.observers.forEach(new Consumer<Listener>() {
        @Override
        public void accept(Listener observer) {
            observer.evolutionStarted();
        }
    });
}