POST-method not working in JAX-RS JERSEY - web-services

I have the following method:
package com.restfully.shop.services;
import java.io.*;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import com.restfully.shop.domain.*;
#Path("/customers")
public class CustomerResource {
private Map<Integer, Customer> customerDB = new ConcurrentHashMap<Integer, Customer>();
private AtomicInteger idCounter = new AtomicInteger();
#POST
#Consumes("application/xml")
public Response createCustomer(InputStream is) {
System.out.println("GOT in POST");
Customer customer = readCustomer(is);
customer.setId(idCounter.incrementAndGet());
customerDB.put(customer.getId(), customer);
System.out.println("Created customer " + customer.getId());
return Response.created(URI.create("/customers/" + customer.getId())).build();
}
#GET
#Path("{id}")
#Produces("application/xml")
public StreamingOutput getCustomer(#PathParam("id") int id) {
Customer cust = new Customer();
cust.setCity("New_york"); cust.setCountry("USA"); cust.setFirstName("Bill");
cust.setId(0); cust.setLastName("Klinton"); cust.setState("MA"); cust.setStreet("Lane st.");
cust.setZip("02610");
customerDB.put(cust.getId(), cust);
final Customer customer = customerDB.get(id);
if (customer == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return new StreamingOutput() {
public void write(OutputStream outputStream)
throws IOException, WebApplicationException {
outputCustomer(outputStream, customer);
}
};
}
#PUT
#Path("{id}")
#Consumes("application/xml")
public void updateCustomer(#PathParam("id") int id, InputStream is) {
System.out.println("GOT in PUT");
Customer update = readCustomer(is);
Customer current = customerDB.get(id);
if (current == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
current.setFirstName(update.getFirstName());
current.setLastName(update.getLastName());
current.setStreet(update.getStreet());
current.setState(update.getState());
current.setZip(update.getZip());
current.setCountry(update.getCountry());
}
protected void outputCustomer(OutputStream os, Customer cust) throws IOException {
PrintStream writer = new PrintStream(os);
writer.println("<customer id=\"" + cust.getId() + "\">");
writer.println("<first-name>" + cust.getFirstName() + "</first-name>");
writer.println("<last-name>" + cust.getLastName() + "</last-name>");
writer.println("<city>" + cust.getCity() + "</city>");
writer.println("<state>" + cust.getState() + "</state>");
writer.println("<zip>" + cust.getZip() + "</zip>");
writer.println("<country>" + cust.getCountry() + "</country>");
writer.println("</customer>");
}
protected Customer readCustomer(InputStream is) {
DocumentBuilder builder;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(is);
Element root = doc.getDocumentElement();
Customer cust = new Customer();
if (root.getAttribute("id") != null
&& !root.getAttribute("id").trim().equals("")) {
cust.setId(Integer.parseInt(root.getAttribute("id")));
}
NodeList nodes = root.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
if (element.getTagName().equals("first-name")) {
cust.setFirstName(element.getTextContent());
} else if (element.getTagName().equals("last-name")) {
cust.setLastName(element.getTextContent());
} else if (element.getTagName().equals("street")) {
cust.setStreet(element.getTextContent());
} else if (element.getTagName().equals("city")) {
cust.setCity(element.getTextContent());
} else if (element.getTagName().equals("state")) {
cust.setState(element.getTextContent());
} else if (element.getTagName().equals("zip")) {
cust.setZip(element.getTextContent());
} else if (element.getTagName().equals("country")) {
cust.setCountry(element.getTextContent());
}
}
return cust;
} catch (Exception e) {
throw new WebApplicationException(e, Response.Status.BAD_REQUEST);
}
}
}
And the following test-client:
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
String req = "<customer>" +
"<first-name>Bill</first-name>" +
"<last-name>Burke</last-name>" +
"<street>256 Kilonrinne</street>" +
"<city>Boston</city>" +
"<state>MA</state>" +
"<zip>02115</zip>" +
"<country>USA</country>" +
"</customer>";
URL url = new URL("http://localhost:8080/customers");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/xml;charset=utf-8");
OutputStream os = con.getOutputStream();
os.write(req.getBytes());
os.flush();
System.out.println(con.getResponseCode());
System.out.println("Location:" + con.getHeaderField("Location"));
con.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
When I test the service - the service seems to work for the #GET-part of the class. But it does not work for the #POST-requests given here.
How can I make it work?

try putting
#POST
#Produces(MediaType.WILDCARD)
#Consumes("application/xml")
in front of post function.

I am not a java developer but i think you can use the #FormParam to read the POST data. It might help. Just make sure you are using 'application/x-www-form-urlencoded' mime type.
Reference: http://docs.jboss.org/resteasy/docs/2.0.0.GA/userguide/html_single/index.html#_FormParam

I'd also say try returning a javax.ws.rs.Response including the streamed output:
StreamingOutput so = new StreamingOutput() {
public void write(OutputStream outputStream)
throws IOException, WebApplicationException {
outputCustomer(outputStream, customer);
}
return Response
.ok(so, MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition", "attachment; file_name = " + ltd.getName())
.header("Content-Length", file_len);

Related

How to mock a private method called inside another private method

I was trying to mock a private method's output which is being called inside another private method, I have no choice but to test the later private method, so I have added sample test code which I can represent here,
This Sample Class
package com.testableClass;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class TestableClass {
private int initialMockMethod(Object obj)
{
System.out.println(" ++++ Came Here ++++ ");
String str = getRestString("");
System.out.println("str ="+str);
return str.length();
}
private String getRestString(String abc)
{
String output="";
try {
URL url = new URL("https://gorest.co.in/public-api/users");//your url i.e fetch data from .
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : "
+ conn.getResponseCode());
}
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
return output;
} catch (Exception e) {
System.out.println("Exception in NetClientGet:- " + e);
}
return abc;
}
}
Now This PowerMock Class
package com.testableClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import junit.framework.Assert;
#RunWith(PowerMockRunner.class)
#PrepareForTest(fullyQualifiedNames = "com.testableClass.TestableClass")
public class PowerMockTest {
#Test
public void testPrivateMethod() throws Exception
{
String message = "Hello PowerMockito";
String expectation = "Expectation";
TestableClass mock = PowerMockito.spy(new TestableClass());
// PowerMockito.doReturn(expectation).when(mock, "getRestString", message);
PowerMockito.when(mock, "getRestString", message).thenReturn(expectation);
int count = Whitebox.invokeMethod(mock, "initialMockMethod", new Object());
System.out.println(" +++ Count : "+count+" ++++ ");
Assert.assertTrue(true);
}
}
my issue is when I am running my test case then
PowerMockito.when(mock, "getRestString", message).thenReturn(expectation);
executes original method and returns original output while my requirement is that,
when my test case is actually calling private method initialMockMethod it should not call getRestString instead of that it should return my mocked expected output which is "Expectation"
Instead of using reflection and PowerMock, I'd say that do not try to mock a private method. It is a hidden detail of the class.
What I suggest is that, if your method makes an HTTP request, then let it do that. But you can use a mock server to mock the response. But to do that, you need to make your endpoint external, so that it can be injected.
I changed your class a little bit; still the same purpose tho.
public class TestableClass {
private final String resourceUrl;
public TestableClass(String resourceUrl) {
this.resourceUrl = resourceUrl;
}
public int publicMethod() {
return initialMockMethod(null);
}
private int initialMockMethod(Object obj) {
var str = getRestString("");
return str.length();
}
private String getRestString(String abc) {
try {
var url = new URL(resourceUrl);
var conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : "
+ conn.getResponseCode());
}
var in = new InputStreamReader(conn.getInputStream());
var br = new BufferedReader(in);
var result = br.lines().collect(Collectors.joining("\n"));
conn.disconnect();
return result;
} catch (Exception e) {
System.out.println("Exception in NetClientGet:- " + e);
}
return abc;
}
}
and here's the test
public class TestingTestableClass {
#Test
#SneakyThrows
public void test() {
final var server = new MockWebServer();
server.start(9999);
var instance = new TestableClass("http://127.0.0.1:9999");
server.enqueue(
new MockResponse()
.setResponseCode(200)
.setBody("this is the response")
);
final int result = instance.publicMethod();
Assertions.assertEquals(
"this is the response".length(),
result
);
final var record = server.takeRequest();
final var method = record.getMethod();
Assertions.assertEquals("GET", method);
server.shutdown();
}
}
Check out MockWebServer here

Testing an API endpoint with Lambda + API Gateway

I'm trying to create and test an API endpoint using AWS Lambda and API Gateway. I can test my function successfully using Lambda Test, but when I try to test my endpoint it gives:
{
"message": "Internal server error"
}
This is my handler class:
package com.amazonaws.lambda.gandhi.conversion.api;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.RandomStringUtils;
import com.amazonaws.lambda.gandhi.conversion.api.Response.AuthClientCredentialResponse;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.lambda.gandhi.conversion.api.utils.ClientAuthPOJO;
public class AuthClientCredentialServiceHandler implements RequestHandler<ClientAuthPOJO, Object> {
private AuthClientCredentialResponse authClientCredentialResponse;
private static final SecureRandom RANDOM = new SecureRandom();
public static int MAX_CLIENT_KEY = 10;
public static int CLIENT_SECRET_LENGTH = 69;
#Override
public AuthClientCredentialResponse handleRequest(ClientAuthPOJO clientIdSecret, Context context) {
String clientSecret;
try {
context.getLogger().log("Input: "
+ clientIdSecret);
String clientId = clientIdSecret.getClientId();
clientSecret = generateClientSecretKey();
Map<String, String> clientCredsMap = getClientCredentials();
if (clientCredsMap.size() > MAX_CLIENT_KEY) {
throw new RuntimeException(String.format("Max limit is %d, Please delete some keys", MAX_CLIENT_KEY));
}
clientCredsMap.forEach((k, v) -> {
if (clientId.equals(k)) {
throw new RuntimeException("Client Already exists");
}
});
storeClientCredentials(clientId, clientSecret);
AuthClientCredentialResponse authClientCredentialResponse = AuthClientCredentialResponse.builder().success(
true).clientId(clientId).clientSecret(clientSecret).build();
this.authClientCredentialResponse = authClientCredentialResponse;
} catch (Exception e) {
throw new RuntimeException(
"Failed to generate client secret: "
+ e.getMessage());
}
return authClientCredentialResponse;
}
private String generateClientSecretKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
String clientSecret = RandomStringUtils.randomAlphanumeric(CLIENT_SECRET_LENGTH);
System.out.printf("clientSecret: %s%n", clientSecret);
return clientSecret;
}
private void storeClientCredentials(String clientId, String clientSecret) throws IOException {
/*
* TODO:
* Some logic to store clientCredentials to a file or DB. Decide later.
*/
System.out.println("temp ClientCredentials stored");
}
public Map<String, String> getClientCredentials() throws IOException {
/*
* TODO:
* Some logic to fetch clientCredentials from file or DB. Decide later.
*/
Map<String, String> clientCredMap = new HashMap<String, String>();
clientCredMap.put("1", "secretKey1");
clientCredMap.put("2", "secretKey2");
clientCredMap.put("3", "secretKey3");
clientCredMap.put("4", "secretKey4");
return clientCredMap;
}
}
My input class:
package com.amazonaws.lambda.gandhi.conversion.api.utils;
public class ClientAuthPOJO {
String clientId;
String clientSecret;
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public ClientAuthPOJO(String clientId, String clientSecret) {
super();
this.clientId = clientId;
this.clientSecret = clientSecret;
}
public ClientAuthPOJO() {
}
}
My test object in lambda:
My test for endpoint in API Gateway:
Can someone please help me figure out the problem in creating the function or API Gateway?
Edit:
When I check the logs, I found that the parameters to the functions (clientId and clientSecret) are null. So there seems to be some problem in the way I'm sending my request body.

WebTestClient does not post object

I am trying to perform simple test of reading method. I am trying to work with reactive approach so to test whole context I am using WebTestClient. Although post method seems to work correctly reading operation is not working. But why? Isn't it should be saved to embedded mongo database?
Do I need to wait for it somehow if this is reactive?
Exception is thrown definitely in service because I am seeing
com.geborskimateusz.util.exceptions.NotFoundException: No product found for productId: 1
This is how test looks like:
#ExtendWith(SpringExtension.class)
#SpringBootTest(webEnvironment = RANDOM_PORT, properties = {"spring.data.mongodb.port: 0"})
public class MovieServiceApplicationTests {
#Autowired
WebTestClient webTestClient;
#Autowired
MovieService movieService;
#Test
public void getMovie() {
Integer given = 1;
postAndVerify(given, HttpStatus.OK);
Movie movie = movieService.getMovie(given); **fails here**
assertNotNull(movie);
getAndVerify(given, HttpStatus.OK);
}
private WebTestClient.BodyContentSpec postAndVerify(Integer id, HttpStatus httpStatus) {
Movie movie = Movie.builder()
.movieId(id)
.title("Title for movie " + id)
.genre("Genre for movie " + id)
.address("Address for movie " + id)
.build();
return webTestClient.post()
.uri("/movie")
.body(Mono.just(movie), Movie.class)
.accept(MediaType.APPLICATION_JSON_UTF8)
.exchange()
.expectStatus().isEqualTo(httpStatus)
.expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8)
.expectBody();
}
private WebTestClient.BodyContentSpec getAndVerify(Integer id, HttpStatus httpStatus) {
return webTestClient.get()
.uri("/movie/" + id)
.accept(MediaType.APPLICATION_JSON_UTF8)
.exchange()
.expectStatus().isEqualTo(httpStatus)
.expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8)
.expectBody()
.jsonPath("$.movieId").isEqualTo(id)
.jsonPath("$.genre").isNotEmpty()
.jsonPath("$.title").isNotEmpty()
.jsonPath("$.address").isNotEmpty();
}
}
Service and repository are very simple implementations:
Service:
#Slf4j
#RestController
public class BaseMovieService implements MovieService {
private final ServiceUtil serviceUtil;
private final MovieRepository movieRepository;
private final MovieMapper movieMapper = MovieMapper.INSTANCE;
#Autowired
public BaseMovieService(ServiceUtil serviceUtil, MovieRepository movieRepository) {
this.serviceUtil = serviceUtil;
this.movieRepository = movieRepository;
}
#Override
public Movie getMovie(Integer movieId) {
if (movieId < 1) throw new InvalidInputException("Invalid productId: " + movieId);
MovieEntity movieEntity = movieRepository.findMovieById(movieId)
.orElseThrow(() -> new NotFoundException("No product found for productId: " + movieId));
Movie movie = movieMapper.entityToApi(movieEntity);
movie.setAddress(serviceUtil.getServiceAddress());
log.debug("/movie return the found movie for movieId={}", movieId);
return movie;
}
#Override
public Movie createMovie(Movie movie) {
try {
MovieEntity movieEntity = movieMapper.apiToEntity(movie);
MovieEntity saved = movieRepository.save(movieEntity);
log.debug("createMovie: entity created for movieId: {}", movie.getMovieId());
return movieMapper.entityToApi(saved);
}catch (DuplicateKeyException e) {
throw new InvalidInputException("Duplicate key for movieId: " +movie.getMovieId());
}
}
#Override
public void deleteMovie(Integer movieId) {
}
}
And repo:
public interface MovieRepository extends PagingAndSortingRepository<MovieEntity, String> {
Optional<MovieEntity> findMovieById(Integer movieId);
}
This is however strange because I am sure that repo work fine, all tests below are passing:
#ExtendWith(SpringExtension.class)
#DataMongoTest
public class MovieRepositoryTest {
public static final int BASE_MOVIE_ID = 1;
#Autowired
MovieRepository movieRepository;
MovieEntity savedMovieEntity;
#BeforeEach
void setUp() {
movieRepository.deleteAll();
MovieEntity movieEntity = MovieEntity
.builder()
.movieId(BASE_MOVIE_ID)
.title("Raise of Jedi")
.address("123.321.54x24")
.genre("Sci-Fi")
.build();
savedMovieEntity = movieRepository.save(movieEntity);
assertEqualsMovie(movieEntity, savedMovieEntity);
}
#Test
void create() {
MovieEntity movieEntity = MovieEntity
.builder()
.movieId(2)
.title("Fall of Jedi")
.address("125.721.54x24")
.genre("Sci-Fi")
.build();
MovieEntity saved = movieRepository.save(movieEntity);
assertEqualsMovie(movieEntity, saved);
assertEquals(2, movieRepository.count());
}
#Test
void update() {
String givenTitle = "Updated Title";
savedMovieEntity.setTitle(givenTitle);
MovieEntity updated = movieRepository.save(savedMovieEntity);
assertEquals(givenTitle, updated.getTitle());
}
#Test
void findById() {
Optional<MovieEntity> optionalMovieEntity = movieRepository.findById(savedMovieEntity.getId());
assertTrue(optionalMovieEntity.isPresent());
MovieEntity movieEntity = optionalMovieEntity.get();
assertEqualsMovie(savedMovieEntity, movieEntity);
}
#Test
void shouldPerformOptimisticLocking() {
String concurrentM1actionData = "Concurrent action data performed on M1";
String concurrentM2actionData = "Concurrent action data performed on M2";
MovieEntity m1 = movieRepository.findById(savedMovieEntity.getId()).get();
MovieEntity m2 = movieRepository.findById(savedMovieEntity.getId()).get();
m1.setTitle(concurrentM1actionData);
// by updating Entity its version should be updated
movieRepository.save(m1);
// should fail because of version mismatch
try {
m2.setTitle(concurrentM2actionData);
movieRepository.save(m2);
fail("Expected an OptimisticLockingFailureException");
} catch (OptimisticLockingFailureException e) {
System.out.println("shouldPerformOptimisticLocking() -> catch OptimisticLockingFailureException");
}
//check current version and state
MovieEntity updatedMovieEntity = movieRepository.findById(savedMovieEntity.getId()).get();
assertEquals(1, (int) updatedMovieEntity.getVersion());
assertEquals(concurrentM1actionData, updatedMovieEntity.getTitle());
}
#Test
void delete() {
movieRepository.delete(savedMovieEntity);
assertEquals(0, movieRepository.count());
}
#Test
void duplicateMovieError() {
MovieEntity duplicate = MovieEntity.builder().build();
duplicate.setId(savedMovieEntity.getId());
assertThrows(DuplicateKeyException.class, () -> movieRepository.save(duplicate));
}
#Test
void paging() {
bulkSaveMovie();
Pageable nextPage = PageRequest.of(0, 4, Sort.Direction.ASC, "movieId");
nextPage = verifyPages(nextPage, "[1, 2, 3, 4]", true);
nextPage = verifyPages(nextPage, "[5, 6, 7, 8]", true);
verifyPages(nextPage, "[9, 10]", false);
}
private Pageable verifyPages(Pageable nextPage, String idsAsString, boolean hasNext) {
Page<MovieEntity> moviePage = movieRepository.findAll(nextPage);
assertEquals(hasNext, moviePage.hasNext());
String ids = moviePage.get().map(MovieEntity::getMovieId).collect(Collectors.toList()).toString();
assertEquals(idsAsString, ids);
return nextPage.next();
}
private void bulkSaveMovie() {
movieRepository.deleteAll();
List<MovieEntity> movies = IntStream.rangeClosed(1, 10)
.mapToObj(i -> MovieEntity.builder()
.movieId(i)
.title("Movie nr: " + i)
.build())
.collect(Collectors.toList());
movieRepository.saveAll(movies);
}
private void assertEqualsMovie(MovieEntity expected, MovieEntity actual) {
assertAll("Executing assertEqualsMovie(..)", () -> {
assertEquals(expected.getId(), actual.getId());
assertEquals(expected.getVersion(), actual.getVersion());
assertEquals(expected.getMovieId(), actual.getMovieId());
assertEquals(expected.getTitle(), actual.getTitle());
assertEquals(expected.getAddress(), actual.getAddress());
assertEquals(expected.getGenre(), actual.getGenre());
});
}
}

EnergyStar Portfolio Manager - Java Client to consume their REST API with Authentication

I am a straight up newbie. After 2 weeks of research, I've arrived at this point, still very lost and desperate.
My goal: Retrieve data from EnergyStar Portfolio Manager Restful web services / API and put that data into a SQL database or an excel worksheet.
Progress so far:
1) I found an example code that seems like it would fit what I need well, except for the authentication part. I am more successful at getting WSDL services to work than RESTful services. Particularly for EnergySTAR, requiring some kind of authentication, which I can't seem to get around to.
2) The retrieve GET protocol: http://portfoliomanager.energystar.gov/webservices/home/test/api/reporting/designMetrics/get
My source code:
package com;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import com.User;
#Path("/wstest/property/")
public class UserManagementModule
{
#GET
#Path("/{propertyId}/design/metrics?measurementSystem=METRIC")
#Produces("application/xml")
public Response getUserById(#PathParam("propertyId") Integer id)
{
User user = new User();
user.setId(id);
return Response.status(200).entity(user).build();
}
}
package com;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.NONE)
#XmlRootElement(name = "propertyMetrics")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#XmlAttribute(name = "propertyId")
private int propertyId;
#XmlElement(name="metric")
private double metric;
#XmlAttribute(name = "designEnergyCost")
private double designEnergyCost;
#XmlAttribute(name = "designScore")
private double designScore;
#XmlAttribute(name = "designSiteTotal")
private double designSiteTotal;
#XmlAttribute(name = "designSiteIntensity")
private double designSiteIntensity;
#XmlAttribute(name = "designTargetEnergyCost")
private double designTargetEnergyCost;
#XmlAttribute(name = "designTargetTotalGHGEmissions")
private double designTargetTotalGHGEmissions;
#XmlAttribute(name = "designTargetSiteTotal")
private double designTargetSiteTotal;
#XmlAttribute(name = "designTargetSiteIntensity")
private double designTargetSiteIntensity;
#XmlAttribute(name = "designTargetSourceTotal")
private double designTargetSourceTotal;
#XmlAttribute(name = "designTargetSourceIntensity")
private double designTargetSourceIntensity;
#XmlAttribute(name = "medianEnergyCost")
private double medianEnergyCost;
#XmlAttribute(name = "medianTotalGHGEmissions")
private double medianTotalGHGEmissions;
#XmlAttribute(name = "medianScore")
private double medianScore;
public int getId() {
return propertyId;
}
public void setId(int propertyId) {
this.propertyId = propertyId;
}
public double getmendianScore() {
return medianScore;
}
//
// public void setFirstName(String firstName) {
// this.firstName = firstName;
// }
// public String getLastName() {
// return lastName;
// }
// public void setLastName(String lastName) {
// this.lastName = lastName;
// }
}
package tests;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import com.User;
public class RestClientXML {
public static void main(String[] args)
{
try
{
URL url = new URL(" https://portfoliomanager.energystar.gov/wstest/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");
if (conn.getResponseCode() != 200)
{
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String apiOutput = br.readLine();
System.out.println(apiOutput);
conn.disconnect();
JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
User user = (User) jaxbUnmarshaller.unmarshal(new StringReader(apiOutput));
System.out.println(user.getId());
/* System.out.println(user.getFirstName());
System.out.println(user.getLastName());
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
I'm know there is some authentication that needs username and pw,so I also tried this piece instead of the RestClient class, but neither works.
public static void main(String[] args) {
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
httpPost = new HttpPost("https://portfoliomanager.energystar.gov/wstest/");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("content-type", "application/xml"));
StringEntity input = new StringEntity("{\"username\": \"yungv1\",\"password\": \"dummypassword\"}");
input.setContentType("application/xml");
httpPost.setEntity(input);
for (NameValuePair h : nvps)
{
httpPost.addHeader(h.getName(), h.getValue());
}
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
response.close();
httpClient.close();
}catch(Exception ex) {
ex.printStackTrace();
}
}
I know it's very sloppy. Can you please point the direction on how I can achieve my goal?
I also tried to run this, and keep getting the 401 errors, which I imagined the authentication fails. I don't know how else to trouble shoot this part and whether there's more thing I need to look into.
conn.setRequestProperty("Authorization", "Basic " + Base64.encodeBase64String((getWebServicesUsername() + ":" + getWebServicesPassword()).getBytes()));
Where conn is HttpURLConnection.

LinkedIn Connections List code is Required for android application

I am new In android and currently working on a project which shows different friend list of different social network.
But Here at the stage I am fail to get LinkedIn Connections List and I have searched rest of the Internet but couldn't find any way. . .
If anyone know the code please help me. . . thanks in advance. .
Cheer!
Sample code is here Bellow. . .
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(
Config.LINKEDIN_CONSUMER_KEY,Config.LINKEDIN_CONSUMER_SECRET, Config.scopeParams);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(Config.LINKEDIN_CONSUMER_KEY,
Config.LINKEDIN_CONSUMER_SECRET);
LinkedInRequestToken liToken;
LinkedInApiClient client;
LinkedInAccessToken accessToken = null;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if( Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
share = (Button) findViewById(R.id.share);
name = (TextView) findViewById(R.id.name);
et = (EditText) findViewById(R.id.et_share);
login = (Button) findViewById(R.id.login);
photo = (ImageView) findViewById(R.id.photo);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
linkedInLogin();
}
});
// share on linkedin
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String share = et.getText().toString();
if (null != share && !share.equalsIgnoreCase("")) {
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Config.LINKEDIN_CONSUMER_KEY, Config.LINKEDIN_CONSUMER_SECRET);
consumer.setTokenWithSecret(accessToken.getToken(), accessToken.getTokenSecret());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://api.linkedin.com/v1/people/~/shares");
try {
consumer.sign(post);
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // here need the consumer for sign in for post the share
post.setHeader("content-type", "text/XML");
String myEntity = "<share><comment>"+ share +"</comment><visibility><code>anyone</code></visibility></share>";
try {
post.setEntity(new StringEntity(myEntity));
org.apache.http.HttpResponse response = httpclient.execute(post);
Toast.makeText(LinkedInSampleActivity.this,
"Shared sucessfully", Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
Toast.makeText(LinkedInSampleActivity.this,
"Please enter the text to share",
Toast.LENGTH_SHORT).show();
}
/*String share = et.getText().toString();
if (null != share && !share.equalsIgnoreCase("")) {
client = factory.createLinkedInApiClient(accessToken);
client.postNetworkUpdate(share);
et.setText("");
Toast.makeText(LinkedInSampleActivity.this,
"Shared sucessfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LinkedInSampleActivity.this,
"Please enter the text to share",
Toast.LENGTH_SHORT).show();
}*/
}
});
}
private void linkedInLogin() {
ProgressDialog progressDialog = new ProgressDialog(
LinkedInSampleActivity.this);
LinkedinDialog d = new LinkedinDialog(LinkedInSampleActivity.this,
progressDialog);
d.show();
// set call back listener to get oauth_verifier value
d.setVerifierListener(new OnVerifyListener() {
#Override
public void onVerify(String verifier) {
try {
Log.i("LinkedinSample", "verifier: " + verifier);
accessToken = LinkedinDialog.oAuthService
.getOAuthAccessToken(LinkedinDialog.liToken,
verifier);
LinkedinDialog.factory.createLinkedInApiClient(accessToken);
client = factory.createLinkedInApiClient(accessToken);
// client.postNetworkUpdate("Testing by Mukesh!!! LinkedIn wall post from Android app");
Log.i("LinkedinSample",
"ln_access_token: " + accessToken.getToken());
Log.i("LinkedinSample",
"ln_access_token: " + accessToken.getTokenSecret());
Person p = client.getProfileForCurrentUser();
name.setText("Welcome " + p.getFirstName() + " "
+ p.getLastName());
name.setVisibility(0);
login.setVisibility(4);
share.setVisibility(0);
et.setVisibility(0);
} catch (Exception e) {
Log.i("LinkedinSample", "error to get verifier");
e.printStackTrace();
}
}
});
// set progress dialog
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.show();
}
}
try this get user-Connections
public class LinkCon_Main extends BaseActivityListView {
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(Config.CONSUMER_KEY,
Config.CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(Config.CONSUMER_KEY, Config.CONSUMER_SECRET);
ProgressDialog mPrograss;
String name;
View experiencePage;
TextView prof_Name, prof_Headline, prof_Location, prof_Industry;
String prof_name, prof_headline, prof_location, prof_industry, prof_summary, prof_experience,prof_education,prof_languages,prof_skills, prof_interests,prof_birthdate,prof_contatct,prof_email;
String con_name, con_headline, con_location,con_industry, con_summary,con_experience,con_education,con_languages,con_skills,con_interets,con_birthdate,con_phone;
Connections con_email;
String pic_url,con_pic_url;
String startDate, endDate;
String item;
String dty;
String dtm;
String dtd;
ImageView person_Pic, con_pic;
Map<SearchParameter, String> searchParameters;
ListView connections_list;
ArrayList<Person> itemslist;
#SuppressWarnings({ "rawtypes" })
Iterator localIterator;
Person mylist;
RelativeLayout layout_persondetils,layout_con_profile;
LinkedInApiClient client;
Person person;
Connections connections;
ImageLoader imageLoader;
DisplayImageOptions options;
LinkConApp myLinkCon;
LayoutInflater inflater;
String[] months= {"Jan", "Feb", "March", "April", "May","June", "July", "August","Sep", "Oct", "Nov", "Dec"};
StringBuilder localStringBuilder;
#Override
#SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLinkCon=new LinkConApp();
prof_Name=(TextView)findViewById(R.id.user_name);
prof_Headline=(TextView)findViewById(R.id.user_headline);
prof_Location=(TextView)findViewById(R.id.user_Location);
prof_Industry=(TextView)findViewById(R.id.user_industry);
person_Pic=(ImageView)findViewById(R.id.profile_pic);
layout_persondetils=(RelativeLayout)findViewById(R.id.layout_profiledetils);
layout_con_profile=(RelativeLayout)findViewById(R.id.layout_con_profile);
layout_persondetils.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
userpersons();
}
});
mPrograss=new ProgressDialog(LinkCon_Main.this);
inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// ImageLoader options
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.photo)
.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
.cacheOnDisc(true).considerExifParams(true).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(this));
connections_list=(ListView)findViewById(R.id.connectionslist);
itemslist = new ArrayList<Person>();
if( Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final SharedPreferences pref = getSharedPreferences(Config.OAUTH_PREF,
MODE_PRIVATE);
final String token = pref.getString(Config.PREF_TOKEN, null);
final String tokenSecret = pref.getString(Config.PREF_TOKENSECRET, null);
if (token == null || tokenSecret == null) {
startAutheniticate();
} else {
showCurrentUser(new LinkedInAccessToken(token, tokenSecret));
}
}
void startAutheniticate() {
mPrograss.setMessage("Loading...");
mPrograss.setCancelable(true);
mPrograss.show();
new AsyncTask<Void, Void, LinkedInRequestToken>() {
#Override
protected LinkedInRequestToken doInBackground(Void... params) {
return oAuthService.getOAuthRequestToken(Config.OAUTH_CALLBACK_URL);
}
#Override
protected void onPostExecute(LinkedInRequestToken liToken) {
final String uri = liToken.getAuthorizationUrl();
getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE)
.edit()
.putString(Config.PREF_REQTOKENSECRET,
liToken.getTokenSecret()).commit();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
}.execute();
mPrograss.dismiss();
}
void finishAuthenticate(final Uri uri) {
if (uri != null && uri.getScheme().equals(Config.OAUTH_CALLBACK_SCHEME)) {
final String problem = uri.getQueryParameter(Config.OAUTH_QUERY_PROBLEM);
if (problem == null) {
new AsyncTask<Void, Void, LinkedInAccessToken>() {
#Override
protected LinkedInAccessToken doInBackground(Void... params) {
final SharedPreferences pref = getSharedPreferences(
Config.OAUTH_PREF, MODE_PRIVATE);
final LinkedInAccessToken accessToken = oAuthService
.getOAuthAccessToken(
new LinkedInRequestToken(
uri.getQueryParameter(Config.OAUTH_QUERY_TOKEN),
pref.getString(
Config.PREF_REQTOKENSECRET,
null)),
uri.getQueryParameter(Config.OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(Config.PREF_TOKEN, accessToken.getToken())
.putString(Config.PREF_TOKENSECRET,
accessToken.getTokenSecret())
.remove(Config.PREF_REQTOKENSECRET).commit();
return accessToken;
}
#Override
protected void onPostExecute(LinkedInAccessToken accessToken) {
mPrograss.dismiss();
showCurrentUser(accessToken);
}
}.execute();
} else {
Toast.makeText(this,
"Appliaction down due OAuth problem: " + problem,
Toast.LENGTH_LONG).show();
finish();
}
}
}
void clearTokens() {
getSharedPreferences(Config.OAUTH_PREF, MODE_PRIVATE).edit()
.remove(Config.PREF_TOKEN).remove(Config.PREF_TOKENSECRET)
.remove(Config.PREF_REQTOKENSECRET).commit();
}
void showCurrentUser(final LinkedInAccessToken accessToken) {
client = factory.createLinkedInApiClient(accessToken);
mPrograss.setMessage("Loading..");
mPrograss.show();
new AsyncTask<Void, Void, Object>() {
#Override
protected Object doInBackground(Void... params) {
try {
final Person user_Profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID));
person = client.getProfileById(user_Profile.getId(), EnumSet.of(
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.PICTURE_URL,
ProfileField.INDUSTRY,
ProfileField.MAIN_ADDRESS,
ProfileField.HEADLINE,
ProfileField.SUMMARY,
ProfileField.POSITIONS,
ProfileField.EDUCATIONS,
ProfileField.LANGUAGES,
ProfileField.SKILLS,
ProfileField.INTERESTS,
ProfileField.PHONE_NUMBERS,
ProfileField.EMAIL_ADDRESS,
ProfileField.DATE_OF_BIRTH,
ProfileField.PUBLIC_PROFILE_URL));
prof_name = person.getFirstName() + " " + person.getLastName();
prof_headline = person.getHeadline();
prof_location = person.getMainAddress();
prof_industry = person.getIndustry();
return person;
} catch (LinkedInApiClientException ex) {
return ex;
}
}
#Override
protected void onPostExecute(Object result) {
if (result instanceof Exception) {
//result is an Exception :)
final Exception ex = (Exception) result;
clearTokens();
Toast.makeText(
LinkCon_Main.this,
"Appliaction down due LinkedInApiClientException: "
+ ex.getMessage()
+ " Authokens cleared - try run application again.",
Toast.LENGTH_LONG).show();
finish();
} else if (result instanceof Person) {
final Person person = (Person) result;
prof_Name.setText( person.getFirstName() + " " + person.getLastName());
prof_Headline.setText(person.getHeadline());
prof_Location.setText(person.getMainAddress());
prof_Industry.setText(person.getIndustry());
prof_Name.setVisibility(0);
prof_Headline.setVisibility(0);
prof_Location.setVisibility(0);
prof_Industry.setVisibility(0);
person_Pic.setVisibility(0);
userConnections();
userDetails();
}
}
}.execute();
mPrograss.dismiss();
}
#Override
protected void onNewIntent(Intent intent) {
finishAuthenticate(intent.getData());
}
public void userDetails(){
if(person.getPictureUrl()!=null){
pic_url = person.getPictureUrl().toString();
imageLoader.displayImage(pic_url, person_Pic);
}else{
person_Pic.setImageResource(R.drawable.ic_launcher);
}
/*************** person Details Summary/experience/education/languages/skills/contacts/interests **********************/
if (person.getSummary()!=null) {
prof_summary = person.getSummary();
}
prof_experience="";
for (Position position:person.getPositions().getPositionList())
{
if(position.isIsCurrent()){
startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
endDate="Currently Working";
}else{
startDate=months[(int) (position.getStartDate().getMonth()-1)]+"-"+position.getStartDate().getYear();
endDate=months[(int) (position.getEndDate().getMonth()-1)]+"-"+position.getEndDate().getYear();
}
prof_experience=prof_experience+"<b>" +"Position :"+"</b>"+position.getTitle()+"<br><b>" +"Company :"+ "</b>"+ position.getCompany().getName()+"<br><b>" +"Start Date:"+ "</b>"+ startDate +"<br><b>" +"End Date:"+ "</b>"+ endDate +"<br>"+"<br>";
}
prof_education="";
for (Education education:person.getEducations().getEducationList())
{
prof_education=prof_education +"<b>" +"Gaduation :"+ "</b>" +education.getDegree()+"<br><b>" +"Institute :"+ "</b>" +education.getSchoolName()+ "<br><b>" +"Graduation Year :"+ "</b>" +education.getEndDate().getYear()+"<br>"+"<br>";
}
prof_languages="";
for(Language language:person.getLanguages().getLanguageList())
{
prof_languages=prof_languages+language.getLanguage().getName()+"\n";
}
prof_skills="";
for(Skill skill:person.getSkills().getSkillList())
{
prof_skills=prof_skills+skill.getSkill().getName()+"\n";
}
prof_contatct="";
PhoneNumbers contactinfo=person.getPhoneNumbers();
if(contactinfo!=null ){
for(PhoneNumber phoneno:person.getPhoneNumbers().getPhoneNumberList())
{
prof_contatct=prof_contatct+ phoneno.getPhoneNumber().toString();
}
}
if(person.getEmailAddress()!=null){
prof_email=person.getEmailAddress();
}
prof_interests = person.getInterests();
prof_birthdate= person.getDateOfBirth().getDay()+"-"+ months[(int) (person.getDateOfBirth().getMonth()-1)]+"-"+person.getDateOfBirth().getYear();
}
public void userConnections(){
final Set<ProfileField> connectionFields = EnumSet.of(ProfileField.ID,
ProfileField.FIRST_NAME,
ProfileField.LAST_NAME,
ProfileField.HEADLINE,
ProfileField.INDUSTRY,
ProfileField.PICTURE_URL,
ProfileField.MAIN_ADDRESS,
ProfileField.LOCATION,
ProfileField.LOCATION_COUNTRY,
ProfileField.LOCATION_NAME,
ProfileField.SUMMARY,
ProfileField.EDUCATIONS,
ProfileField.EDUCATIONS_DEGREE,
ProfileField.EDUCATIONS_END_DATE,
ProfileField.EDUCATIONS_FIELD_OF_STUDY,
ProfileField.EDUCATIONS_ID,
ProfileField.EDUCATIONS_SCHOOL_NAME,
ProfileField.EDUCATIONS_START_DATE,
ProfileField.LANGUAGES,
ProfileField.LANGUAGES_ID,
ProfileField.LANGUAGES_LANGUAGE,
ProfileField.LANGUAGES_LANGUAGE_NAME,
ProfileField.POSITIONS,
ProfileField.POSITIONS_COMPANY,
ProfileField.POSITIONS_COMPANY_INDUSTRY,
ProfileField.POSITIONS_COMPANY_NAME,
ProfileField.POSITIONS_END_DATE,
ProfileField.POSITIONS_IS_CURRENT,
ProfileField.POSITIONS_START_DATE,
ProfileField.POSITIONS_SUMMARY,
ProfileField.POSITIONS_TITLE,
ProfileField.SKILLS,
ProfileField.INTERESTS,
ProfileField.PHONE_NUMBERS,
ProfileField.EMAIL_ADDRESS,
ProfileField.DATE_OF_BIRTH,
ProfileField.PUBLIC_PROFILE_URL
);
connections = client.getConnectionsForCurrentUser(connectionFields);
for (Person person : connections.getPersonList()) {
itemslist.add(person);
}
connection_Adapter myadpter=new connection_Adapter();
connections_list.setAdapter(myadpter);
connections_list.setVisibility(0);
connections_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*Connections List item position selection*/
person = itemslist.get(position);
/*
Map<SearchParameter, String> searchParameters = new EnumMap<SearchParameter, String>(SearchParameter.class);
searchParameters.put(SearchParameter.KEYWORDS, "University of X");
People people = client.searchPeople(searchParameters);
System.out.println("Total search result:" + people.getCount());
for (Person person : people.getPersonList()) {
System.out.println(person.getId() + ":" + person.getFirstName() + " " +
person.getLastName() + ":" + person.getHeadline());
}*/
/*
People people = client.searchPeople(searchParameters);
for (Person persons : people.getPersonList()) {
persons = client.getProfileByApiRequest(persons.getApiStandardProfileRequest());
}
Log.i("My Persons list", ""+person);*/
/*Intent mycon=new Intent(LinkCon_Main.this, Con_Profile.class);
mycon.putExtra("conid", con_name);
startActivity(mycon);
*/
con_name=person.getFirstName()+" "+person.getLastName();
System.out.println("Name:"+con_name);
con_headline=person.getHeadline();
System.out.println("Designation:"+con_headline);
con_industry=person.getIndustry();
System.out.println("Industry:"+con_industry);
Location localLocation = person.getLocation();
if (localLocation != null){
con_location=String.format("%s", new Object[] { localLocation.getName() });
System.out.println("Con_Loaction:"+con_location);
}
/*****PICTURE/NAME/INDUSTRY/LOCATION Tested OK******/
/********need to get SUMMARY/EXPERIENCE/EDUCATION/SKILLS/LANGUAGES/DATEOFBIRTH/PHONENUMBER/EMAIL**********/
Toast.makeText(LinkCon_Main.this, "Name:"+" "+con_name +"\n"+"Position:"+" "+con_headline+"\n"+"Industry:"+" "+con_industry+"\n"+"Locations:"+" "+con_location, Toast.LENGTH_LONG).show();
}//onItemClick
});
}
public class connection_Adapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemslist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if(convertView==null){
convertView = inflater.inflate(R.layout.list_row,
null);
holder = new ViewHolder();
holder.con_Itenames = (TextView) convertView
.findViewById(R.id.connection_name);
holder.con_designations = (TextView) convertView
.findViewById(R.id.connection_headline);
holder.con_ItemImage = (ImageView) convertView
.findViewById(R.id.connection_image);
holder.con_locationad = (TextView) convertView
.findViewById(R.id.connection_location);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
SetData(holder,position);
return convertView;
}
protected Context getBaseContext() {
// TODO Auto-generated method stub
return null;
}
public void SetData(final ViewHolder holder, int position) {
final Person con_details = itemslist.get(position);
holder.con_Itenames.setText(con_details.getFirstName()+" "+con_details.getLastName());
holder.con_designations.setText(con_details.getIndustry());
Location localLocation = con_details.getLocation();
if (localLocation != null){
con_location=String.format("%s", new Object[] { localLocation.getName() });
}
holder.con_locationad.setText(con_location);
holder.con_Itenames.setTag(con_details);
if (con_details.getPictureUrl()!=null) {
imageLoader.displayImage(con_details.getPictureUrl(), holder.con_ItemImage, options);
}else {
holder.con_ItemImage.setImageResource(R.drawable.ic_launcher);}
}
public void setListItems(ArrayList<Person> newList) {
itemslist = newList;
notifyDataSetChanged();
}
}
public class ViewHolder{
TextView con_Itenames,con_designations, con_locationad;
ImageView con_ItemImage;
}
private void userpersons() {
// TODO Auto-generated method stub
Intent user_prof = new Intent(LinkCon_Main.this, User_Profile.class);
user_prof.putExtra("pic", pic_url);
user_prof.putExtra("name", prof_name);
user_prof.putExtra("headline", prof_headline);
user_prof.putExtra("locations", prof_location);
user_prof.putExtra("industry", prof_industry);
user_prof.putExtra("summary", prof_summary);
user_prof.putExtra("languages", prof_languages);
user_prof.putExtra("experience", prof_experience);
user_prof.putExtra("education", prof_education);
user_prof.putExtra("skills", prof_skills);
user_prof.putExtra("interests", prof_interests);
user_prof.putExtra("dateofbirth", prof_birthdate);
user_prof.putExtra("phoneno", prof_contatct);
user_prof.putExtra("email", prof_email);
startActivity(user_prof);
}
}