Check Existence of a folder using Dropbox SDK - dropbox-api

In Dropbox SDK 2.0, is there a way to check the existence of a folder? Or do we use the brute force method of listing the folders and then scanning the list?

You can use the /2/files/get_metadata endpoint to check for an existing folder at a given path. It will either return the metadata if it exists, or a path.not_found error if not.
You didn't mention which SDK you're referring to, but for example, in the Dropbox API v2 Java SDK, that corresponds to the DbxUserFilesRequests.getMetadata method.

Here is the complete Java code to check for existence of a folder and create if folder does not exist
DbxClientV2 dbxClient;
try
{
dbxClient.files().getMetadata("/MyFolder");
}
catch (GetMetadataErrorException e)
{
// TODO Auto-generated catch block
if (e.errorValue.isPath())
{
LookupError le = e.errorValue.getPathValue();
if (le.isNotFound())
{
System.out.println("Path doesn't exist on Dropbox: ");
try
{
dbxClient.files().createFolder("/MyFolder");
}
catch (CreateFolderErrorException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (DbxException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}

Related

NullPointerException with lambda expression - working with loops

I have 2 pieces of codes, one written with the java old style and the other is written with lambda expression,
The first:
Class enumClass = getConstantsEnum();
Object[] enumConstants = enumClass.getEnumConstants();
for(Object o:enumConstants) {
try {
constantsMap.put(o.toString(),o.getClass().getDeclaredField("lookupValue").getInt(o));
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
| SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Is working fine and filling the map correctly
The other:
Class enumClass = getConstantsEnum();
Object[] enumConstants = enumClass.getEnumConstants();
constantsMap.putAll(Arrays.asList(enumConstants)
.stream().collect(Collectors.toMap
(e -> e.toString(), e -> {
try {
return e.getClass().getDeclaredField("lookupValue").getInt(e);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
| SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally {
return null;
}
}
)));
Is giving null pointer exception, though by debugging the line e.getClass().getDeclaredField("lookupValue").getInt(e) I see it gets filled by value
My questions are:
1-what is wrong with this code?
2- how can I debug effectively inside stream methods in eclipse, is there a way to see elements getting populated inside the map one by one as in normal loop ? I could see the first element by putting a breakpoint but then the exceptions is fired immediately
3- is there a cleaner way to handle the exception inside the lambda expression, I tried wrapping the whole code with try/catch but compiler is still complaining that the exception is not handled.
Answer to any question is appreciated :)
EDIT:
Q1 answered by Holger in comments
IDE added
As stated in comment posted by Holger in comment, you can see that there is known bug in Java 8, with unresolved status, because of which you cannot put null values using Collectors.toMap, see issue here: https://bugs.openjdk.java.net/browse/JDK-8148463
Intellij IDEA has a great support for debugging Java 8 streams. Check this article: https://www.baeldung.com/intellij-debugging-java-streams
No, there currrently isn't, or I don't know about it. My suggestion for improving your code is to extract a method where you can handle your exception:
constantsMap.putAll(Arrays.asList(enumConstants)
.stream().collect(
Collectors.toMap(e -> e.toString(),
this::getInteger
)));
}
private Integer getInteger(Object e) {
try {
return e.getClass().getDeclaredField("lookupValue").getInt(e);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
| SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
return null;
}
}

drools-7.23.0.Final KieContainerImpl KieBaseException

In running my application, I receive an error: Cannot find a default KieBaseException! called from KieContainerImpl.
I cannot find KieContainerImpl in the source code for drools-7.23.0.Final.
I have searched the source code org.kie.api.KieBase and drools.compiler.builder.imp, but unable to find KieContainerImpl
try
{
kContainer = ks.newKieContainer();
System.out.println("\ninitialized KieContainer:\t" + kContainer);
// Verify that kContainer was properly loaded
Results results = kContainer.verify();
...
/*
* A KieBase represents a compiled version of a set of assets.
*/
kBase = kContainer.getKieBase();
System.out.println("\ninitialized kBase:\n" + kBase);
}
catch (NoClassDefFoundError e)
{
e.printStackTrace();
}
catch (Exception ex)
{
System.out.println("Exception!");
ex.printStackTrace();
}
I expected the verify function to work. Here is the result:
initialized KieContainer: org.drools.compiler.kie.builder.impl.KieContainerImpl#767e20cf
Exception!
java.lang.RuntimeException: Cannot find a default KieBaseException at org.drools.compiler.kie.builder.impl.KieContainerImpl.getKieBase(KieContainerImpl.java:553)
at chemistryAdvisor.ChemistryAdvisor.initializeRuleEngine(ChemistryAdvisor.java:477)
at chemistryAdvisor.ChemistryAdvisor.main(ChemistryAdvisor.java:227)
java.lang.RuntimeException: Cannot find a default KieSession
at org.drools.compiler.kie.builder.impl.KieContainerImpl.findKieSessionModel(KieContainerImpl.java:684)
at org.drools.compiler.kie.builder.impl.KieContainerImpl.newKieSession(KieContainerImpl.java:677)
at org.drools.compiler.kie.builder.impl.KieContainerImpl.newKieSession(KieContainerImpl.java:660)
at chemistryAdvisor.ChemistryAdvisor.initializeRuleEngine(ChemistryAdvisor.java:496)
at chemistryAdvisor.ChemistryAdvisor.main(ChemistryAdvisor.java:227)
Welcome to ChemistryAdvisor!
When invoking kContainer.getKieBase(); without specifying any parameter, Drools expects to find a KieBase marked as default in your kmodule.xml.
Take a look at my answer in this other question.
Hope it helps,

setRedirect(true) in wicket 6.x or 7.x

I have code something like this, So how can I write in wicket 6.x or 7.x
1.
catch (Exception e) {
log.error("**** Exception ***********");
setRedirect(true);
log.errorException(e);
showErrorMsg(getLocalizer().getString("request.process.page.error", this));
}
2.
if (admin != null && admin.getId().equalsIgnoreCase(aId) == false) {
log.error("UserId do not match");
setRedirect(true);
showErrorMsg(getLocalizer().getString("internal.user.gccverf.auth.failed", this));
}
I have method like this
private void showErrorMsg(String errorMsg) {
setResponsePage(new ErrorPage(this.getPage(), getLocalizer().getString("label.applicaiton.error.page", this), errorMsg));
}
Just remove setRedirect(true);.
Another way is to replace it with: setResponsePage(getPage().getPageClass(), getPage().getPageParameters()). This will tell Wicket to create a new instance of the current page's class and render it. In this case it is important that showErrorMsg() uses Session#error() otherwise the error won't be available for the next page.

Class MessagingException not working as I think it should

I'm developing a web application that sends an email and has to check, that, in fact this mail has been delivered from my application side as much as possible in few seconds (I don't think you can do more than getting that the email has been delivered to email server, if that email server later cannot later send that email to the user that uses it because it has its inbox full or another situation like this, I think it cannot be helped, although if there's some way I'd like to know about it).
Anyway one thing I think could be checked without problems is if the email address doesn't exist as that gives an inmediate response, according to what I've read this could be done with class MessageException, but I've the following code:
String email=Utils.parseString(req,"email");
[....]
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.EnableSSL.enable","true");
Session s = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(s);
try {
InternetAddress from = new InternetAddress(emailadressthatworks);
message.setFrom(from);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return;
}
try {
InternetAddress to = new InternetAddress(email);
message.addRecipient(Message.RecipientType.TO, to);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
resp.sendRedirect("webpage.jsp");
return;
}
try {
message.setSubject("Subject");
message.setText("message");
Transport.send(message);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
resp.sendRedirect("webpage.jsp");
return;
}
[....]
And whatever random String I asign to email it never throws an MessagingException in Transport.send(message); so I can redirect it to another jsp web page when I think it should according to what I have read.
Might I be missing something or is it that this class cannot detect that things?
Thanks for your help.
Use the strict InternetAddress constructor and call message.saveChanges() to perform the validation. See
Content-Type syntax check throws exception too late for more details.
See this JavaMail FAQ entry.
Also, it's up to your mail server whether it tries to detect some kinds of errors immediately or whether it queues all requests and only checks for errors later.

Assigning task to mutiple users in scrpted assignment of kaleo worlflow of liferay

I have created a workflow using kaleo workflow.In this i am trying to assign a task to multiple users,I used groovy script in scripted assignment tag for this.But its not working .when am putting two userid's in user object,first one gets replaced and second user got the approvel task.
also i used users arraylist for this,like roles in kaleo single approver scripted assignment definition.but no use.
How can i manage this.
This is my code.
roles=null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String secondid;
try
{
Class.forName(dbDriver);
con= (Connection) DriverManager.getConnection(dbUrl,dbUser,dbPwd);
stmt = con.createStatement();
rs = stmt.executeQuery("select ap1,ap2 from test where id = '"+userId+"'");
users=new ArrayList<User>();
while (rs.next())
{
println "approverid one"+rs.getInt(1);
println "approverid two"+rs.getInt(2);
user=UserLocalServiceUtil.getUser(Long.parseLong(rs.getString(1)));
user=UserLocalServiceUtil.getUser(Long.parseLong(rs.getString(2)));
users.add(user);
println "array list:"+users;
}
rs.close();
con.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
]]>
</script>
<script-language>groovy</script-language>
</scripted-assignment>
when am adding two user id in user tag.also it indicate error in definition while uploading.
In short, use roles. In the control panel, you can specify roles and add users to them. Or, if you'd rather do it programmatically, (Though I would still create the role beforehand) something like this:
(And I'm assuming you can get or have an array of userIds
//Already created array of userIds like
// [10180,10191], etc.
roles=new ArrayList<Role>();
try {
Role r = RoleLocalServiceUtil.getRole(companyId, roleName);
if (r.getType()==RoleConstants.TYPE_REGULAR) {
UserLocalServiceUtil.addRoleUsers(r.getRoleId(), userIds);
} else {
UserGroupRoleLocalServiceUtil.addUserGroupRoles(userIds, groupId, r.getRoleId());
}
roles.add(r);
} catch (SystemException e) {
e.printStackTrace();
} catch (PortalException e) {
e.printStackTrace();
}
Just toss that or some approximation of that or a call to that in your scripted-assignment definition. If you need to, use UserLocalServiceUtil.unsetRoleUsers or something similar to clear out the old users from the role first.