I'm trying to obtain the shipping address of a buyer via the EBay Developers API however I am getting a NullPointerException. I do not understand why since I am sure the buyer has paid for the item and has a shipping address.
This is the code I'm using:
GetSellerTransactionsCall getSellerTransactions = new GetSellerTransactionsCall();
getSellerTransactions.setApiContext(getAPIContext());
Calendar calFrom = new GregorianCalendar();
Date todayFrom = new Date();
calFrom.setTime(todayFrom);
calFrom.add(Calendar.DAY_OF_MONTH, -29);
Calendar calTo = new GregorianCalendar();
Date todayTo = new Date();
calTo.setTime(todayTo);
TimeFilter modifiedTimeFilter = new TimeFilter(calFrom, calTo);
getSellerTransactions.setModifiedTimeFilter(modifiedTimeFilter);
TransactionType[] transactionType = getSellerTransactions.getSellerTransactions();
System.out.println("Size: " + transactionType.length);
// ^^ This returns 2 items as length
UserType userType = transactionType[1].getBuyer();
AddressType shippingAddress = userType.getShippingAddress();
String buyerFirstName = shippingAddress.getFirstName();
// ^^ This line causes a NullPointerException. Same error when I try to get the street address or any other shipping details of buyer. I can get the buyers email just fine using String email = userType.getEmail(); but no shipping details.
Related
My service would throw an InvalidOperationException if the result of the query
PaymentDetails.findByIdAndAmountDateCreatedGreaterThanEquals is NOT NULL
The function aims to check if there are duplicate details from the last 5 minutes.
I'm trying to create a unit test for this but the function always returns NULL instead
given:
DateUtils.getCurrentDate() >> new Date()
Date currentDate = new Date()
Date twoMinutesBeforeCurrentDate = new Date()
use (TimeCategory) {
twoMinutesBeforeCurrentDate = currentDate - 2.minutes
}
long methodId = 3L
BigDecimal amount = new BigDecimal("5")
PaymentDetails details = new PaymentDetails(amount: amount, id:methodId).save(flush: true)
details.dateCreated = twoMinutesBeforeCurrentDate
details.save(flush: true)
when:
service.validateTransactionDetails(methodId, amount)
then:
InvalidOperationException exception = thrown()
ApiError.SAME_PAYMENT_DETAILS_WITH_PREVIOUS_TRANSACTION == exception.apiError
Here is my service method:
Date currentDate = DateUtils.getCurrentDate()
Date fiveMinutesBeforeCurrentDate = null
use (TimeCategory) {
fiveMinutesBeforeCurrentDate = currentDate-5.minutes
}
PaymentDetails details = PaymentDetails.findByIdAndAmountDateCreatedGreaterThanEquals(methodId, amount, fiveMinutesBeforeCurrentDate)
if (details) {
throw new InvalidOperationException(ApiError.SAME_PAYMENT_DETAILS_WITH_PREVIOUS_TRANSACTION)
}
Thank you in advance! It's my first time debugging something from Grails and I'm having a hard time on this. Please be gentle. Lol.
The problem is that new PaymentDetails(amount: amount, id:methodId) isn't really valid because ids are by default excluded from mass property binding so your PaymentDetails instance does not have the id you think it does (you can verify that by inspecting the object in the debugger if you like). A better idea is to let the entity be assigned an id by the save method and then retrieve that value later to initiate the query. This works:
import grails.testing.gorm.DataTest
import grails.testing.services.ServiceUnitTest
import groovy.time.TimeCategory
import spock.lang.Specification
class PaymentServiceSpec extends Specification implements ServiceUnitTest<PaymentService>, DataTest{
#Override
Class[] getDomainClassesToMock() {
[PaymentDetails]
}
void "test payment details validation"() {
given:
Date currentDate = new Date()
GroovySpy(DateUtils, global: true)
1 * DateUtils.getCurrentDate() >> currentDate
Date twoMinutesBeforeCurrentDate
use (TimeCategory) {
twoMinutesBeforeCurrentDate = currentDate - 2.minutes
}
BigDecimal amount = new BigDecimal("5")
PaymentDetails details = new PaymentDetails(amount: amount).save(flush: true)
when:
service.validateTransactionDetails(details.id, amount)
then:
InvalidOperationException exception = thrown()
ApiError.SAME_PAYMENT_DETAILS_WITH_PREVIOUS_TRANSACTION == exception.apiError
}
}
I hope that helps.
I'm fetching the messages from authorized email but the problem is the separation of Subject, From, and To values from headers in java, I succeed in that below code is working fine but it is taking more time for separation, I have gone through so much Gmail API documentation but I didn't get the solution.
ListMessagesResponse listResponse = service.users().messages().list(user).setMaxResults(10L)
.setLabelIds(labelidlist).setQ(query).execute();
List<Message> listofmesssages = listResponse.getMessages();
HashMap<String, Object> msgsMap;
List messageslist = new ArrayList();
for (Message message : listofmesssages) {
Message fullmessage = service.users().messages().get("me", message.getId()).setFormat("full").execute();
msgsMap = new LinkedHashMap<String, Object>();
/*Adding threadid for threadid is required when delete operation has happen*/
msgsMap.put("threadid", message.getThreadId());
List<MessagePartHeader> headers = fullmessage.getPayload().getHeaders();
if (!headers.isEmpty()) {
for (MessagePartHeader header : headers) {
String name = header.getName();
msgsMap.put("msgid", message.getId());
if (name.equalsIgnoreCase("Subject")) {
subject = header.getValue();
msgsMap.put("subject", subject);
} else if (name.equalsIgnoreCase("From")) {
from = header.getValue().split("<")[0];
msgsMap.put("from", from);
} else if (name.equalsIgnoreCase("To")) {
to = header.getValue().split(" ")[0];
msgsMap.put("to", to);
} else if (name.equalsIgnoreCase("Date")) {
String date = header.getValue();
java.util.Date fecha = new java.util.Date(date);
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
Date date1;
date1 = (Date) formatter.parse(fecha.toString());
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/"
+ cal.get(Calendar.YEAR);
msgsMap.put("date", formatedDate);
}
}
}
messageslist.add(msgsMap);
}
return messageslist;
If you look at the message resource JSON, you can see that headers is an array of objects that contain properties name and value. There is no property key called To, or Subject. That's the reason the library you're using has no methods called getTo, or getSubject.
This makes sense, since headers might not always be the same ones.
Because of this, you cannot specifically fetch a certain header name.
Reference:
Users.messages
getHeaders()
In my current Java/Spring project, I am in the phase of integration with PayPal. After configure a Java class to handle the payment process, following the instructions from here, I run my application and try to checkout an order with paypal.
I am redirected correctly to the PayPal login page, and after the login, to this payment review page:
but then after I click on "Continue", instead of finalizing the payment, I am redirected to my profile page.
Here is my code:
Paypal prop = this.paypalDao.get();
String clientId = prop.getClientID();
String clientSecret = prop.getClientSecret();
APIContext apiContext = new APIContext(clientId, clientSecret, "sandbox");
if(payerId != null) {
if(guid != null) {
Payment payment = new Payment();
payment.setId(map.get(guid));
PaymentExecution paymentExecution = new PaymentExecution();
paymentExecution.setPayerId(payerId);
payment.execute(apiContext, paymentExecution);
String url = request.getContextPath();
return url+"/orders";
}
} else {
List<Produto> lista_de_produtos = this.getListaDeProdutos(clienteId);
Double total = 0.0;
for(Produto produto : lista_de_produtos)
total = total + produto.getPreco();
DecimalFormat df = new DecimalFormat("0.00");
String svalue = df.format(total).replace(',', '.');
Details details = new Details();
details.setSubtotal(svalue);
Amount amount = new Amount();
amount.setCurrency("BRL");
amount.setTotal(svalue);
amount.setDetails(details);
Transaction transaction = new Transaction();
transaction.setAmount(amount);
transaction.setDescription(lista_de_produtos.toString());
List<Transaction> transactions = new ArrayList<Transaction>();
transactions.add(transaction);
Payer payer = new Payer();
payer.setPaymentMethod("paypal");
Payment payment = new Payment();
payment.setIntent("sale");
payment.setPayer(payer);
payment.setTransactions(transactions);
RedirectUrls redirectUrls = new RedirectUrls();
guid = UUID.randomUUID().toString();
String url = request.getContextPath();
redirectUrls.setCancelUrl( url+"/cart" );
redirectUrls.setReturnUrl( url+"/paypal/checkout/"+clientId+"/?guid=" + guid );
payment.setRedirectUrls(redirectUrls);
Payment createdPayment = payment.create(apiContext);
Iterator<Links> links = createdPayment.getLinks().iterator();
while (links.hasNext()) {
Links link = links.next();
if (link.getRel().equalsIgnoreCase("approval_url")) {
map.put("redirectURL", link.getHref());
redirectURL = link.getHref();
}
}
map.put(guid, createdPayment.getId());
payment.setId(map.get(guid));
}
return redirectURL;
Can someone tell me, what am I missing here?
Try printing this value:
System.out.println(url+"/paypal/checkout/"+clientId+"/?guid=" + guid);
The result should be https://www.yoursite.com/paypal/checkout/<number>/?guid=<number>, or a page that would direct there (leaving out https:// to save on bytes could be okay depending on your server configuration).
Additional tests you should try:
Try cancelling on your site.
Try cancelling the payment on paypal's site.
Iff one works but the second does not, then paypal is not redirecting properly, which probably means you're not giving it the right string. Also see comment by #Emile.
Each document contains date property shows when it is stored, so how can I fetch data stored on particular date or between two dates. What is the best way to do this. My implementation is based on Java. Thanks in advance.
I don't have the Java code, but you'll have to set up your collection to use Range indexing on the DateTime strings, then you'll be able to query for dates within a certain time range. The .NET code is to set up range indexing is:
DocumentCollection collection = new DocumentCollection { Id = "orders" };
collection.IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 });
await client.CreateDocumentCollectionAsync("/dbs/orderdb", collection);
See https://learn.microsoft.com/en-us/azure/documentdb/documentdb-working-with-dates#indexing-datetimes-for-range-queries and search for Range on this page https://learn.microsoft.com/en-us/azure/documentdb/documentdb-indexing-policies.
Just using Azure DocumentDB SDK for Java to query documents by _ts property. The document _ts property is as below.
_ts: This is a system generated property. It specifies the last updated timestamp of the resource. The value is a timestamp.
Here is my sample code as below. The _ts unit is second.
// Initialize a DocumentDb client.
String serviceEndpoint = "https://<your-documentdb-name>.documents.azure.com:443/";
String masterKey = "<your-documentdb-key>";
DocumentClient client = new DocumentClient(serviceEndpoint, masterKey, ConnectionPolicy.GetDefault(), ConsistencyLevel.Session);
// Get a collection link via collection id.
String collId = "<collection-Id>";
String query = String.format("SELECT * from ROOT r WHERE r.id = '%s'", dcId);
FeedOptions options = null;
List<DocumentCollection> dcs = client.queryCollections(dbLink, query, options).getQueryIterable().toList();
String collLink = dcs.size() >0 ? dcs.get(0).getSelfLink() : null;
// Generate a query string, see below.
.......
client.queryDocuments(collection.getSelfLink(), query, null);
A query string for fetching data stored on particular date:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = "2017-03-01";
long timestamp = sdf.parse(dateStr).getTime()/1000;
String query = String.format("select * from c where c._ts = %d", timestamp);
A query string for fetching data stored between two dates:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startDateStr = "2017-03-01";
String endDateStr = "2017-03-31";
long tsStart = sdf.parse(startDateStr).getTime()/1000;
long tsEnd = sdf.parse(endDateStr).getTime()/1000;
String query = String.format("select * from c where c._ts >= %d and c._ts <= %d", tsStart, tsEnd);
I want to create an AD user with accountExpires attribute. I am doing like this
public boolean addUser(
String firstName,
String lastName,
String userName,
String password,
String organisationUnit) throws NamingException {
if (findUser(userName, firstName, lastName, organisationUnit)) {
return false;
} else {
// Create a container set of attributes
BasicAttributes container = new BasicAttributes();
// Create the objectclass to add
Attribute objClasses = new BasicAttribute("objectClass");
objClasses.add("top");
objClasses.add("person");
objClasses.add("organizationalPerson");
objClasses.add("user");
// Assign the username, first name, and last name
String cnValue = new StringBuffer(firstName).append(" ").append(lastName).toString();
Attribute cn = new BasicAttribute("cn", cnValue);
Attribute sAMAccountName = new BasicAttribute("sAMAccountName", userName);
Attribute mac = new BasicAttribute("msNPCallingStationID", "ab-ab-ab-b7-6t");
Attribute principalName = new BasicAttribute("userPrincipalName", userName + "#atamunet.com");
Attribute givenName = new BasicAttribute("givenName", firstName);
Attribute sn = new BasicAttribute("sn", lastName);
Attribute uid = new BasicAttribute("uid", userName);
Attribute fullName = new BasicAttribute("displayName", "fullName");
Attribute gender = new BasicAttribute("initials", "gender");
Attribute dob = new BasicAttribute("description", "dob");
Attribute FatherName = new BasicAttribute("physicalDeliveryOfficeName", "FatherName");
Attribute Email = new BasicAttribute("mail", "Email");
Attribute mobile = new BasicAttribute("mobile", "mobile");
Attribute department = new BasicAttribute("department", "department");
Attribute HallName = new BasicAttribute("streetAddress", "HallName");
Attribute FacultyName = new BasicAttribute("company", "FacultyName");
Attribute CourseName = new BasicAttribute("title", "CourseName");
Attribute accountExpires = new BasicAttribute("accountExpires", new Date());
//some useful constants from lmaccess.h
int UF_ACCOUNTENABLE = 0x0001;
//int UF_ACCOUNTDISABLE = 0x0002;
int UF_PASSWD_NOTREQD = 0x0020;
int UF_PASSWD_CANT_CHANGE = 0x0040;
int UF_NORMAL_ACCOUNT = 0x0200;
int UF_DONT_EXPIRE_PASSWD = 0x10000;
//int UF_PASSWORD_EXPIRED = 0x800000;
Attribute enabled = new BasicAttribute("userAccountControl", Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWD_NOTREQD + UF_DONT_EXPIRE_PASSWD + UF_ACCOUNTENABLE));
// Add password
Attribute userPassword = new BasicAttribute("userpassword", password);
// Add these to the container
container.put(objClasses);
container.put(sAMAccountName);
container.put(principalName);
container.put(cn);
container.put(sn);
container.put(givenName);
container.put(uid);
container.put(userPassword);
container.put(mac);
container.put(gender);
container.put(dob);
container.put(FatherName);
container.put(Email);
container.put(mobile);
container.put(department);
container.put(HallName);
container.put(FacultyName);
container.put(CourseName);
container.put(fullName);
container.put(enabled);
container.put(accountExpires);
// Create the entry
try {
ctx.createSubcontext(getUserDN(cnValue, organisationUnit), container);
return true;
} catch (Exception e) {
System.out.println(e.getMessage() + "add");
return false;
}
}
}
How can I add user with accountExpires attribute. Is there anybody can help me. Without this line
Attribute accountExpires = new BasicAttribute("accountExpires", new Date());
Everything goes fine but I want the expiry date as well.
You are setting the attribute to the current date, but this is not correct.
First of all because the attribute is an interval of 100-nanoseconds, according to the Microsoft documentation and this.
What you have to do is set your desired expiration date, then convert to the value of 100-nanoseconds, that in Java are represented by long.
Here is a trivial code example that show you how to do it with Java 8:
UPDATED:
Calendar cal = Calendar.getInstance();
// First you need to get the start date
// according to the documentation it is
// the 1th January of 1601
cal.set(1601, Calendar.JANUARY, 1);
// print the current date
System.out.println(String.format("Start date: %tc", cal));
Date startDate = cal.getTime();
// Reset the calendar to today
cal.set(Calendar.MILLISECOND, System.currentTimeMillis());
// Set the desired expiration date
// here is 1 year in the future
cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + 1);
// print the current date
System.out.println(String.format("Expire date: %tc", cal));
// Get the date from Calendar
Date expireDate = cal.getTime();
// Create an interval from the startDate to the expireDate
// and convert it to nanoseconds interval
long expirationInterval = TimeUnit.NANOSECONDS.toNanos(expireDate.getTime()-startDate.getTime());
// set the attribute value
Attribute accountExpires = new BasicAttribute("accountExpires", expirationInterval);
Thanks for your help what gave me the idea and this code worked for me
/**
* Difference between Filetime epoch and Unix epoch (in ms).
*/
private static final long FILETIME_EPOCH_DIFF = 11644473600000L;
/**
* One millisecond expressed in units of 100s of nanoseconds.
*/
private static final long FILETIME_ONE_MILLISECOND = 10 * 1000;
public static long filetimeToMillis(final long filetime) {
return (filetime / FILETIME_ONE_MILLISECOND) - FILETIME_EPOCH_DIFF;
}
public static long millisToFiletime(final long millis) {
return (millis + FILETIME_EPOCH_DIFF) * FILETIME_ONE_MILLISECOND;
}
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "01-07-2017 10:20:56";
Date date = sdf.parse(dateInString);
final long dd = date.getTime();
Attribute accountExpires = new BasicAttribute("accountExpires", Long.toString(millisToFiletime(dd)));