Hyperledger Fabric Java SDK Event Hub Exception when trying to initialize channel - java

I'm trying to use the Hyperledger Fabric Java SDK to invoke chaincode transactions but I'm getting the following error in channel.initialize():
Exception in thread "main" org.hyperledger.fabric.sdk.exception.TransactionException: org.hyperledger.fabric.sdk.exception.EventHubException: org.hyperledger.fabric.sdk.exception.CryptoException: Could not sign the message using private key
at org.hyperledger.fabric.sdk.Channel.initialize(Channel.java:1158)
at HLFJavaClient.getChannel(HLFJavaClient.java:231)
at HLFJavaClient.main(HLFJavaClient.java:84)
Caused by: org.hyperledger.fabric.sdk.exception.EventHubException: org.hyperledger.fabric.sdk.exception.CryptoException: Could not sign the message using private key
at org.hyperledger.fabric.sdk.EventHub.connect(EventHub.java:322)
at org.hyperledger.fabric.sdk.EventHub.connect(EventHub.java:200)
at org.hyperledger.fabric.sdk.Channel.initialize(Channel.java:1127)
... 2 more
Caused by: org.hyperledger.fabric.sdk.exception.CryptoException: Could not sign the message using private key
at org.hyperledger.fabric.sdk.security.CryptoPrimitives.ecdsaSignToBytes(CryptoPrimitives.java:747)
at org.hyperledger.fabric.sdk.security.CryptoPrimitives.sign(CryptoPrimitives.java:757)
at org.hyperledger.fabric.sdk.identity.X509SigningIdentity.sign(X509SigningIdentity.java:23)
at org.hyperledger.fabric.sdk.transaction.TransactionContext.sign(TransactionContext.java:180)
at org.hyperledger.fabric.sdk.transaction.TransactionContext.signByteString(TransactionContext.java:184)
at org.hyperledger.fabric.sdk.EventHub.blockListen(EventHub.java:389)
at org.hyperledger.fabric.sdk.EventHub.connect(EventHub.java:320)
... 4 more
Caused by: java.security.InvalidKeyException: cannot identify EC private key: java.lang.NullPointerException
at org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil.generatePrivateKeyParameter(Unknown Source)
at org.bouncycastle.jcajce.provider.asymmetric.ec.SignatureSpi.engineInitSign(Unknown Source)
at java.security.Signature$Delegate.engineInitSign(Signature.java:1177)
at java.security.Signature.initSign(Signature.java:530)
at org.hyperledger.fabric.sdk.security.CryptoPrimitives.ecdsaSignToBytes(CryptoPrimitives.java:729)
... 10 more
My network is running with 4 peers (peer0.org1.mydomain.com, peer0.org2..., peer0.org3... and peer0.org4...) and one orderer (orderer.mydomain.com).
Java SDK Client code:
public class HLFJavaClient {
public static final String HLF_USER_NAME = "User1#org1.mydomain.com";
public static final String HLF_CLIENT_ORG = "Org1";
public static final String HLF_CLIENT_MSPID = "Org1MSP";
public static final String HLF_CLIENT_CRT_PATH = "../crypto-config/peerOrganizations/org1.mydomain.com/users/User1#org1.mydomain.com/msp/signcerts/User1#org1.mydomain.com-cert.pem";
public static final String HLF_CLIENT_KEY_PATH = "../crypto-config/peerOrganizations/org1.mydomain.com/users/User1#org1.mydomain.com/msp/keystore/User1#org1.mydomain.com-priv.pem";
public static final String HLF_CHANNEL_NAME = "mychannel";
public static final String HLF_CHAINCODE_NAME = "pkicc";
private static final Logger log = Logger.getLogger(HLFJavaClient.class);
public static void main(String[] args) throws Exception {
AppUser appUser = getUser(HLF_CLIENT_CRT_PATH, HLF_CLIENT_KEY_PATH, HLF_USER_NAME);
HFClient client = getHfClient();
client.setUserContext(appUser);
Channel channel = getChannel(client);
addProperty(client, new String[] {"1","w"});
}
static void addProperty(HFClient client, String[] property) throws ProposalException, InvalidArgumentException {
Channel channel = client.getChannel(HLF_CHANNEL_NAME);
TransactionProposalRequest tpr = client.newTransactionProposalRequest();
ChaincodeID CCId = ChaincodeID.newBuilder().setName(HLF_CHAINCODE_NAME).build();
tpr.setChaincodeID(CCId);
tpr.setFcn("createWallet");
tpr.setArgs(property);
Collection<ProposalResponse> res = channel.sendTransactionProposal(tpr);
for (ProposalResponse pres : res) {
String stringResponse = "Response from endorser is: " + pres.getChaincodeActionResponseStatus();
log.info(stringResponse);
System.out.println(stringResponse);
}
channel.sendTransaction(res);
System.out.println("Transaction sent.");
}
static Channel getChannel(HFClient client) throws InvalidArgumentException, TransactionException {
Channel channel = client.newChannel(HLF_CHANNEL_NAME);
class PeerOrgPort {
public String org;
public int port;
public PeerOrgPort(String org, int port) {
this.org = org;
this.port = port;
}
}
PeerOrgPort[] peers = new PeerOrgPort[] {
new PeerOrgPort("1", 7051),
new PeerOrgPort("2", 8051),
new PeerOrgPort("3", 9051),
new PeerOrgPort("4", 10051),
};
for (int i = 0; i < peers.length; i++) {
File tlsCrt = Paths.get("../crypto-config/peerOrganizations/org" + peers[i].org + ".mydomain.com/tlsca", "tlsca.org" + peers[i].org + ".mydomain.com-cert.pem").toFile();
if (!tlsCrt.exists())
throw new RuntimeException("Missing TLS cert files");
Properties secPeerProperties = new Properties();
secPeerProperties.setProperty("hostnameOverride", "peer0.org" + peers[i].org + ".mydomain.com");
secPeerProperties.setProperty("sslProvider", "openSSL");
secPeerProperties.setProperty("negotiationType", "TLS");
secPeerProperties.setProperty("pemFile", tlsCrt.getAbsolutePath());
Peer peer = client.newPeer("peer0.org" + peers[i].org + ".mydomain.com", "grpcs://localhost:" + peers[i].port, secPeerProperties);
channel.addPeer(peer);
if (peers[i].org.equals("1")) {
EventHub eventHub = client.newEventHub("eventhub01", "grpcs://localhost:7053", secPeerProperties);
channel.addEventHub(eventHub);
}
}
File tlsOrdCrt = Paths.get("../crypto-config/ordererOrganizations/mydomain.com/tlsca", "tlsca.mydomain.com-cert.pem").toFile();
if (!tlsOrdCrt.exists())
throw new RuntimeException("Missing TLS cert files");
Properties secOrdererProperties = new Properties();
secOrdererProperties.setProperty("hostnameOverride", "orderer.mydomain.com");
secOrdererProperties.setProperty("sslProvider", "openSSL");
secOrdererProperties.setProperty("negotiationType", "TLS");
secOrdererProperties.setProperty("pemFile", tlsOrdCrt.getAbsolutePath());
Orderer orderer = client.newOrderer("orderer.mydomain.com", "grpcs://localhost:7050", secOrdererProperties);
channel.addOrderer(orderer);
channel.initialize();
return channel;
}
static HFClient getHfClient() throws Exception {
CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
HFClient client = HFClient.createNewInstance();
client.setCryptoSuite(cryptoSuite);
return client;
}
static AppUser getUser(String certPath, String keyPath, String userId) throws Exception {
AppUser appUser = null;//tryDeserialize(userId);
if (appUser == null) {
appUser = new AppUser(userId, HLF_CLIENT_ORG, HLF_CLIENT_MSPID, certPath, keyPath);
}
return appUser;
}
AppUser:
public class AppUser implements User, Serializable {
private static final long serializationId = 1L;
private static final long serialVersionUID = -6287264119837208213L;
private String name;
private Set<String> roles;
private String account;
private String affiliation;
private Enrollment enrollment;
private String mspId;
public AppUser() {
// no-arg constructor
}
public AppUser(String name, String affiliation, String mspId, String certPath, String keyPath) {
this.name = name;
this.affiliation = affiliation;
this.enrollment = getEnrollmentFromCertPath(certPath, keyPath);
this.mspId = mspId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<String> getRoles() {
return roles;
}
public void setRoles(Set<String> roles) {
this.roles = roles;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getAffiliation() {
return affiliation;
}
public void setAffiliation(String affiliation) {
this.affiliation = affiliation;
}
public Enrollment getEnrollment() {
return enrollment;
}
public void setEnrollment(Enrollment enrollment) {
this.enrollment = enrollment;
}
public String getMspId() {
return mspId;
}
public void setMspId(String mspId) {
this.mspId = mspId;
}
#Override
public String toString() {
return "AppUser{" +
"name='" + name + '\'' +
"\n, roles=" + roles +
"\n, account='" + account + '\'' +
"\n, affiliation='" + affiliation + '\'' +
"\n, enrollment=" + enrollment +
"\n, mspId='" + mspId + '\'' +
'}';
}
private Enrollment getEnrollmentFromCertPath(final String certPath, final String keyPath) {
return new Enrollment() {
public PrivateKey getKey() {
try {
return loadPrivateKey(Paths.get(keyPath));
} catch (Exception e) {
return null;
}
}
public String getCert() {
try {
return new String(Files.readAllBytes(Paths.get(certPath)));
} catch (Exception e) {
return "";
}
}
};
}
private static PrivateKey loadPrivateKey(Path fileName) throws IOException, GeneralSecurityException {
PrivateKey key = null;
InputStream is = null;
BufferedReader br = null;
try {
is = new FileInputStream(fileName.toString());
br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
boolean inKey = false;
for (String line = br.readLine(); line != null; line = br.readLine()) {
if (!inKey) {
if (line.startsWith("-----BEGIN ") && line.endsWith(" PRIVATE KEY-----")) {
inKey = true;
}
continue;
} else {
if (line.startsWith("-----END ") && line.endsWith(" PRIVATE KEY-----")) {
inKey = false;
break;
}
builder.append(line);
}
}
byte[] encoded = DatatypeConverter.parseBase64Binary(builder.toString());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance("ECDSA", "BC");
key = kf.generatePrivate(keySpec);
} finally {
br.close();
is.close();
}
return key;
}
}
What am I doing wrong?
Thank you

Related

How to upload a new version of a file by using WebScript?

I have a simple Spring application (front-end application) that loads files into the Alfresco repository. If the file already exists, its new version is not created.
Repository web script is presented below:
public class CustomFileUploader extends DeclarativeWebScript {
private static final String FIRM_DOC =
"{http://www.firm.com/model/content/1.0}someDoc";
private static final String FIRM_DOC_FOLDER =
"workspace://SpacesStore/8caf07c3-6aa9-4a41-bd63-404cb3e3ef0f";
private FirmFile firmFile;
private FileFolderService fileFolderService;
private ContentService contentService;
protected Map<String, Object> executeImpl(WebScriptRequest req,
Status status) {
retrievePostRequestParams(req);
writeContent();
return null;
}
private void retrievePostRequestParams(WebScriptRequest req) {
FormData formData = (FormData) req.parseContent();
FormData.FormField[] fields = formData.getFields();
for(FormData.FormField field : fields) {
String fieldName = field.getName();
String fieldValue = field.getValue();
if(fieldName.equalsIgnoreCase("firm_file")
&& field.getIsFile()) {
String fileName = field.getFilename();
Content fileContent = field.getContent();
String fileMimetype = field.getMimetype();
firmFile = new FirmFile(fileName, fileContent,
fileMimetype, FIRM_DOC);
}
}
}
private void writeContent() {
try {
NodeRef parentNodeRef = new NodeRef(FIRM_DOC_FOLDER);
NodeRef fileNodeRef = createFileNode(parentNodeRef,
firmFile.getFileName());
ContentWriter contentWriter = contentService.getWriter(fileNodeRef,
ContentModel.PROP_CONTENT, true);
contentWriter.setMimetype(firmFile.getFileMimetype());
contentWriter.putContent(firmFile.getFileContent().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
private NodeRef createFileNode(NodeRef parentNode, String fileName) {
try {
QName contentQName = QName.createQName(FIRM_DOC);
FileInfo fileInfo = fileFolderService.create(parentNode,
fileName, contentQName);
return fileInfo.getNodeRef();
} catch (Exception e) {
e.printStackTrace();
}
}
public FileFolderService getFileFolderService() {
return fileFolderService;
}
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
public ContentService getContentService() {
return contentService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
}
How to create a new version of a file with the same name by using Java-backed WebScript?
Does this solution correct?
Check if the file exists by using Lucene search: TYPE:"firm:doc" AND #cm\:name:contract.png; (for example) If exists, increment the property cm:versionLabel and create a new version of Node with all the properties (Actually, need to iterate through all the ResultSet and find NodeRef with max value of cm:versionLabel then increment it and create a new Node). Is there more elegant solution?
The solution can be represented as follows:
public class CustomFileUploader extends DeclarativeWebScript {
private static final String FIRM_DOC = "{http://www.firm.com/model/content/1.0}doc";
private static final String FIRM_DOC_FOLDER = "workspace://SpacesStore/8caf07c3-6aa9-4a41-bd63-404cb3e3ef0f";
private FileFolderService fileFolderService;
private ContentService contentService;
private NodeService nodeService;
private SearchService searchService;
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
processUpload(req);
return null;
}
private void writeContent(NodeRef node, FirmFile firmFile) {
try {
ContentWriter contentWriter = contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
contentWriter.setMimetype(firmFile.getFileMimetype());
contentWriter.putContent(firmFile.getFileContent().getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
private NodeRef checkIfNodeExists(String fileName) {
StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
ResultSet resultSet = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE/*LANGUAGE_FTS_ALFRESCO*/,
"TYPE:\"firm:doc\" AND #cm\\:name:" + fileName.replaceAll(" ", "\\ ")+ "");
int len = resultSet.length();
if(len == 0) {
return null;
}
NodeRef node = resultSet.getNodeRef(0);
return node;
}
private NodeRef createNewNode(FirmFile firmFile) {
NodeRef parent = new NodeRef(FIRM_DOC_FOLDER);
NodeRef node = createFileNode(parent, firmFile.getFileName());
return node;
}
private void processUpload(WebScriptRequest req) {
FormData formData = (FormData) req.parseContent();
FormData.FormField[] fields = formData.getFields();
for(FormData.FormField field : fields) {
String fieldName = field.getName();
if(fieldName.equalsIgnoreCase("firm_file") && field.getIsFile()) {
String fileName = field.getFilename();
Content fileContent = field.getContent();
String fileMimetype = field.getMimetype();
NodeRef node = checkIfNodeExists(fileName);
// POJO
FirmFile firm = new FirmFile(fileName, fileContent, fileMimetype, FIRM_DOC);
if(node == null) {
node = createNewNode(firmFile);
}
writeContent(node, firmFile);
}
}
}
private NodeRef createFileNode(NodeRef parentNode, String fileName) {
try {
QName contentQName = QName.createQName(FIRM_DOC);
FileInfo fileInfo = fileFolderService.create(parentNode, fileName, contentQName);
return fileInfo.getNodeRef();
} catch (Exception e) {
e.printStackTrace();
}
}
public FileFolderService getFileFolderService() {
return fileFolderService;
}
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
public ContentService getContentService() {
return contentService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
public NodeService getNodeService() {
return nodeService;
}
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public SearchService getSearchService() {
return searchService;
}
public void setSearchService(SearchService searchService) {
this.searchService = searchService;
}
}
The content model must have a mandatory aspect cm:versionable:
<mandatory-aspects>
<aspect>cm:versionable</aspect>
</mandatory-aspects>

Apache Camel pool on email doesn't return attachments

This is my first post and english is not my native language, so please don't be cruel.
As i explained in the title I have a program that poll my mail with Apache Camel, and if there's a csv file in the attachments the program take it and process it. When i take the attachments from the email the method exchange.getIn().getAttachments() return an empty container, but I am pretty sure that the email is beeing readed. I am almost sure that I am not doing something regargins SSL but I don't really know what to do.
I am using Java OSGI with annotations and this bundles included:
org.apache.camel.camel-core 2.15.6
org.apache.camel.camel-mail 2.15.6
com.sun.mail.imap 1.6.0
com.sun.mail.javax.mail 1.6.0
javax.mail.api 1.6.0
The source code is on GitHub. Interesting classes are listed below:
ConfigReaderFactory take the email informations via ConfigAdmin and build the url.
#org.osgi.service.component.annotations.Component(name = "factory", property = "service.pid=it.sensorsystem.core.config.factory", configurationPolicy = ConfigurationPolicy.IGNORE)
public class ConfigReaderFactory implements ManagedServiceFactory {
private static final String DELETE_CONDITIONS = "readLock=changed&idempotent=false&noop=true&delete=true";
private static final String NON_DELETE_CONDITIONS = "noop=true";
private volatile DependencyManager dependencyManager;
private final Map<String, Component> components = new HashMap<>();
private String url;
private String name;
private int confLine;
private String endpointType;
private String ip;
private String username;
private String password;
private String folder;
private boolean delete;
private CamelService camel;
private TypeConverter converter;
private EventPublisher publisher;
private Double latitude;
private Double longitude;
private String email;
#Reference(service = TypeConverter.class)
public void setTypeConverter(TypeConverter converter) {
this.converter = converter;
}
public void unsetTypeConverter(TypeConverter converter) {
this.converter = null;
}
#Reference(service = EventPublisher.class)
public void setEventPublisher(EventPublisher publisher) {
this.publisher = publisher;
}
public void unsetEventPublisher(EventPublisher publisher) {
this.publisher = null;
}
#Reference(service = CamelService.class)
public void setCamelService(CamelService camel) {
this.camel = camel;
}
public void unsetCamelService(CamelService camel) {
this.camel = null;
}
#Override
public String getName() {
return this.getClass().getName();
}
#Override
public void updated(String pid, #SuppressWarnings("rawtypes") Dictionary props) throws ConfigurationException {
if (components.containsKey(pid)) {
return;
}
if (props != null) {
List<String> attributes = new ArrayList<>();
List<String> csvTypes = new ArrayList<>();
int count = 1;
String configurationLine;
while ((configurationLine = (String) props.get(Integer.toString(count++))) != null) {
List<String> values = Utils.getValuesFromLine(configurationLine);
attributes.add(values.size() >= 1 ? values.get(0) : TypeConverter.NAMELESS);
csvTypes.add(values.size() >= 2 ? values.get(1) : TypeConverter.NAMELESS);
}
confLine = Integer.parseInt((String) props.get(Config.CONFIG_LINE));
name = (String) props.get(Config.NAME);
initConfigParameters(props);
buildURL();
System.out.println("[URL] " + url);
try {
Map<String, Object> params = new HashMap<>();
params.put(Constants.ATTRIBUTES, attributes);
params.put(Constants.TYPES, csvTypes);
params.put(Constants.CONF_LINE, confLine);
params.put(Constants.SOURCE, name);
params.put(Constants.PUBLISHER, publisher);
params.put(Constants.CONVERTER, converter);
params.put(Constants.LATITUDE, latitude);
params.put(Constants.LONGITUDE, longitude);
params.put(Constants.ENDPOINT_TYPE, endpointType);
params.put(Constants.EMAIL, email);
Processor processor = new CSVProcessor(params);
camel.start(FrameworkUtil.getBundle(this.getClass()).getBundleContext(), processor, url);
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void deleted(String pid) {
Component component = components.remove(pid);
dependencyManager.remove(component);
component.stop();
}
private void buildURL() {
url = "";
switch(endpointType) {
case Constants.FTP:
url += "ftp://" + username + "#" + ip + "/" + folder + "?";
if(!password.equals("")) {
url += "password=" + password + "&";
}
break;
case Constants.FILE:
url += "file://" + folder + "?";
break;
case Constants.EMAIL:
url += "imaps://imap.gmail.com?username="+email+"&password="+password
+"&delete=false&unseen=false&consumer.delay=100";
}
if(endpointType.equals(Constants.FTP) || endpointType.equals(Constants.FILE)) {
if (delete) {
url += DELETE_CONDITIONS;
} else {
url += NON_DELETE_CONDITIONS;
}
}
}
private void initConfigParameters(#SuppressWarnings("rawtypes") Dictionary props) {
confLine = Integer.parseInt((String) props.get(Config.CONFIG_LINE));
name = (String) props.get(Config.NAME);
endpointType = (String) props.get(Config.ENDPOINT_TYPE);
ip = (String) props.get(Config.IP_ADDRESS);
username = (String) props.get(Config.USERNAME);
password = (String) props.get(Config.PASSWORD);
folder = (String) props.get(Config.FOLDER);
email = (String) props.get(Config.EMAIL);
delete = ((String) props.get(Config.DELETE)).equals("true");
if((String) props.get(Config.LATITUDE)!=null) {
latitude = Double.parseDouble((String) props.get(Config.LATITUDE));
}
if((String) props.get(Config.LONGITUDE)!=null) {
longitude = Double.parseDouble((String) props.get(Config.LONGITUDE));
}
printParameters();
}
private void printParameters() {
System.out.println("\nStarting camel with parameters:");
System.out.println("[sensor_name]::" + name);
System.out.println("[latitude]::" + latitude);
System.out.println("[longitude]::" + longitude);
System.out.println("[endpoint_type]::" + endpointType);
if(endpointType.equals("ftp")) {
System.out.println("[ip_address]::" + ip);
System.out.println("[folder]::" + folder);
System.out.println("[user]::" + username);
System.out.println("[password]::" + password);
} else if(endpointType.equals("file")) {
System.out.println("[folder]::" + folder);
} else if(endpointType.equals("email")) {
System.out.println("[email]::" + email);
System.out.println("[password]::" + password);
}
System.out.println("[delete]::" + delete);
}
}
CSVProcessor take the attachments from the email and process the .csv files.
public class CSVProcessor implements Processor{
private List<String> attributes;
private List<String> csvTypes;
private int confLine;
private String source;
private String endpointType;
private TypeConverter converter;
private EventPublisher publisher;
private Long timestamp;
private Double latitude;
private Double longitude;
#SuppressWarnings("unchecked")
public CSVProcessor(Map<String, Object> params) {
this.attributes = (List<String>) params.get(Constants.ATTRIBUTES);
this.csvTypes = (List<String>) params.get(Constants.TYPES);
this.confLine = (int) params.get(Constants.CONF_LINE);
this.source = (String) params.get(Constants.SOURCE);
this.publisher = (EventPublisher) params.get(Constants.PUBLISHER);
this.converter = (TypeConverter) params.get(Constants.CONVERTER);
this.latitude = (Double) params.get(Constants.LATITUDE);
this.longitude = (Double) params.get(Constants.LONGITUDE);
this.endpointType = (String) params.get(Constants.ENDPOINT_TYPE);
}
#Override
public void process(Exchange exchange) throws Exception {
if(endpointType.equals(Constants.EMAIL)) {
Map<String, DataHandler> attachments = exchange.getIn().getAttachments();
System.out.println("Detected email [attachments: "+exchange.getIn().getAttachments().size()+"]");
System.out.println("[BODY]\n"+exchange.getIn().getBody(String.class));
if(exchange.getIn().hasAttachments()) {
System.out.println("Detected email attachments: "+attachments);
for(String name : attachments.keySet()) {
DataHandler dh = attachments.get(name);
String filename = dh.getName();
System.out.println("Detected email attachment with name: "+filename);
if(filename.contains(".csv")) {
processBody(exchange.getContext().getTypeConverter()
.convertTo(String.class, dh.getInputStream()));
}
}
}
} else {
processBody(exchange.getIn().getBody(String.class));
}
}
private void processBody(String body) {
int count = 1;
for(String line : Utils.getLines(body)){
if(count++>confLine){
for(IOTEvent event: processLine(line)){
publisher.publish(event);
}
}
}
}
private boolean processTimeAndPosition(String line) {
Iterator<String> valueIterator = Utils.getValuesFromLine(line).iterator();
Iterator<String> attributeIterator = attributes.iterator();
Iterator<String> typeIterator = csvTypes.iterator();
boolean systemTimestamp = true;
while(attributeIterator.hasNext()){
String attribute = attributeIterator.next();
String type = typeIterator.next();
String value = valueIterator.next();
switch(attribute.toLowerCase()){
case Constants.TIMESTAMP:
systemTimestamp = false;
timestamp = (Long) converter.convert(type, value);
break;
case Constants.LATITUDE:
latitude = (Double) converter.convert(type, value);
break;
case Constants.LONGITUDE:
longitude = (Double) converter.convert(type, value);
break;
}
}
return systemTimestamp;
}
private List<IOTEvent> processLine(String line){
Iterator<String> valueIterator = Utils.getValuesFromLine(line).iterator();
Iterator<String> attributeIterator = attributes.iterator();
Iterator<String> typeIterator = csvTypes.iterator();
List<IOTEvent> IOTEvents = new ArrayList<>();
boolean systemTimestamp = processTimeAndPosition(line);
// Resetting iterators
valueIterator = Utils.getValuesFromLine(line).iterator();
attributeIterator = attributes.iterator();
typeIterator = csvTypes.iterator();
while(attributeIterator.hasNext()){
String attribute = attributeIterator.next();
String type = typeIterator.next();
String value = valueIterator.next();
switch(attribute.toLowerCase()){
case Constants.TIMESTAMP:
case Constants.LATITUDE:
case Constants.LONGITUDE:
continue;
}
IOTEvent iotEvent = new IOTEvent();
iotEvent.setSource(source);
iotEvent.setValue(new Value(type, converter.convert(type, value)));
if(systemTimestamp) {
iotEvent.setCdate(new Date());
} else {
iotEvent.setCdate(new Date(timestamp));
}
iotEvent.setType(attribute);
iotEvent.setSystemCDate(systemTimestamp);
if(latitude!=null && longitude!=null )
iotEvent.setPoint(new Point(latitude, longitude));
IOTEvents.add(iotEvent);
}
return IOTEvents;
}
}
DefaultCamelService starts camel:
#Component(immediate=true)
public class DefaultCamelService implements CamelService{
private CamelContext camelContext=null;
#Override
public void start(BundleContext context, Processor processor, String url) throws Exception {
if(camelContext==null) {
camelContext = new OsgiDefaultCamelContext(context);
}
camelContext.addRoutes(new RouteBuilder() {
public void configure() {
from(url).process(processor);
}
});
try {
camelContext.start();
} catch(Exception e) {
System.out.println("Error connecting to endpoint:"+url);
}
}
#Override
public void stop() throws Exception {
camelContext.stop();
}
}
This is the result on console that regards email:
Connecting to MailStore: imaps://imap.gmail.com:993 (SSL enabled), folder=INBOX
Getting folder INBOX
Polling mailbox folder: imaps://imap.gmail.com:993 (SSL enabled), folder=INBOX
Configured property: peek on bean: com.sun.mail.imap.IMAPMessage#6dd74603 with value: true
Fetching 1 messages. Total 1 messages.
Processing message: messageNumber=[1], from=[Simone Colaci <sim.colaci#gmail.com>], to=[sensorsystem.csv#gmail.com], subject=[csv testing], sentDate=[Sep 14, 2017 1:15:24 PM], receivedDate=[Sep 14, 2017 1:15:45 PM]
Detected email [attachments: 0]
Close mailbox folder INBOX from imaps://imap.gmail.com:993 (SSL enabled), folder=INBOX
Please help me, remember that this is my first post and english is not my native language. I checked everything on internet.
Thank you.
Edit 1:
This is the body of the email sent by my Gmail account to sensorsystem.csv#gmail.com:
[BODY]
--94eb2c19b976cd06bd055924656c
Content-Type: multipart/alternative; boundary="94eb2c19b976cd06ba055924656a"
--94eb2c19b976cd06ba055924656a
Content-Type: text/plain; charset="UTF-8"
Hi,
this is a csv file
--94eb2c19b976cd06ba055924656a
Content-Type: text/html; charset="UTF-8"
<div dir="ltr"><div>Hi,<br></div>this is a csv file<br><div><div><div class="gmail_quote"><br><div dir="ltr"><br></div>
</div><br></div></div></div>
--94eb2c19b976cd06ba055924656a--
--94eb2c19b976cd06bd055924656c
Content-Type: text/csv; charset="US-ASCII"; name="esrlNcepRe_LonPM180_e063_990c_26e6.csv"
Content-Disposition: attachment;
filename="esrlNcepRe_LonPM180_e063_990c_26e6.csv"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_j7kc6dcl0
dGltZSxsYXRpdHVkZSxsb25naXR1ZGUsYWlyLHByZXMKVVRDLGRlZ3JlZXNfbm9ydGgsZGVncmVl
c19lYXN0LGRlZ0ssUGFzY2FscwoyMDAyLTA3LTAxVDAwOjAwOjAwWiw0Mi41LC0xNDcuNSwyODcu
MSwxMDIyNzAuMAo=
--94eb2c19b976cd06bd055924656c--
Edit 2:
Tried with latest Camel libraries listed below but result is the same:
org.apache.camel.camel-core 2.19.3
org.apache.camel.camel-mail 2.19.3
Edit 3:
Debug also give this warnings from Java Mail:
Sep 18, 2017 10:20:59 AM javax.mail.Session loadResource
WARNING: expected resource not found: /META-INF/javamail.default.providers
Sep 18, 2017 10:20:59 AM javax.mail.Session loadResource
WARNING: expected resource not found: /META-INF/javamail.default.address.map

Get data from file - Buffered Reader

I would just have the id, the content and the hashtag and time of every tweet in a text file, and I dont know how to store infomration in lists of tweet,
I created a tweet class as follows:
public class Tweet {
private String type;
private String origin;
private String tweetText;
private String url;
private String tweetID;
private String tweetDate;
private int retCount;
private String favourit;
private String mEntities;
private String hashtags;
public Tweet(String tweetID,String origin) {
this.tweetID = tweetID;
this.origin = origin;
}
public Tweet(String type, String origin, String tweetText, String url, String tweetID, String tweetDate, int retCount, String favourit, String mEntities, String hashtags) {
this.type = type;
this.origin = origin;
this.tweetText = tweetText;
this.url = url;
this.tweetID = tweetID;
this.tweetDate = tweetDate;
this.retCount = retCount;
this.favourit = favourit;
this.mEntities = mEntities;
this.hashtags = hashtags;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public String getTweetText() {
return tweetText;
}
public void setTweetText(String tweetText) {
this.tweetText = tweetText;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTweetID() {
return tweetID;
}
public void setTweetID(String tweetID) {
this.tweetID = tweetID;
}
public String getTweetDate() {
return tweetDate;
}
public void setTweetDate(String tweetDate) {
this.tweetDate = tweetDate;
}
public int getRetCount() {
return retCount;
}
public void setRetCount(int retCount) {
this.retCount = retCount;
}
public String getFavourit() {
return favourit;
}
public void setFavourit(String favourit) {
this.favourit = favourit;
}
public String getmEntities() {
return mEntities;
}
public void setmEntities(String mEntities) {
this.mEntities = mEntities;
}
public String getHashtags() {
return hashtags;
}
public void setHashtags(String hashtags) {
this.hashtags = hashtags;
}
and my data file has the following format:
***
***
Type:status
Origin: Here's link to listen live to our discussion of #debtceiling #politics :
Text: Here's link to listen live to our discussion of :
URL:
ID: 96944336150867968
Time: Fri Jul 29 09:05:05 CDT 2011
RetCount: 0
Favorite: false
MentionedEntities:
Hashtags: debtceiling politics
***
***
Type:status
Origin: Now we're talking #debtceiling w/ Dick Polman #NewsWorksWHYY #PhillyInquirer & Bill Galston #BrookingsInst #NoLabelsOrg
Text: Now we're talking w/ Dick Polman & Bill Galston
URL:
ID: 96943803600089088
Time: Fri Jul 29 09:02:58 CDT 2011
RetCount: 1
Favorite: false
MentionedEntities: 136337303 151106990 14495726 15161791
Hashtags: debtceiling
***
***
I want to read this file and stock information into lists, i begin with this code, but i dont know how to solve that
public static List<String> readTweets(File file) throws IOException {
List<String> tweets = new ArrayList<String>();
//logger.info("Read tweets from {}", file.getAbsolutePath());
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
String[] fields;
while ((line = reader.readLine()) != null) {
fields = line.split(",");
if (fields.length > 1)
tweets.add(fields[1]);
}
return tweets;
}
By the looks of the code you are experimenting with, this is what I would do:
public static List<String> readTweets(File file) throws IOException {
List<String> tweets = new ArrayList<String>();
List<String> lines = Files.readAllLines(file.toPath());
for(int i = 0; i < lines.length(); i++){
String line = lines.get(i);
String[] part = line.split(",");
if(part.length < 1) tweets.add(part[i]);
}
}
But, if I wrote an application that was purely for printing the contents of tweets into the console, here's how I'd do it:
TweetReader.java
package Testers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
public class TweetReader {
public static List<Tweet> readTweets(File file) throws IOException {
boolean processEnd = false;
String type = "";
String origin = "";
String tweetText = "";
String url = "";
String tweetID = "";
String tweetDate = "";
int retCount = 0;
String favourite = "";
String mEntities = "";
String hashTags = "";
List<Tweet> tweets = new ArrayList<Tweet>();
List<String> lines = Files.readAllLines(file.toPath());
for(int i = 0; i < lines.size(); i++){
String line = lines.get(i);
line = line.trim();
if(line.equals("***")){
if(processEnd){
Tweet tweet = new Tweet(type, origin, tweetText, url, tweetID, tweetDate, retCount, favourite, mEntities, hashTags);
tweets.add(tweet);
processEnd = false;
}else processEnd = true;
}else{
if(line.contains(":")){
String header = line.substring(0, line.indexOf(":"));
//System.out.println(header); //You can uncomment this for troubleshooting
if(header.equals("Type")) type = line.substring(line.length() > 5 ? 5 : line.length());
else if(header.equals("Origin")) origin = line.substring(line.length() > 8 ? 8 : line.length());
else if(header.equals("Text")) tweetText = line.substring(line.length() > 6 ? 6 : line.length());
else if(header.equals("URL")) url = line.substring(line.length() > 5 ? 5 : line.length());
else if(header.equals("ID")) tweetID = line.substring(line.length() > 4 ? 4 : line.length());
else if(header.equals("Time")) tweetDate = line.substring(line.length() > 6 ? 6 : line.length());
else if(header.equals("RetCount")) retCount = Integer.parseInt(line.substring(line.length() > 10 ? 10 : line.length()));
else if(header.equals("Favorite")) favourite = line.substring(line.length() > 11 ? 11 : line.length());
else if(header.equals("MentionedEntities")) mEntities = line.substring(line.length() > 19 ? 19 : line.length());
else if(header.equals("Hashtags")) hashTags = line.substring(line.length() > 10 ? 10 : line.length());
else throw new IOException("Line cannot be identified as part of a tweet:" + line);
}else throw new IOException("Line cannot be processed:" + line);
}
}
return tweets;
}
public static void main(String[] args){
File log = new File("log.txt");
List<Tweet> tweets = new ArrayList<Tweet>();
try {
File f = new File(".").getAbsoluteFile();
File[] array = f.listFiles();
for(int i = 0; i < array.length; i++){
File tweet = array[i];
if(tweet.isFile() && !tweet.getName().contains("log.txt") && !tweet.getName().contains(".jar")){
log("Reading file: " + tweet.getAbsolutePath(), log);
List<Tweet> tweetlist = readTweets(tweet);
tweets.addAll(tweetlist);
}
}
System.out.println("Reading tweets now");
for(int i = 0; i < tweets.size(); i++){
Tweet t = tweets.get(i);
log("Type = " + t.getType(), log);
log("Origin = " + t.getOrigin(), log);
log("Text = " + t.getTweetText(), log);
log("URL = " + t.getURL(), log);
log("ID = " + t.getTweetID(), log);
log("Date = " + t.getTweetDate(), log);
log("Ret count = " + t.getRetCount(), log);
log("Favourite = " + t.getFavourite(), log);
log("Mentioned entities = " + t.getMentionedEntities(), log);
log("Hashtags = " + t.getHashtags(), log);
log("Tweet finished", log);
}
} catch (IOException e) {
log(e, log);
}
log("Finished reading tweets.", log);
}
private static void log(IOException e, File log) {
log(e.getMessage(), log);
StackTraceElement[] array = e.getStackTrace();
for(int i = 0; i < array.length; i++){
log(" " + array[i], log);
}
}
private static void log(String string, File log) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(log, true));
writer.write(string);
writer.newLine();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Tweet.java
package Testers;
public class Tweet {
private String type;
private String origin;
private String tweetText;
private String url;
private String tweetID;
private String tweetDate;
private int retCount;
private String favourit;
private String mEntities;
private String hashtags;
public Tweet(String tweetID,String origin) {
this.tweetID = tweetID;
this.origin = origin;
}
public Tweet(String type, String origin, String tweetText, String url, String tweetID, String tweetDate, int retCount, String favourit, String mEntities, String hashtags) {
this.type = type;
this.origin = origin;
this.tweetText = tweetText;
this.url = url;
this.tweetID = tweetID;
this.tweetDate = tweetDate;
this.retCount = retCount;
this.favourit = favourit;
this.mEntities = mEntities;
this.hashtags = hashtags;
}
public String getType() {
return type;
}
public String getOrigin(){
return origin;
}
public String getTweetText(){
return tweetText;
}
public String getURL(){
return url;
}
public String getTweetID(){
return tweetID;
}
public String getTweetDate(){
return tweetDate;
}
public int getRetCount(){
return retCount;
}
public String getFavourite(){
return favourit;
}
public String getMentionedEntities(){
return mEntities;
}
public String getHashtags(){
return hashtags;
}
}
//global attribute
List<Tweet> tweetList = new ArrayList<>();
String line = "";
String[] fields;
while (line != null) {
line = reader.readLine();
line = reader.readLine();
//these two are for ***
for(int i = 0;i<10;i++){
line = reader.readLine();
tweets.add(line);
// these are for the other data
}
Tweet tweet = createTweetFromList(tweets);
tweetList.add(tweet);
}

Design Pattern Command for Switch java

I want to use design pattern for this switch - case code.
I tried to use the command pattern, but I could not understand how(I was programming only 2 for months)
I wrote this program to learn how to better program.
My code:
public class Server {
private static final String READ_NEW_MESSAGES = "read new mes";
private static final String SEND_PRIVATE_MESSAGES = "send mes";
private static final String JOIN_CHAT = "find chat";
private static final String CREATE_CHAT = "chating";
private static final String QUIT = "quit";
private static final String EXIT = "exit";
private static final String REGISTRATION = "reg";
private static final String CREATE_PRIVATE_CHAT = "priv chat";
private static final String CONNECT_TO_PRIVATE_CHAT = "connect pm";
private static final String START_CHAT = "Start";
private Populator<PrivateMessage> privateMessagePopulator;
private Populator<Registration> registrationPopulator;
private Populator<Message> messagePopulator;
private Populator<PrivateChat> privateChatPopulator;
private Populator<Chat> publicChatPopulator;
private List<PrivateMessage> privateMessages;
private BufferedReader reader;
private String currentUser;
private Set<String> users;
private static Logger log = Logger.getLogger(Server.class.getName());
private List<Chat> chats;
private String password;
private Set<Registration> registration;
private List<PrivateChat> pmChat;
private String chatName;
public Server() {
server();
}
public void server() {
reader = new BufferedReader(new InputStreamReader(System.in));
privateMessages = new ArrayList<PrivateMessage>();
users = new HashSet<String>();
chats = new ArrayList<Chat>();
privateMessagePopulator = new PrivateMessagePopulator();
privateChatPopulator = new PrivateChatPopulator();
publicChatPopulator = new PublicChatPopulator();
messagePopulator = new MessagePopulator();
registrationPopulator = new RegistratorPopulator();
registration = new HashSet<Registration>();
pmChat = new ArrayList<PrivateChat>();
}
public void start() {
String decition = "";
while (true) {
try {
registrationOrLogin();
} catch (IOException e1) {
e1.printStackTrace();
}
while (decition != QUIT) {
System.out.println("Create a chat - chating");
System.out.println("Join the chat - find chat");
System.out.println("Send private message - send mes");
System.out.println("Read new messages - new mes");
System.out.println("Quit - quit");
System.out.println("Create private chat - priv chat");
System.out.println("Connect to private chat - connect pm");
try {
decition = reader.readLine();
switch (decition) {
case CREATE_PRIVATE_CHAT:
createPrivateChat();
break;
case CREATE_CHAT:
createChat();
break;
case JOIN_CHAT:
joinChat();
break;
case SEND_PRIVATE_MESSAGES:
sendPrivateMessage();
break;
case READ_NEW_MESSAGES:
showNewMessages();
break;
case QUIT:
logout();
break;
case REGISTRATION:
registration();
break;
case CONNECT_TO_PRIVATE_CHAT:
joinToPrivateChat();
break;
default:
break;
}
} catch (IOException e) {
log.warning("Error while reading decition from keyboard. "
+ e.getMessage());
}
}
}
}
private void sendPrivateMessage() throws IOException {
PrivateMessage privateMessage = privateMessagePopulator.populate();
privateMessage.setSenderName(currentUser);
privateMessages.add(privateMessage);
}
private void joinChat() throws IOException {
System.out.println("Exist public chat");
for (Chat chat : chats) {
System.out.println(chat.getChatName());
}
System.out.println("Enter the name of chat you wish to join");
chatName = reader.readLine();
for (Chat chat : chats) {
if (chatName.equals(chat.getChatName())) {
for (Message mes : chat.getMessages()) {
System.out.println(mes.getSenderName() + ": "
+ mes.getContent());
}
publicComunication(chat);
}
}
}
private boolean hasNewMessages() {
boolean result = false;
for (PrivateMessage privateMessage : privateMessages) {
if (currentUser.equals(privateMessage.getReceiverName())) {
result = true;
}
}
for (PrivateChat pm : pmChat) {
if (pm.getAddUserName().equals(currentUser)) {
result = true;
}
}
return result;
}
private void showNewMessages() {
if (hasNewMessages()) {
for (PrivateMessage privateMessage : privateMessages) {
if (currentUser.equals(privateMessage.getReceiverName())
&& MessageStatus.DIDNT_READ.equals(privateMessage
.getStatus())) {
System.out.println(privateMessage.getSenderName() + ": "
+ privateMessage.getContent());
}
privateMessage.setStatus(MessageStatus.ALREADY_READ);
}
}
if (hasNewMessages()) {
for (PrivateChat pm : pmChat) {
for (Message message : pm.getMessages()) {
if (pm.getAddUserName().equals(currentUser)) {
System.out.println(message.getSenderName() + ": "
+ message.getContent());
}
}
}
} else {
System.out.println("you don't have new message ");
}
}
private void registrationOrLogin() throws IOException {
String logOrReg;
System.out
.println("Hi,if you already have account - 1,\nIf you would like to register - 2");
logOrReg = reader.readLine();
if (logOrReg.equals("1")) {
login();
} else if (logOrReg.equals("2")) {
registration();
} else {
registrationOrLogin();
}
}
private boolean hasUser() {
boolean result = false;
for (Registration reg : registration) {
if (currentUser.equals(reg.getUserName())
&& password.equals(reg.getUserPassword())) {
result = true;
}
}
return result;
}
private void login() throws IOException {
System.out.println("Please,enter user name and password ");
currentUser = reader.readLine();
password = reader.readLine();
if (hasUser()) {
System.out.println("You already logged in system");
} else {
System.out.println("Wrong user name or password");
registrationOrLogin();
}
}
private void logout() throws IOException {
currentUser = null;
password = null;
registrationOrLogin();
}
private void createChat() throws IOException {
Chat chat = new Chat();
chat = publicChatPopulator.populate();
publicComunication(chat);
chats.add(chat);
}
private void joinToPrivateChat() throws IOException {
for (PrivateChat pm : pmChat) {
for (String user : pm.getUsers()) {
if (user.equals(currentUser)) {
System.out.println(pm.getChatName());
}
}
}
System.out.println("Enter the name of the chat you wish to join");
chatName = reader.readLine();
for (PrivateChat pm : pmChat) {
if (chatName.equals(pm.getChatName())) {
for (Message message : pm.getMessages()) {
System.out.println(message.getSenderName() + " "
+ message.getContent());
}
privateComunication(pm);
}
}
}
private void createPrivateChat() throws IOException {
PrivateChat privateChat = new PrivateChat();
Set<String> chatUsers = new HashSet<String>();
privateChat = privateChatPopulator.populate();
while (true) {
privateChat.setAddUserName(reader.readLine());
chatUsers.add(privateChat.getAddUserName());
privateChat.setUsers(chatUsers);
for (String user : users) {
if (user.equals(privateChat.getAddUserName())) {
System.out.println("you add too chat user - "
+ privateChat.getAddUserName());
}
}
if (privateChat.getAddUserName().equals(START_CHAT)) {
break;
}
}
privateComunication(privateChat);
pmChat.add(privateChat);
}
private void registration() throws IOException {
Registration reg = registrationPopulator.populate();
registration.add(reg);
currentUser = reg.getUserName();
users.add(reg.getUserName());
}
private void privateComunication(PrivateChat privateChat) {
while (true) {
Message message = messagePopulator.populate();
message.setSenderName(currentUser);
System.out.println(message.getSenderName());
System.out.println("\t" + message.getContent());
if (EXIT.equals(message.getContent())) {
break;
}
privateChat.setStatus(MessageStatus.DIDNT_READ);
privateChat.addMessage(message);
}
}
private void publicComunication(Chat chat) {
while (true) {
Message message = messagePopulator.populate();
message.setSenderName(currentUser);
System.out.println(message.getSenderName());
System.out.println("\t" + message.getContent());
if (EXIT.equals(message.getContent())) {
break;
}
chat.addMessage(message);
}
}
}
I never thought about improving the ugly process of creating shells; never used a switch, but a lot of if-elses, which is the same essentially.
package command.example;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CommandExample implements ApplicationContext {
private final Writer writer = new BufferedWriter(new OutputStreamWriter(
System.out));
private boolean quit = false;
private Map<String, Command> commands = new HashMap<>();
{
commands.put("create", new CreateChat(this));
commands.put("join", new JoinChat(this));
commands.put("exit", new ExitCommand(this));
}
public static void main(String[] args) throws Exception {
CommandExample example = new CommandExample();
example.run();
}
public void run() throws IOException {
try (Scanner s = new Scanner(System.in)) {
writer.write("> ");
writer.flush();
while (!quit && s.hasNextLine()) {
String input = s.nextLine().trim();
// get or default is java8, alternatively you could check for null
Command command = commands.getOrDefault(input, new UnknownCommand(this, input));
command.execute();
if (!quit)
writer.write("> ");
writer.flush();
}
}
}
#Override
public void shutdown() {
quit = true;
}
#Override
public Writer getWriter() {
return writer;
}
static interface Command {
public void execute() throws IOException;
}
static abstract class AbstractCommand implements Command {
protected final ApplicationContext context;
protected final Writer writer;
public AbstractCommand(ApplicationContext context) {
this.context = context;
this.writer = context.getWriter();
}
}
static class CreateChat extends AbstractCommand {
public CreateChat(ApplicationContext context) {
super(context);
}
#Override
public void execute() throws IOException {
writer.write(String.format("Successfully created a chat!%n"));
writer.flush();
}
}
static class JoinChat extends AbstractCommand {
public JoinChat(ApplicationContext context) {
super(context);
}
#Override
public void execute() throws IOException {
writer.write(String.format("Successfully joined chat!%n"));
writer.flush();
}
}
static class UnknownCommand extends AbstractCommand {
private final String command;
public UnknownCommand(ApplicationContext context, String command) {
super(context);
this.command = command;
}
#Override
public void execute() throws IOException {
writer.write(String.format("'%s' is not a supported command!%n",
command));
writer.flush();
}
}
static class ExitCommand extends AbstractCommand {
public ExitCommand(ApplicationContext context) {
super(context);
}
#Override
public void execute() throws IOException {
writer.write(String.format("Application is shutting down!%n"));
writer.flush();
context.shutdown();
}
}
};
interface ApplicationContext {
public void shutdown();
public Writer getWriter();
}
Here you have a little start. The Command implementations should not read their input (due to separation of concern), they should specify what they want and some kind of reader should provide it to them (cf. the approach with Writer).
Furthermore I'm asking myself how one would design the QuitProgram command - without using System.exit(0).

Java: Serializing beginner problem :-(

I want to save and store simple mail objects via serializing, but I get always an error and I can't find where it is.
package sotring;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import com.sun.org.apache.bcel.internal.generic.INEG;
public class storeing {
public static void storeMail(Message[] mail){
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("mail.ser"));
out.writeObject(mail);
out.flush();
out.close();
} catch (IOException e) {
}
}
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
for (int i=0; i< array.length;i++)
System.out.println("EMail von:"+ array[i].getSender() + " an " + array[i].getReceiver()+ " Emailbetreff: "+ array[i].getBetreff() + " Inhalt: " + array[i].getContent());
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
return null;
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User user1 = new User("User1", "geheim");
User user2 = new User("User2", "geheim");
Message email1 = new Message(user1.getName(), user2.getName(), "Test", "Fooobaaaar");
Message email2 = new Message(user1.getName(), user2.getName(), "Test2", "Woohoo");
Message email3 = new Message(user1.getName(), user2.getName(), "Test3", "Okay =) ");
Message [] mails = {email1, email2, email3};
storeMail(mails);
Message[] restored = getStoredMails();;
}
}
Here are the user and message class
public class Message implements Serializable{
static final long serialVersionUID = -1L;
private String receiver; //Empfänger
private String sender; //Absender
private String Betreff;
private String content;
private String timestamp;
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
Message (String receiver, String sender, String Betreff, String content) {
this.Betreff= Betreff;
this.receiver = receiver;
this.sender = sender;
this.content = content;
this.timestamp = getDateTime();
}
Message() { // Just for loaded msg
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getBetreff() {
return Betreff;
}
public void setBetreff(String betreff) {
Betreff = betreff;
}
public String getContent() {
return content;
}
public String getTime() {
return timestamp;
}
public void setContent(String content) {
this.content = content;
}
}
public class User implements Serializable{
static final long serialVersionUID = -1L;
private String username; //unique Username
private String ipadress; //changes everytime
private String password; //Password
private int unreadMsg; //Unread Messages
private static int usercount;
private boolean online;
public String getName(){
return username;
}
public boolean Status() {
return online;
}
public void setOnline() {
this.online = true;
}
public void setOffline() {
this.online = false;
}
User(String username,String password){
if (true){
this.username = username;
this.password = password;
usercount++;
} else System.out.print("Username not availiable");
}
public void changePassword(String newpassword){
password = newpassword;
}
public void setIP(String newip){
ipadress = newip;
}
public String getIP(){
if (ipadress.length() >= 7){
return ipadress;
} else return "ip address not set.";
}
public int getUnreadMsg() {
return unreadMsg;
}
}
Here is the exception:
exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type Message[]
at sotring.storeing.getStoredMails(storeing.java:22)
at sotring.storeing.main(storeing.java:57)
THANK YOU FOR YOUR HELP!!!!!!!!!!!
The catch clauses need to return something.
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null; //fix
}
If an exception occurs, you never get to the return statement in getStoredMails. You need to either throw the exception you catch (possibly wrapping it in another more descriptive exception) or just return null at the end of the method. It really depends on what you want to do if there's an error.
Oh, and your in.close() should be in a finally block. Otherwise, it is possible that you could read the data fine but then throw it away if you can't close the stream.
On a different note, have you considered a third-party serializer library?
I'm using Simple right now for a project, and it seems to do stuff just fine with very little effort.
in the exception handling blocks of the getStoredMails method you do not return anything.
Suggested modification:
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null;
}
I modified the source. I added "return null" in exception and the for loop the output in the function. And the function gives me the right output but then throws it the exception.

Categories

Resources