private static ORMSQLContext buildCreateColumnList(
      Object obj, com.corm.mapping.generated.Class clazz, String action, String ignoreFor) {

    //		String catalog = clazz.getKeyspace();
    String table = clazz.getColumnFamily();
    StringBuilder builder = new StringBuilder();
    builder.append(action + " ").append(table + " (");
    Set<String> columns = ORMPropertyListBuilder.build(obj, clazz.getName(), ignoreFor);
    Set<com.corm.mapping.generated.Column> refined =
        new LinkedHashSet<com.corm.mapping.generated.Column>();

    for (String column : columns) {
      //			String name = column.getName();
      builder.append(column + ',');
    }

    builder.trimToSize();
    builder = new StringBuilder(builder.substring(0, builder.length() - 1));
    builder.append(") VALUES (");

    for (int i = 0; i < columns.size(); i++) {
      //			if(column.isInject() && !canIgnore(column,ignoreFor)){
      //				builder.append(column.getHint()+",");
      //			}else{
      //				refined.add(column);
      builder.append("?,");
      //			}
    }

    String sql = builder.substring(0, builder.length() - 1) + ")";
    builder.setLength(0);
    builder = null;
    return new ORMSQLContext(sql, refined);
  }
 public static void __getNotes(String url, String token, Long[] ids)
     throws MoodleRestNotesException, MoodleRestException, UnsupportedEncodingException {
   if (MoodleCallRestWebService.isLegacy())
     throw new MoodleRestNotesException(MoodleRestException.NO_LEGACY);
   // MoodleWarning[] warnings=null;
   String functionCall = MoodleServices.CORE_NOTES_GET_NOTES.toString();
   StringBuilder data = new StringBuilder();
   data.append(URLEncoder.encode("wstoken", MoodleServices.ENCODING.toString()))
       .append("=")
       .append(URLEncoder.encode(token, MoodleServices.ENCODING.toString()));
   data.append("&")
       .append(URLEncoder.encode("wsfunction", MoodleServices.ENCODING.toString()))
       .append("=")
       .append(URLEncoder.encode(functionCall, MoodleServices.ENCODING.toString()));
   for (int i = 0; i < ids.length; i++) {
     if (ids[i] == null) throw new MoodleRestNotesException();
     else
       data.append("&")
           .append(URLEncoder.encode("notes[" + i + "]", MoodleServices.ENCODING.toString()))
           .append("=")
           .append(ids[i]);
   }
   data.trimToSize();
   NodeList elements = (new MoodleCallRestWebService()).__call(url, data.toString());
   // return warnings;
 }
Example #3
1
  @Override
  public void writeXml2ResultFileBody(
      final File file, final List<Defect> allDefectList, final String sourceFileFullPath)
      throws IOException {
    int size = allDefectList.size() * 1024;
    StringBuilder m;
    if (size < Integer.MAX_VALUE) m = new StringBuilder(size);
    else m = new StringBuilder(Integer.MAX_VALUE);

    m.append("\t<error filename=\"").append(sourceFileFullPath).append("\">\n");

    for (Defect defect : allDefectList) {
      m.append("\t\t<defect checker=\"").append(defect.getCheckerCode()).append("\">\n");
      for (Occurence o : defect.getOccurences()) {
        m.append("\t\t\t<occurence startLine=\"")
            .append(o.getStartLine())
            .append("\" ")
            .append("endLine=\"")
            .append(o.getEndLine())
            .append("\" ")
            .append(" message=\"")
            .append(o.getMessage())
            .append("\" />\n");
      }
      m.append("\t\t</defect>\n");
    }

    m.append("\t</error>\n");

    m.trimToSize();
    Files.append(m.toString(), file, Charsets.UTF_8);
  }
 @Override
 public CharSequence getDisplayContents() {
   EmailAddressParsedResult result = (EmailAddressParsedResult) getResult();
   StringBuilder contents = new StringBuilder(100);
   ParsedResult.maybeAppend(result.getEmailAddress(), contents);
   contents.trimToSize();
   return contents.toString();
 }
 public static void updateNotes(MoodleNote[] notes, MoodleWarning[] warnings)
     throws MoodleRestNotesException, UnsupportedEncodingException, MoodleRestException {
   if (MoodleCallRestWebService.isLegacy())
     throw new MoodleRestNotesException(MoodleRestException.NO_LEGACY);
   String functionCall = MoodleServices.CORE_NOTES_UPDATE_NOTES.toString();
   StringBuilder data = new StringBuilder();
   if (MoodleCallRestWebService.getAuth() == null) throw new MoodleRestNotesException();
   else data.append(MoodleCallRestWebService.getAuth());
   data.append("&")
       .append(URLEncoder.encode("wsfunction", MoodleServices.ENCODING.toString()))
       .append("=")
       .append(URLEncoder.encode(functionCall, MoodleServices.ENCODING.toString()));
   for (int i = 0; i < notes.length; i++) {
     data.append("&")
         .append(URLEncoder.encode("notes[" + i + "][id]", MoodleServices.ENCODING.toString()))
         .append("=")
         .append("" + notes[i].getNoteId());
     data.append("&")
         .append(
             URLEncoder.encode(
                 "notes[" + i + "][publishstate]", MoodleServices.ENCODING.toString()))
         .append("=")
         .append(notes[i].getPublishState());
     data.append("&")
         .append(URLEncoder.encode("notes[" + i + "][text]", MoodleServices.ENCODING.toString()))
         .append("=")
         .append(notes[i].getText());
     data.append("&")
         .append(URLEncoder.encode("notes[" + i + "][format]", MoodleServices.ENCODING.toString()))
         .append("=")
         .append("" + notes[i].getDescriptionFormat().toInt());
   }
   data.trimToSize();
   NodeList elements = MoodleCallRestWebService.call(data.toString());
   ArrayList<MoodleWarning> warn = null;
   MoodleWarning warning = null;
   for (int j = 0; j < elements.getLength(); j++) {
     String parent =
         elements
             .item(j)
             .getParentNode()
             .getParentNode()
             .getParentNode()
             .getParentNode()
             .getAttributes()
             .getNamedItem("name")
             .getNodeValue();
     String content = elements.item(j).getTextContent();
     String nodeName =
         elements.item(j).getParentNode().getAttributes().getNamedItem("name").getNodeValue();
     if (parent.equals("warnings")) {
       if (nodeName.equals("item")) {
         if (warn == null) {
           warn = new ArrayList<MoodleWarning>();
         }
         warning = new MoodleWarning(content);
         warn.add(warning);
       } else {
         warning.setMoodleWarningField(nodeName, content);
       }
     }
   }
   if (warn != null) {
     if (warnings != null) {
       warnings = new MoodleWarning[warn.size()];
       warnings = warn.toArray(warnings);
     }
   }
 }
 /**
  * Method to attach notes to users.
  *
  * @param notes MoodleNote[]
  * @return MoodleNote[]
  * @throws MoodleRestNotesException
  * @throws MoodleRestException
  */
 public static MoodleNote[] createNotes(MoodleNote[] notes)
     throws MoodleRestNotesException, MoodleRestException {
   int processedCount = 0;
   String functionCall =
       MoodleCallRestWebService.isLegacy()
           ? MoodleServices.MOODLE_NOTES_CREATE_NOTES.toString()
           : MoodleServices.CORE_NOTES_CREATE_NOTES.toString();
   try {
     StringBuilder data = new StringBuilder();
     if (MoodleCallRestWebService.getAuth() == null) throw new MoodleRestNotesException();
     else data.append(MoodleCallRestWebService.getAuth());
     data.append("&")
         .append(URLEncoder.encode("wsfunction", MoodleServices.ENCODING.toString()))
         .append("=")
         .append(URLEncoder.encode(functionCall, MoodleServices.ENCODING.toString()));
     for (int i = 0; i < notes.length; i++) {
       if (notes[i] == null)
         throw new MoodleRestNotesException(MoodleRestNotesException.NOTES_NULL);
       if (notes[i].getUserId() == null)
         throw new MoodleRestNotesException(MoodleRestNotesException.USERID_NOT_SET);
       else
         data.append("&")
             .append(
                 URLEncoder.encode("notes[" + i + "][userid]", MoodleServices.ENCODING.toString()))
             .append("=")
             .append(
                 URLEncoder.encode("" + notes[i].getUserId(), MoodleServices.ENCODING.toString()));
       if (notes[i].getPublishState() == null)
         throw new MoodleRestNotesException(MoodleRestNotesException.PUBLISHSTATE_NULL);
       else
         data.append("&")
             .append(
                 URLEncoder.encode(
                     "notes[" + i + "][publishstate]", MoodleServices.ENCODING.toString()))
             .append("=")
             .append(
                 URLEncoder.encode(
                     notes[i].getPublishState(), MoodleServices.ENCODING.toString()));
       if (notes[i].getCourseId() == null)
         throw new MoodleRestNotesException(MoodleRestNotesException.COURSEID_NOT_SET);
       else
         data.append("&")
             .append(
                 URLEncoder.encode(
                     "notes[" + i + "][courseid]", MoodleServices.ENCODING.toString()))
             .append("=")
             .append(
                 URLEncoder.encode(
                     "" + notes[i].getCourseId(), MoodleServices.ENCODING.toString()));
       if (notes[i].getText() == null)
         throw new MoodleRestNotesException(MoodleRestNotesException.TEXT_NULL);
       else
         data.append("&")
             .append(
                 URLEncoder.encode("notes[" + i + "][text]", MoodleServices.ENCODING.toString()))
             .append("=")
             .append(URLEncoder.encode(notes[i].getText(), MoodleServices.ENCODING.toString()));
       if (notes[i].getFormat() == null) {
         notes[i].setFormat("text");
       }
       if (notes[i].getFormat().equals("text") || notes[i].getFormat().equals("html"))
         data.append("&")
             .append(
                 URLEncoder.encode("notes[" + i + "][format]", MoodleServices.ENCODING.toString()))
             .append("=")
             .append(URLEncoder.encode(notes[i].getFormat(), MoodleServices.ENCODING.toString()));
       else throw new MoodleRestNotesException(MoodleRestNotesException.FORMAT_INCORRECT);
       if (notes[i].getClientNoteId() != null)
         data.append("&")
             .append(
                 URLEncoder.encode(
                     "notes[" + i + "][clientnoteid]", MoodleServices.ENCODING.toString()))
             .append("=")
             .append(
                 URLEncoder.encode(
                     notes[i].getClientNoteId(), MoodleServices.ENCODING.toString()));
     }
     data.trimToSize();
     NodeList elements = MoodleCallRestWebService.call(data.toString());
     for (int j = 0; j < elements.getLength(); j += 3, processedCount++) {
       for (int k = 0; k < 3; k++) {
         String content = elements.item(j + k).getTextContent();
         String nodeName =
             elements
                 .item(j + k)
                 .getParentNode()
                 .getAttributes()
                 .getNamedItem("name")
                 .getNodeValue();
         notes[processedCount].setMoodleNoteField(nodeName, content);
       }
     }
   } catch (UnsupportedEncodingException ex) {
     Logger.getLogger(MoodleRestNotes.class.getName()).log(Level.SEVERE, null, ex);
   }
   return notes;
 }
Example #7
0
 private String getSharedIntentData() {
   StringBuilder sb = new StringBuilder();
   sb.append(String.format("%s - Dmesg Log Capture\n", getString(R.string.app_name)));
   for (DmesgLine dmesgEntry : this.mListDmesgs) {
     sb.append(dmesgEntry.toString() + "\n");
   }
   sb.trimToSize();
   return sb.toString();
 }
Example #8
0
  @Override
  public void analyze(Document doc, InputStream in) throws IOException {
    content.setLength(0);

    TarInputStream zis = new TarInputStream(in);
    TarEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
      content.append(entry.getName()).append('\n');
    }
    content.trimToSize();
    doc.add(new TextField("full", content.toString(), Store.NO));
  }
Example #9
0
  @Override
  public String transform(Model m) {
    StringBuilder out = new StringBuilder();

    this.appendModel(out, m);

    String result = out.toString();
    out.setLength(0); // Attempt at saving memory (not enough)
    out.trimToSize();
    out = null;

    return result;
  }
Example #10
0
  /**
   * Method to that perform actions on the contacts provided a list of ids
   *
   * @throws MoodleRestMessageException
   * @throws MoodleRestException
   * @throws UnsupportedEncodingException
   */
  public static void actionContacts(Long[] contacts, MoodleContactAction action)
      throws MoodleRestMessageException, UnsupportedEncodingException, MoodleRestException {
    String functionCall = null;
    StringBuilder data = new StringBuilder();

    if (MoodleCallRestWebService.isLegacy())
      throw new MoodleRestException(MoodleRestException.NO_LEGACY);
    else {
      switch (action) {
        case DELETE:
          functionCall = MoodleServices.CORE_MESSAGE_DELETE_CONTACTS.name();
          break;
        case CREATE:
          functionCall = MoodleServices.CORE_MESSAGE_CREATE_CONTACTS.name();
          break;
        case BLOCK:
          functionCall = MoodleServices.CORE_MESSAGE_BLOCK_CONTACTS.name();
          break;
        case UNBLOCK:
          functionCall = MoodleServices.CORE_MESSAGE_UNBLOCK_CONTACTS.name();
          break;
      }
    }

    try {
      if (MoodleCallRestWebService.getAuth() == null) throw new MoodleRestUserException();
      else data.append(MoodleCallRestWebService.getAuth());

      data.append("&");
      data.append(URLEncoder.encode("wsfunction", MoodleServices.ENCODING.toString()));
      data.append("=");
      data.append(URLEncoder.encode(functionCall, MoodleServices.ENCODING.toString().toString()));

      for (int i = 0; i < contacts.length; i++) {
        if (contacts[i] < 1) {
          throw new MoodleRestMessageException(MoodleRestMessageException.PARAMETER_RANGE);
        } else {
          data.append("&");
          data.append(URLEncoder.encode("userids[" + i + "]", MoodleServices.ENCODING.toString()));
          data.append("=");
          data.append(contacts[i]);
        }
      }

      data.trimToSize();
      MoodleCallRestWebService.call(data.toString());

    } catch (final IOException ex) {
      Logger.getLogger(MoodleRestMessage.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Example #11
0
 public boolean isMobileBrowser(String BrowserAgent) {
   if (BrowserAgent == null) return false;
   StringBuilder c_input = new StringBuilder(Server.srv.MOBILE_BROWSER_REGEX);
   c_input.trimToSize();
   Pattern p = Pattern.compile(c_input.toString().toLowerCase());
   Matcher m = p.matcher(BrowserAgent.toLowerCase());
   if (m.find()) {
     Server.log(
         this,
         "found Mobile Browser [" + m.group() + "] (" + BrowserAgent + ")",
         Server.MSG_TRAFFIC,
         Server.LVL_VERBOSE);
     return true;
   } else return false;
 }
  private static String buildSelectColumnList(com.corm.mapping.generated.Class clazz) {
    //		String catalog = clazz.getKeyspace();
    String table = clazz.getColumnFamily();
    StringBuilder builder = new StringBuilder();
    builder.append("SELECT ");

    for (com.corm.mapping.generated.Column Column : clazz.getColumn()) {

      String column = Column.getName();
      builder.append(column + ',');
    }
    builder.trimToSize();
    String ret = builder.substring(0, builder.length() - 1) + " FROM " + table + " ";
    builder.setLength(0);
    builder = null;
    return ret;
  }
  public boolean checkCppcheckPermission() {
    String dexterHome = DexterConfig.getInstance().getDexterHome();

    Process changePermissionProcess = null;
    StringBuilder changePermissionCmd = new StringBuilder(500);

    String dexterBin = dexterHome + DexterUtil.FILE_SEPARATOR + "bin";
    String cppcheckHome = dexterBin + DexterUtil.FILE_SEPARATOR + "cppcheck";

    if (Strings.isNullOrEmpty(dexterBin)) {
      logger.error(
          "Can't initialize Cppcheck plugin, because the dexter_home/bin is not initialized");
      return false;
    }

    if (Strings.isNullOrEmpty(cppcheckHome)) {
      logger.error("Can't initialize Cppcheck plugin, because the cppcheckHome is not initialized");
      return false;
    }

    String baseCommand = DexterConfig.EXECUTION_PERMISSION + " ";
    changePermissionCmd
        .append(baseCommand)
        .append(cppcheckHome)
        .append(DexterUtil.FILE_SEPARATOR)
        .append("cppcheck");

    changePermissionCmd.trimToSize();

    try {
      changePermissionProcess = Runtime.getRuntime().exec(changePermissionCmd.toString());
    } catch (IOException e) {
      throw new DexterRuntimeException(
          e.getMessage() + " changePermissionCmd: " + changePermissionCmd.toString(), e);
    } finally {
      if (changePermissionProcess != null) {
        changePermissionProcess.destroy();
      }
    }

    return true;
  }
  protected String performSubstitution(
      final String template, final Map<String, String> substitutions)
      throws IllegalTemplateException {

    final StringBuilder outputBuffer = new StringBuilder();
    StringBuilder subBuffer = new StringBuilder();
    States state = States.LOOKING_FOR_START_DELIM;
    for (int i = 0; i < template.length(); i++) {
      final char c = template.charAt(i);

      if (state == States.LOOKING_FOR_START_DELIM) {
        if (c == START_DELIM) {
          state = States.INSIDE_START_DELIM;
          subBuffer = new StringBuilder();
        } else {
          outputBuffer.append(c);
        }
      } else if (state == States.INSIDE_START_DELIM) {
        if (c == END_DELIM) {
          final String variable = subBuffer.toString().replaceAll("\\s", "");
          String replacement = substitutions.get(variable);
          if (replacement == null) {
            throw new IllegalTemplateException(i, TEMPLATE_PROCESSOR_UNKNOWN_REPLACEMENT, template);
          }
          outputBuffer.append(replacement);
          state = States.LOOKING_FOR_START_DELIM;
        } else {
          subBuffer.append(c);
        }
      }
    }
    // if still inside a delim, template must be wrong, throw an exception
    if (state == States.INSIDE_START_DELIM) {
      throw new IllegalTemplateException(
          template.length(), TEMPLATE_PROCESSOR_UNCLOSED_VARIABLE, template);
    }

    outputBuffer.trimToSize();
    return outputBuffer.toString();
  }
  @Override
  public String formatLcdValue(final double VALUE) {
    final StringBuilder DEC_BUFFER = new StringBuilder(16);
    DEC_BUFFER.append("0");

    if (this.lcdDecimals > 0) {
      DEC_BUFFER.append(".");
    }

    for (int i = 0; i < this.lcdDecimals; i++) {
      DEC_BUFFER.append("0");
    }

    if (lcdScientificFormat) {
      DEC_BUFFER.append("E0");
    }
    DEC_BUFFER.trimToSize();

    final java.text.DecimalFormat DEC_FORMAT =
        new java.text.DecimalFormat(
            DEC_BUFFER.toString(), new java.text.DecimalFormatSymbols(java.util.Locale.US));

    return DEC_FORMAT.format(VALUE);
  }
  private static ORMSQLContext buildDeleteColumnList(
      Object obj, com.corm.mapping.generated.Class clazz) {

    //		String catalog = clazz.getKeyspace();
    String table = clazz.getColumnFamily();
    StringBuilder builder = new StringBuilder();
    builder.append("DELETE FROM " + table + " where ");

    Set<com.corm.mapping.generated.Column> properties =
        ORMPropertyListBuilder.buildDelete(obj, clazz.getName());

    for (com.corm.mapping.generated.Column column : properties) {
      String name = column.getName();
      builder.append(name).append("=? AND ");
    }

    builder.trimToSize();

    int backTrack = (properties.size() == 0) ? 4 : 0;

    String sql = builder.substring(0, builder.length() - backTrack);

    return new ORMSQLContext(sql, properties);
  }
 public static MoodleGradeArea[] getGradeDefinitions(
     Long[] cmIds, String areaName, boolean activeOnly, MoodleWarning[] warnings)
     throws MoodleRestGradeException, UnsupportedEncodingException, MoodleRestException {
   if (MoodleCallRestWebService.isLegacy()) {
     throw new MoodleRestGradeException(MoodleRestException.NO_LEGACY);
   }
   StringBuilder data = new StringBuilder();
   String functionCall = MoodleServices.CORE_GRADING_GET_DEFINITIONS.toString();
   if (MoodleCallRestWebService.getAuth() == null) {
     throw new MoodleRestGradeException();
   } else {
     data.append(MoodleCallRestWebService.getAuth());
   }
   data.append("&")
       .append(URLEncoder.encode("wsfunction", MoodleServices.ENCODING.toString()))
       .append("=")
       .append(URLEncoder.encode(functionCall, MoodleServices.ENCODING.toString()));
   for (int i = 0; i < cmIds.length; i++) {
     data.append("&")
         .append(URLEncoder.encode("cmids[" + i + "]", MoodleServices.ENCODING.toString()))
         .append("=")
         .append(URLEncoder.encode("" + cmIds[i], MoodleServices.ENCODING.toString()));
   }
   data.append("&")
       .append(URLEncoder.encode("areaname", MoodleServices.ENCODING.toString()))
       .append("=")
       .append(URLEncoder.encode("" + areaName, MoodleServices.ENCODING.toString()));
   if (activeOnly) {
     data.append("&")
         .append(URLEncoder.encode("activeonly", MoodleServices.ENCODING.toString()))
         .append("=")
         .append(URLEncoder.encode("" + (activeOnly ? 1 : 0), MoodleServices.ENCODING.toString()));
   }
   data.trimToSize();
   NodeList elements = MoodleCallRestWebService.call(data.toString());
   ArrayList<MoodleGradeArea> areas = null;
   ArrayList<MoodleWarning> warn = null;
   MoodleGradeArea gradeArea = null;
   MoodleGradeArea.GradeDefinition definition = null;
   MoodleGradeArea.GradeDefinition.Rubric.RubricCriteria rubricCriteria = null;
   Level level = null;
   Guide guide = null;
   GuideCriteria guideCriteria = null;
   GuideComment guideComment = null;
   MoodleWarning warning = null;
   for (int j = 0; j < elements.getLength(); j++) {
     String parent =
         elements
             .item(j)
             .getParentNode()
             .getParentNode()
             .getParentNode()
             .getParentNode()
             .getAttributes()
             .getNamedItem("name")
             .getNodeValue();
     String content = elements.item(j).getTextContent();
     String nodeName =
         elements.item(j).getParentNode().getAttributes().getNamedItem("name").getNodeValue();
     if (parent.equals("areas")) {
       if (nodeName.equals("cmid")) {
         if (areas == null) {
           areas = new ArrayList<MoodleGradeArea>();
         }
         gradeArea = new MoodleGradeArea();
         areas.add(gradeArea);
         gradeArea.setCmid(Long.parseLong(content));
       } else {
         gradeArea.setFieldValue(nodeName, content);
       }
     } else {
       if (parent.equals("definitions")) {
         if (nodeName.equals("id")) {
           definition = gradeArea.newGradeDefinition();
           definition.setId(Long.parseLong(content));
         } else {
           definition.setFieldValue(nodeName, content);
         }
       } else {
         if (parent.equals("rubric_criteria")) {
           if (nodeName.equals("id")) {
             rubricCriteria = definition.getRubric().newRubricCriteria();
             rubricCriteria.setId(Long.parseLong(content));
           } else {
             rubricCriteria.setFieldValue(nodeName, content);
           }
         } else {
           if (parent.equals("levels")) {
             if (nodeName.equals("id")) {
               level = rubricCriteria.newLevel();
               level.setId(Long.parseLong(content));
             } else {
               level.setFieldValue(nodeName, content);
             }
           } else {
             if (parent.equals("guide_criteria")) {
               if (nodeName.equals("id")) {
                 if (guide == null) {
                   guide = definition.newGuide();
                 }
                 guideCriteria = guide.newGuideCriteria();
                 guideCriteria.setId(Long.parseLong(content));
               } else {
                 guideCriteria.setFieldValue(nodeName, content);
               }
             } else {
               if (parent.equals("guide_comment")) {
                 if (nodeName.equals("id")) {
                   if (guide == null) {
                     guide = definition.newGuide();
                   }
                   guideComment = guide.newGuideComment();
                   guideComment.setId(Long.parseLong(content));
                 } else {
                   guideComment.setFieldValue(nodeName, content);
                 }
               } else {
                 if (parent.equals("warnings")) {
                   if (nodeName.equals("item")) {
                     if (warn == null) {
                       warn = new ArrayList<MoodleWarning>();
                     }
                     warning = new MoodleWarning();
                     warn.add(warning);
                     warning.setItem(content);
                   } else {
                     warning.setMoodleWarningField(nodeName, content);
                   }
                 }
               }
             }
           }
         }
       }
     }
   }
   if (warn != null) {
     warnings = new MoodleWarning[warn.size()];
     warnings = warn.toArray(warnings);
   }
   MoodleGradeArea[] results = null;
   if (areas != null) {
     results = new MoodleGradeArea[areas.size()];
     results = areas.toArray(results);
   }
   return results;
 }
  private List<ConnectorSplit> getSplitsForPartitions(
      CassandraTableHandle cassTableHandle, List<ConnectorPartition> partitions) {
    String schema = cassTableHandle.getSchemaName();
    String table = cassTableHandle.getTableName();
    HostAddressFactory hostAddressFactory = new HostAddressFactory();
    ImmutableList.Builder<ConnectorSplit> builder = ImmutableList.builder();

    // For single partition key column table, we can merge multiple partitions into a single split
    // by using IN CLAUSE in a single select query if the partitions have the same host list.
    // For multiple partition key columns table, we can't merge them into a single select query, so
    // keep them in a separate split.
    boolean singlePartitionKeyColumn = true;
    String partitionKeyColumnName = null;
    if (!partitions.isEmpty()) {
      singlePartitionKeyColumn =
          partitions.get(0).getTupleDomain().getNullableColumnDomains().size() == 1;
      if (singlePartitionKeyColumn) {
        String partitionId = partitions.get(0).getPartitionId();
        partitionKeyColumnName = partitionId.substring(0, partitionId.lastIndexOf('=') - 1);
      }
    }
    Map<Set<String>, Set<String>> hostsToPartitionKeys = new HashMap<>();
    Map<Set<String>, List<HostAddress>> hostMap = new HashMap<>();

    for (ConnectorPartition partition : partitions) {
      CassandraPartition cassandraPartition =
          checkType(partition, CassandraPartition.class, "partition");
      Set<Host> hosts =
          cassandraSession.getReplicas(schema, cassandraPartition.getKeyAsByteBuffer());
      List<HostAddress> addresses = hostAddressFactory.toHostAddressList(hosts);
      if (singlePartitionKeyColumn) {
        // host ip addresses
        ImmutableSet.Builder<String> sb = ImmutableSet.builder();
        for (HostAddress address : addresses) {
          sb.add(address.getHostText());
        }
        Set<String> hostAddresses = sb.build();
        // partition key values
        Set<String> values = hostsToPartitionKeys.get(hostAddresses);
        if (values == null) {
          values = new HashSet<>();
        }
        String partitionId = cassandraPartition.getPartitionId();
        values.add(partitionId.substring(partitionId.lastIndexOf('=') + 2));
        hostsToPartitionKeys.put(hostAddresses, values);
        hostMap.put(hostAddresses, addresses);
      } else {
        CassandraSplit split =
            new CassandraSplit(
                connectorId, schema, table, cassandraPartition.getPartitionId(), null, addresses);
        builder.add(split);
      }
    }
    if (singlePartitionKeyColumn) {
      for (Map.Entry<Set<String>, Set<String>> entry : hostsToPartitionKeys.entrySet()) {
        StringBuilder sb = new StringBuilder(partitionSizeForBatchSelect);
        int size = 0;
        for (String value : entry.getValue()) {
          if (size > 0) {
            sb.append(",");
          }
          sb.append(value);
          size++;
          if (size > partitionSizeForBatchSelect) {
            String partitionId = String.format("%s in (%s)", partitionKeyColumnName, sb.toString());
            CassandraSplit split =
                new CassandraSplit(
                    connectorId, schema, table, partitionId, null, hostMap.get(entry.getKey()));
            builder.add(split);
            size = 0;
            sb.setLength(0);
            sb.trimToSize();
          }
        }
        if (size > 0) {
          String partitionId = String.format("%s in (%s)", partitionKeyColumnName, sb.toString());
          CassandraSplit split =
              new CassandraSplit(
                  connectorId, schema, table, partitionId, null, hostMap.get(entry.getKey()));
          builder.add(split);
        }
      }
    }
    return builder.build();
  }
Example #19
0
  /**
   * Generates a model (class definition) from this table. The model includes indexes, primary keys,
   * default values, lengths, and nullables. information.
   *
   * <p>The caller may optionally set a destination package name, whether or not to include the
   * schema name (setting schema can be a problem when using the model between databases), and if to
   * automatically trim strings for those that have a maximum length.
   *
   * <p>
   *
   * @param packageName
   * @param annotateSchema
   * @param trimStrings
   * @return a complete model (class definition) for this table as a string
   */
  String generateModel(String packageName, boolean annotateSchema, boolean trimStrings) {

    // import statements
    Set<String> imports = Utils.newHashSet();
    imports.add(Serializable.class.getCanonicalName());
    imports.add(IQSchema.class.getCanonicalName());
    imports.add(IQTable.class.getCanonicalName());
    imports.add(IQIndexes.class.getCanonicalName());
    imports.add(IQIndex.class.getCanonicalName());
    imports.add(IQColumn.class.getCanonicalName());
    imports.add(IndexType.class.getCanonicalName());

    // fields
    StringBuilder fields = new StringBuilder();
    List<ColumnInspector> sortedColumns = Utils.newArrayList(columns.values());
    Collections.sort(sortedColumns);
    for (ColumnInspector col : sortedColumns) {
      fields.append(generateColumn(imports, col, trimStrings));
    }

    // build complete class definition
    StringBuilder model = new StringBuilder();
    if (!isNullOrEmpty(packageName)) {
      // package
      model.append("package " + packageName + ";");
      model.append(eol).append(eol);
    }

    // imports
    List<String> sortedImports = new ArrayList<String>(imports);
    Collections.sort(sortedImports);
    for (String imp : sortedImports) {
      model.append("import ").append(imp).append(';').append(eol);
    }
    model.append(eol);

    // @IQSchema
    if (annotateSchema && !isNullOrEmpty(schema)) {
      model.append('@').append(IQSchema.class.getSimpleName());
      model.append('(');
      AnnotationBuilder ap = new AnnotationBuilder();
      ap.addParameter(null, schema);
      model.append(ap);
      model.append(')').append(eol);
    }

    // @IQTable
    model.append('@').append(IQTable.class.getSimpleName());
    model.append('(');

    // IQTable annotation parameters
    AnnotationBuilder ap = new AnnotationBuilder();
    ap.addParameter("name", table);

    if (primaryKeys.size() > 1) {
      ap.addParameter("primaryKey", primaryKeys);
    }

    // finish @IQTable annotation
    model.append(ap);
    model.append(')').append(eol);

    // @IQIndexes
    // @IQIndex
    String indexAnnotations = generateIndexAnnotations();
    if (!StringUtils.isNullOrEmpty(indexAnnotations)) {
      model.append(indexAnnotations);
    }

    // class declaration
    String clazzName = ModelUtils.convertTableToClassName(table);
    model.append(format("public class {0} implements Serializable '{'", clazzName)).append(eol);
    model.append(eol);
    model.append("\tprivate static final long serialVersionUID = 1L;").append(eol);
    model.append(eol);

    // field declarations
    model.append(fields);

    // default constructor
    model.append("\t" + "public ").append(clazzName).append("() {").append(eol);
    model.append("\t}").append(eol);

    // end of class body
    model.append('}');
    model.trimToSize();
    return model.toString();
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * com.tangosol.util.processor.AbstractProcessor#processAll(java.util.Set)
   */
  @Override
  public Map processAll(Set entries) {
    final Map<String, String> result = new HashMap<>();
    if (entries == null || entries.size() == 0) {
      return result;
    }

    System.out.println("*** Total entries to be exported: " + entries.size());

    Iterator iter = entries.iterator();
    BinaryEntry bEntry = (BinaryEntry) iter.next();
    String nodeName = System.getProperty("app.nodeName");
    if (nodeName == null || nodeName.trim().isEmpty()) {
      nodeName =
          String.valueOf(
              bEntry
                  .getBackingMapContext()
                  .getManagerContext()
                  .getCacheService()
                  .getCluster()
                  .getLocalMember()
                  .getId());
    }

    final String expFilePath = this.expDir + File.separator + "exp_" + nodeName + ".csv";
    File expFile = new File(expFilePath);
    if (expFile.exists()) {
      expFile.delete();
    }

    System.out.println("*** Exporting data to file: " + expFile);
    BufferedWriter writer = null;
    StringBuilder buf = new StringBuilder(2048);
    int i = 1;
    try {
      writer = new BufferedWriter(new FileWriter(expFile, true));
      // Write header
      buf.append("id")
          .append(",")
          .append("firstName")
          .append(",")
          .append("lastName")
          .append(",")
          .append("gender")
          .append(",")
          .append("favSports")
          .append(",")
          .append("phoneNumber")
          .append(",")
          .append("email")
          .append(",")
          .append("wechat")
          .append(",")
          .append("company")
          .append(",")
          .append("spouse")
          .append(",")
          .append("manager")
          .append(",")
          .append("title")
          .append(",")
          .append("expertise")
          .append(",")
          .append("addr1")
          .append(",")
          .append("addr2")
          .append(",")
          .append("addr3")
          .append(",")
          .append("badgeNo")
          .append(",")
          .append("joinDate")
          .append(",")
          .append("empNo")
          .append(",")
          .append("comments");

      // Write data
      GuardContext ctxGuard = GuardSupport.getThreadContext();
      do {
        Employee emp = (Employee) bEntry.getValue();
        buf.append("\n")
            .append(emp.getId())
            .append(",")
            .append(emp.getFirstName())
            .append(",")
            .append(emp.getLastName())
            .append(",")
            .append(emp.getGender())
            .append(",")
            .append(emp.getFavSports())
            .append(",")
            .append(emp.getPhoneNumber())
            .append(",")
            .append(emp.getEmail())
            .append(",")
            .append(emp.getWechat())
            .append(",")
            .append(emp.getCompany())
            .append(",")
            .append(emp.getSpouse())
            .append(",")
            .append(emp.getManager())
            .append(",")
            .append(emp.getTitle())
            .append(",")
            .append(emp.getExpertise())
            .append(",")
            .append(emp.getAddr1())
            .append(",")
            .append(emp.getAddr2())
            .append(",")
            .append(emp.getAddr3())
            .append(",")
            .append(emp.getBadgeNo())
            .append(",")
            .append(emp.getJoinDate())
            .append(",")
            .append(emp.getEmpNo())
            .append(",")
            .append(emp.getComments());

        // Write file by batch
        if (i % 1000 == 0) {
          System.out.println("*** Flush " + (i / 1000));
          buf.trimToSize();
          writer.write(buf.toString());
          writer.flush();
          buf = null;
          buf = new StringBuilder(204800);
        }

        long cMillis = ctxGuard == null ? 0L : ctxGuard.getTimeoutMillis();
        if (ctxGuard != null) {
          if (i % 50 == 0) {
            ctxGuard.heartbeat(cMillis);
          }
        }

        i++;

        if (iter.hasNext()) {
          bEntry = (BinaryEntry) iter.next();
        } else {
          break;
        }
      } while (true);

      if (buf.length() > 0) {
        buf.trimToSize();
        writer.write(buf.toString());
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (writer != null) {
        try {
          writer.close();
          writer = null;
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

    System.out.println("*** Done data export, please check the file: " + expFile);

    return result;
  }
Example #21
0
 /**
  * Method to send messages between the caller and other users.
  *
  * @param messages
  * @return MoodleMessage[]
  * @throws MoodleRestMessageException
  * @throws MoodleRestException
  */
 public static MoodleMessage[] sendInstantMessages(MoodleMessage[] messages)
     throws MoodleRestMessageException, MoodleRestException {
   final StringBuilder data = new StringBuilder();
   if (MoodleCallRestWebService.isLegacy()) {
     throw new MoodleRestMessageException(MoodleRestException.NO_LEGACY);
   }
   final String functionCall = MoodleServices.CORE_MESSAGE_SEND_INSTANT_MESSAGES.name();
   try {
     if (MoodleCallRestWebService.getAuth() == null) {
       throw new MoodleRestMessageException();
     } else {
       data.append(MoodleCallRestWebService.getAuth());
     }
     data.append("&")
         .append(URLEncoder.encode("wsfunction", MoodleServices.ENCODING.toString()))
         .append("=")
         .append(URLEncoder.encode(functionCall, MoodleServices.ENCODING.toString()));
     for (int i = 0; i < messages.length; i++) {
       if (messages[i].getToUserId() == null) {
         throw new MoodleRestMessageException(MoodleRestMessageException.NO_RECIPIENT);
       }
       if (messages[i].getText() == null) {
         throw new MoodleRestMessageException(MoodleRestMessageException.NO_MESSAGE);
       }
       data.append("&")
           .append(
               URLEncoder.encode(
                   "messages[" + i + "][touserid]", MoodleServices.ENCODING.toString()))
           .append("=")
           .append(
               URLEncoder.encode(
                   Long.toString(messages[i].getToUserId()), MoodleServices.ENCODING.toString()));
       data.append("&")
           .append(
               URLEncoder.encode("messages[" + i + "][text]", MoodleServices.ENCODING.toString()))
           .append("=")
           .append(URLEncoder.encode(messages[i].getText(), MoodleServices.ENCODING.toString()));
       if (messages[i].getClientMsgId() != null) {
         data.append("&")
             .append(
                 URLEncoder.encode(
                     "messages[" + i + "][clientmsgid]", MoodleServices.ENCODING.toString()))
             .append("=")
             .append(
                 URLEncoder.encode(
                     messages[i].getClientMsgId(), MoodleServices.ENCODING.toString()));
       }
     }
     data.trimToSize();
     final NodeList elements = MoodleCallRestWebService.call(data.toString());
     for (int j = 0, i = -1; j < elements.getLength(); j++) {
       String parent =
           elements
               .item(j)
               .getParentNode()
               .getParentNode()
               .getParentNode()
               .getParentNode()
               .getNodeName();
       if (parent.equals("KEY")) {
         parent =
             elements
                 .item(j)
                 .getParentNode()
                 .getParentNode()
                 .getParentNode()
                 .getParentNode()
                 .getAttributes()
                 .getNamedItem("name")
                 .getNodeValue();
       }
       final String content = elements.item(j).getTextContent();
       final String nodeName =
           elements.item(j).getParentNode().getAttributes().getNamedItem("name").getNodeValue();
       if (parent.equals("RESPONSE") && nodeName.equals("msgid")) {
         i++;
         messages[i].setMsgId(Long.parseLong(content));
       } else {
         messages[i].setMoodleMesageField(nodeName, content);
         if (nodeName.equals("errormessage") && content.length() != 0) {
           throw new MoodleRestMessageException(content);
         }
       }
     }
   } catch (final UnsupportedEncodingException ex) {
     Logger.getLogger(MoodleRestMessage.class.getName()).log(Level.SEVERE, null, ex);
   }
   return messages;
 }