Esempio n. 1
0
  /** Metodo que le os clientes de um ficheiro */
  public void lerLocalidades(String fileLocalidades, String fileLigacoes, int nrlocalidades)
      throws FileNotFoundException, IOException {
    BufferedReader readLoc = new BufferedReader(new FileReader(fileLocalidades));
    BufferedReader readLig = new BufferedReader(new FileReader(fileLigacoes));
    int nrligacoes;

    while (readLoc.ready() && nrlocalidades > 0) {

      String linhaLoc = readLoc.readLine();
      StringTokenizer stLoc = new StringTokenizer(linhaLoc, "|");
      nrligacoes = stLoc.countTokens() - 2;
      Localidade localidade = new Localidade(stLoc.nextToken(), stLoc.nextToken());

      while (nrligacoes > 0 && readLig.ready()) {
        String linhaLig = readLig.readLine();
        StringTokenizer stLig = new StringTokenizer(linhaLig, "|");
        stLig.nextToken();
        Ligacao lig =
            new Ligacao(
                stLig.nextToken(),
                Double.valueOf(stLig.nextToken()),
                Double.valueOf(stLig.nextToken()));
        localidade.addLigacao(lig);
        nrligacoes--;
      }
      this.addLocalidade(localidade);
      nrlocalidades--;
    }
    readLoc.close();
    readLig.close();
  }
 private static Map<Integer, Alignment> readAlignments(String fileName) {
   Map<Integer,Alignment> alignments = new HashMap<Integer, Alignment>();
   try {
     BufferedReader in = new BufferedReader(new FileReader(fileName));
     while (in.ready()) {
       String line = in.readLine();
       String[] words = line.split("\\s+");
       if (words.length != 4)
         throw new RuntimeException("Bad alignment file "+fileName+", bad line was "+line);
       Integer sentenceID = Integer.parseInt(words[0]);
       Integer englishPosition = Integer.parseInt(words[1])-1;
       Integer frenchPosition = Integer.parseInt(words[2])-1;
       String type = words[3];
       Alignment alignment = alignments.get(sentenceID);
       if (alignment == null) {
         alignment = new Alignment();
         alignments.put(sentenceID, alignment);
       }
       alignment.addAlignment(englishPosition, frenchPosition, type.equals("S"));
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
   return alignments;
 }
Esempio n. 3
0
 boolean eof() {
   try {
     return br.ready();
   } catch (IOException e) {
   }
   return false;
 }
Esempio n. 4
0
 public void getWords(String fileName) throws IOException {
   this.word = new ArrayList<String>();
   BufferedReader buf = new BufferedReader(new FileReader(fileName));
   while (buf.ready()) {
     this.word.add(buf.readLine());
   }
 }
Esempio n. 5
0
 private Vector readlinesfromfile(String fname) { // trims lines and removes comments
   Vector v = new Vector();
   try {
     BufferedReader br = new BufferedReader(new FileReader(new File(fname)));
     while (br.ready()) {
       String tmp = br.readLine();
       // Strip comments
       while (tmp.indexOf("/*") >= 0) {
         int i = tmp.indexOf("/*");
         v.add(tmp.substring(0, i));
         String rest = tmp.substring(i + 2);
         while (tmp.indexOf("*/") == -1) {
           tmp = br.readLine();
         }
         tmp = tmp.substring(tmp.indexOf("*/") + 2);
       }
       if (tmp.indexOf("//") >= 0) tmp = tmp.substring(0, tmp.indexOf("//"));
       // Strip spaces
       tmp = tmp.trim();
       v.add(tmp);
       //        System.out.println("Read line "+tmp);
     }
     br.close();
   } catch (Exception e) {
     System.out.println("Exception " + e + " occured");
   }
   return v;
 }
Esempio n. 6
0
  /** {@inheritDoc} */
  public String RPC(String Name, String Method, String[] Args) {
    // write to serial port and receive result
    String Response;
    String Arguments = "";
    if (Args != null) {
      int s = Args.length;
      for (int i = 0; i < s; i++) {
        Arguments = Arguments + " " + Args[i];
      }
    }
    try {
      to_mbed.println("/" + Name + "/" + Method + Arguments);
      mbedSerialPort.notifyOnDataAvailable(false);
    } catch (NullPointerException e) {

    }
    boolean valid = true;
    try {
      while (reader.ready() == false) {}
      ;
      do {
        Response = reader.readLine();

        if (Response.length() >= 1) {
          valid = Response.charAt(0) != '!';
        }
      } while (valid == false);
    } catch (IOException e) {
      System.err.println("IOException, error reading from port");
      Response = "error";
    }

    mbedSerialPort.notifyOnDataAvailable(true);
    return (Response);
  }
Esempio n. 7
0
 public boolean hasNext() {
   try {
     boolean a = br.ready();
     return a;
   } catch (IOException e) {
     return false;
   }
 }
Esempio n. 8
0
 static void load(String name) throws Exception {
   List music = new ArrayList();
   BufferedReader in = new BufferedReader(new FileReader(name));
   in.readLine(); // skip column headings
   while (in.ready()) {
     music.add(Music.parse(in.readLine()));
   }
   in.close();
   library = (Music[]) music.toArray(library);
 }
  private static void populateMediaTypeMappings() throws RegistryException {
    BufferedReader reader;
    humanReadableMediaTypeMap = new HashMap<String, String>();
    try {
      File mimeFile = getHumanMediaTypeMappingsFile();
      reader = new BufferedReader(new InputStreamReader(new FileInputStream(mimeFile)));
    } catch (Exception e) {
      String msg = FAILED_TO_READ_THE_THE_HUMAN_READABLE_MEDIA_TYPE_MIME_TYPE_MAPPINGS_FILE_MSG;
      log.warn(msg, e);
      return;
    }

    try {
      while (reader.ready()) {
        String mediaTypeData = reader.readLine().trim();
        if (mediaTypeData.startsWith("#")) {
          // ignore the comments
          continue;
        }

        if (mediaTypeData.length() == 0) {
          // ignore the blank lines
          continue;
        }

        // mime.mappings file delimits media types:extensions by tabs. if there is no
        // extension associated with a media type, there are no tabs in the line. so we
        // don't need such lines.
        if (mediaTypeData.indexOf('\t') > 0) {

          String[] parts = mediaTypeData.split("\t+");
          if (parts.length == 2 && parts[0].length() > 0 && parts[1].length() > 0) {

            // there can multiple extensions associated with a single media type. in
            // that case, extensions are delimited by a space.
            humanReadableMediaTypeMap.put(parts[1], parts[0]);
          }
        }
      }
    } catch (IOException e) {
      String msg = FAILED_TO_READ_THE_THE_HUMAN_READABLE_MEDIA_TYPE_MIME_TYPE_MAPPINGS_FILE_MSG;
      log.error(msg, e);
      throw new RegistryException(msg);
    } finally {
      try {
        reader.close();
        if (humanReadableMediaTypeMap == null) {
          humanReadableMediaTypeMap = Collections.emptyMap();
        }
      } catch (IOException ignore) {
      }
    }
  }
Esempio n. 10
0
 public void load(InputStream inputStream) throws Exception {
   BufferedReader bur = new BufferedReader(new InputStreamReader(inputStream));
   while (bur.ready()) {
     User user = new User();
     user.setFirstName(bur.readLine());
     user.setLastName(bur.readLine());
     user.setBirthDate(new Date(Long.parseLong(bur.readLine())));
     user.setMale(Boolean.parseBoolean(bur.readLine()));
     user.setCountry(User.Country.valueOf(bur.readLine()));
     users.add(user);
   }
   bur.close();
 }
Esempio n. 11
0
  /**
   * Listens to the output of the debugger constantly, and notifies observers when output is
   * recieved.
   */
  public void run() {
    boolean done = false;

    while (!done) {
      try {
        /*make sure we are alive */
        if (!alive) {
          close();
          break;
        }

        int c; // = debugStreamReader.read();
        char theChar; // = (char) c;
        // buffer.append(theChar);
        //

        while (debugStreamReader.ready()) {
          c = debugStreamReader.read();
          theChar = (char) c;
          if ((c == -1) || (c == 0)) {
            done = true;
          } else {
            buffer.append(theChar);
          }
        }

        if (buffer.length() > 0) {
          String output = buffer.toString();
          TextOutputEvent event = new TextOutputEvent(output, handle);
          synchronized (observers) {
            for (TextOutputListener listener : observers) {
              listener.receiveOutput(event);
            }
            buffer.delete(0, buffer.length());
          }
        }
      } catch (IOException e) {
        /*We will eventually want to eat this */
        e.printStackTrace();
        return;
      }
    }

    try {
      debugStreamReader.close();
      return;
    } catch (IOException e) {
      /*Eat it */
    }
    return;
  }
Esempio n. 12
0
 public void Read() {
   try {
     BufferedReader reader = new BufferedReader(new FileReader(file));
     while (reader.ready()) {
       String[] str = reader.readLine().split(";");
       list.add(
           new Item(Integer.parseInt(str[0]), str[1], str[2], str[3], Integer.parseInt(str[4])));
     }
     reader.close();
   } catch (Exception e) {
     // TODO 自动生成的 catch 块
     e.printStackTrace();
   }
 }
 private static List<SentencePair> readSentencePairs(String baseFileName) {
   List<SentencePair> sentencePairs = new ArrayList<SentencePair>();
   String englishFileName = baseFileName + "." + ENGLISH_EXTENSION;
   String frenchFileName = baseFileName + "." + FRENCH_EXTENSION;
   try {
     BufferedReader englishIn = new BufferedReader(new FileReader(englishFileName));
     //BufferedReader frenchIn = new BufferedReader(new FileReader(frenchFileName));
     BufferedReader frenchIn = new BufferedReader(new InputStreamReader(
   		  new FileInputStream(frenchFileName), StandardCharsets.ISO_8859_1));
     while (englishIn.ready() && frenchIn.ready()) {
       String englishLine = englishIn.readLine();
       String frenchLine = frenchIn.readLine();
       Pair<Integer,List<String>> englishSentenceAndID = readSentence(englishLine);
       Pair<Integer,List<String>> frenchSentenceAndID = readSentence(frenchLine);
       if (! englishSentenceAndID.getFirst().equals(frenchSentenceAndID.getFirst()))
         throw new RuntimeException("Sentence ID confusion in file "+baseFileName+", lines were:\n\t"+englishLine+"\n\t"+frenchLine);
       sentencePairs.add(new SentencePair(englishSentenceAndID.getFirst(), baseFileName, englishSentenceAndID.getSecond(), frenchSentenceAndID.getSecond()));
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
   return sentencePairs;
 }
Esempio n. 14
0
 public static String getLicensee() {
   InputStream is = Q2.class.getResourceAsStream(LICENSEE);
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   if (is != null) {
     BufferedReader br = new BufferedReader(new InputStreamReader(is));
     PrintStream p = new PrintStream(baos);
     p.println();
     p.println();
     try {
       while (br.ready()) p.println(br.readLine());
     } catch (Exception e) {
       e.printStackTrace(p);
     }
   }
   return baos.toString();
 }
Esempio n. 15
0
  public void serialEvent(SerialPortEvent event) {
    System.out.println("Serial Port event");
    switch (event.getEventType()) {
      case SerialPortEvent.DATA_AVAILABLE:
        @SuppressWarnings("unused")
        String Interrupt = "";

        try {
          while (reader.ready() == false) {}
          ;
          Interrupt = reader.readLine();
        } catch (IOException e) {
        }
        break;
    }
  }
Esempio n. 16
0
	FileHash(File f) {
		hash=new long[(int)f.length()];
		length=f.length();
		int i=0;
		int h=0;
    try {
      BufferedReader br=new BufferedReader(new FileReader(f));
      while (br.ready()) {
				int c=br.read();
				h=h+c;
				hash[i]=h;
      }
      br.close();
    } catch (Exception e) {
      System.out.println("What should I do with exception "+e+" ?");
    }
		System.out.println(""+h);
  }
Esempio n. 17
0
  private void parseLilyPond() {
    lilyHeader = new LilyHeader(name);
    try {
      BufferedReader LYIn = new BufferedReader(new FileReader("data/ly/" + name + ".ly"));
      int line = 1;
      while (LYIn.ready()) {
        String S = LYIn.readLine();

        // TODO: detect new staff location better
        if ((S.contains("\\new Staff") && (S.contains("down") || S.contains("lower"))
            || S.contains("NEW STAFF"))) {
          staffLine = line;
          staves = 2;
        }

        for (int i = 0; i < S.length(); ++i) {
          if (S.charAt(i) == '~') {
            ArrayList<Integer> t = new ArrayList<Integer>();
            t.add(line);
            t.add(i);
            ties.add(t);
          }
        }

        ++line;
      }

      LYIn.close();
    } catch (Exception e) {
      System.err.println("Parsing the score from Lilypond's output has failed. Error: ");
      e.printStackTrace();
    }

    notes = (Vector<NotePanel>[]) new Vector[staves];
    chords = (Vector<Chord>[]) new Vector[staves];
    currNotes = (Iterator<NotePanel>[]) new Iterator[staves];
    for (int i = 0; i < staves; ++i) {
      notes[i] = new Vector<NotePanel>();
      chords[i] = new Vector<Chord>();
      currNotes[i] = notes[i].iterator();
    }
  }
Esempio n. 18
0
 static ToolBox fromStream(InputStream in, Board board) {
   ToolBox tb = new ToolBox();
   InputStreamReader read = new InputStreamReader(in);
   BufferedReader buff = new BufferedReader(read);
   try {
     while (buff.ready()) {
       String s = buff.readLine();
       SprayTool st = SprayTool.fromString(s, board);
       if (st != null) {
         tb.tools.add(st);
         tb.toolKeys.put(st.getHotKey(), st);
       }
     }
     buff.close();
     tb.currentTool = tb.tools.size() > 0 ? tb.tools.get(0) : null;
   } catch (IOException e) {
     e.printStackTrace();
   }
   return tb;
 }
Esempio n. 19
0
 private String physReadTextFile(File file) {
   // physically read text file
   try {
     BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
     StringBuffer tmp = new StringBuffer();
     while (input.ready()) {
       tmp.append(input.readLine());
       tmp.append("\n");
     }
     return tmp.toString();
   } catch (FileNotFoundException e) {
     // not sure how this can happen
     showErrorDialog("Unable to load \"" + file.getName() + "\" (file not found)");
   } catch (IOException e) {
     // This happens if e.g. file already exists and
     // we do not have write permissions
     showErrorDialog("Unable to load \"" + file.getName() + "\" (I/O error)");
   }
   return new String("");
 }
Esempio n. 20
0
  /**
   * Loads INI formatted input from a stream reader into this instance. Everything in the stream
   * before the first section header is ignored.
   *
   * @param streamReader where to read from
   * @throws IOException at an I/O problem
   */
  public void load(InputStreamReader streamReader) throws IOException {
    BufferedReader reader = new BufferedReader(streamReader);
    String curSection = null;
    String line = null;

    while (reader.ready()) {
      line = reader.readLine().trim();
      if (line.length() > 0 && line.charAt(0) == Section.HEADER_START) {
        int endIndex = line.indexOf(Section.HEADER_END);
        if (endIndex >= 0) {
          curSection = line.substring(1, endIndex);
          addSection(curSection);
        }
      }
      if (curSection != null) {
        Section sect = getSection(curSection);
        sect.load(reader);
      }
    }
  }
Esempio n. 21
0
  static void reader(ArrayList<String> nameFile) throws Exception {

    BufferedReader in = null;
    FileReader file = null;
    try {
      if (isInput) {
        for (int j = 0; j < nameFile.size(); j++) { // read from files
          int numberWord = 0;
          file = new FileReader(nameFile.get(j));
          in = new BufferedReader(file);
          while (in.ready()) {
            String currentLine = in.readLine();
            queue.put(new Pair(currentLine, j, numberWord));
            numberWord++;
          }
          in.close();
          file.close();
        }
      } else { // read from stdin
        in = new BufferedReader(new InputStreamReader(System.in));
        String currentLine;
        int numberWord = 0;
        while ((currentLine = in.readLine()) != null) {
          queue.put(new Pair(currentLine, 1, numberWord));
          numberWord++;
        }
        in.close();
      }
    } finally {
      if (in != null) {
        in.close();
      }
      if (file != null) {
        file.close();
      }
    }
    for (int i = 0; i < numberThreads; i++) {
      queue.put(STOP);
    }
  }
Esempio n. 22
0
  public ScalarFrame(String filename, String delimiter) {
    this.delimiter = delimiter;
    try {
      BufferedReader in = new BufferedReader(new FileReader(filename));

      ArrayList tempvarnames = new ArrayList();
      ArrayList tempvalues = new ArrayList();

      while (in.ready()) {
        // read a line
        String s = in.readLine();
        StringTokenizer t = new StringTokenizer(s, delimiter);
        tempvarnames.add(t.nextToken());
        if (t.hasMoreTokens()) {
          tempvalues.add(new Double(Double.parseDouble(t.nextToken())));
        } else {
          System.out.println(filename + "had a line with a " + "variable " + "name and no value.");
          System.exit(0);
        }
      }

      m = tempvarnames.size();
      md = m;
      mi = ms = 0;
      varnames = new String[m];
      values = new double[m];
      for (int i = 0; i < m; i++) {
        varnames[i] = (String) (tempvarnames.get(i));
        values[i] = ((Double) (tempvalues.get(i))).doubleValue();
      }

      String[] realnames = new String[tempvarnames.size()];

      System.arraycopy(varnames, 0, realnames, 0, md);
    } catch (IOException e) {
      System.out.print("Error: " + e);
      System.exit(1);
    }
  }
Esempio n. 23
0
  /**
   * Steps: 1) open BufferReader of the designated file 2) IF not found, do nothing and stop code 3)
   * ELSE initialize variables 4) Count the number of lines until no longer ready 5) declare indexes
   * of a String array using number of lines 6) close and reboot BufferReader 7) reset counter to
   * zero 8) place each line into corresponding index of the array 9) close the BufferReader 10)
   * sort the array by values 11) initialize an ArrayList 12) clear duplicate entries 14) turn
   * ArrayList back into an array 15) open PrintWriter 16) overwrite the file 17) write the new
   * array per element per line
   *
   * @throws IOException
   */
  protected void assemble() throws IOException {
    // for testing purposes only

    try {
      BufferedReader oldFile;
      oldFile = new BufferedReader(new FileReader("DATABASE.rtf"));

      int k = 0;
      String[] str = {};

      while (true) {
        if (!oldFile.ready()) break;

        oldFile.readLine();
        k++;
      }

      str = new String[k];
      oldFile.close();

      k = 0;

      oldFile = new BufferedReader(new FileReader("DATABASE.rtf"));

      while (true) {
        if (!oldFile.ready()) break;

        String next_line = oldFile.readLine();

        str[k] = next_line;
        k++;
      }

      oldFile.close();

      // java.util.Arrays.sort(str);
      Quicksort quickie = new Quicksort();
      quickie.sort(str);
      // TODO reassign the numbers so that the whole first block of int is sorted, or place the
      // value of '-' before '+', and have numbers with '-' have the order reversed

      /*TODO fix this code
      ArrayList arlList = new ArrayList(Arrays.asList(str));
      HashSet h = new HashSet(arlList);
      arlList.clear();
      arlList.addAll(h);

      arlList.toArray(str);
      */
      PrintWriter newFile;
      newFile = new PrintWriter(new BufferedWriter(new FileWriter("DATABASE.rtf", false)));
      ;

      for (int i = 0; i < str.length; i++) newFile.append(str[i] + "\n");

      newFile.close();

    } catch (FileNotFoundException e) {
      /*do nothing and stop code*/
    }
  }
Esempio n. 24
0
  public static void readCommand() {
    try {

      if (!reader.ready()) {
        return;
      }

      StringTokenizer tokens = new StringTokenizer(reader.readLine());

      if (tokens.hasMoreTokens()) {

        switch (tokens.nextToken()) {
          case "/listen":
            listen(tokens);
            break;

          case "/stop":
            stop();
            break;

          case "/list":
            if (port[0] == -1) {
              System.err.println("Error: start listening before");
            }

            for (Entry<String, SocketChannel> client : clients.entrySet()) {
              System.out.println(client.getKey());
            }

            if (clients.entrySet().isEmpty()) {
              System.out.println("list: no clients online");
            }
            break;

          case "/send":
            if (tokens.hasMoreTokens()) {
              String name = tokens.nextToken();
              if (clients.containsKey(name)) {
                if (tokens.hasMoreTokens()) {
                  sendMessage(
                      clients.get(name),
                      MessageUtils.message("<server>", getMessageFromTokens(tokens)));
                } else {
                  System.err.println("send: message is empty");
                }
              } else {
                System.err.println("send: no such client");
              }
            } else {
              System.err.println("send: no client name");
            }
            break;

          case "/sendall":
            if (tokens.hasMoreTokens()) {
              notifyAllClients(getMessageFromTokens(tokens));
            } else {
              System.err.println("sendall: message is empty");
            }
            break;

          case "/kill":
            kill(tokens);
            break;

          case "/exit":
            if (port[0] != -1) {
              stop();
            }
            Utils.tryClose(selector);
            System.exit(0);
            break;

          default:
            System.err.print("Error: unknown command");
            break;
        }

      } else {
        System.err.println("Error: empty input");
      }

    } catch (Exception expt) {
      Utils.printErrorAndExit(expt.getMessage());
    }
  }
  /**
   * Method to obtain the resource media types.
   *
   * @param configSystemRegistry a configuration system registry instance.
   * @return a String of resource media types, in the format extension:type,extension:type,...
   * @throws RegistryException if the operation failed.
   */
  public static String getResourceMediaTypeMappings(Registry configSystemRegistry)
      throws RegistryException {

    RegistryContext registryContext = configSystemRegistry.getRegistryContext();

    if (getResourceMediaTypeMappings(registryContext) != null) {
      return getResourceMediaTypeMappings(registryContext);
    }

    Resource resource;
    String mediaTypeString = null;

    String resourcePath =
        MIME_TYPE_COLLECTION + RegistryConstants.PATH_SEPARATOR + RESOURCE_MIME_TYPE_INDEX;

    if (!configSystemRegistry.resourceExists(resourcePath)) {
      resource = configSystemRegistry.newCollection();
    } else {
      resource = configSystemRegistry.get(resourcePath);
      Properties properties = resource.getProperties();
      if (properties.size() > 0) {
        Set<Object> keySet = properties.keySet();
        for (Object key : keySet) {
          if (key instanceof String) {
            String ext = (String) key;
            if (RegistryUtils.isHiddenProperty(ext)) {
              continue;
            }
            String value = resource.getProperty(ext);
            String mediaTypeMapping = ext + ":" + value;
            if (mediaTypeString == null) {
              mediaTypeString = mediaTypeMapping;
            } else {
              mediaTypeString = mediaTypeString + "," + mediaTypeMapping;
            }
          }
        }
      }
      registryContext.setResourceMediaTypes(mediaTypeString);
      return mediaTypeString;
    }

    BufferedReader reader;
    try {
      File mimeFile = getMediaTypesFile();
      reader = new BufferedReader(new InputStreamReader(new FileInputStream(mimeFile)));
    } catch (Exception e) {
      String msg =
          "Failed to read the the media type definitions file. Only a limited "
              + "set of media type definitions will be populated. ";
      log.error(msg, e);
      mediaTypeString = "txt:text/plain,jpg:image/jpeg,gif:image/gif";
      registryContext.setResourceMediaTypes(mediaTypeString);
      return mediaTypeString;
    }

    try {
      while (reader.ready()) {
        String mediaTypeData = reader.readLine().trim();
        if (mediaTypeData.startsWith("#")) {
          // ignore the comments
          continue;
        }

        if (mediaTypeData.length() == 0) {
          // ignore the blank lines
          continue;
        }

        // mime.type file delimits media types:extensions by tabs. if there is no
        // extension associated with a media type, there are no tabs in the line. so we
        // don't need such lines.
        if (mediaTypeData.indexOf('\t') > 0) {

          String[] parts = mediaTypeData.split("\t+");
          if (parts.length == 2 && parts[0].length() > 0 && parts[1].length() > 0) {

            // there can multiple extensions associated with a single media type. in
            // that case, extensions are delimited by a space.
            String[] extensions = parts[1].trim().split(" ");
            for (String extension : extensions) {
              if (extension.length() > 0) {
                String mediaTypeMapping = extension + ":" + parts[0];
                resource.setProperty(extension, parts[0]);
                if (mediaTypeString == null) {
                  mediaTypeString = mediaTypeMapping;
                } else {
                  mediaTypeString = mediaTypeString + "," + mediaTypeMapping;
                }
              }
            }
          }
        }
      }
      resource.setDescription(
          "This collection contains the media Types available for "
              + "resources on the Registry. Add, Edit or Delete properties to Manage Media "
              + "Types.");
      Resource collection = configSystemRegistry.newCollection();
      collection.setDescription(
          "This collection lists the media types available on the "
              + "Registry Server. Before changing an existing media type, please make sure "
              + "to alter existing resources/collections and related configuration details.");
      configSystemRegistry.put(MIME_TYPE_COLLECTION, collection);
      configSystemRegistry.put(resourcePath, resource);

    } catch (IOException e) {
      String msg = "Could not read the media type mappings file from the location: ";
      throw new RegistryException(msg, e);

    } finally {
      try {
        reader.close();
      } catch (IOException ignore) {
      }
    }
    registryContext.setResourceMediaTypes(mediaTypeString);
    return mediaTypeString;
  }
Esempio n. 26
0
  /**
   * Takes a vector full of property lists and generates a report.
   *
   * @param args Command line arguments. args[0] should be the config filename.
   */
  public static void main(String[] args) {
    // Load the database properties from properties file
    Properties properties = new Properties();

    // Load config file
    String configFile = null;
    if (args.length > 0) configFile = args[0];

    try {
      if (configFile == null) {
        System.out.println("Database config file not set.");
        return;
      } else properties.load(new FileInputStream(configFile));
    } catch (IOException e) {
      System.out.println("Error opening config file.");
    }

    String url = properties.getProperty("databaseUrl");
    String username = properties.getProperty("username");
    String password = properties.getProperty("password");
    String dir = System.getProperty("user.dir"); // Current working directory
    Connection con = null;

    // Try to open file containing javac output
    String output = "";
    try {
      BufferedReader outputReader = new BufferedReader(new FileReader(dir + "/CompileOut.txt"));

      while (outputReader.ready()) output += outputReader.readLine() + '\n';

      // Close file
      outputReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("Error opening compilation output file.");
      return;
    } catch (IOException e) {
      System.out.println("I/O Exception Occured.");
      return;
    }

    boolean hasDriver = false;
    // Create class for the driver
    try {
      Class.forName("com.mysql.jdbc.Driver");
      hasDriver = true;
    } catch (Exception e) {
      System.out.println("Failed to load MySQL JDBC driver class.");
    }

    // Create connection to database if the driver was found
    if (hasDriver) {
      try {
        con = DriverManager.getConnection(url, username, password);
      } catch (SQLException e) {
        System.out.println("Couldn't get connection!");
      }
    }

    // Check that a connection was made
    if (con != null) {
      long userEventId = -1;

      // Store results from the report into the database
      try {
        BufferedReader rd =
            new BufferedReader(
                new FileReader(dir + "/userId.txt")); // Read userId.txt to get userId
        String userId = rd.readLine(); // Store userId from text file
        rd.close();

        // Insert the report into the table and get the auto_increment id for it
        Statement stmt = con.createStatement();
        stmt.executeUpdate("INSERT INTO userEvents (userId) VALUES ('" + userId + "')");
        ResultSet result = stmt.getGeneratedKeys();
        result.next();
        userEventId = result.getLong(1);

        // Close the statement
        stmt.close();

        // Prepare statement for adding the compilation error to the userEvent
        PreparedStatement compErrorPrepStmt =
            con.prepareStatement(
                "INSERT INTO userEventCompilationErrors(userEventId, output) VALUES (?, ?)");

        // Insert userEventId and docletId into the database
        compErrorPrepStmt.setLong(1, userEventId);
        compErrorPrepStmt.setString(2, output);
        compErrorPrepStmt.executeUpdate();

        // Close the prepare statements
        compErrorPrepStmt.close();
      } catch (Exception e) {
        System.out.println("Exception Occurred");
        System.out.println(e);
      }

      // Store the java files for the report
      try {
        // Prepare statement for storing files
        PreparedStatement filePrepStmt =
            con.prepareStatement(
                "INSERT INTO files(userEventId, filename, contents) VALUES ("
                    + userEventId
                    + ", ?, ?)");

        // Get the list of files from source.txt
        BufferedReader rd =
            new BufferedReader(
                new FileReader(dir + "/source.txt")); // Read userId.txt to get userId
        while (rd.ready()) {
          String filename = rd.readLine(); // Store userId from text file
          // Remove the "src/" from the beginning to get the real file name
          String realname = filename.substring(4);
          filePrepStmt.setString(1, realname);

          // Read in the contents of the files
          String contents = "";
          File javaFile = new File(dir + "/" + filename);
          int length = (int) javaFile.length();

          // Add parameter for file contents to the prepared statement and execute it
          filePrepStmt.setCharacterStream(2, new BufferedReader(new FileReader(javaFile)), length);
          filePrepStmt.executeUpdate();
        }
        rd.close();
      } catch (IOException e) {
        System.err.println("I/O Exception Occured.");
      } catch (SQLException e) {
        System.err.println("SQL Exception Occured.");
      }
    }
  }
Esempio n. 27
0
  public boolean parserCpYieldTxt(File txtFile) throws Exception {
    FileInputStream fIn = null;
    String fileNameUid = "";
    try {
      Calendar calendar = Calendar.getInstance();
      SimpleDateFormat df2 = new SimpleDateFormat("yyyyMM");

      // Using Find Target "|=124" or ",=44" Count
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

      logger.debug(
          "File "
              + txtFile.getAbsolutePath()
              + "  "
              + txtFile.getName()
              + "  "
              + new MimetypesFileTypeMap().getContentType(txtFile));

      // 1.0 讀入檔案, 建立資料流
      fIn = new FileInputStream(txtFile);
      // FileInputStream fIn2 = new FileInputStream(csvFile);
      InputStreamReader isr = null;
      BufferedReader br = null;
      isr = new InputStreamReader(fIn, "UTF-8");
      br = new BufferedReader(isr);

      // byte[] byteArray = new byte[new Long(csvFile.length()).intValue()];
      // 讀入File Data Byte.....
      // fIn2.read(byteArray);
      logger.debug(txtFile.getName() + "<--讀入資料檔...成功");
      // Using get sign  "\n" 抓行數...

      // 1.1 讀入行數資料, 略過行數
      int l = -1;
      List<String> lineDataList = new ArrayList<String>();
      for (int i = 0; i <= l; i++) {
        br.readLine();
      }
      while (br.ready()) {
        String line = br.readLine();
        line = null != line ? line : "";
        // logger.debug(line);
        if (!line.trim().equals("")) {
          lineDataList.add(line);
        }
      }

      // 1.2 確認有資料開使處理
      if (lineDataList != null) {
        CpYieldParserDao cpYieldParserDao = new CpYieldParserDao();

        CpYieldLotTo cpYieldLotTo = new CpYieldLotTo();

        String cpYieldUuid = UUID.randomUUID().toString().toUpperCase();
        logger.debug("lineDataList.size() " + lineDataList.size());

        fileNameUid =
            FilenameUtils.getBaseName(txtFile.getName())
                + "_"
                + cpYieldUuid
                + "."
                + FilenameUtils.getExtension(txtFile.getName());

        File bkFolder =
            new File(fileOutUrl + File.separator + df2.format(calendar.getTime()).toString());

        bkFolder.mkdir();

        File bkFile = new File(bkFolder.getPath().toString() + File.separator + fileNameUid);
        // 1.2.1 處理每行資料
        String tmpWaferID = lineDataList.get(1);
        String arrayWafer[] = tmpWaferID.split("=")[1].trim().split("-");

        // logger.debug("arrayWafer[] " + arrayWafer.length);

        // 1.3 Prepare Data
        String cpLot = arrayWafer[0].trim();
        String waferId = arrayWafer[1].trim();
        String machineId = arrayWafer[2].trim();
        Integer cpTestTimes = cpYieldParserDao.getMaxCpTestTimes(cpLot, waferId);

        String xMaxCoor = lineDataList.get(2).split("=")[1].trim();
        String yMaxCoor = lineDataList.get(3).split("=")[1].trim();
        String flat = lineDataList.get(4).split("=")[1].trim();

        logger.debug("xMaxCoor " + xMaxCoor);
        logger.debug("yMaxCoor " + yMaxCoor);
        logger.debug("flat " + flat);

        // 1.3 Find Bin Data
        int sb = 0, eb = 0;
        for (int i = 0; i < lineDataList.size(); i++) {
          if (lineDataList.get(i).indexOf("Wafer Bin Summary") >= 0) {
            sb = i + 1;
            break;
          }
        }
        for (int i = sb; i < lineDataList.size(); i++) {
          if (lineDataList.get(i).indexOf("bin") < 0) {
            eb = i - 1;
            break;
          }
        }

        logger.debug("sb " + sb);
        logger.debug(lineDataList.get(sb).trim());
        logger.debug("eb " + eb);
        logger.debug(lineDataList.get(eb).trim());
        // 1.3.1 Get Bin Data
        List<CpYieldLotBinTo> cpYieldLotBins = new ArrayList<CpYieldLotBinTo>();
        String cpYieldBinUuid;

        String bin;
        Integer die;
        String percentage;
        String binString;

        for (int j = sb; j <= eb; j++) {
          cpYieldBinUuid = UUID.randomUUID().toString().toUpperCase();
          CpYieldLotBinTo cpYieldLotBinTo = new CpYieldLotBinTo();

          cpYieldLotBinTo.setCpYieldBinUuid(cpYieldBinUuid);
          cpYieldLotBinTo.setCpYieldUuid(cpYieldUuid);

          binString = lineDataList.get(j).trim();
          binString = binString.replaceAll("bin", "").trim();
          // Get Bin
          bin = binString.substring(0, binString.indexOf(" "));
          logger.debug("bin " + bin);
          // Get Die
          bin = binString.substring(0, binString.indexOf(" "));
          binString = binString.replaceAll(bin, "").trim();
          die = Integer.parseInt(binString.substring(0, binString.indexOf(" ")));
          logger.debug("die " + die);
          // Get Percentage
          binString = binString.replaceAll(die.toString(), "").trim();
          percentage = binString.substring(0, binString.length() - 1);
          logger.debug("percentage " + percentage);

          cpYieldLotBinTo.setBin(bin);
          cpYieldLotBinTo.setDie(die);
          cpYieldLotBinTo.setPercentage(percentage);

          cpYieldLotBins.add(cpYieldLotBinTo);
        }

        // 1.4 Die Data
        Integer passDie;
        Integer failDie;
        Integer totelDie;
        for (int i = eb + 1; i < lineDataList.size(); i++) {
          // pass die
          if (lineDataList.get(i).trim().indexOf("pass die") >= 0) {
            passDie = Integer.parseInt(lineDataList.get(i).trim().split(":")[1].trim());
            logger.debug("passDie " + passDie);
            cpYieldLotTo.setPassDie(passDie);
            continue;
          }
          // fail die
          if (lineDataList.get(i).trim().indexOf("fail die") >= 0) {
            failDie = Integer.parseInt(lineDataList.get(i).trim().split(":")[1].trim());
            logger.debug("failDie " + failDie);
            cpYieldLotTo.setFailDie(failDie);
            continue;
          }
          // totel die
          if (lineDataList.get(i).trim().indexOf("totel die") >= 0) {
            totelDie = Integer.parseInt(lineDataList.get(i).trim().split(":")[1].trim());
            logger.debug("totelDie " + totelDie);
            cpYieldLotTo.setTotelDie(totelDie);
            continue;
          }
        }

        // 1.5 Set data in To
        cpYieldLotTo.setCpYieldUuid(cpYieldUuid);
        cpYieldLotTo.setCpTestTimes(cpTestTimes);
        cpYieldLotTo.setCpLot(cpLot);
        cpYieldLotTo.setWaferId(waferId);
        cpYieldLotTo.setMachineId(machineId);
        cpYieldLotTo.setxMaxCoor(xMaxCoor);
        cpYieldLotTo.setyMaxCoor(yMaxCoor);
        cpYieldLotTo.setFlat(flat);

        String fileMimeType = new MimetypesFileTypeMap().getContentType(txtFile);
        cpYieldLotTo.setFileName(
            df2.format(calendar.getTime()).toString() + File.separator + fileNameUid);
        cpYieldLotTo.setFileMimeType(fileMimeType);
        cpYieldLotTo.setFtpFlag("N");

        fIn.close();
        br.close();

        Methods.copyFile(txtFile, bkFile);
        txtFile.delete();
        // 1.6 DataBasse
        // 1.6.1 Insert CP Lot Table
        cpYieldParserDao.insertCpYieldLot(cpYieldLotTo);
        cpYieldParserDao.insertCpYieldLotBin(cpYieldLotBins);
      }

      fIn.close();
      br.close();

      logger.info(txtFile.getName() + " is Parser complete");
      logger.info(fileNameUid + " is Parser complete");

      // logger.debug(tapeList.size());
      logger.info("---------------------------------");
    } catch (Exception e) {
      if (fIn != null) {
        fIn.close();
      }
      logger.info("ERROR MOVE FILE");
      Methods.copyFile(txtFile, new File(fileErrorUrl + "\\" + txtFile.getName()));
      txtFile.delete();

      StackTraceElement[] messages = e.getStackTrace();
      Exception ex = new Exception(txtFile.getName());
      ex.setStackTrace(messages);
      ex.printStackTrace();
      throw ex;
    } finally {
      try {
        if (fIn != null) {
          fIn.close();
        }
      } catch (IOException ie) {
        StackTraceElement[] messages = ie.getStackTrace();
        int length = messages.length;
        String error = "";
        for (int i = 0; i < length; i++) {
          error = error + "toString:" + messages[i].toString() + "\r\n";
        }
        ie.printStackTrace();
        logger.error(error);
        return false;
      }
    }
    return true;
  }
Esempio n. 28
0
    /**
     * Loads options from a reader into this instance. Will read from the stream until it hits a
     * section header, ie a '[' character, and resets the reader to point to this character.
     *
     * @param reader where to read from
     * @throws IOException at an I/O problem
     */
    public void load(BufferedReader reader) throws IOException {
      while (reader.ready()) {
        reader.mark(NAME_MAXLENGTH);
        String line = reader.readLine().trim();

        // Check for section header
        if (line.length() > 0 && line.charAt(0) == HEADER_START) {
          reader.reset();
          return;
        }

        int delimIndex = -1;
        // blank line
        if (line.equals("")) {
          this.addBlankLine();
        }
        // comment line
        else if ((delimIndex = Arrays.binarySearch(this.commentDelimsSorted, line.charAt(0)))
            >= 0) {
          addComment(line.substring(1), this.commentDelimsSorted[delimIndex]);
        }
        // option line
        else {
          delimIndex = -1;
          int delimNum = -1;
          int lastSpaceIndex = -1;
          for (int i = 0, l = line.length(); i < l && delimIndex < 0; i++) {
            delimNum = Arrays.binarySearch(this.optionDelimsSorted, line.charAt(i));
            if (delimNum >= 0) {
              delimIndex = i;
            } else {
              boolean isSpace =
                  Arrays.binarySearch(this.OPTION_DELIMS_WHITESPACE, line.charAt(i)) >= 0;
              if (!isSpace && lastSpaceIndex >= 0) {
                break;
              } else if (isSpace) {
                lastSpaceIndex = i;
              }
            }
          }
          // delimiter at start of line
          if (delimIndex == 0) {
            // XXX what's a man got to do?
          }
          // no delimiter found
          else if (delimIndex < 0) {
            if (lastSpaceIndex < 0) {
              this.set(line, "");
            } else {
              this.set(line.substring(0, lastSpaceIndex), line.substring(lastSpaceIndex + 1));
            }
          }
          // delimiter found
          else {
            this.set(
                line.substring(0, delimIndex),
                line.substring(delimIndex + 1),
                line.charAt(delimIndex));
          }
        }
      }
    }
Esempio n. 29
0
 /**
  * Load curve data from a specified file.
  *
  * @param fileStr the name of the file to be loaded.
  * @return An ArrayList that include the curve data.
  */
 public static ArrayList<ArrayList<Double>> getCurveDataFromFile(String fileName) {
   File file = new File(fileName);
   if (!file.exists()) {
     // showMessage();
     return null;
   }
   // open data file
   FileInputStream inStream = null;
   BufferedReader inReader = null;
   try {
     inStream = new FileInputStream(file);
     inReader = new BufferedReader(new InputStreamReader(inStream));
   } catch (Exception e) {
     // showMessage();
     return null; // Data file open error.
   }
   ArrayList<Double> xaxes = new ArrayList<Double>(1);
   ArrayList<Double> yaxes = new ArrayList<Double>(1);
   try {
     StringTokenizer st;
     String s;
     boolean start = false;
     while (inReader.ready()) {
       st = new StringTokenizer(inReader.readLine());
       over:
       {
         while (!st.hasMoreTokens()) { // Justify blank lines.
           if (inReader.ready()) {
             st = new StringTokenizer(inReader.readLine());
           } else break over;
         }
         s = st.nextToken();
         if ((!start) && (!s.startsWith("@"))) break over;
         if (!start) {
           start = true;
           break over;
         }
         if (s.startsWith("#") || s.startsWith("$") || s.startsWith("/"))
           break over; // Justify comment line.
         Double xaxis = null;
         Double yaxis = null;
         try {
           xaxis = Double.valueOf(s);
           xaxes.add(xaxis);
         } catch (NumberFormatException e) {
           // showMessage();
           inReader.close();
           inStream.close();
           return null; // Data file data format error.
         }
         s = st.nextToken();
         try {
           yaxis = Double.valueOf(s);
           yaxes.add(yaxis);
         } catch (NumberFormatException e) {
           // showMessage();
           inReader.close();
           inStream.close();
           return null; // Data file data format error.
         }
       }
     }
     inReader.close();
   } catch (Exception e) {
     // showMessage();
     return null; // Uncertain data file error.
   }
   ArrayList<ArrayList<Double>> curveData = new ArrayList<ArrayList<Double>>(2);
   curveData.add(xaxes);
   curveData.add(yaxes);
   return curveData;
 }
Esempio n. 30
0
  /**
   * Reads the next line from the process. This method will be used only if the supporting Java
   * Native Interface library could not be loaded.
   */
  private synchronized String pure_readLine() {
    String line;
    long current, timeout = ((new Date()).getTime()) + threshold;

    if (null == p || null == in || null == err) return null;
    // Debug.verbose("P4Process.readLine()");
    try {
      for (; ; ) {
        if (null == p || null == in || null == err) {
          Debug.error("P4Process.readLine(): Something went null");
          return null;
        }

        current = (new Date()).getTime();
        if (current >= timeout) {
          Debug.error("P4Process.readLine(): Timeout");
          // If this was generating a new object from stdin, return an
          // empty string. Otherwise, return null.
          for (int i = 0; i < new_cmd.length; i++) {
            if (new_cmd[i].equals("-i")) return "";
          }
          return null;
        }

        // Debug.verbose("P4Process.readLine().in: "+in);
        try {
          /**
           * If there's something coming in from stdin, return it. We assume that the p4 command was
           * called with -s which sends all messages to standard out pre-pended with a string that
           * indicates what kind of messsage it is error warning text info exit
           */
          // Some errors still come in on Standard error
          while (err.ready()) {
            line = err.readLine();
            if (null != line) {
              addP4Error(line + "\n");
            }
          }

          if (in.ready()) {
            line = in.readLine();
            Debug.verbose("From P4:" + line);
            if (line.startsWith("error")) {
              if (!line.trim().equals("")
                  && (-1 == line.indexOf("up-to-date"))
                  && (-1 == line.indexOf("no file(s) to resolve"))) {
                addP4Error(line);
              }
            } else if (line.startsWith("warning")) {
            } else if (line.startsWith("text")) {
            } else if (line.startsWith("info")) {
            } else if (line.startsWith("exit")) {
              int exit_code =
                  new Integer(line.substring(line.indexOf(" ") + 1, line.length())).intValue();
              if (0 == exit_code) {
                Debug.verbose("P4 Exec Complete.");
              } else {
                Debug.error("P4 exited with an Error!");
              }
              return null;
            }
            if (!raw) line = line.substring(line.indexOf(":") + 1).trim();
            Debug.verbose("P4Process.readLine(): " + line);
            return line;
          }
        } catch (NullPointerException ne) {
        }
        // If there's nothing on stdin or stderr, check to see if the
        // process has exited. If it has, return null.
        try {
          exit_code = p.exitValue();
          return null;
        } catch (IllegalThreadStateException ie) {
          Debug.verbose("P4Process: Thread is not done yet.");
        }
        // Sleep for a second, so this thread can't become a CPU hog.
        try {
          Debug.verbose("P4Process: Sleeping...");
          Thread.sleep(100); // Sleep for 1/10th of a second.
        } catch (InterruptedException ie) {
        }
      }
    } catch (IOException ex) {
      return null;
    }
  }