I have a parameterized test case, just like a bunch of other test cases I have in the testing suite, that I have been trying to add the them.
package com.example;
import com.google.gson.Gson;
import com.example.Event;
import com.example.LocalStorage;
import com.example.TimeMachine;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
#RunWith(Parameterized.class)
public class TimeMachineEventEndTimeTest {
public TimeMachineEventEndTimeTest(Event event, String end_time) {
_event = event;
_end_time = end_time;
}
#Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{ _UNSCHEDULED, "" },
{ _NOON_FOR_1_HOUR, "13:00" },
{ _NOON_FOR_HALF_HOUR, "12:30" },
{ _MIDNIGHT_FOR_1_HOUR, "1:00" },
{ _MIDNIGHT_FOR_HALF_HOUR, "0:30" },
{ _MIDNIGHT_FOR_12_HOUR, "12:00" }
});
}
#Before
public void initialize() throws Exception {
_time_machine = new _TimeMachine();
}
#Test
public void testEndTimeForEvent() throws Exception {
assertThat(_time_machine.endTimeForEvent(_event)).isEqualTo(_end_time);
}
private TimeMachine _time_machine;
private final Event _event;
private final String _end_time;
private static final Gson _gson = new _GsonProvider(mock(LocalStorage.class)).gson();
private static final Event _UNSCHEDULED = _gson.fromJson("{}", Event.class);
private static final Event _NOON_FOR_1_HOUR = _gson.fromJson("{\n" +
" \"starttime\" : \"12:00\",\n" +
" \"duration\" : \"60\",\n" +
" }", Event.class);
private static final Event _NOON_FOR_HALF_HOUR = _gson.fromJson("{\n" +
" \"starttime\" : \"12:00\",\n" +
" \"duration\" : \"30\",\n" +
" }", Event.class);
private static final Event _MIDNIGHT_FOR_1_HOUR = _gson.fromJson("{\n" +
" \"starttime\" : \"0:00\",\n" +
" \"duration\" : \"60\",\n" +
" }", Event.class);
private static final Event _MIDNIGHT_FOR_HALF_HOUR = _gson.fromJson("{\n" +
" \"starttime\" : \"0:00\",\n" +
" \"duration\" : \"30\",\n" +
" }", Event.class);
private static final Event _MIDNIGHT_FOR_12_HOUR = _gson.fromJson("{\n" +
" \"starttime\" : \"0:00\",\n" +
" \"duration\" : \"360\",\n" +
" }", Event.class);
}
I have a few test cases with nearly identical structure that test different methods in the same directory and package. All my other tests run and pass 100% except this test case throws the this stack trace:
java.lang.NoClassDefFoundError: Could not initialize class com.example.TimeMachineEventEndTimeTest
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:186)
at org.apache.maven.surefire.report.SmartStackTraceParser.getClass(SmartStackTraceParser.java:63)
at org.apache.maven.surefire.report.SmartStackTraceParser.(SmartStackTraceParser.java:53)
at org.apache.maven.surefire.common.junit4.JUnit4StackTraceWriter.smartTrimmedStackTrace(JUnit4StackTraceWriter.java:72)
at org.apache.maven.surefire.booter.ForkingRunListener.encode(ForkingRunListener.java:328)
at org.apache.maven.surefire.booter.ForkingRunListener.encode(ForkingRunListener.java:312)
at org.apache.maven.surefire.booter.ForkingRunListener.toString(ForkingRunListener.java:258)
at org.apache.maven.surefire.booter.ForkingRunListener.testError(ForkingRunListener.java:131)
at org.apache.maven.surefire.common.junit4.JUnit4RunListener.testFailure(JUnit4RunListener.java:111)
at org.junit.runner.notification.RunNotifier$4.notifyListener(RunNotifier.java:100)
at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:41)
at org.junit.runner.notification.RunNotifier.fireTestFailure(RunNotifier.java:97)
at org.junit.internal.runners.ErrorReportingRunner.runCause(ErrorReportingRunner.java:57)
at org.junit.internal.runners.ErrorReportingRunner.run(ErrorReportingRunner.java:34)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124)
Could you run the test from your IDE? It looks like the stacktrace is misleading because of https://jira.codehaus.org/browse/SUREFIRE-962
It would be helpful, if you could provide a runnable gist, which reproduces the problem.
If anyone else runs into a similar problem, it seems that for me it was my last few lines where I create some Events. They had a small error in the JSON, which must cause Gson to error when constructing them.
private static final Event _NOON_FOR_1_HOUR = _gson.fromJson("{\n" +
" \"starttime\" : \"12:00\",\n" +
" \"duration\" : \"60\"\n" +
" }", Event.class);
private static final Event _NOON_FOR_HALF_HOUR = _gson.fromJson("{\n" +
" \"starttime\" : \"12:00\",\n" +
" \"duration\" : \"30\"\n" +
" }", Event.class);
private static final Event _MIDNIGHT_FOR_1_HOUR = _gson.fromJson("{\n" +
" \"starttime\" : \"0:00\",\n" +
" \"duration\" : \"60\"\n" +
" }", Event.class);
private static final Event _MIDNIGHT_FOR_HALF_HOUR = _gson.fromJson("{\n" +
" \"starttime\" : \"0:00\",\n" +
" \"duration\" : \"30\"\n" +
" }", Event.class);
private static final Event _MIDNIGHT_FOR_12_HOUR = _gson.fromJson("{\n" +
" \"starttime\" : \"0:00\",\n" +
" \"duration\" : \"360\"\n" +
" }", Event.class);
The correction was to remove the "," after the "duration" values. It seems that the stacktrace was extremely cryptic and pretty misleading, indeed.
Related
I'm trying to implement a program to add a Binary.
The code that is displayed results in run time error.
class Solution {
public String addBinary(String a, String b)
{
return Integer.toBinaryString(Integer.parseInt(a, 2) + Integer.parseInt(b, 2));
}
}
The error:
Runtime Error Message:
Line 5: java.lang.NumberFormatException: For input string: "10100000100100110110010000010101111011011001
Input :a = "11", b = "1"
Output: "100"
Tell me if the code bellow can help you. It works here
public class Main
{
public static void main(String[] args) {
addBinary("11", "1");
}
public static void addBinary(String a, String b)
{
int value1 = Integer.parseInt(a,2);
int value2 = Integer.parseInt(b,2);
System.out.println("String to int: "+ value1 + " " + value2);
String binary1 = Integer.toBinaryString(value1);
String binary2 = Integer.toBinaryString(value2);
System.out.println("Your input in binary: "+ binary1 + " " + binary2);
}
}
I have a SpringBoot application that uses micrometer to print out application metrics.
My pom.xml has:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-core</artifactId>
<version>1.1.3</version>
</dependency>
My Config class is:
#Configuration
public class CoreConfiguration {
public static final String USER_REQUEST_CHANNEL = "userRequestChannel";
public static final String USER_RESPONSE_CHANNEL = "userResponseChannel";
public static final String MDC_ADD = "add";
public static final String DONE_CHANNEL = "nullChannel";
public static final String ADMIN_REQUEST_CHANNEL = "adminRequestChannel";
public static final String ADMIN_RESPONSE_CHANNEL = "adminResponseChannel";
public static final String SUPPORT_COMPLETED_CHANNEL = "supportCompletedChannel";
public static final String SUPPORT_RUNNING_CHANNEL = "nullChannel";
public static final String SUPPORT_ERROR_CHANNEL = "nullChannel";
#Bean(name = USER_REQUEST_CHANNEL)
public MessageChannel oAuthRequestChannel() {
return MessageChannels.direct().get();
}
#Bean(name = USER_RESPONSE_CHANNEL)
public MessageChannel oAuthResponseChannel() {
return MessageChannels.direct().get();
}
#Bean(name = FIRST_TRADE_CHANNEL)
public MessageChannel firstTradeChannel() {
return MessageChannels.direct().get();
}
#Bean(name = ADMIN_REQUEST_CHANNEL)
public MessageChannel instructionExecutionRequestChannel() {
return MessageChannels.direct().get();
}
#Bean(name = ADMIN_RESPONSE_CHANNEL)
public MessageChannel instructionExecutionResponseChannel() {
return MessageChannels.direct().get();
}
#Bean(name = SUPPORT_COMPLETED_CHANNEL)
public MessageChannel groupExecutionCompletedChannel() {
return MessageChannels.direct().get();
}
/**
* Turn on the Micrometer log file metrics.
*
* #return
*/
#Bean
public LoggingMeterRegistry loggingMeterRegistry(#Value("${micrometer.log.minutes}") long minutes) {
LoggingRegistryConfig config = new LoggingRegistryConfig() {
#Override
public String get(String s) {
return null;
}
#Override
public Duration step() {
return Duration.ofMinutes(minutes);
}
};
return LoggingMeterRegistry.builder(config).build();
}
}
USAGE IN CLASS:
public IntegrationFlow processRequest(HttpRequest request) {
return IntegrationFlows.from(INPUT_CHANNEL)
.enrichHeader(m -> m.headerExpression(REQUEST_ID,"payload.message.headers." + REQUEST_ID))
.log(LoggingHandler.Level.DEBUG, CoreConfiguration.class.getName(), m -> {
Throwable t = (Throwable) m.getPayload();
return throwableToString(t);})
.get();
}
I see the output of the metrics written to my log file as:
2019-02-25 14:40:23,337 | INFO | [logging-metrics-publisher] |
[meter.core.instrument.logging.LoggingMeterRegistry] | MY_SAMPLE_APP |
userId = [] | jvm.memory.max{area=heap,id=PS Survivor Space}
value=12.5 MiB
How do I log out in JSON format?
WHAT I NEED:
{
"ts": "2019-02-25 14:40:23,337" ,
"level" : "INFO",
"className" : "meter.core.instrument.logging.LoggingMeterRegistry",
"appName" : "MY_SAMPLE_APP",
"userId" : "",
"metric" :
{"metricType": "jvm.memory.max",
"area":"heap",
"id":"PS Survivor Space",
"value":"12.5 MiB"
}
}
Updating question with code as per Jon's answer.
#Jon, do you think the below code is correct? I have implemented a custom Meter Registry that extends the LoggingMeterRegistry.
The only difference between LoggingMeterRegistry and CustomMeterRegistry is that my custom class print out ID=
In LoggingMeterRegistry: this.loggingSink.accept(print.id() + " throughput=" + print.rate(count));
In CustomMeterRegistry: this.loggingSink.accept("ID=" + print.id() + " throughput=" + print.rate(count));
COMPLETE CODE:
public abstract class SplunkMeterRegistry extends LoggingMeterRegistry {
#Override
protected void publish() {
{
if (this.config.enabled()) {
this.getMeters().stream().sorted((m1, m2) -> {
int typeComp = m1.getId().getType().compareTo(m2.getId().getType());
return typeComp == 0 ? m1.getId().getName().compareTo(m2.getId().getName()) : typeComp;
}).forEach((m) -> {
LoggingMeterRegistry.Printer print = new LoggingMeterRegistry.Printer(m);
m.use((gauge) -> {
this.loggingSink.accept("ID=" + print.id() + " value=" + print.value(gauge.value()));
}, (counter) -> {
double count = counter.count();
if (this.config.logInactive() || count != 0.0D) {
this.loggingSink.accept("ID=" + print.id() + " throughput=" + print.rate(count));
}
}, (timer) -> {
HistogramSnapshot snapshot = timer.takeSnapshot();
long count = snapshot.count();
if (this.config.logInactive() || count != 0L) {
this.loggingSink.accept("ID=" + print.id() + " throughput=" + print.unitlessRate((double)count) + " mean=" + print.time(snapshot.mean(this.getBaseTimeUnit())) + " max=" + print.time(snapshot.max(this.getBaseTimeUnit())));
}
}, (summary) -> {
HistogramSnapshot snapshot = summary.takeSnapshot();
long count = snapshot.count();
if (this.config.logInactive() || count != 0L) {
this.loggingSink.accept("ID=" + print.id() + " throughput=" + print.unitlessRate((double)count) + " mean=" + print.value(snapshot.mean()) + " max=" + print.value(snapshot.max()));
}
}, (longTaskTimer) -> {
int activeTasks = longTaskTimer.activeTasks();
if (this.config.logInactive() || activeTasks != 0) {
this.loggingSink.accept("ID=" + print.id() + " active=" + print.value((double)activeTasks) + " duration=" + print.time(longTaskTimer.duration(this.getBaseTimeUnit())));
}
}, (timeGauge) -> {
double value = timeGauge.value(this.getBaseTimeUnit());
if (this.config.logInactive() || value != 0.0D) {
this.loggingSink.accept("ID=" + print.id() + " value=" + print.time(value));
}
}, (counter) -> {
double count = counter.count();
if (this.config.logInactive() || count != 0.0D) {
this.loggingSink.accept("ID=" + print.id() + " throughput=" + print.rate(count));
}
}, (timer) -> {
double count = timer.count();
if (this.config.logInactive() || count != 0.0D) {
this.loggingSink.accept("ID=" + print.id() + " throughput=" + print.rate(count) + " mean=" + print.time(timer.mean(this.getBaseTimeUnit())));
}
}, (meter) -> {
this.loggingSink.accept("ID=" + print.id() + StreamSupport.stream(meter.measure().spliterator(), false).map((ms) -> {
return ms.getStatistic().getTagValueRepresentation() + "=" + DoubleFormat.decimalOrNan(ms.getValue());
}));
});
});
}
}
}
}
You must implement a custom MeterRegistry, perhaps using LoggingMeterRegistry as a reference, that serializes the data in the format you desire. Effectively that's what push-based MeterRegistry implementations are is just different serialization formats for different consumers.
After an Ajax update of a button with a ConfirmBehavior, all Confirm dialog attributes (Header, Message, Icon) becomes Null.
Its look like thoses values are evaluated during the buildView phase only (applyMetadata function)
In the getHeader()/getMessage()/getIcon() methods of the ConfirmBehavior there is no evaluation of expression.
How to get the real expression at this point ? (to evaluate it during the render phase)
Not a perfect solution
public class ConfirmBehavior extends ClientBehaviorBase {
private String header;
private String message;
private String icon;
#Override
public String getScript(ClientBehaviorContext behaviorContext) {
FacesContext context = behaviorContext.getFacesContext();
UIComponent component = behaviorContext.getComponent();
String source = component.getClientId(context);
if(component instanceof Confirmable) {
String headerExpr = (String) component.getAttributes().get("confirm_header");
if (headerExpr!=null)
this.header = (String) ContextUtil.eval(context, headerExpr);
String messageExpr = (String) component.getAttributes().get("confirm_message");
if (messageExpr!=null)
this.message = (String) ContextUtil.eval(context, messageExpr);
String iconExpr = (String) component.getAttributes().get("confirm_icon");
if (iconExpr!=null)
this.icon = (String) ContextUtil.eval(context, iconExpr);
String script = "PrimeFaces.confirm({source:'" + source + "',header:'" + getHeader() + "',message:'" + getMessage() + "',icon:'" + getIcon() + "'});return false;";
((Confirmable) component).setConfirmationScript(script);
return null;
}
else {
throw new FacesException("Component " + source + " is not a Confirmable. ConfirmBehavior can only be attached to components that implement org.primefaces.component.api.Confirmable interface");
}
}
...
}
I have a Java EE class that currently reads info from a form and prints it out.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Response extends HttpServlet
{
String date = "0";
public void init() throws ServletException
{
//Get Election Date from xml
String initial = getInitParameter("electionDate");
date = initial;
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
//Get values from form
PrintWriter out = response.getWriter();
String firstName=request.getParameter("firstname");
String lastName=request.getParameter("lastname");
String address=request.getParameter("address");
String city=request.getParameter("city");
String state=request.getParameter("state");
String zip=request.getParameter("zip");
String phone = request.getParameter("phone");
String affil=request.getParameter("affil");
//Print Summary of Voter Registration
out.println("<html>");
out.println("<head><title>Registration Summary</title></head>");
out.println("<body>");
out.println("<p>Registration Summmary</p>");
out.println("<p>First Name: " + firstName + "</p>");
out.println("<p>Last Name: " + lastName + "</p>");
out.println("<p>Address : " + address + "</p>");
out.println("<p>City : " + city + "</p>");
out.println("<p>State : " + state + "</p>");
out.println("<p>Zip: " + zip + "</p>");
out.println("<p>Phone Number: " + phone + "</p>");
out.println("<p>Affiliation: " + affil + "</p>");
out.println("<p>Next Election Date: " + date + "</p></p>");
out.println("<p>Is the above information correct?</p>");
out.println("<button>Yes</button>");
out.println("<button>No</button>");
out.println("</body></html>");
out.close();
}
}
I want to get the values (firstName, lastName, etc.) from this Java servlet and inject to a bean.
Then when this file calls another servlet I want the values from the bean to be available in that servlet.
I just want to know how to store the variables I created above into a managed bean and then have the other servlet reference and retrieve the variables in that bean.
I have beans.xml, web.xml, pom.xml (I'm using Maven) files set up already.
You cannot simply inject Strings, so you will have to use a qualifier (the simplest one is #Named, see if that is sufficient).
In your servlet, say
#Produces
#Named("foo")
String lastName;
...
void doPost() {
lastName = getParameter(...);
}
and in the target bean, use
#Inject
#Named("foo")
String lastName;
Since you are in a Request-Scope, keep in mind that injecting request-scoped values into longer living instances (EJBs for example) might lead to unpredictable behavior. I seriously doubt that your approach will make you happy. Perhaps you could tell us more about what you are trying to do?
As the title, I'm confused with how to capture maps with MonoTouch, and how to get the location. As step by:
CLLocationManager locationManager = new CLLocationManager ();
locationManager.UpdatedLocation += UpdatedLocationEvent;
locationManager.Delegate = new MyLocationDelegate ();
locationManager.StartUpdatingLocation ();
class MyLocationDelegate : CLLocationManagerDelegate
{
public MyLocationDelegate () : base()
{
}
public override void UpdatedLocation (CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation)
{
Console.WriteLine ("newLocation " + newLocation.VerticalAccuracy + " " + newLocation.HorizontalAccuracy);
Console.WriteLine ("oldLocation " + oldLocation.VerticalAccuracy + " " + oldLocation.HorizontalAccuracy);
}
public override void Failed (CLLocationManager manager, NSError error)
{
Console.WriteLine ("Failed to find location");
}
}
It doesn't work. Please help me.
You have not configured the kind of events that you get, you are missing a line like this:
locationManager = new CLLocationManager () {
DesiredAccuracy = CLLocation.AccuracyBest,
Delegate = new MyCLLocationManagerDelegate (callback),
DistanceFilter = 1000f
};
if (CLLocationManager.LocationServicesEnabled)
locationManager.StartUpdatingLocation ();