Java Code Examples for org.apache.commons.lang3.StringUtils.appendIfMissing()

The following are Jave code examples for showing how to use appendIfMissing() of the org.apache.commons.lang3.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: plugin-vm-vcloud   File: VCloudPluginResource.java   View Source Code Vote up 7 votes
/**
 * Return a snapshot of the console.
 * 
 * @param subscription
 *            the valid screenshot of the console.
 * @return the valid screenshot of the console.
 */
@GET
@Path("{subscription:\\d+}/console.png")
@Produces("image/png")
public StreamingOutput getConsole(@PathParam("subscription") final int subscription) {
	final Map<String, String> parameters = subscriptionResource.getParameters(subscription);
	final VCloudCurlProcessor processor = new VCloudCurlProcessor();
	authenticate(parameters, processor);

	// Get the screen thumbnail
	return output -> {
		final String url = StringUtils.appendIfMissing(parameters.get(PARAMETER_API), "/") + "vApp/vm-" + parameters.get(PARAMETER_VM)
				+ "/screen";
		final CurlRequest curlRequest = new CurlRequest("GET", url, null, (request, response) -> {
			if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
				// Copy the stream
				IOUtils.copy(response.getEntity().getContent(), output);
				output.flush();
			}
			return false;
		});
		processor.process(curlRequest);
	};
}
 
Example 2
Project: cas-5.1.0   File: AzureAuthenticatorAuthenticationEventExecutionPlanConfiguration.java   View Source Code Vote up 6 votes
@Bean
public PFAuth azureAuthenticatorInstance() {
    try {
        final MultifactorAuthenticationProperties.Azure azure = casProperties.getAuthn().getMfa().getAzure();
        final File cfg = new File(azure.getConfigDir());
        if (!cfg.exists() || !cfg.isDirectory()) {
            throw new FileNotFoundException(cfg.getAbsolutePath() + " does not exist or is not a directory");
        }
        final PFAuth pf = new PFAuth();
        pf.setDebug(true);
        pf.setAllowInternationalCalls(azure.isAllowInternationalCalls());

        final String dir = StringUtils.appendIfMissing(azure.getConfigDir(), "/");
        pf.initialize(dir, azure.getPrivateKeyPassword());
        return pf;
    } catch (final Exception e) {
        throw new BeanCreationException(e.getMessage(), e);
    }
}
 
Example 3
Project: nixmash-blog   File: PostUtils.java   View Source Code Vote up 6 votes
public static String formatPostContent(Post post) {
    String content = post.getPostContent();
    String imageHtml = "<img alt=\"\" src=\"%s\"  class=\"%s-image\"/>\n";
    String thumbnail = String.format(imageHtml, post.getPostImage(), "thumbnail");
    String feature = String.format(imageHtml, post.getPostImage(), "feature");

    switch (post.getDisplayType()) {
        case LINK_SUMMARY:
            content = StringUtils.prependIfMissing(content, thumbnail);
            break;
        case LINK_FEATURE:
            content = StringUtils.appendIfMissing(content, feature);
            break;
        case LINK:
            break;
    }
    return content;
}
 
Example 4
Project: plugin-security-fortify   File: FortifyPluginResource.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
@Override
public String getVersion(final Map<String, String> parameters) throws Exception {
	final FortifyCurlProcessor processor = new FortifyCurlProcessor();
	// Check the user can log-in to Fortify
	authenticate(parameters, processor);

	final String url = StringUtils.appendIfMissing(parameters.get(PARAMETER_URL), "/") + "api/v1/userSession/info";
	final CurlRequest request = new CurlRequest("POST", url, null, "Accept: application/json");
	request.setSaveResponse(true);
	processor.process(request);
	final String content = ObjectUtils.defaultIfNull(request.getResponse(), "{}");
	final ObjectMapper mapper = new ObjectMapper();
	final Map<String, ?> data = MapUtils
			.emptyIfNull((Map<String, ?>) mapper.readValue(content, Map.class).get("data"));
	final String version = (String) data.get("webappVersion");
	processor.close();
	return version;
}
 
Example 5
Project: plugin-qa-sonarqube   File: SonarPluginResource.java   View Source Code Vote up 6 votes
/**
 * Validate the basic REST connectivity to SonarQube.
 * 
 * @param parameters
 *            the server parameters.
 * @return the detected SonarQube version.
 */
protected String validateAdminAccess(final Map<String, String> parameters) throws Exception {
	final String url = StringUtils.appendIfMissing(parameters.get(PARAMETER_URL), "/") + "sessions/new";
	CurlProcessor.validateAndClose(url, PARAMETER_URL, "sonar-connection");

	// Check the user can log-in to SonarQube with the preempted authentication processor
	if (!StringUtils.trimToEmpty(getResource(parameters, "api/authentication/validate?format=json")).contains("true")) {
		throw new ValidationJsonException(PARAMETER_USER, "sonar-login");
	}

	// Check the user has enough rights to access to the provisioning page
	if (getResource(parameters, "provisioning") == null) {
		throw new ValidationJsonException(PARAMETER_USER, "sonar-rights");
	}
	return getVersion(parameters);
}
 
Example 6
Project: plugin-scm   File: AbstractIndexBasedPluginResource.java   View Source Code Vote up 6 votes
/**
 * Find the repositories matching to the given criteria.Look into name only.
 * 
 * @param criteria
 *            the search criteria.
 * @param node
 *            the node to be tested with given parameters.
 * @return project name.
 */
@GET
@Path("{node}/{criteria}")
@Consumes(MediaType.APPLICATION_JSON)
public List<NamedBean<String>> findAllByName(@PathParam("node") final String node, @PathParam("criteria") final String criteria) {
	final Map<String, String> parameters = pvResource.getNodeParameters(node);
	final CurlRequest request = new CurlRequest(HttpMethod.GET, StringUtils.appendIfMissing(parameters.get(parameterUrl), "/"), null);
	request.setSaveResponse(true);
	newCurlProcessor(parameters).process(request);

	// Prepare the context, an ordered set of projects
	final Format format = new NormalizeFormat();
	final String formatCriteria = format.format(criteria);

	// Limit the result
	return inMemoryPagination.newPage(
			Arrays.stream(StringUtils.splitByWholeSeparator(StringUtils.defaultString(request.getResponse()), "<a href=\"")).skip(1)
					.filter(s -> format.format(s).contains(formatCriteria))
					.map(s -> StringUtils.removeEnd(s.substring(0, Math.max(0, s.indexOf('\"'))), "/"))
					.filter(((Predicate<String>) String::isEmpty).negate()).map(id -> new NamedBean<>(id, id)).collect(Collectors.toList()),
					PageRequest.of(0, 10)).getContent();
}
 
Example 7
Project: plugin-bt-jira   File: JiraBaseResource.java   View Source Code Vote up 6 votes
/**
 * Prepare an authenticated connection to JIRA
 */
protected boolean authenticateAdmin(final Map<String, String> parameters, final CurlProcessor processor) {
	final String user = parameters.get(PARAMETER_ADMIN_USER);
	final String password = StringUtils.trimToEmpty(parameters.get(PARAMETER_ADMIN_PASSWORD));
	final String baseUrl = parameters.get(PARAMETER_URL);
	final String url = StringUtils.appendIfMissing(baseUrl, "/") + "login.jsp";
	final List<CurlRequest> requests = new ArrayList<>();
	requests.add(new CurlRequest(HttpMethod.GET, url, null));
	requests.add(new CurlRequest(HttpMethod.POST, url,
			"os_username=" + user + "&os_password=" + password + "&os_destination=&atl_token=&login=Connexion",
			JiraCurlProcessor.LOGIN_CALLBACK, "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));

	// Sudoing is only required for JIRA 4+
	if ("4".compareTo(getVersion(parameters)) <= 0) {
		requests.add(
				new CurlRequest(HttpMethod.POST, StringUtils.appendIfMissing(baseUrl, "/") + "secure/admin/WebSudoAuthenticate.jspa",
						"webSudoIsPost=false&os_cookie=true&authenticate=Confirm&webSudoPassword=" + password,
						JiraCurlProcessor.SUDO_CALLBACK, "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
	}
	return processor.process(requests);
}
 
Example 8
Project: sling-org-apache-sling-testing-clients   File: SlingClient.java   View Source Code Vote up 5 votes
/**
 * Creates a new Folder of type sling:OrderedFolder. Same as using {@code New Folder...} in the Site Admin.
 *
 * @param folderName     The name of the folder to be used in the URL.
 * @param folderTitle    Title of the Folder to be set in jcr:title
 * @param parentPath     The parent path where the folder gets added.
 * @param expectedStatus list of expected HTTP Status to be returned, if not set, 201 is assumed.
 * @return the response
 * @throws ClientException if something fails during the request/response cycle
 */
public SlingHttpResponse createFolder(String folderName, String folderTitle, String parentPath, int... expectedStatus)
        throws ClientException {
    // we assume the parentPath is a folder, even though it doesn't end with a slash
    parentPath = StringUtils.appendIfMissing(parentPath, "/");
    String folderPath = parentPath + folderName;
    HttpEntity feb = FormEntityBuilder.create()
            .addParameter("./jcr:primaryType", "sling:OrderedFolder")  // set primary type for folder node
            .addParameter("./jcr:content/jcr:primaryType", "nt:unstructured")  // add jcr:content as sub node
            .addParameter("./jcr:content/jcr:title", folderTitle)  //set the title
            .build();

    // execute request and return the sling response
    return this.doPost(folderPath, feb, HttpUtils.getExpectedStatus(SC_CREATED, expectedStatus));
}
 
Example 9
Project: plugin-vm-vcloud   File: VCloudPluginResource.java   View Source Code Vote up 5 votes
/**
 * Prepare an authenticated connection to vCloud. The given processor would
 * be updated with the security token.
 */
protected void authenticate(final Map<String, String> parameters, final VCloudCurlProcessor processor) {
	final String user = parameters.get(PARAMETER_USER);
	final String password = StringUtils.trimToEmpty(parameters.get(PARAMETER_PASSWORD));
	final String organization = StringUtils.trimToEmpty(parameters.get(PARAMETER_ORGANIZATION));
	final String url = StringUtils.appendIfMissing(parameters.get(PARAMETER_API), "/") + "sessions";

	// Encode the authentication '[email protected]:password'
	final String authentication = Base64
			.encodeBase64String((user + "@" + organization + ":" + password).getBytes(StandardCharsets.UTF_8));

	// Authentication request using cache
	processor.setToken(authenticate(url, authentication, processor));
}
 
Example 10
Project: plugin-vm-vcloud   File: VCloudPluginResource.java   View Source Code Vote up 5 votes
/**
 * Return/execute a vCloud resource. Return <code>null</code> when the
 * resource is not found. Authentication should be proceeded before for
 * authenticated query.
 */
protected String execute(final CurlProcessor processor, final String method, final String url, final String resource) {
	// Get the resource using the preempted authentication
	final CurlRequest request = new CurlRequest(method, StringUtils.appendIfMissing(url, "/") + StringUtils.removeStart(resource, "/"),
			null);
	request.setSaveResponse(true);

	// Execute the requests
	processor.process(request);
	processor.close();
	return request.getResponse();
}
 
Example 11
Project: plugin-security-fortify   File: FortifyPluginResource.java   View Source Code Vote up 5 votes
/**
 * Fetch given node from parameters and given URL, and return the JSON
 * object.
 */
private Object getFortifyResource(final Map<String, String> parameters, final String resource,
		final FortifyCurlProcessor processor) throws IOException {

	final String url = StringUtils.appendIfMissing(parameters.get(PARAMETER_URL), "/") + resource;
	final CurlRequest request = new CurlRequest("GET", url, null);
	request.setSaveResponse(true);
	processor.process(request);

	// Parse the JSON response
	final String content = ObjectUtils.defaultIfNull(request.getResponse(), "{}");
	final ObjectMapper mapper = new ObjectMapper();
	return mapper.readValue(content, Map.class).get("data");
}
 
Example 12
Project: plugin-km-confluence   File: ConfluencePluginResource.java   View Source Code Vote up 5 votes
/**
 * Prepare an authenticated connection to Confluence
 */
protected void authenticate(final Map<String, String> parameters, final CurlProcessor processor) {
	final String user = parameters.get(PARAMETER_USER);
	final String password = StringUtils.trimToEmpty(parameters.get(PARAMETER_PASSWORD));
	final String url = StringUtils.appendIfMissing(parameters.get(PARAMETER_URL), "/") + "dologin.action";
	final List<CurlRequest> requests = new ArrayList<>();
	requests.add(new CurlRequest(HttpMethod.GET, url, null));
	requests.add(new CurlRequest(HttpMethod.POST, url,
			"os_username=" + user + "&os_password=" + password + "&os_destination=&atl_token=&login=Connexion",
			ConfluenceCurlProcessor.LOGIN_CALLBACK, "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
	if (!processor.process(requests)) {
		throw new ValidationJsonException(PARAMETER_URL, "confluence-login", parameters.get(PARAMETER_USER));
	}
}
 
Example 13
Project: plugin-scm   File: AbstractIndexBasedPluginResource.java   View Source Code Vote up 5 votes
/**
 * Validate the administration connectivity. Expect an authenticated connection.
 */
private void validateAdminAccess(final Map<String, String> parameters, final CurlProcessor processor) {
	final CurlRequest request = new CurlRequest(HttpMethod.GET, StringUtils.appendIfMissing(parameters.get(parameterUrl), "/"), null);
	request.setSaveResponse(true);
	// Request all repositories access
	if (!processor.process(request) || !StringUtils.contains(request.getResponse(), "<a href=\"/\">")) {
		throw new ValidationJsonException(parameterUrl, simpleName + "-admin", parameters.get(parameterUser));
	}
}
 
Example 14
Project: plugin-scm-svn   File: SvnPluginResource.java   View Source Code Vote up 4 votes
@Override
protected String getRepositoryUrl(final Map<String, String> parameters) {
	// For SVN, a trailing "/" is added.
	return StringUtils.appendIfMissing(super.getRepositoryUrl(parameters), "/");
}
 
Example 15
Project: plugin-scm   File: IndexBasedPluginResourceTest.java   View Source Code Vote up 4 votes
@SuppressWarnings("unchecked")
@Before
public void newMockResource() {
	resource = new AbstractIndexBasedPluginResource("service", "impl") {

		@Override
		protected String getRepositoryUrl(final Map<String, String> parameters) {
			return StringUtils.appendIfMissing(super.getRepositoryUrl(parameters), "/");
		}

		/**
		 * Return the revision number.
		 */
		@Override
		protected Object toData(final String statusContent) {
			return 1;
		}

		{
			subscriptionResource = Mockito.mock(SubscriptionResource.class);
			parameters = new HashMap<>();
			parameters.put("service:url", "http://localhost:" + MOCK_PORT);
			parameters.put("service:user", "user");
			parameters.put("service:password", "secret");
			parameters.put("service:index", "true");
			parameters.put("service:repository", "my-repo");
			Mockito.when(subscriptionResource.getParameters(1)).thenReturn(parameters);
			Mockito.when(subscriptionResource.getParametersNoCheck(1)).thenReturn(parameters);
			IndexBasedPluginResourceTest.this.subscriptionResource = subscriptionResource;

			pvResource = Mockito.mock(ParameterValueResource.class);
			Mockito.when(pvResource.getNodeParameters("service:impl:node")).thenReturn(parameters);

			inMemoryPagination = Mockito.mock(InMemoryPagination.class);
			Mockito.when(inMemoryPagination.newPage(ArgumentMatchers.anyCollection(),
					ArgumentMatchers.any(Pageable.class)))
					.thenAnswer(i -> new PageImpl<>(new ArrayList<>((Collection<Object>) i.getArguments()[0]),
							(Pageable) i.getArguments()[1], ((Collection<Object>) i.getArguments()[0]).size()));
		}
	};
}
 
Example 16
Project: plugin-scm   File: AbstractIndexBasedPluginResource.java   View Source Code Vote up 2 votes
/**
 * Return the repository URL.
 * 
 * @param parameters
 *            the subscription parameters.
 * @return the computed repository URL.
 */
protected String getRepositoryUrl(final Map<String, String> parameters) {
	return StringUtils.appendIfMissing(parameters.get(parameterUrl), "/") + parameters.get(parameterRepository);
}