/*
  * Clean up the temporary data used to run the tests.
  * This method is not intended to be called by clients, it will be called
  * automatically when the clients use a ReconcilerTestSuite.
  */
 public void cleanup() throws Exception {
   // rm -rf eclipse sub-dir
   boolean leaveDirty =
       Boolean.parseBoolean(TestActivator.getContext().getProperty("p2.tests.doNotClean"));
   if (leaveDirty) return;
   for (Iterator iter = toRemove.iterator(); iter.hasNext(); ) {
     File next = (File) iter.next();
     delete(next);
   }
   output = null;
   toRemove.clear();
 }
Пример #2
0
 private void restUseConfiguredCerts(
     final PwmRequest pwmRequest, final ConfigGuideBean configGuideBean)
     throws PwmUnrecoverableException, IOException {
   final boolean value = Boolean.parseBoolean(pwmRequest.readParameterAsString("value"));
   configGuideBean.setUseConfiguredCerts(value);
   final StoredValue newStoredValue =
       value
           ? new X509CertificateValue(configGuideBean.getLdapCertificates())
           : new X509CertificateValue(new X509Certificate[0]);
   configGuideBean
       .getStoredConfiguration()
       .writeSetting(PwmSetting.LDAP_SERVER_CERTS, LDAP_PROFILE_KEY, newStoredValue, null);
   pwmRequest.outputJsonResult(new RestResultBean());
 }
Пример #3
0
  private void checkLdapServer(ConfigGuideBean configGuideBean)
      throws PwmOperationalException, IOException {
    final Map<String, String> formData = configGuideBean.getFormData();
    final String host = formData.get(PARAM_LDAP_HOST);
    final int port = Integer.parseInt(formData.get(PARAM_LDAP_PORT));
    if (Boolean.parseBoolean(formData.get(PARAM_LDAP_SECURE))) {
      X509Utils.readRemoteCertificates(host, port);
    } else {
      InetAddress addr = InetAddress.getByName(host);
      SocketAddress sockaddr = new InetSocketAddress(addr, port);
      Socket sock = new Socket();

      // this method will block for the defined number of milliseconds
      int timeout = 2000;
      sock.connect(sockaddr, timeout);
    }
  }
Пример #4
0
  private void checkLdapServer(ConfigGuideBean configGuideBean)
      throws PwmOperationalException, IOException {
    final Map<String, String> formData = configGuideBean.getFormData();
    final String host = formData.get(PARAM_LDAP_HOST);
    final int port = Integer.parseInt(formData.get(PARAM_LDAP_PORT));

    { // socket test
      final InetAddress inetAddress = InetAddress.getByName(host);
      final SocketAddress socketAddress = new InetSocketAddress(inetAddress, port);
      final Socket socket = new Socket();

      final int timeout = 2000;
      socket.connect(socketAddress, timeout);
    }

    if (Boolean.parseBoolean(formData.get(PARAM_LDAP_SECURE))) {
      X509Utils.readRemoteCertificates(host, port);
    }
  }
Пример #5
0
  @Override
  public void init() {
    try {
      this.debug = Boolean.parseBoolean(this.getInitParameter("debug"));

      if (!this.debug) this.pageInfoCache = new HashMap<String, PageInfo>();

      String routesParameter = this.getInitParameter("routes");
      if (routesParameter != null) {
        this.routes = new Properties();
        routes.load(new StringReader(routesParameter));
      }

      String sourceParameter = this.getInitParameter("source");
      if (sourceParameter == null) throw new RuntimeException("Missing init parameter 'source'");
      // automatically insert a reference to our PageServlet.js if not present
      String sourceDelimiter = ";";
      if (sourceParameter.indexOf("PageServlet.js") < 0)
        sourceParameter =
            "jar:file:WEB-INF/lib/glasspages.jar!/glasspages/PageServlet.js"
                + sourceDelimiter
                + sourceParameter;
      this.errorPath = this.getInitParameter("error");
      String[] sourceFiles = sourceParameter.split(sourceDelimiter);
      URL[] sourceUrls = new URL[sourceFiles.length];
      for (int i = 0; i < sourceFiles.length; i++) {
        String sourceFile = sourceFiles[i];
        if (sourceFile.indexOf(':') < 0) sourceFile = "file:" + sourceFile;
        try {
          sourceUrls[i] = new URL(sourceFile);
        } catch (MalformedURLException e) {
          throw new RuntimeException(e);
        }
      }
      this.contextCache = new ScriptContextCache(sourceUrls);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  /**
   * Creates REST request.
   *
   * @param cmd Command.
   * @param params Parameters.
   * @return REST request.
   * @throws GridException If creation failed.
   */
  @Nullable
  private GridRestRequest createRequest(
      GridRestCommand cmd, Map<String, Object> params, ServletRequest req) throws GridException {
    GridRestRequest restReq;

    switch (cmd) {
      case CACHE_GET:
      case CACHE_GET_ALL:
      case CACHE_PUT:
      case CACHE_PUT_ALL:
      case CACHE_REMOVE:
      case CACHE_REMOVE_ALL:
      case CACHE_ADD:
      case CACHE_CAS:
      case CACHE_METRICS:
      case CACHE_REPLACE:
      case CACHE_DECREMENT:
      case CACHE_INCREMENT:
      case CACHE_APPEND:
      case CACHE_PREPEND:
        {
          GridRestCacheRequest restReq0 = new GridRestCacheRequest();

          restReq0.cacheName((String) params.get("cacheName"));
          restReq0.key(params.get("key"));
          restReq0.value(params.get("val"));
          restReq0.value2(params.get("val2"));

          Object val1 = params.get("val1");

          if (val1 != null) restReq0.value(val1);

          restReq0.cacheFlags(intValue("cacheFlags", params, 0));
          restReq0.ttl(longValue("exp", params, null));
          restReq0.initial(longValue("init", params, null));
          restReq0.delta(longValue("delta", params, null));

          if (cmd == CACHE_GET_ALL || cmd == CACHE_PUT_ALL || cmd == CACHE_REMOVE_ALL) {
            List<Object> keys = values("k", params);
            List<Object> vals = values("v", params);

            if (keys.size() < vals.size())
              throw new GridException(
                  "Number of keys must be greater or equals to number of values.");

            Map<Object, Object> map = U.newHashMap(keys.size());

            Iterator<Object> keyIt = keys.iterator();
            Iterator<Object> valIt = vals.iterator();

            while (keyIt.hasNext()) map.put(keyIt.next(), valIt.hasNext() ? valIt.next() : null);

            restReq0.values(map);
          }

          restReq = restReq0;

          break;
        }

      case TOPOLOGY:
      case NODE:
        {
          GridRestTopologyRequest restReq0 = new GridRestTopologyRequest();

          restReq0.includeMetrics(Boolean.parseBoolean((String) params.get("mtr")));
          restReq0.includeAttributes(Boolean.parseBoolean((String) params.get("attr")));

          restReq0.nodeIp((String) params.get("ip"));

          restReq0.nodeId(uuidValue("id", params));

          restReq = restReq0;

          break;
        }

      case EXE:
      case RESULT:
      case NOOP:
        {
          GridRestTaskRequest restReq0 = new GridRestTaskRequest();

          restReq0.taskId((String) params.get("id"));
          restReq0.taskName((String) params.get("name"));

          restReq0.params(values("p", params));

          restReq0.async(Boolean.parseBoolean((String) params.get("async")));

          restReq0.timeout(longValue("timeout", params, 0L));

          restReq = restReq0;

          break;
        }

      case LOG:
        {
          GridRestLogRequest restReq0 = new GridRestLogRequest();

          restReq0.path((String) params.get("path"));

          restReq0.from(intValue("from", params, -1));
          restReq0.to(intValue("to", params, -1));

          restReq = restReq0;

          break;
        }

      case VERSION:
        {
          restReq = new GridRestRequest();

          break;
        }

      default:
        throw new GridException("Invalid command: " + cmd);
    }

    restReq.address(new InetSocketAddress(req.getRemoteAddr(), req.getRemotePort()));

    restReq.command(cmd);

    if (params.containsKey("gridgain.login") || params.containsKey("gridgain.password")) {
      GridSecurityCredentials cred =
          new GridSecurityCredentials(
              (String) params.get("gridgain.login"), (String) params.get("gridgain.password"));

      restReq.credentials(cred);
    }

    String clientId = (String) params.get("clientId");

    try {
      if (clientId != null) restReq.clientId(UUID.fromString(clientId));
    } catch (Exception ignored) {
      // Ignore invalid client id. Rest handler will process this logic.
    }

    String destId = (String) params.get("destId");

    try {
      if (destId != null) restReq.destinationId(UUID.fromString(destId));
    } catch (IllegalArgumentException ignored) {
      // Don't fail - try to execute locally.
    }

    String sesTokStr = (String) params.get("sessionToken");

    try {
      if (sesTokStr != null) restReq.sessionToken(U.hexString2ByteArray(sesTokStr));
    } catch (IllegalArgumentException ignored) {
      // Ignore invalid session token.
    }

    return restReq;
  }
Пример #7
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType(XML_RESPONSE_HEADER); // Talkback happens in XML form.
    response.setCharacterEncoding("UTF-8"); // Unicode++
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = null; // The talkback buffer.

    // handle startrecord
    Integer startRecord = 0;

    if (!(request.getParameter("startRecord") == null)) {
      try {
        startRecord = Integer.parseInt(request.getParameter("startRecord")) - 1;
      } catch (NumberFormatException e) {
        startRecord = 0;
      }
    }

    // maximumrecords
    Integer maximumRecords = Integer.parseInt(this.config.getProperty("default_maximumRecords"));
    if (!(request.getParameter("maximumRecords") == null)) {
      maximumRecords = Integer.parseInt(request.getParameter("maximumRecords"));
    }

    // operation
    String operation = request.getParameter("operation");

    // x_collection
    String x_collection = request.getParameter("x-collection");
    if (x_collection == null) x_collection = this.config.getProperty("default_x_collection");
    if (x_collection == null) operation = null;

    // sortkeys
    String sortKeys = request.getParameter("sortKeys");

    // sortorder
    String sortOrder = request.getParameter("sortOrder");

    // recordschema
    String recordSchema = request.getParameter("recordSchema");
    if (recordSchema == null) recordSchema = "dc";

    if (recordSchema.equalsIgnoreCase("dcx")) {
      recordSchema = "dcx";
    }

    if (recordSchema.equalsIgnoreCase("solr")) {
      recordSchema = "solr";
    }

    // query request
    String query = request.getParameter("query");
    String q = request.getParameter("q");

    // who is requestor ?
    String remote_ip = request.getHeader("X-FORWARDED-FOR");

    if (remote_ip == null) {
      remote_ip = request.getRemoteAddr().trim();
    } else {
      remote_ip = request.getHeader("X-FORWARDED-FOR");
    }

    // handle debug
    Boolean debug = Boolean.parseBoolean(request.getParameter("debug"));
    if (!debug) {
      out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
    }

    // handle query
    if ((query == null) && (q != null)) {
      query = q;
    } else {
      if ((query != null) && (q == null)) {
        q = query;
      } else {
        operation = null;
      }
    }

    // handle operation
    if (operation == null) {
      if (query != null) {
        operation = "searchRetrieve";
      } else {
        operation = "explain";
      }
    }

    //  searchRetrieve
    if (operation.equalsIgnoreCase("searchRetrieve")) {
      if (query == null) {
        operation = "explain";
        log.debug(operation + ":" + query);
      }
    }

    // start talking back.
    String[] sq = {""};
    String solrquery = "";

    // facet

    String facet = null;
    List<FacetField> fct = null;

    if (request.getParameter("facet") != null) {
      facet = request.getParameter("facet");
      log.debug("facet : " + facet);
    }

    if (operation == null) {
      operation = "searchretrieve";
    } else { // explain response
      if (operation.equalsIgnoreCase("explain")) {
        log.debug("operation = explain");
        out.write("<srw:explainResponse xmlns:srw=\"http://www.loc.gov/zing/srw/\">");
        out.write("</srw:explainResponse>");
      } else { // DEBUG routine
        operation = "searchretrieve";

        String triplequery = null;

        if (query.matches(".*?\\[.+?\\].*?")) { // New symantic syntax
          triplequery = symantic_query(query);
          query = query.split("\\[")[0] + " " + triplequery;
          log.fatal(triplequery);

          solrquery = CQLtoLucene.translate(query, log, config);
        } else {
          solrquery = CQLtoLucene.translate(query, log, config);
        }
        log.debug(solrquery);

        if (debug == true) {
          response.setContentType(HTML_RESPONSE_HEADER);
          out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
          out.write("<html><body>\n\n");
          out.write("'" + remote_ip + "'<br>\n");
          out.write("<form action='http://www.kbresearch.nl/kbSRU'>");
          out.write("<input type=text name=q value='" + query + "' size=120>");
          out.write("<input type=hidden name=debug value=True>");
          out.write("<input type=submit>");
          out.write("<table border=1><tr><td>");
          out.write("q</td><td>" + query + "</td></tr><tr>");
          out.write("<td>query out</td><td>" + URLDecoder.decode(solrquery) + "</td></tr>");
          out.write(
              "<tr><td>SOLR_URL</td><td> <a href='"
                  + this.config.getProperty(
                      "collection." + x_collection.toLowerCase() + ".solr_baseurl")
                  + "/?q="
                  + solrquery
                  + "'>"
                  + this.config.getProperty(
                      "collection." + x_collection.toLowerCase() + ".solr_baseurl")
                  + "/select/?q="
                  + solrquery
                  + "</a><br>"
                  + this.config.getProperty("solr_url")
                  + solrquery
                  + "</td></tr>");
          out.write(
              "<b>SOLR_QUERY</b> : <BR> <iframe width=900 height=400 src='"
                  + this.config.getProperty(
                      "collection." + x_collection.toLowerCase() + ".solr_baseurl")
                  + "/../?q="
                  + solrquery
                  + "'></iframe><BR>");
          out.write(
              "<b>SRU_QUERY</b> : <BR> <a href="
                  + this.config.getProperty("baseurl")
                  + "?q="
                  + query
                  + "'>"
                  + this.config.getProperty("baseurl")
                  + "?q="
                  + query
                  + "</a><br><iframe width=901 height=400 src='http://www.kbresearch.nl/kbSRU/?q="
                  + query
                  + "'></iframe><BR>");
          out.write(
              "<br><b>JSRU_QUERY</b> : <BR><a href='http://jsru.kb.nl/sru/?query="
                  + query
                  + "&x-collection="
                  + x_collection
                  + "'>http://jsru.kb.nl/sru/?query="
                  + query
                  + "&x-collection=GGC</a><br><iframe width=900 height=400 src='http://jsru.kb.nl/sru/?query="
                  + query
                  + "&x-collection=GGC'></iframe>");

        } else { // XML SearchRetrieve response
          String url =
              this.config.getProperty("collection." + x_collection.toLowerCase() + ".solr_baseurl");
          String buffer = "";
          CommonsHttpSolrServer server = null;
          server = new CommonsHttpSolrServer(url);
          log.fatal("URSING " + url);
          server.setParser(new XMLResponseParser());
          int numfound = 0;
          try {
            SolrQuery do_query = new SolrQuery();
            do_query.setQuery(solrquery);
            do_query.setRows(maximumRecords);
            do_query.setStart(startRecord);

            if ((sortKeys != null) && (sortKeys.length() > 1)) {
              if (sortOrder != null) {
                if (sortOrder.equals("asc")) {
                  do_query.setSortField(sortKeys, SolrQuery.ORDER.asc);
                }
                if (sortOrder.equals("desc")) {
                  do_query.setSortField(sortKeys, SolrQuery.ORDER.desc);
                }
              } else {
                for (String str : sortKeys.trim().split(",")) {
                  str = str.trim();
                  if (str.length() > 1) {
                    if (str.equals("date")) {
                      do_query.setSortField("date_date", SolrQuery.ORDER.desc);
                      log.debug("SORTORDERDEBUG | DATE! " + str + " | ");
                      break;
                    } else {
                      do_query.setSortField(str + "_str", SolrQuery.ORDER.asc);
                      log.debug("SORTORDERDEBUG | " + str + " | ");
                      break;
                    }
                  }
                }
              }
            }

            if (facet != null) {
              if (facet.indexOf(",") > 1) {
                for (String str : facet.split(",")) {
                  if (str.indexOf("date") > 1) {
                    do_query.addFacetField(str);
                  } else {
                    do_query.addFacetField(str);
                  }
                  // do_query.setParam("facet.method", "enum");
                }
                // q.setFacetSort(false);
              } else {
                do_query.addFacetField(facet);
              }
              do_query.setFacet(true);
              do_query.setFacetMinCount(1);
              do_query.setFacetLimit(-1);
            }

            log.fatal(solrquery);

            QueryResponse rsp = null;
            boolean do_err = false;
            boolean do_sugg = false;
            SolrDocumentList sdl = null;
            String diag = "";
            StringBuffer suggest = new StringBuffer("");

            String content = "1";

            SolrQuery spellq = do_query;
            try {
              rsp = server.query(do_query);
            } catch (SolrServerException e) {
              String header = this.SRW_HEADER.replaceAll("\\$numberOfRecords", "0");
              out.write(header);
              diag = this.SRW_DIAG.replaceAll("\\$error", e.getMessage());
              do_err = true;
              rsp = null;
            }

            log.fatal("query done..");
            if (!(do_err)) { // XML dc response

              SolrDocumentList docs = rsp.getResults();
              numfound = (int) docs.getNumFound();
              int count = startRecord;
              String header =
                  this.SRW_HEADER.replaceAll("\\$numberOfRecords", Integer.toString(numfound));
              out.write(header);
              out.write("<srw:records>");

              Iterator<SolrDocument> iter = rsp.getResults().iterator();

              while (iter.hasNext()) {
                count += 1;
                if (recordSchema.equalsIgnoreCase("dc")) {
                  SolrDocument resultDoc = iter.next();
                  content = (String) resultDoc.getFieldValue("id");
                  out.write("<srw:record>");
                  out.write("<srw:recordPacking>xml</srw:recordPacking>");
                  out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                  out.write(
                      "<srw:recordData xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/loc.terms/relators/OTH\" xmlns:facets=\"info:srw/extension/4/facets\" >");
                  StringBuffer result = new StringBuffer("");

                  construct_lucene_dc(result, resultDoc);

                  out.write(result.toString());
                  out.write("</srw:recordData>");
                  out.write(
                      "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                  out.write("</srw:record>");
                }

                if (recordSchema.equalsIgnoreCase("solr")) {
                  SolrDocument resultDoc = iter.next();
                  content = (String) resultDoc.getFieldValue("id");
                  out.write("<srw:record>");
                  out.write("<srw:recordPacking>xml</srw:recordPacking>");
                  out.write("<srw:recordSchema>info:srw/schema/1/solr</srw:recordSchema>");
                  out.write("<srw:recordData xmlns:expand=\"http://www.kbresearch.nl/expand\">");
                  StringBuffer result = new StringBuffer("");
                  construct_lucene_solr(result, resultDoc);
                  out.write(result.toString());

                  out.write("</srw:recordData>");
                  out.write(
                      "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                  out.write("</srw:record>");
                }

                if (recordSchema.equalsIgnoreCase("dcx")) { // XML dcx response
                  out.write("<srw:record>");
                  out.write("<srw:recordPacking>xml</srw:recordPacking>");
                  out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                  out.write(
                      "<srw:recordData><srw_dc:dc xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/marc.relators/\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                  SolrDocument resultDoc = iter.next();
                  content = (String) resultDoc.getFieldValue("id");

                  String dcx_data =
                      helpers.getOAIdcx(
                          "http://services.kb.nl/mdo/oai?verb=GetRecord&identifier=" + content,
                          log);
                  if (x_collection.equalsIgnoreCase("ggc-thes")) {
                    dcx_data =
                        helpers.getOAIdcx(
                            "http://serviceso.kb.nl/mdo/oai?verb=GetRecord&identifier=" + content,
                            log);
                  }

                  if (!(dcx_data.length() == 0)) {
                    out.write(dcx_data);
                  } else {
                    // Should not do this!!

                    out.write("<srw:record>");
                    out.write("<srw:recordPacking>xml</srw:recordPacking>");
                    out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                    out.write(
                        "<srw:recordData xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/loc.terms/relators/OTH\" >");
                    StringBuffer result = new StringBuffer("");

                    construct_lucene_dc(result, resultDoc);

                    out.write(result.toString());
                    out.write("</srw:recordData>");
                    out.write(
                        "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                    out.write("</srw:record>");
                  }

                  out.write("</srw_dc:dc>");

                  StringBuffer expand_data;
                  boolean expand = false;

                  if (content.startsWith("GGC-THES:AC:")) {
                    String tmp_content = "";
                    tmp_content = content.replaceFirst("GGC-THES:AC:", "");
                    log.fatal("calling get");
                    expand_data =
                        new StringBuffer(
                            helpers.getExpand(
                                "http://www.kbresearch.nl/general/lod_new/get/"
                                    + tmp_content
                                    + "?format=rdf",
                                log));
                    log.fatal("get finini");

                    if (expand_data.toString().length() > 4) {

                      out.write(
                          "<srw_dc:expand xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                      out.write(expand_data.toString());
                      expand = true;
                    }
                  } else {
                    expand_data =
                        new StringBuffer(
                            helpers.getExpand(
                                "http://www.kbresearch.nl/ANP.cgi?q=" + content, log));
                    if (expand_data.toString().length() > 0) {
                      if (!expand) {
                        out.write(
                            "<srw_dc:expand xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                        expand = true;
                      }
                      out.write(expand_data.toString());
                    }
                  }
                  if (expand) {
                    out.write("</srw_dc:expand>");
                  }

                  out.write("</srw:recordData>");
                  out.write(
                      "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                  out.write("</srw:record>");
                }
              }
            }

            if ((do_err) || (numfound == 0)) {
              log.fatal("I haz suggestions");

              try {
                spellq.setParam("spellcheck", true);
                spellq.setQueryType("/spell");
                server = new CommonsHttpSolrServer(url);
                rsp = server.query(spellq);
                sdl = rsp.getResults();
                SpellCheckResponse spell;
                spell = rsp.getSpellCheckResponse();
                List<SpellCheckResponse.Suggestion> suggestions = spell.getSuggestions();
                if (suggestions.isEmpty() == false) {
                  suggest.append("<srw:extraResponseData>");
                  suggest.append("<suggestions>");

                  for (SpellCheckResponse.Suggestion sugg : suggestions) {
                    suggest.append("<suggestionfor>" + sugg.getToken() + "</suggestionfor>");
                    for (String item : sugg.getSuggestions()) {
                      suggest.append("<suggestion>" + item + "</suggestion>");
                    }
                    suggest.append("</suggestions>");
                    suggest.append("</srw:extraResponseData>");
                  }
                  do_sugg = true;
                }
              } catch (Exception e) {
                rsp = null;
                // log.fatal(e.toString());
              }
              ;
            }
            ;

            if (!do_err) {
              if (facet != null) {

                try {
                  fct = rsp.getFacetFields();
                  out.write("<srw:facets>");

                  for (String str : facet.split(",")) {
                    out.write("<srw:facet>");
                    out.write("<srw:facetType>");
                    out.write(str);
                    out.write("</srw:facetType>");

                    for (FacetField f : fct) {
                      log.debug(f.getName());
                      // if (f.getName().equals(str+"_str") || (f.getName().equals(str+"_date")) ) {
                      List<FacetField.Count> facetEnties = f.getValues();
                      for (FacetField.Count fcount : facetEnties) {
                        out.write("<srw:facetValue>");
                        out.write("<srw:valueString>");
                        out.write(helpers.xmlEncode(fcount.getName()));
                        out.write("</srw:valueString>");
                        out.write("<srw:count>");
                        out.write(Double.toString(fcount.getCount()));
                        out.write("</srw:count>");
                        out.write("</srw:facetValue>");
                        //   }
                      }
                    }
                    out.write("</srw:facet>");
                  }
                  out.write("</srw:facets>");
                  startRecord += 1;
                } catch (Exception e) {
                }

                // log.fatal(e.toString()); }
              }
            } else {
              out.write(diag);
            }
            out.write("</srw:records>"); // SearchRetrieve response footer
            String footer = this.SRW_FOOTER.replaceAll("\\$query", helpers.xmlEncode(query));
            footer = footer.replaceAll("\\$startRecord", (startRecord).toString());
            footer = footer.replaceAll("\\$maximumRecords", maximumRecords.toString());
            footer = footer.replaceAll("\\$recordSchema", recordSchema);
            if (do_sugg) {
              out.write(suggest.toString());
            }
            out.write(footer);
          } catch (MalformedURLException e) {
            out.write(e.getMessage());
          } catch (IOException e) {
            out.write("TO ERR is Human");
          }
        }
      }
    }
    out.close();
  }
Пример #8
0
  @Override
  protected boolean handlePost(RequestInfo requestInfo) throws ServletException {
    String gitSegment = requestInfo.gitSegment;
    HttpServletRequest request = requestInfo.request;
    HttpServletResponse response = requestInfo.response;
    Repository db = requestInfo.db;
    String pattern = requestInfo.relativePath;
    JSONObject requestObject = requestInfo.getJSONRequest();
    try {
      String commitToMerge = requestObject.optString(GitConstants.KEY_MERGE, null);
      if (commitToMerge != null) {
        boolean squash = requestObject.optBoolean(GitConstants.KEY_SQUASH, false);
        return merge(request, response, db, commitToMerge, squash);
      }

      String commitToRebase = requestObject.optString(GitConstants.KEY_REBASE, null);
      String rebaseOperation = requestObject.optString(GitConstants.KEY_OPERATION, null);
      if (commitToRebase != null) {
        return rebase(request, response, db, commitToRebase, rebaseOperation);
      }

      String commitToCherryPick = requestObject.optString(GitConstants.KEY_CHERRY_PICK, null);
      if (commitToCherryPick != null) {
        return cherryPick(request, response, db, commitToCherryPick);
      }

      String commitToRevert = requestObject.optString(GitConstants.KEY_REVERT, null);
      if (commitToRevert != null) {
        return revert(request, response, db, commitToRevert);
      }

      String newCommit = requestObject.optString(GitConstants.KEY_COMMIT_NEW, null);
      if (newCommit != null) return identifyNewCommitResource(request, response, db, newCommit);

      String reviewReqLogin = requestObject.optString(GitConstants.KEY_REVIEW_REQ_NOTIFY_LOGIN);
      if (reviewReqLogin != null && reviewReqLogin.length() != 0) {
        String reviewReqUrl = requestObject.optString(GitConstants.KEY_REVIEW_REQ_URL);
        String ReviewReqCommit = requestObject.optString(GitConstants.KEY_REVIEW_REQ_COMMIT);
        String ReviewReqAuthorName =
            requestObject.optString(GitConstants.KEY_REVIEW_REQ_AUTHOR_NAME);
        String ReviewMessage = requestObject.optString(GitConstants.KEY_REVIEW_REQ_MESSAGE);
        return sendNotification(
            request,
            response,
            db,
            reviewReqLogin,
            ReviewReqCommit,
            reviewReqUrl,
            ReviewReqAuthorName,
            ReviewMessage);
      }

      ObjectId refId = db.resolve(gitSegment);
      if (refId == null || !Constants.HEAD.equals(gitSegment)) {
        String msg = NLS.bind("Commit failed. Ref must be HEAD and is {0}", gitSegment);
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
      }

      String message = requestObject.optString(GitConstants.KEY_COMMIT_MESSAGE, null);
      if (message == null || message.isEmpty()) {
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(
                IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST,
                "Missing commit message.",
                null));
      }

      Git git = new Git(db);
      CommitCommand cc = git.commit();
      Config config = git.getRepository().getConfig();

      boolean amend =
          Boolean.parseBoolean(requestObject.optString(GitConstants.KEY_COMMIT_AMEND, null));
      boolean insertChangeId =
          GitUtils.isGerrit(config)
              || Boolean.parseBoolean(requestObject.optString(GitConstants.KEY_CHANGE_ID, null));

      String committerName = requestObject.optString(GitConstants.KEY_COMMITTER_NAME, null);
      String committerEmail = requestObject.optString(GitConstants.KEY_COMMITTER_EMAIL, null);
      String authorName = requestObject.optString(GitConstants.KEY_AUTHOR_NAME, null);
      String authorEmail = requestObject.optString(GitConstants.KEY_AUTHOR_EMAIL, null);

      // workaround of a bug in JGit which causes invalid
      // support of null values of author/committer name/email, see bug 352984
      PersonIdent defPersonIdent = new PersonIdent(db);
      if (committerName == null) committerName = defPersonIdent.getName();
      if (committerEmail == null) committerEmail = defPersonIdent.getEmailAddress();
      if (authorName == null) authorName = committerName;
      if (authorEmail == null) authorEmail = committerEmail;
      cc.setCommitter(committerName, committerEmail);
      cc.setAuthor(authorName, authorEmail);
      if (insertChangeId) cc.setInsertChangeId(true);

      // support for committing by path: "git commit -o path"
      if (!pattern.isEmpty()) {
        cc.setOnly(pattern);
      }

      try {
        // "git commit [--amend] -m '{message}' [-a|{path}]"
        RevCommit lastCommit = cc.setAmend(amend).setMessage(message).call();

        URI cloneLocation =
            BaseToCloneConverter.getCloneLocation(
                getURI(request), BaseToCloneConverter.COMMIT_REFRANGE);
        Commit commit = new Commit(cloneLocation, db, lastCommit, pattern);
        JSONObject result = commit.toJSON();
        OrionServlet.writeJSONResponse(
            request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
        return true;
      } catch (GitAPIException e) {
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(
                IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST,
                "An error occured when commiting.",
                e));
      } catch (UnmergedPathException e) {
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(
                IStatus.ERROR,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An internal error occured when commiting.",
                e));
      }
    } catch (Exception e) {
      return statusHandler.handleRequest(
          request,
          response,
          new ServerStatus(
              IStatus.ERROR,
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "An error occured when requesting a commit info.",
              e));
    }
  }
Пример #9
0
  public static void main(String args[]) throws Exception {
    boolean usePersistConnection = JokeClient.usePersistConnection;
    // default server name to connect
    String serverName = "localhost";

    // read optional serverName param from args if there is args.
    if (args.length > 0) {
      serverName = args[0];
    }

    String userName = null;

    String clientId = java.util.UUID.randomUUID().toString();
    /** user can pass a clientId as arg. */
    if (args.length > 1) {
      clientId = args[1];
    }
    /** user can pass usePersistConnection as arg. */
    if (args.length > 2) {
      usePersistConnection = Boolean.parseBoolean(args[2]);
    }
    // print configuration information
    printConfiguration(serverName, clientId, usePersistConnection);
    /**
     * we need to close resources after use them, so declared two named object, and auto close them
     * by jdk7.
     */
    try (InputStreamReader inputStreamReader = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader); ) {
      /** create connection to server .I do not want reconnect socket each time, so I re-use it. */
      Socket server = null;
      /** when use PersistConnection, will not re connect each time */
      if (usePersistConnection) {
        server = new Socket(serverName, SERVER_PORT);
      }
      // continue do job until break by user's quit command
      while (true) {
        if (!usePersistConnection) {
          server = new Socket(serverName, SERVER_PORT);
        }
        if (userName == null) {
          System.out.print(
              "Enter \""
                  + ClientCommandType.SetName
                  + " yourName\" to set your name,("
                  + QUIT_COMMAND
                  + ") to end: ");
        } else {
          System.out.print(
              "Enter "
                  + ClientCommandType.QueryNext
                  + " to query next joke/proverb, ("
                  + QUIT_COMMAND
                  + ") to end: ");
        }
        System.out.flush();

        String clientCommand = bufferedReader.readLine();
        /** validate input.must be not null and not empty. */
        if (clientCommand == null || clientCommand.isEmpty()) {
          System.out.println("command must not be null or empty");
          continue;
        }

        /**
         * More strict condition to quit. Must exactly equals quit command to quit, other than only
         * contains quit command in the host name.
         */
        if (clientCommand.equals(QUIT_COMMAND)) {
          System.out.println("Cancelled by user request.");
          // break is to quit here.
          break;
        }
        /** if userName is not set ,do not allow query command. */
        if (userName == null) {
          if (!clientCommand.startsWith(ClientCommandType.SetName.toString())) {
            System.out.println("You must enter name before QueryNext joke or proverb.");
            continue;
          } else {
            /**
             * client don't store input userName, instead ,it store verified and accepted userName
             * by server.
             */
            userName = getResponse(clientId, clientCommand, server)[0];
            continue;
          }
        }
        // didn't quit. userName is set. so do query and print.
        getResponse(clientId, clientCommand, server);

        if (!usePersistConnection) {
          server.close();
        }
      }
    } catch (IOException x) {
      System.out.println("Socket error. Client Terminated");
      x.printStackTrace();
    }
  }
Пример #10
0
 public boolean bInCheck() {
   return Boolean.parseBoolean(ask("check:b;"));
 }
Пример #11
0
    private ClassGraphics parse(Element grNode /*, boolean isRelation*/) {
      ClassGraphics newGraphics = new ClassGraphics();
      newGraphics.setShowFields(Boolean.parseBoolean(grNode.getAttribute(ATR_SHOW_FIELDS)));
      // newGraphics.setRelation( isRelation );

      NodeList list = grNode.getChildNodes();
      for (int k = 0; k < list.getLength(); k++) {
        if (list.item(k).getNodeType() != Node.ELEMENT_NODE) continue;
        Element node = (Element) list.item(k);
        String nodeName = node.getNodeName();

        Shape shape = null;
        if (EL_BOUNDS.equals(nodeName)) {
          Dim dim = getDim(node);
          newGraphics.setBounds(dim.x, dim.y, dim.width, dim.height);
          continue;
        } else if (EL_LINE.equals(nodeName)) {

          shape = makeLine(node, newGraphics);

        } else if (EL_RECT.equals(nodeName)) {

          Dim dim = getDim(node);
          Lineprops lp = getLineProps(node);
          shape =
              new Rect(
                  dim.x,
                  dim.y,
                  dim.width,
                  dim.height,
                  getColor(node),
                  isShapeFilled(node),
                  lp.strokeWidth,
                  lp.lineType);

        } else if (EL_OVAL.equals(nodeName)) {

          Dim dim = getDim(node);
          Lineprops lp = getLineProps(node);
          shape =
              new Oval(
                  dim.x,
                  dim.y,
                  dim.width,
                  dim.height,
                  getColor(node),
                  isShapeFilled(node),
                  lp.strokeWidth,
                  lp.lineType);

        } else if (EL_ARC.equals(nodeName)) {

          Dim dim = getDim(node);
          Lineprops lp = getLineProps(node);
          int startAngle = Integer.parseInt(node.getAttribute(ATR_START_ANGLE));
          int arcAngle = Integer.parseInt(node.getAttribute(ATR_ARC_ANGLE));
          shape =
              new Arc(
                  dim.x,
                  dim.y,
                  dim.width,
                  dim.height,
                  startAngle,
                  arcAngle,
                  getColor(node),
                  isShapeFilled(node),
                  lp.strokeWidth,
                  lp.lineType);

        } else if (EL_POLYGON.equals(nodeName)) {
          Lineprops lp = getLineProps(node);

          Polygon polygon =
              new Polygon(getColor(node), isShapeFilled(node), lp.strokeWidth, lp.lineType);

          // points
          NodeList points = node.getElementsByTagName(EL_POINT);
          int pointCount = points.getLength();
          // arrays of polygon points
          int[] xs = new int[pointCount];
          int[] ys = new int[pointCount];
          // arrays of FIXED information about polygon points
          int[] fxs = new int[pointCount];
          int[] fys = new int[pointCount];
          int width = newGraphics.getBoundWidth();
          int height = newGraphics.getBoundHeight();

          for (int j = 0; j < pointCount; j++) {
            FixedCoords fc = getFixedCoords((Element) points.item(j), width, height, null);
            xs[j] = fc.x;
            fxs[j] = fc.fx;
            ys[j] = fc.y;
            fys[j] = fc.fy;
          }

          polygon.setPoints(xs, ys, fxs, fys);
          shape = polygon;

        } else if (EL_IMAGE.equals(nodeName)) {

          Dim dim = getDim(node);
          // image path should be relative to the package xml
          String imgPath = node.getAttribute(ATR_PATH);
          String fullPath = FileFuncs.preparePathOS(getWorkingDir() + imgPath);
          shape = new Image(dim.x, dim.y, fullPath, imgPath, isShapeFixed(node));

        } else if (EL_TEXT.equals(nodeName)) {
          shape = makeText(node, newGraphics);
          /*
           * if (str.equals("*self")) newText.name = "self"; else if
           * (str.equals("*selfWithName")) newText.name = "selfName";
           */
        }

        if (shape != null) newGraphics.addShape(shape);
      }

      return newGraphics;
    }
Пример #12
0
 private boolean isShapeFixed(Element shape) {
   return Boolean.parseBoolean(shape.getAttribute(ATR_FIXED));
 }
Пример #13
0
  private void parsePort(PackageClass newClass, Element portNode) {
    String name = portNode.getAttribute(ATR_NAME);
    String type = portNode.getAttribute(ATR_TYPE);
    String x = portNode.getAttribute(ATR_X);
    String y = portNode.getAttribute(ATR_Y);
    String portConnection = portNode.getAttribute(ATR_PORT_CONNECTION);
    String strict = portNode.getAttribute(ATR_STRICT);
    String multi = portNode.getAttribute(ATR_MULTI);

    ClassField cf = newClass.getSpecField(name);

    if (newClass.getComponentType().hasSpec()) {

      if (name.indexOf(".") > -1) {
        // TODO - temporarily do not dig into hierarchy
        int idx = name.indexOf(".");
        String root = name.substring(0, idx);

        if (newClass.getSpecField(root) == null) {
          collector.collectDiagnostic(
              "Field "
                  + root
                  + " in class "
                  + newClass.getName()
                  + " is not declared in the specification, variable "
                  + type
                  + " "
                  + name
                  + " ignored ");
          return;
        }

        newClass.addSpecField(new ClassField(name, type));
      } else if (!TypeUtil.TYPE_THIS.equalsIgnoreCase(name)) {
        if (cf == null) {

          collector.collectDiagnostic(
              "Port "
                  + type
                  + " "
                  + name
                  + " in class "
                  + newClass.getName()
                  + " does not have the corresponding field in the specification");
        } else if (!cf.getType().equals(type)
            // type may be declared as "alias", however cf.getType() returns e.g. "double[]", ignore
            // it
            && !(cf.isAlias() && TypeUtil.TYPE_ALIAS.equals(type))) {

          collector.collectDiagnostic(
              "Port "
                  + type
                  + " "
                  + name
                  + " in class "
                  + newClass.getName()
                  + " does not match the field declared in the specification: "
                  + cf.getType()
                  + " "
                  + cf.getName());
        }
      }
    }

    Port newPort =
        new Port(
            name,
            type,
            Integer.parseInt(x),
            Integer.parseInt(y),
            portConnection,
            Boolean.parseBoolean(strict),
            Boolean.parseBoolean(multi));

    if (portNode.hasAttribute(ATR_ID)) newPort.setId(portNode.getAttribute(ATR_ID));

    Element gr;
    // open
    if ((gr = getElementByName(portNode, EL_OPEN)) != null
        && (gr = getElementByName(gr, EL_GRAPHICS)) != null) {
      newPort.setOpenGraphics(getGraphicsParser().parse(gr));
    }

    // closed
    if ((gr = getElementByName(portNode, EL_CLOSED)) != null
        && (gr = getElementByName(gr, EL_GRAPHICS)) != null) {
      newPort.setClosedGraphics(getGraphicsParser().parse(gr));
    }

    newClass.addPort(newPort);
  }
Пример #14
0
  private void parseField(PackageClass newClass, Element fieldNode) {
    String name = fieldNode.getAttribute(ATR_NAME);
    String type = fieldNode.getAttribute(ATR_TYPE);

    ClassField newField;

    if (newClass.getComponentType().hasSpec()) {
      if (name.indexOf(".") > -1) {
        // TODO - temporarily do not dig into hierarchy
        int idx = name.indexOf(".");
        String root = name.substring(0, idx);

        if (newClass.getSpecField(root) == null) {
          collector.collectDiagnostic(
              "Field "
                  + root
                  + " in class "
                  + newClass.getName()
                  + " is not declared in the specification, variable "
                  + type
                  + " "
                  + name
                  + " ignored ");
          return;
        }

        newField = new ClassField(name, type);
        newClass.addSpecField(newField);
      } else {
        newField = newClass.getSpecField(name);

        if (newField == null) {

          collector.collectDiagnostic(
              "Field "
                  + type
                  + " "
                  + name
                  + " in class "
                  + newClass.getName()
                  + " is not declared in the specification");
          return;
        } else if (!newField.getType().equals(type)) {

          collector.collectDiagnostic(
              "Field "
                  + type
                  + " "
                  + name
                  + " in class "
                  + newClass.getName()
                  + " does not match the field declared in the specification: "
                  + newField.getType()
                  + " "
                  + newField.getName());
          return;
        }
      }
    } else {
      newField = new ClassField(name, type);
      newClass.addSpecField(newField);
    }

    newField.setValue(fieldNode.hasAttribute(ATR_VALUE) ? fieldNode.getAttribute(ATR_VALUE) : null);
    newField.setDescription(fieldNode.getAttribute(ATR_DESCRIPTION));
    newField.setHidden(Boolean.parseBoolean(fieldNode.getAttribute(ATR_HIDDEN)));

    String nature = fieldNode.getAttribute(ATR_NATURE);
    if ("input".equals(nature)) newField.setInput(true);
    else if ("goal".equals(nature)) newField.setGoal(true);

    newClass.addField(newField);

    Element gr;
    // known
    if ((gr = getElementByName(fieldNode, EL_KNOWN)) != null
        && (gr = getElementByName(gr, EL_GRAPHICS)) != null) {
      newField.setKnownGraphics(getGraphicsParser().parse(gr));
    }
    // default
    if ((gr = getElementByName(fieldNode, EL_DEFAULT)) != null
        && (gr = getElementByName(gr, EL_GRAPHICS)) != null) {
      newField.setDefaultGraphics(getGraphicsParser().parse(gr));
    }
  }
Пример #15
0
  private PackageClass parseClass(Element classNode) {
    PackageClass newClass = new PackageClass();
    _package.getClasses().add(newClass);

    newClass.setComponentType(PackageClass.ComponentType.getType(classNode.getAttribute(ATR_TYPE)));
    newClass.setStatic(Boolean.parseBoolean(classNode.getAttribute(ATR_STATIC)));
    newClass.setName(getElementByName(classNode, EL_NAME).getTextContent());
    final String source = getElementStringByName(classNode, EL_FILE);
    if (source != null) {
      newClass.setSource(source);
    }
    newClass.setTarget(getElementStringByName(classNode, EL_EXTENDS));
    newClass.setDescription(getElementByName(classNode, EL_DESCRIPTION).getTextContent());
    newClass.setIcon(getElementByName(classNode, EL_ICON).getTextContent());

    // parse all variables declared in the corresponding specification
    if (newClass.getComponentType().hasSpec()) {
      final String newClassName = newClass.getName();
      try {
        switch (RuntimeProperties.getSpecParserKind()) {
          case REGEXP:
            {
              ClassList classList = new ClassList();
              SpecParser.parseSpecClass(newClassName, getWorkingDir(), classList);
              newClass.setSpecFields(classList.getType(newClassName).getFields());
              break;
            }
          case ANTLR:
            {
              if (specificationLoader == null) {
                specificationLoader =
                    new SpecificationLoader(new PackageSpecSourceProvider(_package), null);
              }
              final AnnotatedClass annotatedClass =
                  specificationLoader.getSpecification(newClassName);
              newClass.setSpecFields(annotatedClass.getFields());
              break;
            }
          default:
            throw new IllegalStateException("Undefined specification language parser");
        }
      } catch (SpecParseException e) {
        final String msg = "Unable to parse the specification of class " + newClassName;
        logger.error(msg, e);
        collector.collectDiagnostic(msg + "\nReason: " + e.getMessage() + "\nLine: " + e.getLine());
      }
    }

    // Graphics
    Element grNode = getElementByName(classNode, EL_GRAPHICS);
    newClass.addGraphics(
        getGraphicsParser().parse(grNode/*, newClass.getComponentType() == ComponentType.REL*/ ));

    Element painter;
    if ((painter = getElementByName(grNode, EL_PAINTER)) != null) {
      newClass.setPainterName(painter.getTextContent());
    }

    // Ports
    NodeList ports = classNode.getElementsByTagName(EL_PORT);
    for (int i = 0; i < ports.getLength(); i++) {
      parsePort(newClass, (Element) ports.item(i));
    }

    // Fields
    NodeList fields = classNode.getElementsByTagName(EL_FIELD);
    for (int i = 0; i < fields.getLength(); i++) {
      parseField(newClass, (Element) fields.item(i));
    }

    return newClass;
  }
  /**
   * Load client configuration from the properties map.
   *
   * @param prefix Prefix for the client properties.
   * @param in Properties map to load configuration from.
   * @throws GridClientException If parsing configuration failed.
   */
  public void load(String prefix, Properties in) throws GridClientException {
    while (prefix.endsWith(".")) prefix = prefix.substring(0, prefix.length() - 1);

    if (!prefix.isEmpty()) prefix += ".";

    String balancer = in.getProperty(prefix + "balancer");
    String connectTimeout = in.getProperty(prefix + "connectTimeout");
    String cred = in.getProperty(prefix + "credentials");
    String autoFetchMetrics = in.getProperty(prefix + "autoFetchMetrics");
    String autoFetchAttrs = in.getProperty(prefix + "autoFetchAttributes");
    String maxConnIdleTime = in.getProperty(prefix + "idleTimeout");
    String proto = in.getProperty(prefix + "protocol");
    String srvrs = in.getProperty(prefix + "servers");
    String tcpNoDelay = in.getProperty(prefix + "tcp.noDelay");
    String topRefreshFreq = in.getProperty(prefix + "topology.refresh");

    String sslEnabled = in.getProperty(prefix + "ssl.enabled");

    String sslProto = in.getProperty(prefix + "ssl.protocol", "TLS");
    String sslKeyAlg = in.getProperty(prefix + "ssl.key.algorithm", "SunX509");

    String keyStorePath = in.getProperty(prefix + "ssl.keystore.location");
    String keyStorePwd = in.getProperty(prefix + "ssl.keystore.password");
    String keyStoreType = in.getProperty(prefix + "ssl.keystore.type");

    String trustStorePath = in.getProperty(prefix + "ssl.truststore.location");
    String trustStorePwd = in.getProperty(prefix + "ssl.truststore.password");
    String trustStoreType = in.getProperty(prefix + "ssl.truststore.type");

    String dataCfgs = in.getProperty(prefix + "data.configurations");

    setBalancer(resolveBalancer(balancer));

    if (!F.isEmpty(connectTimeout)) setConnectTimeout(Integer.parseInt(connectTimeout));

    if (!F.isEmpty(cred)) {
      int idx = cred.indexOf(':');

      if (idx >= 0 && idx < cred.length() - 1) {
        setSecurityCredentialsProvider(
            new SecurityCredentialsBasicProvider(
                new SecurityCredentials(cred.substring(0, idx), cred.substring(idx + 1))));
      } else {
        setSecurityCredentialsProvider(
            new SecurityCredentialsBasicProvider(new SecurityCredentials(null, null, cred)));
      }
    }

    if (!F.isEmpty(autoFetchMetrics)) setAutoFetchMetrics(Boolean.parseBoolean(autoFetchMetrics));

    if (!F.isEmpty(autoFetchAttrs)) setAutoFetchAttributes(Boolean.parseBoolean(autoFetchAttrs));

    if (!F.isEmpty(maxConnIdleTime)) setMaxConnectionIdleTime(Integer.parseInt(maxConnIdleTime));

    if (!F.isEmpty(proto)) setProtocol(GridClientProtocol.valueOf(proto));

    if (!F.isEmpty(srvrs)) setServers(Arrays.asList(srvrs.replaceAll("\\s+", "").split(",")));

    if (!F.isEmpty(tcpNoDelay)) setTcpNoDelay(Boolean.parseBoolean(tcpNoDelay));

    if (!F.isEmpty(topRefreshFreq)) setTopologyRefreshFrequency(Long.parseLong(topRefreshFreq));

    //
    // SSL configuration section
    //

    if (!F.isEmpty(sslEnabled) && Boolean.parseBoolean(sslEnabled)) {
      GridSslBasicContextFactory factory = new GridSslBasicContextFactory();

      factory.setProtocol(F.isEmpty(sslProto) ? "TLS" : sslProto);
      factory.setKeyAlgorithm(F.isEmpty(sslKeyAlg) ? "SunX509" : sslKeyAlg);

      if (F.isEmpty(keyStorePath))
        throw new IllegalArgumentException("SSL key store location is not specified.");

      factory.setKeyStoreFilePath(keyStorePath);

      if (keyStorePwd != null) factory.setKeyStorePassword(keyStorePwd.toCharArray());

      factory.setKeyStoreType(F.isEmpty(keyStoreType) ? "jks" : keyStoreType);

      if (F.isEmpty(trustStorePath))
        factory.setTrustManagers(GridSslBasicContextFactory.getDisabledTrustManager());
      else {
        factory.setTrustStoreFilePath(trustStorePath);

        if (trustStorePwd != null) factory.setTrustStorePassword(trustStorePwd.toCharArray());

        factory.setTrustStoreType(F.isEmpty(trustStoreType) ? "jks" : trustStoreType);
      }

      setSslContextFactory(factory);
    }

    //
    // Data configuration section
    //

    if (!F.isEmpty(dataCfgs)) {
      String[] names = dataCfgs.replaceAll("\\s+", "").split(",");
      Collection<GridClientDataConfiguration> list = new ArrayList<>();

      for (String cfgName : names) {
        if (F.isEmpty(cfgName)) continue;

        String name = in.getProperty(prefix + "data." + cfgName + ".name");
        String bal = in.getProperty(prefix + "data." + cfgName + ".balancer");
        String aff = in.getProperty(prefix + "data." + cfgName + ".affinity");

        GridClientDataConfiguration dataCfg = new GridClientDataConfiguration();

        dataCfg.setName(F.isEmpty(name) ? null : name);
        dataCfg.setBalancer(resolveBalancer(bal));
        dataCfg.setAffinity(resolveAffinity(aff));

        list.add(dataCfg);
      }

      setDataConfigurations(list);
    }
  }