@Test
  public void testJavaScript() throws IOException, ImporterHandlerException {

    String script =
        "metadata.addString('test', 'success');"
            + "text = content.replace(/Alice/g, 'Roger');"
            + "/*return*/ text;";

    ScriptTransformer t = new ScriptTransformer();
    t.setScript(script);

    File htmlFile = TestUtil.getAliceHtmlFile();
    FileInputStream is = new FileInputStream(htmlFile);

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    ImporterMetadata metadata = new ImporterMetadata();
    metadata.setString(ImporterMetadata.DOC_CONTENT_TYPE, "text/html");
    t.transformDocument(htmlFile.getAbsolutePath(), is, out, metadata, false);

    is.close();

    String successField = metadata.getString("test");

    Assert.assertEquals("success", successField);
    String content = new String(out.toString());

    Assert.assertEquals(0, StringUtils.countMatches(content, "Alice"));
    Assert.assertEquals(34, StringUtils.countMatches(content, "Roger"));
  }
  @Test
  public void testTaskLogOutByTag() throws Exception {
    HttpResponse response = sendRequest("jobs/" + jobId + "/tasks/tag/LOOP-T2-1/result/log/out");
    String responseContent = getContent(response);

    System.out.println(responseContent);

    assertEquals(2, StringUtils.countMatches(responseContent, "Task 1 : Test STDOUT"));
    assertEquals(2, StringUtils.countMatches(responseContent, "Terminate task number 1"));
  }
  protected void validateAttendees(Meeting m) {
    // some defensive code:
    int semicolonCount = StringUtils.countMatches(m.getAttendees(), ";");
    int atSymbolCount = StringUtils.countMatches(m.getAttendees(), "@");

    if (semicolonCount != (atSymbolCount - 1)) {
      logger.severe("Attendees is poorly formatted: " + m.getAttendees());
      throw new RuntimeException("The email addresses are poorly formatted");
    }
  }
示例#4
0
 private void searchFilefind(File file) {
   if (!file.exists()) {
     return;
   }
   if (file.isDirectory() && file.listFiles() != null) {
     for (File f : file.listFiles()) {
       searchFilefind(f);
     }
     if (rootFile == file) {
       return;
     }
     if (StringUtils.countMatches(file.getAbsolutePath(), "\\") <= dirLayerLimit) {
       System.out.println(file);
       try {
         long mb = (FileUtils.sizeOfDirectory(file) / (1024 * 1024));
         if (mb > 10) {
           System.out.println(file + "\t" + mb + "mb");
           writer.writeLine("\"" + file + "\",\"" + mb + "\"");
         }
       } catch (Exception ex) {
         ex.printStackTrace();
       }
     }
   } else {
     // file
   }
 }
示例#5
0
 @Override
 public int currentLine() {
   if (null == template) return -1; // for testing purpose only
   if (cursor >= template.length()) return totalLines;
   // return template.substring(0, cursor).split("(\\r\\n|\\n|\\r)").length;
   return StringUtils.countMatches(template.substring(0, cursor), "\n") + 1;
 }
示例#6
0
  public static void handle(final UtdFile file) {
    if (checkValidity(file)) {
      int loops = StringUtils.countMatches(file.getContent(), "::BEGINLOOP");

      while (loops > 0) {
        replaceLastLoop(file, loops);
        loops--;
      }
    } else {
      System.out.println("Loop structure not valid");
    }
  }
示例#7
0
  /** A helper here where the junit test can assert success */
  protected AbstractPlanNode compileForSinglePartition(String sql) {
    // Yes, we ARE assuming that test queries don't contain quoted question marks.
    int paramCount = StringUtils.countMatches(sql, "?");
    boolean m_infer = m_byDefaultInferPartitioning;
    boolean m_forceSP = m_byDefaultInferPartitioning;
    m_byDefaultInferPartitioning = false;
    m_byDefaultPlanForSinglePartition = true;

    AbstractPlanNode pn = compileSPWithJoinOrder(sql, paramCount, null);
    m_byDefaultInferPartitioning = m_infer;
    m_byDefaultPlanForSinglePartition = m_forceSP;
    return pn;
  }
  @Test(groups = {"webserviceSmoke"})
  public void testRequisitionStatusUsingCommTrackUserForExportOrderFlagFalse()
      throws IOException, SQLException, ParserConfigurationException, SAXException {
    HttpClient client = new HttpClient();
    client.createContext();
    submitRnRThroughApi("V10", "HIV", "P10", 1, 10, 1, 0, 0, 2);
    Long id = (long) dbWrapper.getMaxRnrID();

    ResponseEntity responseEntity = client.SendJSON("", URL + "recent", "GET", "", "");
    assertEquals(200, responseEntity.getStatus());
    assertEquals(StringUtils.countMatches(responseEntity.getResponse(), ":"), 41);
    List<String> feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content");
    checkRequisitionStatusOnFeed("INITIATED", feedJSONList.get(0), id);
    checkRequisitionStatusOnFeed("SUBMITTED", feedJSONList.get(1), id);
    checkRequisitionStatusOnFeed("AUTHORIZED", feedJSONList.get(2), id);

    dbWrapper.setExportOrdersFlagInSupplyLinesTable(false, "F10");

    approveRequisition(id, 65);
    dbWrapper.updateRestrictLogin("commTrack", false);
    convertToOrder("commTrack", "Admin123");
    dbWrapper.updateRestrictLogin("commTrack", true);
    responseEntity = client.SendJSON("", URL + "1", "GET", "", "");
    assertEquals(200, responseEntity.getStatus());

    feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content");
    checkRequisitionStatusOnFeed("APPROVED", feedJSONList.get(3), id);
    checkRequisitionStatusOnFeed("RELEASED", feedJSONList.get(4), id);

    responseEntity = client.SendJSON("", URL + "recent", "GET", "", "");
    assertEquals(200, responseEntity.getStatus());
    feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content");
    checkOrderStatusOnFeed("READY_TO_PACK", feedJSONList.get(0), id);

    dbWrapper.assignRight("store in-charge", "MANAGE_POD");

    OrderPOD OrderPODFromJson =
        JsonUtility.readObjectFromFile(FULL_JSON_POD_TXT_FILE_NAME, OrderPOD.class);
    OrderPODFromJson.getPodLineItems().get(0).setQuantityReceived(65);
    OrderPODFromJson.getPodLineItems().get(0).setProductCode("P10");

    client.SendJSON(
        getJsonStringFor(OrderPODFromJson), format(POD_URL, id), "POST", "commTrack", "Admin123");

    responseEntity = client.SendJSON("", URL + "recent", "GET", "", "");
    assertEquals(200, responseEntity.getStatus());
    feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content");
    checkOrderStatusOnFeed("RECEIVED", feedJSONList.get(1), id);
  }
示例#9
0
 static Date parseDate(String inputUntrimmed) throws ParseException {
   String input = inputUntrimmed.trim();
   // remove milliseconds to reduce number of needed patterns
   final MatcherWrapper matcher = new MatcherWrapper(PATTERN_MILLISECONDS, input);
   input = matcher.replaceFirst("");
   if (input.contains("Z")) {
     return formatSimpleZ.parse(input);
   }
   if (StringUtils.countMatches(input, ":") == 3) {
     final String removeColon =
         input.substring(0, input.length() - 3) + input.substring(input.length() - 2);
     return formatTimezone.parse(removeColon);
   }
   return formatSimple.parse(input);
 }
示例#10
0
 @Override
 protected String Compile() throws IOException, ValidateException {
   Process process = Runtime.getRuntime().exec("javac " + workpath + "Main.java");
   BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()));
   String s = null;
   String res = "";
   while ((s = br.readLine()) != null) {
     res += s + "\n";
     System.out.println("编译-命令----" + s);
   }
   if (StringUtils.countMatches(res, "\n") > 1) {
     throw new ValidateException("编译错误" + res);
   }
   return res;
 }
  public void populatefilelist(String fpath) {

    tfile = new File(fpath);
    File[] tfileArr = tfile.listFiles();
    int tlength = tfileArr.length;
    for (int i = 0; i < tlength; i++) {
      File tf = tfileArr[i];
      String filetype;
      if (tf.isDirectory()) {
        filetype = "directory";
        // flLst.add(tf.getName());
        int count = StringUtils.countMatches(tf.getAbsolutePath(), "/");
        /* Toast.makeText(getApplicationContext(), "/ count=" + count,
        Toast.LENGTH_LONG).show();*/
        if (count < (dircount + 3)) populatefilelist(tf.getAbsolutePath());
      } else filetype = "file";
      /*Toast.makeText(getApplicationContext(),"filename="+ tf.getName()+"filetype="+filetype+"getabspath="+tf.getAbsolutePath(),
      Toast.LENGTH_LONG).show();*/
      if (tf.getName().contains(".JPEG")
          || tf.getName().contains(".jpeg")
          || tf.getName().contains(".png")
          || tf.getName().contains(".PNG")
          || tf.getName().contains(".JPG")
          || tf.getName().contains(".jpg")
          || tf.getName().contains(".bmp")
          || tf.getName().contains(".BMP")
          || tf.getName().contains(".GIF")
          || tf.getName().contains(".gif")
          || tf.getName().contains(".mp4")
          || tf.getName().contains(".MP4")) {

        /*Toast.makeText(getApplicationContext(), "/ createdtime=" + tf.lastModified(),
        Toast.LENGTH_LONG).show();*/

        if (!Arrays.asList(fnamelLst).contains(tf.getName())) {
          flLst.add(tf.getAbsolutePath());
          // filecreatdtimelist.add(tf.lastModified());
          fnamelLst.add(tf.getName());
        }
      }
    }
  }
示例#12
0
 private void calcLayerLimit() {
   dirLayerLimit = StringUtils.countMatches(rootFile.getAbsolutePath(), "\\") + 3;
 }
示例#13
0
 /** A helper here where the junit test can assert success */
 protected AbstractPlanNode compile(String sql) {
   // Yes, we ARE assuming that test queries don't contain quoted question marks.
   int paramCount = StringUtils.countMatches(sql, "?");
   return compileSPWithJoinOrder(sql, paramCount, null);
 }
示例#14
0
 private AbstractPlanNode compileWithCountedParamsAndJoinOrder(String sql, String joinOrder)
     throws Exception {
   // Yes, we ARE assuming that test queries don't contain quoted question marks.
   int paramCount = StringUtils.countMatches(sql, "?");
   return compileSPWithJoinOrder(sql, paramCount, joinOrder);
 }
示例#15
0
 /** A helper here where the junit test can assert success */
 private List<AbstractPlanNode> compileWithJoinOrderToFragments(
     String sql, boolean planForSinglePartition, String joinOrder) {
   // Yes, we ARE assuming that test queries don't contain quoted question marks.
   int paramCount = StringUtils.countMatches(sql, "?");
   return compileWithJoinOrderToFragments(sql, paramCount, planForSinglePartition, joinOrder);
 }
示例#16
0
  VoltTable runSQLWithSubstitutions(
      final SQLStmt stmt, ParameterSet params, byte[] paramJavaTypes) {
    // HSQLProcedureWrapper does nothing smart. it just implements this interface with
    // runStatement()
    StringBuilder sqlOut = new StringBuilder(stmt.getText().length() * 2);

    assert (paramJavaTypes != null);

    int lastIndex = 0;
    String sql = stmt.getText();

    // if there's no ? in the statmemt, then zero out any auto-parameterization
    int paramCount = StringUtils.countMatches(sql, "?");
    if (paramCount == 0) {
      params = ParameterSet.emptyParameterSet();
      paramJavaTypes = new byte[0];
    }

    Object[] paramObjs = params.toArray();
    for (int i = 0; i < paramObjs.length; i++) {
      int nextIndex = sql.indexOf('?', lastIndex);
      if (nextIndex == -1)
        throw new RuntimeException("SQL Statement has more arguments than params.");
      sqlOut.append(sql, lastIndex, nextIndex);
      lastIndex = nextIndex + 1;

      VoltType type = VoltType.get(paramJavaTypes[i]);

      if (VoltType.isNullVoltType(paramObjs[i])) {
        sqlOut.append("NULL");
      } else if (paramObjs[i] instanceof TimestampType) {
        if (type != VoltType.TIMESTAMP)
          throw new RuntimeException("Inserting date into mismatched column type in HSQL.");
        TimestampType d = (TimestampType) paramObjs[i];
        // convert VoltDB's microsecond granularity to millis.
        Timestamp t = new Timestamp(d.getTime() / 1000);
        sqlOut.append('\'').append(t.toString()).append('\'');
      } else if (paramObjs[i] instanceof byte[]) {
        if (type == VoltType.STRING) {
          // Convert from byte[] -> String; escape single quotes
          try {
            sqlOut.append(sqlEscape(new String((byte[]) paramObjs[i], "UTF-8")));
          } catch (UnsupportedEncodingException e) {
            // should NEVER HAPPEN
            System.err.println("FATAL: Your JVM doens't support UTF-&");
            System.exit(-1);
          }
        } else if (type == VoltType.VARBINARY) {
          // Convert from byte[] -> String; using hex
          sqlOut.append(sqlEscape(Encoder.hexEncode((byte[]) paramObjs[i])));
        } else {
          throw new RuntimeException(
              "Inserting string/varbinary (bytes) into mismatched column type in HSQL.");
        }
      } else if (paramObjs[i] instanceof String) {
        if (type != VoltType.STRING)
          throw new RuntimeException("Inserting string into mismatched column type in HSQL.");
        // Escape single quotes
        sqlOut.append(sqlEscape((String) paramObjs[i]));
      } else {
        if (type == VoltType.TIMESTAMP) {
          long t = Long.parseLong(paramObjs[i].toString());
          TimestampType d = new TimestampType(t);
          // convert VoltDB's microsecond granularity to millis
          Timestamp ts = new Timestamp(d.getTime() * 1000);
          sqlOut.append('\'').append(ts.toString()).append('\'');
        } else sqlOut.append(paramObjs[i].toString());
      }
    }
    sqlOut.append(sql, lastIndex, sql.length());

    return runDML(sqlOut.toString());
  }
示例#17
0
  /** tcp server thread. */
  public void run() {
    LOG.log(Level.INFO, "Ready receiving messages...");
    while (Thread.currentThread() == runner) {

      if (tcpServer != null) {
        try {

          // check if client is available
          if (client != null && client.active()) {
            // do not send sound status to gui - very cpu intensive!
            // sendSoundStatus();

            if ((count % 20) == 2 && Collector.getInstance().isRandomMode()) {
              sendStatusToGui();
            }
          }

          Client c = tcpServer.available();
          if (c != null && c.available() > 0) {

            // clean message
            String msg = lastMsg + StringUtils.replace(c.readString(), "\n", "");
            // add replacement end string
            msg = StringUtils.replace(msg, FUDI_ALTERNATIVE_END_MARKER, FUDI_MSG_END_MARKER);
            msg = StringUtils.trim(msg);

            int msgCount = StringUtils.countMatches(msg, FUDI_MSG_END_MARKER);
            LOG.log(Level.INFO, "Got Message: <{0}> cnt: {1}", new Object[] {msg, msgCount});

            // work around bug - the puredata gui sends back a message as soon we send one
            long delta = System.currentTimeMillis() - lastMessageSentTimestamp;
            if (delta < FLOODING_TIME) {
              LOG.log(
                  Level.INFO,
                  "Ignore message, flooding protection ({0}<{1})",
                  new String[] {"" + delta, "" + FLOODING_TIME});
              // delete message
              msgCount = 0;
              msg = "";
            }

            // ideal, one message receieved
            if (msgCount == 1) {
              msg = StringUtils.removeEnd(msg, FUDI_MSG_END_MARKER);
              lastMsg = "";
              processMessage(StringUtils.split(msg, ' '));
            } else if (msgCount == 0) {
              // missing end of message... save it
              lastMsg = msg;
            } else {
              // more than one message received, split it
              // TODO: reuse partial messages
              lastMsg = "";
              String[] msgs = msg.split(FUDI_MSG_END_MARKER);
              for (String s : msgs) {
                s = StringUtils.trim(s);
                s = StringUtils.removeEnd(s, FUDI_MSG_END_MARKER);
                processMessage(StringUtils.split(s, ' '));
              }
            }
          }
        } catch (Exception e) {
        }
      }

      count++;
      try {
        Thread.sleep(50);
      } catch (InterruptedException e) {
        // Ignored
      }
    }
  }
  @Override
  public String parseKeySequenceToKorean(String keySequence)
      throws ParseException, IllegalArgumentException {
    String result = "";

    LetterState stateFlag = LetterState.Null;

    String tICon = "";
    String tIConLookahead = "";
    String tIConLookaheadCombination = "";
    String tVow = "";
    String tVowLookahead = "";
    String tVowLookaheadCombination = "";
    String tFCon = "";
    String tFConLookahead = "";
    String tFConLookaheadCombination = "";

    LetterObject syl = new LetterObject(KeyboardLayout.Dubeol);

    if (isEnableParsingExceptionSyntax() && StringUtils.countMatches(keySequence, "\\") % 2 == 1)
      throw new ParseException("Back slashes do not match", keySequence.lastIndexOf("\\", 0));

    for (int i = 0; i < keySequence.length(); i++) {
      if (stateFlag.equals(LetterState.Null) || stateFlag.equals(LetterState.Finish)) {
        stateFlag = LetterState.IConsonant;
      }

      if (!CharUtils.isAsciiAlpha(keySequence.charAt(i))) {
        if (keySequence.charAt(i) == '\\' && isEnableParsingExceptionSyntax()) {
          if (i < keySequence.length() - 1)
            if (keySequence.charAt(i + 1) == '\\') {
              result += "\\";
              continue;
            }
          i++;
          while (true) {
            if (i + 1 <= keySequence.length() - 1) {
              if (keySequence.charAt(i) == '\\') {
                if (keySequence.charAt(i + 1) == '\\') {
                  i++;
                  result += '\\';
                } else break;
              } else {
                result += keySequence.charAt(i);
              }
            } else {
              if (keySequence.charAt(i) == '\\') {
                break;
              } else {
                result += keySequence.charAt(i);
              }
            }
            i++;
          }
        } else {
          result += keySequence.charAt(i);
        }
        continue;
      }
      // 초성 (자음, 쌍자음)
      if (stateFlag.equals(LetterState.IConsonant)) {
        // 일단 초기화
        tIConLookahead = tIConLookaheadCombination = "";

        // 대 소문자에 따라 값이 바뀌는 키라면 그냥 넣어주고 아니면 소문자로 바꿔준다
        tICon =
            hasTwoSymbolinOneKey(keySequence.charAt(i))
                ? Character.toString(keySequence.charAt(i))
                : Character.toString(keySequence.charAt(i)).toLowerCase();
        // 다음 키 시퀀스랑 조합 분석하기 위한 할당
        if (i < keySequence.length() - 1) {
          // 대 소문자에 따라 값이 바뀌는 키라면 그냥 넣어주고 아니면 소문자로 바꿔준다
          tIConLookahead =
              hasTwoSymbolinOneKey(keySequence.charAt(i + 1))
                  ? Character.toString(keySequence.charAt(i + 1))
                  : Character.toString(keySequence.charAt(i + 1)).toLowerCase();
          tIConLookaheadCombination = tICon + tIConLookahead;
        }

        // 받침자음은 첫자음을 포함하며, 수가 더 많음.
        // (ㄸ와 ㅃ,ㅉ 같은 경우 제외)
        if (isFConsonant(tIConLookaheadCombination)) {

          // 2 step - lookahead가 가능하면 try
          if (i + 2 <= keySequence.length() - 1) {
            String lookOverTwoStep =
                hasTwoSymbolinOneKey(keySequence.charAt(i + 2))
                    ? Character.toString(keySequence.charAt(i + 2))
                    : Character.toString(keySequence.charAt(i + 2)).toLowerCase();

            // 자음 두번 입력 후, 자음 혹은 특수문자, 공백, 숫자
            if (isISingleConsonant(lookOverTwoStep)
                || isIDoubleConsonant(lookOverTwoStep)
                || !CharUtils.isAsciiAlpha(lookOverTwoStep.charAt(0))) {

              result += getSingleChar(getSingleCharVal(tIConLookaheadCombination));

              i++;
            }
            // 자음 두번 입력 후 모음
            else if (isVowel(lookOverTwoStep)) {
              // 받침자음의 앞 자는 버리고 뒤 자를 살린다
              result += getSingleChar(getSingleCharVal(tICon));
              continue;
            }

          }
          // 문장의 마지막에 (받침용) 겹자음 입력했을 경우 출력 후 종료
          else {
            result += getSingleChar(getSingleCharVal(tIConLookaheadCombination));
            stateFlag = LetterState.Null;
            break;
          }
        }
        // 쌍자음, 단자음인 경우 ( (받침용) 겹자음 제외)
        else {
          // 자음이면 대기 슬롯에 넣음
          if (isISingleConsonant(tICon) || isIDoubleConsonant(tICon)) {
            syl.setIConsonant(tICon);
            // init = DubeolSymbol.DubeolIConsonant.valueOf(tICon);
          }
          // 모음이면 독립모음을 찍기 위해 모음 단계부터 다시 처리
          else if (isVowel(tICon)) {
            stateFlag = LetterState.Vowel;
            i--;
            continue;
          }

          // 문장의 마지막에 단일 자음 입력했을 경우 출력 후 종료
          if (i == keySequence.length() - 1) {

            result += getSingleChar(getSingleCharVal(tICon));
            syl.initLetter();
            stateFlag = LetterState.Null;
            break;
          }

          // 현재 자음이고 다음 글자가 모음이면 모음을 확인하기 위해 계속 진행
          if (isVowel(tIConLookahead)) {
            stateFlag = LetterState.Vowel;
            continue;
          }
          // 초성 자음이 뒤따라 오는 경우
          else {

            result += getSingleChar(getSingleCharVal(tICon));
            syl.initLetter();
          }
        }
      }
      // 중성 (모음)
      else if (stateFlag.equals(LetterState.Vowel)) {
        // 일단 초기화
        tVowLookahead = tVowLookaheadCombination = "";

        // 대 소문자에 따라 값이 바뀌는 키라면 그냥 넣어주고 아니면 소문자로 바꿔준다
        tVow =
            hasTwoSymbolinOneKey(keySequence.charAt(i))
                ? Character.toString(keySequence.charAt(i))
                : Character.toString(keySequence.charAt(i)).toLowerCase();
        // 다음 키 시퀀스랑 조합 분석하기 위한 할당
        if (i < keySequence.length() - 1) {
          // 대 소문자에 따라 값이 바뀌는 키라면 그냥 넣어주고 아니면 소문자로 바꿔준다
          tVowLookahead =
              hasTwoSymbolinOneKey(keySequence.charAt(i + 1))
                  ? Character.toString(keySequence.charAt(i + 1))
                  : Character.toString(keySequence.charAt(i + 1)).toLowerCase();
          tVowLookaheadCombination = tVow + tVowLookahead;
        }

        // 겹모음인 경우?
        if (isVowel(tVowLookaheadCombination)) {
          syl.setVowel(tVowLookaheadCombination);
          // vow =
          // DubeolSymbol.DubeolVowel.valueOf(tVowLookaheadCombination);

          // 2 step - lookahead가 가능하면 try
          if (i + 2 <= keySequence.length() - 1) {
            // 대 소문자에 따라 값이 바뀌는 키라면 그냥 넣어주고 아니면 소문자로 바꿔준다
            String lookOverTwoStep =
                hasTwoSymbolinOneKey(keySequence.charAt(i + 2))
                    ? Character.toString(keySequence.charAt(i + 2))
                    : Character.toString(keySequence.charAt(i + 2)).toLowerCase();

            i++;

            // 겹모음에 모음이 또 따라오면 현재 글자는 완성, 다음 모음은 독립적인 존재.
            // 다음에 오는 자음은 받침에 쓸 수 없을 경우 이 과정을 밟는다
            if (isVowel(lookOverTwoStep)
                || ((isISingleConsonant(lookOverTwoStep) || isIDoubleConsonant(lookOverTwoStep))
                    && !isFConsonant(lookOverTwoStep))) {
              stateFlag = LetterState.Finish;
            }
            // 겹모음에 받침이 따라오는 경우 받침을 찾을 차례, ex: 왠
            else if (isFConsonant(lookOverTwoStep)) {
              if (!syl.isCompleteSyllable()) {

                result += getSingleChar(getSingleCharVal(tVowLookaheadCombination));
                stateFlag = LetterState.Null;
              } else {
                stateFlag = LetterState.FConsonant;
                continue;
              }
            }
            // 빈 칸 혹은 특수문자
            else if (!CharUtils.isAsciiAlpha(lookOverTwoStep.charAt(0))) {
              if (!syl.isCompleteSyllable()) {
                result += getSingleChar(getSingleCharVal(tVowLookaheadCombination));
                syl.initLetter();
                stateFlag = LetterState.Null;
              } else stateFlag = LetterState.Finish;
            }
          }
          // 다음 문자 밖에 볼 수 없을 경우 (시퀀스의 마지막)
          else {
            // 자음이 대기 슬롯에 없으면 독립 모음 출력
            if (!syl.isCompleteSyllable()) {
              result += getSingleChar(getSingleCharVal(tVowLookaheadCombination));
              syl.initLetter();
              i++;
              stateFlag = LetterState.Null;
            } else {
              stateFlag = LetterState.Finish;
            }

            // 포인터가 시퀀스의 마지막에 있으면 종료
            if (i == keySequence.length() - 1) break;
          }
        }
        // 겹모음이 아닌 경우, ㅏ ㅐ ㅑ ㅒ ㅓ ㅖ ㅕ ㅖ ㅗ ㅛ ㅜ ㅠ ㅡ ㅣ
        else {
          // 현재 키 시퀀스가 모음에 해당해야 함
          if (isVowel(tVow)) {
            // 모음을 대기 슬롯에 넣는다.
            if (!syl.isCompleteSyllable()) syl.setVowel(tVow);

            // 키 시퀀스의 마지막이라면
            if (i == keySequence.length() - 1) {
              // 자음이 존재하지 않는다면 독립 모음 입력
              if (!syl.isCompleteSyllable()) {

                result += getSingleChar(getSingleCharVal(tVow));
                syl.initLetter();
                stateFlag = LetterState.Null;
              }
              // 자음이 있으면 받침이 없는 완전한 글자 완성
              else {
                stateFlag = LetterState.Finish;
              }
              break;
            }

            // 2벌식 초성 중성 종성은 영문글자의 위치 영역에 있으므로
            // 영문자가 아닌 문자를 별개문자 혹은 delimiter로 취급
            // 뒤에 공백, 숫자, 특수문자 따라오는 경우.
            if (!CharUtils.isAsciiAlpha(tVowLookahead.charAt(0))) {

              // 초성이 없다면 독립 모음 입력.
              if (!syl.isCompleteSyllable()) {

                result += getSingleChar(getSingleCharVal(tVow));
                syl.initLetter();
                stateFlag = LetterState.IConsonant;
                continue;
              } else stateFlag = LetterState.Finish;
            }

            // *// 접근이 안되는 코드인듯. 주석처리
            // 자음이 입력되지 않았을 경우
            if (!syl.isCompleteSyllable()) {
              // 독립 모음
              result += getSingleChar(getSingleCharVal(tVow));
              syl.initLetter();

              // 다음이 자음이면 자음으로
              if (isISingleConsonant(tVowLookahead) || isIDoubleConsonant(tVowLookahead))
                stateFlag = LetterState.IConsonant;
              // 모음이면 모음으로 검색모드 전환
              else if (isVowel(tVowLookahead)) stateFlag = LetterState.Vowel;

              continue;
            } else {
              // 자음 + 모음 + 받침 : good!
              if (isFConsonant(tVowLookahead)) stateFlag = LetterState.FConsonant;
              // 자음이 입력되었을 때 모음 다음 모음 오는 경우, 예: 거ㅣ
              // ㄸ 과 같은 자음은 받침으로 쓰이지 않는다.
              else stateFlag = LetterState.Finish;
            }
          }
        }
      }
      // 종성
      else if (stateFlag.equals(LetterState.FConsonant)) {
        // 일단 초기화
        tFConLookahead = tFConLookaheadCombination = "";

        // 대 소문자에 따라 값이 바뀌는 키라면 그냥 넣어주고 아니면 소문자로 바꿔준다
        tFCon =
            hasTwoSymbolinOneKey(keySequence.charAt(i))
                ? Character.toString(keySequence.charAt(i))
                : Character.toString(keySequence.charAt(i)).toLowerCase();
        // 다음 키 시퀀스랑 조합 분석하기 위한 할당
        if (i < keySequence.length() - 1) {
          tFConLookahead =
              hasTwoSymbolinOneKey(keySequence.charAt(i + 1))
                  ? Character.toString(keySequence.charAt(i + 1))
                  : Character.toString(keySequence.charAt(i + 1)).toLowerCase();
          tFConLookaheadCombination = tFCon + tFConLookahead;
        }

        stateFlag = LetterState.Finish; // 받침이 나오면 한 글자 완성이 끝남.

        // 받침용 겹모음이라면?
        if (isFConsonant(tFConLookaheadCombination)) {

          // 2 step - lookahead가 가능하면 try
          if (i + 2 <= keySequence.length() - 1) {
            String lookOverTwoStep =
                hasTwoSymbolinOneKey(keySequence.charAt(i))
                    ? Character.toString(keySequence.charAt(i + 2))
                    : Character.toString(keySequence.charAt(i + 2)).toLowerCase();

            // (받침용) 겹자음에 자음이 뒤따라오는 모양새
            if (isISingleConsonant(lookOverTwoStep)
                || isIDoubleConsonant(lookOverTwoStep)
                || !CharUtils.isAsciiAlpha(lookOverTwoStep.charAt(0))) {
              // 받침을 대기 슬롯에 넣는다. 겹자음이므로 키 시퀀스를 하나 건너뛴다
              syl.setFConsonant(tFConLookaheadCombination);
              i++;
              // 단자음 받침일 수도 있다. 받침, 자음 + 모음
            } else if (isVowel(lookOverTwoStep)) syl.setFConsonant(tFCon);

          } else {
            // 키 시퀀스의 마지막이라면 대기 슬롯 받침자리에 받침을 채우고 끝낸다.
            if (isFConsonant(tFConLookaheadCombination)) {
              syl.setFConsonant(tFConLookaheadCombination);
            }

            break;
          }

        } else {
          // 단자음 받침이나 쌍자음 받침을 슬롯에 넣는다.
          if (isFConsonant(tFCon)) syl.setFConsonant(tFCon);

          // 키 시퀀스의 끝이라면 끝낸다.
          if (i == keySequence.length() - 1) break;

          // 다음 글자가 모음이면 받침으로 간주하지 않고 backtracking.
          // 대기 슬롯의 받침 자리를 비워둔다
          if (isVowel(tFConLookahead)) {
            syl.setFConsonant("nul");
            stateFlag = LetterState.Finish;
            i--;
          }
        }
      }

      // 한 글자가 완성되었으니 대기 슬롯에서 글자를 빼내어 결과 스트링에 붙여준다
      if (stateFlag == LetterState.Finish) {
        result += syl.getLetter();
        syl.initLetter();
      }
    }

    // 마무리.
    if (stateFlag == LetterState.Finish) result += syl.getLetter();

    return result;
  }
示例#19
0
 private static boolean checkValidity(final UtdFile file) {
   final String content = file.getContent();
   return StringUtils.countMatches(content, "::BEGINLOOP")
       == StringUtils.countMatches(content, "::ENDLOOP");
 }
示例#20
0
 public TemplateParser(CodeBuilder cb) {
   this.template = cb.template();
   totalLines = StringUtils.countMatches(template, "\n") + 1;
   this.cb = cb;
 }
示例#21
0
  public static boolean importTable(
      JdbcConnection conn,
      String tableName,
      Map<String, String> features,
      File fileIn,
      File tablePath,
      char delimiter,
      boolean header) {
    boolean ok = true;
    try {
      DbChecker dbCh = new DbChecker(conn);
      if (!dbCh.isTableExist(tableName)) {
        logger.debug("The table which has to be imported has not been created");
        logger.debug("Creation of the table");
        Integer ASCIIVal = (int) delimiter;
        String[] options = {ASCIIVal.toString(), tablePath.getCanonicalPath()};
        conn.executeQuery(
            new MySqlBasicStatement().createExternalTable(tableName, features, options));
      } else {
        // Check if it is the same table
        if (!dbCh.areFeaturesTheSame(tableName, features.keySet())) {
          logger.warn("Mismatch between the table to import and the table in the database");
          return false;
        }

        logger.warn("Have to check if the table is external or not, I do not know how to do that");
      }
    } catch (SQLException e) {
      logger.debug("Fail to watch the datastore");
      logger.debug(e.getMessage());
      return false;
    } catch (IOException e) {
      logger.warn("Fail to get the output path from a File object");
      logger.warn(e.getMessage());
      return false;
    }

    // Check if the input file has the right number of field
    FileChecker fChIn = new FileChecker(fileIn);
    FileChecker fChOut = new FileChecker(tablePath);
    String strLine = "";
    try {

      if (fChIn.isDirectory() || !fChIn.canRead()) {
        logger.warn("The file " + fChIn.getFilename() + "is a directory or can not be read");
        return false;
      }
      BufferedReader br = new BufferedReader(new FileReader(fileIn));
      // Read first line
      strLine = br.readLine();
      br.close();
    } catch (IOException e1) {
      logger.debug("Fail to open the file" + fChIn.getFilename());
      return false;
    }

    if (StringUtils.countMatches(strLine, String.valueOf(delimiter)) != features.size() - 1) {
      logger.warn(
          "File given does not match with the delimiter '"
              + delimiter
              + "' given and the number of fields '"
              + features.size()
              + "'");
      return false;
    }

    BufferedWriter bw = null;
    BufferedReader br = null;

    try {
      bw = new BufferedWriter(new FileWriter(tablePath));
      logger.debug("read the file" + fileIn.getAbsolutePath());
      br = new BufferedReader(new FileReader(fileIn));
      String delimiterStr = "" + delimiter;
      // Read File Line By Line
      while ((strLine = br.readLine()) != null) {
        bw.write("\"" + strLine.replace(delimiterStr, "\",\"") + "\"\n");
      }
      br.close();

      bw.close();
    } catch (FileNotFoundException e1) {
      logger.error(e1.getCause() + " " + e1.getMessage());
      logger.error("Fail to read " + fileIn.getAbsolutePath());
      ok = false;
    } catch (IOException e1) {
      logger.error(
          "Error writting, reading on the filesystem from the directory"
              + fChIn.getFilename()
              + " to the file "
              + fChOut.getFilename());
      ok = false;
    }

    return ok;
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.setContentView(R.layout.choose_uploader);

    // mListView = (ListView) findViewById(R.id.listView1);
    file = Environment.getExternalStorageDirectory();
    dircount = StringUtils.countMatches(file.getAbsolutePath(), "/");

    deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
    Intent intent = getIntent();
    uploadtype = intent.getStringExtra("uploadtype");

    uploadtype = uploadtype.valueOf(uploadtype);

    /* Toast.makeText(getApplicationContext(), "image clicked "+uploadtype,
    Toast.LENGTH_LONG).show();*/
    Button playButton = (Button) findViewById(R.id.imgcancelbtn);
    if (uploadtype.matches("group")) {
      /*Toast.makeText(getApplicationContext(), "image clicked in group ",
      Toast.LENGTH_LONG).show();*/
      playButton.setVisibility(View.GONE);
    }

    if (uploadtype.matches("editp")) {
      /* Toast.makeText(getApplicationContext(), "image clicked in group ",
      Toast.LENGTH_LONG).show();*/
      playButton.setVisibility(View.GONE);
    }
    if (uploadtype.matches("editpb")) {
      /* Toast.makeText(getApplicationContext(), "image clicked in group ",
      Toast.LENGTH_LONG).show();*/
      playButton.setVisibility(View.GONE);
    }

    /*gridView = (GridView) findViewById(R.id.gridView);
    gridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout, getFilePaths());
    gridView.setAdapter(gridAdapter);*/

    gridView.setOnItemClickListener(
        new AdapterView.OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            // ImageItem item = (ImageItem) parent.getItemAtPosition(position);
            // ImageItem item = (ImageItem) parent.getItemAtPosition(position);
            String prompt = (String) parent.getItemAtPosition(position);

            /*Toast.makeText(getApplicationContext(), "image clicked " + prompt,
            Toast.LENGTH_LONG).show();*/

            dialog = ProgressDialog.show(allfilelist.this, "Uploading", "Please wait...", true);
            if (prompt.contains(".mp4") || prompt.contains(".MP4")) {

              fileuri = prompt;
              new VideoUploadTask().execute();

              SystemClock.sleep(1000);

              new VideoUploadTaskupdatelocation().execute();
              new VideoUploadTaskfull().execute();

            } else {

              decodeFile(prompt);
              new ImageUploadTask().execute();
            }

            // Create intent
            /*Intent intent = new Intent(upload.this, cameraActivity.class);
            intent.putExtra("title", item.getTitle());
            intent.putExtra("image", item.getImage());

            //Start details activity
            startActivity(intent);*/
          }
        });
  }
  public static Optional<ItemStack> getItemStack(final String name, final int quantity) {

    if (name == null || name.isEmpty()) return Optional.absent();

    // Check our preferred list first. If we have a hit, use it.
    ItemStack result = PreferredItemStacks.instance.get(name);

    if (result != null) {

      result = result.copy();
      result.stackSize = quantity;

    } else {

      // Parse out the possible subtype from the end of the string
      String workingName = name;
      int subType = -1;

      if (StringUtils.countMatches(name, ":") == 2) {
        workingName = StringUtils.substringBeforeLast(name, ":");
        final String num = StringUtils.substringAfterLast(name, ":");

        if (num != null && !num.isEmpty()) {

          if ("*".compareTo(num) == 0) subType = OreDictionaryHelper.WILDCARD_VALUE;
          else {
            try {
              subType = Integer.parseInt(num);
            } catch (Exception e) {
              // It appears malformed - assume the incoming name
              // is
              // the real name and continue.
              ;
            }
          }
        }
      }

      // Check the OreDictionary first for any alias matches. Otherwise
      // go to the game registry to find a match.
      final List<ItemStack> ores = OreDictionaryHelper.getOres(workingName);
      if (!ores.isEmpty()) {
        result = ores.get(0).copy();
        result.stackSize = quantity;
      } else {
        final Item i = GameData.getItemRegistry().getObject(workingName);
        if (i != null) {
          result = new ItemStack(i, quantity);
        }
      }

      // If we did have a hit on a base item, set the sub-type
      // as needed.
      if (result != null && subType != -1) {
        if (subType == OreDictionaryHelper.WILDCARD_VALUE && !result.getHasSubtypes()) {
          ModLog.warn("[%s] GENERIC requested but Item does not support sub-types", name);
        } else {
          result.setItemDamage(subType);
        }
      }
    }

    return Optional.fromNullable(result);
  }