NPE while receiving messages from Azure Service bus Queue - java

NPE while receving messages from Queue. ( Only when messages are present in Queue). I feel like there is an issue with de-serializing the messages.
java.lang.NullPointerException
at com.sun.jersey.api.client.ClientResponse.getResponseDate(ClientResponse.java:738)
at com.microsoft.windowsazure.services.servicebus.implementation.ServiceBusRestProxy.receiveMessage(ServiceBusRestProxy.java:288)
at com.microsoft.windowsazure.services.servicebus.implementation.ServiceBusRestProxy.receiveQueueMessage(ServiceBusRestProxy.java:225)
at com.microsoft.windowsazure.services.servicebus.implementation.ServiceBusExceptionProcessor.receiveQueueMessage(ServiceBusExceptionProcessor.java:142)
RECEIVE_AND_DELETE option deletes the messages and throws NPE.
All other operations like create queue , send messages etc working fine. Any thoughts one this ?
Code to receive message
public void receiveMessage(String queueName) {
try {
ReceiveMessageOptions opts = ReceiveMessageOptions.DEFAULT;
opts.setReceiveMode(ReceiveMode.PEEK_LOCK);
while (true) {
ReceiveQueueMessageResult resultQM
= service.receiveQueueMessage(queueName, opts);
BrokeredMessage message = resultQM.getValue();
if (message != null && message.getMessageId() != null) {
log.println("MessageID: " + message.getMessageId());
// Display the queue message.
log.print("From queue: ");
byte[] b = new byte[200];
String s = null;
int numRead = message.getBody().read(b);
while (-1 != numRead) {
s = new String(b);
s = s.trim();
System.out.print(s);
numRead = message.getBody().read(b);
}
log.println("");
log.println("Custom Property: "
+ message.getProperty("MyProperty"));
// Remove message from queue.
log.println("Deleting this message.");
//service.deleteMessage(message);
} else {
log.println("Finishing up - no more messages.");
break;
// Added to handle no more messages.
// Could instead wait for more messages to be added.
}
}
} catch (Exception e) {
log.print(e);
}
}

Even though it was throwing NPE the actual issue was with the missing jar files. Here is the list of jar files
<dependencies>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-svc-mgmt</artifactId>
<version>0.9.7</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-svc-mgmt-compute</artifactId>
<version>0.9.7</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-svc-mgmt-network</artifactId>
<version>0.9.7</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-svc-mgmt-sql</artifactId>
<version>0.9.7</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-svc-mgmt-storage</artifactId>
<version>0.9.7</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-svc-mgmt-websites</artifactId>
<version>0.9.7</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-svc-mgmt-media</artifactId>
<version>0.9.7</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-servicebus</artifactId>
<version>0.9.7</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-serviceruntime</artifactId>
<version>0.9.7</version>
</dependency>
</dependencies>

Related

DOCX4j : space removed in pdf by deploying war file into tomcat

I am using below code to convert docx to pdf using DOCX4j.While running this code into IDE it is working fine and space preserved after conversion. For deployment I created war and put it into tomcat server. But into test server space is not preserved into document after conversion.
pom.xml
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.docx4j/docx4j-JAXB-Internal -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-Internal</artifactId>
<version>8.3.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.docx4j/docx4j-JAXB-ReferenceImpl -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
<version>8.3.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.docx4j/docx4j-JAXB-MOXy -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-MOXy</artifactId>
<version>8.3.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.docx4j/docx4j-export-fo -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-export-fo</artifactId>
<version>8.3.7</version>
</dependency>
code for conversion
private byte[] docxToPdfBytes() {
InputStream templateInputStream = null;
try {
templateInputStream = new FileInputStream(ApplicationConstants.TEMP_DOCX_PATH);
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);
FileOutputStream os = new FileOutputStream(ApplicationConstants.TEMP_PDF_PATH);
Docx4J.toPDF(wordMLPackage, os);
os.flush();
os.close();
return Files.readAllBytes(Paths.get(ApplicationConstants.TEMP_PDF_PATH));
} catch (Throwable e) {
logger.info(XrefSubscriberServiceService.class.getName() + "==> Method : docxToPdfBytes");
logger.error(e.getMessage(), e);
}
finally {
if(null != templateInputStream) {
try {
templateInputStream.close();
} catch (IOException e) {
logger.info(XrefSubscriberServiceService.class.getName() + "==> Method : docxToPdfBytes");
logger.error(e.getMessage(), e);
}
}
}
return null;
}
So can anyone have idea why this type of behaviour is happened ??
this question is resolved. Just need to correct docx styling of font in docx document.

Unable to use full text search with oak lucene

I am trying out jackrabbit oak with lucene in a file node store. The index definition record is created successfully but it seems the index record is not created.
The full project I am working on is here
What I am doing in the code is initializa a repository, create the lucene index definition, add a test data with a single property "name" with value "foo".
Sleep for 5 second for async indexing to complete, then perform the following query in a retry loop
select * from [nt:base] where contains(., 'foo').
No result is returned.
I have tried oak-run console to retrieve lc info on oak:index/lucene directory, it displays no result as well.
This is the main part of the code
public static void main( String[] args ) throws Exception
{
init();
createLuceneIndex();
createTestData();
performQuery();
}
private static void init() throws InvalidFileStoreVersionException, IOException {
LuceneIndexProvider provider = new LuceneIndexProvider();
FileStore fs = FileStoreBuilder.fileStoreBuilder(new File("repository")).build();
nodestore = SegmentNodeStoreBuilders.builder(fs).build();
repository = new Jcr(new Oak(nodestore))
.withAsyncIndexing("async", 3)
.with(new LuceneIndexEditorProvider())
.with((QueryIndexProvider) provider)
.with((Observer)provider)
.withAsyncIndexing()
.createRepository();
}
private static void createLuceneIndex() throws RepositoryException {
Session session = createAdminSession();
Node indexesNode = session.getRootNode().getNode("oak:index");
IndexDefinitionBuilder idxBuilder = new IndexDefinitionBuilder();
IndexRule indexRules = idxBuilder.indexRule("nt:unstructured");
indexRules.sync();
indexRules.property("name").analyzed().nodeScopeIndex();
idxBuilder.async("async");
idxBuilder.includedPaths("/");
Node documentIndex = indexesNode.addNode("lucene", "oak:QueryIndexDefinition");
idxBuilder.build(documentIndex);
session.save();
session.logout();
}
private static void createTestData() throws LoginException, RepositoryException {
Session session = createAdminSession();
Node test = session.getRootNode().addNode("test");
test.setProperty("name", "foo");
session.save();
session.logout();
}
private static void performQuery() throws Exception {
final Session session = createAdminSession();
TimeUnit.MICROSECONDS.sleep(5);
QueryManager qm = session.getWorkspace().getQueryManager();
final Query q = qm.createQuery("select * from [nt:base] where contains(., 'foo')", Query.JCR_SQL2);
new RetryLoop(new RetryLoop.Condition() {
public String getDescription() {
return "Full text query";
}
public boolean isTrue() throws Exception {
QueryResult r = q.execute();
return r.getNodes().hasNext();
}
}, 20, 500);
}
the pom file dependencies
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.jcr</groupId>
<artifactId>jcr</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.jackrabbit</groupId>
<artifactId>oak-jcr</artifactId>
<version>1.21-SNAPSHOT</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jackrabbit</groupId>
<artifactId>oak-core</artifactId>
<version>1.21-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.jackrabbit</groupId>
<artifactId>oak-jcr</artifactId>
<version>1.21-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.jackrabbit</groupId>
<artifactId>oak-segment-tar</artifactId>
<version>1.21-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.jackrabbit</groupId>
<artifactId>oak-lucene</artifactId>
<version>1.21-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>com.codahale.metrics</groupId>
<artifactId>metrics-core</artifactId>
<version>3.0.2</version>
</dependency>

Programmatically connect LDAP and authenticate credentials in AEM

I want to connect to LDAP programmatically in AEM using maven dependency which resolves in OSGi
Approaches and subsequent issues faced:-
1. Cannot use
#Reference
private ExternalIdentityProviderManager externalIdentityProviderManager;
final String externalId = request.getParameter("externalId");
final String externalPassword = request.getParameter("externalPassword");
final ExternalIdentityProvider idap = externalIdentityProviderManager.getProvider("ldap");
final SimpleCredentials credentials = new SimpleCredentials(externalId, externalPassword.toCharArray());
final ExternalUser externalUser = idap.authenticate(credentials);
as this Identity provider config is only present in author environment and not in publish servers(as per req).
2. Trying to use
<dependency>
<groupId>org.apache.directory.api</groupId>
<artifactId>api-ldap-client-api</artifactId>
<version>2.0.0.AM4</version>
</dependency>
to resolve dependencies. It resolve my compile time errors but this is not an 'osgi ready' library, hence couldn't be installed in OSGi. If done so manually it has further unresolved dependencies.
Code reference for this approach -
https://directory.apache.org/api/user-guide/2.1-connection-disconnection.html
&
https://directory.apache.org/api/user-guide/2.10-ldap-connection-template.html
3. I've also tried to use
String rootDN = "uid=admin,ou=system";
String rootPWD = "secret";
Hashtable < String, String > environment = new Hashtable < String, String > ();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://localhost:10389");
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, rootDN);
environment.put(Context.SECURITY_CREDENTIALS, rootPWD);
DirContext dirContext = null;
NamingEnumeration < ? > results = null;
dirContext = new InitialDirContext(environment);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String userId = "abhishek";
String userPwd = "{SSHA}ip/DD+zUhv22NH3wE1dvJN7oauYE4TYQ3ziRtg=="; //"apple";
String filter = "(&(objectclass=person)(uid=" + userId + ")(userPassword=" + userPwd + "))";
results = dirContext.search("", filter, controls);
if(results.hasMore()) {
System.out.println("User found");
} else {
System.out.println("User not found");
}
It has 2 issues -
a) It works fine when tested as plain Java class in main method on class load, but when attempted to integrate in AEM/osgi service class, it throws -
javax.naming.NotContextException: Not an instance of DirContext at javax.naming.directory.InitialDirContext.getURLOrDefaultInitDirCtx(InitialDirContext.java:111) at javax.naming.directory.InitialDirContext.search(InitialDirContext.java:267)
b) Even in plain Java class, i had to provide the hashed password to validate, which would be difficult to integrate.
String userPwd = "{SSHA}ip/DD+zUhv22NH3wE1dvJN7oauYE4TYQ3ziRtg==";//"apple";
Can someone provide me any maven dependency/library that can integrate with osgi and resolve dependency as well as i don't need to provide hashed password to validate user credentials? Any approach that may resolve these issues?
Step 1:
Add these dependencies in project pom
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.directory.api</groupId>
<artifactId>api-all</artifactId>
<version>1.0.0-RC2</version>
</dependency>
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-core</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>
Step 2:
Add them to bundle pom
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.apache.directory.api</groupId>
<artifactId>api-all</artifactId>
</dependency>
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-core</artifactId>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
</dependency>
Step 3:
In bundle pom at the plugin description
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Import-Package>!net.sf.cglib.proxy, javax.inject;version=0.0.0,*</Import-Package>
<Export-Package />
<Sling-Model-Packages></Sling-Model-Packages>
<Bundle-SymbolicName></Bundle-SymbolicName>
<Embed-Dependency>antlr, mina-core, api-all, commons-pool, commons-pool2</Embed-Dependency>
</instructions>
</configuration>
</plugin>
Use these for the above mentioned plugin
<Import-Package>!net.sf.cglib.proxy</Import-Package>
<Embed-Dependency>antlr, mina-core, api-all, commons-pool, commons-pool2</Embed-Dependency>
Step 4:
Imports are specifics and works only when
<dependency>
<groupId>org.apache.directory.api</groupId>
<artifactId>api-all</artifactId>
<version>1.0.0-RC2</version>
</dependency>
is used. As there are some other dependencies which provides packages/class but they don't work at some point or the other.
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.DefaultPoolableLdapConnectionFactory;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import org.apache.directory.ldap.client.api.LdapConnectionPool;
import org.apache.directory.ldap.client.template.LdapConnectionTemplate;
import org.apache.directory.ldap.client.template.PasswordWarning;
import org.apache.directory.ldap.client.template.exception.PasswordException;
private String ldapAuthenticationApacheDsFlow(final SlingHttpServletRequest request) {
String status = "";
try {
LdapConnectionConfig config = new LdapConnectionConfig();
config.setLdapHost("localhost");
config.setLdapPort(10389);
config.setName("uid=admin,ou=system");
config.setCredentials("secret");
final DefaultPoolableLdapConnectionFactory factory = new DefaultPoolableLdapConnectionFactory(config);
final LdapConnectionPool pool = new LdapConnectionPool(factory);
pool.setTestOnBorrow(true);
final LdapConnectionTemplate ldapConnectionTemplate = new LdapConnectionTemplate(pool);
final String uid = request.getParameter("externalId");
final String password = request.getParameter("externalPassword");
final PasswordWarning warning = ldapConnectionTemplate.authenticate(
"ou=Users,dc=example,dc=com", "(uid=" + uid +")", SearchScope.SUBTREE, password.toCharArray());
status = "User credentials authenticated";
if(warning != null) {
status = status + " \n Warning!!" +warning.toString();
}
} catch(final PasswordException e) {
status = e.toString();
e.printStackTrace();
}
return status;
}
If no error is thrown at final PasswordWarning warning = user credentials are successfully validated.

java ObjectOutputStream create csv file with gibberish data

I have over 300 tables which i want to export to CSV files. However i see gibberish data.
I send the tablename and the retrieve the data using jdbctemplate I can see the data but when i export I see gibberish values
sr1org.springframework.util.LinkedCaseInsensitiveMapiEkMÑ=f$LcaseInsensitiveKeystLjava/util/HashMap
sr1org.springframework.util.LinkedCaseInsensitiveMapiEkMÑ=f$LcaseInsensitiveKeystLjava/util/HashMap
q~q~q~q~xq~sq~?#wq~sq~q~trivera92q~
Below is the code:
exportData.java
public List getTableData(String tableName){
return jdbcTemplate.queryForList("select * FROM " + tableName + " LIMIT 10");
}
To create csv file
#Autowired
ExportData exportData;
public void CreateCsvData(){
String tableName = "user_details";
String folderPath = "/tmp/Data/";
List data = this.exportData.getTableData(tableName);
try {
FileOutputStream fis = new FileOutputStream(folderPath + tableName + ".csv",true);
ObjectOutputStream os = new ObjectOutputStream(fis);
for (int i = 0; i < data.size(); i++) {
os.writeObject(data.get(i));
os.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
here is pom.xml
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<dependencies>
I saw many examples with resultsetextractor and RowMapper but its difficult to write models for 300 tables.
Sorry my bad; I did iterate over the object forgot to paste it here;

NoClassDefFoundError while reading a pdf file

Iam trying to read a pdf file the code is
try {
File fileConn = new File(filePath);
InputStream inp = new FileInputStream(fileConn);
PdfReader reader = new PdfReader(inp);
int pages = reader.getNumberOfPages();
System.out.println("Pages" + pages);
} catch (Exception e) {
//Handle Exception
}
But the method is throwing NOClassDefFoundError. What coukd be the possible reason
Did you added pdfbox and itextpdf to your classpath?
Try this, if you're using maven:
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.0.6</version>
</dependency>

Categories

Resources