Package javax.swing

Examples of javax.swing.ProgressMonitor$ProgressOptionPane


                Messages.getString("ClientFrame.104") + Messages.getString("ClientFrame.105"), //$NON-NLS-1$ //$NON-NLS-2$
                Messages.getString("ClientFrame.106"), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { //$NON-NLS-1$
            final Runnable removeTask = new Runnable() {
                @Override
                public void run() {
                    final ProgressMonitor monitor = new ProgressMonitor(ClientFrame.this, Messages.getString("ClientFrame.107"), Messages.getString("ClientFrame.108"), 1, res.length); //$NON-NLS-1$ //$NON-NLS-2$
                    monitor.setMillisToDecideToPopup(500);
                    monitor.setMillisToPopup(500);
                    for (int i = 0; i < res.length; i++) {
                        final ResourceDescriptor resource = res[i];
                        if (resource.isCollection()) {
                            try {
                                final CollectionManagementServiceImpl mgtService = (CollectionManagementServiceImpl) removeRootCollection
                                        .getService(
                                        "CollectionManagementService", //$NON-NLS-1$
                                        "1.0"); //$NON-NLS-1$
                                mgtService
                                        .removeCollection(resource.getName());
                            } catch (final XMLDBException e) {
                                showErrorMessage(e.getMessage(), e);
                            }
                        } else {
                            try {
                                final Resource res = removeRootCollection
                                        .getResource(resource.getName().toString());
                                removeRootCollection.removeResource(res);
                            } catch (final XMLDBException e) {
                                showErrorMessage(e.getMessage(), e);
                            }
                        }
                        monitor.setProgress(i + 1);
                        if (monitor.isCanceled()) {
                            return;
                        }
                    }
                   
                    try {
View Full Code Here


                return;
            }
        }

        //  Now generate the key
        final ProgressMonitor monitor = new ProgressMonitor(this,
                "Generating keys", "Generating", 0, 100);
        monitor.setMillisToDecideToPopup(0);
        monitor.setMillisToPopup(0);

        Runnable r = new Runnable() {
                public void run() {
                    try {
                        if (keygen.getAction() == KeygenPanel.CHANGE_PASSPHRASE) {
                            monitor.setNote("Changing passphrase");
                            SshKeyGenerator.changePassphrase(inputFile,
                                oldPassphrase, newPassphrase);
                            monitor.setNote("Complete");
                            JOptionPane.showMessageDialog(Main.this,
                                "Passphrase changed", "Passphrase changed",
                                JOptionPane.INFORMATION_MESSAGE);
                        } else if (keygen.getAction() == KeygenPanel.CONVERT_IETF_SECSH_TO_OPENSSH) {
                            monitor.setNote("Converting key file");
                            writeString(outputFile,
                                SshKeyGenerator.convertPublicKeyFile(
                                    inputFile, new OpenSSHPublicKeyFormat()));
                            monitor.setNote("Complete");
                            JOptionPane.showMessageDialog(Main.this,
                                "Key converted", "Key converted",
                                JOptionPane.INFORMATION_MESSAGE);
                        } else if (keygen.getAction() == KeygenPanel.CONVERT_OPENSSH_TO_IETF_SECSH) {
                            monitor.setNote("Converting key file");
                            writeString(outputFile,
                                SshKeyGenerator.convertPublicKeyFile(
                                    inputFile, new SECSHPublicKeyFormat()));
                            monitor.setNote("Complete");
                            JOptionPane.showMessageDialog(Main.this,
                                "Key converted", "Key converted",
                                JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            monitor.setNote("Creating generator");

                            SshKeyGenerator generator = new SshKeyGenerator();
                            monitor.setNote("Generating");

                            String username = System.getProperty("user.name");
                            generator.generateKeyPair(keygen.getType(),
                                keygen.getBits(), outputFile.getAbsolutePath(),
                                username, newPassphrase);
                            monitor.setNote("Complete");
                            JOptionPane.showMessageDialog(Main.this,
                                "Key generated to " + outputFile.getName(),
                                "Complete", JOptionPane.INFORMATION_MESSAGE);
                        }
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(Main.this,
                            e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    } finally {
                        monitor.close();
                    }
                }
            };

        Thread t = new Thread(r);
View Full Code Here

        return instance;
    }

    public void readPlugins(String base, JFrame parent) throws Exception {
        String baseURL = base;
        ProgressMonitor monitor;

        if (base == null) {
            baseURL = TiledConfiguration.root().get("pluginsDir", "plugins");
        }

        File dir = new File(baseURL);
        if (!dir.exists() || !dir.canRead()) {
            //FIXME: removed for webstart
            //throw new Exception(
            //        "Could not open directory for reading plugins: " +
            //        baseURL);
            return;
        }

        int total = 0;
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            String aPath = files[i].getAbsolutePath();
            if (aPath.endsWith(".jar")) {
                total++;
            }
        }

        // Start the progress monitor
        monitor = new ProgressMonitor(
                parent, "Loading plugins", "", 0, total - 1);
        monitor.setProgress(0);
        monitor.setMillisToPopup(0);
        monitor.setMillisToDecideToPopup(0);

        for (int i = 0; i < files.length; i++) {
            String aPath = files[i].getAbsolutePath();
            String aName =
                aPath.substring(aPath.lastIndexOf(File.separatorChar) + 1);

            // Skip non-jar files.
            if (!aPath.endsWith(".jar")) {
                continue;
            }

            try {
                monitor.setNote("Reading " + aName + "...");
                JarFile jf = new JarFile(files[i]);

                monitor.setProgress(i);

                if (jf.getManifest() == null)
                    continue;

                String readerClassName =
                    jf.getManifest().getMainAttributes().getValue(
                            "Reader-Class");
                String writerClassName =
                    jf.getManifest().getMainAttributes().getValue(
                            "Writer-Class");

                Class readerClass = null, writerClass = null;

                // Verify that the jar has the necessary files to be a
                // plugin
                if (readerClassName == null && writerClassName == null) {
                    continue;
                }

                monitor.setNote("Loading " + aName + "...");
                addURL(new File(aPath).toURI().toURL());

                if (readerClassName != null) {
                    JarEntry reader = jf.getJarEntry(
                            readerClassName.replace('.', '/') + ".class");
View Full Code Here

          if(headless){
            System.out.println("Starting job for " + id);
          }else{
         
            if(!currentProgress.containsKey(id)){
              ProgressMonitor pm = new ProgressMonitor(null, "Clustering task:", "Starting clustering of "+ msg, 0,100);
              pm.setMillisToPopup(10000);
              currentProgress.put(id, pm)
              pm.setProgress(0);

            }
          }

        }else if(evt.type == ProgressEvent.TYPE_PROGRESS){
          if(headless){
            Logger.getLogger(StatusMonitor.class.getName()).log(Level.INFO,"Progress update on " + id + ": " + prog + "%");
          }else{
            if(!currentProgress.containsKey(id)){

              ProgressMonitor pm = new ProgressMonitor(null, "Clustering task:", id, 0,100);
              pm.setMillisToPopup(10000);
              currentProgress.put(id, pm)
            }

            ProgressMonitor p = currentProgress.get(id);
            p.setProgress(prog);
          }

        }else if (evt.type == ProgressEvent.TYPE_FINISH){
          if(headless){
            System.out.println("Job " + id + " finished.");
View Full Code Here

     * extract data from pdf (if allowed).
     */
    if ((decode_pdf.isEncrypted()&&(!decode_pdf.isPasswordSupplied()))&&(!decode_pdf.isExtractionAllowed()))
      return;
   
    ProgressMonitor status = new ProgressMonitor(currentGUI.getFrame(),
        Messages.getMessage("PdfViewerMessage.ExtractImages"),"",start,end);
   
    try{
      int count=0;
      boolean yesToAll = false;
      for( int page = start;page < end + 1;page++ ){ //read pages
        if(status.isCanceled()){
          currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.UserStoppedExport") +
              count+ ' ' +Messages.getMessage("PdfViewerError.ReportNumberOfImagesExported"));
          return;
        }
        //decode the page
        decode_pdf.decodePage( page );
       
        //get the PdfImages object which now holds the images.
        //binary data is stored in a temp directory and we hold the
        //image name and other info in this object
        PdfImageData pdf_images = decode_pdf.getPdfImageData();
       
        //image count (note image 1 is item 0, so any loop runs 0 to count-1)
        int image_count = pdf_images.getImageCount();
       
        if(image_count>0){
          target=output_dir+page+separator;
          File targetExists=new File(target);
          if(!targetExists.exists())
            targetExists.mkdir();
        }
       
        //work through and save each image
        for( int i = 0;i < image_count;i++ ){
         
          String image_name =pdf_images.getImageName( i );
          BufferedImage image_to_save;
         
          float x1=pdf_images.getImageXCoord(i);
          float y1=pdf_images.getImageYCoord(i);
          float w=pdf_images.getImageWidth(i);
          float h=pdf_images.getImageHeight(i);
         
          try{
           
            image_to_save =decode_pdf.getObjectStore().loadStoredImage"CLIP_"+image_name );
           
            //save image

            if(image_to_save!=null){
             
              //remove transparency on jpeg
              if(imageType.toLowerCase().startsWith("jp"))
                image_to_save=ColorSpaceConvertor.convertToRGB(image_to_save);

              File fileToSave = new File(target+image_name+ '.' +imageType);
              if(fileToSave.exists() && !yesToAll){
                int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(),true);
                       
                        if(n==0){
                          // clicked yes so just carry on for this once
                        }else if(n==1){
                          // clicked yes to all, so set flag
                          yesToAll = true;
                        }else if(n==2){
                          // clicked no, so loop round again
                          status.setProgress(page);
                          continue;
                        }else{
                         
                          currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.UserStoppedExport") +
                              count+ ' ' +Messages.getMessage("PdfViewerError.ReportNumberOfImagesExported"));
                         
                          status.close();
                          return;
                        }
              }
             
              saveImage(image_to_save,target+image_name+ '.' +imageType,imageType);
              count++;
            }
           
            //save an xml file with details
            /**
             * output the data
             */
            //LogWriter.writeLog( "Writing out "+(outputName + ".xml"));
            OutputStreamWriter output_stream =
              new OutputStreamWriter(
                  new FileOutputStream(target+image_name + ".xml"),
              "UTF-8");
           
            output_stream.write(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            output_stream.write(
            "<!-- Pixel Location of image x1,y1,x2,y2\n");
            output_stream.write("(x1,y1 is top left corner)\n");
            output_stream.write(
            "(origin is bottom left corner)  -->\n");
            output_stream.write("\n\n<META>\n");
            output_stream.write(
                "<PAGELOCATION x1=\""+ x1+ "\" "
                + "y1=\""+ (y1+h)+ "\" "
                + "x2=\""+ (x1+w)+ "\" "
                + "y2=\""+ (y1)+ "\" />\n");
            output_stream.write("<FILE>"+this.fileName+"</FILE>\n");
            output_stream.write("</META>\n");
            output_stream.close();
          }catch( Exception ee ){
            ee.printStackTrace();
            LogWriter.writeLog( "Exception " + ee + " in extracting images" );
          }
        }
       
       
        //flush images in case we do more than 1 page so only contains
        //images from current page
        decode_pdf.flushObjectValues(true);
       
        status.setProgress(page+1);
       
      }
      status.close();
     
      currentGUI.showMessageDialog(Messages.getMessage("PdfViewerMessage.ImagesSavedTo")+ ' ' +output_dir);
     
     
    }catch( Exception e ){
View Full Code Here

     * extract data from pdf (if allowed).
     */
    if ((decode_pdf.isEncrypted()&&(!decode_pdf.isPasswordSupplied()))&&(!decode_pdf.isExtractionAllowed()))
      return;
   
    ProgressMonitor status = new ProgressMonitor(currentGUI.getFrame(),
        Messages.getMessage("PdfViewerMessage.ExtractImages"),"",start,end);
   
    try{
      int count=0;
      boolean yesToAll = false;
      for( int page = start;page < end + 1;page++ ){ //read pages
        if(status.isCanceled()){
          currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.UserStoppedExport") +
                            count + Messages.getMessage("PdfViewerError.ReportNumberOfImagesExported"));
          return;
        }
        //decode the page
        decode_pdf.decodePage( page );
       
        //get the PdfImages object which now holds the images.
        //binary data is stored in a temp directory and we hold the
        //image name and other info in this object
        PdfImageData pdf_images = decode_pdf.getPdfImageData();
       
        //image count (note image 1 is item 0, so any loop runs 0 to count-1)
        int image_count = pdf_images.getImageCount();
       
        String target=output_dir+separator;
        if(downsampled)
          target=target+"downsampled"+separator+page+separator;
        else
          target=target+"normal"+separator+page+separator;
       
        //tell user
        if( image_count > 0 ){
         
         
          //create a directory for page
          File page_path = new File( target );
          if( page_path.exists() == false )
            page_path.mkdirs();
         
         
          //do it again as some OS struggle with creating nested dirs
          page_path = new File( target );
          if( page_path.exists() == false )
            page_path.mkdirs();
         
        }
       
        //work through and save each image
        for( int i = 0;i < image_count;i++ )
        {
          String image_name = pdf_images.getImageName( i );
          BufferedImage image_to_save;
         
          try
          {
            if(downsampled){
              //load processed version of image (converted to rgb)
              image_to_save = decode_pdf.getObjectStore().loadStoredImage( image_name );
              if(prefix.toLowerCase().startsWith("jp")){
                image_to_save=ColorSpaceConvertor.convertToRGB(image_to_save);
               
              }
            }else{
              //get raw version of image (R prefix for raw image)
              image_to_save = decode_pdf.getObjectStore().loadStoredImage( image_name );
              if(prefix.toLowerCase().startsWith("jp")){
                image_to_save=ColorSpaceConvertor.convertToRGB(image_to_save);
              }     
            }
           
            File fileToSave = new File(target+ image_name+ '.' +prefix);
            if(fileToSave.exists() && !yesToAll){
              int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(),true);
                     
                      if(n==0){
                        // clicked yes so just carry on for this once
                      }else if(n==1){
                        // clicked yes to all, so set flag
                        yesToAll = true;
                      }else if(n==2){
                        // clicked no, so loop round again
                        status.setProgress(page);
                        continue;
                      }else{
                       
                        currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.UserStoppedExport") +
                            count+ ' ' +Messages.getMessage("PdfViewerError.ReportNumberOfImagesExported"));
                       
                        status.close();
                        return;
                      }
            }
           
            //save image
            saveImage(image_to_save,target+ image_name+ '.' +prefix,prefix);
            count++;
          }
         
         
          catch( Exception ee )
          {
            System.err.println( "Exception " + ee + " in extracting images" );
          }
        }
       
        //flush images in case we do more than 1 page so only contains
        //images from current page
        decode_pdf.flushObjectValues(true);
       
       
        status.setProgress(page+1);
      }

      currentGUI.showMessageDialog(Messages.getMessage("PdfViewerMessage.ImagesSavedTo")+ ' ' +output_dir);
     
      status.close();
    }catch( Exception e ){
      decode_pdf.closePdfFile();
      LogWriter.writeLog( "Exception " + e.getMessage() );
    }
   
View Full Code Here

    if ((decode_pdf.isEncrypted()&&(!decode_pdf.isPasswordSupplied()))&& (!decode_pdf.isExtractionAllowed())) {
      System.out.println("Encrypted settings");
      System.out.println("Please look at SimpleViewer for code sample to handle such files");
    } else {
     
      ProgressMonitor status = new ProgressMonitor(currentGUI.getFrame(),
          Messages.getMessage("PdfViewerMessage.ExtractText"),"",startPage,endPage);
      /**
       * extract data from pdf
       */
      try {
        int count=0;
        boolean yesToAll = false;
        for (int page = startPage; page < endPage + 1; page++) { //read pages
          if(status.isCanceled()){
            currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.UserStoppedExport") +count
                + ' ' +Messages.getMessage("PdfViewerError.ReportNumberOfPagesExported"));
            return;
          }
          //decode the page
          decode_pdf.decodePage(page);
         
          /** create a grouping object to apply grouping to data*/
          PdfGroupingAlgorithms currentGrouping =decode_pdf.getGroupingObject();
         
          /**use whole page size for  demo - get data from PageData object*/
          PdfPageData currentPageData = decode_pdf.getPdfPageData();
         
          int x1,y1,x2,y2;
         
          x1 = currentPageData.getMediaBoxX(page);
          x2 = currentPageData.getMediaBoxWidth(page)+x1;
         
          y2 = currentPageData.getMediaBoxY(page);
          y1 = currentPageData.getMediaBoxHeight(page)+y2;
         
          //default for xml
          String ending="_text.csv";
         
          if(useXMLExtraction)
            ending="_xml.txt";
         
          /**Co-ordinates are x1,y1 (top left hand corner), x2,y2(bottom right) */
         
          /**The call to extract the table*/
          Map tableContent =null;
          String tableText=null;
         
          try{
            //the source code for this grouping is in the customer area
            //in class pdfGroupingAlgorithms
            //all these settings are defined in the Java
           
            tableContent =currentGrouping.extractTextAsTable(
                x1,
                y1,
                x2,
                y2,
                page,
                !useXMLExtraction,
                false,
                false,false,0);
           
            //get the text from the Map object
            tableText=(String)tableContent.get("content");
           
          } catch (PdfException e) {
            decode_pdf.closePdfFile();
            System.err.println("Exception " + e.getMessage()+" with table extraction");
          }catch (Error e) {
            e.printStackTrace();
          }
         
          if (tableText == null) {
            System.out.println("No text found");
          } else {
           
           
            String target=output_dir+separator+"table"+separator;
           
            //create a directory if it doesn't exist
            File output_path = new File(target);
            if (output_path.exists() == false)
              output_path.mkdirs();
           
            File fileToSave = new File(target + fileName+ '_' +page+ ending);
            if(fileToSave.exists() && !yesToAll){
              if((endPage - startPage) > 1){
                        int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(),true);
                       
                        if(n==0){
                          // clicked yes so just carry on for this once
                        }else if(n==1){
                          // clicked yes to all, so set flag
                          yesToAll = true;
                        }else if(n==2){
                          // clicked no, so loop round again
                          status.setProgress(page);
                          continue;
                        }else{
                         
                          currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.UserStoppedExport") +
                              count+ ' ' +Messages.getMessage("PdfViewerError.ReportNumberOfPagesExported"));
                         
                          status.close();
                          return;
                        }
                      }else{
                        int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(),false);
                       
                        if(n==0){
                          // clicked yes so just carry on
                        }else{
                          // clicked no, so exit
                          return;
                        }
                      }
            }
           
            /**
             * output the data - you may wish to alter the encoding to suit
             */
            OutputStreamWriter output_stream =
              new OutputStreamWriter(
                  new FileOutputStream(target + fileName+ '_' +page+ ending),
              "UTF-8");
           
//            xml header
            if(useXMLExtraction)
              output_stream.write("<xml><BODY>\n\n");
           
            output_stream.write(tableText); //write actual data
           
//            xml footer
            if(useXMLExtraction)
              output_stream.write("\n</body></xml>");
           
            output_stream.close();
           
          }
          count++;
          status.setProgress(page+1);
          //remove data once written out
          decode_pdf.flushObjectValues(false);
        }
        status.close();
        currentGUI.showMessageDialog(Messages.getMessage("PdfViewerMessage.TextSavedTo")+ ' ' +output_dir);
      } catch (Exception e) {
        decode_pdf.closePdfFile();
        System.err.println("Exception " + e.getMessage());
        e.printStackTrace();
View Full Code Here

    } else{
      //page range
      int start = startPage, end = endPage;
      int wordsExtracted=0;
     
      ProgressMonitor status = new ProgressMonitor(currentGUI.getFrame(),
          Messages.getMessage("PdfViewerMessage.ExtractText"),"",startPage,endPage);
     
      /**
       * extract data from pdf
       */
      try {
        int count=0;
        boolean yesToAll = false;
        for (int page = start; page < end + 1; page++) { //read pages
          if(status.isCanceled()){
            currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.UserStoppedExport") +
                count+ ' ' +Messages.getMessage("PdfViewerError.ReportNumberOfPagesExported"));
            return;
          }
          //decode the page
          decode_pdf.decodePage(page);
         
          /** create a grouping object to apply grouping to data*/
          PdfGroupingAlgorithms currentGrouping =decode_pdf.getGroupingObject();
         
          /**use whole page size for  demo - get data from PageData object*/
          PdfPageData currentPageData = decode_pdf.getPdfPageData();
         
          int x1 = currentPageData.getMediaBoxX(page);
          int x2 = currentPageData.getMediaBoxWidth(page)+x1;
         
          int y2 = currentPageData.getMediaBoxX(page);
          int y1 = currentPageData.getMediaBoxHeight(page)-y2;
         
          /**Co-ordinates are x1,y1 (top left hand corner), x2,y2(bottom right) */
         
          /**The call to extract the list*/
          List words =null;
         
          try{
            words =currentGrouping.extractTextAsWordlist(
                x1,
                y1,
                x2,
                y2,
                page,
                true,"&:=()!;.,\\/\"\"\'\'");
          } catch (PdfException e) {
            decode_pdf.closePdfFile();
            System.err.println("Exception= "+ e+" in "+selectedFile);
            e.printStackTrace();
          }catch(Error e){
            e.printStackTrace();
          }
         
          if (words == null) {
           
            System.out.println("No text found");
           
          } else {
           
            String target=output_dir+separator+"wordlist"+separator;
           
            //create a directory if it doesn't exist
            File output_path = new File(target);
            if (output_path.exists() == false)
              output_path.mkdirs();
           
            /**
             * choose correct prefix
             */
            String prefix="_text.txt";
            String encoding=System.getProperty("file.encoding");
           
            if(useXMLExtraction){
              prefix="_xml.txt";
              encoding="UTF-8";
            }
           
            /**each word is stored as 5 consecutive values (word,x1,y1,x2,y2)*/
            int wordCount=words.size()/5;
           
            //update our count
            wordsExtracted=wordsExtracted+wordCount;
           
           
            File fileToSave = new File(target + fileName+ '_' +page + prefix);
            if(fileToSave.exists() && !yesToAll){
              if((endPage - startPage) > 1){
                        int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(),true);
                       
                        if(n==0){
                          // clicked yes so just carry on for this once
                        }else if(n==1){
                          // clicked yes to all, so set flag
                          yesToAll = true;
                        }else if(n==2){
                          // clicked no, so loop round again
                          status.setProgress(page);
                          continue;
                        }else{
                         
                          currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.UserStoppedExport") +
                              count+ ' ' +Messages.getMessage("PdfViewerError.ReportNumberOfPagesExported"));
                         
                          status.close();
                          return;
                        }
                      }else{
                        int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(),false);
                       
                        if(n==0){
                          // clicked yes so just carry on
                        }else{
                          // clicked no, so exit
                          return;
                        }
                      }
            }
           
           
            /**
             * output the data
             */
            OutputStreamWriter output_stream =
              new OutputStreamWriter(
                  new FileOutputStream(target + fileName+ '_' +page + prefix),
                  encoding);
           
            Iterator wordIterator=words.iterator();
            while(wordIterator.hasNext()){
             
              String currentWord=(String) wordIterator.next();
             
              /**remove the XML formatting if present - not needed for pure text*/
              if(!useXMLExtraction)
                currentWord=Strip.convertToText(currentWord,true);
             
              int wx1=(int)Float.parseFloat((String) wordIterator.next());
              int wy1=(int)Float.parseFloat((String) wordIterator.next());
              int wx2=(int)Float.parseFloat((String) wordIterator.next());
              int wy2=(int)Float.parseFloat((String) wordIterator.next());
             
              /**this could be inserting into a database instead*/
              output_stream.write(currentWord+ ',' +wx1+ ',' +wy1+ ',' +wx2+ ',' +wy2+ '\n');
             
            }
            output_stream.close();
           
          }
         
          count++;
          status.setProgress(page+1);
         
          //remove data once written out
          decode_pdf.flushObjectValues(false);
         
        }
        status.close();
        currentGUI.showMessageDialog(Messages.getMessage("PdfViewerMessage.TextSavedTo")+ ' ' +output_dir);
      } catch (Exception e) {
        decode_pdf.closePdfFile();
        System.err.println("Exception "+ e+" in "+selectedFile);
        e.printStackTrace();
View Full Code Here

      System.out.println("Encrypted settings");
      System.out.println("Please look at SimpleViewer for code sample to handle such files");
     
    } else {
     
      ProgressMonitor status = new ProgressMonitor(currentGUI.getFrame(),
          Messages.getMessage("PdfViewerMessage.ExtractText"),"",startPage,endPage);
     
      /**
       * extract data from pdf
       */
      try {
        int count=0;
        boolean yesToAll = false;
        for (int page = startPage; page < endPage + 1; page++) { //read pages
          if(status.isCanceled()){
            currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.UserStoppedExport")
                +count+ ' ' +Messages.getMessage("PdfViewerError.ReportNumberOfPagesExported"));
            return;
          }
          //decode the page
          decode_pdf.decodePage(page);
         
          /** create a grouping object to apply grouping to data*/
          PdfGroupingAlgorithms currentGrouping =decode_pdf.getGroupingObject();
         
          /**use whole page size for  demo - get data from PageData object*/
          PdfPageData currentPageData = decode_pdf.getPdfPageData();
         
          int x1 = currentPageData.getMediaBoxX(page);
          int x2 = currentPageData.getMediaBoxWidth(page)+x1;
         
          int y2 = currentPageData.getMediaBoxY(page);
          int y1 = currentPageData.getMediaBoxHeight(page)+y2;
         
          /**Co-ordinates are x1,y1 (top left hand corner), x2,y2(bottom right) */
         
          /**The call to extract the text*/
          String text =null;
         
          try{
            text =currentGrouping.extractTextInRectangle(
                x1,
                y1,
                x2,
                y2,
                page,
                false,
                true);
          } catch (PdfException e) {
            decode_pdf.closePdfFile();
            System.err.println("Exception " + e.getMessage()+" in file "+decode_pdf.getObjectStore().fullFileName);
            e.printStackTrace();
          }
         
          //allow for no text
          if(text==null)
            continue;
         
          String target=output_dir+separator+"rectangle"+separator;         
         
          //ensure a directory for data
          File page_path = new File(target);
          if (page_path.exists() == false)
            page_path.mkdirs();
         
          /**
           * choose correct prefix
           */
          String prefix="_text.txt";
          String encoding=System.getProperty("file.encoding");
         
          if(useXMLExtraction){
            prefix="_xml.txt";
            encoding="UTF-8";
          }

          File fileToSave = new File(target + fileName+ '_' +page + prefix);
          if(fileToSave.exists() && !yesToAll){
            if((endPage - startPage) > 1){
                      int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(),true);
                     
                      if(n==0){
                        // clicked yes so just carry on for this once
                      }else if(n==1){
                        // clicked yes to all, so set flag
                        yesToAll = true;
                      }else if(n==2){
                        // clicked no, so loop round again
                        status.setProgress(page);
                        continue;
                      }else{
                       
                        currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.UserStoppedExport") +
                            count+ ' ' +Messages.getMessage("PdfViewerError.ReportNumberOfPagesExported"));
                       
                        status.close();
                        return;
                      }
                    }else{
                      int n = currentGUI.showOverwriteDialog(fileToSave.getAbsolutePath(),false);
                     
                      if(n==0){
                        // clicked yes so just carry on
                      }else{
                        // clicked no, so exit
                        return;
                      }
                    }
          }

          /**
           * output the data
           */
          OutputStreamWriter output_stream =
            new OutputStreamWriter(
                new FileOutputStream(target + fileName+ '_' +page + prefix),
                encoding);
         
          if((useXMLExtraction)){
            output_stream.write(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n");
            output_stream.write(
            "<!-- Pixel Location of text x1,y1,x2,y2\n");
            output_stream.write("(x1,y1 is top left corner)\n");
            output_stream.write("(x1,y1 is bottom right corner)\n");
            output_stream.write(
            "(origin is bottom left corner)  -->\n");
            output_stream.write("\n\n<ARTICLE>\n");
            output_stream.write(
                "<LOCATION x1=\""
                + x1
                + "\" "
                + "y1=\""
                + y1
                + "\" "
                + "x2=\""
                + x2
                + "\" "
                + "y2=\""
                + y2
                + "\" />\n");
            output_stream.write("\n\n<TEXT>\n");
            //NOTE DATA IS TECHNICALLY UNICODE
            output_stream.write(text); //write actual data
            output_stream.write("\n\n</TEXT>\n");
            output_stream.write("\n\n</ARTICLE>\n");
          }else
            output_stream.write(text); //write actual data
         
          count++;
          output_stream.close();
         
          status.setProgress(page+1);
         
          //remove data once written out
          decode_pdf.flushObjectValues(true);
        }
        status.close();
        currentGUI.showMessageDialog(Messages.getMessage("PdfViewerMessage.TextSavedTo")+ ' ' +output_dir);
       
      } catch (Exception e) {
        decode_pdf.closePdfFile();
        System.err.println("Exception " + e.getMessage());
View Full Code Here

        // Save time for later analysis
        final long timeBeforeCalculating = System.currentTimeMillis();

        // Create progress monitor
        final ProgressMonitor pm = new ProgressMonitor(
            Cooja.getTopParentContainer(),
            "Calculating channel attenuation",
            null,
            0,
            resolution.width - 1
        );

        // Thread that will perform the work
        final Runnable runnable = new Runnable() {
          public void run() {
            try {

              // Available signal strength intervals
              double lowestImageValue = Double.MAX_VALUE;
              double highestImageValue = -Double.MAX_VALUE;

              // Create image values (calculate each pixel)
              double[][] imageValues = new double[resolution.width][resolution.height];
              for (int x=0; x < resolution.width; x++) {
                for (int y=0; y < resolution.height; y++) {
                  final double xx = x;
                  final double yy = y;
                  TxPair txPair = new TxPair() {
                    public double getDistance() {
                      double w = getFromX() - getToX();
                      double h = getFromY() - getToY();
                      return Math.sqrt(w*w+h*h);
                    }
                    public double getFromX() { return radioX; }
                    public double getFromY() { return radioY; }
                    public double getToX() { return startX + width * xx/resolution.width; }
                    public double getToY() { return startY + height * yy/resolution.height; }
                    public double getTxPower() { return selectedRadio.getCurrentOutputPower(); }
                    public double getTxGain() {
                      if (!(selectedRadio instanceof DirectionalAntennaRadio)) {
                        return 0;
                      }
                      DirectionalAntennaRadio r = (DirectionalAntennaRadio)selectedRadio;
                      double txGain = r.getRelativeGain(r.getDirection() + getAngle(), getDistance());
                      //logger.debug("tx gain: " + txGain + " (angle " + String.format("%1.1f", Math.toDegrees(r.getDirection() + getAngle())) + ")");
                      return txGain;
                    }
                    public double getRxGain() {
                      return 0;
                    }
                  };

                  if (dataTypeToVisualize == ChannelModel.TransmissionData.SIGNAL_STRENGTH) {
                    // Attenuate
                    double[] signalStrength = currentChannelModel.getReceivedSignalStrength(txPair);

                    // Collecting signal strengths
                    if (signalStrength[0] < lowestImageValue) {
                      lowestImageValue = signalStrength[0];
                    }
                    if (signalStrength[0] > highestImageValue) {
                      highestImageValue = signalStrength[0];
                    }

                    imageValues[x][y] = signalStrength[0];

                  } else if (dataTypeToVisualize == ChannelModel.TransmissionData.SIGNAL_STRENGTH_VAR) {
                    // Attenuate
                    double[] signalStrength = currentChannelModel.getReceivedSignalStrength(txPair);

                    // Collecting variances
                    if (signalStrength[1] < lowestImageValue) {
                      lowestImageValue = signalStrength[1];
                    }
                    if (signalStrength[1] > highestImageValue) {
                      highestImageValue = signalStrength[1];
                    }

                    imageValues[x][y] = signalStrength[1];

                  } else if (dataTypeToVisualize == ChannelModel.TransmissionData.SNR) {
                    // Get signal to noise ratio
                    double[] snr = currentChannelModel.getSINR(
                        txPair,
                        -Double.MAX_VALUE
                    );

                    // Collecting signal to noise ratio
                    if (snr[0] < lowestImageValue) {
                      lowestImageValue = snr[0];
                    }
                    if (snr[0] > highestImageValue) {
                      highestImageValue = snr[0];
                    }

                    imageValues[x][y] = snr[0];

                  } else if (dataTypeToVisualize == ChannelModel.TransmissionData.SNR_VAR) {
                    // Get signal to noise ratio
                    double[] snr = currentChannelModel.getSINR(
                        txPair,
                        -Double.MAX_VALUE
                    );

                    // Collecting variances
                    if (snr[1] < lowestImageValue) {
                      lowestImageValue = snr[1];
                    }
                    if (snr[1] > highestImageValue) {
                      highestImageValue = snr[1];
                    }

                    imageValues[x][y] = snr[1];
                  } else if (dataTypeToVisualize == ChannelModel.TransmissionData.PROB_OF_RECEPTION) {
                    // Get probability of receiving a packet TODO What size? Does it matter?
                    double probability = currentChannelModel.getProbability(
                        txPair, -Double.MAX_VALUE
                    )[0];

                    // Collecting variances
                    if (probability < lowestImageValue) {
                      lowestImageValue = probability;
                    }
                    if (probability > highestImageValue) {
                      highestImageValue = probability;
                    }

                    imageValues[x][y] = probability;
                  } else if (dataTypeToVisualize == ChannelModel.TransmissionData.DELAY_SPREAD_RMS) {
                    // Get RMS delay spread of receiving a packet
                    double rmsDelaySpread = currentChannelModel.getRMSDelaySpread(
                        txPair
                    );

                    // Collecting variances
                    if (rmsDelaySpread < lowestImageValue) {
                      lowestImageValue = rmsDelaySpread;
                    }
                    if (rmsDelaySpread > highestImageValue) {
                      highestImageValue = rmsDelaySpread;
                    }

                    imageValues[x][y] = rmsDelaySpread;
                  }

                  // Check if the dialog has been canceled
                  if (pm.isCanceled()) {
                    return;
                  }

                  // Update progress
                  pm.setProgress(x);

                }
              }

              // Adjust coloring signal strength limit
              if (coloringIsFixed) {
                if (dataTypeToVisualize == ChannelModel.TransmissionData.SIGNAL_STRENGTH) {
                  lowestImageValue = -100;
                  highestImageValue = 0;
                } else if (dataTypeToVisualize == ChannelModel.TransmissionData.SIGNAL_STRENGTH_VAR) {
                  lowestImageValue = 0;
                  highestImageValue = 20;
                } else if (dataTypeToVisualize == ChannelModel.TransmissionData.SNR) {
                  lowestImageValue = -10;
                  highestImageValue = 30;
                } else if (dataTypeToVisualize == ChannelModel.TransmissionData.SNR_VAR) {
                  lowestImageValue = 0;
                  highestImageValue = 20;
                } else if (dataTypeToVisualize == ChannelModel.TransmissionData.PROB_OF_RECEPTION) {
                  lowestImageValue = 0;
                  highestImageValue = 1;
                } else if (dataTypeToVisualize == ChannelModel.TransmissionData.DELAY_SPREAD_RMS) {
                  lowestImageValue = 0;
                  highestImageValue = 5;
                }
              }

              // Save coloring high-low interval
              coloringHighest = highestImageValue;
              coloringLowest = lowestImageValue;

              // Create image
              for (int x=0; x < resolution.width; x++) {
                for (int y=0; y < resolution.height; y++) {

                  tempChannelImage.setRGB(
                      x,
                      y,
                      getColorOfSignalStrength(imageValues[x][y], lowestImageValue, highestImageValue)
                  );
                }
              }
              logger.info("Attenuating area done, time=" + (System.currentTimeMillis() - timeBeforeCalculating));

              // Repaint to show the new channel propagation
              channelStartX = startX;
              channelStartY = startY;
              channelWidth = width;
              channelHeight = height;
              channelImage = tempChannelImage;

              AreaViewer.this.repaint();
              coloringIntervalPanel.repaint();

            } catch (Exception ex) {
              if (pm.isCanceled()) {
                return;
              }
              logger.fatal("Attenuation aborted: " + ex);
              ex.printStackTrace();
              pm.close();
            }
            pm.close();
          }
        };

        // Start thread
        attenuatorThread = new Thread(runnable);
View Full Code Here

TOP

Related Classes of javax.swing.ProgressMonitor$ProgressOptionPane

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.