Esempio n. 1
0
  public void addSample(String packagePath, Sample sample) {
    // convert something like 'org.controlsfx.samples.actions' to 'samples.actions'
    String packagesWithoutBase = "";
    try {
      if (!basePackage.equals(packagePath)) {
        packagesWithoutBase = packagePath.substring(basePackage.length() + 1);
      }
    } catch (StringIndexOutOfBoundsException e) {
      System.out.println("packagePath: " + packagePath + ", basePackage: " + basePackage);
      e.printStackTrace();
      return;
    }

    // then split up the packages into separate strings
    String[] packages =
        packagesWithoutBase.isEmpty() ? new String[] {} : packagesWithoutBase.split("\\.");

    // then for each package convert to a prettier form
    for (int i = 0; i < packages.length; i++) {
      String packageName = packages[i];
      if (packageName.isEmpty()) continue;

      packageName = packageName.substring(0, 1).toUpperCase() + packageName.substring(1);
      packageName = packageName.replace("_", " ");
      packages[i] = packageName;
    }

    // now we have the pretty package names, we add this sample into the
    // tree in the appropriate place
    sampleTree.addSample(packages, sample);
  }
Esempio n. 2
0
 /**
  * Test of doOCR method, of class Tesseract.
  *
  * @throws Exception while processing image.
  */
 @Test
 public void testDoOCR_List_Rectangle() throws Exception {
   File imageFile = null;
   String expResult = "The (quick) [brown] {fox} jumps!\nOver the $43,456.78 <lazy> #90 dog";
   String result = "<empty>";
   try {
     logger.info("doOCR on a PDF document");
     imageFile = new File(this.testResourcesDataPath, "eurotext.pdf");
     List<IIOImage> imageList = ImageIOHelper.getIIOImageList(imageFile);
     result = instance.doOCR(imageList, null);
     logger.info(result);
     assertEquals(expResult, result.substring(0, expResult.length()));
   } catch (IOException e) {
     logger.error(
         "Exception-Message: '{}'. Imagefile: '{}'",
         e.getMessage(),
         imageFile.getAbsoluteFile(),
         e);
     fail();
   } catch (TesseractException e) {
     logger.error(
         "Exception-Message: '{}'. Imagefile: '{}'",
         e.getMessage(),
         imageFile.getAbsoluteFile(),
         e);
     fail();
   } catch (StringIndexOutOfBoundsException e) {
     logger.error(
         "Exception-Message: '{}'. Imagefile: '{}'",
         e.getMessage(),
         imageFile.getAbsoluteFile(),
         e);
     fail();
   }
 }
Esempio n. 3
0
  public static String getSentencecaseString(String name) {
    String titleCaseValue = null;
    try {

      String[] words = name.split(" ");
      StringBuilder sb = new StringBuilder();
      if (words[0].length() > 0) {
        sb.append(
            Character.toUpperCase(words[0].charAt(0))
                + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
        for (int i = 1; i < words.length; i++) {
          sb.append(" ");
          sb.append(
              Character.toUpperCase(words[i].charAt(0))
                  + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
        }
      }
      titleCaseValue = sb.toString();

      // Log.i("STAG",titleCaseValue);

    } catch (StringIndexOutOfBoundsException e) {
      titleCaseValue = name;
      e.printStackTrace();
    } catch (Exception e) {
      titleCaseValue = name;
      e.printStackTrace();
    }
    return titleCaseValue;
  }
Esempio n. 4
0
 @Test
 public void testGetThrowsStringIndexOutOfBoundsException() throws Throwable {
   FSDMsg fSDMsg = new FSDMsg("testFSDMsgBasePath");
   try {
     fSDMsg.get("testFSDMsgId", "", 100, "testFSDMsgDefValue", null);
     fail("Expected StringIndexOutOfBoundsException to be thrown");
   } catch (StringIndexOutOfBoundsException ex) {
     assertEquals("ex.getMessage()", "String index out of range: 0", ex.getMessage());
     assertEquals("fSDMsg.fields.size()", 0, fSDMsg.fields.size());
   }
 }
  /**
   * Cut String by appointed size (Byte unit)
   *
   * @param beforeStr String need to convert
   * @param afterSize Size of string after converting(Byte Unit)
   * @return String String after converting
   */
  public static String cnvStrFixedLength(String beforeStr, int afterSize) {
    if (beforeStr == null) {
      return "";
    } else if (afterSize == 0) {
      return "";
    } else {

      // String after converting
      String afterStr = null;
      try {

        byte[] beforStrByte = beforeStr.getBytes("Shift_JIS");

        // In case string include only one-byte character(),and
        // string's size < appointed size
        if ((beforeStr.getBytes().length == beforeStr.length() && beforeStr.length() <= afterSize)
            || beforStrByte.length <= afterSize) {
          // Return same string
          return beforeStr;

        } else {

          // Generate after converting string(byte)
          byte[] afterStrByte = new byte[afterSize];
          for (int i = 0; i < afterSize; i++) {
            afterStrByte[i] = beforStrByte[i];
          }
          // Check if the last 2-byte character can be converted or
          // not
          try {
            // String tmpNewString = new String(afterStrByte);
            // If the last 2-byte character is not converted
            // correctly
            // Throw StringIndexOutOfBoundsException
            // String lastString = tmpNewString.substring(tmpNewString.length() - 1);
            afterStr = new String(afterStrByte);

          } catch (StringIndexOutOfBoundsException e) {
            e.printStackTrace();
            // Remove the last 2-byte character
            byte[] tmpBytes = afterStrByte;
            afterStrByte = new byte[tmpBytes.length - 1];
            for (int i = 0; i < afterStrByte.length; i++) {
              afterStrByte[i] = tmpBytes[i];
            }
            afterStr = new StringBuffer(new String(afterStrByte, "Shift_JIS")).toString();
          }
        }
      } catch (Exception e) {
        return null;
      }
      return afterStr;
    }
  }
Esempio n. 6
0
 @Test
 public void testGetHexHeaderThrowsStringIndexOutOfBoundsException() throws Throwable {
   FSDMsg fSDMsg = new FSDMsg("testFSDMsgBasePath", "testFSDMsgBaseSchema");
   byte[] h = new byte[0];
   fSDMsg.setHeader(h);
   try {
     fSDMsg.getHexHeader();
     fail("Expected StringIndexOutOfBoundsException to be thrown");
   } catch (StringIndexOutOfBoundsException ex) {
     assertEquals("ex.getMessage()", "String index out of range: -2", ex.getMessage());
   }
 }
Esempio n. 7
0
 @Test
 public void testDumpThrowsStringIndexOutOfBoundsException() throws Throwable {
   byte[] h = new byte[0];
   FSDMsg fSDMsg = new FSDMsg("testFSDMsgBasePath", "testFSDMsgBaseSchema");
   fSDMsg.setHeader(h);
   PrintStream p = new PrintStream(new ByteArrayOutputStream(), true, "UTF-16");
   try {
     fSDMsg.dump(p, "testFSDMsgIndent");
     fail("Expected StringIndexOutOfBoundsException to be thrown");
   } catch (StringIndexOutOfBoundsException ex) {
     assertEquals("ex.getMessage()", "String index out of range: -2", ex.getMessage());
     assertEquals("fSDMsg.fields.size()", 0, fSDMsg.fields.size());
   }
 }
Esempio n. 8
0
  public static void main(String args[]) {
    String textLine = new String("");
    int i = 0;
    try {
      System.out.println("aData1.dat integrity check.");
      AtomTypeFile f = new AtomTypeFile();
      // BufferedReader text = new BufferedReader(new FileReader("p.txt"));
      BufferedReader text =
          new BufferedReader(
              new FileReader(newNanocad.txtDir + newNanocad.fileSeparator + "p.txt"));

      while (text.ready()) {
        textLine = text.readLine();
        String numText = textLine.substring(0, textLine.indexOf(" "));
        int TextAtomNum = Integer.parseInt(numText);
        atomProperty curProp = f.getProperty(i);
        // System.out.println(curProp.getANumber() + " " + textLine);

        if (curProp.getANumber() != TextAtomNum) {
          System.out.print("ANumber mismatch for " + textLine + " (" + i + ")");
          System.out.println(" - dat:" + curProp.getANumber() + " txt:" + TextAtomNum);
          while (curProp.getANumber() != TextAtomNum) {
            int j = 0;
            while (curProp.getANumber() > TextAtomNum) {
              textLine = text.readLine();
              numText = textLine.substring(0, textLine.indexOf(" "));
              TextAtomNum = Integer.parseInt(numText);
              j++;
            }
            while (curProp.getANumber() < TextAtomNum) {
              i++;
              curProp = f.getProperty(i);
              j++;
            }
            System.out.println(j + " items skipped.");
          }
        }
        i++;
      }
    } catch (StringIndexOutOfBoundsException e) {
      System.out.println("Text parse error in line " + i + ": " + textLine);
      e.printStackTrace();
    } catch (Exception e) {
      System.out.println("ERROR");
      System.out.println(i + ": " + textLine);
      e.printStackTrace();
    }
    System.out.println("Integrity check concluded.");
  }
  @Override
  protected void connectedFunction() {
    int decimalCount = 0;
    int remainingCharacters = 3;
    byte[] rawPacket = new byte[100];
    int read = 0;
    while (mState == BluetoothState.CONNECTED && remainingCharacters > 0) {
      // Read one byte
      try {
        read += mBluetoothSocket.getInputStream().read(rawPacket, read, 1);
      } catch (IOException e) {
        e.printStackTrace();
        lostConnection();
        break;
      }
      String temp = "";
      try {
        temp = new String(rawPacket, read - 1, 1, "ISO-8859-1");
        if (temp.equals(".")) {
          if (decimalCount <= MAX_DECIMALS) decimalCount++;
          else remainingCharacters = 0;

        } else {
          if (decimalCount == MAX_DECIMALS) remainingCharacters--;
        }
      } catch (UnsupportedEncodingException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      } catch (StringIndexOutOfBoundsException e1) {
        e1.printStackTrace();
      }
    }
    if (mState == BluetoothState.CONNECTED) {
      AffectivaPacket p = null;
      try {
        p = AffectivaPacket.packetFromString(new String(rawPacket, 0, read, "ISO-8859-1"));
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
      // If p is not null the packet is a valid affectiva packet
      if (p != null) {
        // Log.d(TAG,"Read: "+p.toString());
        if (mHandler != null)
          mHandler.obtainMessage(SensorService.MESSAGE_BLUETOOTH_DATA, p).sendToTarget();
      } else {
        Log.d(TAG, "Read: invalid packet");
      }
    }
  }
Esempio n. 10
0
  public static Pair makeJavaMethodPair(String s) {
    try {
      String left = s.substring(s.indexOf('{') + 1, s.indexOf('\t'));
      JavaMethod t1 = null;
      if (!left.equals("empty")) t1 = new JavaMethod(left);
      ;

      String right = s.substring(s.indexOf('\t') + 1, s.indexOf('}'));
      JavaMethod t2 = null;
      if (!right.equals("empty")) t2 = new JavaMethod(right);
      return new Pair(t1, t2);

    } catch (StringIndexOutOfBoundsException e) {
      e.printStackTrace();
      System.out.println(s);
    }
    return null;
  }
  /**
   * Rekursive Erzeugung möglicher Permuationen aus der Eckenliste.
   *
   * @param beginning Leere Liste
   * @param ending Eckenliste
   */
  public void generatePermutation(List<Edge> beginning, List<Edge> ending) {
    if (ending.size() <= 1) {
      ArrayList<Edge> list = new ArrayList<Edge>(beginning);
      list.addAll(ending);
      permutations.add(new Path(list));

    } else {
      for (int i = 0; i < ending.size(); i++) {
        try {

          List<Edge> newList = new ArrayList<Edge>(ending.subList(0, i));
          newList.addAll(ending.subList(i + 1, ending.size()));

          List<Edge> newBeginning = new ArrayList<Edge>(beginning);
          newBeginning.add(ending.get(i));

          generatePermutation(newBeginning, newList);
        } catch (StringIndexOutOfBoundsException exception) {
          exception.printStackTrace();
        }
      }
    }
  }
Esempio n. 12
0
 /** @tests java.lang.String#substring(int, int) */
 public void test_substringErrorMessage() {
   try {
     hw1.substring(-1, 1);
   } catch (StringIndexOutOfBoundsException ex) {
     String msg = ex.getMessage();
     assertTrue("Expected message to contain -1: " + msg, msg.indexOf("-1") != -1);
   }
   try {
     hw1.substring(4, 1);
   } catch (StringIndexOutOfBoundsException ex) {
     String msg = ex.getMessage();
     assertTrue("Expected message to contain -3: " + msg, msg.indexOf("-3") != -1);
   }
   try {
     hw1.substring(0, 100);
   } catch (StringIndexOutOfBoundsException ex) {
     String msg = ex.getMessage();
     assertTrue("Expected message to contain 100: " + msg, msg.indexOf("100") != -1);
   }
 }
Esempio n. 13
0
  @SuppressWarnings("unused")
  @Override
  public void onDraw(Canvas canvas) {
    Rect frame = cameraManager.getFramingRect();
    if (frame == null) {
      return;
    }
    int width = canvas.getWidth();
    int height = canvas.getHeight();

    paint.setColor(maskColor);
    canvas.drawRect(0, 0, width, frame.top, paint);
    canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
    canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint);
    canvas.drawRect(0, frame.bottom + 1, width, height, paint);

    if (resultText != null) {

      Point bitmapSize = resultText.getBitmapDimensions();
      previewFrame = cameraManager.getFramingRectInPreview();
      if (bitmapSize.x == previewFrame.width() && bitmapSize.y == previewFrame.height()) {

        float scaleX = frame.width() / (float) previewFrame.width();
        float scaleY = frame.height() / (float) previewFrame.height();

        if (DRAW_REGION_BOXES) {
          regionBoundingBoxes = resultText.getRegionBoundingBoxes();
          for (int i = 0; i < regionBoundingBoxes.size(); i++) {
            paint.setAlpha(0xA0);
            paint.setColor(Color.MAGENTA);
            paint.setStyle(Style.STROKE);
            paint.setStrokeWidth(1);
            rect = regionBoundingBoxes.get(i);
            canvas.drawRect(
                frame.left + rect.left * scaleX,
                frame.top + rect.top * scaleY,
                frame.left + rect.right * scaleX,
                frame.top + rect.bottom * scaleY,
                paint);
          }
        }

        if (DRAW_TEXTLINE_BOXES) {
          textlineBoundingBoxes = resultText.getTextlineBoundingBoxes();
          paint.setAlpha(0xA0);
          paint.setColor(Color.RED);
          paint.setStyle(Style.STROKE);
          paint.setStrokeWidth(1);
          for (int i = 0; i < textlineBoundingBoxes.size(); i++) {
            rect = textlineBoundingBoxes.get(i);
            canvas.drawRect(
                frame.left + rect.left * scaleX,
                frame.top + rect.top * scaleY,
                frame.left + rect.right * scaleX,
                frame.top + rect.bottom * scaleY,
                paint);
          }
        }

        if (DRAW_WORD_BOXES || DRAW_WORD_TEXT) {
          wordBoundingBoxes = resultText.getWordBoundingBoxes();
        }

        if (DRAW_WORD_TEXT) {
          words = resultText.getText().replace("\n", " ").split(" ");
          int[] wordConfidences = resultText.getWordConfidences();
          for (int i = 0; i < wordBoundingBoxes.size(); i++) {
            boolean isWordBlank = true;
            try {
              if (!words[i].equals("")) {
                isWordBlank = false;
              }
            } catch (ArrayIndexOutOfBoundsException e) {
              e.printStackTrace();
            }

            if (!isWordBlank) {
              rect = wordBoundingBoxes.get(i);
              paint.setColor(Color.WHITE);
              paint.setStyle(Style.FILL);
              if (DRAW_TRANSPARENT_WORD_BACKGROUNDS) {
                paint.setAlpha(wordConfidences[i] * 255 / 100);
              } else {
                paint.setAlpha(255);
              }
              canvas.drawRect(
                  frame.left + rect.left * scaleX,
                  frame.top + rect.top * scaleY,
                  frame.left + rect.right * scaleX,
                  frame.top + rect.bottom * scaleY,
                  paint);

              paint.setColor(Color.BLACK);
              paint.setAlpha(0xFF);
              paint.setAntiAlias(true);
              paint.setTextAlign(Align.LEFT);

              paint.setTextSize(100);
              paint.setTextScaleX(1.0f);
              Rect bounds = new Rect();
              paint.getTextBounds(words[i], 0, words[i].length(), bounds);
              int h = bounds.bottom - bounds.top;
              float size = (((float) (rect.height()) / h) * 100f);
              paint.setTextSize(size);
              paint.setTextScaleX(1.0f);
              paint.getTextBounds(words[i], 0, words[i].length(), bounds);
              int w = bounds.right - bounds.left;
              int text_h = bounds.bottom - bounds.top;
              int baseline = bounds.bottom + ((rect.height() - text_h) / 2);
              float xscale = ((float) (rect.width())) / w;
              paint.setTextScaleX(xscale);
              canvas.drawText(
                  words[i],
                  frame.left + rect.left * scaleX,
                  frame.top + rect.bottom * scaleY - baseline,
                  paint);
            }
          }
        }

        if (DRAW_WORD_BOXES) {
          paint.setAlpha(0xA0);
          paint.setColor(0xFF00CCFF);
          paint.setStyle(Style.STROKE);
          paint.setStrokeWidth(1);
          for (int i = 0; i < wordBoundingBoxes.size(); i++) {
            rect = wordBoundingBoxes.get(i);
            canvas.drawRect(
                frame.left + rect.left * scaleX,
                frame.top + rect.top * scaleY,
                frame.left + rect.right * scaleX,
                frame.top + rect.bottom * scaleY,
                paint);
          }
        }

        if (DRAW_CHARACTER_BOXES || DRAW_CHARACTER_TEXT) {
          characterBoundingBoxes = resultText.getCharacterBoundingBoxes();
        }

        if (DRAW_CHARACTER_BOXES) {
          // Draw bounding boxes around each character
          paint.setAlpha(0xA0);
          paint.setColor(0xFF00FF00);
          paint.setStyle(Style.STROKE);
          paint.setStrokeWidth(1);
          for (int c = 0; c < characterBoundingBoxes.size(); c++) {
            Rect characterRect = characterBoundingBoxes.get(c);
            canvas.drawRect(
                frame.left + characterRect.left * scaleX,
                frame.top + characterRect.top * scaleY,
                frame.left + characterRect.right * scaleX,
                frame.top + characterRect.bottom * scaleY,
                paint);
          }
        }

        if (DRAW_CHARACTER_TEXT) {
          // Draw letters individually
          for (int i = 0; i < characterBoundingBoxes.size(); i++) {
            Rect r = characterBoundingBoxes.get(i);

            // Draw a white background for every letter
            int meanConfidence = resultText.getMeanConfidence();
            paint.setColor(Color.WHITE);
            paint.setAlpha(meanConfidence * (255 / 100));
            paint.setStyle(Style.FILL);
            canvas.drawRect(
                frame.left + r.left * scaleX,
                frame.top + r.top * scaleY,
                frame.left + r.right * scaleX,
                frame.top + r.bottom * scaleY,
                paint);

            // Draw each letter, in black
            paint.setColor(Color.BLACK);
            paint.setAlpha(0xFF);
            paint.setAntiAlias(true);
            paint.setTextAlign(Align.LEFT);
            String letter = "";
            try {
              char c = resultText.getText().replace("\n", "").replace(" ", "").charAt(i);
              letter = Character.toString(c);

              if (!letter.equals("-") && !letter.equals("_")) {

                // Adjust text size to fill rect
                paint.setTextSize(100);
                paint.setTextScaleX(1.0f);

                // ask the paint for the bounding rect if it were to draw this text
                Rect bounds = new Rect();
                paint.getTextBounds(letter, 0, letter.length(), bounds);

                // get the height that would have been produced
                int h = bounds.bottom - bounds.top;

                // figure out what textSize setting would create that height of text
                float size = (((float) (r.height()) / h) * 100f);

                // and set it into the paint
                paint.setTextSize(size);

                // Draw the text as is. We don't really need to set the text scale, because the
                // dimensions
                // of the Rect should already be suited for drawing our letter.
                canvas.drawText(
                    letter, frame.left + r.left * scaleX, frame.top + r.bottom * scaleY, paint);
              }
            } catch (StringIndexOutOfBoundsException e) {
              e.printStackTrace();
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        }
      }
    }
    // Draw a two pixel solid border inside the framing rect
    paint.setAlpha(0);
    paint.setStyle(Style.FILL);
    paint.setColor(frameColor);
    canvas.drawRect(frame.left, frame.top, frame.right + 1, frame.top + 2, paint);
    canvas.drawRect(frame.left, frame.top + 2, frame.left + 2, frame.bottom - 1, paint);
    canvas.drawRect(frame.right - 1, frame.top, frame.right + 1, frame.bottom - 1, paint);
    canvas.drawRect(frame.left, frame.bottom - 1, frame.right + 1, frame.bottom + 1, paint);

    // Draw the framing rect corner UI elements
    paint.setColor(cornerColor);
    canvas.drawRect(frame.left - 15, frame.top - 15, frame.left + 15, frame.top, paint);
    canvas.drawRect(frame.left - 15, frame.top, frame.left, frame.top + 15, paint);
    canvas.drawRect(frame.right - 15, frame.top - 15, frame.right + 15, frame.top, paint);
    canvas.drawRect(frame.right, frame.top - 15, frame.right + 15, frame.top + 15, paint);
    canvas.drawRect(frame.left - 15, frame.bottom, frame.left + 15, frame.bottom + 15, paint);
    canvas.drawRect(frame.left - 15, frame.bottom - 15, frame.left, frame.bottom, paint);
    canvas.drawRect(frame.right - 15, frame.bottom, frame.right + 15, frame.bottom + 15, paint);
    canvas.drawRect(frame.right, frame.bottom - 15, frame.right + 15, frame.bottom + 15, paint);
  }
  /** @param args program arguments */
  public static void main(String[] args) {
    AggressiveUrlCanonicalizer canonicalizer = new AggressiveUrlCanonicalizer();
    int n = 0;
    int i = 0;
    ArrayList<Integer> columns = new ArrayList<Integer>();

    long lineNumber = 0;
    boolean cdxPassThru = false;
    String delimiter = " ";
    while (n < args.length) {
      String arg = args[n];
      if (arg.compareTo("-cdx") == 0) {
        cdxPassThru = true;
        n++;
        continue;
      }
      if (n == (args.length - 1)) {
        USAGE();
      }
      String val = args[n + 1];
      if (arg.compareTo("-f") == 0) {
        columns.add(new Integer(val));
      } else if (arg.compareTo("-d") == 0) {
        delimiter = val;
      } else {
        USAGE();
      }
      n += 2;
    }
    // place default '0' in case none specified:
    if (columns.size() == 0) {
      columns.add(new Integer(1));
    }

    // convert to int[]:
    int[] cols = new int[columns.size()];
    for (int idx = 0; idx < columns.size(); idx++) {
      cols[idx] = columns.get(idx).intValue() - 1;
    }
    BufferedReader r = new BufferedReader(new InputStreamReader(System.in, ByteOp.UTF8));
    StringBuilder sb = new StringBuilder();
    String line = null;

    while (true) {
      try {
        line = r.readLine();
      } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
      }
      if (line == null) {
        break;
      }
      lineNumber++;
      if (cdxPassThru && line.startsWith(CDX_PREFIX)) {
        System.out.println(line);
        continue;
      }
      String parts[] = line.split(delimiter);
      for (int column : cols) {
        if (column >= parts.length) {
          System.err.println("Invalid line " + lineNumber + " (" + line + ") skipped");
        } else {
          try {
            parts[column] = canonicalizer.urlStringToKey(parts[column]);
          } catch (URIException e) {
            System.err.println(
                "Invalid URL in line "
                    + lineNumber
                    + " ("
                    + line
                    + ") skipped ("
                    + parts[column]
                    + ")");
            e.printStackTrace();
            continue;
          } catch (StringIndexOutOfBoundsException e) {
            System.err.println(
                "Invalid URL in line "
                    + lineNumber
                    + " ("
                    + line
                    + ") skipped ("
                    + parts[column]
                    + ")");
            e.printStackTrace();
            continue;
          }
        }
      }
      sb.setLength(0);
      for (i = 0; i < parts.length; i++) {
        sb.append(parts[i]);
        if (i < (parts.length - 1)) {
          sb.append(delimiter);
        }
      }
      System.out.println(sb.toString());
    }
  }
  public String urlStringToKey(final String urlString) throws URIException {

    if (urlString.startsWith("dns:")) {
      return urlString;
    }
    String searchUrl = canonicalize(urlString);
    String scheme = UrlOperations.urlToScheme(searchUrl);
    if (scheme != null) {
      searchUrl = searchUrl.substring(scheme.length());
    } else {
      scheme = UrlOperations.HTTP_SCHEME;
    }

    if (-1 == searchUrl.indexOf("/")) {
      searchUrl = scheme + searchUrl + "/";
    } else {
      searchUrl = scheme + searchUrl;
    }

    // Custom rules

    for (CanonicalizationRule rule : getProcessingRules()) {
      searchUrl = rule.processIfMatches(new CanonicalizationInput(searchUrl));
    }

    // Core rules

    // TODO: These next few lines look crazy -- need to be reworked.. This
    // was the only easy way I could find to get the correct unescaping
    // out of UsableURIs, possible a bug. Definitely needs some TLC in any case,
    // as building UsableURIs is *not* a cheap operation.

    // unescape anything that can be:
    UsableURI tmpURI = null;
    try {
      tmpURI = UsableURIFactory.getInstance(searchUrl);
    } catch (StringIndexOutOfBoundsException e) {
      LOGGER.warning(e.getMessage() + ": " + searchUrl);
      return searchUrl;
      //		} catch(URIException e) {
      //			LOGGER.warning(e.getMessage() + ": " + searchUrl);
      //			return searchUrl;
    }
    tmpURI.setPath(tmpURI.getPath());

    // convert to UsableURI to perform required URI fixup:
    UsableURI searchURI = UsableURIFactory.getInstance(tmpURI.getURI());

    // replace ' ' with '+' (this is only to match Alexa's canonicalization)
    String newPath = searchURI.getEscapedPath().replace("%20", "+");

    // replace multiple consecutive '/'s in the path.
    while (newPath.contains("//")) {
      newPath = newPath.replace("//", "/");
    }

    // this would remove trailing a '/' character, unless the path is empty
    // but we're not going to do this just yet..
    //		if((newPath.length() > 1) && newPath.endsWith("/")) {
    //			newPath = newPath.substring(0,newPath.length()-1);
    //		}

    StringBuilder sb = new StringBuilder(searchUrl.length());
    sb.append(searchURI.getHostBasename());

    // omit port if scheme default:
    int defaultSchemePort = UrlOperations.schemeToDefaultPort(scheme);
    if (searchURI.getPort() != defaultSchemePort && searchURI.getPort() != -1) {

      sb.append(":").append(searchURI.getPort());
    }

    sb.append(newPath);
    if (searchURI.getEscapedQuery() != null) {
      sb.append("?").append(searchURI.getEscapedQuery());
    }

    return sb.toString();
  }
Esempio n. 16
0
  private void loadobject(BufferedReader br, String pathtoimages) {
    int linecounter = 0;
    try {

      String newline;
      boolean firstpass = true;
      mtl matset = new mtl();
      int mtlcounter = 0;

      while (((newline = br.readLine()) != null)) {
        linecounter++;
        newline = newline.trim();
        if (newline.length() > 0) {
          if (newline.charAt(0) == 'n' && newline.charAt(1) == 'e' && newline.charAt(2) == 'w') {
            if (firstpass) {
              firstpass = false;
            } else {
              Materials.add(matset);
              matset = new mtl();
            }
            String[] coordstext = new String[2];
            coordstext = newline.split("\\s+");
            matset.name = coordstext[1];
            matset.mtlnum = mtlcounter;
            mtlcounter++;
          } else if (newline.charAt(0) == 'K' && newline.charAt(1) == 'a') {
            float[] coords = new float[3];
            String[] coordstext = new String[4];
            coordstext = newline.split("\\s+");
            for (int i = 1; i < coordstext.length; i++) {
              coords[i - 1] = Float.valueOf(coordstext[i]).floatValue();
            }
            matset.Ka = coords;
          } else if (newline.charAt(0) == 'K' && newline.charAt(1) == 'd') {
            float[] coords = new float[3];
            String[] coordstext = new String[4];
            coordstext = newline.split("\\s+");
            for (int i = 1; i < coordstext.length; i++) {
              coords[i - 1] = Float.valueOf(coordstext[i]).floatValue();
            }
            matset.Kd = coords;
          } else if (newline.charAt(0) == 'K' && newline.charAt(1) == 's') {
            float[] coords = new float[3];
            String[] coordstext = new String[4];
            coordstext = newline.split("\\s+");
            for (int i = 1; i < coordstext.length; i++) {
              coords[i - 1] = Float.valueOf(coordstext[i]).floatValue();
            }
            matset.Ks = coords;
          } else if (newline.charAt(0) == 'd') {
            String[] coordstext = newline.split("\\s+");
            matset.d = Float.valueOf(coordstext[1]).floatValue();
          } else if (newline.contains("map_Ka")) {
            String texture = newline.replace("map_Ka ", "");
            while (texture.startsWith(" ")) texture = texture.replaceFirst(" ", "");
            if (texture != null) matset.map_Ka = texture;
          } else if (newline.contains("map_Kd")) {
            String texture = newline.replace("map_Kd ", "");
            while (texture.startsWith(" ")) texture = texture.replaceFirst(" ", "");
            if (texture != null) matset.map_Kd = texture;
          } else if (newline.contains("map_d")) {
            String texture = newline.replace("map_d ", "");
            while (texture.startsWith(" ")) texture = texture.replaceFirst(" ", "");
            if (texture != null) matset.map_d = texture;
          }
        }
      }
      Materials.add(matset);

    } catch (IOException e) {
      System.out.println("Failed to read file: " + br.toString());
      e.printStackTrace();
    } catch (NumberFormatException e) {
      System.out.println(
          "Malformed MTL (on line "
              + linecounter
              + "): "
              + br.toString()
              + "\r \r"
              + e.getMessage());
    } catch (StringIndexOutOfBoundsException e) {
      System.out.println(
          "Malformed MTL (on line "
              + linecounter
              + "): "
              + br.toString()
              + "\r \r"
              + e.getMessage());
    }
  }
Esempio n. 17
0
  /**
   * The parser. Checks what kind of message it is, and then gives the correct data to the responder
   * for more processing.
   *
   * @param message The raw message to parse.
   * @param ipAddress The IP address of the user who sent the message.
   */
  @Override
  public void messageArrived(final String message, final String ipAddress) {
    try {
      final int exclamation = message.indexOf("!");
      final int hash = message.indexOf("#");
      final int colon = message.indexOf(":");

      final int msgCode = Integer.parseInt(message.substring(0, exclamation));
      final String type = message.substring(exclamation + 1, hash);
      final String msgNick = message.substring(hash + 1, colon);
      final String msg = message.substring(colon + 1, message.length());

      final User tempme = settings.getMe();

      if (msgCode != tempme.getCode() && loggedOn) {
        if (type.equals("MSG")) {
          final int leftBracket = msg.indexOf("[");
          final int rightBracket = msg.indexOf("]");
          final int rgb = Integer.parseInt(msg.substring(leftBracket + 1, rightBracket));

          responder.messageArrived(msgCode, msg.substring(rightBracket + 1, msg.length()), rgb);
        } else if (type.equals("LOGON")) {
          final User newUser = new User(msgNick, msgCode);
          newUser.setIpAddress(ipAddress);
          newUser.setLastIdle(System.currentTimeMillis());
          newUser.setLogonTime(System.currentTimeMillis());

          responder.userLogOn(newUser);
        } else if (type.equals("EXPOSING")) {
          final User user = new User(msgNick, msgCode);
          user.setIpAddress(ipAddress);
          user.setAwayMsg(msg);

          if (msg.length() > 0) {
            user.setAway(true);
          }

          user.setLastIdle(System.currentTimeMillis());
          user.setLogonTime(System.currentTimeMillis());

          responder.userExposing(user);
        } else if (type.equals("LOGOFF")) {
          responder.userLogOff(msgCode);
        } else if (type.equals("AWAY")) {
          responder.awayChanged(msgCode, true, msg);
        } else if (type.equals("BACK")) {
          responder.awayChanged(msgCode, false, "");
        } else if (type.equals("EXPOSE")) {
          responder.exposeRequested();
        } else if (type.equals("NICKCRASH")) {
          if (tempme.getNick().equals(msg)) {
            responder.nickCrash();
          }
        } else if (type.equals("WRITING")) {
          responder.writingChanged(msgCode, true);
        } else if (type.equals("STOPPEDWRITING")) {
          responder.writingChanged(msgCode, false);
        } else if (type.equals("GETTOPIC")) {
          responder.topicRequested();
        } else if (type.equals("TOPIC")) {
          final int leftBracket = msg.indexOf("[");
          final int rightBracket = msg.indexOf("]");
          final int leftPara = msg.indexOf("(");
          final int rightPara = msg.indexOf(")");

          if (rightBracket != -1 && leftBracket != -1) {
            final String theNick = msg.substring(leftPara + 1, rightPara);
            final long theTime = Long.parseLong(msg.substring(leftBracket + 1, rightBracket));
            String theTopic = null;

            if (msg.length() > rightBracket + 1) {
              theTopic = msg.substring(rightBracket + 1, msg.length());
            }

            responder.topicChanged(msgCode, theTopic, theNick, theTime);
          }
        } else if (type.equals("NICK")) {
          responder.nickChanged(msgCode, msgNick);
        } else if (type.equals("IDLE")) {
          responder.userIdle(msgCode, ipAddress);
        } else if (type.equals("SENDFILEACCEPT")) {
          final int leftPara = msg.indexOf("(");
          final int rightPara = msg.indexOf(")");
          final int fileCode = Integer.parseInt(msg.substring(leftPara + 1, rightPara));

          if (fileCode == tempme.getCode()) {
            final int leftCurly = msg.indexOf("{");
            final int rightCurly = msg.indexOf("}");
            final int leftBracket = msg.indexOf("[");
            final int rightBracket = msg.indexOf("]");
            final int port = Integer.parseInt(msg.substring(leftBracket + 1, rightBracket));
            final int fileHash = Integer.parseInt(msg.substring(leftCurly + 1, rightCurly));
            final String fileName = msg.substring(rightCurly + 1, msg.length());

            responder.fileSendAccepted(msgCode, fileName, fileHash, port);
          }
        } else if (type.equals("SENDFILEABORT")) {
          final int leftPara = msg.indexOf("(");
          final int rightPara = msg.indexOf(")");
          final int fileCode = Integer.parseInt(msg.substring(leftPara + 1, rightPara));

          if (fileCode == tempme.getCode()) {
            final int leftCurly = msg.indexOf("{");
            final int rightCurly = msg.indexOf("}");
            final String fileName = msg.substring(rightCurly + 1, msg.length());
            final int fileHash = Integer.parseInt(msg.substring(leftCurly + 1, rightCurly));

            responder.fileSendAborted(msgCode, fileName, fileHash);
          }
        } else if (type.equals("SENDFILE")) {
          final int leftPara = msg.indexOf("(");
          final int rightPara = msg.indexOf(")");
          final int fileCode = Integer.parseInt(msg.substring(leftPara + 1, rightPara));

          if (fileCode == tempme.getCode()) {
            final int leftCurly = msg.indexOf("{");
            final int rightCurly = msg.indexOf("}");
            final int leftBracket = msg.indexOf("[");
            final int rightBracket = msg.indexOf("]");
            final long byteSize = Long.parseLong(msg.substring(leftBracket + 1, rightBracket));
            final String fileName = msg.substring(rightCurly + 1, msg.length());
            final int fileHash = Integer.parseInt(msg.substring(leftCurly + 1, rightCurly));

            responder.fileSend(msgCode, byteSize, fileName, msgNick, fileHash);
          }
        } else if (type.equals("CLIENT")) {
          final int leftPara = msg.indexOf("(");
          final int rightPara = msg.indexOf(")");
          final int leftBracket = msg.indexOf("[");
          final int rightBracket = msg.indexOf("]");
          final int leftCurly = msg.indexOf("{");
          final int rightCurly = msg.indexOf("}");
          final int lessThan = msg.indexOf("<");
          final int greaterThan = msg.indexOf(">");

          final String client = msg.substring(leftPara + 1, rightPara);
          final long timeSinceLogon = Long.parseLong(msg.substring(leftBracket + 1, rightBracket));
          final String operatingSystem = msg.substring(leftCurly + 1, rightCurly);

          int privateChatPort = 0;

          try {
            privateChatPort = Integer.parseInt(msg.substring(lessThan + 1, greaterThan));
          } catch (final NumberFormatException e) {
            LOG.log(Level.WARNING, e.toString());
          }

          responder.clientInfo(msgCode, client, timeSinceLogon, operatingSystem, privateChatPort);
        }
      } else if (msgCode == tempme.getCode() && type.equals("LOGON")) {
        responder.meLogOn(ipAddress);
        loggedOn = true;
      } else if (msgCode == tempme.getCode() && type.equals("IDLE") && loggedOn) {
        responder.meIdle(ipAddress);
      }
    } catch (final StringIndexOutOfBoundsException e) {
      LOG.log(Level.SEVERE, e.toString(), e);
    } catch (final NumberFormatException e) {
      LOG.log(Level.SEVERE, e.toString(), e);
    }
  }
Esempio n. 18
0
  @SuppressWarnings("unused")
  @Override
  public void onDraw(Canvas canvas) {
    Rect frame = cameraManager.getFramingRect();
    if (frame == null) {
      return;
    }
    int width = canvas.getWidth();
    int height = canvas.getHeight();

    // Draw the exterior (i.e. outside the framing rect) darkened
    paint.setColor(maskColor);
    canvas.drawRect(0, 0, width, frame.top, paint);
    canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
    canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint);
    canvas.drawRect(0, frame.bottom + 1, width, height, paint);

    // If we have an OCR result, overlay its information on the viewfinder.
    if (resultText != null) {

      // Only draw text/bounding boxes on viewfinder if it hasn't been resized since the OCR was
      // requested.
      Point bitmapSize = resultText.getBitmapDimensions();
      previewFrame = cameraManager.getFramingRectInPreview();
      if (bitmapSize.x == previewFrame.width() && bitmapSize.y == previewFrame.height()) {

        float scaleX = frame.width() / (float) previewFrame.width();
        float scaleY = frame.height() / (float) previewFrame.height();

        if (DRAW_REGION_BOXES) {
          regionBoundingBoxes = resultText.getRegionBoundingBoxes();
          for (int i = 0; i < regionBoundingBoxes.size(); i++) {
            paint.setAlpha(0xA0);
            paint.setColor(Color.MAGENTA);
            paint.setStyle(Style.STROKE);
            paint.setStrokeWidth(1);
            rect = regionBoundingBoxes.get(i);
            canvas.drawRect(
                frame.left + rect.left * scaleX,
                frame.top + rect.top * scaleY,
                frame.left + rect.right * scaleX,
                frame.top + rect.bottom * scaleY,
                paint);
          }
        }

        if (DRAW_TEXTLINE_BOXES) {
          // Draw each textline
          textlineBoundingBoxes = resultText.getTextlineBoundingBoxes();
          paint.setAlpha(0xA0);
          paint.setColor(Color.RED);
          paint.setStyle(Style.STROKE);
          paint.setStrokeWidth(1);
          for (int i = 0; i < textlineBoundingBoxes.size(); i++) {
            rect = textlineBoundingBoxes.get(i);
            canvas.drawRect(
                frame.left + rect.left * scaleX,
                frame.top + rect.top * scaleY,
                frame.left + rect.right * scaleX,
                frame.top + rect.bottom * scaleY,
                paint);
          }
        }

        if (DRAW_STRIP_BOXES) {
          stripBoundingBoxes = resultText.getStripBoundingBoxes();
          paint.setAlpha(0xFF);
          paint.setColor(Color.YELLOW);
          paint.setStyle(Style.STROKE);
          paint.setStrokeWidth(1);
          for (int i = 0; i < stripBoundingBoxes.size(); i++) {
            rect = stripBoundingBoxes.get(i);
            canvas.drawRect(
                frame.left + rect.left * scaleX,
                frame.top + rect.top * scaleY,
                frame.left + rect.right * scaleX,
                frame.top + rect.bottom * scaleY,
                paint);
          }
        }

        if (DRAW_WORD_BOXES || DRAW_WORD_TEXT) {
          // Split the text into words
          wordBoundingBoxes = resultText.getWordBoundingBoxes();
          //      for (String w : words) {
          //        Log.e("ViewfinderView", "word: " + w);
          //      }
          // Log.d("ViewfinderView", "There are " + words.length + " words in the string array.");
          // Log.d("ViewfinderView", "There are " + wordBoundingBoxes.size() + " words with bounding
          // boxes.");
        }

        if (DRAW_WORD_BOXES) {
          paint.setAlpha(0xFF);
          paint.setColor(0xFF00CCFF);
          paint.setStyle(Style.STROKE);
          paint.setStrokeWidth(1);
          for (int i = 0; i < wordBoundingBoxes.size(); i++) {
            // Draw a bounding box around the word
            rect = wordBoundingBoxes.get(i);
            canvas.drawRect(
                frame.left + rect.left * scaleX,
                frame.top + rect.top * scaleY,
                frame.left + rect.right * scaleX,
                frame.top + rect.bottom * scaleY,
                paint);
          }
        }

        if (DRAW_WORD_TEXT) {
          words = resultText.getText().replace("\n", " ").split(" ");
          int[] wordConfidences = resultText.getWordConfidences();
          for (int i = 0; i < wordBoundingBoxes.size(); i++) {
            boolean isWordBlank = true;
            try {
              if (!words[i].equals("")) {
                isWordBlank = false;
              }
            } catch (ArrayIndexOutOfBoundsException e) {
              e.printStackTrace();
            }

            // Only draw if word has characters
            if (!isWordBlank) {
              // Draw a white background around each word
              rect = wordBoundingBoxes.get(i);
              paint.setColor(Color.WHITE);
              paint.setStyle(Style.FILL);
              if (DRAW_TRANSPARENT_WORD_BACKGROUNDS) {
                // Higher confidence = more opaque, less transparent background
                paint.setAlpha(wordConfidences[i] * 255 / 100);
              } else {
                paint.setAlpha(255);
              }
              canvas.drawRect(
                  frame.left + rect.left * scaleX,
                  frame.top + rect.top * scaleY,
                  frame.left + rect.right * scaleX,
                  frame.top + rect.bottom * scaleY,
                  paint);

              // Draw the word in black text
              paint.setColor(Color.BLACK);
              paint.setAlpha(0xFF);
              paint.setAntiAlias(true);
              paint.setTextAlign(Align.LEFT);

              // Adjust text size to fill rect
              paint.setTextSize(100);
              paint.setTextScaleX(1.0f);
              // ask the paint for the bounding rect if it were to draw this text
              Rect bounds = new Rect();
              paint.getTextBounds(words[i], 0, words[i].length(), bounds);
              // get the height that would have been produced
              int h = bounds.bottom - bounds.top;
              // figure out what textSize setting would create that height of text
              float size = (((float) (rect.height()) / h) * 100f);
              // and set it into the paint
              paint.setTextSize(size);
              // Now set the scale.
              // do calculation with scale of 1.0 (no scale)
              paint.setTextScaleX(1.0f);
              // ask the paint for the bounding rect if it were to draw this text.
              paint.getTextBounds(words[i], 0, words[i].length(), bounds);
              // determine the width
              int w = bounds.right - bounds.left;
              // calculate the baseline to use so that the entire text is visible including the
              // descenders
              int text_h = bounds.bottom - bounds.top;
              int baseline = bounds.bottom + ((rect.height() - text_h) / 2);
              // determine how much to scale the width to fit the view
              float xscale = ((float) (rect.width())) / w;
              // set the scale for the text paint
              paint.setTextScaleX(xscale);
              canvas.drawText(
                  words[i],
                  frame.left + rect.left * scaleX,
                  frame.top + rect.bottom * scaleY - baseline,
                  paint);
            }
          }
        }

        if (DRAW_CHARACTER_BOXES || DRAW_CHARACTER_TEXT) {
          characterBoundingBoxes = resultText.getCharacterBoundingBoxes();
        }

        if (DRAW_CHARACTER_BOXES) {
          // Draw bounding boxes around each character
          paint.setAlpha(0xA0);
          paint.setColor(0xFF00FF00);
          paint.setStyle(Style.STROKE);
          paint.setStrokeWidth(1);
          for (int c = 0; c < characterBoundingBoxes.size(); c++) {
            Rect characterRect = characterBoundingBoxes.get(c);
            canvas.drawRect(
                frame.left + characterRect.left * scaleX,
                frame.top + characterRect.top * scaleY,
                frame.left + characterRect.right * scaleX,
                frame.top + characterRect.bottom * scaleY,
                paint);
          }
        }

        if (DRAW_CHARACTER_TEXT) {
          // Draw letters individually
          for (int i = 0; i < characterBoundingBoxes.size(); i++) {
            Rect r = characterBoundingBoxes.get(i);

            // Draw a white background for every letter
            int meanConfidence = resultText.getMeanConfidence();
            paint.setColor(Color.WHITE);
            paint.setAlpha(meanConfidence * (255 / 100));
            paint.setStyle(Style.FILL);
            canvas.drawRect(
                frame.left + r.left * scaleX,
                frame.top + r.top * scaleY,
                frame.left + r.right * scaleX,
                frame.top + r.bottom * scaleY,
                paint);

            // Draw each letter, in black
            paint.setColor(Color.BLACK);
            paint.setAlpha(0xFF);
            paint.setAntiAlias(true);
            paint.setTextAlign(Align.LEFT);
            String letter = "";
            try {
              char c = resultText.getText().replace("\n", "").replace(" ", "").charAt(i);
              letter = Character.toString(c);

              if (!letter.equals("-") && !letter.equals("_")) {

                // Adjust text size to fill rect
                paint.setTextSize(100);
                paint.setTextScaleX(1.0f);

                // ask the paint for the bounding rect if it were to draw this text
                Rect bounds = new Rect();
                paint.getTextBounds(letter, 0, letter.length(), bounds);

                // get the height that would have been produced
                int h = bounds.bottom - bounds.top;

                // figure out what textSize setting would create that height of text
                float size = (((float) (r.height()) / h) * 100f);

                // and set it into the paint
                paint.setTextSize(size);

                // Draw the text as is. We don't really need to set the text scale, because the
                // dimensions
                // of the Rect should already be suited for drawing our letter.
                canvas.drawText(
                    letter, frame.left + r.left * scaleX, frame.top + r.bottom * scaleY, paint);
              }
            } catch (StringIndexOutOfBoundsException e) {
              e.printStackTrace();
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        }
      }
    }
    // Draw a two pixel solid border inside the framing rect
    paint.setAlpha(0);
    paint.setStyle(Style.FILL);
    paint.setColor(frameColor);
    canvas.drawRect(frame.left, frame.top, frame.right + 1, frame.top + 2, paint);
    canvas.drawRect(frame.left, frame.top + 2, frame.left + 2, frame.bottom - 1, paint);
    canvas.drawRect(frame.right - 1, frame.top, frame.right + 1, frame.bottom - 1, paint);
    canvas.drawRect(frame.left, frame.bottom - 1, frame.right + 1, frame.bottom + 1, paint);

    // Draw the framing rect corner UI elements
    paint.setColor(cornerColor);
    //    canvas.drawRect(frame.left - 15, frame.top - 15, frame.left + 15, frame.top, paint);
    //    canvas.drawRect(frame.left - 15, frame.top, frame.left, frame.top + 15, paint);
    //    canvas.drawRect(frame.right - 15, frame.top - 15, frame.right + 15, frame.top, paint);
    //    canvas.drawRect(frame.right, frame.top - 15, frame.right + 15, frame.top + 15, paint);
    //    canvas.drawRect(frame.left - 15, frame.bottom, frame.left + 15, frame.bottom + 15, paint);
    //    canvas.drawRect(frame.left - 15, frame.bottom - 15, frame.left, frame.bottom, paint);
    //    canvas.drawRect(frame.right - 15, frame.bottom, frame.right + 15, frame.bottom + 15,
    // paint);
    //    canvas.drawRect(frame.right, frame.bottom - 15, frame.right + 15, frame.bottom + 15,
    // paint);

    // Request another update at the animation interval, but don't repaint the entire viewfinder
    // mask.
    // postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top, frame.right, frame.bottom);
  }
Esempio n. 19
0
 /**
  * This is the method which will upload the properties file into Cache and will bind cache to
  * POJO. This method will share a lock and condition object with ReturnMapValue method to avoid
  * concurrent access to HashMap. Following precautions has been taken to avoid concurrent HashMap
  * access problem: ConcurrentHashMap has been choosen. UnmodifiableHashMap has been returned to
  * caller so that other party doesn't modify it.
  */
 void loadPropertiesFile()
     throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
   this.priorityFlag = true;
   updateLock.lock();
   logger.debug("UPDATE HAS THE LOCK");
   try {
     logger.debug("Loading the properties file");
     for (FolderEvent event : eventQueue) {
       logger.debug("Event size " + eventQueue.size());
       switch (event) {
         case LOAD:
           {
             for (String name : load) {
               try {
                 String className = name.substring(0, name.indexOf(".")).concat("Handler");
                 PropHandler handler = null;
                 if (propMap.get(name) == null) {
                   // ----MEANS This is the first time.
                   try {
                     handler =
                         (PropHandler) Class.forName("com.GR.handler." + className).newInstance();
                     handler.loadPropertiesFile(location + File.separator + name);
                     handler.initialize();
                     handler.addToSession(propMap);
                     beanPropHandlerMap.put(propMap.get(name), handler);
                   } catch (ClassNotFoundException e) {
                     logger.info(
                         "No Handler/Bean has been defined for the ["
                             + name
                             + "] properties file");
                     logger.error("IGNORE -->" + e.getMessage());
                   }
                 } else {
                   handler = beanPropHandlerMap.get(propMap.get(name));
                   handler.loadPropertiesFile(location + File.separator + name);
                   handler.initialize();
                   handler.addToSession(propMap);
                 }
               } catch (StringIndexOutOfBoundsException e) {
                 logger.info(name + " doesn't seem to be a valid property file name");
                 logger.error("IGNORE -->" + e.getMessage());
               }
             } // End of For Loop for Load Class
             break;
           }
         case UNLOAD:
           {
             for (String name : unload) {
               propMap.remove(name);
             }
             break;
           }
       }
     }
     // -------------------CLEAR THE QUEUES--------------
     eventQueue.clear();
     load.clear();
     unload.clear();
     isRefreshed = true;
   } finally {
     // -----------------NOTIFY the returnMapValue-----------
     this.priorityFlag = false;
     loadCondition.signal();
     updateLock.unlock();
     logger.info("Files uploaded into Cache");
     logger.debug("UPDATE RELEASED THE LOCK");
   }
 }
  @Override
  public List<AndroidMethod> parse() throws IOException {
    BufferedReader rdr = null;
    List<AndroidMethod> resList = new ArrayList<AndroidMethod>();
    try {
      rdr = new BufferedReader(new FileReader(this.fileName));
      String line = null;
      boolean firstLine = true;
      while ((line = rdr.readLine()) != null) {
        // Ignore the first line which is a header
        if (firstLine) {
          firstLine = false;
          continue;
        }
        firstLine = false;

        // Get the CSV fields
        String[] fields = line.split("\t");
        if (fields.length < 1) {
          System.err.println("Found invalid line: " + line);
          continue;
        }

        // Parse the method signature
        String methodName;
        String className;
        List<String> methodParams = new ArrayList<String>();
        Set<String> permissions = new HashSet<String>();
        try {
          if (fields[0].contains(")")) methodName = fields[0].substring(0, fields[0].indexOf("("));
          else methodName = fields[0];
          className = methodName.substring(0, methodName.lastIndexOf("."));
          methodName = methodName.substring(methodName.lastIndexOf(".") + 1);

          // Parse the parameters
          if (fields[0].contains("(")) {
            String parameters = fields[0].substring(fields[0].indexOf("(") + 1);
            parameters = parameters.substring(0, parameters.indexOf(")"));
            for (String p : parameters.split(",")) methodParams.add(p);
          }

          String perm = (fields.length > 1) ? fields[1] : "";
          perm = perm.replaceAll(" and ", " ");
          perm = perm.replaceAll(" or ", " ");
          if (perm.contains(".")) perm = perm.substring(perm.lastIndexOf(".") + 1);
          for (String p : perm.split(" ")) permissions.add(p);
        } catch (StringIndexOutOfBoundsException ex) {
          System.err.println("Could not parse line: " + line);
          ex.printStackTrace();
          continue;
        }

        AndroidMethod method =
            new AndroidMethod(methodName, methodParams, "", className, permissions);
        resList.add(method);
      }

    } finally {
      if (rdr != null) rdr.close();
    }
    return resList;
  }
 protected String extractClassificationNameFromOption(boolean check) {
   if (_extracted) {
     return _specifiedValue;
   }
   _extracted = true;
   final String pmbMetaDataPropertyOption = getPmbMetaDataPropertyOption();
   if (pmbMetaDataPropertyOption == null) {
     if (check) {
       String msg = "The property name didn't have its option:";
       msg = msg + " " + _pmbMetaData.getClassName() + "." + _propertyName;
       throw new IllegalStateException(msg);
     } else {
       return null;
     }
   }
   String option = pmbMetaDataPropertyOption.trim();
   {
     if (option.trim().length() == 0) {
       if (check) {
         String msg = "The option of the property name should not be empty:";
         msg = msg + " property=" + _pmbMetaData.getClassName() + "." + _propertyName;
         throw new IllegalStateException(msg);
       } else {
         return null;
       }
     }
     final List<String> splitOption = splitOption(option);
     String firstOption = null;
     for (String element : splitOption) {
       if (element.startsWith(OPTION_PREFIX) && element.endsWith(OPTION_SUFFIX)) {
         firstOption = element;
         break;
       }
     }
     if (firstOption == null) {
       if (check) {
         String msg = "The option of class name and the property name should be 'cls(xxx)':";
         msg =
             msg + " property=" + _pmbMetaData.getClassName() + "." + _propertyName + ":" + option;
         throw new IllegalStateException(msg);
       } else {
         return null;
       }
     }
     option = firstOption;
   }
   final int clsIdx = OPTION_PREFIX.length();
   final int clsEndIdx = option.length() - OPTION_SUFFIX.length();
   try {
     _specifiedValue = option.substring(clsIdx, clsEndIdx);
   } catch (StringIndexOutOfBoundsException e) {
     final ExceptionMessageBuilder br = new ExceptionMessageBuilder();
     br.addNotice("The classification option for the parameter comment was invalid.");
     br.addItem("ParameterBean");
     br.addElement(_pmbMetaData.getClassName());
     br.addItem("Property");
     br.addElement(_propertyName);
     br.addItem("Option");
     br.addElement(option);
     br.addItem("Exception");
     br.addElement(e.getClass());
     br.addElement(e.getMessage());
     br.addElement("{" + option + "}.substring(" + clsIdx + ", " + clsEndIdx + ")");
     final String msg = br.buildExceptionMessage();
     throw new IllegalStateException(msg, e);
   }
   return _specifiedValue;
 }
  /**
   * Operates on the invariant that for any sorted hand, if the 1st card is not a club, there are no
   * clubs in the hand, if the 2nd card is not a diamond there are no diamonds, etc. This allows
   * in-place char replacements (i.e. without swapping a->temp, b->a, temp->b). All hands are sorted
   * in their constructors
   *
   * @return a hand string suited to match the database's hand-saving hash of
   *     clubs->diamonds->hearts->spades
   */
  @SuppressWarnings("serial")
  public String toDatabaseString() {
    System.out.println("toDatabaseString() input: " + this.toString());
    ArrayList<Character> suits =
        new ArrayList<Character>() {
          {
            add('c');
            add('d');
            add('h');
            add('s');
          }
        };
    String ans = new String(this.toString());
    int counter = 0;
    ArrayList<Card> seen = new ArrayList<Card>();

    Card max = getMaxValueCard();
    //		seen.add(max);
    ans = ans.replace(max.getSuit().charAt(0), ' ');
    ans = ans.replace(suits.get(counter), max.getSuit().charAt(0));
    ans = ans.replace(' ', suits.get(counter));
    seen.add(new Card(max.getRank().charAt(0), suits.get(counter)));
    counter++;
    if (new Hand(ans).getMaxValueCard(seen) != null
        && new Hand(ans).getMaxValueCard(seen).getSuit().charAt(0)
            != seen.get(seen.size() - 1).getSuit().charAt(0)) {
      max = new Hand(ans).getMaxValueCard(seen);
      //			seen.add(max);
      while (suits.indexOf(max.getSuit().charAt(0)) < counter) {
        seen.add(max);
        max = new Hand(ans).getMaxValueCard(seen);
        //				seen.add(max);
        if (max == null) {
          ans = new Hand(ans).toString();
          return ans;
        }
      }
      ans = ans.replace(max.getSuit().charAt(0), ' ');
      ans = ans.replace(suits.get(counter), max.getSuit().charAt(0));
      ans = ans.replace(' ', suits.get(counter));
      seen.add(new Card(max.getRank().charAt(0), suits.get(counter)));
      counter++;
    } else {
      max = new Hand(ans).getMaxValueCard(seen);
      seen.add(max);
      if (max == null) {
        ans = new Hand(ans).toString();
        return ans;
      }
    }

    if (new Hand(ans).getMaxValueCard(seen) != null
        && new Hand(ans).getMaxValueCard(seen).getSuit().charAt(0)
            != seen.get(seen.size() - 1).getSuit().charAt(0)) {
      max = new Hand(ans).getMaxValueCard(seen);
      //			seen.add(max);

      while (suits.indexOf(max.getSuit().charAt(0)) < counter) {
        seen.add(max);
        max = new Hand(ans).getMaxValueCard(seen);
        //				seen.add(max);
        if (max == null) {
          ans = new Hand(ans).toString();
          return ans;
        }
      }
      ans = ans.replace(max.getSuit().charAt(0), ' ');
      ans = ans.replace(suits.get(counter), max.getSuit().charAt(0));
      ans = ans.replace(' ', suits.get(counter));
      seen.add(new Card(max.getRank().charAt(0), suits.get(counter)));
      counter++;
    } else {
      max = new Hand(ans).getMaxValueCard(seen);
      seen.add(max);
      if (max == null) {
        ans = new Hand(ans).toString();
        return ans;
      }
    }

    ans = new Hand(ans).toString();
    System.out.println("Intermediary: " + ans);
    int suitTracker = 1;
    while (suitTracker < numDifferentSuits()) {
      boolean temp = true;
      for (int i = 1; i < ans.length(); i += 2) {
        if (ans.charAt(i) == suits.get(suitTracker)) {
          temp = false;
        }
      }
      if (temp) {
        int last_index = -1;
        for (int j = 1; j < ans.length(); j += 2) {
          if (ans.charAt(j) == suits.get(suitTracker - 1)) {
            last_index = j;
          }
        }
        try {
          ans = ans.replace(ans.charAt(last_index + 2), suits.get(suitTracker));
        } catch (StringIndexOutOfBoundsException e) {
          e.printStackTrace();
        }
      }
      suitTracker++;
    }
    ans = new Hand(ans).toString();
    System.out.println("Intermediary2: " + ans);

    int max_flush = 0;
    char max_suit = ' ';
    for (char c : suits) {
      if (max_flush < get_num_suit(ans, c)) {
        max_flush = Math.max(max_flush, c);
        max_suit = c;
      }
    }
    ans = ans.replace(max_suit, ' ');
    ans = ans.replace('c', max_suit);
    ans = ans.replace(' ', 'c');

    ans = new Hand(ans).toString();
    System.out.println("Returning: " + ans);
    return ans;
  }