I work on my Spring Boot app which uses Spring API client as a maven depencency. When I use it in my code, it logs data. How can I turn it off? Where shall I place log4j.properties to actually work? I tried inside resources and also inside folder with my service which uses it.
package com.example.demo.service;
import com.wrapper.spotify.SpotifyApi;
import com.wrapper.spotify.SpotifyHttpManager;
import com.wrapper.spotify.exceptions.SpotifyWebApiException;
import com.wrapper.spotify.model_objects.credentials.AuthorizationCodeCredentials;
import com.wrapper.spotify.requests.authorization.authorization_code.AuthorizationCodeRequest;
import org.apache.hc.core5.http.ParseException;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class AuthorizationCodeExample {
private static final String clientId = "";
private static final String clientSecret = "";
private static final URI redirectUri = SpotifyHttpManager.makeUri("");
private static final String code = "";
private static final SpotifyApi spotifyApi = new SpotifyApi.Builder()
.setClientId(clientId)
.setClientSecret(clientSecret)
.setRedirectUri(redirectUri)
.build();
private static final AuthorizationCodeRequest authorizationCodeRequest = spotifyApi.authorizationCode(code)
.build();
public static void authorizationCode_Sync() {
try {
final AuthorizationCodeCredentials authorizationCodeCredentials = authorizationCodeRequest.execute();
// Set access and refresh token for further "spotifyApi" object usage
spotifyApi.setAccessToken(authorizationCodeCredentials.getAccessToken());
spotifyApi.setRefreshToken(authorizationCodeCredentials.getRefreshToken());
System.out.println("Expires in: " + authorizationCodeCredentials.getExpiresIn());
} catch (IOException | SpotifyWebApiException | ParseException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
authorizationCode_Sync();
}
}
This is my project tree:
https://imgur.com/mS676gw
logging.level.*=LEVEL
There are different levels available, the one you are looking for is OFF. So just add the following line into your application.properties file
logging.level.*=OFF
It should be resources folder. But did you made changes inside the file to turn off logs ?
log4j.rootLogger=OFF, Note that this has the highest priority and will turn off all logging.
Related
I am trying to use "MiniKdc" in my code implementation like "MiniKdc.main(config)" but am getting error "can not resolve symbol 'MiniKdc' ".
I am following this example https://www.baeldung.com/spring-security-kerberos-integration
i have added this dependecy in my build.gradle
implementation 'org.springframework.security.kerberos:spring-security-kerberos-test:1.0.1.RELEASE'
i tried to search the dependecy from maven central/repository and i can't find it.
here is the class i am working on, i want to be able to import Minikdc in the second import statement.
import org.apache.commons.io.FileUtils;
import org.springframework.security.kerberos.test.MiniKdc;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
class KerberosMiniKdc {
private static final String KRB_WORK_DIR = ".\\spring-security-sso\\spring-security-sso-kerberos\\krb-test-workdir";
public static void main(String[] args) throws Exception {
String[] config = MiniKdcConfigBuilder.builder()
.workDir(prepareWorkDir())
.confDir("minikdc-krb5.conf")
.keytabName("example.keytab")
.principals("client/localhost", "HTTP/localhost")
.build();
MiniKdc.main(config);
}
private static String prepareWorkDir() throws IOException {
Path dir = Paths.get(KRB_WORK_DIR);
File directory = dir.normalize().toFile();
FileUtils.deleteQuietly(directory);
FileUtils.forceMkdir(directory);
return dir.toString();
}
}
is there anything am doing wrong?
As of 2021, spring-security-kerberos is not well maintained.
I suggest using Apache Kerby instead, either directly or via other library like Kerb4J. See an example here.
package com.kerb4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.kerby.kerberos.kerb.client.KrbConfig;
import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import java.io.File;
public class KerberosSecurityTestcase {
private static final Log log = LogFactory.getLog(KerberosSecurityTestcase.class);
private static int i = 10000;
protected int kdcPort;
private SimpleKdcServer kdc;
private File workDir;
private KrbConfig conf;
#BeforeAll
public static void debugKerberos() {
System.setProperty("sun.security.krb5.debug", "true");
}
#BeforeEach
public void startMiniKdc() throws Exception {
kdcPort = i++;
createTestDir();
createMiniKdcConf();
log.info("Starting Simple KDC server on port " + kdcPort);
kdc = new SimpleKdcServer(workDir, conf);
kdc.setKdcPort(kdcPort);
kdc.setAllowUdp(false);
kdc.init();
kdc.start();
}
#AfterEach
public void stopMiniKdc() throws Exception {
log.info("Stopping Simple KDC server on port " + kdcPort);
if (kdc != null) {
kdc.stop();
log.info("Stopped Simple KDC server on port " + kdcPort);
}
}
public void createTestDir() {
workDir = new File(System.getProperty("test.dir", "target"));
}
public void createMiniKdcConf() {
conf = new KrbConfig();
}
public SimpleKdcServer getKdc() {
return kdc;
}
public File getWorkDir() {
return workDir;
}
public KrbConfig getConf() {
return conf;
}
}
Disclaimer: I'm the author of Kerb4J
I need to run the gradle eclipse task to an external gradle project from a java method, is it possible to do it using the Gradle Tooling API ?
The Gradle forum gives a nice example for doing this programmatically but since it disregards the projects individual gradle wrapper, it can't guarantee the smooth execution of your build and even break your application. For more information why you always should rely on the gradle wrapper read here and here.
Using the Gradle wrapper
The recommended approach is to run exec and call the projects wrapper while passing the task as a parameter. This example calls the current projects wrapper and passes jar as a parameter:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Main
{
private static String PATH_TO_GRADLE_PROJECT = "./";
private static String GRADLEW_EXECUTABLE = "gradlew.bat";
private static String BLANK = " ";
private static String GRADLE_TASK = "jar";
public static void main(String[] args)
{
String command = PATH_TO_GRADLE_PROJECT + GRADLEW_EXECUTABLE + BLANK + GRADLE_TASK;
try
{
Runtime.getRuntime().exec(command);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Using the Gradle Tooling API
To use the Gradle tooling api on a external project, you simply have to define the property forProjectDirectory of your GradleConnectorobject. To run a task call run() on the BuildLauncher object. The example below demostrates the basic principle:
import org.gradle.tooling.BuildLauncher;
import org.gradle.tooling.GradleConnector;
import org.gradle.tooling.ProjectConnection;
import java.io.File;
public class ToolingAPI
{
private static final String GRADLE_INSTALLATION = "C:\\Program Files\\Gradle";
private static final String GRADLE_PROJECT_DIRECTORY = "path_to_root_of_a_gradle_project";
private static final String GRADLE_TASK = "help";
private GradleConnector connector;
public ToolingAPI(String gradleInstallationDir, String projectDir)
{
connector = GradleConnector.newConnector();
connector.useInstallation(new File(gradleInstallationDir));
connector.forProjectDirectory(new File(projectDir));
}
public void executeTask(String... tasks)
{
ProjectConnection connection = connector.connect();
BuildLauncher build = connection.newBuild();
build.forTasks(tasks);
build.run();
connection.close();
}
public static void main(String[] args)
{
ToolingAPI toolingAPI = new ToolingAPI(GRADLE_INSTALLATION, GRADLE_PROJECT_DIRECTORY);
toolingAPI.executeTask(GRADLE_TASK);
}
}
The downside of this approach is the location unawareness of gradle when executing a task. In case you call any file creation or modification method in a custom task like new File("somefile") a exception will be raised.
what does this Spring JSON endpoint break in Jboss/Tomcat ? I tried to add this to an existing APPLICATION and It worked until I started refactoring the code and now the errors do not point to anything that is logical to me.
Here is my code a controller and Helper class to keep things clean.
Controller.Java
import java.io.IOException;
import java.util.Properties;
import javax.annotation.Nonnull;
import org.apache.commons.configuration.ConfigurationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class PropertiesDisplayController {
#Nonnull
private final PropertiesDisplayHelper propertiesHelper;
/**
* #param propertiesHelper
*/
#Nonnull
#Autowired
public PropertiesDisplayController(#Nonnull final PropertiesDisplayHelper propertiesHelper) {
super();
this.propertiesHelper = propertiesHelper;
}
#Nonnull
#RequestMapping("/localproperties")
public #ResponseBody Properties localProperties() throws ConfigurationException, IOException {
return propertiesHelper.getLocalProperties();
}
#Nonnull
#RequestMapping("/properties")
public #ResponseBody Properties applicationProperties() throws IOException,
ConfigurationException {
return propertiesHelper.getApplicationProperties();
}
}
this would be the Helper.java
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import javax.annotation.Nonnull;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
public class PropertiesDisplayHelper {
/** Static location of properties in for SSO */
private static String LOCAL_PROPERTIES_LOCATION =
"local.properties";
/** Static strings for masking the passwords and blank values */
private static String NOVALUE = "**NO VALUE**";
/** Static strings for masking the passwords and blank values */
private static String MASKED = "**MASKED**";
#Nonnull
public Properties getApplicationProperties() throws ConfigurationException {
final Properties properties = new Properties();
final Configuration configuration = AppConfiguration.Factory.getConfiguration();
// create a map of properties
final Iterator<?> propertyKeys = configuration.getKeys();
final Map<String, String> sortedProperties = new TreeMap<String, String>();
// loops the configurations and builds the properties
while (propertyKeys.hasNext()) {
final String key = propertyKeys.next().toString();
final String value = configuration.getProperty(key).toString();
sortedProperties.put(key, value);
}
properties.putAll(sortedProperties);
// output of the result
formatsPropertiesData(properties);
return properties;
}
#Nonnull
public Properties getLocalProperties() throws ConfigurationException, IOException {
FileInputStream fis = null;
final Properties properties = new Properties();
// imports file local.properties from specified location
// desinated when the update to openAM12
try {
fis = new FileInputStream(LOCAL_PROPERTIES_LOCATION);
properties.load(fis);
} finally {
// closes file input stream
IOUtils.closeQuietly(fis);
}
formatsPropertiesData(properties);
return properties;
}
void formatsPropertiesData(#Nonnull final Properties properties) {
for (final String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
if (StringUtils.isEmpty(value)) {
value = NOVALUE;
} else if (key.endsWith("ssword")) {
value = MASKED;
} else {
value = StringEscapeUtils.escapeHtml(value);
}
// places data to k,v paired properties object
properties.put(key, value);
}
}
}
they set up a json display of the properties in application and from a file for logging. Yet now this no intrusive code seems to break my entire application build.
Here is the error from Jboss
20:33:41,559 ERROR [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS015870: Deploy of deployment "openam.war" was rolled back with the following failure message:
{"JBAS014671: Failed services" => {"jboss.deployment.unit.\"APPLICATION.war\".STRUCTURE" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"APPLICATION.war\".STRUCTURE: JBAS018733: Failed to process phase STRUCTURE of deployment \"APPLICATION.war\"
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: JBAS018740: Failed to mount deployment content
Caused by: java.io.FileNotFoundException:APPLICATION.war (Access is denied)"}}
and the Errors from Tomcat
http://pastebin.com/PXdcpqvc
I am at a lost here and think there is something I just do not see.
A simple solution was at hand. The missing component was #Component annotation on the helper class.
From test.java, how can I access for reading the Contact.xml file located in the contacts.jar library ?
The bellow code returns null.
package views;
import fr.hznteam.contacts.Contact;
import fr.hznteam.errors.ResourceException;
import java.io.InputStream;
public class Test {
private static final String TAG = "Test ";
public static void main(String[] args) throws ResourceException {
InputStream is = Contact.class.getResourceAsStream("/fr/hznteam/contacts/sql/Contact.xml");
System.out.println(TAG + "resource from jar " + is);
}
The package structure :
this works (see above comment). Inside an object instance use
getClass().getResourceAsStream("/absolute/class_path/to/resource.file"))
I am trying to query vendors using the QBOVendorService but having no luck.
I am creating the service as follows:
QBOVendorService vService = QBServiceFactory.getService(context, QBOVendorService.class);
where the context is a valid PlatformSessionContext. I know the platform session context is good since I can get information about the user with it. When I try
vService.addVendor(context, vendor);
I end up with a NPE like my vService is null. Shouldn't I get an error initializing the QBOVendorService if it fails? Is there a good place to find more examples for using this since the intuit developer forums have been shut down?
I'm sharing a sample code snippet. Replace your OAuth tokens and relamId. It should work fine.
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import com.intuit.ds.qb.QBIdType;
import com.intuit.ds.qb.QBVendor;
import com.intuit.ds.qb.QBVendorQuery;
import com.intuit.ds.qb.QBVendorService;
import com.intuit.ds.qb.QBInvalidContextException;
import com.intuit.ds.qb.QBObjectFactory;
import com.intuit.ds.qb.QBServiceFactory;
import com.intuit.ds.qb.impl.QBRecordCountImpl;
import com.intuit.ds.qb.qbd.QBDRecordCountService;
import com.intuit.ds.qb.qbd.QBDServiceFactory;
import com.intuit.platform.client.PlatformSessionContext;
import com.intuit.platform.client.PlatformServiceType;
import com.intuit.platform.client.security.OAuthCredentials;
import com.intuit.ds.qb.QBSyncStatusRequest;
import com.intuit.ds.qb.QBSyncStatusRequestService;
import com.intuit.ds.qb.QBSyncStatusResponse;
import com.intuit.sb.cdm.NgIdSet;
import com.intuit.sb.cdm.ObjectName;
import org.slf4j.Logger;
// QBD API Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0500_quickbooks_windows/0600_object_reference/vendor
// QBO API Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0400_quickbooks_online/vendor
// JavaDocs - http://developer-static.intuit.com/SDKDocs/QBV2Doc/ipp-java-devkit-2.0.10-SNAPSHOT-javadoc/
public class CodegenStubVendorall {
final PlatformSessionContext context;
public CodegenStubVendorall(PlatformSessionContext context) {
this.context = context;
}
public void testAdd() {
final List<QBVendor> entityList = new ArrayList<QBVendor>();
try {
QBVendorService service = QBServiceFactory.getService(context, QBVendorService.class);
//Your Code
//Use Vendor POJO for creating Vendor
}
} catch (QBInvalidContextException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
PlatformSessionContext context = getPlatformContext();
CodegenStubVendorall testObj = new CodegenStubVendorall(context);
testObj.testAdd();
}
public static PlatformSessionContext getPlatformContext() {
String accesstoken = "rplce_your_application_token";
String accessstokensecret = "rplce_your_application_token";
String appToken = "rplce_your_application_token";
String oauth_consumer_key = "rplce_your_application_token";
String oauth_consumer_secret = "rplce_your_application_token";
String realmID = "123456";
String dataSource = "QBO";
PlatformServiceType serviceType;
if (dataSource.equalsIgnoreCase("QBO")) {
serviceType = PlatformServiceType.QBO;
} else {
serviceType = PlatformServiceType.QBD;
}
final OAuthCredentials oauthcredentials = new OAuthCredentials(
oauth_consumer_key, oauth_consumer_secret, accesstoken,
accessstokensecret);
final PlatformSessionContext context = new PlatformSessionContext(
oauthcredentials, appToken, serviceType, realmID);
return context;
}
}
You can try to use ApiExplorer tool to verify your OAuth tokens and to check the create Vendor API endpoint.
Link - https://developer.intuit.com/apiexplorer?apiname=V2QBO
Please let me know how it goes.
Thanks