I try to execute the startUp method when i deploy my web services, but doesn`t work.
I'm using:
windows 7
tomcat 8.0.30
axis2 1.7.0
I've tryed to deploy my service as a pojo service also i try generating the *.aar and placing it in:
apache-tomcat-8.0.30\webapps\axis2\WEB-INF\services
but when i run the tomcat, and deploy this and other services, the startUp method dont launch.
this is my code:
import java.io.*;
import java.util.*;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.ServiceLifeCycle;
public class Login implements ServiceLifeCycle{
static String IPprop = "";
static String rutaDB = "C:/resources/users_DB.txt";
static String rutaUddiXml = "C:/resources/uddi.xml";
static String rutaIP = "C:/resources/ip.txt";
static boolean registrado=false;
static String comp ="";
public static void main(String[] args) {
IP();
String nombreServicio = "Login";
String rutaServicio = "http://"+ IPprop +":8080/axis2/services/Login";
SimplePublishPortable spp = new SimplePublishPortable(rutaUddiXml);
spp.publish(nombreServicio, rutaServicio);
System.out.println("te registraste");
}
public static void createUser(String user, String pass) {
interacFich("crea", user, pass);
}
public static String loginAccess(String user, String pass) {
return interacFich("login", user, pass);
}
public static String runComprobation(){
return "deployed service" + comp;
}
public static String regComprobation(){
if(registrado==true){
return "registered";
}
else{
return "failed";
}
}
private static String getToken() {
String cadenaAleatoria = "";
int i = 0;
while (i < 10) {
char c = (char) ((int) (Math.random() * 255 + 1));
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z')) {
cadenaAleatoria += c;
i++;
}
}
return cadenaAleatoria;
}
private static String interacFich(String accion, String user, String pass) {
String usuario = "";
LinkedHashMap<String, String> usuarios = new LinkedHashMap<String, String>();
File archivo = new File(rutaDB);
// leer fichero y meterlo en el mapa
if (archivo.exists() == false) {
try {
archivo.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try (BufferedReader br = new BufferedReader(new FileReader(archivo))) {
while (br.ready()) {
usuario = br.readLine();
String[] param = usuario.split("\\*");
usuarios.put(param[0], param[1]);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
switch (accion) {
case "crea":
usuarios.put(user + "-" + pass, getToken());
try (BufferedWriter bw = new BufferedWriter(new FileWriter(archivo))) {
Set<String> keysUsuarios = usuarios.keySet();
for (String k : keysUsuarios) {
bw.write(k + "*" + usuarios.get(k).toString());
bw.write("\n");
}
System.out.println("todo escrito");
bw.close();
return "el fichero se crea";
} catch (IOException e) {
e.printStackTrace();
}
break;
case "login":
if (usuarios.containsKey(user + "-" + pass)) {
return usuarios.get(user + "-" + pass);
}
return "User o pass erroneos";
default:
break;
}
return null;
}
private static void IP() {
File archivo = new File(rutaIP);
try (BufferedReader br = new BufferedReader(new FileReader(archivo))) {
br.readLine();
IPprop = br.readLine();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
#Override
public void startUp(ConfigurationContext arg0, AxisService arg1) {
///////////////
//registrarse//
///////////////
comp="entramos";
IP();
String nombreServicio = "Login";
String rutaServicio = "http://"+ IPprop +":8080/axis2/services/Login";
SimplePublishPortable spp = new SimplePublishPortable(rutaUddiXml);
spp.publish(nombreServicio, rutaServicio);
registrado=true;
}
#Override
public void shutDown(ConfigurationContext arg0, AxisService arg1) {
// TODO Auto-generated method stub
}
}
Have you created the Service Definition (services.xml) file, on which you describe your services?
I am referring to a file similar to the example in Code Listing 3: The Service Definition File in the following link (axis2 quick start):
https://axis.apache.org/axis2/java/core/docs/quickstartguide.html#services
Related
Im trying to read username and password from .txt file in Java.
Format of file is as following:
user1:pass1
user2:pass2
user3:pass3
My code can't properly read passwords, any hints?
EDIT: also missing last password because last \n is missing, any way to repair it instead of adding extra newline to txt file?
try {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
int c;
String user = "";
String pass = "";
char helper = 0;
while(( c = bufferedReader.read()) != -1 ) {
System.out.println((char)c);
if((char)c == '\n') {
ftpServer.addUser(user, pass);
//System.out.printf("%s", pass);
user = "";
pass = "";
helper = 0;
} else {
if ((char) c == ':') {
helper = ':';
}
if (helper == 0) {
user += (char) c;
}
if (helper == ':') {
if ((char) c != ':')
pass += (char) c;
}
}
}
bufferedReader.close();
}
If using JAVA: 8 and 8+ you could use stream on Files - java.nio.files
Path path = Paths.get(filename);
try (Stream<String> lines = Files.lines(path)) {
lines.forEach(s -> {
if (s.contains(":")) {
String[] line = s.split(":");
String userName = line[0];
String pass = line[1];
System.out.println("User name: " + userName + " password: " + pass);
}
});
} catch (IOException ex) {
// do something or re-throw...
}
Or use BufferedReader
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("/Users/kants/test.txt"));
String lineInFile = reader.readLine();
while (lineInFile != null) {
if (lineInFile.contains(":")) {
String[] line = lineInFile.split(":");
String userName = line[0];
String pass = line[1];
System.out.println("User name: " + userName + " password: " + pass);
}
lineInFile = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
NOTE: You must add further null checks and try-catch handlings. Above code is just to show you the logic.
I dont think you need an additional loop
public static void main(String[] args) throws IOException {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"path/to/file"));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
// read next line
line = reader.readLine();
if (line.contains(":")) {
String user = line.split(":")[0];
String pass = line.split(":")[1];
System.out.println("User is " + user + "Password is " + pass);
} }
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
prints
user1:pass1
User is user2Password is pass2
user2:pass2
User is user3Password is pass3
user3:pass3
Here is an elaborated implementation -
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
public class ReadFileAsStream {
public static void main(String... arguments) {
CredentialsParser parser;
try {
parser = new CredentialsParser("c:/temp/credtest.txt");
Credential[] credentials = parser.getCredentials();
for (Credential credential : credentials) {
System.out.println(String.format("%s : %s", credential.getUsername(), credential.getPassword()));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Parser for the credentials file format
class CredentialsParser {
private Set<Credential> credentials = new HashSet<>();
String filename = null;
public CredentialsParser() {
super();
}
public CredentialsParser(String filename) throws IOException {
super();
setFilename(filename);
if (getFilename() != null) {
parseCredentialsFile();
}
}
public Credential[] getCredentials() {
return credentials.toArray(new Credential[credentials.size()]);
}
// method to add credentials
public void addCredential(String entry) {
if (entry.indexOf(':') > -1) {
String[] values = entry.split(":");
credentials.add(new Credential(values[0], values[1]));
}
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
protected void parseCredentialsFile() throws IOException {
// read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(filename))) {
stream.forEach(this::addCredential);
}
}
}
// Value holder for each credential entry
class Credential {
private String username = null;
private String password = null;
public Credential() {
super();
}
public Credential(String username, String password) {
super();
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Please modify your code to this :
Use split method to make your work easy :)
public class Example {
public static void main(String[] args) {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("F://test.txt"));
String line = reader.readLine();
while (line != null) {
String[] lineParts = line.split(":");
System.out.println("user : " + lineParts[0]);
System.out.println("password : " + lineParts[1]);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In test.txt :
user1:pass1
user2:pass2
user3:pass3
Output :
user : user1
password : pass1
user : user2
password : pass2
user : user3
password : pass3
I found this great Java Bean that allows you to send an html email including attachments via a managed java bean. It works as described when I use it directly form an Xpage.
However, I would like to use this in the backend in a scheduled agent. The problem I have run into is when I try to pass a document to the java bean. The bean is expecting (I think) an XSP document, which I don't have when in the back end, so it throws an error.
I thought I would just send the UNID of the document that I want and then change it so it would work with this bean, however, when I try to set the UNID I get an error:
Unknown member 'setUNID' in Java class 'com.scoular.utls.Email'
I am confused. Seems like this has something to do with a wrapped document, but don't understand.
Here is the faces-config:
<faces-config>
<managed-bean>
<managed-bean-name>Email</managed-bean-name>
<managed-bean-class>com.scoular.utls.Email</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>debugMode</property-name>
<value>true</value>
</managed-property>
</managed-bean>
</faces-config>
Here is a button I am using to test calling the method:
//Need to get email document
var emlView = database.getView("xpViewEmailsAll");
var emlDoc = emlView.getFirstDocument();
if (emlDoc != null) {
//try{
var subject = ""
var senderEmail = supEml
var senderName = supNme
Email.setSendTo("John");
Email.setSubject("subject");
Email.setSenderEmail("John#gmal.com");
Email.setUNID = emlDoc.getUniversalID();
Email.setSenderName("Sender");
//Email.setBackEndDocument(emlDoc);
Email.setFieldName("Body");
Email.send();
//}catch(e){
//print(e.getMessage());
//}
}
And here is the bean:
package com.scoular.utls;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.context.FacesContext;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.EmbeddedObject;
import lotus.domino.MIMEEntity;
import lotus.domino.MIMEHeader;
import lotus.domino.NotesException;
import lotus.domino.Session;
import lotus.domino.Stream;
import com.ibm.commons.util.NotImplementedException;
import com.ibm.domino.xsp.module.nsf.NotesContext;
import com.ibm.xsp.model.FileRowData;
import com.ibm.xsp.model.domino.wrapped.DominoDocument;
import com.ibm.xsp.model.domino.wrapped.DominoRichTextItem;
import com.ibm.xsp.model.domino.wrapped.DominoDocument.AttachmentValueHolder;
import com.ibm.xsp.persistence.PersistedContent;
public class Email {
private ArrayList<String> sendTo;
private ArrayList<String> ccList;
private ArrayList<String> bccList;
private String senderEmail;
private String senderName;
private String subject;
private DominoDocument document;
private String fieldName;
private String bannerHTML;
private String footerHTML;
private String unid;
private boolean debugMode = false;
private static final Pattern imgRegExp = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");
// -------------------------------------------------------------------------
public Email() {
this.subject = "";
this.sendTo = new ArrayList<String>();
this.ccList = new ArrayList<String>();
this.bccList = new ArrayList<String>();
}
// -------------------------------------------------------------------------
public String getSendTo() {
if (this.isDebugMode()) {
System.out.println("getSendTo() : " + this.sendTo.toString());
}
return this.sendTo.toString().replace("[", "").replace("]", "");
}
public void setSendTo(final String sendTo) {
this.sendTo.add(sendTo);
}
// -------------------------------------------------------------------------
public String getCcList() {
if (this.isDebugMode()) {
System.out.println("getCcList() : " + this.ccList.toString());
}
return this.ccList.toString().replace("[", "").replace("]", "");
}
public void setCcList(final String ccList) {
this.ccList.add(ccList);
}
// -------------------------------------------------------------------------
public String getBccList() {
if (this.isDebugMode()) {
System.out.println("getBccList() : " + this.bccList.toString());
}
return this.bccList.toString().replace("[", "").replace("]", "");
}
public void setBccList(final String bccList) {
this.bccList.add(bccList);
}
// -------------------------------------------------------------------------
public String getSenderEmail() {
return this.senderEmail;
}
public void setSenderEmail(final String senderEmail) {
this.senderEmail = senderEmail;
}
// -------------------------------------------------------------------------
public String getSenderName() {
return this.senderName;
}
public void setSenderName(final String senderName) {
this.senderName = senderName;
}
// -------------------------------------------------------------------------
public String getSubject() {
return this.subject;
}
public void setSubject(final String subject) {
this.subject = subject;
}
// -------------------------------------------------------------------------
public boolean isDebugMode() {
return this.debugMode;
}
public void setDebugMode(final boolean debugMode) {
this.debugMode = debugMode;
}
// -------------------------------------------------------------------------
private Session getCurrentSession() {
NotesContext nc = NotesContext.getCurrentUnchecked();
return (null != nc) ? nc.getCurrentSession() : null;
}
// -------------------------------------------------------------------------
private Database getCurrentDatabase() {
NotesContext nc = NotesContext.getCurrentUnchecked();
return (null != nc) ? nc.getCurrentDatabase() : null;
}
// -------------------------------------------------------------------------
public void send() throws NotesException, IOException, Exception {
Session session = getCurrentSession();
Database database = getCurrentDatabase();
if (null != session && null != database && null != this.sendTo && null != this.subject
&& null != this.senderEmail) {
try {
if (this.isDebugMode()) {
System.out.println("Started send()");
}
session.setConvertMime(false);
Document emailDocument = database.createDocument();
MIMEEntity emailRoot = emailDocument.createMIMEEntity("Body");
if (null != emailRoot) {
MIMEHeader emailHeader = emailRoot.createHeader("Reply-To");
emailHeader.setHeaderVal(this.getSenderEmail());
emailHeader = emailRoot.createHeader("Return-Path");
emailHeader.setHeaderVal(this.getSenderEmail());
final String fromSender = (null == this.getSenderName()) ? this.getSenderEmail() : "\""
+ this.getSenderName() + "\" <" + this.getSenderEmail() + ">";
emailHeader = emailRoot.createHeader("From");
emailHeader.setHeaderVal(fromSender);
emailHeader = emailRoot.createHeader("Sender");
emailHeader.setHeaderVal(fromSender);
emailHeader = emailRoot.createHeader("To");
emailHeader.setHeaderVal(this.getSendTo());
if (!this.ccList.isEmpty()) {
emailHeader = emailRoot.createHeader("CC");
emailHeader.setHeaderVal(this.getCcList());
}
if (!this.bccList.isEmpty()) {
emailHeader = emailRoot.createHeader("BCC");
emailHeader.setHeaderVal(this.getBccList());
}
emailHeader = emailRoot.createHeader("Subject");
emailHeader.setHeaderVal(this.getSubject());
MIMEEntity emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild) {
final String boundary = System.currentTimeMillis() + "-" + this.document.getDocumentId();
emailHeader = emailRootChild.createHeader("Content-Type");
emailHeader.setHeaderVal("multipart/alternative; boundary=\"" + boundary + "\"");
MIMEEntity emailChild = emailRootChild.createChildEntity();
if (null != emailChild) {
final String contentAsText = this.document.getRichTextItem(this.fieldName)
.getContentAsText();
Stream stream = session.createStream();
stream.writeText(contentAsText);
emailChild.setContentFromText(stream, "text/plain; charset=\"UTF-8\"", MIMEEntity.ENC_NONE);
stream.close();
emailChild = emailRootChild.createChildEntity();
stream = session.createStream();
stream.writeText(this.getHTML());
emailChild.setContentFromText(stream, "text/html; charset=\"UTF-8\"", MIMEEntity.ENC_NONE);
stream.close();
stream.recycle();
stream = null;
}
// add embedded images....
final List<FileRowData> embeddedImages = this.getEmbeddedImagesList();
if (null != embeddedImages && !embeddedImages.isEmpty()) {
if (this.isDebugMode()) {
System.out.println("Adding Embedded Images...");
}
for (FileRowData embeddedImage : embeddedImages) {
emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild && embeddedImage instanceof AttachmentValueHolder) {
InputStream is = null;
try {
String persistentName = ((AttachmentValueHolder) embeddedImage)
.getPersistentName();
String cid = ((AttachmentValueHolder) embeddedImage).getCID();
emailHeader = emailRootChild.createHeader("Content-Disposition");
emailHeader.setHeaderVal("inline; filename=\"" + persistentName + "\"");
emailHeader = emailRootChild.createHeader("Content-ID");
emailHeader.setHeaderVal("<" + cid + ">");
is = this.getEmbeddedImageStream(persistentName);
Stream stream = session.createStream();
stream.setContents(is);
emailRootChild.setContentFromBytes(stream, embeddedImage.getType(),
MIMEEntity.ENC_IDENTITY_BINARY);
if (this.isDebugMode()) {
System.out.println("Added Embedded Image : " + persistentName);
}
} catch (IOException e) {
if (this.isDebugMode()) {
System.out.println("Adding Embedded Image failed : " + e.getMessage());
}
throw e;
} finally {
if (null != is) {
is.close();
is = null;
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed Adding Embedded Images");
}
}
// add attachments....
final List<FileRowData> attachments = this.getDocument().getAttachmentList(this.getFieldName());
if (null != attachments && !attachments.isEmpty()) {
if (this.isDebugMode()) {
System.out.println("Adding Attachments...");
}
for (FileRowData attachment : attachments) {
emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild && attachment instanceof AttachmentValueHolder) {
InputStream is = null;
try {
String persistentName = ((AttachmentValueHolder) attachment)
.getPersistentName();
String cid = ((AttachmentValueHolder) attachment).getCID();
EmbeddedObject eo = this.getDocument().getDocument().getAttachment(
persistentName);
if (null != eo) {
emailHeader = emailRootChild.createHeader("Content-Disposition");
emailHeader.setHeaderVal("attachment; filename=\"" + persistentName + "\"");
emailHeader = emailRootChild.createHeader("Content-ID");
emailHeader.setHeaderVal("<" + cid + ">");
is = eo.getInputStream();
Stream stream = session.createStream();
stream.setContents(is);
emailRootChild.setContentFromBytes(stream, attachment.getType(),
MIMEEntity.ENC_IDENTITY_BINARY);
if (this.isDebugMode()) {
System.out.println("Added Attachment : " + persistentName);
}
}
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Adding Attachment failed : " + e.getMessage());
}
throw e;
} finally {
if (null != is) {
is.close();
is = null;
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed Adding Attachments");
}
}
}
}
emailDocument.send();
session.setConvertMime(true);
if (this.isDebugMode()) {
System.out.println("Completed send()");
}
} catch (NotesException e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with NotesException" + e.getMessage());
}
throw e;
} catch (IOException e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with IOException" + e.getMessage());
}
throw e;
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with Exception" + e.getMessage());
}
throw e;
}
}
}
// -------------------------------------------------------------------------
public DominoDocument getDocument() {
return this.document;
}
public void setDocument(final DominoDocument document) {
this.document = document;
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
public String getFieldName() {
return this.fieldName;
}
public void setFieldName(final String fieldName) {
this.fieldName = fieldName;
}
// -------------------------------------------------------------------------
public List<FileRowData> getEmbeddedImagesList() throws NotesException {
if (null != document && null != fieldName) {
return document.getEmbeddedImagesList(fieldName);
}
return null;
}
// -------------------------------------------------------------------------
private InputStream getEmbeddedImageStream(final String fileName) throws NotesException, IOException {
if (null != document && null != fieldName && null != fileName) {
final DominoRichTextItem drti = document.getRichTextItem(fieldName);
if (null != drti) {
final PersistedContent pc = drti.getPersistedContent(FacesContext.getCurrentInstance(), fieldName,
fileName);
if (null != pc) {
return pc.getInputStream();
}
}
}
return null;
}
// -------------------------------------------------------------------------
public String getHTML() {
StringBuffer html = new StringBuffer();
html.append(getBannerHTML());
html.append(getBodyHTML());
html.append(getFooterHTML());
return html.toString();
}
// -------------------------------------------------------------------------
public String getBannerHTML() {
return this.bannerHTML;
}
public void setBannerHTML(final String bannerHTML) {
this.bannerHTML = bannerHTML;
}
// -------------------------------------------------------------------------
public String getBodyHTML() {
if (null != document && null != fieldName) {
if (this.isDebugMode()) {
System.out.println("Started getBodyHTML()");
}
final DominoRichTextItem drti = document.getRichTextItem(fieldName);
if (null != drti) {
try {
String html = drti.getHTML();
if (null != html) {
final List<FileRowData> fileRowDataList = document.getEmbeddedImagesList(fieldName);
if (null != fileRowDataList) {
final Matcher matcher = imgRegExp.matcher(html);
while (matcher.find()) {
String src = matcher.group();
final String srcToken = "src=\"";
final int x = src.indexOf(srcToken);
final int y = src.indexOf("\"", x + srcToken.length());
final String srcText = src.substring(x + srcToken.length(), y);
for (FileRowData fileRowData : fileRowDataList) {
final String srcImage = fileRowData.getHref();
final String cidImage = ((AttachmentValueHolder) fileRowData).getCID();
if (srcText.endsWith(srcImage)) {
final String newSrc = src.replace(srcText, "cid:" + cidImage);
html = html.replace(src, newSrc);
if (this.isDebugMode()) {
System.out.println("CID referenced image: " + srcText + " with CID:"
+ cidImage);
}
}
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed getBodyHTML() : " + html);
}
return html;
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Failed getBodyHTML() : " + e.getMessage());
}
}
}
}
return null;
}
public void setBodyHTML(final String bodyHTML) throws NotImplementedException {
if (this.isDebugMode()) {
System.out.println("Method setBodyHTML(string) is not permitted");
}
throw new NotImplementedException();
}
// -------------------------------------------------------------------------
public String getFooterHTML() {
return this.footerHTML;
}
public void setFooterHTML(final String footerHTML) {
this.footerHTML = footerHTML;
}
public String getUnid() {
return unid;
}
public void setUnid(final String unid) {
this.unid = unid;
}
// -------------------------------------------------------------------------
} // end EmailBean
The Email.setUNID statement is wrong. Try:
Email.setUnid(emlDoc.getUniversalID());
I'm trying to fix a bug in the code I wrote which convert a srt file to dxfp.xml. it works fine but when there is a special character such as an ampersand it throws an java.lang.NumberFormatException error. I tried to use the StringEscapeUtils function from apache commons to solve it. Can someone explain to me what it is I am missing here? thanks in advance!
public class SRT_TO_DFXP_Converter {
File input_file;
File output_file;
ArrayList<CaptionLine> node_list;
public SRT_TO_DFXP_Converter(File input_file, File output_file) {
this.input_file = input_file;
this.output_file = output_file;
this.node_list = new ArrayList<CaptionLine>();
}
class CaptionLine {
int line_num;
String begin_time;
String end_time;
ArrayList<String> content;
public CaptionLine(int line_num, String begin_time, String end_time,
ArrayList<String> content) {
this.line_num = line_num;
this.end_time = end_time;
this.begin_time = begin_time;
this.content = content;
}
public String toString() {
return (line_num + ": " + begin_time + " --> " + end_time + "\n" + content);
}
}
private void readSRT() {
BufferedReader bis = null;
FileReader fis = null;
String line = null;
CaptionLine node;
Integer line_num;
String[] time_split;
String begin_time;
String end_time;
try {
fis = new FileReader(input_file);
bis = new BufferedReader(fis);
do {
line = bis.readLine();
line_num = Integer.valueOf(line);
line = bis.readLine();
time_split = line.split(" --> ");
begin_time = time_split[0];
begin_time = begin_time.replace(',', '.');
end_time = time_split[1];
end_time.replace(',', '.');
ArrayList<String> content = new ArrayList<String>();
while (((line = bis.readLine()) != null)
&& (!(line.trim().equals("")))) {
content.add(StringEscapeUtils.escapeJava(line));
//if (StringUtils.isEmpty(line)) break;
}
node = new CaptionLine(line_num, begin_time, end_time, content);
node_list.add(node);
} while (line != null);
} catch (Exception e) {
System.out.println(e);
}
finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private String convertToXML() {
StringBuffer dfxp = new StringBuffer();
dfxp.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tt xml:lang=\"en\" xmlns=\"http://www.w3.org/2006/04/ttaf1\" xmlns:tts=\"http://www.w3.org/2006/04/ttaf1#styling\">\n\t<head>\n\t\t<styling>\n\t\t\t<style id=\"1\" tts:backgroundColor=\"black\" tts:fontFamily=\"Arial\" tts:fontSize=\"14\" tts:color=\"white\" tts:textAlign=\"center\" tts:fontStyle=\"Plain\" />\n\t\t</styling>\n\t</head>\n\t<body>\n\t<div xml:lang=\"en\" style=\"default\">\n\t\t<div xml:lang=\"en\">\n");
for (int i = 0; i < node_list.size(); i++) {
dfxp.append("\t\t\t<p begin=\"" + node_list.get(i).begin_time + "\" ")
.append("end=\"" + node_list.get(i).end_time
+ "\" style=\"1\">");
for (int k = 0; k < node_list.get(i).content.size(); k++) {
dfxp.append("" + node_list.get(i).content.get(k));
}
dfxp.append("</p>\n");
}
dfxp.append("\t\t</div>\n\t</body>\n</tt>\n");
return dfxp.toString();
}
private void writeXML(String dfxp) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(output_file));
out.write(dfxp);
out.close();
} catch (IOException e) {
System.out.println("Error Writing To File:"+ input_file +'\n');
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
if ((args.length < 2) || (args[1].equals("-h"))) {
System.out.println("\n<--- SRT to DFXP Converter Usage --->");
System.out
.println("Conversion: java -jar SRT_TO_DFXP.jar <input_file> <output_file> [-d]");
System.out
.println("Conversion REQUIRES a input file and output file");
System.out.println("[-d] Will Display XML Generated In Console");
System.out.println("Help: java -jar SRT_TO_DFXP.jar -h");
} else if (!(new File(args[0]).exists())) {
System.out.println("Error: Input SubScript File Does Not Exist\n");
} else {
SRT_TO_DFXP_Converter converter = new SRT_TO_DFXP_Converter(
new File(args[0]), new File(args[1]));
converter.readSRT();
String dfxp = converter.convertToXML();
if ((args.length == 3) && (args[2].equals("-d")))
System.out.println("\n" + dfxp + "\n");
converter.writeXML(dfxp);
System.out.println("Conversion Complete");
}
}
here's part of the srt file that it is throwing an error when exported and run as a jar file.
1
00:20:43,133 --> 00:20:50,599
literature and paper by Liversmith & Newman, and I think the point is well made that a host of factors
I am trying to create a typestate client program in java that speaks to the gimaps but I am having trouble getting it to login in. When I enter my details it sends back * BAD invalid tag. I presume this is something to do with the tag that I am sending. Here's the code then I'll explain more.
public class CMain {
static final String CRLF = "\r\n";
public static String safeRead(BufferedReader readerC) {
String readline = "";
try {
readline = readerC.readLine();
}
catch(IOException e) {
System.out.println("Input/Output error, unable to read");
System.exit(+1);
}
return readline;
}
public static void main(String[] args) {
CRole currentC = new CRole();
BufferedReader readerC = new BufferedReader(new InputStreamReader(System.in));
System.out.println("connecting: ");
String payload2 = currentC.receive_acceptedStringFromS();
System.out.println("Received from S: " + payload2);
//connected - now decide if you want to login
System.out.print("Choose a label among [LOGIN, QUIT]: ");
String label1 = safeRead(readerC).equals("LOGIN") ? "1" : "2";
switch(currentC.send_Choice1LabelToS(label1).getEnum()){
case Choice1.LOGIN:
System.out.print("Send to S: ");
//When i get here I enter username#gmail.com password
String payload3 = safeRead(readerC);
currentC.send_loginStringToS(payload3);
String response = currentC.receive_Choice2LabelFromS();
System.out.println("Server: " + response);
String payload4 = currentC.receive_OKStringFromS();
System.out.println("Received from S: " + payload4);
System.out.print("Choose a label among [INBOX, QUIT]: ");
String label2 = safeRead(readerC).equals("INBOX") ? "1" : "2";
switch(currentC.send_Choice3LabelToS(label2).getEnum()){
case Choice3.INBOX:
System.out.print("Send to S: ");
String payload5 = safeRead(readerC);
currentC.send_inboxStringToS(payload5);
break;
case Choice3.QUIT:
System.out.print("Send to S: ");
String payload6 = safeRead(readerC);
currentC.send_quitStringToS(payload6);
break;
}
break;
case Choice1.QUIT:
System.out.print("Send to S: ");
String payload8 = safeRead(readerC);
currentC.send_quitStringToS(payload8);
break;
}
}
}
public class CRole {
private BufferedReader socketSIn = null;
private PrintWriter socketSOut = null;
private Socket client;
public CRole(){
SSLSocketFactory sslsocketfactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
try {
client = (SSLSocket) sslsocketfactory.createSocket("imap.gmail.com", 993);
System.out.println("Connect to Host");
}
catch(IOException e) {
System.out.println("Unable to listen on ports");
System.exit(+1);
}
try {
socketSIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
socketSOut = new PrintWriter(client.getOutputStream(), true);
}
catch(IOException e) {
System.out.println("Read failed");
System.exit(+1);
}
}
public void send_connectStringToS(String payload) {
this.socketSOut.println(payload);
}
public String receive_acceptedStringFromS() {
String line = "";
try {
line = this.socketSIn.readLine();
}
catch(IOException e) {
System.out.println("Input/Outpur error.");
System.exit(+1);
}
return line;
}
public Choice1 send_Choice1LabelToS(String payload) {
this.socketSOut.println(payload);
int intLabelChoice1 = Integer.parseInt(payload);
//int intLabelChoice1 = 1;
switch(intLabelChoice1){
case 1:
return new Choice1(Choice1.LOGIN);
case 2:
default:
return new Choice1(Choice1.QUIT);
}
}
public void send_loginStringToS(String payload) {
this.socketSOut.println(payload);
}
public String receive_Choice2LabelFromS() {
String line = "";
try {
line = this.socketSIn.readLine();
}
catch(IOException e) {
System.out.println("Input/Outpur error.");
System.exit(+1);
}
return line;
}
public String receive_OKStringFromS() {
String line = "";
try {
line = this.socketSIn.readLine();
}
catch(IOException e) {
System.out.println("Input/Outpur error.");
System.exit(+1);
}
return line;
}
public Choice3 send_Choice3LabelToS(String payload) {
this.socketSOut.println(payload);
int intLabelChoice3 = Integer.parseInt(payload);
switch(intLabelChoice3){
case 1:
return new Choice3(Choice3.INBOX);
case 2:
default:
return new Choice3(Choice3.QUIT);
}
}
public void send_inboxStringToS(String payload) {
this.socketSOut.println(payload);
}
public void send_quitStringToS(String payload) {
this.socketSOut.println(payload);
}
public String receive_quitStringFromS() {
String line = "";
try {
line = this.socketSIn.readLine();
}
catch(IOException e) {
System.out.println("Input/Outpur error.");
System.exit(+1);
}
return line;
}
}
So is it a case of the string that I am sending gmail? I have sent the following strings: username#gmail.com password; a001 login username#gmail.com password; a001 username#gmail.com password; username#gmail.com, password. And I have had no luck with these.
Or is it something to do with OAuth?
I am not using javamail and do not wish to use it.
Thank you for your help
Problem semi fixed. I rewrote a simple program not using the typestating method of programming and this work so it is not sending an incorrect tag but there is something in the typestated code that is causing the problems.
I have server class which implements common interface between client and server. I have multiple remote objects bonded to different rim registry(diff ports and rim_id). Client will lookup the registry based on clientID for e.g. IF clientID is EXE1111 then it should connects to EXE server remote object. I want each server object to have its own hashtable to store data given by client. Here is server code::
enter code here
public class StationServers extends UnicastRemoteObject implements StationService{
private static final long serialVersionUID = 8119533223378875144L;
private String criminalRecordID="CR";
private String missingRecordID="MR";
private int count=11111;
protected StationServers() throws RemoteException {
super();
}
public static void main(String args[]){
try {
bindSPVMServer(new StationServers());
bindSPLServer(new StationServers());
bindSPBServer(new StationServers());
System.out.print("Servers are up and running on ");
System.out.println(InetAddress.getLocalHost().getHostName());
} catch (Exception e) {
System.err.println("Server start up error: "+e.getMessage());
e.printStackTrace();
}
}
private static void bindSPVMServer(StationServers spvmObject) {
try {
Registry reg = LocateRegistry.createRegistry(Constants.SPVM_RMI_PORT);
reg.bind(Constants.SPVM_RMI_ID, spvmObject);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void bindSPLServer(StationServers splObject) {
try {
Registry reg = LocateRegistry.createRegistry(Constants.SPL_RMI_PORT);
reg.bind(Constants.SPL_RMI_ID, splObject);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void bindSPBServer(StationServers spbObject) {
try {
Registry reg = LocateRegistry.createRegistry(Constants.SPB_RMI_PORT);
reg.bind(Constants.SPB_RMI_ID, spbObject);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void createCRecord(String firstName, String lastName,
String description, RecordStatus status) throws RemoteException {
}
#Override
public void createMRecord(String firstName, String lastName,
String address, String lastDate, String lastLocation,
RecordStatus status) throws RemoteException {
// TODO Auto-generated method stub
}
#Override
public String getRecordCounts() throws RemoteException {
// TODO Auto-generated method stub
return null;
}
#Override
public void editCRecord(String lastName, String recordID,
RecordStatus newStatus) throws RemoteException {
// TODO Auto-generated method stub
}
}
Client Code::
enter code here
public class OfficerClients implements Runnable{
public static void showMenu() {
System.out.println("\n****Welcome to DPIS****\n");
System.out.println("Please select an option (1-5)");
System.out.println("1. Create Criminal Record");
System.out.println("2. Create Missing Record");
System.out.println("3. Get Records Count");
System.out.println("4. Edit Record");
System.out.println("5. Exit");
}
public static void main(String[] args) {
try {
if (System.getSecurityManager() == null)
System.setSecurityManager(new RMISecurityManager());
new Thread(new OfficerClients()).start();
} catch (Exception e) {
e.printStackTrace();
}
}
private static RecordStatus getRecordStatus(String status, int userChoice) {
if (userChoice == 1) {
if (RecordStatus.CAPTURED.name().equals(status))
return RecordStatus.CAPTURED;
else if (RecordStatus.ONTHERUN.name().equals(status))
return RecordStatus.ONTHERUN;
else
throw new IllegalArgumentException("Invalid status for Criminal Record");
} else if (userChoice == 2) {
if (RecordStatus.FOUND.name().equals(status))
return RecordStatus.FOUND;
else if (RecordStatus.MISSING.name().equals(status))
return RecordStatus.MISSING;
else
throw new IllegalArgumentException("Invalid status for Missing Record");
} else if (userChoice == 3) {
if (RecordStatus.CAPTURED.name().equals(status))
return RecordStatus.CAPTURED;
else if (RecordStatus.ONTHERUN.name().equals(status))
return RecordStatus.ONTHERUN;
else if (RecordStatus.FOUND.name().equals(status))
return RecordStatus.FOUND;
else if (RecordStatus.MISSING.name().equals(status))
return RecordStatus.MISSING;
}
throw new IllegalArgumentException("No Enum specified for this string");
}
private static StationService getRemoteObjectStub(String stationName) {
String url = "rmi://localhost:";
Remote lookup = null;
try {
if ("SPVM".equals(stationName))
url += Constants.SPVM_RMI_PORT;
else if ("SPL".equals(stationName))
url += Constants.SPL_RMI_PORT;
else if ("SPB".equals(stationName))
url += Constants.SPB_RMI_PORT;
url += "/" + stationName;
System.out.println("URL==" + url);
if (url != null && !url.isEmpty())
lookup = Naming.lookup(url);
} catch (Exception e) {
e.printStackTrace();
}
return (StationService) lookup;
}
#Override
public void run() {
int userChoice = 0;
String firstName = "", lastName = "", description = "", address = "", lastDate = "", lastLocation = "", badgeID = "", recStatus = "", recordID = "";
RecordStatus status;
String requestBadgeID = "Please enter your unique BadgeID: ";
String requestRecordID = "Please enter RecordID: ";
String requestFName = "First Name: ";
String requestLName = "Last Name: ";
String requestDesc = "Description of Crime: ";
String requestAddress = "Last Known Address: ";
String requestDate = "Date last seen: ";
String requestPlace = "Place last seen: ";
String requestStatus = "Status: ";
String requestNewStatus = "New Status: ";
showMenu();
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
try{
while (true) {
Boolean valid = false;
System.out.print(requestBadgeID);
badgeID = br.readLine().toUpperCase();
System.out.println(badgeID);
String stationName = badgeID.replaceAll("[0-9]", "").trim();
System.out.println(stationName);
StationService server = getRemoteObjectStub(stationName);
while (!valid) {
try {
System.out.print("Enter your choice: ");
userChoice = Integer.parseInt(br.readLine());
valid = true;
} catch (Exception e) {
System.out
.println("Invalid Input, please enter an integer: ");
valid = false;
}
}
switch (userChoice) {
case 1:
System.out.print(requestFName);
firstName = br.readLine().trim().toUpperCase();
System.out.print(requestLName);
lastName = br.readLine().trim().toUpperCase();
System.out.print(requestDesc);
description = br.readLine().trim().toUpperCase();
System.out.print(requestStatus);
recStatus = br.readLine().trim().toUpperCase()
.replaceAll("\\s+", "");
status = getRecordStatus(recStatus, userChoice);
server.createCRecord(firstName, lastName, description,
status);
showMenu();
break;
case 2:
System.out.print(requestFName);
firstName = br.readLine().trim().toUpperCase();
System.out.print(requestLName);
lastName = br.readLine().trim().toUpperCase();
System.out.print(requestAddress);
address = br.readLine().trim().toUpperCase();
System.out.print(requestDate);
lastDate = br.readLine().trim().toUpperCase();
System.out.print(requestPlace);
lastLocation = br.readLine().trim().toUpperCase();
System.out.print(requestStatus);
recStatus = br.readLine().trim().toUpperCase()
.replaceAll("\\s+", "");
status = getRecordStatus(recStatus, userChoice);
server.createMRecord(firstName, lastName, requestAddress,
lastDate, lastLocation, status);
showMenu();
break;
case 3:
String recordCounts = server.getRecordCounts();
System.out.println(recordCounts);
showMenu();
break;
case 4:
System.out.print(requestLName);
lastName = br.readLine().trim().toUpperCase();
System.out.print(requestRecordID);
recordID = br.readLine().trim().toUpperCase();
System.out.print(requestNewStatus);
recStatus = br.readLine().trim().toUpperCase()
.replaceAll("\\s+", "");
status = getRecordStatus(recStatus, userChoice);
server.editCRecord(lastName, recordID, status);
showMenu();
break;
case 5:
System.out.println("Have a nice day!");
br.close();
System.exit(0);
default:
System.out.println("Invalid Input, please try again.");
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
I am new to RMI so I don't have any idea how to maintain each remote object and invoke based on client request and store records in hash table (per remote object).
please help...
You've described most of it yourself. Just create multiple instances of the remote object; bind each one into the Registry under a different name; have the client look up the appropriate name every time it wants that specific instance; and call the method via the stub that gets returned by that lookup.
Bingo.