I have a serious issue regarding the REST API of Mailjet as used with the recommended v3 library.
When I try to UPDATE I am able to do so for the first time without errors, but when I try to do so again, I got NullPointerException. In spite of that, it does update the stat in the Mailjet Server part.
Also the HTTP Response I get is HTTP/1.1 500 Internal Server Error
Code used:
thisUser=cl.createCall(User.Update).identifiedBy(UserProperty.ID, **myUniqueID**).property(UserProperty.USERNAME, propertyValue).execute();
Any thoughts would be more than welcome.
Ok after the comment, here is the function:
#Path("/userUpdate/{propertyName}/{propertyValue}")
#GET
public Response userUpdate(#PathParam("propertyName") String propertyName, #PathParam("propertyValue") String propertyValue) throws ClientProtocolException, IOException{
MailJetApiClient cl=null;
User thisUser=null;
Response resp=null;
StringEntity stringEntity = null;
try {
cl = MailjetUsersRest.createClient();
} catch (MailJetClientConfigurationException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
thisUser=cl.createCall(User.Get).identifiedBy(UserProperty.ID, ___MY_UNIQUE_ID___).execute();
} catch (MailJetApiCallException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String email = thisUser.getEmail();
String lastip = thisUser.getLastIp();
Date lastlogin = thisUser.getLastLoginAt();
String local = thisUser.getLocale();
String timezone = thisUser.getTimezone();
Date warned = thisUser.getWarnedRatelimitAt();
try {
cl = MailjetUsersRest.createClient();
switch(propertyName){
case "Username":
thisUser=cl.createCall(User.Update).identifiedBy(UserProperty.ID, ___MY_UNIQUE_ID___).property(UserProperty.USERNAME, propertyValue).execute();
resp = Response.status(200).entity(thisUser).build();
break;
default:
System.out.println("Invalid propertyName.");
break;
}
} catch (MailJetClientConfigurationException | MailJetApiCallException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resp;
}
First of all, thank you for using Mailjet!
After some testing, I was unable to reproduce your issue. You will find below the code I used.
However I strongly suggest that you open a ticket with our support here.
A working code
Please note that it is unnecessary and considered bad practice to rebuild the client before each call.
// Build a Mailjet client config
MailJetClientConfiguration config;
config = new MailJetClientConfiguration()
.setBaseUrl("https://api.mailjet.com/v3/REST/")
.setDefaultApiKey(System.getenv("MJ_PROD_PUBLIC"))
.setDefaultSecretKey(System.getenv("MJ_PROD_PRIVATE"));
// Build a Mailjet client
MailJetApiClient client = config.buildClient();
// Your code (adapted to my environment, ie no 'Response' object
// and no client factory.)
User thisUser = null;
try
{
// Note that the 'L' in the 'identifiedBy' value fi is necessary
thisUser = client
.createCall(User.Get)
.identifiedBy(UserProperty.ID, /*Our user's ID*/L)
.execute();
}
catch (MailJetApiCallException e2)
{
e2.printStackTrace();
}
String email = thisUser.getEmail();
String lastip = thisUser.getLastIp();
Date lastlogin = thisUser.getLastLoginAt();
String local = thisUser.getLocale();
String timezone = thisUser.getTimezone();
Date warned = thisUser.getWarnedRatelimitAt();
try
{
thisUser = client
.createCall(User.Update)
.identifiedBy(UserProperty.ID, /*Our user's ID*/L)
.property(UserProperty.USERNAME, "DevRel Team Mailjet")
.execute();
}
catch (MailJetApiCallException e)
{
e.printStackTrace();
}
Copy pasting the last bit (the update process) so that the update call is executed twice (without the same new username, of course) doesn't throw any error and certainly not a NullPointerException or a 500 HTTP error code.
And the username is changed accordingly.
So yeah, as written above, please contact our support here. This will allow us to better help you.
If this answer satisfies you, don't forget to accept & upvote it so that others going through similar issues can know this helped :-)
Related
I'm trying to implement a kick command for my bot, but Guild.kick(Member member) doesn't actually kick the specified user. IntelliJ simply says "Result of Guild.kick(Member member) is ignored". Here's my implementation (with non-relevant code removed):
public void onGuildMessageReceived(#Nonnull GuildMessageReceivedEvent e) {
// other code
g = e.getGuild();
// other code
if (args[0].equalsIgnoreCase("kick")) {
// other code
String target = getConnectedName(args, 1, 0); // gets name of target from message
List<Member> nameList = g.getMembersByEffectiveName(target, true);
try {
target = nameList.get(0).getAsMention();
c.sendMessage("Target: "+target).queue();
} catch (IndexOutOfBoundsException e) {
c.sendMessage("No user found with the name \"target\" in this guild.").queue();
}
Member targetM = null;
if (!nameList.isEmpty()) {
targetM = nameList.get(0);
c.sendMessage(targetM.toString()).queue();
try {
g.kick(targetM);
} catch (HierarchyException e) {
error403MissingPermission(); // sends a message that user is missing permission to use !kick
}
}
}
}
Does anyone know why this won't work / what's wrong with my implementation?
SOLVED:
Guild.kick(Member member) has to be queued like TextChannel.sendMessage(String text) , so the correct usage is g.kick(Member member).queue();. Credit to #Minn
I am given a shortened url and I want to get the expanded form. The below java function is used to achieve this.
public String expand(String shortenedUrl){
URL url = null;
try {
url = new URL(shortenedUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// open connection
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
} catch (IOException e) {
e.printStackTrace();
}
// stop following browser redirect
httpURLConnection.setInstanceFollowRedirects(false);
// extract location header containing the actual destination URL
String expandedURL = httpURLConnection.getHeaderField("Location");
httpURLConnection.disconnect();
return expandedURL;
}
The code works fine in Eclipse but the same doesn't work in android.
String expandedURL = httpURLConnection.getHeaderField("Location");
The above line throws java.lang.RuntimeException: Unable to start activity ComponentInfo. And the error is pointed to the above line. If I remove the above line no error is encountered. Even I am not able to use getResponseCode() function.
int status = 0;
try {
status = httpURLConnection.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
This piece of code also has the same problem. works in eclipse but not in android.
Any kind of help will be greatly appreciated.
Edit: The code using above function is,
ExpandUrl expandUrl = new ExpandUrl();
String expandedUrl = expandUrl.expand(shortenedUrl);
Note: The function expand is defined inside the class ExpandUrl.
Well, the code works in Eclipse but not in android. The reason is that you are doing it in Main thread and blocking it. Android wouldn't allow you to do so and throw runtime error.
I have tried to implement your code using AsyncTask in android. It works fine.
Give it a try.
To know more about AsyncTask follow: Android Documentation on AsyncTask
Good Luck!
that's my first question on stackoverflow ; i need to make a post request (using an inputBean/pojo class for needed paramaters) and get a response (using an outputBean/pojo class to map the json response) using the jira rest api , currently i'm using jersey to do the unmarshallowing thing with json and for annotations, here's the code :
public Resource create(CreateIssueRequest createIssueRequest) {
//creating the issue builder with project key and issuetype
IssueInputBuilder issueBuilder = new IssueInputBuilder(
createIssueRequest.getFields().getProject().getKey()
,createIssueRequest.getFields().getIssueType().getCodeName());
//setting issue fields using the inputBean
issueBuilder.setSummary(createIssueRequest.getFields().getSummary());
issueBuilder.setDescription(createIssueRequest.getFields().getDescription());
//requesting the issue creation method , BasicIssue contains the same fields as my outputbean , this whole thing is the request
BasicIssue issue = jiraClient.getClient().getIssueClient().createIssue(issueBuilder.build()).claim();
//creating the output bean
CreateIssueResponse createIssueResponse = new CreateIssueResponse(
issue.getId(),
issue.getKey(),
issue.getSelf());
try {
jiraClient.getClient().getMetadataClient().getStatus(new URI("localhost:8080/rest/api/2/issue"));
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Resource resource = new Resource();
try {
jiraClient.getClient().close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resource.setData(createIssueResponse);
return resource;
}
what i managed to achieve using this code is creating an issue and obtaining the corresponding outputbean , what i would like instead is getting a Response instance like a jersey one , which has more information attached to it like the status of that response + the entity response (using this code the only thing i get is the entity) ; i've looked for something similar in the jira rest api but i found nothing .
i might have been unclear , if enyone is willing to help me , i'll be glad to clarify any doubts
api:https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-create-issue
i solved surrounding the "post request" with a try catch (when the request doesnt return 201 it throws that exception witch holds some useful data like
try{
issue = jiraClient.getClient().getIssueClient().createIssue(issueBuilder.build()).claim();
}catch(RestClientException e){
ErrorResource error = new ErrorResource();
error.setStatus(e.getStatusCode().get());
error.setDetail(e.getLocalizedMessage());
error.setTitle("An error occurred while creating the issue");
resource.setErrors(new ArrayList<ErrorResource>());
resource.getErrors().add(error);
return resource;
}
As you can see, the official JIRA REST Client abstracts away the response and only gives you the object(s) returned from it.
If you want to keep using the client you need to create a filter or an interceptor or something that catches the response before it gets to the Client.
all my crystal report are publish on my business object server.
all of them are connected to Business Views Object.
all of these Business Views use the same dynamic Data Connection.
This make that my report have this Dynamic Data Connection Parameter.
I can change this parameter via the Central Management Console.
But now I would like to be able to change it via code with the BO's SDK.
I have this method that I think is near achieving what i want , I just can save the changes.
public static void updateParameter(IInfoObject report){
// get all parameters
try {
IReport rpt = (IReport) report;
int i = 0;
IReportParameter params;
for(i=0;i<rpt.getReportParameters().size();i++){
params = (IReportParameter) rpt.getReportParameters().get(i);
int y = 0;
for(y=0;y<params.getCurrentValues().getValues(IReportParameter.ReportVariableValueType.STRING).size();y++){
IParameterFieldDiscreteValue val = (IParameterFieldDiscreteValue) params.getCurrentValues().getValues(IReportParameter.ReportVariableValueType.STRING).getValue(y);
if(val.getDescription().contains("Data Connection")){
val.setValue(boConstance.conn_EXAMPLE1);
val.setDescription(boConstance.desc_EXAMPLE1);
//save the new parameter ?????
System.out.println("report parameters modified");
}
}
}
} catch (SDKException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Any Idea ? Thanks,
Since you are already setting the parameters you should just need to call the save method on the IReport itself. You wouldn't save the parameters directly since they are data belonging to the report.
So to finish your example after the for loop
try {
IReport rpt = (IReport) report;
int i = 0;
IReportParameter params;
for(i=0;i<rpt.getReportParameters().size();i++){
// do for loop here setting the parameters
}
rpt.save();
} catch (SDKException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Apparantely liferay does not log the currently logged in user if you try to login again, and in fact even keeps the currently logged in user logged in.
So I'm trying to force a logout.
I tried:
request.getSession().invalidate();
But that does not seem to work besides somehow breaking the login functionality.
I was wondering if anyone has any other idea how to force a logout.
Edit:
try {
HttpSession session = request.getSession();
EventsProcessorUtil.process(PropsKeys.LOGOUT_EVENTS_PRE,
PropsUtil.getArray(PropsKeys.LOGOUT_EVENTS_PRE), request, response);
String domain = CookieKeys.getDomain(request);
Cookie companyIdCookie = new Cookie(CookieKeys.COMPANY_ID,
StringPool.BLANK);
if (Validator.isNotNull(domain)) {
companyIdCookie.setDomain(domain);
}
companyIdCookie.setMaxAge(0);
companyIdCookie.setPath(StringPool.SLASH);
Cookie idCookie = new Cookie(CookieKeys.ID, StringPool.BLANK);
if (Validator.isNotNull(domain)) {
idCookie.setDomain(domain);
}
idCookie.setMaxAge(0);
idCookie.setPath(StringPool.SLASH);
Cookie passwordCookie = new Cookie(CookieKeys.PASSWORD,
StringPool.BLANK);
if (Validator.isNotNull(domain)) {
passwordCookie.setDomain(domain);
}
passwordCookie.setMaxAge(0);
passwordCookie.setPath(StringPool.SLASH);
CookieKeys.addCookie(request, response, companyIdCookie);
CookieKeys.addCookie(request, response, idCookie);
CookieKeys.addCookie(request, response, passwordCookie);
try {
session.invalidate();
} catch (Exception e) {
}
EventsProcessorUtil.process(PropsKeys.LOGOUT_EVENTS_POST,
PropsUtil.getArray(PropsKeys.LOGOUT_EVENTS_POST), request, response);
} catch (Exception e) {
try {
PortalUtil.sendError(e, request, response);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ServletException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Gives noclassdeffounderrors on cookiekeys/processorserviceutil/... depending on which I replace with a more base level. (like processorserviceutil with a processorserviceimpl and copy the function code from proeccesorserviceutil).
1) session.invalidate() only works if authentication is managed by the application server session, which it is not ;)
2) regardless of whether you use Community or Enterprise edition, you should have enough source code to achieve whatever you want
3) portal-ext.properties supports login chains as well as pre- and post-login hooks
4) Logout calls com.liferay.portal.action.LogoutAction which contains a bunch of logic but without spoiling the ending it should give you enough to shake the other Liferay authentication parts lose.
Hope this helps.