java.lang.AssertionError: Test failed wrong SSL DateFormat [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 days ago.
Improve this question
public class LoggerDateFormatterTest {
SSLPrintStream sslStream;
static String year = "(\\|\\d\\d\\d\\d-\\d\\d-\\d\\d";
static String hour = "\\s\\d\\d:\\d\\d:\\d\\d\\.\\d\\d\\d\\s";
static String zone = "([A-Za-z]+([\\+\\-][0-2]?[0-9](\\:[0-5]?[0-9]))?))";
static Pattern pattern;
Matcher matcher;
#BeforeTest
public void setUp() {
sslStream = new SSLPrintStream(System.err);
System.setErr(sslStream);
String format = year + hour + zone;
pattern = Pattern.compile(format);
}
#Test
public void testDateFormat() {
SSLLogger.info("logging");
System.out.println("The value is: " + sslStream.bos.toString());
matcher = pattern.matcher(sslStream.bos.toString());
if (matcher.find()) {
out.println("Test Passed with value :" + matcher.group());
}
else {
fail("Test failed wrong SSL DateFormat");
}
}
public static class SSLPrintStream extends PrintStream {
public ByteArrayOutputStream bos; // Stream that accumulates System.err
public SSLPrintStream(OutputStream out) {
super(out);
bos = new ByteArrayOutputStream();
}
#Override
public void write(int b) {
super.write(b);
bos.write(b);
}
#Override
public void write(byte[] buf, int off, int len) {
super.write(buf, off, len);
bos.write(buf, off, len);
}
#Override
public void write(byte[] buf) throws IOException {
super.write(buf);
bos.write(buf);
}
#Override
public void writeBytes(byte[] buf) {
super.writeBytes(buf);
bos.writeBytes(buf);
}
}
}
I am getting java.lang.AssertionError: Test failed wrong SSL DateFormat. How can I correct this? I am using Pattern Class - Defines a pattern (to be used in a search)
and Matcher Class - Used to search for the pattern.

Related

How to display all console massage in javaFX? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm new in java and wanted to add a TextArea on my JavaFX program and get the console messages displayed on it. Exactly like what you get when you start a jar file on white CMD (Exceptions, prints and etc...).
You can create your own implementation of OutputStream to do it:
public class TextInputForwardingOutputStream extends OutputStream {
private final TextInputControl control;
private final Charset charset;
public TextInputForwardingOutputStream(TextInputControl control) {
this(control, Charset.defaultCharset());
}
public TextInputForwardingOutputStream(TextInputControl control, Charset charset) {
this.control = control;
this.charset = charset;
}
#Override
public void write(int b) throws IOException {
write(new byte[]{(byte) b});
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
final String str = new String(b, off, len, this.charset);
Platform.runLater(() -> this.control.appendText(str));
}
}
and then forward the output to that OutputStream:
final TextArea myTextArea = new TextArea();
System.setOut(new PrintStream(new TextInputForwardingOutputStream(myTextArea)));
System.setErr(new PrintStream(new TextInputForwardingOutputStream(myTextArea)));

Replicating console functionality with a ListView

I apologize for not being able to think of a more descriptive title.
I have managed to redirect the system.out to a new ListView via my own OutputStream class Console:
public class Console extends OutputStream {
private ListView<String> output;
public Console(ListView<String> output) {
this.output = output;
}
private void addText(String str) {
Platform.runLater( () -> output.getItems().add(str) );
}
#Override
public void write(int b) throws IOException {
addText(String.valueOf((char) b));
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
addText(new String(b, off, len));
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
}
Here, I create the console in my controller class. output is the name of the
ListView in my FXML:
private void buildConsole() {
Console console = new Console(output);
PrintStream ps = new PrintStream(console, true);
System.setOut(ps);
System.setErr(ps);
}
Here is where I am testing the output with an event handler that prints the tile coordinates over which my mouse is hovering:
tile.setOnMouseEntered(e -> {
tile.setFill(hoverColor);
showConnections(tile);
gridController.getCoordinateLabel().setText(tile.getVertex().toString());
System.out.print("Tile " + tile.getVertex().toString() + " selected.");
});
Notice that I am using System.out.print() and not println(). This is the output:
If I were to use println():
My ideal behavior is:
system.out.print() - text to be added to the same line.
system.out.println() - text added to the next cell.
Since you are looking for behavior that corresponds to a system or IDE console, that corresponds, in part, to splitting the output into logical units (i.e. "lines") at newline characters. That would happen automatically if you just collected whatever is written and appended it to a text area, so I would encourage you to try that and see. Even if it turns out to be less efficient, it may still be plenty efficient for your purposes.
If you want to proceed with the ListView, however, then your Console class needs to internally buffer the data written to it, scan for newlines, and break up the output into cells at newlines. It create a new cell only when it sees a newline, and in that case include all the buffered text up to, but not including that newline.
Update:
A ByteArrayOutputStream would make a fine buffer. Something like this, for example:
public class Console extends OutputStream {
private ListView<String> output;
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
public Console(ListView<String> output) {
this.output = output;
}
private void addText() throws IOException {
String text = buffer.toString("UTF-8");
buffer.reset();
Platform.runLater( () -> output.getItems().add(text) );
}
#Override
public void write(int b) throws IOException {
if (b == '\n') {
addText();
} else {
buffer.write(b);
}
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
int bound = off + len;
for (int i = off; i < bound; i++) {
if (b[i] == '\n') {
buffer.write(b, off, i - off);
addText();
off = i + 1;
}
}
assert(off <= bound);
buffer.write(b, off, bound - off);
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
#Override
public void flush() throws IOException {
// outputs all currently buffered data as a new cell, without receiving
// a newline as otherwise is required for that
addText();
}
#Override
public void close() throws IOException {
flush();
buffer.close();
}
}

How to make sure multiple threads run methods from different classes in order? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am making a program where a server offers a quiz to any number of clients. I have to make this using sockets, so I am trying to solve this by making multiple threads with socket objects in my server class, each socket maintaining the connection to one client.
This was working fine until I did some refactoring, after which I discovered through debugging that information between client and server was being sent in the right order by sheer luck.
Here is the code for my client threads. It's an inner class of my Server class and the questionList is an attribute thereof.
private class ClientThread implements AutoCloseable, Runnable
{
private Socket clientConnection;
private DataOutputStream output;
private DataInputStream input;
public ClientThread(Socket clientConnection) throws IOException
{
this.clientConnection = clientConnection;
output = new DataOutputStream(clientConnection.getOutputStream());
output.flush();
input = new DataInputStream(clientConnection.getInputStream());
}
public void sendQuestion() throws IOException
{
if (input.available() > 0) if (input.readBoolean())
{
Question question = questionList.get((int) (Math.random() * questionList.size()));
sendQuestionInfo(question);
}
}
private void sendQuestionInfo(Question question) throws IOException
{
sendInfo(question.getAuthor());
sendInfo(question.getTitle());
}
private void sendInfo(String info) throws IOException
{
output.writeUTF(info);
output.flush();
}
#Override
public void run()
{
try
{
sendQuestion();
}
catch (IOException e)
{
e.printStackTrace();
}
}
#Override
public void close() {...}
}
And here is the relevant code from my Client class:
public class QuizClient implements AutoCloseable
{
private Socket serverConnection;
private DataOutputStream output;
private DataInputStream input;
public QuizClient(String serverAdress, int portNumber) throws IOException
{
serverConnection = new Socket(serverAdress, portNumber);
output = new DataOutputStream(serverConnection.getOutputStream());
output.flush();
input = new DataInputStream(serverConnection.getInputStream());
}
public void getQuiz()
{...}
private void playQuiz(boolean firstRun, Scanner scanner) throws IOException
{...}
private boolean playQuizTurn(Scanner scanner) throws IOException
{...}
private boolean isFirstRun()
{...}
private void askQuestion(Scanner scanner) throws IOException
{
output.writeBoolean(true);
output.flush();
Question question = getQuestion();
question.quizMe(scanner);
}
private Question getQuestion() throws IOException
{
String author = input.readUTF();
String title = input.readUTF();
return new Question(author, title);
}
#Override
public void close() throws IOException
{...}
}
The intended order of execution is askQuestion() -> sendQuestion() -> getQuestion(), but with the current code it insteads runs like sendQuestion() -> askQuestion() -> getQuestion(), and the program ends up being unresponsive.
How can I get this under control?
Your server's ClientThread.sendQuestion() method exits silently if input.available() is 0 - that is, if the "true" has not yet been received from the client - which will often be the case with a newly established client. Try having it wait patiently until there is data available, and see if you get any further.

How to calculate message digests in custom output stream?

I would like to implement an OutputStream that can produce MessageDigests. Likewise, I already have an InputStream implementation of it here, which works fine and extends FilterInputStream.
The problem is this: if I'm extending FilterOutputStream, the checksums don't match. If I use FileOutputStream it works fine (although that is not the stream I'd like to be using, as I'd like it to be a bit more generic than that).
public class MultipleDigestOutputStream extends FilterOutputStream
{
public static final String[] DEFAULT_ALGORITHMS = { EncryptionConstants.ALGORITHM_MD5,
EncryptionConstants.ALGORITHM_SHA1 };
private Map<String, MessageDigest> digests = new LinkedHashMap<>();
private File file;
public MultipleDigestOutputStream(File file, OutputStream os)
throws NoSuchAlgorithmException, FileNotFoundException
{
this(file, os, DEFAULT_ALGORITHMS);
}
public MultipleDigestOutputStream(File file, OutputStream os, String[] algorithms)
throws NoSuchAlgorithmException, FileNotFoundException
{
// super(file); // If extending FileOutputStream
super(os);
this.file = file;
for (String algorithm : algorithms)
{
addAlgorithm(algorithm);
}
}
public void addAlgorithm(String algorithm)
throws NoSuchAlgorithmException
{
MessageDigest digest = MessageDigest.getInstance(algorithm);
digests.put(algorithm, digest);
}
public MessageDigest getMessageDigest(String algorithm)
{
return digests.get(algorithm);
}
public Map<String, MessageDigest> getDigests()
{
return digests;
}
public String getMessageDigestAsHexadecimalString(String algorithm)
{
return MessageDigestUtils.convertToHexadecimalString(getMessageDigest(algorithm));
}
public void setDigests(Map<String, MessageDigest> digests)
{
this.digests = digests;
}
#Override
public void write(int b)
throws IOException
{
super.write(b);
System.out.println("write(int b)");
for (Map.Entry entry : digests.entrySet())
{
int p = b & 0xFF;
byte b1 = (byte) p;
MessageDigest digest = (MessageDigest) entry.getValue();
digest.update(b1);
}
}
#Override
public void write(byte[] b)
throws IOException
{
super.write(b);
for (Map.Entry entry : digests.entrySet())
{
MessageDigest digest = (MessageDigest) entry.getValue();
digest.update(b);
}
}
#Override
public void write(byte[] b, int off, int len)
throws IOException
{
super.write(b, off, len);
for (Map.Entry entry : digests.entrySet())
{
MessageDigest digest = (MessageDigest) entry.getValue();
digest.update(b, off, len);
}
}
#Override
public void close()
throws IOException
{
super.close();
}
}
My test case (the asserted checksums have been checked with md5sum and sha1sum):
public class MultipleDigestOutputStreamTest
{
#Before
public void setUp()
throws Exception
{
File dir = new File("target/test-resources");
if (!dir.exists())
{
//noinspection ResultOfMethodCallIgnored
dir.mkdirs();
}
}
#Test
public void testWrite()
throws IOException,
NoSuchAlgorithmException
{
String s = "This is a test.";
File file = new File("target/test-resources/metadata.xml");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MultipleDigestOutputStream mdos = new MultipleDigestOutputStream(file, baos);
mdos.write(s.getBytes());
mdos.flush();
final String md5 = mdos.getMessageDigestAsHexadecimalString("MD5");
final String sha1 = mdos.getMessageDigestAsHexadecimalString("SHA-1");
Assert.assertEquals("Incorrect MD5 sum!", "120ea8a25e5d487bf68b5f7096440019", md5);
Assert.assertEquals("Incorrect SHA-1 sum!", "afa6c8b3a2fae95785dc7d9685a57835d703ac88", sha1);
System.out.println("MD5: " + md5);
System.out.println("SHA1: " + sha1);
}
}
Could you please advise as to what could be the problem and how to fix it? Many thanks in advance!
If you are using java 7 or above, you can just use DigestOutputstream.
UPDATE
You can inplement the abstract MessageDigest class to wrap multiple MessageDigest instances.
SOME CODE
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class DigestWrapper extends MessageDigest
{
private final MessageDigest md5;
private final MessageDigest sha1;
// some methods missing.
// I just implemeted them throwing a RuntimeException.
public DigestWrapper() throws NoSuchAlgorithmException
{
super(null);
sha1 = MessageDigest.getInstance("sha-1");
md5 = MessageDigest.getInstance("md5");
}
public byte[] getMD5Digest()
{
return md5.digest();
}
public byte[] getSHA1Digest()
{
return sha1.digest();
}
#Override
public int digest(byte[] buf, int offset, int len) throws DigestException
{
md5.digest(buf, offset, len);
sha1.digest(buf, offset, len);
return 0;
}
#Override
public byte[] digest(byte[] input)
{
md5.digest(input);
sha1.digest(input);
return input;
}
#Override
public void reset()
{
md5.reset();
sha1.reset();
}
#Override
public void update(byte input)
{
md5.update(input);
sha1.update(input);
}
#Override
public void update(byte[] input, int offset, int len)
{
md5.update(input, offset, len);
sha1.update(input, offset, len);
}
#Override
public void update(byte[] input)
{
md5.update(input);
sha1.update(input);
}
}
I have created a project on Github which contains my implementation of the MultipleDigestInputStream and MultipleDigestOutputStream here.
To check how the code can be used, have a look at the following tests:
MultipleDigestInputStreamTest
MultipleDigestOutputStreamTest
Let me know, if there is enough interest and I can release it and publish it to Maven Central.

load html on Blackberry4.6 os version

Hi I'm new in Blackberry app development i want to load HTML in browser field..
I'm able to load HTML for version 5 ,and 6 and more but it not loading in OS version 4
plz tell me how to load this HTML on Blackberry OS version4.6 i m using Eclipsed
to developing application on 5 and 6 works properly but in 4.6 not plz tell me how to write. Code for this or any specific change in code or we cant load HTML in OS version 4.6?
BrowserField mybroBrowserField=new BrowserField();
add(mybroBrowserField);
mybroBrowserField.displayContent(
"<html><body><h1>hello world! This blackbery apps</h1> </body></html>",
"http://localhost");
this code apply for 5 and more than 5 version but not work for OS version 4
You can show your html document in this way
BrowserSession session = Browser.getDefaultSession();
session.displayPage("cod://Name of your application code file/test.html");
If you are using BlackBerry Eclipse Plug-in to develop BB apps, you can import sample BlackBerry projects. In the list there is something like BlackBerry Browser Field Demo. Just import that and find out how this works. Insert this snippet to Utilities class
private static DataInputStream dataInput;
private static InputStream in;
static HttpConnection makeDummyConnection(String htmlData){
try {
in = new ByteArrayInputStream(htmlData.getBytes("UTF-8"));
dataInput = new DataInputStream(in);
} catch (Exception e) {
System.out.println("HttpConnectionImpl : Exception : " + e);
}
return new HttpConnection() {
public String getURL() {
return "";
}
public String getProtocol() {
return "";
}
public String getHost() {
return "";
}
public String getFile() {
return "";
}
public String getRef() {
return "";
}
public String getQuery() {
return "";
}
public int getPort() {
return 0;
}
public String getRequestMethod() {
return "";
}
public void setRequestMethod(String s) throws IOException {
}
public String getRequestProperty(String s) {
return "";
}
public void setRequestProperty(String s, String s1) throws IOException {
}
public int getResponseCode() throws IOException {
return 200;
}
public String getResponseMessage() throws IOException {
return "";
}
public long getExpiration() throws IOException {
return 0;
}
public long getDate() throws IOException {
return 0;
}
public long getLastModified() throws IOException {
return 0;
}
public String getHeaderField(String s) throws IOException {
return "";
}
public int getHeaderFieldInt(String s, int i) throws IOException {
return 0;
}
public long getHeaderFieldDate(String s, long l) throws IOException {
return 0;
}
public String getHeaderField(int i) throws IOException {
return "";
}
public String getHeaderFieldKey(int i) throws IOException {
return "";
}
public String getType() {
return "text/html";
}
public String getEncoding() {
return "text/html";
}
public long getLength() {
return 7000;
}
public InputStream openInputStream() throws IOException {
return in;
}
public DataInputStream openDataInputStream() throws IOException {
return dataInput;
}
public void close() throws IOException {
}
public OutputStream openOutputStream() throws IOException {
return new ByteArrayOutputStream();
}
public DataOutputStream openDataOutputStream() throws IOException {
return new DataOutputStream(new ByteArrayOutputStream());
}
};
}
and call this instead of makeConnection(String url, HttpHeaders requestHeaders, byte[] postData) method.
BrowserField exist only since BlackBerry API 5.0.0, but you can use this custom BrowserFieldRenderer class from LogicMail to solve your problem

Categories