Esempio n. 1
0
  public void keyTyped(KeyEvent e) {
    if (!enabled) return;
    TextComponent input = (TextComponent) e.getSource();
    String strContent = input.getText();

    char c = e.getKeyChar();
    if (!isModifier(c)) return;
    int pos = input.getCaretPosition();
    if (pos <= 0) return;
    int idx = pos - 1; // position of the character to be modified
    char last = strContent.charAt(idx);
    char newVal = last;
    if (isCircumflex(c, last)) newVal = encoding.addCircumflex(last);
    else if (isBreve(c, last)) newVal = encoding.addBreveHorn(last);
    else if (isHorn(c, last)) newVal = encoding.addBreveHorn(last);
    else if (isStroke(c, last)) newVal = encoding.addStroke(last);
    else if (isToneMark(c)) {
      idx = indexOfToneCarrier(pos, strContent);
      if (idx < 0) return;
      last = strContent.charAt(idx);
      newVal = encoding.modifyTone(last, getToneMarkId(c));
    }
    if (last != newVal) {
      input.setCaretPosition(idx);
      TextField txt;
      //			input.moveCaretPosition(idx+1);
      //			input.replaceSelection("" + newVal);
      input.setCaretPosition(pos);
      e.consume();
    }
  }
Esempio n. 2
0
 /** Return the {@link FrameType} for the given {@link Class}. */
 protected HandlerWrapper createHandlerWrapper(
     Class<?> type, MessageHandler handler, boolean partialHandler) {
   if (partialHandler) {
     // Partial message handler supports only String, byte[] and ByteBuffer.
     // See JavaDocs of the MessageHandler.Partial interface.
     if (type == String.class) {
       return new HandlerWrapper(FrameType.TEXT, handler, type, false, true);
     }
     if (type == byte[].class || type == ByteBuffer.class) {
       return new HandlerWrapper(FrameType.BYTE, handler, type, false, true);
     }
     throw JsrWebSocketMessages.MESSAGES.unsupportedFrameType(type);
   }
   if (type == byte[].class || type == ByteBuffer.class || type == InputStream.class) {
     return new HandlerWrapper(FrameType.BYTE, handler, type, false, false);
   }
   if (type == String.class || type == Reader.class) {
     return new HandlerWrapper(FrameType.TEXT, handler, type, false, false);
   }
   if (type == PongMessage.class) {
     return new HandlerWrapper(FrameType.PONG, handler, type, false, false);
   }
   Encoding encoding = session.getEncoding();
   if (encoding.canDecodeText(type)) {
     return new HandlerWrapper(FrameType.TEXT, handler, type, true, false);
   } else if (encoding.canDecodeBinary(type)) {
     return new HandlerWrapper(FrameType.BYTE, handler, type, true, false);
   }
   throw JsrWebSocketMessages.MESSAGES.unsupportedFrameType(type);
 }
 /**
  * Get an instance based on the expected precision. Here are examples of the number of required
  * bytes per value depending on the expected precision:
  *
  * <ul>
  *   <li>1km: 4 bytes
  *   <li>3m: 6 bytes
  *   <li>1m: 8 bytes
  *   <li>1cm: 8 bytes
  *   <li>1mm: 10 bytes
  * </ul>
  */
 public static final Encoding of(DistanceUnit.Distance precision) {
   for (Encoding encoding : INSTANCES) {
     if (encoding != null && encoding.precision().compareTo(precision) <= 0) {
       return encoding;
     }
   }
   return INSTANCES[MAX_NUM_BYTES];
 }
  /**
   * The most important part of the classifier learning process! This method determines, for the
   * given weight vector x, what the (negative) log conditional likelihood of the data is, as well
   * as the derivatives of that likelihood wrt each weight parameter.
   */
  public Pair<Double, double[]> calculate() {
    double objective = 0.0;
    System.out.println("In Calculate...");

    double[] derivatives = DoubleArrays.constantArray(0.0, dimension());
    int numSubLabels = encoding.getNumSubLabels();
    int numData = data.length;
    for (int l = 0; l < numData; ++l) {
      EncodedDatum datum = data[l];
      double[] logProbabilities = getLogProbabilities(datum, x, encoding, indexLinearizer);
      int C = datum.getLabelIndex();
      double[] labelWeights = datum.getWeights();
      int numSubstatesC = labelWeights.length;
      int substate0 = encoding.getLabelSubindexBegin(C);
      for (int c = 0; c < numSubstatesC; c++) { // For each substate of label C
        objective -= labelWeights[c] * logProbabilities[substate0 + c];
      }
      // Convert to probabilities:
      double[] probabilities = new double[numSubLabels];
      double sum = 0.0;
      for (int c = 0; c < numSubLabels; ++c) { // For each substate
        probabilities[c] = Math.exp(logProbabilities[c]);
        sum += probabilities[c];
      }
      if (Math.abs(sum - 1.0) > 1e-3) {
        System.err.println("Probabilities do not sum to 1!");
      }
      // Compute derivatives:
      for (int i = 0; i < datum.getNumActiveFeatures(); ++i) {
        int featureIndex = datum.getFeatureIndex(i);
        double featureCount = datum.getFeatureCount(i);
        for (int c = 0; c < numSubLabels; ++c) { // For each substate
          int index = indexLinearizer.getLinearIndex(featureIndex, c);
          derivatives[index] += featureCount * probabilities[c];
        }
        for (int c = 0; c < numSubstatesC; c++) { // For each substate of label C
          int index = indexLinearizer.getLinearIndex(featureIndex, substate0 + c);
          derivatives[index] -= labelWeights[c] * featureCount;
        }
      }
    }

    // Incorporate penalty terms (regularization) into the objective and derivatives
    double sigma2 = sigma * sigma;
    double penalty = 0.0;
    for (int index = 0; index < x.length; ++index) {
      penalty += x[index] * x[index];
    }
    objective += penalty / (2 * sigma2);

    for (int index = 0; index < x.length; ++index) {
      // 'x' and 'derivatives' have same layout
      derivatives[index] += x[index] / sigma2;
    }
    return new Pair<Double, double[]>(objective, derivatives);
  }
  /**
   * Write a portion of an array of characters.
   *
   * @param cbuf Array of characters
   * @param off Offset from which to start writing characters
   * @param len Number of characters to write
   * @throws java.io.IOException If an I/O error occurs
   */
  public void write(final char[] cbuf, final int off, final int len) throws IOException {
    text = Utf16LE.getInstance().decode(cbuf, off, len, text);
    if (buffer != null) {
      buffer.setCursor(0);
    }

    if (errorType == null) {
      buffer = encoding.encode(text, buffer);
    } else {
      buffer = encoding.encode(text, buffer, errorType);
    }

    outputStream.write(buffer.getData(), buffer.getOffset(), buffer.getLength());
  }
Esempio n. 6
0
 protected int indexOfToneCarrier(int pos, String strContent) {
   int idx = indexOfLastVowel(pos, strContent);
   if (idx <= 0) return idx;
   char c = strContent.charAt(idx - 1);
   if (!encoding.isVowel(c) && !eq(c, 'q')) return idx;
   if (encoding.hasDiacritic(strContent.charAt(idx))) return idx;
   if (encoding.hasDiacritic(c)) return idx - 1;
   if (eq(c, 'q') && eq(strContent.charAt(idx), 'u')) return -1;
   if (eq(c, 'o') && eq(strContent.charAt(idx), 'a')) return idx;
   if (eq(c, 'o') && eq(strContent.charAt(idx), 'e')) return idx;
   if (eq(c, 'u') && eq(strContent.charAt(idx), 'y')) return idx;
   if ((idx >= 2) && eq(c, 'u') && eq(strContent.charAt(idx - 2), 'q')) return idx;
   if ((idx >= 2) && eq(c, 'i') && eq(strContent.charAt(idx - 2), 'g')) return idx;
   return idx - 1;
 }
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = super.hashCode();
   result = prime * result + encoding.hashCode() + ((getMsg() == null ? 0 : getMsg().hashCode()));
   return result;
 }
  @RequestMapping(params = "method=search_queryRecruit")
  public @ResponseBody String search_queryRecruit() {

    List l = recruitservice.queryAll();
    Iterator iter = l.iterator();
    Map data = new HashMap();
    JSONArray json_result = new JSONArray();
    for (int i = 0; i < l.size(); i++) {
      Recruit_Info info = (Recruit_Info) iter.next();
      data.put("info_id", info.getInfo_id());
      data.put("issue_time", info.getIssue_time());
      data.put("recruit_detail", info.getRecruit_detail());
      data.put("recruit_job", info.getRecruit_job());
      data.put("recruit_time", info.getRecruit_time());
      data.put("salary", info.getSalary());
      data.put("recruit_num", info.getRecruit_num());
      data.put("user_id", info.getUser_id());
      data.put("recruit_industry", info.getRecruit_industry());
      data.put("work_place", info.getWork_place());
      data.put("etp_name", info.getEtp_name());
      json_result.put(data);
    }
    String result = "{\"recruit_info\":" + json_result + "}";
    String result_temp = "error";
    result_temp = encoding.encoding(result);
    return result_temp;
  }
  /** Calculate the log probabilities of each class, for the given datum (feature bundle). */
  public <F, L> double[] getLogProbabilities(
      EncodedDatum datum,
      double[] weights,
      Encoding<F, L> encoding,
      IndexLinearizer indexLinearizer) {
    // Compute unnormalized log probabilities
    int numSubLabels = encoding.getNumSubLabels();
    double[] logProbabilities = DoubleArrays.constantArray(0.0, numSubLabels);
    for (int i = 0; i < datum.getNumActiveFeatures(); i++) {
      int featureIndex = datum.getFeatureIndex(i);
      double featureCount = datum.getFeatureCount(i);
      for (int j = 0; j < numSubLabels; j++) {
        int index = indexLinearizer.getLinearIndex(featureIndex, j);
        double weight = weights[index];
        logProbabilities[j] += weight * featureCount;
      }
    }
    // Normalize
    double logNormalizer = SloppyMath.logAdd(logProbabilities);
    for (int i = 0; i < numSubLabels; i++) {
      logProbabilities[i] -= logNormalizer;
    }

    return logProbabilities;
  }
  @Override
  public void putAttributes(AttributeGenerator generator) {
    super.putAttributes(generator);

    if (encoding != Encoding.NONE) {
      generator.put(ATTRIBUTE_ENCODING, encoding.name().toLowerCase());
    }
  }
Esempio n. 11
0
 void close0() {
   openSessions.remove(this);
   try {
     endpoint.release();
   } finally {
     encoding.close();
   }
 }
Esempio n. 12
0
 protected int indexOfLastVowel(int pos, String strContent) {
   int beg = Math.max(0, pos - 3);
   for (int i = pos - 1; i >= beg; i--) {
     char c = strContent.charAt(i);
     if (encoding.isVowel(c)) return i;
   }
   return -1;
 }
Esempio n. 13
0
 public String encode(String input) {
   List<String> results = new ArrayList<String>();
   String[] words = input.split(" ");
   for (String word : words) {
     results.add(encoding.encodeWord(word));
   }
   return StringUtils.join(results, " ");
 }
  @Override
  protected void consumeAttributes(AttributeHelper helper) throws ParseException {
    super.consumeAttributes(helper);

    String enc = helper.consume(ATTRIBUTE_ENCODING, false);
    if (enc != null) {
      this.encoding = Encoding.valueOf(enc.toUpperCase());
    } else {
      this.encoding = Encoding.NONE;
    }
  }
Esempio n. 15
0
 /**
  * 获取发件人
  *
  * @param b
  * @return
  */
 public static String getSender(byte[] b) {
   if (null != b) {
     byte[] bytes = new byte[5];
     for (int i = 0; i < bytes.length; i++) {
       bytes[i] = b[13 + i];
     }
     String reString = String.valueOf(Long.parseLong(Encoding.bytes2HexString(bytes), 16));
     return reString;
   }
   return "";
 }
  @Override
  public boolean equals(Object obj) {
    if (this == obj) return true;
    if (!super.equals(obj)) return false;
    if (!(obj instanceof Rfc822Msg)) return false;
    final Rfc822Msg other = (Rfc822Msg) obj;

    if (getMsg() == null) {
      if (other.getMsg() != null) return false;
    } else if (!getMsg().equals(other.getMsg())) return false;

    if (!encoding.equals(other.encoding)) return false;
    return true;
  }
Esempio n. 17
0
 /*
  * (non-Javadoc)
  *
  * @see java.io.Writer#write(char[], int, int)
  */
 @Override
 public void write(char[] cbuf, int off, int len) throws IOException {
   synchronized (lock) {
     ensureOpen();
     if ((off < 0)
         || (off > cbuf.length)
         || (len < 0)
         || ((off + len) > cbuf.length)
         || ((off + len) < 0)) {
       throw new IndexOutOfBoundsException();
     } else if (len == 0) {
       return;
     }
     int stop = off + len;
     for (int i = off; i < stop; i++) {
       encoding.putNextDecoded(outStream, cbuf[i]);
     }
   }
 }
 @RequestMapping(params = "method=search_querySeeker")
 public @ResponseBody String search_querySeeker() {
   List l = userservice.queryByUserType("1");
   Iterator iter = l.iterator();
   Map data = new HashMap();
   JSONArray json_result = new JSONArray();
   for (int i = 0; i < l.size(); i++) {
     User_Reg userregInstance = (User_Reg) iter.next();
     data.put("user_id", userregInstance.getUser_id());
     data.put("user_name", userregInstance.getUser_name());
     data.put("eng_name", userregInstance.getEng_name());
     data.put("cn_tname", userregInstance.getCn_tname());
     data.put("email", userregInstance.getEmail());
     data.put("password", userregInstance.getPassword());
     data.put("user_type", userregInstance.getUser_type());
     Seeker_Info seeker_infoInstance =
         seekerImpl.queryBySeekerUserId(userregInstance.getUser_id());
     data.put("seekerinfo_id", seeker_infoInstance.getInfo_id());
     data.put("user_id", seeker_infoInstance.getUser_id());
     data.put("age", seeker_infoInstance.getAge());
     data.put("edu_type", seeker_infoInstance.getEdu_type());
     data.put("end_time", seeker_infoInstance.getEnd_time());
     data.put("etp_industry", seeker_infoInstance.getEtp_industry());
     data.put("etp_name", seeker_infoInstance.getEtp_name());
     data.put("gender", seeker_infoInstance.getGender());
     data.put("highest_edu", seeker_infoInstance.getHighest_edu());
     data.put("job_status", seeker_infoInstance.getJob_status());
     data.put("marital_status", seeker_infoInstance.getMarital_status());
     data.put("mobile", seeker_infoInstance.getMobile());
     data.put("seeker_photo", seeker_infoInstance.getSeeker_photo());
     data.put("seeker_profession", seeker_infoInstance.getSeeker_profession());
     data.put("self_intro", seeker_infoInstance.getSelf_intro());
     data.put("start_time", seeker_infoInstance.getStart_time());
     data.put("tech_direction", seeker_infoInstance.getTech_direction());
     data.put("work_place", seeker_infoInstance.getWork_place());
     json_result.put(data);
   }
   String result = "{\"seeker\":" + json_result + "}";
   String result_temp = "error";
   result_temp = encoding.encoding(result);
   return result_temp;
 }
 @RequestMapping(params = "method=search_queryHunter")
 public @ResponseBody String search_queryHunter() {
   List l = userservice.queryByUserType("2");
   Iterator iter = l.iterator();
   Map data = new HashMap();
   JSONArray json_result = new JSONArray();
   for (int i = 0; i < l.size(); i++) {
     User_Reg userregInstance = (User_Reg) iter.next();
     data.put("user_id", userregInstance.getUser_id());
     data.put("user_name", userregInstance.getUser_name());
     data.put("eng_name", userregInstance.getEng_name());
     data.put("cn_tname", userregInstance.getCn_tname());
     data.put("email", userregInstance.getEmail());
     data.put("password", userregInstance.getPassword());
     data.put("user_type", userregInstance.getUser_type());
     Hunter_Info info = hunterImpl.queryByHunterUserId(userregInstance.getUser_id());
     data.put("info_id", info.getInfo_id());
     data.put("business_card", info.getBusiness_card());
     data.put("certificate", info.getCertificate());
     data.put("check_status", info.getCheck_status());
     data.put("etp_intro", info.getEtp_intro());
     data.put("etp_name", info.getEtp_name());
     data.put("gender", info.getGender());
     data.put("hunter_fax", info.getHunter_fax());
     data.put("mobile", info.getMobile());
     data.put("msg_addr", info.getMsg_addr());
     data.put("partner", info.getPartner());
     data.put("self_intro", info.getSelf_intro());
     data.put("t_area", info.getT_area());
     data.put("work_city", info.getWork_place());
     data.put("work_email", info.getWork_email());
     data.put("work_phone", info.getWork_phone());
     data.put("work_time", info.getWork_time());
     json_result.put(data);
   }
   String result = "{\"hunter\":" + json_result + "}";
   String result_temp = "error";
   result_temp = encoding.encoding(result);
   return result_temp;
 }
Esempio n. 20
0
    @Override
    public int compareTo(final ParsedEncoding other) {
      // we compare the strings as if they were decimal values.
      // we know they can only be

      final String t = qvalue;
      final String o = other.qvalue;
      if (t == null && o == null) {
        // neither of them has a q value
        // we compare them via the server specified default precedence
        // note that encoding is never null here, a * without a q value is meaningless
        // and will be discarded before this
        return handler.compareTo(other.handler);
      }

      if (o == null) {
        return 1;
      } else if (t == null) {
        return -1;
      }

      final int tl = t.length();
      final int ol = o.length();
      // we only compare the first 5 characters as per spec
      for (int i = 0; i < 5; ++i) {
        if (tl == i || ol == i) {
          return ol - tl; // longer one is higher
        }
        if (i == 1) continue; // this is just the decimal point
        final int tc = t.charAt(i);
        final int oc = o.charAt(i);

        int res = tc - oc;
        if (res != 0) {
          return res;
        }
      }
      return 0;
    }
Esempio n. 21
0
 /**
  * TRies to get a fuill url out of string
  *
  * @throws BrowserException
  */
 public String getURL(String string) throws BrowserException {
   if (string == null) {
     string = this.getRedirectLocation();
   }
   if (string == null) {
     throw new BrowserException("Null URL");
   }
   try {
     new URL(string);
   } catch (final Exception e) {
     if (this.request == null || this.request.getHttpConnection() == null) {
       return string;
     }
     final String base = this.getBase(string);
     if (string.startsWith("/") || string.startsWith("\\")) {
       try {
         final URL bUrl = new URL(base);
         String proto = "http://";
         if (base.startsWith("https")) {
           proto = "https://";
         }
         String portUse = "";
         if (bUrl.getDefaultPort() > 0
             && bUrl.getPort() > 0
             && bUrl.getDefaultPort() != bUrl.getPort()) {
           portUse = ":" + bUrl.getPort();
         }
         string = proto + new URL(base).getHost() + portUse + string;
       } catch (final MalformedURLException e1) {
         e1.printStackTrace();
       }
     } else {
       string = base + string;
     }
   }
   return Browser.correctURL(Encoding.urlEncode_light(string));
 }
 @RequestMapping(params = "method=search_queryEtp")
 public @ResponseBody String search_queryEtp() {
   List l = userservice.queryByUserType("3");
   Iterator iter = l.iterator();
   Map data = new HashMap();
   JSONArray json_result = new JSONArray();
   for (int i = 0; i < l.size(); i++) {
     User_Reg userregInstance = (User_Reg) iter.next();
     data.put("user_id", userregInstance.getUser_id());
     data.put("user_name", userregInstance.getUser_name());
     data.put("eng_name", userregInstance.getEng_name());
     data.put("cn_tname", userregInstance.getCn_tname());
     data.put("email", userregInstance.getEmail());
     data.put("password", userregInstance.getPassword());
     data.put("user_type", userregInstance.getUser_type());
     Etp_Info info = etpImpl.queryByEtpUserId(userregInstance.getUser_id());
     data.put("info_id", info.getInfo_id());
     data.put("certificate", info.getCertificate());
     data.put("check_status", info.getCheck_status());
     data.put("etp_intro", info.getEtp_intro());
     data.put("etp_name", info.getEtp_name());
     data.put("msg_addr", info.getMsg_addr());
     data.put("etp_addr", info.getEtp_addr());
     data.put("etp_email", info.getEtp_email());
     data.put("contact_person", info.getContact_person());
     data.put("etp_industry", info.getEtp_industry());
     data.put("etp_nature", info.getEtp_nature());
     data.put("mobile", info.getMobile());
     data.put("etp_size", info.getEtp_size());
     json_result.put(data);
   }
   String result = "{\"etp\":" + json_result + "}";
   String result_temp = "error";
   result_temp = encoding.encoding(result);
   return result_temp;
 }
  private void readStartupMessages(
      PGStream pgStream, ProtocolConnectionImpl protoConnection, Logger logger)
      throws IOException, SQLException {
    while (true) {
      int beresp = pgStream.ReceiveChar();
      switch (beresp) {
        case 'Z':
          // Ready For Query; we're done.
          if (pgStream.ReceiveInteger4() != 5)
            throw new IOException("unexpected length of ReadyForQuery packet");

          char tStatus = (char) pgStream.ReceiveChar();
          if (logger.logDebug()) logger.debug(" <=BE ReadyForQuery(" + tStatus + ")");

          // Update connection state.
          switch (tStatus) {
            case 'I':
              protoConnection.setTransactionState(ProtocolConnection.TRANSACTION_IDLE);
              break;
            case 'T':
              protoConnection.setTransactionState(ProtocolConnection.TRANSACTION_OPEN);
              break;
            case 'E':
              protoConnection.setTransactionState(ProtocolConnection.TRANSACTION_FAILED);
              break;
            default:
              // Huh?
              break;
          }

          return;

        case 'K':
          // BackendKeyData
          int l_msgLen = pgStream.ReceiveInteger4();
          if (l_msgLen != 12)
            throw new PSQLException(
                GT.tr("Protocol error.  Session setup failed."),
                PSQLState.CONNECTION_UNABLE_TO_CONNECT);

          int pid = pgStream.ReceiveInteger4();
          int ckey = pgStream.ReceiveInteger4();

          if (logger.logDebug())
            logger.debug(" <=BE BackendKeyData(pid=" + pid + ",ckey=" + ckey + ")");

          protoConnection.setBackendKeyData(pid, ckey);
          break;

        case 'E':
          // Error
          int l_elen = pgStream.ReceiveInteger4();
          ServerErrorMessage l_errorMsg =
              new ServerErrorMessage(pgStream.ReceiveString(l_elen - 4), logger.getLogLevel());

          if (logger.logDebug()) logger.debug(" <=BE ErrorMessage(" + l_errorMsg + ")");

          throw new PSQLException(l_errorMsg);

        case 'N':
          // Warning
          int l_nlen = pgStream.ReceiveInteger4();
          ServerErrorMessage l_warnMsg =
              new ServerErrorMessage(pgStream.ReceiveString(l_nlen - 4), logger.getLogLevel());

          if (logger.logDebug()) logger.debug(" <=BE NoticeResponse(" + l_warnMsg + ")");

          protoConnection.addWarning(new PSQLWarning(l_warnMsg));
          break;

        case 'S':
          // ParameterStatus
          int l_len = pgStream.ReceiveInteger4();
          String name = pgStream.ReceiveString();
          String value = pgStream.ReceiveString();

          if (logger.logDebug())
            logger.debug(" <=BE ParameterStatus(" + name + " = " + value + ")");

          if (name.equals("server_version")) protoConnection.setServerVersion(value);
          else if (name.equals("client_encoding")) {
            if (!value.equals("UNICODE"))
              throw new PSQLException(
                  GT.tr("Protocol error.  Session setup failed."),
                  PSQLState.CONNECTION_UNABLE_TO_CONNECT);
            pgStream.setEncoding(Encoding.getDatabaseEncoding("UNICODE"));
          } else if (name.equals("standard_conforming_strings")) {
            if (value.equals("on")) protoConnection.setStandardConformingStrings(true);
            else if (value.equals("off")) protoConnection.setStandardConformingStrings(false);
            else
              throw new PSQLException(
                  GT.tr("Protocol error.  Session setup failed."),
                  PSQLState.CONNECTION_UNABLE_TO_CONNECT);
          }

          break;

        default:
          if (logger.logDebug()) logger.debug("invalid message type=" + (char) beresp);
          throw new PSQLException(
              GT.tr("Protocol error.  Session setup failed."),
              PSQLState.CONNECTION_UNABLE_TO_CONNECT);
      }
    }
  }
 /**
  * Sets the text encoding used by the main database.
  *
  * @param encoding One of "UTF-8", "UTF-16le" (little-endian UTF-16) or "UTF-16be" (big-endian
  *     UTF-16).
  * @see <a href="http://www.sqlite.org/pragma.html#pragma_encoding">
  *     http://www.sqlite.org/pragma.html#pragma_encoding</a>
  */
 public void setEncoding(String encoding) {
   config.setEncoding(Encoding.getEncoding(encoding));
 }
Esempio n. 25
0
 /** 加密字符串 */
 public String encrypt(String s, String key) {
   byte[] tmp = Encoding.stringToUtf8(s);
   return Base64Encoder.byteArrayToBase64(encrypt(tmp, key));
 }
Esempio n. 26
0
 /** 解密字符串 */
 public String decrypt(String c, String key) {
   byte[] tmp = Base64Encoder.base64ToByteArray(c);
   return Encoding.utf8ToString(decrypt(tmp, key));
 }
  private File guideTheAtack(WebSession s, String fileName, List<File> htmlFiles) throws Exception {
    // Most people are going to start off with a simple test of
    // ./lesson.html or ../en/lesson.html  where lesson is equal
    // to the name of the selection from the UI.
    //     Example real path: plugin_extracted/plugin/CSRF/lessonPlans/en/CSRF.html
    //     the URL input by default for CSRF is &File=CSRF.html

    // We need to see if this was a simple attempt and serve the file as an allowed
    // file.  I don;t like this path hack, but it puts them in the right spot
    // on the file system...

    int lastSlash = fileName.lastIndexOf(System.getProperty("file.separator"));
    if (lastSlash == -1) lastSlash = 0;
    String lessonDir = fileName.substring(lastSlash);
    if (lessonDir.length() >= ".html".length()) // at least something semi valid is there
    {
      lessonDir = lessonDir.substring(0, lessonDir.length() - ".html".length());
    }
    String attemptedFileName =
        LessonUtil.getLessonDirectory(s, this).getParent()
            + "/"
            + lessonDir
            + "/lessonPlans/en/"
            + fileName;
    File attemptedFile = new File(attemptedFileName);

    // Check access to an allowed file.  if allowedFile != null, access is allowed
    // FIXME: This will incorrectly match ../lesson.html when it should be ../en/lesson.html
    File allowedFile = null;
    for (File htmlFile : htmlFiles) {
      if (htmlFile.getName().equals(fileName)
          || htmlFile.getName().equals(attemptedFile.getName())) {
        allowedFile = htmlFile;
      }
    }
    if (allowedFile != null && allowedFile.isFile() && allowedFile.exists()) {
      // Don't set completion if they are listing files in the
      // directory listing we gave them.
      if (upDirCount(fileName) >= 1) {
        s.setMessage(
            getLabelManager().get("OnTheRightPath")
                + " ==> "
                + Encoding.urlDecode(allowedFile.getCanonicalPath()));
      } else {
        s.setMessage(
            getLabelManager().get("FileInAllowedDirectory")
                + " ==> "
                + Encoding.urlDecode(allowedFile.getCanonicalPath()));
      }
    }

    if (s.isDebug()) {
      // f is only null if the "File" input was NOT a known lesson file
      s.setMessage(getLabelManager().get("File") + fileName);
      if (allowedFile != null) {
        s.setMessage(getLabelManager().get("Dir") + allowedFile.getParentFile());
        s.setMessage(getLabelManager().get("IsFile") + allowedFile.isFile());
        s.setMessage(getLabelManager().get("Exists") + allowedFile.exists());
      }
    }

    return allowedFile;
  }
  /**
   * Description of the Method
   *
   * @param s Description of the Parameter
   * @return Description of the Return Value
   */
  protected Element createContent(WebSession s) {
    ElementContainer ec = new ElementContainer();

    try {
      Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center");

      if (s.isColor()) {
        t.setBorder(1);
      }
      List<File> htmlFiles = findHtmlFiles(LessonUtil.getLessonDirectory(s, this).getParentFile());
      List<String> htmlFilenames =
          Lists.newArrayList(
              Iterables.transform(
                  htmlFiles,
                  new Function<File, String>() {
                    @Override
                    public String apply(File input) {
                      return input.getName();
                    }
                  }));
      String[] list = htmlFilenames.toArray(new String[htmlFilenames.size()]);
      String listing =
          " <p><B>"
              + getLabelManager().get("CurrentDirectory")
              + "</B> "
              + Encoding.urlDecode(htmlFiles.get(0).getParent())
              + "<br><br>"
              + getLabelManager().get("ChooseFileToView")
              + "</p>";

      TR tr = new TR();
      tr.addElement(new TD().setColSpan(2).addElement(new StringElement(listing)));
      t.addElement(tr);

      tr = new TR();
      tr.addElement(
          new TD().setWidth("35%").addElement(ECSFactory.makePulldown(FILE, list, "", 15)));
      tr.addElement(new TD().addElement(ECSFactory.makeButton(getLabelManager().get("ViewFile"))));
      t.addElement(tr);

      ec.addElement(t);

      // FIXME: would be cool to allow encodings here -- hex, percent,
      // url, etc...
      final String file = s.getParser().getRawParameter(FILE, "");

      if (!file.equals("")) // first time in or missing parameter - just kick out
      {
        // defuse file searching
        boolean illegalCommand = true;
        // allow them to look at any file in the webgoat hierachy.
        // Don't allow them to look about the webgoat root,
        // except to see the LICENSE file
        if (upDirCount(file) == 3 && !file.endsWith("LICENSE")) {
          s.setMessage(getLabelManager().get("AccessDenied"));
          s.setMessage(getLabelManager().get("ItAppears1"));
        } else {
          if (upDirCount(file) > 5) {
            s.setMessage(getLabelManager().get("AccessDenied"));
            s.setMessage(getLabelManager().get("ItAppears2"));
          } else {
            illegalCommand = false;
          }
        }

        // provide a little guidance to help them along.  If the allowed file comes back as
        // null we have the potential for a real attack vector
        File allowedFile = guideTheAtack(s, file, htmlFiles);

        if (!illegalCommand) {
          File attemptedFile =
              new File(LessonUtil.getLessonDirectory(s, this) + "/lessonPlans/en/" + file);
          if (allowedFile == null) {
            // We have a potential attack
            if (file != null && attemptedFile.isFile() && attemptedFile.exists()) {
              // They have accessed something meaningful
              s.setMessage(
                  getLabelManager().get("CongratsAccessToFileAllowed")
                      + " ==> "
                      + Encoding.urlDecode(attemptedFile.getCanonicalPath()));
              makeSuccess(s);
            } else if (file != null && file.length() != 0) {
              s.setMessage(
                  getLabelManager().get("AccessToFileDenied1")
                      + Encoding.urlDecode(file)
                      + getLabelManager().get("AccessToFileDenied2"));
            } else {
              // do nothing, probably entry screen
            }
          } else {
            attemptedFile = allowedFile;
          }

          displayAttemptedFile(ec, attemptedFile);
        }
      }

    } catch (Exception e) {
      s.setMessage(getLabelManager().get("ErrorGenerating") + this.getClass().getName());
      e.printStackTrace();
    }
    return (ec);
  }