/*
   * Path: /auto/provider
   *
   * Generate the service provider description document.
   */
  public void doProvider(StaplerRequest request, StaplerResponse response)
      throws URISyntaxException, WebApplicationException, IOException {
    requireGET();

    ServiceProvider provider = new ServiceProvider();
    provider.setAbout(getProviderURI());
    provider.setTitle("OSLC Automation Provider for Hudson and Jenkins");
    provider.setPublisher(new Publisher("Eclipse Lyo", "urn:oslc:ServiceProvider"));

    final PrefixDefinition[] prefixDefinitions = getPrefixDefinitions();
    provider.setPrefixDefinitions(prefixDefinitions);

    Service service = new Service();
    provider.addService(service);
    service.setDomain(new URI(AutomationConstants.AUTOMATION_DOMAIN));
    service.setUsages(new URI[] {new URI(AutomationConstants.AUTOMATION_NAMESPACE + "Build")});

    QueryCapability queryJobs =
        new QueryCapability("Jobs", getBaseUriBuilder().path("queryJobs").build());
    queryJobs.addResourceType(new URI(AutomationConstants.TYPE_AUTOMATION_PLAN));
    service.addQueryCapability(queryJobs);

    QueryCapability queryRuns =
        new QueryCapability("Runs", getBaseUriBuilder().path("queryRuns").build());
    queryRuns.addResourceType(new URI(AutomationConstants.TYPE_AUTOMATION_RESULT));
    service.addQueryCapability(queryRuns);

    UriBuilder creationFactoryUriBuilder = getBaseUriBuilder().path("scheduleBuild");

    /*
     * Hudson uses crumbs to prevent CSRF attacks on POST requests. OSLC
     * interfaces cannot support this, however. To workaround -- for now at
     * least -- bake the crumb into the URL. Then we can use OAuth or
     * another authentication mechanism to avoid CSRF problems.
     */
    CrumbIssuer issuer = Hudson.getInstance().getCrumbIssuer();
    if (issuer != null) {
      String crumbName = issuer.getDescriptor().getCrumbRequestField();
      String crumb = issuer.getCrumb(null);
      creationFactoryUriBuilder.queryParam(crumbName, crumb);
    }

    CreationFactory scheduleBuild =
        new CreationFactory("Schedule Build", creationFactoryUriBuilder.build());
    scheduleBuild.addResourceType(new URI(AutomationConstants.TYPE_AUTOMATION_REQUEST));
    service.addCreationFactory(scheduleBuild);

    Dialog selectJobs = new Dialog("Select Job", getBaseUriBuilder().path("selectJob").build());
    selectJobs.addResourceType(new URI(AutomationConstants.TYPE_AUTOMATION_PLAN));
    selectJobs.setHintHeight("400px");
    selectJobs.setHintWidth("600px");
    service.addSelectionDialog(selectJobs);

    marshal(provider);
  }
  public void start() {
    String directory = TriplestoreUtil.getTriplestoreLocation();
    Dataset dataset = TDBFactory.createDataset(directory);

    ClientConfig clientConfig = new ClientConfig();
    for (Class providerClass : JenaProvidersRegistry.getProviders()) {
      clientConfig.register(providerClass);
    }
    Client rdfclient = ClientBuilder.newClient(clientConfig);
    System.out.println(
        AMESimAdapterAndTDBSubversionSyncClientWithRevision.oslcServiceProviderCatalogURI);
    Response response =
        rdfclient
            .target(
                AMESimAdapterAndTDBSubversionSyncClientWithRevision.oslcServiceProviderCatalogURI)
            .request("application/rdf+xml")
            .get();
    System.out.println(response.getStatus());
    ServiceProviderCatalog serviceProviderCatalog =
        response.readEntity(ServiceProviderCatalog.class);

    // list to collect all AMESim resources
    ArrayList<AbstractResource> oslcResourcesArrayList = new ArrayList<AbstractResource>();

    for (ServiceProvider serviceProvider : serviceProviderCatalog.getServiceProviders()) {
      System.out.println("serviceProvider " + serviceProvider.getAbout());
      if (serviceProvider.getAbout().toString().endsWith("/serviceProviders/" + fileName)) {

        for (Service service : serviceProvider.getServices()) {
          for (QueryCapability queryCapability : service.getQueryCapabilities()) {
            System.out.println(queryCapability.getQueryBase());
            Response queryCapabilityResponse =
                rdfclient
                    .target(queryCapability.getQueryBase())
                    .request("application/rdf+xml")
                    .get();
            System.out.println(queryCapabilityResponse.getStatus());
            if (queryCapability.getQueryBase().toString().endsWith("components")) {
              AMESimComponent[] oslcResources =
                  queryCapabilityResponse.readEntity(AMESimComponent[].class);
              oslcResourcesArrayList.addAll(
                  Arrays.asList(getResourcesWithVersion(oslcResources, revision)));
            }
            //						else if(queryCapability.getQueryBase().toString().endsWith("lines")){
            //							AMESimLine[] oslcResources =
            // queryCapabilityResponse.readEntity(AMESimLine[].class);
            //
            //	oslcResourcesArrayList.addAll(Arrays.asList(getResourcesWithVersion(oslcResources,
            // revision)));
            //						}
            else if (queryCapability.getQueryBase().toString().endsWith("parameters")) {
              AMESimParameter[] oslcResources =
                  queryCapabilityResponse.readEntity(AMESimParameter[].class);
              oslcResourcesArrayList.addAll(
                  Arrays.asList(getResourcesWithVersion(oslcResources, revision)));
            }
            //						else if(queryCapability.getQueryBase().toString().endsWith("outputports")){
            //							AMESimOutputPort[] oslcResources =
            // queryCapabilityResponse.readEntity(AMESimOutputPort[].class);
            //
            //	oslcResourcesArrayList.addAll(Arrays.asList(getResourcesWithVersion(oslcResources,
            // revision)));
            //						}
            //						else if(queryCapability.getQueryBase().toString().endsWith("inputports")){
            //							AMESimInputPort[] oslcResources =
            // queryCapabilityResponse.readEntity(AMESimInputPort[].class);
            //
            //	oslcResourcesArrayList.addAll(Arrays.asList(getResourcesWithVersion(oslcResources,
            // revision)));
            //						}
            //						else if(queryCapability.getQueryBase().toString().endsWith("model")){
            //							AMESimModel oslcResource =
            // queryCapabilityResponse.readEntity(AMESimModel.class);
            //							oslcResourcesArrayList.add(getResourceWithVersion(oslcResource,revision));
            //						}

          }
        }
      }
    }

    Object[] objects = oslcResourcesArrayList.toArray();

    Model model;
    Model tdbModel = dataset.getDefaultModel();
    try {
      model = JenaModelHelper.createJenaModel(objects);
      tdbModel.add(model);
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (DatatypeConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (OslcCoreApplicationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    tdbModel.close();
    dataset.close();
  }