How to retrieve messages which are not flagged as deleted? - java

I flag a message to be deleted after a treatment :
...
import javax.mail.*;
...
public void delete(Message message) throws MessagingException {
try {
message.setFlag(Flags.Flag.DELETED, true);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
...
Then I want to get messages :
...
import com.sun.mail.pop3.POP3Store;
import java.util.Properties;
...
#Value("${mail.host}")
private String host;
#Value("${mail.storeType}")
private String storeType;
#Value("${mail.port}")
private int port;
#Value("${mail.username}")
private String username;
#Value("${mail.password}")
private String password;
#Value("${mail.auth}")
private boolean auth;
#Value("${mail.ssl.trust}")
private String sss_trust;
private POP3Store emailstore = null;
private boolean start = true;
...
public POP3Store getEmailStore() throws Exception {
Properties properties = new Properties();
properties.setProperty("mail.store.protocol", storeType);
properties.setProperty("mail." + storeType + ".host", host);
properties.setProperty("mail." + storeType + ".port", String.valueOf(port));
properties.setProperty("mail." + storeType + ".auth", String.valueOf(auth));
properties.setProperty("mail." + storeType + ".socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail." + storeType + ".ssl.trust", sss_trust);
try {
Session emailSession = Session.getDefaultInstance(properties);
POP3Store emailStore = (POP3Store) emailSession.getStore(storeType);
return emailStore;
} catch (NoSuchProviderException e) {
e.printStackTrace();
throw e;
}
}
Folder emailFolder = emailstore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
Message[] messages = emailFolder.getMessages(); // how to get messages that are not flagged as deleted ?
if (messages != null) {
for (Message message : messages) {
try {
mailService.createTicket(message);
mailService.delete(message);
} catch (Exception ex) {
throw ex;
}
}
}
emailFolder.close(true);
As I commented I want to get messages that are not flagged deleted. How to do that ?

Based on Message class, you can do something like this:
for (Message message : messages) {
if (!message.getFlags().contains(Flags.Flag.DELETED)) { // This will hopefully help
try {
mailService.createTicket(message);
mailService.delete(message);
} catch (Exception ex) {
throw ex;
}
}
}

Related

Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized

I'm trying to launch my application, the meaning of which is to place an ad on the google cloud platform
Here is my code
import com.google.api.services.jobs.v3.CloudTalentSolution;
import com.google.api.services.jobs.v3.model.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
public class BasicJobSample {
private static final String DEFAULT_PROJECT_ID = "projects/" + System.getenv("GOOGLE_CLOUD_PROJECT");
private static CloudTalentSolution talentSolutionClient = JobServiceQuickstart.getTalentSolutionClient();
public static Job generateJobWithRequiredFields(String companyName) {
String requisitionId = "jobWithRequiredFields:" + String.valueOf(new Random().nextLong());
ApplicationInfo applicationInfo = new ApplicationInfo().setUris(Arrays.asList("http://careers.google.com"));
Job job = new Job().setRequisitionId(requisitionId).setTitle("Software Engineer")
.setCompanyName(companyName).setApplicationInfo(applicationInfo)
.setDescription("Design, develop, test, deploy, maintain and improve software.");
System.out.println("Job generated: " + job);
return job;
}
public static Job createJob(Job jobToBeCreated) throws IOException {
try {
CreateJobRequest createJobRequest = new CreateJobRequest().setJob(jobToBeCreated);
Job jobCreated = talentSolutionClient.projects().jobs().create(DEFAULT_PROJECT_ID, createJobRequest)
.execute();
System.out.println("Job created: " + jobCreated);
return jobCreated;
} catch (IOException e) {
System.out.println("Got exception while creating job");
throw e;
}
}
public static Job getJob(String jobName) throws IOException {
try {
Job jobExisted = talentSolutionClient.projects().jobs().get(jobName).execute();
System.out.println("Job existed: " + jobExisted);
return jobExisted;
} catch (IOException e) {
System.out.println("Got exception while getting job");
throw e;
}
}
public static Job updateJob(String jobName, Job jobToBeUpdated) throws IOException {
try {
UpdateJobRequest updateJobRequest = new UpdateJobRequest().setJob(jobToBeUpdated);
Job jobUpdated = talentSolutionClient.projects().jobs().patch(jobName, updateJobRequest).execute();
System.out.println("Job updated: " + jobUpdated);
return jobUpdated;
} catch (IOException e) {
System.out.println("Got exception while updating job");
throw e;
}
}
public static Job updateJobWithFieldMask(String jobName, String fieldMask, Job jobToBeUpdated)
throws IOException {
try {
UpdateJobRequest updateJobRequest = new UpdateJobRequest().setUpdateMask(fieldMask)
.setJob(jobToBeUpdated);
Job jobUpdated = talentSolutionClient.projects().jobs().patch(jobName, updateJobRequest).execute();
System.out.println("Job updated: " + jobUpdated);
return jobUpdated;
} catch (IOException e) {
System.out.println("Got exception while updating job");
throw e;
}
}
public static void deleteJob(String jobName) throws IOException {
try {
talentSolutionClient.projects().jobs().delete(jobName).execute();
System.out.println("Job deleted");
} catch (IOException e) {
System.out.println("Got exception while deleting job");
throw e;
}
}
public static void main(String... args) throws Exception {
Company companyToBeCreated = BasicCompanySample.generateCompany();
Company companyCreated = BasicCompanySample.createCompany(companyToBeCreated);
String companyName = companyCreated.getName();
Job jobToBeCreated = generateJobWithRequiredFields(companyName);
Job jobCreated = createJob(jobToBeCreated);
String jobName = jobCreated.getName();
getJob(jobName);
Job jobToBeUpdated = jobCreated.setDescription("changedDescription");
updateJob(jobName, jobToBeUpdated);
updateJobWithFieldMask(jobName, "title", new Job().setTitle("changedJobTitle"));
deleteJob(jobName);
BasicCompanySample.deleteCompany(companyName);
try {
ListCompaniesResponse listCompaniesResponse = talentSolutionClient.projects().companies()
.list(DEFAULT_PROJECT_ID).execute();
System.out.println("Request Id is " + listCompaniesResponse.getMetadata().getRequestId());
if (listCompaniesResponse.getCompanies() != null) {
for (Company company : listCompaniesResponse.getCompanies()) {
System.out.println(company.getName());
}
}
} catch (IOException e) {
System.out.println("Got exception while listing companies");
throw e;
}
}
}
import com.google.api.services.jobs.v3.CloudTalentSolution;
import com.google.api.services.jobs.v3.model.Company;
import com.google.api.services.jobs.v3.model.CreateCompanyRequest;
import com.google.api.services.jobs.v3.model.UpdateCompanyRequest;
import java.io.IOException;
import java.util.Random;
public class BasicCompanySample {
private static final String DEFAULT_PROJECT_ID = "projects/" + System.getenv("GOOGLE_CLOUD_PROJECT");
private static CloudTalentSolution talentSolutionClient = JobServiceQuickstart.getTalentSolutionClient();
public static Company generateCompany() {
String companyName = "company:" + String.valueOf(new Random().nextLong());
Company company = new Company().setDisplayName("Google")
.setHeadquartersAddress("1600 Amphitheatre Parkway Mountain View, CA 94043")
.setExternalId(companyName);
System.out.println("Company generated: " + company);
return company;
}
public static Company createCompany(Company companyToBeCreated) throws IOException {
try {
CreateCompanyRequest createCompanyRequest = new CreateCompanyRequest().setCompany(companyToBeCreated);
Company companyCreated = talentSolutionClient.projects().companies()
.create(DEFAULT_PROJECT_ID, createCompanyRequest).execute();
System.out.println("Company created: " + companyCreated);
return companyCreated;
} catch (IOException e) {
System.out.println("Got exception while creating company");
throw e;
}
}
public static Company getCompany(String companyName) throws IOException {
try {
Company companyExisted = talentSolutionClient.projects().companies().get(companyName).execute();
System.out.println("Company existed: " + companyExisted);
return companyExisted;
} catch (IOException e) {
System.out.println("Got exception while getting company");
throw e;
}
}
public static Company updateCompany(String companyName, Company companyToBeUpdated) throws IOException {
try {
UpdateCompanyRequest updateCompanyRequest = new UpdateCompanyRequest().setCompany(companyToBeUpdated);
Company companyUpdated = talentSolutionClient.projects().companies()
.patch(companyName, updateCompanyRequest).execute();
System.out.println("Company updated: " + companyUpdated);
return companyUpdated;
} catch (IOException e) {
System.out.println("Got exception while updating company");
throw e;
}
}
public static Company updateCompanyWithFieldMask(String companyName, String fieldMask,
Company companyToBeUpdated) throws IOException {
try {
// String foo = String.format("?updateCompanyFields=%s",fieldMask);
UpdateCompanyRequest updateCompanyRequest = new UpdateCompanyRequest().setUpdateMask(fieldMask)
.setCompany(companyToBeUpdated);
Company companyUpdated = talentSolutionClient.projects().companies()
.patch(companyName, updateCompanyRequest).execute();
System.out.println("Company updated: " + companyUpdated);
return companyUpdated;
} catch (IOException e) {
System.out.println("Got exception while updating company");
throw e;
}
}
public static void deleteCompany(String companyName) throws IOException {
try {
talentSolutionClient.projects().companies().delete(companyName).execute();
System.out.println("Company deleted");
} catch (IOException e) {
System.out.println("Got exception while deleting company");
throw e;
}
}
}
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.jobs.v3.CloudTalentSolution;
import com.google.api.services.jobs.v3.model.Company;
import com.google.api.services.jobs.v3.model.ListCompaniesResponse;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;
public class JobServiceQuickstart {
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final NetHttpTransport NET_HTTP_TRANSPORT = new NetHttpTransport();
private static final String SCOPES = "https://www.googleapis.com/auth/jobs";
private static final String DEFAULT_PROJECT_ID = "projects/" + System.getenv("GOOGLE_CLOUD_PROJECT");
private static final CloudTalentSolution talentSolutionClient = createTalentSolutionClient(generateCredential());
private static CloudTalentSolution createTalentSolutionClient(GoogleCredentials credential) {
String url = "https://jobs.googleapis.com";
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential);
return new CloudTalentSolution.Builder(NET_HTTP_TRANSPORT, JSON_FACTORY, setHttpTimeout(requestInitializer))
.setApplicationName("JobServiceClientSamples").setRootUrl(url).build();
}
private static GoogleCredentials generateCredential() {
try {
// Credentials could be downloaded after creating service account
// set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable, for example:
// export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/key.json
return GoogleCredentials.getApplicationDefault().createScoped(Collections.singleton(SCOPES));
} catch (Exception e) {
System.out.print("Error in generating credential");
throw new RuntimeException(e);
}
}
private static HttpRequestInitializer setHttpTimeout(final HttpRequestInitializer requestInitializer) {
return request -> {
requestInitializer.initialize(request);
request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
request.setConnectTimeout(1 * 60000); // 1 minute connect timeout
request.setReadTimeout(1 * 60000); // 1 minute read timeout
};
}
public static CloudTalentSolution getTalentSolutionClient() {
return talentSolutionClient;
}
I can’t figure out the authorization and I can’t figure out where I should write (in my application) all the authorization parameters
Here is the error I'm getting right now
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
POST https://jobs.googleapis.com/v3/projects/null/companies
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:118)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:37)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:428)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1111)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:514)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:455)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:565)
at io.fortylines.tapintech.jobapi.BasicCompanySample.createCompany(BasicCompanySample.java:37)
at io.fortylines.tapintech.jobapi.BasicJobSample.main(BasicJobSample.java:116)
And one more note. When I debug I see that in this line
private static final String DEFAULT_PROJECT_ID = "projects/" + System.getenv("GOOGLE_CLOUD_PROJECT");
"projects/" = null
While in google cloud i created a project
Here are my application.properties
# application
server.port=8081
# database
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=
spring.cloud.gcp.core.enabled=true
spring.cloud.gcp.project-id=tab-in-tech
spring.cloud.gcp.credentials.location=file:/usr/local/key.json
spring.cloud.gcp.credentials.scopes=https://www.googleapis.com/auth/pubsub,https://www.googleapis.com/auth/sqlservice.admin
spring.cloud.gcp.config.name=
spring.cloud.gcp.config.credentials.encoded-key=
Maybe I'm doing something wrong here

How can I read a application properties file by prefix?

I am trying to first print my application properties into java, then push it into a thymeleaf html page. Purpose: to allow users to edit the properties file using GET/POST. My current code will display the values key and values of the properties to the console if it is equal to something. How can I get it where it would only extract specific and multiple prefixes?
Code/Attempt
public class ReadPropertiesFile {
public static void readProp() {
try {
Properties prop = new Properties();
prop.load(ReadPropertiesFile.class.getResourceAsStream("/application.properties"));
Enumeration enuKeys = prop.keys();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = prop.getProperty(key);
System.out.println(key + "= " + value);
}
} catch (FileNotFoundException e) {
//System.out.print("System cannot find file");
e.printStackTrace();
} catch (IOException e) {
//System.out.print("System cannot find file");
e.printStackTrace();
}
}
}
Example application.properties
prefix.foo = bar#!car#!war#!scar
prefix.cool = honda#!toyota#lexus
some.feed = live#!stream#!offline
some.feed = humans#!dogs#!cat
noprefix = dont#!print#!me
host = host1#!host2#!host3
To be able to just print all values of prefix and some.
public class ReadPropertiesFile {
public static void readProp() {
try {
Properties prop = new Properties();
prop.load(ReadPropertiesFile.class.getResourceAsStream("/application.properties"));
Enumeration enuKeys = prop.keys();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = prop.getProperty(key);
if (key.startsWith("prefix") || key.startsWith("some")) {
System.out.println(key + "= " + value);
}
}
} catch (FileNotFoundException e) {
//System.out.print("System cannot find file");
e.printStackTrace();
} catch (IOException e) {
//System.out.print("System cannot find file");
e.printStackTrace();
}
}
Is this what you want? Just print keys that start with "prefix" or "some"?

Retrieving emails from Latest to oldest Java Mail API

public class testemail {
Properties properties = null;
private Session session = null;
private Store store = null;
private Folder inbox = null;
private String userName = "xxx#gmail.com"; //
private String password = "xxx";
public testemail() {
}
public void readMails() throws Exception {
properties = new Properties();
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "995");
properties.setProperty("mail.transport.protocol", "imaps");
session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
store = session.getStore("imaps");
store.connect();
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.search(new FlagTerm(
new Flags(Flag.SEEN), false));
System.out.println("Number of mails = " + messages.length);
for ( Message message : messages ) {
Address[] from = message.getFrom();
System.out.println("-------------------------------");
System.out.println("Date : " + message.getSentDate());
System.out.println("From : " + from[0]);
System.out.println("Subject: " + message.getSubject());
System.out.println("Content :");
Object content = message.getContent();
Multipart multiPart = (Multipart) content;
procesMultiPart(multiPart);
System.out.println("--------------------------------");
}
inbox.close(true);
store.close();
}
catch (NoSuchProviderException e)
{
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void procesMultiPart(Multipart content) throws Exception {
int multiPartCount = content.getCount();
for (int i = 0; i < multiPartCount; i++) {
BodyPart bodyPart = content.getBodyPart(i);
Object o;
o = bodyPart.getContent();
if (o instanceof String) {
System.out.println(o);
} else if (o instanceof Multipart) {
procesMultiPart((Multipart) o);
}
}
}
public static void main(String[] args) throws Exception {
testemail sample = new testemail();
sample.readMails();
}}
In the above code I am able to get emails from oldest to newest on my console from gmail. However I would want it to loop from newest to oldest. Is there any way I could get this achieved. Please Help :)
I don't think there's a parameter or method for this in the JavaMail API. You have to reverse the messages array yourself, e.g. by including the Commons.Lang library:
messages = ArrayUtils.reverse(messages);
or iterating over it in the other direction:
for (int i = messages.length - 1; i >= 0; i--) {
Message message = messages[i];

Store different objects and return it in a method

I am very new to Java programming. I have a requirement where i need to connect to Mbean and perform certain tasks like Enable ,disable, count of MBeans.
enable method is used to enable the Mbean and disable method is to disable and Count method is used to get the count of Mbean.
In all the 3 case i need to connect to the Mbean server. So i decided to write a generic method to create a connection to the server, so when ever any method called then inside each method i can call the generic method.
The challenge that i am facing in storing different objects and have to return in generic method so that i can use the objects values in disable,enable and count methods.
Please see below code and let me how i can achieve it.
package mbeanappscontrollerws;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXServiceURL;
import oracle.oc4j.admin.jmx.remote.api.JMXConnectorConstant;
import java.net.MalformedURLException;
import java.io.IOException;
import java.util.regex.Pattern;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.ReflectionException;
public class MBeanAppsController {
public static void main(String[] args) {
try {
/* enable("******", "****", "****",
"*****", "****",
"***");
disable("******", "****", "****",
"*****", "****",
"***");
*/
} catch (Exception e) {
// TODO
}
}
public static MBeanServerConnection connectMethd(String host, String port,
String container,
String beanFQDN,
String usr, String pwd) {
/* MBean server URL */
String mbeanServerURL =
new String("service:jmx:rmi:" + "///opmn://" + host + ":" + port +
"/" + container);
/* credentials for authentication */
Hashtable cred = new Hashtable();
cred.put(JMXConnectorConstant.CREDENTIALS_LOGIN_KEY, (Object)usr);
cred.put(JMXConnectorConstant.CREDENTIALS_PASSWORD_KEY, (Object)pwd);
/* connection parameters */
Hashtable env = new Hashtable();
env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,
(Object)"oracle.oc4j.admin.jmx.remote");
env.put(JMXConnector.CREDENTIALS, (Object)cred);
/*System.out.println("env " + env);*/
JMXServiceURL jmxServerURL = null;
JMXConnector jmxConn = null;
MBeanServerConnection serverConn = null;
try {
/* connect to the MBean Server */
System.out.println("mbeanServerURL " + mbeanServerURL);
jmxServerURL = new JMXServiceURL(mbeanServerURL);
System.out.println("jmxServerURL " + jmxServerURL);
try {
jmxConn = JMXConnectorFactory.connect(jmxServerURL, env);
serverConn = jmxConn.getMBeanServerConnection();
} catch (IOException e) {
System.out.println(e);
}
}
catch (MalformedURLException e) {
}
return serverConn;
}
public static String[] enable(String host, String port, String container,
String beanFQDN, String usr, String pwd) {
String Output[] = new String[3];
try {
MBeanServerConnection serverConn =
connectMethd(host, port, container, beanFQDN, usr, pwd);
/* retrieve mbean app using the FQDN */
ObjectName mbeanName = new ObjectName(beanFQDN);
/* enable the MBean App */
serverConn.invoke(mbeanName, "startUp", null, null);
/* retrieve the running status of the MBean App after enabling */
Boolean mbeanAppRunning =
Boolean.valueOf(serverConn.getAttribute(mbeanName,
"Running").toString());
String beanAppStatus = "DISABLED";
if (mbeanAppRunning.booleanValue())
beanAppStatus = "ENABLED";
/* pattern to extract mbean application names */
Pattern mbeanAppPat =
Pattern.compile("name=", Pattern.CASE_INSENSITIVE);
String beanName = mbeanAppPat.split(beanFQDN)[1];
Output[0] = beanName;
Output[1] = beanFQDN;
Output[2] = beanAppStatus;
} catch (MalformedObjectNameException e) {
e.getStackTrace();
} catch (InstanceNotFoundException e) {
e.getStackTrace();
} catch (AttributeNotFoundException e) {
e.getStackTrace();
} catch (ReflectionException e) {
e.getStackTrace();
} catch (MBeanException e) {
e.getStackTrace();
} catch (IOException ioe) {
System.out.println(ioe);
}
System.out.println("Enable Method OutPut " + Output);
return Output;
}
public static String[] disable(String host, String port, String container,
String beanFQDN, String usr, String pwd) {
String Output[] = new String[3];
try {
MBeanServerConnection serverConn =
connectMethd(host, port, container, beanFQDN, usr, pwd);
/* retrieve mbean app using the FQDN */
ObjectName mbeanName = new ObjectName(beanFQDN);
/* enable the MBean App */
serverConn.invoke(mbeanName, "shutDown", null, null);
/* retrieve the running status of the MBean App after enabling */
Boolean mbeanAppRunning =
Boolean.valueOf(serverConn.getAttribute(mbeanName,
"Running").toString());
String beanAppStatus = "DISABLED";
if (mbeanAppRunning.booleanValue())
beanAppStatus = "ENABLED";
Pattern mbeanAppPat =
Pattern.compile("name=", Pattern.CASE_INSENSITIVE);
String beanName = mbeanAppPat.split(beanFQDN)[1];
/* debug */
System.out.println("Finished executing 'disable' operation.");
Output[0] = beanName;
Output[1] = beanFQDN;
Output[2] = beanAppStatus;
} catch (MalformedObjectNameException e) {
e.getStackTrace();
} catch (InstanceNotFoundException e) {
e.getStackTrace();
} catch (AttributeNotFoundException e) {
e.getStackTrace();
} catch (ReflectionException e) {
e.getStackTrace();
} catch (MBeanException e) {
e.getStackTrace();
} catch (IOException ioe) {
System.out.println(ioe);
}
System.out.println("Disable Method OutPut " + Output);
return Output;
}
public static int MBeancount(String host, String port, String container,
String filter, String usr, String pwd) {
int mbeanAppsCount = 0;
try {
MBeanServerConnection serverConn =
connectMethd(host, port, container, filter, usr, pwd);
ObjectName mbeanDomainName = new ObjectName(filter);
Set mbeanAppNames = serverConn.queryNames(mbeanDomainName, null);
/* retrieve mbean apps count */
Iterator i;
for (i = mbeanAppNames.iterator(); i.hasNext();
i.next(), mbeanAppsCount++)
;
} catch (MalformedObjectNameException e) {
/* debug */
System.out.println(e);
} catch (IOException ioe) {
System.out.println(ioe);
} finally {
/* debug */
System.out.println("End: MBeanAppsController-Java-getMBeanAppsCount");
try {
/* close server connection */
if (jmxConn != null) {
jmxConn.close();
} else {
}
} catch (IOException e) {
/* debug */
System.out.println(e);
}
}
System.out.println("mbeanAppsCount" + mbeanAppsCount);
return mbeanAppsCount;
}
}
In above code under final block i am not able to access jmxconn variable from the method connect because it is derived from JMXconnector but in generic method i am returning MBeanServerConnection type. In my case i want both the object type MBeanServerConnection and JMXconnector values to be returned. If some one can help me then it would be a great help.
Regards,
TJ.
An ugly/simple solution is to make the connectMethd(sic) method return an array containing serverConn and jmxConn:
Change its declaration and return statements, as bellow:
public static Object[] connectMethd(String host, String port,
String container,
String beanFQDN,
String usr, String pwd){
// same code as before here...
return new Object[]{serverConn,jmxConn};
}
When calling connectMethd, put the result in an Object[] variable, and cast its elements at indexes 0 and 1 to the appropriate types. Examples:
Object[] connections = connectMethd(host, port, container, beanFQDN, usr, pwd);
MBeanServerConnection serverConn = (MBeanServerConnection) connections[0];
JMXConnector jmxConn = (JMXConnector) connections[1];

JavaMail : Folder.hasNewMessages() and .getMessageCount() don't seem to work properly

I have this simple code to perdiodically access a pop3 server and check if there are new messages in the inbox folder
public static void main(String[] args) {
try {
String storeType = "pop3";
String host = "...";
int port = ...;
String user = "...";
String psw = "...";
//
int delay = 1;
long mins = 200 * 60 * delay;
firstAccess = true;
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.user", user);
properties.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.pop3.port", port);
RomasAuthenticator r = new RomasAuthenticator(user, psw);
Session session = Session.getDefaultInstance(properties, r);
POP3Store emailStore = (POP3Store) session.getStore(storeType);
emailStore.connect(host, port, user, psw);
Folder emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
while (true) {
if (checkInbox(emailFolder)) {
//prepara la notifica per il voice_service
System.out.println("mes!");
}
firstAccess = false;
Thread.sleep(mins);
}
} catch (Exception ex) {
//return null;
}
}
private static boolean checkInbox(Folder inbox_folder) throws MessagingException, IOException {
System.out.println("checking");
boolean res = false;
try {
int email_actual_count = inbox_folder.getMessageCount();
if (email_actual_count > email_prev_count /*or hasNewMessages()*/) {
if (!firstAccess) {
res = true;
}
}
//bisogna aggiornare comunque email_count in caso siano stati cancellati messaggi
email_prev_count = email_actual_count;
}
catch (Exception e) {
e.printStackTrace();
}
return res;
}
Both getMessageCount() and hasNewMessages() do not work, because the first always returns the same number of messages, and the second always returns false. What's that I'm doing wrong?
I don't want to use a messagelistener because this code will run on a robot with really low performances..
thanks everyone
The JavaMail FAQ explains why these features don't work with the POP3 protocol.

Categories

Resources