Exemple #1
1
 private CIJobStatus deleteCI(CIJob job, List<String> builds) throws PhrescoException {
   S_LOGGER.debug("Entering Method CIManagerImpl.deleteCI(CIJob job)");
   S_LOGGER.debug("Job name " + job.getName());
   cli = getCLI(job);
   String deleteType = null;
   List<String> argList = new ArrayList<String>();
   S_LOGGER.debug("job name " + job.getName());
   S_LOGGER.debug("Builds " + builds);
   if (CollectionUtils.isEmpty(builds)) { // delete job
     S_LOGGER.debug("Job deletion started");
     S_LOGGER.debug("Command " + FrameworkConstants.CI_JOB_DELETE_COMMAND);
     deleteType = DELETE_TYPE_JOB;
     argList.add(FrameworkConstants.CI_JOB_DELETE_COMMAND);
     argList.add(job.getName());
   } else { // delete Build
     S_LOGGER.debug("Build deletion started");
     deleteType = DELETE_TYPE_BUILD;
     argList.add(FrameworkConstants.CI_BUILD_DELETE_COMMAND);
     argList.add(job.getName());
     StringBuilder result = new StringBuilder();
     for (String string : builds) {
       result.append(string);
       result.append(",");
     }
     String buildNos = result.substring(0, result.length() - 1);
     argList.add(buildNos);
     S_LOGGER.debug("Command " + FrameworkConstants.CI_BUILD_DELETE_COMMAND);
     S_LOGGER.debug("Build numbers " + buildNos);
   }
   try {
     int status = cli.execute(argList);
     String message = deleteType + " deletion started in jenkins";
     if (status == FrameworkConstants.JOB_STATUS_NOTOK) {
       deleteType = deleteType.substring(0, 1).toLowerCase() + deleteType.substring(1);
       message = "Error while deleting " + deleteType + " in jenkins";
     }
     S_LOGGER.debug("Delete CI Status " + status);
     S_LOGGER.debug("Delete CI Message " + message);
     return new CIJobStatus(status, message);
   } finally {
     if (cli != null) {
       try {
         cli.close();
       } catch (IOException e) {
         if (debugEnabled) {
           S_LOGGER.error(
               "Entered into catch block of CIManagerImpl.deleteCI(CIJob job) "
                   + e.getLocalizedMessage());
         }
       } catch (InterruptedException e) {
         if (debugEnabled) {
           S_LOGGER.error(
               "Entered into catch block of CIManagerImpl.deleteCI(CIJob job) "
                   + e.getLocalizedMessage());
         }
       }
     }
   }
 }
 @NotNull
 public static IpnbFile parseIpnbFile(
     @NotNull final CharSequence fileText, @NotNull final VirtualFile virtualFile)
     throws IOException {
   final String path = virtualFile.getPath();
   IpnbFileRaw rawFile = gson.fromJson(fileText.toString(), IpnbFileRaw.class);
   if (rawFile == null) {
     int nbformat = isIpythonNewFormat(virtualFile) ? 4 : 3;
     return new IpnbFile(Collections.emptyMap(), nbformat, Lists.newArrayList(), path);
   }
   List<IpnbCell> cells = new ArrayList<IpnbCell>();
   final IpnbWorksheet[] worksheets = rawFile.worksheets;
   if (worksheets == null) {
     for (IpnbCellRaw rawCell : rawFile.cells) {
       cells.add(rawCell.createCell());
     }
   } else {
     for (IpnbWorksheet worksheet : worksheets) {
       final List<IpnbCellRaw> rawCells = worksheet.cells;
       for (IpnbCellRaw rawCell : rawCells) {
         cells.add(rawCell.createCell());
       }
     }
   }
   return new IpnbFile(rawFile.metadata, rawFile.nbformat, cells, path);
 }
  private List<String> getOutOfTopicTweets(HttpServletRequest request) throws ServletException {

    String topicFile = request.getParameter("topicFile");

    List<String> listFiles = new ArrayList<String>();
    Properties properties = new Properties();
    try {
      properties.load(new FileInputStream(topicFile));
    } catch (FileNotFoundException e) {
      final String emsg =
          "missing file for out of topic tweets: '" + topicFile + "'" + e.getMessage();
      LOGGER.error(emsg);
      throw new ServletException(emsg, e);
    } catch (IOException e) {
      final String emsg =
          "can't read file for out of topic tweets: '" + topicFile + "'" + e.getMessage();
      LOGGER.error(emsg);
      throw new ServletException(emsg);
    }

    for (Entry<Object, Object> propertyEntry : properties.entrySet()) {
      String key = (String) propertyEntry.getKey();

      if (key.startsWith("outOfTopic")) {
        listFiles.add((String) propertyEntry.getValue());
      }
    }

    List<String> tweets = new ArrayList<String>();
    for (String filtFile : listFiles) {
      tweets.addAll(parseTweetsFromFile(filtFile));
    }
    return tweets;
  }
    @Override
    public HanabiraBoard deserialize(
        JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
      JsonObject boardsJsonObject = json.getAsJsonObject().get("boards").getAsJsonObject();
      Set<Map.Entry<String, JsonElement>> boardsSet = boardsJsonObject.entrySet();
      if (boardsSet.size() > 1) {
        throw new IllegalArgumentException("Few board entries received for a request");
      }
      Map.Entry<String, JsonElement> boardEntry = boardsSet.iterator().next();
      boardKey = boardEntry.getKey();
      JsonObject boardObject = boardEntry.getValue().getAsJsonObject();
      int pages = boardObject.get("pages").getAsInt();

      HanabiraBoard cachedBoard = Hanabira.getStem().findBoardByKey(boardKey);
      if (cachedBoard == null) {
        cachedBoard = new HanabiraBoard(boardKey, pages, null);
        Hanabira.getStem().saveBoard(cachedBoard);
      } else {
        cachedBoard.update(pages, null);
      }

      JsonElement pageElement = boardObject.get("page");
      int page = (pageElement == null) ? 0 : pageElement.getAsInt();

      List<Integer> threadsOnPageIds = new ArrayList<>();
      for (JsonElement threadElement : boardObject.getAsJsonArray("threads")) {
        threadsOnPageIds.add(
            createThreadWithPosts(threadElement.getAsJsonObject(), boardKey).getThreadId());
      }
      cachedBoard.updatePage(page, threadsOnPageIds);

      return cachedBoard;
    }
Exemple #5
0
  @Override
  public List<FeedValue> getFeed(final int count, final String relationshipEntityKey)
      throws NimbitsException {

    final User loggedInUser = getUser();
    final User feedUser = getFeedUser(relationshipEntityKey, loggedInUser);

    if (feedUser != null) {

      final Point point = getFeedPoint(feedUser);
      if (point == null) {
        return new ArrayList<FeedValue>(0);
      } else {
        final List<Value> values =
            RecordedValueServiceFactory.getInstance().getTopDataSeries(point, count, new Date());
        final List<FeedValue> retObj = new ArrayList<FeedValue>(values.size());

        for (final Value v : values) {
          if (!Utils.isEmptyString(v.getData())) {
            try {
              retObj.add(GsonFactory.getInstance().fromJson(v.getData(), FeedValueModel.class));
            } catch (JsonSyntaxException ignored) {

            }
          }
        }
        return retObj;
      }
    } else {
      return new ArrayList<FeedValue>(0);
    }
  }
Exemple #6
0
 private void deleteJsonJobs(ApplicationInfo appInfo, List<CIJob> selectedJobs)
     throws PhrescoException {
   try {
     if (CollectionUtils.isEmpty(selectedJobs)) {
       return;
     }
     Gson gson = new Gson();
     List<CIJob> jobs = getJobs(appInfo);
     if (CollectionUtils.isEmpty(jobs)) {
       return;
     }
     // all values
     Iterator<CIJob> iterator = jobs.iterator();
     // deletable values
     for (CIJob selectedInfo : selectedJobs) {
       while (iterator.hasNext()) {
         CIJob itrCiJob = iterator.next();
         if (itrCiJob.getName().equals(selectedInfo.getName())) {
           iterator.remove();
           break;
         }
       }
     }
     writeJsonJobs(appInfo, jobs, CI_CREATE_NEW_JOBS);
   } catch (Exception e) {
     throw new PhrescoException(e);
   }
 }
Exemple #7
0
 public List<CIBuild> getBuilds(CIJob job) throws PhrescoException {
   if (debugEnabled) {
     S_LOGGER.debug("Entering Method CIManagerImpl.getCIBuilds(CIJob job)");
   }
   List<CIBuild> ciBuilds = null;
   try {
     if (debugEnabled) {
       S_LOGGER.debug("getCIBuilds()  JobName = " + job.getName());
     }
     JsonArray jsonArray = getBuildsArray(job);
     ciBuilds = new ArrayList<CIBuild>(jsonArray.size());
     Gson gson = new Gson();
     CIBuild ciBuild = null;
     for (int i = 0; i < jsonArray.size(); i++) {
       ciBuild = gson.fromJson(jsonArray.get(i), CIBuild.class);
       setBuildStatus(ciBuild, job);
       String buildUrl = ciBuild.getUrl();
       String jenkinUrl = job.getJenkinsUrl() + ":" + job.getJenkinsPort();
       buildUrl =
           buildUrl.replaceAll(
               "localhost:" + job.getJenkinsPort(),
               jenkinUrl); // when displaying url it should display setup machine ip
       ciBuild.setUrl(buildUrl);
       ciBuilds.add(ciBuild);
     }
   } catch (Exception e) {
     if (debugEnabled) {
       S_LOGGER.debug(
           "Entering Method CIManagerImpl.getCIBuilds(CIJob job) " + e.getLocalizedMessage());
     }
   }
   return ciBuilds;
 }
 public IpnbCell createCell() {
   final IpnbCell cell;
   if (cell_type.equals("markdown")) {
     cell = new IpnbMarkdownCell(source, metadata);
   } else if (cell_type.equals("code")) {
     final List<IpnbOutputCell> outputCells = new ArrayList<IpnbOutputCell>();
     for (CellOutputRaw outputRaw : outputs) {
       outputCells.add(outputRaw.createOutput());
     }
     final Integer prompt = prompt_number != null ? prompt_number : execution_count;
     cell =
         new IpnbCodeCell(
             language == null ? "python" : language,
             input == null ? source : input,
             prompt,
             outputCells,
             metadata);
   } else if (cell_type.equals("raw")) {
     cell = new IpnbRawCell(source);
   } else if (cell_type.equals("heading")) {
     cell = new IpnbHeadingCell(source, level, metadata);
   } else {
     cell = null;
   }
   return cell;
 }
Exemple #9
0
  private CIJobStatus buildJob(CIJob job) throws PhrescoException {
    if (debugEnabled) {
      S_LOGGER.debug("Entering Method CIManagerImpl.buildJob(CIJob job)");
    }
    cli = getCLI(job);

    List<String> argList = new ArrayList<String>();
    argList.add(FrameworkConstants.CI_BUILD_JOB_COMMAND);
    argList.add(job.getName());
    try {
      int status = cli.execute(argList);
      String message = FrameworkConstants.CI_BUILD_STARTED;
      if (status == FrameworkConstants.JOB_STATUS_NOTOK) {
        message = FrameworkConstants.CI_BUILD_STARTING_ERROR;
      }
      return new CIJobStatus(status, message);
    } finally {
      if (cli != null) {
        try {
          cli.close();
        } catch (IOException e) {
          if (debugEnabled) {
            S_LOGGER.error(e.getLocalizedMessage());
          }
        } catch (InterruptedException e) {
          if (debugEnabled) {
            S_LOGGER.error(e.getLocalizedMessage());
          }
        }
      }
    }
  }
Exemple #10
0
 @Override
 public List clone() {
   List l = new List();
   l._jobs = _jobs.clone();
   for (int i = 0; i < l._jobs.length; ++i) l._jobs[i] = (Key) l._jobs[i].clone();
   return l;
 }
  private List<String> getTopicTweets(HttpServletRequest request) throws ServletException {

    final String topicFile = request.getParameter("topicFile");
    final String fullFilePath = topicFile;
    List<String> listFiles = new ArrayList<String>();

    Properties properties = new Properties();

    try {
      properties.load(new FileInputStream(fullFilePath));
    } catch (FileNotFoundException e) {
      LOGGER.error("missing file for in topic tweets: '" + fullFilePath + "'" + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      LOGGER.error("can't read file for in topic tweets: '" + fullFilePath + "'" + e.getMessage());
      e.printStackTrace();
    }

    for (Entry<Object, Object> propertyEntry : properties.entrySet()) {
      String key = (String) propertyEntry.getKey();
      if (key.startsWith("inTopic")) {
        listFiles.add((String) propertyEntry.getValue());
      }
    }

    List<String> tweets = new ArrayList<String>();
    for (String filtFile : listFiles) {
      tweets.addAll(parseTweetsFromFile(filtFile));
    }
    return tweets;
  }
 public static Object gsonToPrimitive(JsonElement element) {
   if (element.isJsonPrimitive()) {
     JsonPrimitive prim = element.getAsJsonPrimitive();
     if (prim.isString()) {
       return prim.getAsString();
     } else if (prim.isBoolean()) {
       return prim.getAsBoolean();
     } else if (prim.isNumber()) {
       return prim.getAsNumber();
     } else {
       throw new IllegalArgumentException("Unknown Gson primitive: " + prim);
     }
   } else if (element.isJsonArray()) {
     JsonArray array = element.getAsJsonArray();
     List<Object> list = new ArrayList<Object>();
     for (int i = 0; i < array.size(); i++) {
       list.add(gsonToPrimitive(array.get(i)));
     }
     return list;
   } else if (element.isJsonNull()) {
     return null;
   } else if (element.isJsonObject()) {
     Map<String, Object> map = new HashMap<String, Object>();
     for (Map.Entry<String, JsonElement> entry : element.getAsJsonObject().entrySet()) {
       map.put(entry.getKey(), gsonToPrimitive(entry.getValue()));
     }
     return map;
   } else {
     throw new IllegalArgumentException("Unknown Gson value: " + element);
   }
 }
 protected List<Card> loadCards() {
   List<CardData> data = loadRawData();
   List<Card> cards = new ArrayList<Card>();
   for (CardData cardData : data) {
     cards.add(new Card(cardData));
   }
   return cards;
 }
 @Override
 public List<String> deckNames() {
   List<String> deckNames = new ArrayList<String>();
   File deckDir = getDeckDir();
   File[] files = deckDir.listFiles();
   for (File deckFile : files) {
     deckNames.add(deckFile.getName());
   }
   return deckNames;
 }
Exemple #15
0
    private <T> JsonElement serializeAsElementOrArray(
        List<T> items, JsonSerializationContext context) {
      if (items.isEmpty()) {
        return null;
      }

      if (items.size() == 1) {
        return context.serialize(items.get(0));
      } else {
        return context.serialize(items);
      }
    }
Exemple #16
0
 private <T> List<T> deserializeAsArray(
     JsonElement json,
     JsonDeserializationContext context,
     TypeToken<T> typeToken,
     Type listOfT) {
   if (json.isJsonPrimitive()) {
     List<T> list = new ArrayList<T>();
     list.add((T) context.deserialize(json, typeToken.getType()));
     return list;
   } else {
     return context.deserialize(json, listOfT);
   }
 }
  public WikidataEntity parse(String json) throws WpParseException {
    JacksonTermedStatementDocument mwDoc;

    try {
      mwDoc = mapper.readValue(json, JacksonTermedStatementDocument.class);
    } catch (IOException e) {
      LOG.info("Error parsing: " + json);
      throw new WpParseException(e);
    }

    WikidataEntity record = new WikidataEntity(mwDoc.getEntityId().getId());

    // Aliases (multiple per language)
    for (List<MonolingualTextValue> vlist : mwDoc.getAliases().values()) {
      if (vlist.isEmpty()) continue;
      if (!validLanguage(vlist.get(0).getLanguageCode())) continue;
      Language lang = Language.getByLangCodeLenient(vlist.get(0).getLanguageCode());
      record.getAliases().put(lang, new ArrayList<String>());
      for (MonolingualTextValue v : vlist) {
        record.getAliases().get(lang).add(v.getText());
      }
    }

    // Descriptions (one per language)
    for (MonolingualTextValue v : mwDoc.getDescriptions().values()) {
      if (validLanguage(v.getLanguageCode())) {
        Language lang = Language.getByLangCodeLenient(v.getLanguageCode());
        record.getDescriptions().put(lang, v.getText());
      }
    }

    // Labels (one per language)
    for (MonolingualTextValue v : mwDoc.getLabels().values()) {
      if (validLanguage(v.getLanguageCode())) {
        Language lang = Language.getByLangCodeLenient(v.getLanguageCode());
        record.getLabels().put(lang, v.getText());
      }
    }

    // Claims (only for Item entities)
    if (mwDoc instanceof JacksonItemDocument) {
      for (List<JacksonStatement> statements :
          ((JacksonItemDocument) mwDoc).getJsonClaims().values()) {
        for (JacksonStatement s : statements) {
          record.getStatements().add(parseOneClaim(record, s));
        }
      }
    }

    return record;
  }
Exemple #18
0
  public List<RollupTask> parseRollupTasks(String json)
      throws BeanValidationException, QueryException {
    List<RollupTask> tasks = new ArrayList<RollupTask>();
    JsonParser parser = new JsonParser();
    JsonArray rollupTasks = parser.parse(json).getAsJsonArray();
    for (int i = 0; i < rollupTasks.size(); i++) {
      JsonObject taskObject = rollupTasks.get(i).getAsJsonObject();
      RollupTask task = parseRollupTask(taskObject, "tasks[" + i + "]");
      task.addJson(taskObject.toString().replaceAll("\\n", ""));
      tasks.add(task);
    }

    return tasks;
  }
Exemple #19
0
  public RollupTask parseRollupTask(JsonObject rollupTask, String context)
      throws BeanValidationException, QueryException {
    RollupTask task = m_gson.fromJson(rollupTask.getAsJsonObject(), RollupTask.class);

    validateObject(task);

    JsonArray rollups = rollupTask.getAsJsonObject().getAsJsonArray("rollups");
    if (rollups != null) {
      for (int j = 0; j < rollups.size(); j++) {
        JsonObject rollupObject = rollups.get(j).getAsJsonObject();
        Rollup rollup = m_gson.fromJson(rollupObject, Rollup.class);

        context = context + "rollup[" + j + "]";
        validateObject(rollup, context);

        JsonObject queryObject = rollupObject.getAsJsonObject("query");
        List<QueryMetric> queries = parseQueryMetric(queryObject, context);

        for (int k = 0; k < queries.size(); k++) {
          QueryMetric query = queries.get(k);
          context += ".query[" + k + "]";
          validateHasRangeAggregator(query, context);

          // Add aggregators needed for rollups
          SaveAsAggregator saveAsAggregator =
              (SaveAsAggregator) m_aggregatorFactory.createAggregator("save_as");
          saveAsAggregator.setMetricName(rollup.getSaveAs());

          TrimAggregator trimAggregator =
              (TrimAggregator) m_aggregatorFactory.createAggregator("trim");
          trimAggregator.setTrim(TrimAggregator.Trim.LAST);

          query.addAggregator(saveAsAggregator);
          query.addAggregator(trimAggregator);
        }

        rollup.addQueries(queries);
        task.addRollup(rollup);
      }
    }

    return task;
  }
 private static List<Element> getChildMessages(List<Element> messages, String $ref) {
   List<Element> childMessages =
       messages
           .stream()
           .filter(
               f ->
                   (f.source.$ref.equals($ref) && !f.name.contains("result"))
                       || (f.target.$ref.equals($ref) && f.name.contains("result")))
           .collect(Collectors.toList());
   return childMessages;
 }
  // it now resolves full paths using propertiesLoader
  private TwitterCache initTwitterCache() throws PersistenceFacadeException {

    final String consumerTokenFilename = this.properties.getProperty("application_token_path");
    final String consumerTokenFullPath = this.pl.getTokensDirectory() + consumerTokenFilename;

    final Token applicationToken = new Token(consumerTokenFullPath);
    final List<Token> userTokens = new ArrayList<Token>();

    int i = 0;
    String userTokenFilename;
    while ((userTokenFilename = this.properties.getProperty("user_token_" + i + "_path")) != null) {
      final String userTokenFullPath = this.pl.getTokensDirectory() + userTokenFilename;
      LOGGER.info("loading token from " + userTokenFullPath);
      userTokens.add(new Token(userTokenFullPath));
      i++;
    }
    WebFacade webFacade = WebFacade.getInstance(applicationToken, userTokens);

    return TwitterCache.getInstance(webFacade, this.persistenceFacade);
  }
  private List<String> parseTweetsFromFile(String listFilePath) throws ServletException {

    List<String> tweets = new ArrayList<String>();

    FileReader in = null;

    try {
      in = new FileReader(listFilePath);
    } catch (FileNotFoundException e) {
      String emsg = "cant find file '" + listFilePath + "'";
      throw new ServletException(emsg, e);
    }

    BufferedReader fileReader = new BufferedReader(in);

    String currentLine = null;

    try {
      currentLine = fileReader.readLine();
    } catch (IOException e) {
      throw new ServletException("cant read line from file '" + listFilePath + "'", e);
    }

    while (currentLine != null) {
      tweets.add(currentLine);
      try {
        currentLine = fileReader.readLine();
      } catch (IOException e) {
        throw new ServletException("cant read line from file '" + listFilePath + "'", e);
      }
    }

    try {
      fileReader.close();
    } catch (IOException e) {
      final String emsg = "cant close file '" + listFilePath + "'";
      throw new ServletException(e);
    }

    return tweets;
  }
 private static List<Element> getNextParent(List<Element> messages, String $ref) {
   List<Element> nextMessage =
       messages
           .stream()
           .filter(
               f ->
                   (f.source.$ref.equals($ref) && !f.name.contains("result"))
                       || (f.target.$ref.equals($ref) && f.name.contains("result"))
                           && !(f.source.equals(f.target)))
           .collect(Collectors.toList());
   return nextMessage;
 }
Exemple #24
0
 private void writeJsonJobs(ApplicationInfo appInfo, List<CIJob> jobs, String status)
     throws PhrescoException {
   try {
     if (jobs == null) {
       return;
     }
     Gson gson = new Gson();
     List<CIJob> existingJobs = getJobs(appInfo);
     if (CI_CREATE_NEW_JOBS.equals(status) || existingJobs == null) {
       existingJobs = new ArrayList<CIJob>();
     }
     existingJobs.addAll(jobs);
     FileWriter writer = null;
     File ciJobFile = new File(getCIJobPath(appInfo));
     String jobJson = gson.toJson(existingJobs);
     writer = new FileWriter(ciJobFile);
     writer.write(jobJson);
     writer.flush();
   } catch (Exception e) {
     throw new PhrescoException(e);
   }
 }
  private List<Long> parseUsersIdsFromFile(String listFilePath) throws ServletException {

    List<Long> ids = new ArrayList<Long>();
    try {
      BufferedReader fileReader = new BufferedReader(new FileReader(listFilePath));
      String currentLine = fileReader.readLine();
      while (currentLine != null) {
        LOGGER.debug(currentLine);
        long id = Long.parseLong(currentLine);
        ids.add(id);
        currentLine = fileReader.readLine();
      }
      fileReader.close();
    } catch (FileNotFoundException e) {
      String emsg = "cant find file '" + listFilePath + "'";
      throw new ServletException(emsg, e);
    } catch (IOException e) {
      String emsg = "cant read from file '" + listFilePath + "'";
      throw new ServletException(emsg, e);
    }
    return ids;
  }
  public String postFile(URLFetchService us, List<PostObj> postobjlist) throws Exception {
    int index;

    Gson gson;
    String linkID;
    List<String> linkList;
    HTTPRequest req;
    String param;

    gson = new Gson();

    linkID = createUID();
    linkList = new ArrayList<String>();
    for (index = 0; index < postobjlist.size(); index++) {
      linkList.add(postobjlist.get(index).filelink);
    }

    param =
        URLEncoder.encode("postlist", "UTF-8")
            + "="
            + URLEncoder.encode(gson.toJson(postobjlist), "UTF-8")
            + '&'
            + URLEncoder.encode("linkid", "UTF-8")
            + "="
            + URLEncoder.encode(linkID, "UTF-8")
            + '&'
            + URLEncoder.encode("linklist", "UTF-8")
            + "="
            + URLEncoder.encode(gson.toJson(linkList), "UTF-8");
    req =
        new HTTPRequest(
            new URL("http://tnfshmoe.appspot.com/postdf89ksfxsyx9sfdex09usdjksd"), HTTPMethod.POST);
    req.setPayload(param.getBytes());
    us.fetch(req);

    return linkID;
  }
Exemple #27
0
    public List<T> get(Class<?> clazz) {
      List<T> usableSegments = new ArrayList<T>();
      for (Segment segment : this) {
        if (!segment.isDisabled() && segment.shouldCheckType(clazz)) {
          usableSegments.add((T) segment);
        }
      }
      if (usableSegments.size() > 1) {
        Priority highestPriority = Priority.LOWEST;
        for (Segment segment : usableSegments) {
          if (highestPriority.ordinal() < segment.getPriority().ordinal()) {
            highestPriority = segment.getPriority();
          }
        }

        for (Iterator<T> it = usableSegments.iterator(); it.hasNext(); ) {
          Segment segment = it.next();
          if (segment.getPriority() != highestPriority) {
            it.remove();
          }
        }
      }
      return usableSegments;
    }
Exemple #28
0
 private boolean adaptExistingJobs(ApplicationInfo appInfo) {
   try {
     CIJob existJob = getJob(appInfo);
     S_LOGGER.debug("Going to get existing jobs to relocate!!!!!");
     if (existJob != null) {
       S_LOGGER.debug("Existing job found " + existJob.getName());
       boolean deleteExistJob = deleteCIJobFile(appInfo);
       Gson gson = new Gson();
       List<CIJob> existingJobs = new ArrayList<CIJob>();
       existingJobs.addAll(Arrays.asList(existJob));
       FileWriter writer = null;
       File ciJobFile = new File(getCIJobPath(appInfo));
       String jobJson = gson.toJson(existingJobs);
       writer = new FileWriter(ciJobFile);
       writer.write(jobJson);
       writer.flush();
       S_LOGGER.debug("Existing job moved to new type of project!!");
     }
     return true;
   } catch (Exception e) {
     S_LOGGER.debug("It is already adapted !!!!! ");
   }
   return false;
 }
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    int index;

    DatastoreService ds;
    MemcacheService ms;
    BlobstoreService bs;
    URLFetchService us;
    FileService fs;

    Map<String, List<BlobKey>> blobMap;
    BlobKey blobKey;
    BlobInfoFactory blobInfoFactory;
    BlobInfo blobInfo;

    int postCount;
    int postIndex;
    String postType;
    String postText;
    String postDelpw;
    String postShowgallery;
    DataObj dataObj;
    String filelink;

    String picUrl;
    HTTPResponse picRes;
    List<HTTPHeader> headerList;
    String picMime;
    String[] fileNamePart;
    AppEngineFile picFile;
    FileWriteChannel writeChannel;

    PostObj postObj;
    List<PostObj> postObjList;
    String linkID;

    resp.setCharacterEncoding("UTF-8");
    resp.setContentType("text/plain");

    try {
      ds = DatastoreServiceFactory.getDatastoreService();
      ms = MemcacheServiceFactory.getMemcacheService();
      bs = BlobstoreServiceFactory.getBlobstoreService();
      us = URLFetchServiceFactory.getURLFetchService();
      fs = FileServiceFactory.getFileService();
      blobInfoFactory = new BlobInfoFactory(ds);

      blobMap = bs.getUploads(req);
      postCount = Integer.valueOf(req.getParameter("input_post_count"));
      postObjList = new ArrayList<PostObj>();

      for (postIndex = 0; postIndex < postCount; postIndex++) {
        try {
          postType = req.getParameter("input_post_type_" + postIndex);
          if (postType == null) {
            continue;
          }

          postText = req.getParameter("input_post_text_" + postIndex);
          postDelpw = req.getParameter("input_post_delpw_" + postIndex);
          postShowgallery = req.getParameter("input_post_showgallery_" + postIndex);
          if (postShowgallery == null) {
            postShowgallery = "";
          }

          if (postType.equals("file") == true) {
            blobKey = blobMap.get("input_post_file_" + postIndex).get(0);
            if (blobKey == null) {
              throw new Exception();
            }

            dataObj = new DataObj();
            dataObj.fileid = createUID();
            dataObj.posttime = new Date().getTime();
            dataObj.delpw = postDelpw;
            dataObj.blobkey = blobKey;
            dataObj.putDB(ds);

            blobInfo = blobInfoFactory.loadBlobInfo(dataObj.blobkey);
            filelink =
                "http://"
                    + req.getServerName()
                    + "/down/"
                    + dataObj.fileid
                    + "/"
                    + blobInfo.getFilename();
            postObj =
                new PostObj(
                    dataObj.fileid,
                    filelink,
                    blobInfo.getSize(),
                    dataObj.posttime,
                    dataObj.delpw,
                    postShowgallery);
            postObjList.add(postObj);
          } else if (postType.equals("url") == true) {
            picUrl = postText;

            picRes = us.fetch(new URL(picUrl));
            headerList = picRes.getHeaders();
            picMime = "application/octet-stream";
            for (index = 0; index < headerList.size(); index++) {
              if (headerList.get(index).getName().compareToIgnoreCase("Content-Type") == 0) {
                picMime = headerList.get(index).getValue();
                break;
              }
            }

            fileNamePart = picUrl.split("/");

            picFile = fs.createNewBlobFile(picMime, fileNamePart[fileNamePart.length - 1]);
            writeChannel = fs.openWriteChannel(picFile, true);
            writeChannel.write(ByteBuffer.wrap(picRes.getContent()));
            writeChannel.closeFinally();

            dataObj = new DataObj();
            dataObj.fileid = createUID();
            dataObj.posttime = new Date().getTime();
            dataObj.delpw = postDelpw;
            dataObj.blobkey = fs.getBlobKey(picFile);
            dataObj.putDB(ds);

            blobInfo = blobInfoFactory.loadBlobInfo(dataObj.blobkey);
            filelink =
                "http://"
                    + req.getServerName()
                    + "/down/"
                    + dataObj.fileid
                    + "/"
                    + blobInfo.getFilename();
            postObj =
                new PostObj(
                    dataObj.fileid,
                    filelink,
                    blobInfo.getSize(),
                    dataObj.posttime,
                    dataObj.delpw,
                    postShowgallery);
            postObjList.add(postObj);
          }
        } catch (Exception e) {
        }
      }

      linkID = postFile(us, postObjList);

      if (req.getParameter("specflag") != null) {
        resp.getWriter().print("http://tnfshmoe.appspot.com/link.jsp?linkid=" + linkID);
      } else {
        resp.sendRedirect("http://tnfshmoe.appspot.com/link.jsp?linkid=" + linkID);
      }
    } catch (Exception e) {
    }
  }
 private static LifeLine getLifeLine(List<LifeLine> lifeLines, String $ref) {
   List<LifeLine> list =
       lifeLines.stream().filter(f -> f.getId().equals($ref)).collect(Collectors.toList());
   return list.get(0);
 }