Ejemplo n.º 1
0
 public void updateJob(ApplicationInfo appInfo, CIJob job) throws PhrescoException {
   if (debugEnabled) {
     S_LOGGER.debug(
         "Entering Method ProjectAdministratorImpl.updateJob(Project project, CIJob job)");
   }
   FileWriter writer = null;
   try {
     CIJobStatus jobStatus = configureJob(job, FrameworkConstants.CI_UPDATE_JOB_COMMAND);
     if (jobStatus.getCode() == -1) {
       throw new PhrescoException(jobStatus.getMessage());
     }
     if (debugEnabled) {
       S_LOGGER.debug("getCustomModules() ProjectInfo = " + appInfo);
     }
     updateJsonJob(appInfo, job);
   } catch (ClientHandlerException ex) {
     if (debugEnabled) {
       S_LOGGER.error(ex.getLocalizedMessage());
     }
     throw new PhrescoException(ex);
   } finally {
     if (writer != null) {
       try {
         writer.close();
       } catch (IOException e) {
         if (debugEnabled) {
           S_LOGGER.error(e.getLocalizedMessage());
         }
       }
     }
   }
 }
  /**
   * Get the URL of the file to download. This has not been modified from the original version.
   *
   * <p>For more information, please see: <a href=
   * "https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-portal-help#features">
   * https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-
   * portal-help#features</a>
   *
   * <p>Original code can be accessed at: <a href=
   * "https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip">
   * https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip </a>
   *
   * @see #login(String, String)
   * @see org.collegeboard.scoredwnld.client.FileInfo
   * @author CollegeBoard
   * @param accessToken Access token obtained from {@link #login(String, String)}
   * @param filePath File to download
   * @return FileInfo descriptor of file to download
   */
  private FileInfo getFileUrlByToken(String accessToken, String filePath) {

    Client client = getClient();
    WebResource webResource =
        client.resource(
            scoredwnldUrlRoot + "/pascoredwnld/file?tok=" + accessToken + "&filename=" + filePath);
    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
    if (response.getStatus() != 200) {
      throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    try {
      JSONObject json = new JSONObject(response.getEntity(String.class));
      FileInfo fileInfo = new FileInfo();
      fileInfo.setFileName(filePath);
      fileInfo.setFileUrl(String.valueOf(json.get("fileUrl")));
      return fileInfo;
    } catch (ClientHandlerException e) {
      log("Error: " + e.getMessage());
      e.printStackTrace();
    } catch (UniformInterfaceException e) {
      log("Error: " + e.getMessage());
      e.printStackTrace();
    } catch (JSONException e) {
      log("Error: " + e.getMessage());
      e.printStackTrace();
    }

    return null;
  }
  private List<AuthGroup> getAuthGroups(AuthToken token) {
    if (token != null && requestGroups) {

      AuthGroups authGroups = checkGroupCache(token);

      if (authGroups == null) {
        try {
          authGroups = getGroups(token.getUserId());
          cacheGroupInfo(token, authGroups);
        } catch (ClientHandlerException ex) {
          LOG.error(
              "Failure communicating with the auth service when retrieving groups: "
                  + ex.getMessage(),
              ex);
          LOG.error("X-PP-Groups will not be set.");
        } catch (Exception ex) {
          LOG.error("Failure in auth when retrieving groups: " + ex.getMessage(), ex);
          LOG.error("X-PP-Groups will not be set.");
        }
      }

      if (authGroups != null && authGroups.getGroups() != null) {
        return authGroups.getGroups();
      }
    }
    return new ArrayList<AuthGroup>();
  }
Ejemplo n.º 4
0
 public int getTotalBuilds(ApplicationInfo appInfo) throws PhrescoException {
   try {
     CIJob ciJob = getJob(appInfo);
     return getTotalBuilds(ciJob);
   } catch (ClientHandlerException ex) {
     S_LOGGER.error(ex.getLocalizedMessage());
     throw new PhrescoException(ex);
   }
 }
Ejemplo n.º 5
0
  public Map<String, ApplicationWrapper> getApplications() {
    Map<String, ApplicationWrapper> apps = new HashMap<String, ApplicationWrapper>();
    String csarUrl = getContainerUrl() + CONFIG.CSAR_LIST_REL_URL;

    try {
      String ret =
          this.jerseyClient
              .resource(csarUrl)
              .accept(MediaType.MEDIA_TYPE_WILDCARD)
              .get(String.class);

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document parse = builder.parse(new InputSource(new StringReader(ret)));
      NodeList elementsByTagName = parse.getElementsByTagName("Reference");

      for (int i = 0; i < elementsByTagName.getLength(); i++) {
        Node item = elementsByTagName.item(i);
        String csarBaseUrl = item.getAttributes().getNamedItem("xlink:href").getNodeValue();
        // "self" is no application
        if (item.getAttributes().getNamedItem("xlink:title").getNodeValue().equals("Self")) {
          continue;
        }

        // Create Self Service Base Url
        String selfServiceBaseUrl = csarBaseUrl + CONFIG.METADATA_FOLDER;
        String data = get(selfServiceBaseUrl + CONFIG.METADATA_FILE);
        if (data == null || data.isEmpty()) {
          continue;
        }

        // Create Application
        ApplicationWrapper application = ApplicationUnmarshaller.unmarshall(data);
        application.setSelfServiceBaseUrl(selfServiceBaseUrl);
        apps.put(selfServiceBaseUrl, application);
      }

    } catch (com.sun.jersey.api.client.ClientHandlerException e) {
      if (e.getCause() != null && e.getCause() instanceof java.net.ConnectException) {
        throw new CannotConnectToContainerException(getContainerUrl(), e.getCause());
      } else {
        throw new RuntimeException("Failed to get applications from " + csarUrl, e);
      }

    } catch (com.sun.jersey.api.client.UniformInterfaceException e) {
      throw new CannotConnectToContainerException(
          csarUrl, (e.getCause() != null) ? e.getCause() : e);

    } catch (Exception e) {
      throw new RuntimeException("Failed to get applications from " + csarUrl, e);
    }

    return apps;
  }
Ejemplo n.º 6
0
 // When already existing adapted project is created , need to move to new adapted project
 private boolean deleteCIJobFile(ApplicationInfo appInfo) throws PhrescoException {
   S_LOGGER.debug("Entering Method ProjectAdministratorImpl.deleteCI()");
   try {
     File ciJobInfo = new File(getCIJobPath(appInfo));
     return ciJobInfo.delete();
   } catch (ClientHandlerException ex) {
     S_LOGGER.error(
         "Entered into catch block of ProjectAdministratorImpl.deleteCI()"
             + ex.getLocalizedMessage());
     throw new PhrescoException(ex);
   }
 }
Ejemplo n.º 7
0
 @Override
 public void testConnection() throws ConnectionException {
   WnsToast toast = new WnsToastBuilder().bindingTemplateToastText01("test").build();
   try {
     // this fails every time due to jax error which is ok
     service.pushToast(
         "s-1-15-2-2411381248-444863693-3819932088-4077691928-1194867744-112853457-373132695",
         toast);
   } catch (ClientHandlerException e) {
     LOG.info("Windows Phone notifier added: " + e.toString());
   }
 }
  private FilterDirector authenticate(HttpServletRequest request) {
    final FilterDirector filterDirector = new FilterDirectorImpl();
    filterDirector.setResponseStatus(HttpStatusCode.UNAUTHORIZED);
    filterDirector.setFilterAction(FilterAction.RETURN);

    final String authToken = request.getHeader(CommonHttpHeader.AUTH_TOKEN.toString());
    ExtractorResult<String> account = null;
    AuthToken token = null;

    if (tenanted) {
      account = extractAccountIdentification(request);
    }

    final boolean allow = allowAccount(account);

    if ((!StringUtilities.isBlank(authToken) && allow)) {
      token = checkToken(account, authToken);

      if (token == null) {
        try {
          token = validateToken(account, StringUriUtilities.encodeUri(authToken));
          cacheUserInfo(token);
        } catch (ClientHandlerException ex) {
          LOG.error("Failure communicating with the auth service: " + ex.getMessage(), ex);
          filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR);
        } catch (AuthServiceException ex) {
          LOG.error("Failure in Auth-N: " + ex.getMessage());
          filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR);
        } catch (IllegalArgumentException ex) {
          LOG.error("Failure in Auth-N: " + ex.getMessage());
          filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR);
        } catch (Exception ex) {
          LOG.error("Failure in auth: " + ex.getMessage(), ex);
          filterDirector.setResponseStatus(HttpStatusCode.INTERNAL_SERVER_ERROR);
        }
      }
    }

    List<AuthGroup> groups = getAuthGroups(token);

    setFilterDirectorValues(
        authToken,
        token,
        delegable,
        filterDirector,
        account == null ? "" : account.getResult(),
        groups);

    return filterDirector;
  }
Ejemplo n.º 9
0
 public CIJobStatus buildJobs(ApplicationInfo appInfo, List<String> jobsName)
     throws PhrescoException {
   try {
     CIJobStatus jobStatus = null;
     for (String jobName : jobsName) {
       CIJob ciJob = getJob(appInfo, jobName);
       jobStatus = buildJob(ciJob);
     }
     return jobStatus;
   } catch (ClientHandlerException ex) {
     S_LOGGER.error(ex.getLocalizedMessage());
     throw new PhrescoException(ex);
   }
 }
Ejemplo n.º 10
0
 public CIJobStatus deleteJobs(ApplicationInfo appInfo, List<String> jobNames)
     throws PhrescoException {
   S_LOGGER.debug("Entering Method ProjectAdministratorImpl.deleteCI()");
   try {
     CIJobStatus deleteCI = null;
     for (String jobName : jobNames) {
       S_LOGGER.debug(" Deleteable job name " + jobName);
       CIJob ciJob = getJob(appInfo, jobName);
       // job and build numbers
       deleteCI = deleteCI(ciJob, null);
       S_LOGGER.debug("write back json data after job deletion successfull");
       deleteJsonJobs(appInfo, Arrays.asList(ciJob));
     }
     return deleteCI;
   } catch (ClientHandlerException ex) {
     S_LOGGER.error(
         "Entered into catch block of ProjectAdministratorImpl.deleteCI()"
             + ex.getLocalizedMessage());
     throw new PhrescoException(ex);
   }
 }
Ejemplo n.º 11
0
 // Code to add comments for Jira Issue
 public static void RestAddComment(String strComment, String strIssueID) {
   try {
     String auth = new String(Base64.encode("admin:admin"));
     String createCommentData = "{\"body\": \"" + strComment + "\"}\"";
     String comment =
         invokePostMethod(
             auth, BASE_URL + "/rest/api/2/issue/" + strIssueID + "/comment", createCommentData);
     System.out.println(comment);
     JSONObject issueObj = new JSONObject(comment);
     String newKey = issueObj.getString("id");
     System.out.println("id:" + newKey);
   } catch (AuthenticationException e) {
     System.out.println("Username or Password wrong!");
     e.printStackTrace();
   } catch (ClientHandlerException e) {
     System.out.println("Error invoking REST method");
     e.printStackTrace();
   } catch (JSONException e) {
     System.out.println("Invalid JSON output");
     e.printStackTrace();
   }
 }
Ejemplo n.º 12
0
 private int getTotalBuilds(CIJob job) throws PhrescoException {
   try {
     S_LOGGER.debug("Entering Method CIManagerImpl.getTotalBuilds(CIJob job)");
     S_LOGGER.debug("getCIBuilds()  JobName = " + job.getName());
     JsonArray jsonArray = getBuildsArray(job);
     Gson gson = new Gson();
     CIBuild ciBuild = null;
     if (jsonArray.size() > 0) {
       ciBuild = gson.fromJson(jsonArray.get(0), CIBuild.class);
       String buildUrl = ciBuild.getUrl();
       String jenkinsUrl = job.getJenkinsUrl() + ":" + job.getJenkinsPort();
       // display the jenkins running url in ci
       buildUrl = buildUrl.replaceAll("localhost:" + job.getJenkinsPort(), jenkinsUrl);
       // list
       String response = getJsonResponse(buildUrl + API_JSON);
       JsonParser parser = new JsonParser();
       JsonElement jsonElement = parser.parse(response);
       JsonObject jsonObject = jsonElement.getAsJsonObject();
       JsonElement resultJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_RESULT);
       JsonArray asJsonArray =
           jsonObject.getAsJsonArray(FrameworkConstants.CI_JOB_BUILD_ARTIFACTS);
       // when build result is not known
       if (jsonObject.get(FrameworkConstants.CI_JOB_BUILD_RESULT).toString().equals(STRING_NULL)) {
         // it indicates the job is in progress and not yet completed
         return -1;
         // when build is success and build zip relative path is unknown
       } else if (resultJson.getAsString().equals(CI_SUCCESS_FLAG) && asJsonArray.size() < 1) {
         return -1;
       } else {
         return jsonArray.size();
       }
     } else {
       return -1; // When the project is build first time,
     }
   } catch (ClientHandlerException ex) {
     S_LOGGER.error(ex.getLocalizedMessage());
     throw new PhrescoException(ex);
   }
 }
Ejemplo n.º 13
0
 public CIJobStatus deleteBuilds(ApplicationInfo appInfo, Map<String, List<String>> builds)
     throws PhrescoException {
   S_LOGGER.debug("Entering Method ProjectAdministratorImpl.deleteCI()");
   try {
     CIJobStatus deleteCI = null;
     Iterator iterator = builds.keySet().iterator();
     while (iterator.hasNext()) {
       String jobName = iterator.next().toString();
       List<String> deleteBuilds = builds.get(jobName);
       S_LOGGER.debug("jobName " + jobName + " builds " + deleteBuilds);
       CIJob ciJob = getJob(appInfo, jobName);
       // job and build numbers
       deleteCI = deleteCI(ciJob, deleteBuilds);
     }
     return deleteCI;
   } catch (ClientHandlerException ex) {
     S_LOGGER.error(
         "Entered into catch block of ProjectAdministratorImpl.deleteCI()"
             + ex.getLocalizedMessage());
     throw new PhrescoException(ex);
   }
 }
Ejemplo n.º 14
0
  @Override
  public void deployPackage(
      PackageModel packageRN,
      String token,
      InputStream stream,
      Map<String, DatabaseAction> associatedDatabases) {
    try {
      install(stream, packageRN, associatedDatabases);

      String name = packageRN.getUrlPath();
      if (packageRN.getUrlPath() == null || packageRN.getUrlPath().isEmpty()) name = "ROOT";

      name = name + PackageFileType.APP_WAR.getDotExtension();
      String file = packageRN.getName() + PackageFileType.APP_WAR.getDotExtension();
      progress.status("... deploying application: " + name, 1, LogLevel.INFO);
      requestTaskService.deploy(packageRN.getId(), name, file);
      progress.status("Archive version", 2, LogLevel.INFO);
      OPFEngine.RegistryService.archive(packageRN.getId());
      progress.status("Installation process has been completed", 2, LogLevel.INFO);
    } catch (ClientHandlerException e) {
      if (e.getCause() instanceof FileNotFoundException) {
        progress.status("Package archive has not been found", 1, LogLevel.ERROR);
      } else if (e.getCause() instanceof ConnectException) {
        progress.status("Connection refused", 1, LogLevel.ERROR);
      } else {
        progress.status("Occurred error", 1, LogLevel.ERROR);
      }
      logger.error(e.getMessage(), e);
    } catch (Exception e) {
      progress.status("Occurred error", 1, LogLevel.ERROR);
      logger.error(e.getMessage(), e);
    } finally {
      if (stream != null) {
        IOUtils.closeQuietly(stream);
      }
    }
  }
Ejemplo n.º 15
0
  @Override
  public void route(
      MutableHttpServletRequest servletRequest, MutableHttpServletResponse servletResponse)
      throws IOException, ServletException, URISyntaxException {
    DestinationLocation location = null;

    if (!StringUtilities.isBlank(defaultDst)) {
      servletRequest.addDestination(defaultDst, servletRequest.getRequestURI(), -1);
    }
    RouteDestination routingDestination = servletRequest.getDestination();
    String rootPath = "";

    if (routingDestination != null) {
      Destination configDestinationElement =
          destinations.get(routingDestination.getDestinationId());
      if (configDestinationElement == null) {
        LOG.warn(
            "Invalid routing destination specified: "
                + routingDestination.getDestinationId()
                + " for domain: "
                + domain.getId());
        ((HttpServletResponse) servletResponse).setStatus(HttpStatusCode.NOT_FOUND.intValue());
      } else {
        location =
            locationBuilder.build(
                configDestinationElement, routingDestination.getUri(), servletRequest);

        rootPath = configDestinationElement.getRootPath();
      }
    }

    if (location != null) {
      // According to the Java 6 javadocs the routeDestination passed into getContext:
      // "The given path [routeDestination] must begin with /, is interpreted relative to the
      // server's document root
      // and is matched against the context roots of other web applications hosted on this
      // container."
      final ServletContext targetContext = context.getContext(location.getUri().toString());

      if (targetContext != null) {
        // Capture this for Location header processing
        final HttpServletRequest originalRequest = (HttpServletRequest) servletRequest.getRequest();

        String uri =
            new DispatchPathBuilder(location.getUri().getPath(), targetContext.getContextPath())
                .build();
        final RequestDispatcher dispatcher = targetContext.getRequestDispatcher(uri);

        servletRequest.setRequestUrl(new StringBuffer(location.getUrl().toExternalForm()));
        servletRequest.setRequestUri(location.getUri().getPath());
        requestHeaderService.setVia(servletRequest);
        requestHeaderService.setXForwardedFor(servletRequest);
        if (dispatcher != null) {
          LOG.debug("Attempting to route to " + location.getUri());
          LOG.debug("Request URL: " + ((HttpServletRequest) servletRequest).getRequestURL());
          LOG.debug("Request URI: " + ((HttpServletRequest) servletRequest).getRequestURI());
          LOG.debug("Context path = " + targetContext.getContextPath());

          final long startTime = System.currentTimeMillis();
          try {
            reportingService.incrementRequestCount(routingDestination.getDestinationId());
            dispatcher.forward(servletRequest, servletResponse);
            final long stopTime = System.currentTimeMillis();
            reportingService.recordServiceResponse(
                routingDestination.getDestinationId(),
                servletResponse.getStatus(),
                (stopTime - startTime));
            responseHeaderService.fixLocationHeader(
                originalRequest,
                servletResponse,
                routingDestination,
                location.getUri().toString(),
                rootPath);
          } catch (ClientHandlerException e) {
            if (e.getCause() instanceof ReadLimitReachedException) {
              LOG.error("Error reading request content", e);
              servletResponse.sendError(
                  HttpStatusCode.REQUEST_ENTITY_TOO_LARGE.intValue(),
                  "Error reading request content");
              servletResponse.setLastException(e);
            } else {
              LOG.error("Connection Refused to " + location.getUri() + " " + e.getMessage(), e);
              ((HttpServletResponse) servletResponse)
                  .setStatus(HttpStatusCode.SERVICE_UNAVAIL.intValue());
            }
          }
        }
      }
    }
  }
Ejemplo n.º 16
0
  /**
   * Run a CLI programmatically.
   *
   * <p>It does not exit the JVM.
   *
   * <p>A CLI instance can be used only once.
   *
   * @param args options and arguments for the Oozie CLI.
   * @return '0' (success), '-1' (failure).
   */
  public synchronized int run(final String[] args) {

    CLIParser parser = new CLIParser("falcon", FALCON_HELP);

    parser.addCommand(ADMIN_CMD, "", "admin operations", createAdminOptions(), true);
    parser.addCommand(HELP_CMD, "", "display usage", new Options(), false);
    parser.addCommand(VERSION_CMD, "", "show client version", new Options(), false);
    parser.addCommand(
        ENTITY_CMD,
        "",
        "Entity operations like submit, suspend, resume, delete, status, definition, submitAndSchedule",
        entityOptions(),
        false);
    parser.addCommand(
        INSTANCE_CMD,
        "",
        "Process instances operations like running, status, kill, suspend, resume, rerun, logs",
        instanceOptions(),
        false);
    parser.addCommand(GRAPH_CMD, "", "graph operations", createGraphOptions(), true);

    try {
      CLIParser.Command command = parser.parse(args);
      int exitValue = 0;
      if (command.getName().equals(HELP_CMD)) {
        parser.showHelp();
      } else {
        CommandLine commandLine = command.getCommandLine();
        String falconUrl = getFalconEndpoint(commandLine);
        FalconClient client = new FalconClient(falconUrl, clientProperties);

        if (command.getName().equals(ADMIN_CMD)) {
          exitValue = adminCommand(commandLine, client, falconUrl);
        } else if (command.getName().equals(ENTITY_CMD)) {
          entityCommand(commandLine, client);
        } else if (command.getName().equals(INSTANCE_CMD)) {
          instanceCommand(commandLine, client);
        } else if (command.getName().equals(GRAPH_CMD)) {
          graphCommand(commandLine, client);
        }
      }

      return exitValue;
    } catch (ParseException ex) {
      ERR.get().println("Invalid sub-command: " + ex.getMessage());
      ERR.get().println();
      ERR.get().println(parser.shortHelp());
      ERR.get().println("Stacktrace:");
      ex.printStackTrace();
      return -1;
    } catch (ClientHandlerException ex) {
      ERR.get()
          .print(
              "Unable to connect to Falcon server, "
                  + "please check if the URL is correct and Falcon server is up and running\n");
      ERR.get().println("Stacktrace:");
      ex.printStackTrace();
      return -1;
    } catch (Exception ex) {
      ERR.get().println("Stacktrace:");
      ex.printStackTrace();
      return -1;
    }
  }