How to retrieve all users in my domain - java

I created one domain in that domain i created nearly 500 user accounts.I want to retrieve all the users in my domain .so that i use the following coding to retrieve all the users in my domain.But in that coding i displayed only first 100 users.And also it display total user entries 100.I dont know what problem in this coding.
import com.google.gdata.client.appsforyourdomain.UserService;
import com.google.gdata.data.appsforyourdomain.provisioning.UserEntry;
import com.google.gdata.data.appsforyourdomain.provisioning.UserFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
/**
* This is a test template
*/
public class AppsProvisioning {
public static void main(String[] args) {
try {
// Create a new Apps Provisioning service
UserService myService = new UserService("My Application");
myService.setUserCredentials(admin,password);
// Get a list of all entries
URL metafeedUrl = new URL("https://www.google.com/a/feeds/"+domain+"/user/2.0/");
System.out.println("Getting user entries...\n");
UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class);
List<UserEntry> entries = resultFeed.getEntries();
for(int i=0; i<entries.size(); i++) {
UserEntry entry = entries.get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
System.out.println("\nTotal Entries: "+entries.size());
}
catch(AuthenticationException e) {
e.printStackTrace();
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch(ServiceException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
what problem in this coding?

The list of users is returned in an atom feed. This is a paged feed, with a maximum of 100 entries per page. If there are more entries in the feed then there will be an atom:link element with a rel="next" attribute, pointing at the next page. You need to keep following these links until there are no more 'next' pages.
See: http://code.google.com/apis/apps/gdata_provisioning_api_v2.0_reference.html#Results_Pagination
The code will look something like:
URL metafeedUrl = new URL("https://www.google.com/a/feeds/"+domain+"/user/2.0/");
System.out.println("Getting user entries...\n");
List<UserEntry> entries = new ArrayList<UserEntry>();
while (metafeedUrl != null) {
// Fetch page
System.out.println("Fetching page...\n");
UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class);
entries.addAll(resultFeed.getEntries());
// Check for next page
Link nextLink = resultFeed.getNextLink();
if (nextLink == null) {
metafeedUrl = null;
} else {
metafeedUrl = nextLink.getHref();
}
}
// Handle results
for(int i=0; i<entries.size(); i++) {
UserEntry entry = entries.get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
System.out.println("\nTotal Entries: "+entries.size());

Related

Youtube live stream to specific Channel

I am using the below code to create event in Youtube for Live Streaming. Everything works fine, my problem, I want users to live stream to our company's Channel.
At present events are getting created in users channel, this is wrong, we want to create the event in our channel and live stream should come to our company's channel. I would like to know how we should specify our company's channel to create the events.
I tried to specify
YouTube.LiveBroadcasts.Insert liveBroadcastInsert = youtube
.liveBroadcasts().insert(Arrays.asList(lbInsert),
broadcast);
liveBroadcastInsert.onBehalfOfContentOwner("user#company.com");
liveBroadcastInsert.onBehalfOfContentOwnerChannel("ChannelID");
Both did not work. It gave error
"errors": [
{
"domain": "youtube.common",
"message": "The authenticated user cannot act on behalf of the specified Google account.",
"reason": "accountDelegationForbidden"
}
//// Code ///
import com.google.android.gms.common.Scopes;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.util.DateTime;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.YouTube.LiveBroadcasts.Transition;
import com.google.api.services.youtube.YouTubeScopes;
import com.google.api.services.youtube.model.CdnSettings;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.api.services.youtube.model.IngestionInfo;
import com.google.api.services.youtube.model.LiveBroadcast;
import com.google.api.services.youtube.model.LiveBroadcastContentDetails;
import com.google.api.services.youtube.model.LiveBroadcastListResponse;
import com.google.api.services.youtube.model.LiveBroadcastSnippet;
import com.google.api.services.youtube.model.LiveBroadcastStatus;
import com.google.api.services.youtube.model.LiveStream;
import com.google.api.services.youtube.model.LiveStreamListResponse;
import com.google.api.services.youtube.model.LiveStreamSnippet;
import com.google.api.services.youtube.model.MonitorStreamInfo;
import com.test.tv.usb.MainActivity;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
public class YouTubeApi {
public static final String RTMP_URL_KEY = "rtmpUrl";
public static final String BROADCAST_ID_KEY = "broadcastId";
private static final int FUTURE_DATE_OFFSET_MILLIS = 5 * 1000;
public static void createLiveEvent(YouTube youtube, String description,
String name) {
// We need a date that's in the proper ISO format and is in the future,
// since the API won't
// create events that start in the past.
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
long futureDateMillis = System.currentTimeMillis()
+ FUTURE_DATE_OFFSET_MILLIS;
Date futureDate = new Date();
futureDate.setTime(futureDateMillis);
String date = dateFormat.format(futureDate);
Log.i(MainActivity.APP_NAME, String.format(
"Creating event: name='%s', description='%s', date='%s'.",
name, description, date));
try {
LiveBroadcastSnippet broadcastSnippet = new LiveBroadcastSnippet();
broadcastSnippet.setTitle(name);
broadcastSnippet.setScheduledStartTime(new DateTime(futureDate));
LiveBroadcastContentDetails contentDetails = new LiveBroadcastContentDetails();
MonitorStreamInfo monitorStream = new MonitorStreamInfo();
monitorStream.setEnableMonitorStream(false);
contentDetails.setMonitorStream(monitorStream);
// Create LiveBroadcastStatus with privacy status.
LiveBroadcastStatus status = new LiveBroadcastStatus();
status.setPrivacyStatus("public");
LiveBroadcast broadcast = new LiveBroadcast();
broadcast.setKind("youtube#liveBroadcast");
broadcast.setSnippet(broadcastSnippet);
broadcast.setStatus(status);
broadcast.setContentDetails(contentDetails);
// Create the insert request
String[] lbInsert = {"snippet", "status","contentDetails"};
YouTube.LiveBroadcasts.Insert liveBroadcastInsert = youtube
.liveBroadcasts().insert(Arrays.asList(lbInsert),
broadcast);
// Request is executed and inserted broadcast is returned
LiveBroadcast returnedBroadcast = liveBroadcastInsert.execute();
// Create a snippet with title.
LiveStreamSnippet streamSnippet = new LiveStreamSnippet();
streamSnippet.setTitle(name);
// Create content distribution network with format and ingestion
// type.
CdnSettings cdn = new CdnSettings();
cdn.setIngestionType("rtmp");
cdn.setResolution("1080p");
cdn.setFrameRate("30fps");
LiveStream stream = new LiveStream();
stream.setKind("youtube#liveStream");
stream.setSnippet(streamSnippet);
stream.setCdn(cdn);
// Create the insert request
String[] lsInsert = {"snippet", "cdn"};
YouTube.LiveStreams.Insert liveStreamInsert = youtube.liveStreams()
.insert(Arrays.asList(lsInsert), stream);
// Request is executed and inserted stream is returned
LiveStream returnedStream = liveStreamInsert.execute();
// Create the bind request
String[] lbBind = {"id", "contentDetails"};
YouTube.LiveBroadcasts.Bind liveBroadcastBind = youtube
.liveBroadcasts().bind(returnedBroadcast.getId(),
Arrays.asList(lbBind));
// Set stream id to bind
liveBroadcastBind.setStreamId(returnedStream.getId());
// Request is executed and bound broadcast is returned
liveBroadcastBind.execute();
} catch (GoogleJsonResponseException e) {
System.err.println("GoogleJsonResponseException code: "
+ e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
e.printStackTrace();
} catch (Throwable t) {
System.err.println("Throwable: " + t.getStackTrace());
t.printStackTrace();
}
}
// TODO: Catch those exceptions and handle them here.
public static List<EventData> getLiveEvents(
YouTube youtube) throws IOException {
Log.i(MainActivity.APP_NAME, "Requesting live events.");
String[] yReq = {"id", "snippet", "contentDetails"};
YouTube.LiveBroadcasts.List liveBroadcastRequest = youtube
.liveBroadcasts().list(Arrays.asList(yReq));
// liveBroadcastRequest.setMine(true);
liveBroadcastRequest.setBroadcastStatus("upcoming");
// List request is executed and list of broadcasts are returned
LiveBroadcastListResponse returnedListResponse = liveBroadcastRequest.execute();
// Get the list of broadcasts associated with the user.
List<LiveBroadcast> returnedList = returnedListResponse.getItems();
List<EventData> resultList = new ArrayList<EventData>(returnedList.size());
EventData event;
for (LiveBroadcast broadcast : returnedList) {
event = new EventData();
event.setEvent(broadcast);
String streamId = broadcast.getContentDetails().getBoundStreamId();
if (streamId != null) {
String[] strID = {streamId};
String ingestionAddress = getIngestionAddress(youtube, strID);
event.setIngestionAddress(ingestionAddress);
}
resultList.add(event);
}
return resultList;
}
public static void startEvent(YouTube youtube, String broadcastId)
throws IOException {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Log.e(MainActivity.APP_NAME, "", e);
}
String[] tReq = {"status"};
Transition transitionRequest = youtube.liveBroadcasts().transition(
"live", broadcastId, Arrays.asList(tReq));
transitionRequest.execute();
}
public static void endEvent(YouTube youtube, String broadcastId)
throws IOException {
String[] tReq = {"status"};
Transition transitionRequest = youtube.liveBroadcasts().transition(
"complete", broadcastId, Arrays.asList(tReq));
transitionRequest.execute();
}
public static String getIngestionAddress(YouTube youtube, String[] streamId)
throws IOException {
String[] tReq = {"cdn"};
YouTube.LiveStreams.List liveStreamRequest = youtube.liveStreams()
.list(Arrays.asList(tReq));
liveStreamRequest.setId(Arrays.asList(streamId));
LiveStreamListResponse returnedStream = liveStreamRequest.execute();
List<LiveStream> streamList = returnedStream.getItems();
if (streamList.isEmpty()) {
return "";
}
IngestionInfo ingestionInfo = streamList.get(0).getCdn().getIngestionInfo();
return ingestionInfo.getIngestionAddress() + "/"
+ ingestionInfo.getStreamName();
}
}

Java PDFBox list all named destinations of a page

For my Java project I need to list all named destinations of a PDF page.
The PDF and its named destination are created with LaTeX (using the hypertarget command), e.g. as follows:
\documentclass[12pt]{article}
\usepackage{hyperref}
\begin{document}
\hypertarget{myImportantString}{} % the anchor/named destination to be extracted "myImportantString"
Empty example page
\end{document}
How do I extract all named destinations of a specific page of this PDF document with the PDFBox library version 2.0.11?
I could not find any working code for this problem in the internet or the PDFBox examples. This is my current (minified) code:
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import java.io.File;
import java.util.List;
public class ExtractNamedDests {
public static void main(String[] args) {
try {
int c = 1;
PDDocument document = PDDocument.load(new File("<path to PDF file>"));
for (PDPage page : document.getPages()) {
System.out.println("Page " + c + ":");
// named destinations seem to be no type of annotations since the list is always empty:
List<PDAnnotation> annotations = page.getAnnotations();
System.out.println(" Count annotations: " + annotations.size());
// How to extract named destinations??
}
}catch(Exception e){
e.printStackTrace();
}
}
}
In this example I want to extract the String "myImportantString" from the page in Java.
EDIT: Here is the example PDF file. I use PDFBox version 2.0.11.
I found a solution with the great help of Tilman Hausherr. It uses the code he suggested in his comments.
The method getAllNamedDestinations() returns a map of all named destinations in the document (not annotations) with name and destination. Named destinations can be deeply nested in the document. Therefore, the method traverseKids() recursively finds all nested named destinations.
public static Map<String, PDPageDestination> getAllNamedDestinations(PDDocument document){
Map<String, PDPageDestination> namedDestinations = new HashMap<>(10);
// get catalog
PDDocumentCatalog documentCatalog = document.getDocumentCatalog();
PDDocumentNameDictionary names = documentCatalog.getNames();
if(names == null)
return namedDestinations;
PDDestinationNameTreeNode dests = names.getDests();
try {
if (dests.getNames() != null)
namedDestinations.putAll(dests.getNames());
} catch (Exception e){ e.printStackTrace(); }
List<PDNameTreeNode<PDPageDestination>> kids = dests.getKids();
traverseKids(kids, namedDestinations);
return namedDestinations;
}
private static void traverseKids(List<PDNameTreeNode<PDPageDestination>> kids, Map<String, PDPageDestination> namedDestinations){
if(kids == null)
return;
try {
for(PDNameTreeNode<PDPageDestination> kid : kids){
if(kid.getNames() != null){
try {
namedDestinations.putAll(kid.getNames());
} catch (Exception e){ System.out.println("INFO: Duplicate named destinations in document."); e.printStackTrace(); }
}
if (kid.getKids() != null)
traverseKids(kid.getKids(), namedDestinations);
}
} catch (Exception e){
e.printStackTrace();
}
}

java.util.NoSuchElementException: No line found error java

Keep getting this error
"java.util.NoSuchElementException: No line found error java"
and searched through code so many times and cant see to find problems heres my files can anyone help?
Am currently doing this as an assignment and am trying to transfer it from unthreaded to threaded and in the process came up with this error!!
This is the Client class
package Client;
import core.Email;
import core.EmailServiceDetails;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.InputMismatchException;
import java.util.Scanner;
public class EmailClient {
public static void main(String[] args) {
try
{
// Step 1 (on consumer side) - Establish channel of communication
Socket dataSocket = new Socket("localhost", EmailServiceDetails.LISTENING_PORT);
// Step 3) Build output and input objects
OutputStream out = dataSocket.getOutputStream();
PrintWriter output = new PrintWriter(new OutputStreamWriter(out));
InputStream in = dataSocket.getInputStream();
Scanner input = new Scanner(new InputStreamReader(in));
Scanner keyboard = new Scanner(System.in);
String message = "";
while(!message.equals(EmailServiceDetails.END_SESSION))
{
displayMenu();
int choice = getNumber(keyboard);
String response = "";
if(choice >=0 && choice < 3)
{
switch (choice)
{
case 0:
message = EmailServiceDetails.END_SESSION;
// Send message
output.println(message);
output.flush();
response = input.nextLine();
if(response.equals(EmailServiceDetails.SESSION_TERMINATED))
{
System.out.println("Session ended.");
}
break;
case 1:
message = sendEmail(keyboard);
// Send message
output.println(message);
output.flush();
// Get response
response = input.nextLine();
if(response.equals(EmailServiceDetails.SUCCESSFUL_ADD))
{
System.out.println("Email sent successfully");
}
else if(response.equals(EmailServiceDetails.UNSUCCESSFUL_ADD))
{
System.out.println("Sorry, the email could not be sent at this time.");
}
break;
case 2:
message = viewUnread(keyboard);
// Send message
output.println(message);
output.flush();
// Get response
response = input.nextLine();
if(response.equals(EmailServiceDetails.NO_UNREAD))
{
System.out.println("No unread mails found for that account.");
}
else
{
ArrayList<Email> unreadMails = EmailServiceDetails.parseEmailList(response);
System.out.println("Unread Emails:");
for(Email e: unreadMails)
{
System.out.println(e);
}
}
break;
}
if(response.equals(EmailServiceDetails.UNRECOGNISED))
{
System.out.println("Sorry, that request cannot be recognised.");
}
}
else
{
System.out.println("Please select an option from the menu");
}
}
System.out.println("Thank you for using the Email system.");
dataSocket.close();
}catch(Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
e.printStackTrace();
}
}
public static void displayMenu()
{
System.out.println("0) Exit");
System.out.println("1) Send an email");
System.out.println("2) View all unread mails");
}
public static int getNumber(Scanner keyboard)
{
boolean numberEntered = false;
int number = 0;
while(!numberEntered)
{
try{
number = keyboard.nextInt();
numberEntered = true;
}
catch(InputMismatchException e)
{
System.out.println("Please enter a number.");
keyboard.nextLine();
}
}
keyboard.nextLine();
return number;
}
public static String sendEmail(Scanner keyboard)
{
System.out.println("Please enter the sender of this email:");
String sender = keyboard.nextLine();
// Get recipient information
String anotherRecipient = "Y";
ArrayList<String> recipients = new ArrayList();
while(anotherRecipient.equalsIgnoreCase("Y"))
{
System.out.println("Enter the recipient's email address:");
String recipient = keyboard.nextLine();
recipients.add(recipient);
System.out.println("Would you like to add another recipient? ('Y' for yes and 'N' for no)");
anotherRecipient = keyboard.nextLine();
}
System.out.println("Please enter the email subject:");
String subject = keyboard.nextLine();
System.out.println("Please enter the message body:");
String body = keyboard.nextLine();
// Get attachment information
ArrayList<String> attachments = new ArrayList();
System.out.println("Would you like to enter an attachment ('Y' to add and 'N' to continue)");
String anotherAttachment = keyboard.nextLine();
while(anotherAttachment.equalsIgnoreCase("Y"))
{
System.out.println("Enter the attachment information:");
String attachment = keyboard.nextLine();
attachments.add(attachment);
System.out.println("Would you like to add another attachment? ('Y' for yes and 'N' to Continue)");
anotherAttachment = keyboard.nextLine();
}
long timestamp = new Date().getTime();
String response = null;
Email e = null;
if(attachments.size() > 0)
{
e = new Email(sender, recipients, subject, body, timestamp, attachments);
}
else
{
e = new Email(sender, recipients, subject, body, timestamp);
}
response = EmailServiceDetails.ADD_MAIL + EmailServiceDetails.COMMAND_SEPARATOR + EmailServiceDetails.formatEmail(e);
return response;
}
public static String viewUnread(Scanner keyboard)
{
System.out.println("Please enter the name of the email account you wish to see unread mail for:");
String recipient = keyboard.nextLine();
String response = EmailServiceDetails.VIEW_UNREAD + EmailServiceDetails.COMMAND_SEPARATOR + recipient;
return response;
}
}
--------------------------------------------------------------------------------
This is Server
---------------
package Server;
import Server.Commands.Command;
import core.EmailServiceDetails;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class EmailServer {
public static void main(String[] args) {
try{
// Set up a connection socket for other programs to connect to
ServerSocket listeningSocket = new ServerSocket(EmailServiceDetails.LISTENING_PORT);
// Create the list of emails to be stored and worked with
EmailStore emails = new EmailStore();
boolean continueRunning = true;
int threadCount = 0;
while(continueRunning)
{
// Step 2) wait for incoming connection and build communications link
Socket dataSocket = listeningSocket.accept();
threadCount++;
System.out.println("The server has now accepted " + threadCount + " clients");
// Step 3) Build thread
// Thread should be given:
// 1) a group to be stored in
// 2) a name to be listed under
// 3) a socket to communicate through
// 4) Any extra information that should be shared
EmailThread newClient = new EmailThread (emails, dataSocket.getInetAddress()+"", dataSocket,threadCount);
newClient.start();
}
listeningSocket.close();
}
catch(Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
}
}
}
--------------------------------------------------------------------------------
This is ServerThread
---------------
package Server;
import Server.Commands.Command;
import Server.EmailStore;
import core.EmailServiceDetails;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;
/**
*
* #author User
*/
public class EmailThread extends Thread {
private Socket dataSocket;
private Scanner input;
private PrintWriter output;
private int number;
private EmailStore emails;
public EmailThread(EmailStore emails,String name, Socket dataSocket, int number) {
try {
// Save the data socket used for communication between the thread and the Client
this.dataSocket = dataSocket;
// Save the id of the thread to identify output
// Save the id of the thread to identify output
this.number = number;
input = new Scanner(new InputStreamReader(this.dataSocket.getInputStream()));
// Create the stream for writing to the Client
output = new PrintWriter(this.dataSocket.getOutputStream(), true);
} catch (IOException e) {
System.out.println("An exception occurred while setting up connection links for a thread: " + e.getMessage());
}
}
#Override
public void run() {
{
String incomingMessage = "";
String response;
try {
while (!incomingMessage.equals(EmailServiceDetails.END_SESSION)) {
// Wipe the response to make sure we never use an old value
response = null;
// take in information from the client
incomingMessage = input.nextLine();
System.out.println("Received message: " + incomingMessage);
// Break up information into components
String[] components = incomingMessage.split(EmailServiceDetails.COMMAND_SEPARATOR);
// Confirm that the command was correctly formatted
// Did it include more than just the command text?
if (components.length > 1) {
CommandFactory factory = new CommandFactory();
// Figure out which command was sent by the client
// I.e. what does the client want to do?
Command command = factory.createCommand(components[0]);
// Take the remaining text the client sent (i.e. all the information provided)
// and execute the requested action (e.g. store the new mail, get all sent mails etc)
response = command.createResponse(components[1], emails);
} else if (components[0].equals(EmailServiceDetails.END_SESSION)) {
response = EmailServiceDetails.SESSION_TERMINATED;
} else {
// If information was missing, set the response to inform the
// client that the command wasn't recognised
response = EmailServiceDetails.UNRECOGNISED;
}
// Send back the computed response
output.println(response);
output.flush();
}
} catch (Exception e) {
System.out.println("An exception occurred while communicating with client #" + number + ": " + e.getMessage());
} finally {
try {
// Shut down connection
System.out.println("\n* Closing connection with client #" + number + "... *");
dataSocket.close();
} catch (IOException e) {
System.out.println("Unable to disconnect: " + e.getMessage());
System.exit(1);
}
}
}
}
}
--------------------------------------------------------------------------------
This is EmailStore
---------------
package Server;
import core.Email;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class EmailStore
{
private ArrayList<Email> emailList = new ArrayList();
public boolean addMail(Email newEmail)
{
return emailList.add(newEmail);
}
public boolean removeMail(Email mailToBeDeleted)
{
return emailList.remove(mailToBeDeleted);
}
public ArrayList<Email> findEmailByRecipient(String recipient)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails whose recipients list contents the specified recipient
.filter(email -> email.getRecipients().contains(recipient))
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
public ArrayList<Email> findEmailBySender(String sender)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails matching the specified sender
.filter(email -> email.getSender().equals(sender))
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
// Methods to mark emails as read
// Provide a version that marks multiple mails as read AND a version that
// marks a single email as read
public void markMultipleAsRead(ArrayList<Email> emails)
{
for(Email e : emails)
{
markAsRead(e);
}
}
public void markAsRead(Email e)
{
int index = emailList.indexOf(e);
if(index != -1)
{
Email storedMail = emailList.get(index);
storedMail.markAsRead(true);
}
}
// Methods to mark emails as spam
// Provide a version that marks multiple mails as spam AND a version that
// marks a single email as spam
public void markAsSpam(Email e)
{
int index = emailList.indexOf(e);
if(index != -1)
{
Email storedMail = emailList.get(index);
storedMail.markAsSpam(true);
}
}
public void markMultipleAsSpam(ArrayList<Email> emails)
{
for(Email e : emails)
{
markAsSpam(e);
}
}
public ArrayList<Email> findUnreadEmailByRecipient(String recipient)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails whose recipients list contents the specified recipient AND the email is not unread
.filter(email -> email.getRecipients().contains(recipient) && !email.isRead())
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
}
-------
Help Appreciated
-
----------
Help would be great appreciated as the frustration levels are at a high!!
This answer is a wild guess but in case 1 of the switch statement of the main method you are calling the input.nextLine() scanner which it might not contain information at that time. It is possible that you have to check if data arrived by using the hasNext() method first.
Also in the last method when you are collecting the email classes you don't really need to cast. It can be done like this:
results = emailList.stream()
.filter(email -> email.getRecipients().contains(recipient) && !email.isRead())
.collect(Collectors.toCollection(ArrayList::new));

Structure JSOUP content to JSON

I extract some data from a http site and now I want to format this using JSON . I watched some examples but i don't understand how to do that exactly .I want something like that :
{
Product name:"Samsung..."
{ review 1:"..."
review 2:"..."
}
}
Also my code don't iterate over all reviews, it stops at page 1 ,and there is 10 more pages and i want to get like 20-30 reviews at least. There is what i did until now :
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class JsoupMain {
private static int nr = 1;
public static void main(String[] args) {
Document document = null;
try {
document = Jsoup.connect("http://www.emag.ro/telefon-mobil-samsung- galaxy-j5-2016-dual-sim-16gb-4g-gold-sm-j510fzdurom/pd/DQD3B7BBM/").get();
String title = document.title();
System.out.println("Title: " + title);
Elements review = document.select("div.product-review-body");
for (Element rev : review) {
System.out.println("Review : " + nr + " :" + rev.text() + "\n");
nr++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
See this answer for a similar question - Parsing table html with Jsoup In your case it might look like this:
JSONObject root = new JSONObject();
JSONArray reviews = new JSONArray();
root.put("name", "Product Name");
for (int i=0; i < elements.size(); i++){
JSONObject review = new JSONObject();
review.put("review"+i , elements.get(i).text());
reviews.add(review);
}
root.put("reviews", reviews);
The JSON output for root would look like this:
{
"name":"Product Name",
"reviews":[
{
"review0":"ok"
},
{
"review1":"awesome"
}
]
}
I want to make this code to show info exactly like that:
{ Reviews:
{ review 1: "..."}
{ review 2: "..."}
................
................
}
In present my code is printing info's like that: "Reviews":[[{"Review 0":"Foarte multumit Un telefon foarte bun. Ce m-a impresionat este camera foto care face niste poze foarte bune"},{"R............}
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class JsoupMain {
private static int nr = 1;
public static void main(String[] args) {
Document document = null;
try {
document = Jsoup.connect("http://www.emag.ro/telefon-mobil-samsung-galaxy-j5-2016-dual-sim-16gb-4g-gold-sm-j510fzdurom/pd/DQD3B7BBM/").get();
String title = document.title();
System.out.println("Product name : " + title);
Elements review = document.select("div.product-review-body");
JSONObject mainObject = new JSONObject();
JSONObject root = new JSONObject();
JSONArray list = new JSONArray();
root.put("Product name", title);
for (int i = 0; i < review.size(); i++) {
JSONObject revieww = new JSONObject();
revieww.put("Review " + i, review.get(i).text());
list.put(revieww);
}
mainObject.accumulate("Reviews", list);
System.out.println(mainObject);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Replace your code from Elements review = document.select("div.product-review-body");... to ... System.out.println(mainObject); with the following code snippet.
Elements review = document.select("div[class=product-review-body]");
JSONObject parent = new JSONObject();
parent.put("Product name", title);
JSONArray reviews = new JSONArray();
int i = 1;
for (Element rev : review) {
reviews.put(new JSONObject().put("review" + i, rev.text()));
i++;
}
parent.put("Reviews", reviews);
System.out.println(parent);
Hope this helps.

How to read MP3 file tags

I want to have a program that reads metadata from an MP3 file. My program should also able to edit these metadata. What can I do?
I got to search out for some open source code. But they have code; but not simplified idea for my job they are going to do.
When I read further I found the metadata is stored in the MP3 file itself. But I am yet not able to make a full idea of my baby program.
Any help will be appreciated; with a program or very idea (like an algorithm). :)
The last 128 bytes of a mp3 file contains meta data about the mp3 file., You can write a program to read the last 128 bytes...
UPDATE:
ID3v1 Implementation
The Information is stored in the last 128 bytes of an MP3. The Tag
has got the following fields, and the offsets given here, are from
0-127.
Field Length Offsets
Tag 3 0-2
Songname 30 3-32
Artist 30 33-62
Album 30 63-92
Year 4 93-96
Comment 30 97-126
Genre 1 127
WARINING- This is just an ugly way of getting metadata and it might not actually be there because the world has moved to id3v2. id3v1 is actually obsolete. Id3v2 is more complex than this, so ideally you should use existing libraries to read id3v2 data from mp3s . Just putting this out there.
You can use apache tika Java API for meta-data parsing from MP3 such as title, album, genre, duraion, composer, artist and etc.. required jars are tika-parsers-1.4, tika-core-1.4.
Sample Program:
package com.parse.mp3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.mp3.Mp3Parser;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class AudioParser {
/**
* #param args
*/
public static void main(String[] args) {
String fileLocation = "G:/asas/album/song.mp3";
try {
InputStream input = new FileInputStream(new File(fileLocation));
ContentHandler handler = new DefaultHandler();
Metadata metadata = new Metadata();
Parser parser = new Mp3Parser();
ParseContext parseCtx = new ParseContext();
parser.parse(input, handler, metadata, parseCtx);
input.close();
// List all metadata
String[] metadataNames = metadata.names();
for(String name : metadataNames){
System.out.println(name + ": " + metadata.get(name));
}
// Retrieve the necessary info from metadata
// Names - title, xmpDM:artist etc. - mentioned below may differ based
System.out.println("----------------------------------------------");
System.out.println("Title: " + metadata.get("title"));
System.out.println("Artists: " + metadata.get("xmpDM:artist"));
System.out.println("Composer : "+metadata.get("xmpDM:composer"));
System.out.println("Genre : "+metadata.get("xmpDM:genre"));
System.out.println("Album : "+metadata.get("xmpDM:album"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
}
}
For J2ME(which is what I was struggling with), here's the code that worked for me..
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.*;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.MetaDataControl;
import javax.microedition.midlet.MIDlet;
public class MetaDataControlMIDlet extends MIDlet implements CommandListener {
private Display display = null;
private List list = new List("Message", List.IMPLICIT);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Alert alert = new Alert("Message");
private Player player = null;
public MetaDataControlMIDlet() {
display = Display.getDisplay(this);
alert.addCommand(exitCommand);
alert.setCommandListener(this);
list.addCommand(exitCommand);
list.setCommandListener(this);
//display.setCurrent(list);
}
public void startApp() {
try {
FileConnection connection = (FileConnection) Connector.open("file:///e:/breathe.mp3");
InputStream is = null;
is = connection.openInputStream();
player = Manager.createPlayer(is, "audio/mp3");
player.prefetch();
player.realize();
} catch (Exception e) {
alert.setString(e.getMessage());
display.setCurrent(alert);
e.printStackTrace();
}
if (player != null) {
MetaDataControl mControl = (MetaDataControl) player.getControl("javax.microedition.media.control.MetaDataControl");
if (mControl == null) {
alert.setString("No Meta Information");
display.setCurrent(alert);
} else {
String[] keys = mControl.getKeys();
for (int i = 0; i < keys.length; i++) {
list.append(keys[i] + " -- " + mControl.getKeyValue(keys[i]), null);
}
display.setCurrent(list);
}
}
}
public void commandAction(Command cmd, Displayable disp) {
if (cmd == exitCommand) {
notifyDestroyed();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}

Categories