// Responsible for loading the number of lines per node
  // Receives a line delimited tokenizer.  It will only process one line of
  // that tokenizer.  It must read that line, create a space/tab delimited
  // tokenizer from it, grab the number of lines per node from that tokenizer.
  // Structures that can contain additional information following the number
  // of lines per node (such as trees) should then override this generic
  // loadLinesPerNodeInfo with their own version of the method which will call
  // on the super version to get the actual lines per node and add additional
  // code to process the other information
  public void loadLinesPerNodeInfo(StringTokenizer st, LinkedList llist, draw d)
      throws VisualizerLoadException {
    String tempString, tempString2;
    if (st.hasMoreTokens()) tempString = st.nextToken();
    else throw (new VisualizerLoadException("Expected lines per node - found end of string"));

    StringTokenizer t = new StringTokenizer(tempString, " \t");
    if (t.hasMoreTokens()) tempString2 = t.nextToken();
    else throw (new VisualizerLoadException("Expected lines per node - found " + tempString));

    linespernode = Format.atoi(tempString2);

    xspacing = 1.5;
    yspacing = 1.5;

    if (t.hasMoreTokens()) tempString2 = t.nextToken();
    else return;

    xspacing = Format.atof(tempString2);

    if (t.hasMoreTokens()) tempString2 = t.nextToken();
    else return;

    yspacing = Format.atof(tempString2);
  }
Exemple #2
0
  // See comment in createericlist regarding HandleViewParams
  private /*synchronized*/ String HandleViewParams(
      String tempString, LinkedList tempList, StringTokenizer st) throws VisualizerLoadException {
    while (tempString.toUpperCase().startsWith("VIEW")) {
      StringTokenizer t = new StringTokenizer(tempString, " \t");
      String s1 = t.nextToken().toUpperCase();
      String s2 = t.nextToken().toUpperCase();
      String s3 = t.nextToken();

      // HERE PROCESS URL's AS YOU DID QUESTIONS

      if (s2.compareTo("ALGO") == 0) {
        add_a_pseudocode_URL(s3);
        // System.out.println("Adding to urls: "+Snaps+":"+s3);
        //                 urlList.append(Snaps+1 +":"+s3);
      } else if (s2.compareTo("DOCS") == 0) {
        add_a_documentation_URL(s3);
        // System.out.println("Adding to urls: "+Snaps+":"+s3);
        //                 if (debug) System.out.println("Adding to urlList: "+Snaps+1+":"+s3);
        //                 urlList.append(Snaps+1 +":"+s3);
      } else if (s2.compareTo("SCALE") == 0) {
        GKS.scale(Format.atof(s3.toUpperCase()), tempList, this);
      } else if (s2.compareTo("WINDOWS") == 0) {
        GKS.windows(Format.atoi(s3.toUpperCase()), tempList, this);
      } else if (s2.compareTo("JUMP") == 0) {
        GKS.jump(Format.atoi(s3.toUpperCase()), tempList, this);
      } else throw (new VisualizerLoadException(s2 + " is invalid VIEW parameter"));
      tempString = st.nextToken();
    }
    //         if (urlList.size() == 0)
    //             urlList.append("**");
    return (tempString);
  }
 public void printPoints() {
   for (int i = 0; i < npoint; i++) {
     SequencePoint sp = (SequencePoint) points.elementAt(i);
     Format.print(System.out, "%5d ", i);
     for (int j = 0; j < 3; j++) {
       Format.print(System.out, "%13.3f  ", sp.coord[j]);
     }
     System.out.println();
   }
 }
 /**
  * Called when there was a change in one of the pin values. The event contains the changed value
  * in a string representation and a boolean which is true if the user pressed the 'ok' button and
  * false if the user pressed the 'cancel' button.
  */
 public void pinValueChanged(PinValueEvent e) {
   pinsTable.setEnabled(true);
   if (e.getIsOk()) {
     valuesStr[pinsTable.getSelectedRow()] = e.getValueStr();
     partPins[pinsTable.getSelectedRow()].value =
         Format.translateValueToShort(e.getValueStr(), dataFormat);
   }
   notifyListeners(
       pinsTable.getSelectedRow(), Format.translateValueToShort(e.getValueStr(), dataFormat));
 }
  /**
   * Returns a String representation of the Object <code>value</code>. This invokes <code>format
   * </code> on the current <code>Format</code>.
   *
   * @throws ParseException if there is an error in the conversion
   * @param value Value to convert
   * @return String representation of value
   */
  public String valueToString(Object value) throws ParseException {
    if (value == null) {
      return "";
    }
    Format f = getFormat();

    if (f == null) {
      return value.toString();
    }
    return f.format(value);
  }
    /** Sets the value at a specific row and column. */
    public void setValueAt(Object value, int row, int col) {

      String data = ((String) value).trim();
      try {
        valuesStr[row] = data;
        partPins[row].value = Format.translateValueToShort(data, dataFormat);
        notifyListeners((short) row, partPins[row].value);
      } catch (NumberFormatException nfe) {
        notifyErrorListeners("Illegal value");
        valuesStr[row] = Format.translateValueToString(partPins[row].value, dataFormat);
      }
      repaint();
    }
Exemple #7
0
  public void solve1216(int kaseno) throws Exception {
    int r1 = iread(), r2 = iread(), h = iread(), p = iread();

    double R1 = (double) r2;
    double R2 = ((double) ((r1 - r2) * p)) / h;
    R2 += r2;
    double H = (double) p;

    double ret = pii * (R1 * R1 + R2 * R2 + R1 * R2) * H;
    ret /= 3.;
    Format df = new DecimalFormat("0.0000000000");
    String res = df.format(ret);
    out.write("Case " + kaseno + ": " + res + "\n");
  }
 /** Sets the pins list's contents with the given vector of PartPinInfo objects. */
 public void setContents(Vector newPins) {
   partPins = new PartPinInfo[newPins.size()];
   valuesStr = new String[newPins.size()];
   newPins.toArray(partPins);
   for (int i = 0; i < partPins.length; i++)
     valuesStr[i] = Format.translateValueToString(partPins[i].value, dataFormat);
   pinsTable.clearSelection();
   pinsTable.revalidate();
   repaint();
 }
  public GTN getGTNode(StringTokenizer st, String s, int linesPerNode, LinkedList llist, draw d)
      throws EndOfSnapException, VisualizerLoadException {
    GTN gtn = new GTN();

    if (s.equals("-1")) throw (new EndOfSnapException("End of Snap Shot Reached"));

    gtn.Glevel = Format.atoi(s);
    gtn.textInNode = getTextNode(st, linesPerNode, llist, d);

    return (gtn);
  }
Exemple #10
0
  /**
   * Changes the output of all probes to the specified file. This method may be called multiple
   * times during the execution of the JVM.
   *
   * @param pathname the pathname of the output file.
   */
  public static void setOutput(String pathname) {

    // open specified file
    PrintStream previous = outputStream;
    try {
      outputStream = new PrintStream(new FileOutputStream(pathname));
    } catch (FileNotFoundException e) {
      // if file cannot be opened, output remains unchanged
      return;
    }

    // close previous output if not standard output
    if (previous != null && !previous.equals(System.out)) {
      previous.close();
    }

    // print date and time
    Format format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    outputStream.println("Starting on " + format.format(new Date()));
  }
 /** Sets the value at a specific row and column. */
 public void setValueAt(Object value, int row, int col) {
   String data = ((String) value).trim();
   if (!getStrAt(row).equals(data)) {
     try {
       short currentValue;
       if (data.equals("") && hideNullValue) currentValue = nullValue;
       else currentValue = Format.translateValueToShort(data, memory.dataFormat);
       notifyListeners((short) row, currentValue);
     } catch (NumberFormatException nfe) {
       notifyErrorListeners("Illegal value");
     }
     repaint();
   }
 }
Exemple #12
0
  /**
   * Gets the list of the hierarchical folders.
   *
   * @return the list of the hierarchical folders.
   */
  public Vector getHierarchicalFolders() {
    Vector folder_list = new Vector();

    folder_list.addElement(CatalogManager.getCatalogCategoryFolder(getCatalogCategoryNumber()));
    folder_list.addElement(getCatalogFolderCode());

    folder_list.addElement(name.substring(0, 1));

    int number = Format.intValueOf(name.substring(2)) / 100;
    number *= 100;
    folder_list.addElement(String.valueOf(number));

    return folder_list;
  }
  /**
   * Gets the sortable array of the specified column.
   *
   * @param header_value the header value of the column to sort.
   */
  protected SortableArray getSortableArray(String header_value) {
    if (header_value.length() == 0) return null;

    SortableArray array = null;
    if (header_value.equals("R.A.") || header_value.equals("Decl.") || header_value.equals("ID"))
      array = new StringArray(record_list.size());
    else array = new Array(record_list.size());

    for (int i = 0; i < record_list.size(); i++) {
      String value = getCellString(header_value, i);

      if (header_value.equals("R.A.")
          || header_value.equals("Decl.")
          || header_value.equals("ID")) {
        ((StringArray) array).set(i, value);
      } else if (header_value.equals("Max Mag") || header_value.equals("Min Mag")) {
        double mag_value = 0.0;
        if ('0' <= value.charAt(0) && value.charAt(0) <= '9'
            || value.charAt(0) == '-'
            || value.charAt(0) == '+') {
          mag_value = Format.doubleValueOf(value);
        } else {
          mag_value = 100 + Format.doubleValueOf(value.substring(1));
        }
        ((Array) array).set(i, mag_value);
      } else if (header_value.equals("First Date") || header_value.equals("Last Date")) {
        double jd = 0.0;
        if (value.length() > 0) jd = JulianDay.create(value).getJD();
        ((Array) array).set(i, jd);
      } else {
        ((Array) array).set(i, Double.parseDouble(value));
      }
    }

    return array;
  }
 public static synchronized Vector<CaptureDeviceInfo> getDeviceList(Format format) {
   Vector<CaptureDeviceInfo> result = new Vector<CaptureDeviceInfo>();
   for (CaptureDeviceInfo captureDeviceInfo : getDeviceList()) {
     if (format == null) {
       result.add(captureDeviceInfo);
     } else {
       for (Format aFormat : captureDeviceInfo.getFormats()) {
         if (format.matches(aFormat)) {
           result.add(captureDeviceInfo);
           break;
         }
       }
     }
   }
   return result;
 }
  /**
   * Gets the output string of the cell.
   *
   * @param header_value the header value of the column.
   * @param row the index of row in original order.
   * @return the output string of the cell.
   */
  protected String getCellString(String header_value, int row) {
    Variability record = (Variability) record_list.elementAt(row);

    if (header_value.equals("R.A.")) {
      String coor = record.getStar().getCoor().getOutputString();
      int p = coor.indexOf(' ');
      return coor.substring(0, p);
    }
    if (header_value.equals("Decl.")) {
      String coor = record.getStar().getCoor().getOutputString();
      int p = coor.indexOf(' ');
      return coor.substring(p + 1);
    }
    if (header_value.equals("ID")) {
      if (record.getIdentifiedStar() != null) return record.getIdentifiedStar().getName();
    }
    if (header_value.equals("Max Mag")) {
      return ((XmlMag) record.getBrightestMagnitude().getMag()).getOutputString();
    }
    if (header_value.equals("Min Mag")) {
      return ((XmlMag) record.getFaintestMagnitude().getMag()).getOutputString();
    }
    if (header_value.equals("Mag Range")) {
      return Format.formatDouble(record.getMagnitudeRange(), 5, 2);
    }
    if (header_value.equals("Observations")) {
      return String.valueOf(record.getObservations());
    }
    if (header_value.equals("Positive Observations")) {
      return String.valueOf(record.getPositiveObservations());
    }
    if (header_value.equals("Arc")) {
      return String.valueOf(record.getArcInDays());
    }
    if (header_value.equals("First Date")) {
      String s = record.getFirstDate();
      if (s != null) return s;
    }
    if (header_value.equals("Last Date")) {
      String s = record.getLastDate();
      if (s != null) return s;
    }
    return "";
  }
Exemple #16
0
  public /*synchronized*/ Color colorSet(String values) {
    String temp;
    int x;
    Color c = Color.black;

    StringTokenizer st = new StringTokenizer(values);
    x = Format.atoi(st.nextToken());
    if (x == 1) c = Color.black;
    else if (x == 2) c = Color.blue;
    else if (x == 6) c = Color.cyan;
    else if (x == 13) c = Color.darkGray;
    else if (x == 11) c = Color.gray;
    else if (x == 3) c = Color.green;
    else if (x == 9) c = Color.lightGray;
    else if (x == 5) c = Color.magenta;
    else if (x == 10) c = Color.orange;
    else if (x == 12) c = Color.pink;
    else if (x == 4) c = Color.red;
    else if (x == 8) c = Color.white;
    else if (x == 7) c = Color.yellow;
    else if (x < 0) c = new Color(-x);
    return c;
  }
Exemple #17
0
  // creates the list of snapshots
  public /*synchronized*/ obj dothis(String inputString) {
    /* Snapshot codes

    29 - rectangle draw
    2 - oval draw
    5 - fill oval
    6 - string
    7 - line & text color
    8 - fill color
    9 - text color (possible to ignore)
    10 - text height
    11 - polydraw
    4 - fill poly
    14 - arc draw
    30 - fill arc
    12 - text style, centered horizontal/vertical
    ???? 45 - url.  Note, when bring up multiple algorithms, the URL's for the most recently
    run algorithm are posted in the upper browser frame
    THE CODE BELOW WOULD INDICATE THIS IS 54, NOT 45 ????

    20 - number of windows.  For static algorithms, 1, 2, 3, 4 have the obvious meaning.
    21 - scale factor
    22 - jump factor

    For 20, 21, 22, the last factor loaded is the one that will affect all snapshots in
    the show

     */

    obj temp = new rectDraw("0 0 0 0", lineC);
    Object urlTest;
    String arrg;

    int graphic_obj_code = Format.atoi(inputString.substring(0, 3));
    StringTokenizer tmp = null;

    switch (graphic_obj_code) {
      case 29:
        temp = new rectDraw(inputString.substring(3, (inputString.length())), lineC);
        break;
      case 2:
        temp = new ovalDraw(inputString.substring(3, (inputString.length())), lineC);
        break;
      case 5:
        temp = new fillOvalDraw(inputString.substring(3, (inputString.length())), fillC);
        break;
      case 6:
        temp =
            new stringDraw(
                inputString.substring(3, (inputString.length())), textC, LineH, LineV, fontMult);
        // 		System.out.println(" printing " + inputString);
        break;
      case 7:
        lineC = colorSet(inputString.substring(3, (inputString.length())));
        textC = lineC;
        break;
      case 8:
        tmp = new StringTokenizer(inputString.substring(2, (inputString.length())));
        fillC = colorSet(tmp.nextToken());
        break;
      case 9:
        textC = colorSet(inputString.substring(3, (inputString.length())));
        break;
      case 10:
        StringTokenizer st = new StringTokenizer(inputString.substring(3, (inputString.length())));
        fontMult = Format.atof(st.nextToken());
        // 		System.out.println("setting fontMult= " + fontMult);
        break;
        // TLN changed on 10/14/97 to accomodate condensed prm files
        // temp=new textHeight(inputString.substring(3,(inputString.length())));
      case 11:
        temp = new polyDraw(inputString.substring(3, (inputString.length())), lineC);
        break;
      case 4:
        temp = new fillPolyDraw(inputString.substring(3, (inputString.length())), fillC);
        break;
      case 64:
        temp = new animated_fillPolyDraw(inputString.substring(3, (inputString.length())), fillC);
        break;
      case 14:
        temp = new arcDraw(inputString.substring(3, (inputString.length())), lineC);
        break;
      case 30:
        temp = new fillArcDraw(inputString.substring(3, (inputString.length())), fillC);
        break;
      case 12:
        tmp = new StringTokenizer(inputString.substring(3, (inputString.length())));
        LineH = Format.atoi(tmp.nextToken());
        LineV = Format.atoi(tmp.nextToken());
        break;
      case 20:
        tmp = new StringTokenizer(inputString.substring(3, (inputString.length())));
        // graphWin.setNumViews(Format.atoi(tmp.nextToken()));
        // multiTrigger=true;
        break;
      case 21:
        tmp = new StringTokenizer(inputString.substring(3, (inputString.length())));
        double tempFloat = Format.atof(tmp.nextToken());
        zoom = tempFloat;
        break;
      case 22:
        tmp = new StringTokenizer(inputString.substring(3, (inputString.length())));
        //            graphWin.setJump(Format.atoi(tmp.nextToken()));  // This is now a noop in
        // gaigs2
        break;
      case 54:
        tmp = new StringTokenizer(inputString.substring(3, (inputString.length())));
        //             if (tmp.hasMoreElements()){
        //                 urlTest=tmp.nextToken();
        //                 urlList.append(urlTest);
        //             }
        //             else{
        //                 tmp=new StringTokenizer("**");
        //                 urlTest=tmp.nextToken();
        //                 urlList.append(urlTest);
        //             }
        break;
    } // end switch

    return (temp);
  }
Exemple #18
0
  public void loadStructure(StringTokenizer st, LinkedList llist, draw d)
      throws VisualizerLoadException {
    String s;
    GTN gtn = new GTN();
    Dne = false; // For handling EOSS in the recursive procedure *)

    s = st.nextToken();
    if (!(st.hasMoreTokens()))
      throw (new VisualizerLoadException(
          "Encountered Bad Data When Expecting number of total nodes"));
    nn = Format.atoi(s);
    numNodes = nn;

    s = st.nextToken();
    if (!(st.hasMoreTokens()))
      throw (new VisualizerLoadException(
          "Encountered Bad Data When Expecting number of total nodes"));
    path = Format.atoi(s);

    s = st.nextToken();
    if (!(st.hasMoreTokens()))
      throw (new VisualizerLoadException(
          "Encountered Bad Data When Expecting number of total nodes"));
    weight = Format.atoi(s);

    s = st.nextToken();
    if (!(st.hasMoreTokens()))
      throw (new VisualizerLoadException(
          "Encountered Bad Data When Expecting number of total nodes"));
    badCommand = Format.atoi(s);

    s = st.nextToken();
    if (!(s.equals(newTree)))
      throw (new VisualizerLoadException("Encountered Bad Data When Expecting New Tree Delimeter"));

    while (!Dne && numNodes > 0) {
      if (st.hasMoreTokens()) s = st.nextToken();
      else s = "-1";

      try {
        gtn = getGTNode(st, s, linespernode, llist, d);
        numNodes--;
      } catch (EndOfSnapException e) {
        Dne = true;
      }
      if (!Dne) {
        buildGeneralTree(st, gtn, llist, d); // Build Tree *)
        nodelist.append(gtn);
        Dne = false;
      }
    }

    // loop that gets the final info values from the file
    for (int x = 0; x < 4; x++) {
      if (st.hasMoreTokens()) s = st.nextToken();
      else throw (new VisualizerLoadException("End of data when expecting info"));

      if (x == 0) cpf = s;
      else if (x == 1) cpu = s;
      else if (x == 2) command = s;
    }
  }
 /** Returns the value at the given index in its string representation. */
 public String getValueAsString(int index) {
   return Format.translateValueToString(
       memory.getValueAsShort((short) (index + startAddress)), dataFormat);
 }
 // Returns the string at the given location
 private String getStrAt(int index) {
   short currentValue = memory.getValueAsShort((short) (index + startAddress));
   if (currentValue == nullValue && hideNullValue) return "";
   else return Format.translateValueToString(currentValue, dataFormat);
 }
 /** Sets the element at the given index with the given value. */
 public void setValueAt(int index, short value) {
   partPins[index].value = value;
   valuesStr[index] = Format.translateValueToString(value, dataFormat);
   repaint();
 }
  public static String calculateYouTubeUrl(
      String pYouTubeFmtQuality, boolean pFallback, String pYouTubeVideoId)
      throws IOException, ClientProtocolException, UnsupportedEncodingException {

    String lUriStr = null;
    HttpClient lClient = new DefaultHttpClient();

    HttpGet lGetMethod = new HttpGet(YoutubeUrlIDs.YOUTUBE_VIDEO_INFORMATION_URL + pYouTubeVideoId);

    HttpResponse lResp = null;

    lResp = lClient.execute(lGetMethod);

    ByteArrayOutputStream lBOS = new ByteArrayOutputStream();
    String lInfoStr = null;

    lResp.getEntity().writeTo(lBOS);
    lInfoStr = new String(lBOS.toString("UTF-8"));

    String[] lArgs = lInfoStr.split("&");
    Map<String, String> lArgMap = new HashMap<String, String>();
    for (int i = 0; i < lArgs.length; i++) {
      String[] lArgValStrArr = lArgs[i].split("=");
      if (lArgValStrArr != null) {
        if (lArgValStrArr.length >= 2) {
          lArgMap.put(lArgValStrArr[0], URLDecoder.decode(lArgValStrArr[1]));
        }
      }
    }

    // Find out the URI string from the parameters

    // Populate the list of formats for the video
    String lFmtList = URLDecoder.decode(lArgMap.get("fmt_list"));
    ArrayList<Format> lFormats = new ArrayList<Format>();
    if (null != lFmtList) {
      String lFormatStrs[] = lFmtList.split(",");

      for (String lFormatStr : lFormatStrs) {
        Format lFormat = new Format(lFormatStr);
        lFormats.add(lFormat);
      }
    }

    // Populate the list of streams for the video
    String lStreamList = lArgMap.get("url_encoded_fmt_stream_map");
    if (null != lStreamList) {
      String lStreamStrs[] = lStreamList.split(",");
      ArrayList<VideoStream> lStreams = new ArrayList<VideoStream>();
      for (String lStreamStr : lStreamStrs) {
        VideoStream lStream = new VideoStream(lStreamStr);
        lStreams.add(lStream);
      }

      // Search for the given format in the list of video formats
      // if it is there, select the corresponding stream
      // otherwise if fallback is requested, check for next lower format
      int lFormatId = Integer.parseInt(pYouTubeFmtQuality);

      Format lSearchFormat = new Format(lFormatId);
      while (!lFormats.contains(lSearchFormat) && pFallback) {
        int lOldId = lSearchFormat.getId();
        int lNewId = getSupportedFallbackId(lOldId);

        if (lOldId == lNewId) {
          break;
        }
        lSearchFormat = new Format(lNewId);
      }

      int lIndex = lFormats.indexOf(lSearchFormat);
      if (lIndex >= 0) {
        VideoStream lSearchStream = lStreams.get(lIndex);
        lUriStr = lSearchStream.getUrl();
      }
    }
    // Return the URI string. It may be null if the format (or a fallback format if enabled)
    // is not found in the list of formats for the video
    return lUriStr;
  }
  /** Parsing videos from youtube. This is : Script#2 */
  public static ArrayList<Video> func_get_video_script2(String pYouTubeVideoId)
      throws IOException, ClientProtocolException, UnsupportedEncodingException {

    ArrayList<Video> lVideoList = new ArrayList<Video>();

    HttpClient lClient = new DefaultHttpClient();

    HttpGet lGetMethod =
        new HttpGet(
            YoutubeUrlIDs.YOUTUBE_VIDEO_INFORMATION_URL
                + pYouTubeVideoId
                + "&el=embedded&gl=US&hl=en&eurl="
                + URLEncoder.encode("https://youtube.googleapis.com/v/" + pYouTubeVideoId, "UTF-8")
                + "&asv=3&sts=1588");

    HttpResponse lResp = null;

    lResp = lClient.execute(lGetMethod);

    ByteArrayOutputStream lBOS = new ByteArrayOutputStream();
    String lInfoStr = null;

    lResp.getEntity().writeTo(lBOS);
    lInfoStr = new String(lBOS.toString("UTF-8"));

    String[] lArgs = lInfoStr.split("&");
    Map<String, String> lArgMap = new HashMap<String, String>();
    for (int i = 0; i < lArgs.length; i++) {
      String[] lArgValStrArr = lArgs[i].split("=");
      if (lArgValStrArr != null) {
        if (lArgValStrArr.length >= 2) {
          lArgMap.put(lArgValStrArr[0], URLDecoder.decode(lArgValStrArr[1]));
        }
      }
    }

    // Find out the URI string from the parameters

    // Populate the list of formats for the video
    String lFmtList = URLDecoder.decode(lArgMap.get("fmt_list"));
    ArrayList<Format> lFormats = new ArrayList<Format>();
    if (null != lFmtList) {
      String lFormatStrs[] = lFmtList.split(",");

      for (String lFormatStr : lFormatStrs) {
        Format lFormat = new Format(lFormatStr);
        lFormats.add(lFormat);
      }
    }

    // Populate the list of streams for the video
    String lStreamList = lArgMap.get("url_encoded_fmt_stream_map");
    if (null != lStreamList) {
      String lStreamStrs[] = lStreamList.split(",");
      ArrayList<VideoStream> lStreams = new ArrayList<VideoStream>();
      for (String lStreamStr : lStreamStrs) {
        VideoStream lStream = new VideoStream(lStreamStr);
        lStreams.add(lStream);
      }

      // -----------------------------------------------------
      // ----
      HashMap<Integer, String> typeMap = new HashMap<Integer, String>();

      typeMap.put(13, "Low : 176x144 | 3GP");
      typeMap.put(17, "Low : 176x144 | 3GP");
      typeMap.put(36, "Medium : 320x240 | 3GP");

      typeMap.put(5, "Medium : 640x360 | FLV");
      typeMap.put(6, "Medium : 640x360 | FLV");

      typeMap.put(34, "Medium : 640x360 | FLV");
      typeMap.put(35, "High : 854x480 | FLV");

      typeMap.put(43, "Medium : 640x360 | WEBM");
      typeMap.put(44, "High : 854x480 | WEBM");
      typeMap.put(45, "HD : 1280x720 | WEBM");
      typeMap.put(46, "Full HD 3D : 1920x1020 | WEBM");

      typeMap.put(18, "Medium :  480x360 | MP4");
      typeMap.put(22, "HD :  1280x720 | MP4");

      typeMap.put(37, "Full HD : 1920x1080 | MP4");
      typeMap.put(38, "Full HD 3D : 3072x1080 | MP4");
      typeMap.put(33, "4K : 4096x230 | MP4");

      for (Format lformat : lFormats) {
        Video lvid = new Video();
        int lIndex = lFormats.indexOf(lformat);
        int id = lformat.getId();
        // get video quality type string..
        String ltype = typeMap.get(id);

        if (lIndex >= 0) {
          VideoStream lSearchStream = lStreams.get(lIndex);

          String lUriString = Uri.decode(Uri.parse(lSearchStream.getUrl()).toString());

          lvid.type = ltype;
          lvid.url = lUriString;
          if (lvid.type != null && lvid.url != null) {
            lVideoList.add(lvid);
          }
        }
      }
    }

    return lVideoList;
  }
  /** Parsing videos from youtube. Script#1. */
  public static ArrayList<Video> func_get_video_script1(String web_source) throws Exception {
    ArrayList<Video> video_list = new ArrayList<Video>();

    String[] lArgs = web_source.split("&");
    Map<String, String> lArgMap = new HashMap<String, String>();
    for (int i = 0; i < lArgs.length; i++) {
      String[] lArgValStrArr = lArgs[i].split("=");
      if (lArgValStrArr != null) {
        if (lArgValStrArr.length >= 2) {
          lArgMap.put(lArgValStrArr[0], URLDecoder.decode(lArgValStrArr[1]));
        }
      }
    }

    // Find out the URI string from the parameters

    // Populate the list of formats for the video
    String lFmtList = URLDecoder.decode(lArgMap.get("fmt_list"));
    ArrayList<Format> lFormats = new ArrayList<Format>();
    if (null != lFmtList) {
      String lFormatStrs[] = lFmtList.split(",");

      for (String lFormatStr : lFormatStrs) {
        Format lFormat = new Format(lFormatStr);
        lFormats.add(lFormat);
      }
    }

    // Populate the list of streams for the video
    String lStreamList = lArgMap.get("url_encoded_fmt_stream_map");
    if (null != lStreamList) {
      String lStreamStrs[] = lStreamList.split(",");
      ArrayList<VideoStream> lStreams = new ArrayList<VideoStream>();
      for (String lStreamStr : lStreamStrs) {
        VideoStream lStream = new VideoStream(lStreamStr);
        lStreams.add(lStream);
      }

      // -----------------------------------------------------
      // ----
      HashMap<Integer, String> typeMap = new HashMap<Integer, String>();

      typeMap.put(13, "Low : 176x144 | 3GP");
      typeMap.put(17, "Low : 176x144 | 3GP");
      typeMap.put(36, "Medium : 320x240 | 3GP");

      typeMap.put(5, "Medium : 640x360 | FLV");
      typeMap.put(6, "Medium : 640x360 | FLV");

      typeMap.put(34, "Medium : 640x360 | FLV");
      typeMap.put(35, "High : 854x480 | FLV");

      typeMap.put(43, "Medium : 640x360 | WEBM");
      typeMap.put(44, "High : 854x480 | WEBM");
      typeMap.put(45, "HD : 1280x720 | WEBM");
      typeMap.put(46, "Full HD 3D : 1920x1020 | WEBM");

      typeMap.put(18, "Medium :  480x360 | MP4");
      typeMap.put(22, "HD :  1280x720 | MP4");

      typeMap.put(37, "Full HD : 1920x1080 | MP4");
      typeMap.put(38, "Full HD 3D : 3072x1080 | MP4");
      typeMap.put(33, "4K : 4096x230 | MP4");

      for (Format lformat : lFormats) {
        Video lvid = new Video();
        int lIndex = lFormats.indexOf(lformat);
        int id = lformat.getId();
        // get video quality type string..
        String ltype = typeMap.get(id);

        if (lIndex >= 0) {
          VideoStream lSearchStream = lStreams.get(lIndex);

          String lUriString = Uri.decode(Uri.parse(lSearchStream.getUrl()).toString());

          lvid.type = ltype;
          lvid.url = lUriString;
          if (lvid.type != null && lvid.url != null) {
            video_list.add(lvid);
          }
        }
      }
    }

    return video_list;
  }
 /** Invokes <code>parseObject</code> on <code>f</code>, returning its value. */
 Object stringToValue(String text, Format f) throws ParseException {
   if (f == null) {
     return text;
   }
   return f.parseObject(text);
 }
Exemple #26
0
  /**
   * Implements {@link ControllerListener#controllerUpdate(ControllerEvent)}. Handles events from
   * the <tt>Processor</tt>s that this instance uses to transcode media.
   *
   * @param ev the event to handle.
   */
  public void controllerUpdate(ControllerEvent ev) {
    if (ev == null || ev.getSourceController() == null) {
      return;
    }

    Processor processor = (Processor) ev.getSourceController();
    ReceiveStreamDesc desc = findReceiveStream(processor);

    if (desc == null) {
      logger.warn("Event from an orphaned processor, ignoring: " + ev);
      return;
    }

    if (ev instanceof ConfigureCompleteEvent) {
      if (logger.isInfoEnabled()) {
        logger.info(
            "Configured processor for ReceiveStream ssrc="
                + desc.ssrc
                + " ("
                + desc.format
                + ")"
                + " "
                + System.currentTimeMillis());
      }

      boolean audio = desc.format instanceof AudioFormat;

      if (audio) {
        ContentDescriptor cd = processor.setContentDescriptor(AUDIO_CONTENT_DESCRIPTOR);
        if (!AUDIO_CONTENT_DESCRIPTOR.equals(cd)) {
          logger.error(
              "Failed to set the Processor content "
                  + "descriptor to "
                  + AUDIO_CONTENT_DESCRIPTOR
                  + ". Actual result: "
                  + cd);
          removeReceiveStream(desc, false);
          return;
        }
      }

      for (TrackControl track : processor.getTrackControls()) {
        Format trackFormat = track.getFormat();

        if (audio) {
          final long ssrc = desc.ssrc;
          SilenceEffect silenceEffect;
          if (Constants.OPUS_RTP.equals(desc.format.getEncoding())) {
            silenceEffect = new SilenceEffect(48000);
          } else {
            // We haven't tested that the RTP timestamps survive
            // the journey through the chain when codecs other than
            // opus are in use, so for the moment we rely on FMJ's
            // timestamps for non-opus formats.
            silenceEffect = new SilenceEffect();
          }

          silenceEffect.setListener(
              new SilenceEffect.Listener() {
                boolean first = true;

                @Override
                public void onSilenceNotInserted(long timestamp) {
                  if (first) {
                    first = false;
                    // send event only
                    audioRecordingStarted(ssrc, timestamp);
                  } else {
                    // change file and send event
                    resetRecording(ssrc, timestamp);
                  }
                }
              });
          desc.silenceEffect = silenceEffect;
          AudioLevelEffect audioLevelEffect = new AudioLevelEffect();
          audioLevelEffect.setAudioLevelListener(
              new SimpleAudioLevelListener() {
                @Override
                public void audioLevelChanged(int level) {
                  activeSpeakerDetector.levelChanged(ssrc, level);
                }
              });

          try {
            // We add an effect, which will insert "silence" in
            // place of lost packets.
            track.setCodecChain(new Codec[] {silenceEffect, audioLevelEffect});
          } catch (UnsupportedPlugInException upie) {
            logger.warn("Failed to insert silence effect: " + upie);
            // But do go on, a recording without extra silence is
            // better than nothing ;)
          }
        } else {
          // transcode vp8/rtp to vp8 (i.e. depacketize vp8)
          if (trackFormat.matches(vp8RtpFormat)) track.setFormat(vp8Format);
          else {
            logger.error("Unsupported track format: " + trackFormat + " for ssrc=" + desc.ssrc);
            // we currently only support vp8
            removeReceiveStream(desc, false);
            return;
          }
        }
      }

      processor.realize();
    } else if (ev instanceof RealizeCompleteEvent) {
      desc.dataSource = processor.getDataOutput();

      long ssrc = desc.ssrc;
      boolean audio = desc.format instanceof AudioFormat;
      String suffix = audio ? AUDIO_FILENAME_SUFFIX : VIDEO_FILENAME_SUFFIX;

      // XXX '\' on windows?
      String filename = getNextFilename(path + "/" + ssrc, suffix);
      desc.filename = filename;

      DataSink dataSink;
      if (audio) {
        try {
          dataSink = Manager.createDataSink(desc.dataSource, new MediaLocator("file:" + filename));
        } catch (NoDataSinkException ndse) {
          logger.error("Could not create DataSink: " + ndse);
          removeReceiveStream(desc, false);
          return;
        }

      } else {
        dataSink = new WebmDataSink(filename, desc.dataSource);
      }

      if (logger.isInfoEnabled())
        logger.info(
            "Created DataSink ("
                + dataSink
                + ") for SSRC="
                + ssrc
                + ". Output filename: "
                + filename);
      try {
        dataSink.open();
      } catch (IOException e) {
        logger.error("Failed to open DataSink (" + dataSink + ") for" + " SSRC=" + ssrc + ": " + e);
        removeReceiveStream(desc, false);
        return;
      }

      if (!audio) {
        final WebmDataSink webmDataSink = (WebmDataSink) dataSink;
        webmDataSink.setSsrc(ssrc);
        webmDataSink.setEventHandler(eventHandler);
        webmDataSink.setKeyFrameControl(
            new KeyFrameControlAdapter() {
              @Override
              public boolean requestKeyFrame(boolean urgent) {
                return requestFIR(webmDataSink);
              }
            });
      }

      try {
        dataSink.start();
      } catch (IOException e) {
        logger.error(
            "Failed to start DataSink (" + dataSink + ") for" + " SSRC=" + ssrc + ". " + e);
        removeReceiveStream(desc, false);
        return;
      }

      if (logger.isInfoEnabled()) logger.info("Started DataSink for SSRC=" + ssrc);

      desc.dataSink = dataSink;

      processor.start();
    } else if (logger.isDebugEnabled()) {
      logger.debug(
          "Unhandled ControllerEvent from the Processor for ssrc=" + desc.ssrc + ": " + ev);
    }
  }