Java create DKIM with jDKIM - java

Can you give me an example for create DKIM with jDKIM?
I don't see any example for this.
http://james.apache.org/jdkim/
Thanks!

Use: james-jdkim
Have a look at this code, This is the answer you are looking for:
lima here is the selector and domain is yahoogroups.com
PublicKeyRecordRetriever publicKeyRecordRetriever = new DNSPublicKeyRecordRetriever();
PublicKeyRecord keys = new DKIMVerifier()
.publicKeySelector(publicKeyRecordRetriever.getRecords("dns/txt", "lima", "yahoogroups.com"));
String signedMIME = "DKIM-Signature: a=rsa-sha256; b=xxxxxxxxxxxxxxxxxx; s=lima; d=yahoogroups.com; v=1; bh=xxxxxxxxx; h=from:to;"
+ "From: test#yahoogroups.com" + "To: test#yahoogroups.com" + "body";
try {
// Verify message against public key
new DKIMVerifier(publicKeyRecordRetriever).verify(new ByteArrayInputStream(signedMIME.getBytes()));
} catch (Exception e) {
throw e;
}

Have a look if this helps. I am also starting with jDKIM. I just wrote a method to list the signature records for the input message. Puzzled how to parse the signature records.
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.james.jdkim.DKIMVerifier;
import org.apache.james.jdkim.api.SignatureRecord;
import org.apache.james.jdkim.exceptions.FailException;
import org.apache.mailet.Mail;
import org.apache.mailet.Mailet;
public class AlgorithmDkimVerification {
public List<SignatureRecord> verifyDkim(InputStream messageStream)
{
DKIMVerifier verifier = new DKIMVerifier();
List<SignatureRecord> records = null;
try {
records = verifier.verify(messageStream);
} catch (IOException | FailException e) {
e.printStackTrace();
}
System.out.println(records);
return records;
}
}

Related

getSingleResult did not retrieve any entites - should be fixed (I think so) but it isn't

So I have this code in
PersoanaDao
public Optional<PersoanaEntity> get(String username) throws NoResultException {
return Optional.ofNullable(connection
.getEntityManager()
.createQuery("SELECT a FROM PersoanaEntity as a WHERE a.username = :username", PersoanaEntity.class)
.setParameter("username", username).getSingleResult()
);
}
and this code in ProcessInput
package socket;
import database.daos.PersoanaDao;
import database.models.PersoanaEntity;
import jakarta.persistence.NoResultException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Optional;
public class ProcessInput {
void processInput(JSONObject data, ObjectOutputStream out) {
switch (data.get("type").toString())
{
case "LOGIN_USER":
PersoanaDao persoanaDao = new PersoanaDao();
String username = data.get("username").toString();
Optional<PersoanaEntity> persoanaEntity = persoanaDao.get(username);
JSONObject json = new JSONObject();
if(persoanaEntity.isEmpty()) {
try {
json.put("status_code", "404");
out.writeObject(json.toString());
return;
}
catch(NoResultException noResultException) {
try {
json.put("status_code", "200");
out.writeObject(json.toString());
}
catch (IOException exception) {
System.out.println(exception);
}
}
catch(IOException exception) {
System.out.println(exception);
}
}
break;
}
}
}
Long story short, the method from PersoanaDao will be called in ProcessInput - but I get this exception:
Exception in thread "Thread-2" jakarta.persistence.NoResultException: getSingleResult() did not retrieve any entities.
and I don't understand why. I specified in the method that it throws NoResultException, and I caught it in my ProcessInput.
I think that this might happen because .getSingleResult is wrapped in that Optional clause - but I'm not really sure. If so, how can I fix my code?
Thanks.
It looks like your call to persoanaDao.get(username); is out of the try catch block that catches the NoResultException. Refactor your code so that call is in the correct try-catch.

calling a java class method in another class

Hi I have below Java Class for Sending Fax from Java
package oracle.apps.print;
import com.softlinx.replixfax.*;
import javax.xml.ws.*;
import org.apache.commons.codec.binary.Base64;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.io.File;
public class Fax {
public void SendFax(String Filepath, String faxno) {
try {
ReplixFaxService service = new ReplixFaxService();
ReplixFaxPort port = service.getReplixFaxPort();
((BindingProvider)port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "admin");
// ((BindingProvider) port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,"https://api.rpxfax.com/softlinx/replixfax/wsapi");
((BindingProvider)port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"https://api.rpxtest.com:9999/softlinx/replixfax/wsapi");
Authentication auth = new Authentication();
auth.setLogin("user");
String password = "pwd";
auth.setPassword(org.apache.commons.codec.binary.Base64.encodeBase64String(password.getBytes()));
auth.setRealm("MTBC");
auth.setPasswordSecurity("base64");
SendFaxInput sendFaxInput = new SendFaxInput();
sendFaxInput.setAuthentication(auth);
FaxRecipient recipient = new FaxRecipient();
recipient.setFaxNumber(faxno.toString());
Attachment attachment = new Attachment();
File f = new File(Filepath.toString());
attachment.setFileName(f.getName());
Path path = Paths.get(Filepath.toString());
byte[] data = Files.readAllBytes(path);
attachment.setAttachmentContent(data);
sendFaxInput.getFaxRecipient().add(recipient);
sendFaxInput.getAttachment().add(attachment);
SendFaxOutput result = port.sendFax(sendFaxInput);
System.out.println("Status Code= " + result.getRequestStatus().getStatusCode());
if (result.getFaxInfo() != null) {
System.out.println("Fax ID = " + result.getFaxInfo().get(0).getFaxId());
}
} catch (Exception ex) {
System.out.println("Exception: " + ex.getMessage());
}
}
}
I am compiling this class like this
javac -cp .;./commons-codec-1.10.jar Fax.java
However Compiling of both classes is fine no error at compile time
when i call the method Fax in another class (XXEmail) like this
package oracle.apps.print;
public class XXEmail implements JavaConcurrentProgram {
public static void main(String[] args) {
try {
Fax mtbcfax = new Fax();
mtbcfax.SendFax("E:\\csv_svb\\3010218.pdf", "173224xxxx");
out.writeln("Fax Sent Successfully");
} catch (Exception i) {
log.writeln("Error while Sending Fax " + i.getMessage(), LogFile.STATEMENT);
} finally {
log.writeln("Error while Sending Fax ");
}
}
}
It always goes to Finally block with out showing any error
How can i call this method so it should return with success code or exception
Try to:
Comment all lines in the SendFax function and add only a log:
public void SendFax(String Filepath, String faxno) {
out.writeln("No problem here");
}
Now start the program and see if the function is correctly called or not.
If It is correctly called, so probably the arguments you send are wrong.

How to read two XML files using XMLUnit

I am new to XML.After a lot of search i found XMLUnit to do that but the problem am getting is :
whenever i change the contents of xml file to simple string text and try to execute the code ,it still shows green in junit test which it should not do although it is throwing an exception but my requirement is the signal should be red even the files are not in proper xml format.Enclosing my work for so far.
package mypack;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLTestCase;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Test;
import org.xml.sax.SAXException;
public class MyXMLTestCase extends XMLTestCase {
enter code here
#Test
public void testMyXmlTestCase() {
FileReader expected = null;
FileReader output = null;
try {
expected = new FileReader("D:/vivek.xml");
output = new FileReader("D:/rahul.xml");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
XMLUnit.setNormalizeWhitespace(Boolean.TRUE);
try {
Diff diff = new Diff(expected,output);
// assertTrue("XMLSimilar"+diff.toString(),diff.similar());
//assertTrue("XMLIdentical"+diff.toString(),diff.identical());
DetailedDiff mydiff = new DetailedDiff(diff);
List allDifferences = mydiff.getAllDifferences();
assertEquals(mydiff.toString(), 0, allDifferences.size());
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

adding value on treeset

ı read text. my text is like that
AYSE;SERDAR-9.8;EMRE-5.2;AYTAC-3.3
FATMA;OYTUN-8.8;ORKUN-7.5;ONUR-5.4;UMUT-4.4;BERK-3.3;CAN-3.2
DERYA;VELI-7.7;ALI-6.5;SUAT-6.0;YAVUZ-5.0;OYTUN-4.2;ORKUN-3.1
DILARA;DOGUS-8.8;VELI-7.4;ALI-6.5;SUAT-5.5;YAVUZ-3.1
BEGUM;SUAT-6.6;YAVUZ-5.1;OYTUN-4.3;ORKUN-4.0
BERIL;CANER-8.7;DOGUS-7.5;VELI-6.2;ALI-6.1;SUAT-5.8;YAVUZ-4.8;OYTUN-4.0
FUNDA;ORKUN-9.7;ONUR-8.3;UMUT-7.2;BERK-6.5;CAN-5.5
ISIL;AYTAC-8.3;CANER-7.4;DOGUS-6.5;VELI-5.5;ALI-5.4;SUAT-4.4;YAVUZ-4.0;OYTUN-3.9;ORKUN-3.5;ONUR-3.4;UMUT-3.2;BERK-3.1;CAN-3.0
ELIF;EMRE-7.4;AYTAC-6.1
ı cant add "u.eleman" and "u.uyum" values to "treeset tSU". it gives memory address when ı do syso ı cant see them in the tSU TREESET. I want to add all of them to treeset. How can ı do that.. please help
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.TreeSet;
public class Rapor {
static class Uyum implements Comparable<Uyum> {
String eleman;
Double uyum;
public int compareTo(Uyum u) {
if (uyum < u.uyum)
return -1;
if (uyum > u.uyum)
return 1;
return 0;
}
}
public static void main(String[] args) {
FileInputStream fIS;
try {
fIS = new FileInputStream("C:\\deneme\\rapor.txt");
Reader r;
r = new InputStreamReader(fIS, "UTF-8");
BufferedReader bR = new BufferedReader(r);
String satır;
String[] point, p2;
while ((satır = bR.readLine()) != null) {
point = satır.split(";");
String kelime = point[0];
HashMap<String, TreeSet<Uyum>> uyumlar = new HashMap<String, TreeSet<Uyum>>();
TreeSet<Uyum> tSU = new TreeSet<Uyum>() ;
Uyum u ;
for (int i = 1; i < point.length; i++) {
p2=point[i].split("\\-");
u = new Uyum();
u.eleman = p2[0];//EMRE,AYTAC,..
u.uyum = Double.parseDouble(p2
[1]);//7.8,9.5
tSU.add(u);
}
uyumlar.put(kelime, tSU);
System.out.println(uyumlar);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}// main end
}// class end
it gives memory address when ı do syso ı cant see them in the tSU TREESET.
No, it does not print the memory address. It prints the class name, an # and the hash code for the object in hexadecimal - that's what Object.toString() does by default.
If you want your Uyum objects to be printed differently, then override the toString() method in your class Uyum.

How to read MP3 file tags

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

Categories