List of usage examples for javax.swing ProgressMonitorInputStream ProgressMonitorInputStream
public ProgressMonitorInputStream(Component parentComponent, Object message, InputStream in)
From source file:com.monead.semantic.workbench.SemanticWorkbench.java
/** * Attempt to load a set of assertions with the supplied format (e.g. N3, * RDF/XML, etc)/*from w w w . j a v a 2s . c o m*/ * * @param format * The format to use, must be a value in the array FORMATS * * @throws IOException * If the file cannot be read */ private void tryFormat(String format) throws IOException { InputStream inputStream = null; try { LOGGER.debug("Start " + reasoningLevel.getSelectedItem().toString() + " model load and setup with format " + format); if (hasIncompleteAssertionsInput) { inputStream = new ProgressMonitorInputStream(this, "Reading file " + rdfFileSource.getAbsolutePath(), rdfFileSource.getInputStream()); if (rdfFileSource.isUrl()) { final ProgressMonitor pm = ((ProgressMonitorInputStream) inputStream).getProgressMonitor(); pm.setMaximum((int) rdfFileSource.length()); } LOGGER.debug("Using a ProgressMonitorInputStream"); } else { inputStream = new ByteArrayInputStream(assertionsInput.getText().getBytes("UTF-8")); } ontModel = createModel((ReasonerSelection) reasoningLevel.getSelectedItem()); LOGGER.debug("Begin loading model"); ontModel.read(inputStream, null, format.toUpperCase()); LOGGER.debug(reasoningLevel.getSelectedItem().toString() + " model load and setup completed"); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Throwable throwable) { LOGGER.error("Error closing input file", throwable); } } } }
From source file:org.apache.tika.gui.TikaGUI.java
private void handleStream(InputStream input, Metadata md) throws Exception { StringWriter htmlBuffer = new StringWriter(); StringWriter textBuffer = new StringWriter(); StringWriter textMainBuffer = new StringWriter(); StringWriter xmlBuffer = new StringWriter(); StringBuilder metadataBuffer = new StringBuilder(); ContentHandler handler = new TeeContentHandler(getHtmlHandler(htmlBuffer), getTextContentHandler(textBuffer), getTextMainContentHandler(textMainBuffer), getXmlContentHandler(xmlBuffer)); context.set(DocumentSelector.class, new ImageDocumentSelector()); input = TikaInputStream.get(new ProgressMonitorInputStream(this, "Parsing stream", input)); if (input.markSupported()) { int mark = -1; if (input instanceof TikaInputStream) { if (((TikaInputStream) input).hasFile()) { mark = (int) ((TikaInputStream) input).getLength(); }/*from w w w . jav a2 s. c om*/ } if (mark == -1) { mark = MAX_MARK; } input.mark(mark); } parser.parse(input, handler, md, context); String[] names = md.names(); Arrays.sort(names); for (String name : names) { for (String val : md.getValues(name)) { metadataBuffer.append(name); metadataBuffer.append(": "); metadataBuffer.append(val); metadataBuffer.append("\n"); } } String name = md.get(Metadata.RESOURCE_NAME_KEY); if (name != null && name.length() > 0) { setTitle("Apache Tika: " + name); } else { setTitle("Apache Tika: unnamed document"); } setText(metadata, metadataBuffer.toString()); setText(xml, xmlBuffer.toString()); setText(text, textBuffer.toString()); setText(textMain, textMainBuffer.toString()); setText(html, htmlBuffer.toString()); if (!input.markSupported()) { setText(json, "InputStream does not support mark/reset for Recursive Parsing"); layout.show(cards, "metadata"); return; } boolean isReset = false; try { input.reset(); isReset = true; } catch (IOException e) { setText(json, "Error during stream reset.\n" + "There's a limit of " + MAX_MARK + " bytes for this type of processing in the GUI.\n" + "Try the app with command line argument of -J."); } if (isReset) { RecursiveParserWrapper wrapper = new RecursiveParserWrapper(parser, new BasicContentHandlerFactory(BasicContentHandlerFactory.HANDLER_TYPE.BODY, -1)); wrapper.parse(input, null, new Metadata(), new ParseContext()); StringWriter jsonBuffer = new StringWriter(); JsonMetadataList.setPrettyPrinting(true); JsonMetadataList.toJson(wrapper.getMetadata(), jsonBuffer); setText(json, jsonBuffer.toString()); } layout.show(cards, "metadata"); }
From source file:org.silverpeas.openoffice.windows.webdav.WebdavManager.java
/** * Get the ressource from the webdav server. * * @param uri the uri to the ressource./*from ww w . j av a 2 s . c om*/ * @param lockToken the current lock token. * @return the path to the saved file on the filesystem. * @throws IOException */ public String getFile(URI uri, String lockToken) throws IOException { GetMethod method = executeGetFile(uri); String fileName = uri.getPath(); fileName = fileName.substring(fileName.lastIndexOf('/') + 1); fileName = URLDecoder.decode(fileName, "UTF-8"); UIManager.put("ProgressMonitor.progressText", MessageUtil.getMessage("download.file.title")); ProgressMonitorInputStream is = new ProgressMonitorInputStream(null, MessageUtil.getMessage("downloading.remote.file") + ' ' + fileName, new BufferedInputStream(method.getResponseBodyAsStream())); fileName = fileName.replace(' ', '_'); ProgressMonitor monitor = is.getProgressMonitor(); monitor.setMaximum(new Long(method.getResponseContentLength()).intValue()); monitor.setMillisToDecideToPopup(0); monitor.setMillisToPopup(0); File tempDir = new File(System.getProperty("java.io.tmpdir"), "silver-" + System.currentTimeMillis()); tempDir.mkdirs(); File tmpFile = new File(tempDir, fileName); FileOutputStream fos = new FileOutputStream(tmpFile); byte[] data = new byte[64]; int c; try { while ((c = is.read(data)) > -1) { fos.write(data, 0, c); } } catch (InterruptedIOException ioinex) { logger.log(Level.INFO, "{0} {1}", new Object[] { MessageUtil.getMessage("info.user.cancel"), ioinex.getMessage() }); unlockFile(uri, lockToken); System.exit(0); } finally { fos.close(); } return tmpFile.getAbsolutePath(); }
From source file:org.swiftexplorer.util.FileUtils.java
public static InputStream getInputStreamWithProgressMonitor(InputStream input, Component parentComponent, String message) {/*w w w. j av a2 s. c om*/ if (input == null) return null; Frame owner = null; if (parentComponent == null) owner = SwingUtils.tryFindSuitableFrameOwner(); InputStream in = new BufferedInputStream(new ProgressMonitorInputStream( (parentComponent == null) ? (owner) : (parentComponent), message, input)); return in; }
From source file:utybo.branchingstorytree.swing.OpenBSTGUI.java
private JMenu createShortMenu() { JMenu shortMenu = new JMenu(); addDarkModeCallback(b -> {/*from w w w . j a v a2s . co m*/ shortMenu.setBackground(b ? OPENBST_BLUE.darker().darker() : OPENBST_BLUE.brighter()); shortMenu.setForeground(b ? Color.WHITE : OPENBST_BLUE); }); shortMenu.setBackground(OPENBST_BLUE.brighter()); shortMenu.setForeground(OPENBST_BLUE); shortMenu.setText(Lang.get("banner.title")); shortMenu.setIcon(new ImageIcon(Icons.getImage("Logo", 16))); JMenuItem label = new JMenuItem(Lang.get("menu.title")); label.setEnabled(false); shortMenu.add(label); shortMenu.addSeparator(); shortMenu.add( new JMenuItem(new AbstractAction(Lang.get("menu.open"), new ImageIcon(Icons.getImage("Open", 16))) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { openStory(VisualsUtils.askForFile(OpenBSTGUI.this, Lang.get("file.title"))); } })); shortMenu.addSeparator(); shortMenu.add(new JMenuItem( new AbstractAction(Lang.get("menu.create"), new ImageIcon(Icons.getImage("Add Property", 16))) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { doNewEditor(); } })); JMenu additionalMenu = new JMenu(Lang.get("menu.advanced")); shortMenu.add(additionalMenu); additionalMenu.add(new JMenuItem( new AbstractAction(Lang.get("menu.package"), new ImageIcon(Icons.getImage("Open Archive", 16))) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { new PackageDialog(instance).setVisible(true); } })); additionalMenu.add(new JMenuItem( new AbstractAction(Lang.get("langcheck"), new ImageIcon(Icons.getImage("LangCheck", 16))) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { final Map<String, String> languages = new Gson() .fromJson(new InputStreamReader( OpenBST.class.getResourceAsStream( "/utybo/branchingstorytree/swing/lang/langs.json"), StandardCharsets.UTF_8), new TypeToken<Map<String, String>>() { }.getType()); languages.remove("en"); languages.remove("default"); JComboBox<String> jcb = new JComboBox<>(new Vector<>(languages.keySet())); JPanel panel = new JPanel(); panel.add(new JLabel(Lang.get("langcheck.choose"))); panel.add(jcb); int result = JOptionPane.showOptionDialog(OpenBSTGUI.this, panel, Lang.get("langcheck"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (result == JOptionPane.OK_OPTION) { Locale selected = new Locale((String) jcb.getSelectedItem()); if (!Lang.getMap().keySet().contains(selected)) { try { Lang.loadTranslationsFromFile(selected, OpenBST.class .getResourceAsStream("/utybo/branchingstorytree/swing/lang/" + languages.get(jcb.getSelectedItem().toString()))); } catch (UnrespectedModelException | IOException e1) { LOG.warn("Failed to load translation file", e1); } } ArrayList<String> list = new ArrayList<>(); Lang.getLocaleMap(Locale.ENGLISH).forEach((k, v) -> { if (!Lang.getLocaleMap(selected).containsKey(k)) { list.add(k + "\n"); } }); StringBuilder sb = new StringBuilder(); Collections.sort(list); list.forEach(s -> sb.append(s)); JDialog dialog = new JDialog(OpenBSTGUI.this, Lang.get("langcheck")); dialog.getContentPane().setLayout(new MigLayout()); dialog.getContentPane().add(new JLabel(Lang.get("langcheck.result")), "pushx, growx, wrap"); JTextArea area = new JTextArea(); area.setLineWrap(true); area.setWrapStyleWord(true); area.setText(sb.toString()); area.setEditable(false); area.setBorder(BorderFactory.createLoweredBevelBorder()); JScrollPane jsp = new JScrollPane(area); jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); dialog.getContentPane().add(jsp, "pushx, pushy, growx, growy"); dialog.setSize((int) (Icons.getScale() * 300), (int) (Icons.getScale() * 300)); dialog.setLocationRelativeTo(OpenBSTGUI.this); dialog.setModalityType(ModalityType.APPLICATION_MODAL); dialog.setVisible(true); } } })); additionalMenu.add(new JMenuItem( new AbstractAction(Lang.get("menu.debug"), new ImageIcon(Icons.getImage("Code", 16))) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { DebugInfo.launch(OpenBSTGUI.this); } })); JMenu includedFiles = new JMenu("Included BST files"); for (Entry<String, String> entry : OpenBST.getInternalFiles().entrySet()) { JMenuItem jmi = new JMenuItem(entry.getKey()); jmi.addActionListener(ev -> { String path = "/bst/" + entry.getValue(); InputStream is = OpenBSTGUI.class.getResourceAsStream(path); ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(OpenBSTGUI.this, "Extracting...", is); new Thread(() -> { try { File f = File.createTempFile("openbstinternal", ".bsp"); FileOutputStream fos = new FileOutputStream(f); IOUtils.copy(pmis, fos); openStory(f); } catch (final IOException e) { LOG.error("IOException caught", e); showException(Lang.get("file.error").replace("$e", e.getClass().getSimpleName()) .replace("$m", e.getMessage()), e); } }).start(); }); includedFiles.add(jmi); } additionalMenu.add(includedFiles); shortMenu.addSeparator(); JMenu themesMenu = new JMenu(Lang.get("menu.themes")); shortMenu.add(themesMenu); themesMenu.setIcon(new ImageIcon(Icons.getImage("Color Wheel", 16))); ButtonGroup themesGroup = new ButtonGroup(); JRadioButtonMenuItem jrbmi; jrbmi = new JRadioButtonMenuItem(Lang.get("menu.themes.dark")); if (0 == selectedTheme) { jrbmi.setSelected(true); } jrbmi.addActionListener(e -> switchLaF(0, DARK_THEME)); themesMenu.add(jrbmi); themesGroup.add(jrbmi); jrbmi = new JRadioButtonMenuItem(Lang.get("menu.themes.light")); if (1 == selectedTheme) { jrbmi.setSelected(true); } jrbmi.addActionListener(e -> switchLaF(1, LIGHT_THEME)); themesMenu.add(jrbmi); themesGroup.add(jrbmi); jrbmi = new JRadioButtonMenuItem(Lang.get("menu.themes.debug")); if (2 == selectedTheme) { jrbmi.setSelected(true); } jrbmi.addActionListener(e -> switchLaF(2, DEBUG_THEME)); themesMenu.add(jrbmi); themesGroup.add(jrbmi); JMenu additionalLightThemesMenu = new JMenu(Lang.get("menu.themes.morelight")); int j = 3; for (Map.Entry<String, LookAndFeel> entry : ADDITIONAL_LIGHT_THEMES.entrySet()) { int jf = j; jrbmi = new JRadioButtonMenuItem(entry.getKey()); if (j == selectedTheme) jrbmi.setSelected(true); jrbmi.addActionListener(e -> switchLaF(jf, entry.getValue())); additionalLightThemesMenu.add(jrbmi); themesGroup.add(jrbmi); j++; } themesMenu.add(additionalLightThemesMenu); JMenu additionalDarkThemesMenu = new JMenu(Lang.get("menu.themes.moredark")); for (Map.Entry<String, LookAndFeel> entry : ADDITIONAL_DARK_THEMES.entrySet()) { int jf = j; jrbmi = new JRadioButtonMenuItem(entry.getKey()); if (j == selectedTheme) jrbmi.setSelected(true); jrbmi.addActionListener(e -> switchLaF(jf, entry.getValue())); additionalDarkThemesMenu.add(jrbmi); themesGroup.add(jrbmi); j++; } themesMenu.add(additionalDarkThemesMenu); shortMenu.add(new JMenuItem( new AbstractAction(Lang.get("menu.about"), new ImageIcon(Icons.getImage("About", 16))) { /** * */ private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { new AboutDialog(instance).setVisible(true); } })); return shortMenu; }
From source file:utybo.branchingstorytree.swing.OpenBSTGUI.java
/** * Load and parse a file, using appropriate dialogs if an error occurs to * inform the user and even give him the option to reload the file * * @param file// w w w . j a v a 2 s .c o m * The file to load * @param client * The BST Client. This is required for parsing the file * @return */ public void loadFile(final File file, final TabClient client, Consumer<BranchingStory> callback) { SwingWorker<BranchingStory, Object> worker = new SwingWorker<BranchingStory, Object>() { @Override protected BranchingStory doInBackground() throws Exception { try { LOG.trace("Parsing story"); String ext = FilenameUtils.getExtension(file.getName()); BranchingStory bs = null; if (ext.equals("bsp")) { bs = BSTPackager.fromPackage(new ProgressMonitorInputStream(instance, "Opening " + file.getName() + "...", new FileInputStream(file)), client); } else { bs = parser .parse(new BufferedReader(new InputStreamReader( new ProgressMonitorInputStream(instance, "Opening " + file.getName() + "...", new FileInputStream(file)), StandardCharsets.UTF_8)), new Dictionary(), client, "<main>"); client.setBRMHandler(new BRMFileClient(file, client, bs)); } callback.accept(bs); return bs; } catch (final IOException e) { LOG.error("IOException caught", e); showException(Lang.get("file.error").replace("$e", e.getClass().getSimpleName()).replace("$m", e.getMessage()), e); return null; } catch (final BSTException e) { LOG.error("BSTException caught", e); String s = "<html>" + Lang.get("file.bsterror.1"); s += Lang.get("file.bsterror.2"); s += Lang.get("file.bsterror.3").replace("$l", "" + e.getWhere()).replace("$f", "[main]"); if (e.getCause() != null) { s += Lang.get("file.bsterror.4").replace("$e", e.getCause().getClass().getSimpleName()) .replace("$m", e.getCause().getMessage()); } s += Lang.get("file.bsterror.5").replace("$m", "" + e.getMessage()); s += Lang.get("file.bsterror.6"); String s2 = s; if (doAndReturn(() -> Messagers.showConfirm(instance, s2, Messagers.OPTIONS_YES_NO, Messagers.TYPE_ERROR, Lang.get("bsterror"))) == Messagers.OPTION_YES) { LOG.debug("Reloading"); return doInBackground(); } return null; } catch (final Exception e) { LOG.error("Random exception caught", e); showException(Lang.get("file.crash"), e); return null; } } private <T> T doAndReturn(Supplier<T> supplier) { ArrayList<T> l = new ArrayList<>(); invokeSwingAndWait(() -> { l.add(supplier.get()); }); return l.size() == 0 ? null : l.get(0); } @Override protected void done() { try { get(); } catch (InterruptedException e) { // Shouldn't happen } catch (ExecutionException e) { LOG.error("Random exception caught", e); Messagers.showException(instance, Lang.get("file.crash"), e); } } }; worker.execute(); }