com.sun.jersey.api.client.filter.HTTPBasicAuthFilter Java Examples

The following examples show how to use com.sun.jersey.api.client.filter.HTTPBasicAuthFilter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HopServerTest.java    From hop with Apache License 2.0 6 votes vote down vote up
@Test
public void callStopHopServerRestService() throws Exception {
  WebResource status = mock( WebResource.class );
  doReturn( "<serverstatus>" ).when( status ).get( String.class );

  WebResource stop = mock( WebResource.class );
  doReturn( "Shutting Down" ).when( stop ).get( String.class );

  Client client = mock( Client.class );
  doCallRealMethod().when( client ).addFilter( any( HTTPBasicAuthFilter.class ) );
  doCallRealMethod().when( client ).getHeadHandler();
  doReturn( status ).when( client ).resource( "http://localhost:8080/hop/status/?xml=Y" );
  doReturn( stop ).when( client ).resource( "http://localhost:8080/hop/stopHopServer" );

  mockStatic( Client.class );
  when( Client.create( any( ClientConfig.class ) ) ).thenReturn( client );

  HopServer.callStopHopServerRestService( "localhost", "8080", "admin", "Encrypted 2be98afc86aa7f2e4bb18bd63c99dbdde" );

  // the expected value is: "Basic <base64 encoded username:password>"
  assertEquals( "Basic " + new String( Base64.getEncoder().encode( "admin:password".getBytes( "utf-8" ) ) ),
    getInternalState( client.getHeadHandler(), "authentication" ) );
}
 
Example #2
Source File: RepositoryCleanupUtilTest.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
@Test
public void authenticateLoginCredentials() throws Exception {
  RepositoryCleanupUtil util = mock( RepositoryCleanupUtil.class );
  doCallRealMethod().when( util ).authenticateLoginCredentials();

  setInternalState( util, "url", "http://localhost:8080/pentaho" );
  setInternalState( util, "username", "admin" );
  setInternalState( util, "password", "Encrypted 2be98afc86aa7f2e4bb18bd63c99dbdde" );

  WebResource resource = mock( WebResource.class );
  doReturn( "true" ).when( resource ).get( String.class );

  Client client = mock( Client.class );
  doCallRealMethod().when( client ).addFilter( any( HTTPBasicAuthFilter.class ) );
  doCallRealMethod().when( client ).getHeadHandler();
  doReturn( resource ).when( client ).resource( anyString() );

  mockStatic( Client.class );
  when( Client.create( any( ClientConfig.class ) ) ).thenReturn( client );
  util.authenticateLoginCredentials();

  // the expected value is: "Basic <base64 encoded username:password>"
  assertEquals( "Basic " + new String( Base64.getEncoder().encode( "admin:password".getBytes( "utf-8" ) ) ),
    getInternalState( client.getHeadHandler(), "authentication" ) );
}
 
Example #3
Source File: RepositoryCleanupUtil.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Use REST API to authenticate provided credentials
 * 
 * @throws Exception
 */
@VisibleForTesting
void authenticateLoginCredentials() throws Exception {
  KettleClientEnvironment.init();

  if ( client == null ) {
    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE );
    client = Client.create( clientConfig );
    client.addFilter( new HTTPBasicAuthFilter( username, Encr.decryptPasswordOptionallyEncrypted( password ) ) );
  }

  WebResource resource = client.resource( url + AUTHENTICATION + AdministerSecurityAction.NAME );
  String response = resource.get( String.class );

  if ( !response.equals( "true" ) ) {
    throw new Exception( Messages.getInstance().getString( "REPOSITORY_CLEANUP_UTIL.ERROR_0012.ACCESS_DENIED" ) );
  }
}
 
Example #4
Source File: UserRoleDelegate.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private void initManaged( PurRepositoryMeta repositoryMeta, IUser userInfo ) throws JSONException {
  String baseUrl = repositoryMeta.getRepositoryLocation().getUrl();
  String webService = baseUrl + ( baseUrl.endsWith( "/" ) ? "" : "/" ) + "api/system/authentication-provider";
  HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter( userInfo.getLogin(), userInfo.getPassword() );
  Client client = new Client();
  client.addFilter( authFilter );

  WebResource.Builder resource = client.resource( webService ).accept( MediaType.APPLICATION_JSON_TYPE );
  /**
   * if set, _trust_user_ needs to be considered. See other places in pur-plugin's:
   *
   * @link https://github.com/pentaho/pentaho-kettle/blob/8.0.0.0-R/plugins/pur/core/src/main/java/org/pentaho/di/repository/pur/PurRepositoryConnector.java#L97-L101
   * @link https://github.com/pentaho/pentaho-kettle/blob/8.0.0.0-R/plugins/pur/core/src/main/java/org/pentaho/di/repository/pur/WebServiceManager.java#L130-L133
   */
  if ( StringUtils.isNotBlank( System.getProperty( "pentaho.repository.client.attemptTrust" ) ) ) {
    resource = resource.header( TRUST_USER, userInfo.getLogin() );
  }
  String response = resource.get( String.class );
  String provider = new JSONObject( response ).getString( "authenticationType" );
  managed = "jackrabbit".equals( provider );
}
 
Example #5
Source File: CarteTest.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
@Test
public void callStopCarteRestService() throws Exception {
  WebResource status = mock( WebResource.class );
  doReturn( "<serverstatus>" ).when( status ).get( String.class );

  WebResource stop = mock( WebResource.class );
  doReturn( "Shutting Down" ).when( stop ).get( String.class );

  Client client = mock( Client.class );
  doCallRealMethod().when( client ).addFilter( any( HTTPBasicAuthFilter.class ) );
  doCallRealMethod().when( client ).getHeadHandler();
  doReturn( status ).when( client ).resource( "http://localhost:8080/kettle/status/?xml=Y" );
  doReturn( stop ).when( client ).resource( "http://localhost:8080/kettle/stopCarte" );

  mockStatic( Client.class );
  when( Client.create( any( ClientConfig.class ) ) ).thenReturn( client );

  Carte.callStopCarteRestService( "localhost", "8080", "admin", "Encrypted 2be98afc86aa7f2e4bb18bd63c99dbdde" );

  // the expected value is: "Basic <base64 encoded username:password>"
  assertEquals( "Basic " + new String( Base64.getEncoder().encode( "admin:password".getBytes( "utf-8" ) ) ),
    getInternalState( client.getHeadHandler(), "authentication" ) );
}
 
Example #6
Source File: CPEClientSession.java    From tr069-simulator with MIT License 6 votes vote down vote up
public CPEClientSession (CpeActions cpeActions, String username, String passwd, String authtype) {
	this.cpeActions = cpeActions;		
	this.authtype 	= authtype;
	this.username 	= username;
	this.passwd 	= passwd;		
	String urlstr 	= ((ConfParameter)this.cpeActions.confdb.confs.get(this.cpeActions.confdb.props.getProperty("MgmtServer_URL"))).value;  //"http://192.168.1.50:8085/ws?wsdl";
	System.out.println("ACS MGMT URL -------> " + urlstr);
	service = ResourceAPI.getInstance().getResourceAPI(urlstr);		
	if (username != null && passwd != null) {
		if (authtype.equalsIgnoreCase("digest")) {
			service.addFilter(new HTTPDigestAuthFilter(username, passwd));
		} else {
			service.addFilter(new HTTPBasicAuthFilter(username, passwd));
		}
		//System.out.println("==========================> " + username + " " + passwd);
	}
	//System.out.println(" 2nd time ==============> " + username + " " + passwd);
}
 
Example #7
Source File: JCRSolutionFileModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public JCRSolutionFileModel( final String url,
                             final String username,
                             final String password,
                             final int timeout ) {
  if ( url == null ) {
    throw new NullPointerException();
  }
  this.url = url;
  descriptionEntries = new HashMap<FileName, String>();

  final ClientConfig config = new DefaultClientConfig();
  config.getProperties().put( ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true );
  config.getProperties().put( ClientConfig.PROPERTY_READ_TIMEOUT, timeout );
  this.client = Client.create( config );
  this.client.addFilter( new CookiesHandlerFilter() ); // must be inserted before HTTPBasicAuthFilter
  this.client.addFilter( new HTTPBasicAuthFilter( username, password ) );
  this.majorVersion = "999";
  this.minorVersion = "999";
  this.releaseVersion = "999";
  this.buildVersion = "999";
  this.milestoneVersion = "999";
  this.loadTreePartially = Boolean.parseBoolean( PARTIAL_LOADING_ENABLED );
}
 
Example #8
Source File: MailgunService.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
@Override
public EmailSendingStatus sendEmail(EmailWrapper wrapper) {
    try (FormDataMultiPart email = parseToEmail(wrapper)) {
        Client client = Client.create();
        client.addFilter(new HTTPBasicAuthFilter("api", Config.MAILGUN_APIKEY));
        WebResource webResource =
                client.resource("https://api.mailgun.net/v3/" + Config.MAILGUN_DOMAINNAME + "/messages");

        ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE)
                .post(ClientResponse.class, email);

        return new EmailSendingStatus(response.getStatus(), response.getStatusInfo().getReasonPhrase());
    } catch (IOException e) {
        log.warning("Could not clean up resources after sending email: " + TeammatesException.toStringWithStackTrace(e));
        return new EmailSendingStatus(HttpStatus.SC_OK, e.getMessage());
    }
}
 
Example #9
Source File: MailgunServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("VariableDeclarationUsageDistance")
private ClientResponse sendComplexMessage(String recipient) {
  Client client = Client.create();
  client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY));
  FormDataMultiPart formData = new FormDataMultiPart();
  formData.field("from", "Mailgun User <mailgun@" + MAILGUN_DOMAIN_NAME + ">");
  formData.field("to", recipient);
  formData.field("subject", "Complex Mailgun Example");
  formData.field("html", "<html>HTML <strong>content</strong></html>");
  ClassLoader classLoader = getClass().getClassLoader();
  File txtFile = new File(classLoader.getResource("example-attachment.txt").getFile());
  formData.bodyPart(new FileDataBodyPart("attachment", txtFile, MediaType.TEXT_PLAIN_TYPE));
  WebResource webResource =
      client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages");
  return webResource
      .type(MediaType.MULTIPART_FORM_DATA_TYPE)
      .post(ClientResponse.class, formData);
}
 
Example #10
Source File: MailgunServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private ClientResponse sendComplexMessage(String recipient) {
  Client client = Client.create();
  client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY));
  WebResource webResource =
      client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages");
  FormDataMultiPart formData = new FormDataMultiPart();
  formData.field("from", "Mailgun User <mailgun@" + MAILGUN_DOMAIN_NAME + ">");
  formData.field("to", recipient);
  formData.field("subject", "Complex Mailgun Example");
  formData.field("html", "<html>HTML <strong>content</strong></html>");
  ClassLoader classLoader = getClass().getClassLoader();
  File txtFile = new File(classLoader.getResource("example-attachment.txt").getFile());
  formData.bodyPart(new FileDataBodyPart("attachment", txtFile, MediaType.TEXT_PLAIN_TYPE));
  return webResource
      .type(MediaType.MULTIPART_FORM_DATA_TYPE)
      .post(ClientResponse.class, formData);
}
 
Example #11
Source File: HopServer.java    From hop with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that HopServer is running and if so, shuts down the HopServer server
 *
 * @param hostname
 * @param port
 * @param username
 * @param password
 * @throws ParseException
 * @throws HopServerCommandException
 */
@VisibleForTesting
static void callStopHopServerRestService( String hostname, String port, String username, String password )
  throws ParseException, HopServerCommandException {
  // get information about the remote connection
  try {
    HopClientEnvironment.init();

    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE );
    Client client = Client.create( clientConfig );

    client.addFilter( new HTTPBasicAuthFilter( username, Encr.decryptPasswordOptionallyEncrypted( password ) ) );

    // check if the user can access the hop server. Don't really need this call but may want to check it's output at
    // some point
    String contextURL = "http://" + hostname + ":" + port + "/hop";
    WebResource resource = client.resource( contextURL + "/status/?xml=Y" );
    String response = resource.get( String.class );
    if ( response == null || !response.contains( "<serverstatus>" ) ) {
      throw new HopServerCommandException( BaseMessages.getString( PKG, "HopServer.Error.NoServerFound", hostname, ""
        + port ) );
    }

    // This is the call that matters
    resource = client.resource( contextURL + "/stopHopServer" );
    response = resource.get( String.class );
    if ( response == null || !response.contains( "Shutting Down" ) ) {
      throw new HopServerCommandException( BaseMessages.getString( PKG, "HopServer.Error.NoShutdown", hostname, ""
        + port ) );
    }
  } catch ( Exception e ) {
    throw new HopServerCommandException( BaseMessages.getString( PKG, "HopServer.Error.NoServerFound", hostname, ""
      + port ), e );
  }
}
 
Example #12
Source File: MailgunServlet.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("VariableDeclarationUsageDistance")
private ClientResponse sendSimpleMessage(String recipient) {
  Client client = Client.create();
  client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY));
  MultivaluedMapImpl formData = new MultivaluedMapImpl();
  formData.add("from", "Mailgun User <mailgun@" + MAILGUN_DOMAIN_NAME + ">");
  formData.add("to", recipient);
  formData.add("subject", "Simple Mailgun Example");
  formData.add("text", "Plaintext content");
  WebResource webResource =
      client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages");
  return webResource
      .type(MediaType.APPLICATION_FORM_URLENCODED)
      .post(ClientResponse.class, formData);
}
 
Example #13
Source File: AtlasBaseClient.java    From atlas with Apache License 2.0 5 votes vote down vote up
void initializeState(Configuration configuration, String[] baseUrls, UserGroupInformation ugi, String doAsUser) {
    this.configuration = configuration;
    Client client = getClient(configuration, ugi, doAsUser);

    if ((!AuthenticationUtil.isKerberosAuthenticationEnabled()) && basicAuthUser != null && basicAuthPassword != null) {
        final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(basicAuthUser, basicAuthPassword);
        client.addFilter(authFilter);
    }

    String activeServiceUrl = determineActiveServiceURL(baseUrls, client);
    atlasClientContext = new AtlasClientContext(baseUrls, client, ugi, doAsUser);
    service = client.resource(UriBuilder.fromUri(activeServiceUrl).build());
}
 
Example #14
Source File: ChannelFinderClientImpl.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
ChannelFinderClientImpl(URI uri, ClientConfig config, HTTPBasicAuthFilter httpBasicAuthFilter,
            ExecutorService executor) {
        Client client = Client.create(config);
        if (httpBasicAuthFilter != null) {
            client.addFilter(httpBasicAuthFilter);
        }
//        client.addFilter(new RawLoggingFilter(Logger.getLogger(RawLoggingFilter.class.getName())));
        client.setFollowRedirects(true);
        service = client.resource(uri.toString());
        this.executor = executor;
    }
 
Example #15
Source File: OlogClient.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
private OlogClient(URI ologURI, ClientConfig config, boolean withHTTPBasicAuthFilter, String username, String password) {
    config.getClasses().add(MultiPartWriter.class);
    Client client = Client.create(config);
    if (withHTTPBasicAuthFilter) {
        client.addFilter(new HTTPBasicAuthFilter(username, password));
    }
    if (Logger.getLogger(OlogClient.class.getName()).isLoggable(Level.ALL)) {
        client.addFilter(new RawLoggingFilter(Logger.getLogger(OlogClient.class.getName())));
    }
    client.setFollowRedirects(true);
    client.setConnectTimeout(3000);
    this.service = client.resource(UriBuilder.fromUri(ologURI).build());
}
 
Example #16
Source File: Carte.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that Carte is running and if so, shuts down the Carte server
 *
 * @param hostname
 * @param port
 * @param username
 * @param password
 * @throws ParseException
 * @throws CarteCommandException
 */
@VisibleForTesting
static void callStopCarteRestService( String hostname, String port, String username, String password )
  throws ParseException, CarteCommandException {
  // get information about the remote connection
  try {
    KettleClientEnvironment.init();

    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE );
    Client client = Client.create( clientConfig );

    client.addFilter( new HTTPBasicAuthFilter( username, Encr.decryptPasswordOptionallyEncrypted( password ) ) );

    // check if the user can access the carte server. Don't really need this call but may want to check it's output at
    // some point
    String contextURL = "http://" + hostname + ":" + port + "/kettle";
    WebResource resource = client.resource( contextURL + "/status/?xml=Y" );
    String response = resource.get( String.class );
    if ( response == null || !response.contains( "<serverstatus>" ) ) {
      throw new Carte.CarteCommandException( BaseMessages.getString( PKG, "Carte.Error.NoServerFound", hostname, ""
          + port ) );
    }

    // This is the call that matters
    resource = client.resource( contextURL + "/stopCarte" );
    response = resource.get( String.class );
    if ( response == null || !response.contains( "Shutting Down" ) ) {
      throw new Carte.CarteCommandException( BaseMessages.getString( PKG, "Carte.Error.NoShutdown", hostname, ""
          + port ) );
    }
  } catch ( Exception e ) {
    throw new Carte.CarteCommandException( BaseMessages.getString( PKG, "Carte.Error.NoServerFound", hostname, ""
        + port ), e );
  }
}
 
Example #17
Source File: ClientManagerClient.java    From jerseyoauth2 with MIT License 5 votes vote down vote up
public ClientAuthEntity authorizeClient(ClientEntity clientEntity, String scope)
{
	client.addFilter(new HTTPBasicAuthFilter("manager", "test".getBytes()));
	WebResource webResource = client.resource("http://localhost:9998/testsuite/rest/clientAuth");
	ClientAuthEntity clientAuthEntity = webResource.
			queryParam("client_id", clientEntity.getClientId()).
			queryParam("scope", scope).
			post(ClientAuthEntity.class);
	return clientAuthEntity;
}
 
Example #18
Source File: OlogClient.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
private OlogClient(URI ologURI, ClientConfig config, boolean withHTTPBasicAuthFilter, String username,
        String password, ExecutorService executor, boolean withRawFilter) {
    this.executor = executor;
    config.getClasses().add(MultiPartWriter.class);
    Client client = Client.create(config);
    if (withHTTPBasicAuthFilter) {
        client.addFilter(new HTTPBasicAuthFilter(username, password));
    }
    if (withRawFilter) {
        client.addFilter(new RawLoggingFilter(Logger.getLogger(OlogClient.class.getName())));
    }
    client.setFollowRedirects(true);
    service = client.resource(UriBuilder.fromUri(ologURI).build());
}
 
Example #19
Source File: JCRRepositoryTest.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testJCRRepository() throws FileSystemException {
    if ( GraphicsEnvironment.isHeadless() ) {
      return;
    }

    String url = "http://localhost:8080/pentaho";

    final ClientConfig config = new DefaultClientConfig();
    config.getProperties().put( ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true );
    Client client = Client.create( config );
    client.addFilter( new HTTPBasicAuthFilter( "joe", "password" ) );

    final WebResource resource = client.resource( url + "/api/repo/files/children?depth=-1&filter=*" );
    final RepositoryFileTreeDto tree =
      resource.path( "" ).accept( MediaType.APPLICATION_XML_TYPE ).get( RepositoryFileTreeDto.class );

    printDebugInfo( tree );

    final List<RepositoryFileTreeDto> children = tree.getChildren();
    for ( int i = 0; i < children.size(); i++ ) {
      final RepositoryFileTreeDto child = children.get( i );
      printDebugInfo( child );
    }

/*
    final FileSystemOptions fileSystemOptions = new FileSystemOptions();
    final DefaultFileSystemConfigBuilder configBuilder = new DefaultFileSystemConfigBuilder();
    configBuilder.setUserAuthenticator(fileSystemOptions, new StaticUserAuthenticator(url, "joe", "password"));
    FileObject fileObject = VFS.getManager().resolveFile(url, fileSystemOptions);

    System.out.println(fileObject);
    FileObject inventoryReport = fileObject.resolveFile("public/steel-wheels/reports/Inventory.prpt");
    System.out.println(inventoryReport);
    System.out.println(inventoryReport.exists());
    final FileContent content = inventoryReport.getContent();
    System.out.println(content.getAttribute("param-service-url"));
    */
  }
 
Example #20
Source File: PublishRestUtil.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Used for REST Jersey calls
 */
private void initRestService() {
  ClientConfig clientConfig = new DefaultClientConfig();
  clientConfig.getClasses().add( MultiPartWriter.class );
  clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE );
  client = Client.create( clientConfig );
  client.addFilter( new HTTPBasicAuthFilter( username, password ) );
}
 
Example #21
Source File: AtlasBaseClient.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
void initializeState(Configuration configuration, String[] baseUrls, UserGroupInformation ugi, String doAsUser) {
    this.configuration = configuration;
    Client client = getClient(configuration, ugi, doAsUser);

    if ((!AuthenticationUtil.isKerberosAuthenticationEnabled()) && basicAuthUser != null && basicAuthPassword != null) {
        final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(basicAuthUser, basicAuthPassword);
        client.addFilter(authFilter);
    }

    String activeServiceUrl = determineActiveServiceURL(baseUrls, client);
    atlasClientContext = new AtlasClientContext(baseUrls, client, ugi, doAsUser);
    service = client.resource(UriBuilder.fromUri(activeServiceUrl).build());
}
 
Example #22
Source File: JAXRSTester.java    From ice with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This operation checks posting updates to the server.
 */
@Test
public void checkPostingUpdates() {

	// Create the json message
	String message = "post={\"item_id\":\"5\", "
			+ "\"client_key\":\"1234567890ABCDEFGHIJ1234567890ABCDEFGHIJ\", "
			+ "\"posts\":[{\"type\":\"UPDATER_STARTED\",\"message\":\"\"},"
			+ "{\"type\":\"FILE_MODIFIED\","
			+ "\"message\":\"/tmp/file\"}]}";

	// Create the client
	Client jaxRSClient = Client.create();
	// Create the filter that will let us login with basic HTTP
	// authentication.
	final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter("ice",
			"veryice");
	jaxRSClient.addFilter(authFilter);
	// Add a filter for logging. This filter will automatically dump stuff
	// to stdout.
	jaxRSClient.addFilter(new LoggingFilter());

	// Get the handle to the server as a web resource
	WebResource webResource = jaxRSClient
			.resource("http://localhost:8080/ice");

	// Get the normal response from the server to make sure we can connect
	// to it
	webResource.accept(MediaType.TEXT_PLAIN).header("X-FOO", "BAR")
			.get(String.class);

	// Try posting something to the update page
	webResource.path("update").type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(String.class, message);

	return;
}
 
Example #23
Source File: MailgunServlet.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private ClientResponse sendSimpleMessage(String recipient) {
  Client client = Client.create();
  client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY));
  WebResource webResource =
      client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages");
  MultivaluedMapImpl formData = new MultivaluedMapImpl();
  formData.add("from", "Mailgun User <mailgun@" + MAILGUN_DOMAIN_NAME + ">");
  formData.add("to", recipient);
  formData.add("subject", "Simple Mailgun Example");
  formData.add("text", "Plaintext content");
  return webResource
      .type(MediaType.APPLICATION_FORM_URLENCODED)
      .post(ClientResponse.class, formData);
}
 
Example #24
Source File: TeamctiyRest.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Trigger a build on the Teamcity instance using vcs root
 *
 * @param repository - {@link Repository}
 * @param url - url to TeamCity server
 * @param username - TeamCity user name
 * @param password - TeamCity user password
 * @return "OK" if it worked. Otherwise, an error message.
 */
@GET
@Path(value = "testconnection")
@Produces("text/plain; charset=UTF-8")
public Response testconnection(
        @Context final Repository repository,
        @QueryParam("url") final String url,
        @QueryParam("username") final String username,
        @QueryParam("password") final String password,
        @QueryParam("debugon") final String isDebugOn) {

  String realPasswordValue = password;
  if (Constant.TEAMCITY_PASSWORD_SAVED_VALUE.equals(realPasswordValue)) {
    realPasswordValue = this.connectionSettings.getPassword(repository);
  }

  final Client restClient = Client.create(Constant.REST_CLIENT_CONFIG);
  restClient.addFilter(new HTTPBasicAuthFilter(username, realPasswordValue));

  try {
    final ClientResponse response = restClient.resource(url + "/app/rest/builds?locator=lookupLimit:0").accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
    if (ClientResponse.Status.OK == response.getClientResponseStatus()) {
      this.connectionSettings.savePassword(realPasswordValue, repository);
      return Response.ok(Constant.TEAMCITY_PASSWORD_SAVED_VALUE).build();
    } else {
      return Response.status(response.getClientResponseStatus()).entity(response.getEntity(String.class)).build();
    }
  } catch (final UniformInterfaceException | ClientHandlerException e) {
    return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
  } finally {
    restClient.destroy();
  }
}
 
Example #25
Source File: RangerUgSyncRESTClient.java    From ranger with Apache License 2.0 5 votes vote down vote up
public RangerUgSyncRESTClient(String policyMgrBaseUrls, String ugKeyStoreFile, String ugKeyStoreFilepwd,
		String ugKeyStoreType, String ugTrustStoreFile, String ugTrustStoreFilepwd, String ugTrustStoreType,
		String authenticationType, String principal, String keytab, String polMgrUsername, String polMgrPassword) {

	super(policyMgrBaseUrls, "", UserGroupSyncConfig.getInstance().getConfig());
	if (!(authenticationType != null && AUTH_KERBEROS.equalsIgnoreCase(authenticationType)
			&& SecureClientLogin.isKerberosCredentialExists(principal, keytab))) {
		setBasicAuthInfo(polMgrUsername, polMgrPassword);
	}

	if (isSSL()) {
		setKeyStoreType(ugKeyStoreType);
		setTrustStoreType(ugTrustStoreType);
		KeyManager[] kmList = getKeyManagers(ugKeyStoreFile, ugKeyStoreFilepwd);
		TrustManager[] tmList = getTrustManagers(ugTrustStoreFile, ugTrustStoreFilepwd);
		SSLContext sslContext = getSSLContext(kmList, tmList);
		ClientConfig config = new DefaultClientConfig();

		config.getClasses().add(JacksonJsonProvider.class); // to handle List<> unmarshalling
		HostnameVerifier hv = new HostnameVerifier() {
			public boolean verify(String urlHostName, SSLSession session) {
				return session.getPeerHost().equals(urlHostName);
			}
		};
		config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hv, sslContext));

		setClient(Client.create(config));
		if (StringUtils.isNotEmpty(getUsername()) && StringUtils.isNotEmpty(getPassword())) {
			getClient().addFilter(new HTTPBasicAuthFilter(getUsername(), getPassword()));
		}
	}
}
 
Example #26
Source File: KylinClient.java    From ranger with Apache License 2.0 5 votes vote down vote up
private static ClientResponse getClientResponse(String kylinUrl, String userName, String password) {
	ClientResponse response = null;
	String[] kylinUrls = kylinUrl.trim().split("[,;]");
	if (ArrayUtils.isEmpty(kylinUrls)) {
		return null;
	}

	Client client = Client.create();
	String decryptedPwd = PasswordUtils.getDecryptPassword(password);
	client.addFilter(new HTTPBasicAuthFilter(userName, decryptedPwd));

	for (String currentUrl : kylinUrls) {
		if (StringUtils.isBlank(currentUrl)) {
			continue;
		}

		String url = currentUrl.trim() + KYLIN_LIST_API_ENDPOINT;
		try {
			response = getProjectResponse(url, client);

			if (response != null) {
				if (response.getStatus() == HttpStatus.SC_OK) {
					break;
				} else {
					response.close();
				}
			}
		} catch (Throwable t) {
			String msgDesc = "Exception while getting kylin response, kylinUrl: " + url;
			LOG.error(msgDesc, t);
		}
	}
	client.destroy();

	return response;
}
 
Example #27
Source File: RemoteCoreProxy.java    From ice with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * <p>
 * This operation connects to the ICE Core using Basic authentication over
 * HTTPS.
 * </p>
 * 
 * @param username
 *            <p>
 *            The users' name.
 *            </p>
 * @param password
 *            <p>
 *            The users' password.
 *            </p>
 * @return
 * 		<p>
 *         The client id as specified by ICore.connect().
 *         </p>
 */
public String connect(String username, String password) {

	// Create a filter for the client that sets the authentication
	// credentials
	final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(username,
			password);
	client.addFilter(authFilter);

	// Connect as usual
	return connect();
}