I am trying to access Google Docs API V1 document in Java Servlet using AbstractAuthorizationCodeServlet provide by google api client library but code give error it can't build object of Doc Builder. I have auth 2 creatential and Google doc api is enable from google developer console. below is my code.
#WebServlet("/GetGoogleDoc")
public class GetGoogleDoc extends AbstractAuthorizationCodeServlet {
private static final long serialVersionUID = 1L;
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final List<String> SCOPES = Collections.singletonList(DocsScopes.DOCUMENTS_READONLY);
private static final String DOCUMENT_ID = "";
private static final String CLIENT_ID="";
private static final String CLIENT_SECRET="";
public GetGoogleDoc() {
super();
// TODO Auto-generated constructor stub
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Docs service = new Docs.Builder(HTTP_TRANSPORT, JSON_FACTORY, initializeFlow())
.build();
}
#Override
protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
GenericUrl url = new GenericUrl(req.getRequestURL().toString());
url.setRawPath("/oauth2callback");
return url.build();
}
#Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
return new GoogleAuthorizationCodeFlow.Builder(
new NetHttpTransport(), JSON_FACTORY, CLIENT_ID,CLIENT_SECRET,SCOPES).build();
}
#Override
protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
return null;
// return user ID
}
static void replaceNamedRange(Docs service, String documentId, String rangeName, String newText)
throws IOException {
Document document = service.documents().get(documentId).execute();
NamedRanges namedRangeList = document.getNamedRanges().get(rangeName);
if (namedRangeList == null) {
throw new IllegalArgumentException("The named range is no longer present in the document.");
}
List<Range> allRanges = new ArrayList<>();
Set<Integer> insertIndexes = new HashSet<>();
for (NamedRange namedRange : namedRangeList.getNamedRanges()) {
allRanges.addAll(namedRange.getRanges());
insertIndexes.add(namedRange.getRanges().get(0).getStartIndex());
}
// Sort the list of ranges by startIndex, in descending order.
allRanges.sort(Comparator.comparing(Range::getStartIndex).reversed());
// Create a sequence of requests for each range.
List<Request> requests = new ArrayList<>();
for (Range range : allRanges) {
// Delete all the content in the existing range.
requests.add(
new Request().setDeleteContentRange(new DeleteContentRangeRequest().setRange(range)));
if (insertIndexes.contains(range.getStartIndex())) {
// Insert the replacement text.
requests.add(
new Request()
.setInsertText(
new InsertTextRequest()
.setLocation(
new Location()
.setSegmentId(range.getSegmentId())
.setIndex(range.getStartIndex()))
.setText(newText)));
// Re-create the named range on the new text.
requests.add(
new Request()
.setCreateNamedRange(
new CreateNamedRangeRequest()
.setName(rangeName)
.setRange(
new Range()
.setSegmentId(range.getSegmentId())
.setStartIndex(range.getStartIndex())
.setEndIndex(range.getStartIndex() + newText.length()))));
}
}
BatchUpdateDocumentRequest batchUpdateRequest =
new BatchUpdateDocumentRequest()
.setRequests(requests)
.setWriteControl(new WriteControl().setRequiredRevisionId(document.getRevisionId()));
service.documents().batchUpdate(documentId, batchUpdateRequest).execute();
}
}
I've these two methods from my MetadataManagement class which I'd like to unit test:
#Override
protected void doPut(final HttpServletRequest request, final HttpServletResponse response,
final MetadataResource resource)
throws IOException {
ServiceCommon.checkRole(getSubject(request));
if (resource.getType() != Type.CONTAINER) {
final String err = "Request not allowed for " + request.getURI();
throw new ServiceApiException(ServiceApiError.METHOD_NOT_ALLOWED, err);
}
final String name = getContainerName(resource);
final ServiceApiMetadata config = getConfig(request, PATH);
final StorageLocation storageLocation = getStorageLocation(conf.getStorageLocation());
if (config.getNotifications() != null) {
checkMethodSupported(id);
checkService(id);
}
}
private ServiceApiMetadata getConfig(final HttpServletRequest request, final String path)
throws IOException {
final Schema schema;
try (final InputStream inStream = this.getClass().getResourceAsStream(path)) {
final JSONObject origSchema = new JSONObject(new JSONTokener(inStream));
if (isGoldStar()) {
origSchema.getJSONObject("properties")
.getJSONObject("notifications")
.getJSONObject("properties")
.getJSONObject("topic")
.put("pattern", "^[0-9A-Za-z-.]*$");
}
schema = SchemaLoader.load(origSchema);
}
final ServiceApiMetadata config;
try (final BufferedReader reader = request.getReader()) {
final JSONObject json = new JSONObject(new JSONTokener(reader));
schema.validate(json);
config = ServiceApiMetadata.read(json);
} catch (final ValidationException e) {
_logger.debug(e.getMessage());
if (e.getLocation().contains("#/properties/notifications")) {
throw new ServiceApiException(ServiceApiError.MALFORMED_NOTIFICATIONS_ERROR,
ServiceApiErrorMessage.MALFORMED_JSON);
} else {
throw new ServiceApiException(ServiceApiError.MALFORMED_JSON);
}
} catch (final JSONException e) {
_logger.debug(e.getMessage());
throw new ServiceApiException(ServiceApiError.MALFORMED_JSON);
}
return config;
}
As I understand it I can not directly call getConfig in my test because the method is private. I believe using reflection is an option but is not advised. Based on that, any test of getConfig should be done through doPut.
What I'm most interested in checking is if getConfig.isGoldStar is true, the origSchema pattern updates to ^[0-9A-Za-z]*$ and if it is false it remains at ^[0-9A-Za-z-._]*$.
To call doPut in my test I will need HttpServletRequest, HttpServletResponse and MetadataResource objects. I'm not sure how I generate these. HttpServletRequest and HttpServletResponse are from javax.servlet.ServletRequest and MetadataResource comes from within my project. It takes HttpServletRequest and an enum as parameters.
How do I do this test? I think I should be OK once I can call the doPut method but I'm struggling to do that.
In my Java 8 code,
public ChangePersonsName(String email, final String password, final String wantedUsername, final String uuid, final long time, int latency, int[] requests, int[] proxyRequests) throws IOException {
final AtomicReference<Object> token = new AtomicReference<Object>();
final AtomicReference<ArrayList<?>> newHeaders = new AtomicReference<ArrayList<?>>();
new Thread(() -> {
boolean lock = true;
while (lock) {
if (time - System.currentTimeMillis() > 60000) continue;
Map<Header[], String> loginResults = null;
try {
loginResults = this.login(email, password, uuid);
}
catch (IOException e) {
e.printStackTrace();
}
String token = loginResults.entrySet().iterator().next().getValue();
Header[] headers = loginResults.entrySet().iterator().next().getKey();
newHeaders.set(new ArrayList<Object>());
for (Header header : headers) {
if (!header.toString().startsWith("Set-Cookie:")) continue;
((List<BasicHeader>)newHeaders.get()).add(new BasicHeader("Cookie", header.toString().split("Set-Cookie: ")[1]));
}
lock = false;
}
}
).start();
new Timer().schedule(new TimerTask(){
You'll notice that
String token = loginResults.entrySet().iterator().next().getValue();
throws a compile error,
Lambda expression's local variable token cannot redeclare another local variable defined in an enclosing scope.
My question is, How would one go about fixing this? I'm pretty new to Java, I should probably know how to fix this, but i don't.
You already have variable with name token in this scope. You've declared it in 2nd row. To fix just rename 2nd variable:
String newToken = loginResults.entrySet().iterator().next().getValue();
I have working code as follows
public class receive_meter_to_store extends HttpServlet {
WSEMAMSTS EMAMService = new WSEMAMSTS();
ItronEMAMStsBinding itronEMAM = EMAMService.getItronEMAMStsBinding();
ItronAuthCredit lItronAuthCredit = new ItronAuthCredit();
EANDeviceID lTerminalID = new EANDeviceID();
EANDeviceID lClientID = new EANDeviceID();
SimpleDateFormat itronDF = new SimpleDateFormat("yyyyMMddHHmmss");
Date current_datetime = new Date();
String s_current_datetime = itronDF.format(current_datetime);
MsgID lMsgID = new MsgID();
reuse_func gc_reuse_func = new reuse_func();
curr_time gs_current_datetime = new curr_time("");
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String retdata = "Failure";
try {
retdata = add_meter_to_store(request, response);
}
finally {
out.println(retdata);
out.close();
}
}
I want to make it thread safe, as in to make it run faster. First I am to remove all the global variables, but when i do so, I get error
"An unhandled program error has occured. Please contact the Support services and report the issue"
I have moved them so they can be local as follows
public class receive_meter_to_store extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String retdata = "Failure";
reuse_func lc_reuse_func = new reuse_func();
try {
WSECMPublic EMAMService = lc_reuse_func.getMeterWebService();
ItronEMAMStsBinding itronEMAM = EMAMService.getItronEMAMStsBinding();
}
catch (Exception ex)
{
String ErrorMsg = ex.getMessage();
out.println("Error" + ErrorMsg);
}
finally {
out.close();
}
try {
retdata = add_meter_to_store(request, response);
}
finally {
out.println(retdata);
out.close();
}
}
Am I doing something wrong here?
the class i am calling add_meter
public String add_meter_to_store(HttpServletRequest request, HttpServletResponse response)
{
reuse_func lc_reuse_func = new reuse_func();
try
{
WSECMPublic EMAMService = lc_reuse_func.getMeterWebService();
ItronEMAMStsBinding itronEMAM = EMAMService.getItronEMAMStsBinding();
ItronAuthCredit lItronAuthCredit = new ItronAuthCredit();
EANDeviceID lTerminalID = new EANDeviceID();
EANDeviceID lClientID = new EANDeviceID();
SimpleDateFormat itronDF = new SimpleDateFormat("yyyyMMddHHmmss");
Date current_datetime = new Date();
String s_current_datetime = itronDF.format(current_datetime);
MsgID lMsgID = new MsgID();
curr_time ls_current_datetime = new curr_time("");
// Declare MeterImportResponse Variable
ItronMeterStsImportResp stsImportResp = new ItronMeterStsImportResp();
// Call meterStsImport WebMethod
stsImportResp = itronEMAM.meterStsImport(stsImportReq);
}
catch (Exception ex) {
// TODO handle custom exceptions here
String ErrorMsg = ex.getMessage();
retdata = "Error : " + ErrorMsg;
}
return retdata;
}
Note: i have removed the global variables in first part and put them in the class
The problem (or one problem, at least) is that in the first finally block, you close out, but then try to use it again later.
This means that your out.println(retdata) statement is always operating on a closed stream.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How to implement Facebook Realtime API
Configure Facebook app and then install the app on Facebook pages/users that you want updates for.
We need to maintain a callback URL for Facebook to be able to post updates. Jersey based implementation as an example:
#Path("/social/facebook/update")
public class FacebookRealtimeAPIResource
{
private static final String HUB_MODE = "hub.mode";
private static final String HUB_CHALLENGE = "hub.challenge";
private static final String HUB_VERIFY_TOKEN = "hub.verify_token";
public FacebookRealtimeAPIResource()
{
// any desired implementation here
}
#GET
#Produces(MediaType.TEXT_HTML)
public void validateFacebookRequest(
#DefaultValue("") #QueryParam(HUB_MODE) String hubMode,
#DefaultValue("") #QueryParam(HUB_CHALLENGE) String hubChallenge,
#DefaultValue("") #QueryParam(HUB_VERIFY_TOKEN) String hubVerifyToken,
#Context HttpServletRequest request,
#Context HttpServletResponse response)
{
try
{
// hubVerifyToken based validation if desired
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().write(hubChallenge);
response.getWriter().flush();
response.getWriter().close();
}
catch (IOException exc)
{
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
}
#POST
#Consumes(MediaType.APPLICATION_JSON)
public void processFacebookRealtimeUpdate(#Context HttpServletRequest request, InputStream inputStream)
{
StringBuilder sb = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
String json = "";
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, request.getCharacterEncoding()));
while ((line = reader.readLine()) != null)
sb.append(line).append(newLine);
}
catch (Exception exc)
{
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
json = sb.toString(); // use this json string for desired purpose
}
}
Install app for page and then subscribe for page updates
public class FacebookRealtimeSubscriber
{
private AccessToken appAccessToken = null;
private String appSecret = // your app secret
private String userAccessToken = // access token for user that owns the page, generated using your app
private String applicationId = // your application id
private String callbackURL = "<your context root>/social/facebook/update";
private String pageName = // page name you want to install app for
private FacebookClient client = null;
private final String subscribedAppsEdge = "/subscribed_apps";
private final String appSubscriptions = "/subscriptions";
private final String verifyToken = "AnyRandomVerifyToken";
// below are all the fields that can be subscribed for page object
private final String pageFields = "feed,ratings,name,picture,category,description,founded,company_overview,conversations,mission,products,general_info,location,hours,parking,public_transit,phone,email,website,attire,payment_options,culinary_team,general_manager,price_range,restaurant_services,restaurant_specialties,videos,release_date,genre,starring,screenplay_by,directed_by,produced_by,studio,awards,plot_outline,network,season,schedule,written_by,band_members,hometown,current_location,record_label,booking_agent,press_contact,artists_we_like,influences,band_interests,bio,affiliation,birthday,personal_info,personal_interests,members,built,features,mpg,checkins,productlists";
public static void main(String[] args)
{
new FacebookRealtimeSubscriber().subscribe();
}
private void subscribe()
{
String pageAccessToken = "";
String pageId = "";
client = new DefaultFacebookClient(Version.VERSION_2_3);
appAccessToken = client.obtainAppAccessToken(applicationId, appSecret);
client = new DefaultFacebookClient(userAccessToken, Version.VERSION_2_3);
Connection<Account> pages = client.fetchConnection("me/accounts", Account.class);
List<Account> accounts = pages.getData();
for (Account account : accounts)
{
if (pageName.equals(account.getName()))
{
pageAccessToken = account.getAccessToken();
pageId = account.getId();
}
}
client = new DefaultFacebookClient(pageAccessToken, appSecret, Version.VERSION_2_3);
// subscribe app for page
Object obj = client.publish(pageId + subscribedAppsEdge, JsonObject.class, Parameter.with("id", Long.valueOf(pageId)));
System.out.println(obj.toString());
// list subscriptions for app
obj = client.fetchObject(pageId + subscribedAppsEdge, JsonObject.class);
System.out.println(obj.toString());
// subscribe for page updates for app
client = new DefaultFacebookClient(appAccessToken.getAccessToken(), appSecret, Version.VERSION_2_3);
obj = client.publish(applicationId + appSubscriptions,
JsonObject.class,
Parameter.with("object", "page"),
Parameter.with("callback_url", callbackURL),
Parameter.with("fields", pageFields),
Parameter.with("verify_token", verifyToken));
System.out.println(obj);
// get subscriptions for app
obj = client.fetchObject(applicationId + appSubscriptions, JsonObject.class);
System.out.println(obj);
}
}