Below is the code-I am getting intialization error while running the below code
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
#RunWith(Parameterized.class)
public class test1 {
public String name;
public int acc;
public test1(String name,int acc)
{
this.name=name;
this.acc=acc;
}
#Test
public void bank()
{
System.out.println(name+acc);
}
#Parameters
public static Collection<Object[]> getdata()
{
Object data[][]= new Object[1][2];
data[1][0]="ddd";
data[1][1]=123;
return Arrays.asList(data);
}
}
I am getting Intialization error while running this code.
The initialization error is caused by a ArrayIndexOutOfBoundsException.
In the getData method the variable data is accessed with index 1 for the first dimension but the index of arrays start at zero. Change the method to
#Parameters
public static Collection<Object[]> getdata() {
Object data[][] = new Object[1][2];
data[0][0] = "ddd";
data[0][1] = 123;
return Arrays.asList(data);
}
Related
using bytebuddy to intercept class Foo, whihc has two method A,B
in A method, B method get called. if we deleget both A and B to C method in intercetpor class Bar, which call callable#call at first line
what will happen ? what's the execution sequence of those methods ?
package org.wxt.xtools.agents;
import static net.bytebuddy.matcher.ElementMatchers.isAbstract;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.namedOneOf;
import static net.bytebuddy.matcher.ElementMatchers.not;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import net.bytebuddy.utility.JavaModule;
class Foo {
public void methodA() {
System.out.println("method A");
methodB();
}
public void methodB() {
System.out.println("method B");
}
}
class Bar {
#RuntimeType
public static void interceptor(#Origin Class<?> clazz, #Origin Method method, #SuperCall Callable<?> callable,
#net.bytebuddy.implementation.bind.annotation.This Object inst) throws Exception {
callable.call();
System.out.println("intercepting " + method.getName());
}
}
public class Test {
public static void premain(String agentArgs, Instrumentation inst) throws IOException {
AgentBuilder.Transformer methodsTransformer = new AgentBuilder.Transformer() {
#Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription,
ClassLoader classLoader, JavaModule javaModule) {
return builder.method(namedOneOf("methodA", "methodB").and(not(isAbstract())))
.intercept(MethodDelegation.to(Bar.class));
}
};
AgentBuilder.Listener listener = new AgentBuilder.Listener.WithErrorsOnly(
new AgentBuilder.Listener.StreamWriting(System.out));
new AgentBuilder.Default().type(named("org.wxt.xtools.agents.Foo")).transform(methodsTransformer)
.with(listener).installOn(inst);
}
public static void main(String[] args) throws IOException {
premain(null, ByteBuddyAgent.install());
new Foo().methodA();
}
}
results
method A
method B
intercepting methodB
intercepting methodA
You can of course just try it, but what will happen is that the internal call will again be intercepted. Methods do not know who is calling them. To avoid this, you can discover the caller via a StackWalker or by generating a stack trace using an exception.
IntelliJ does not resolve my setter-methods although
I have installed the Lombok-plugin
I have enabled annotation processing
I have added the Lombok-Maven-dependency on my pom.xml
My classes:
TournamentController:
package ba2.demo.Service;
import ba2.demo.DTO.ArcherDTO;
import ba2.demo.DTO.DivisionDTO;
import ba2.demo.DTO.TournamentDTO;
import ba2.demo.Model.Archer;
import ba2.demo.Model.Tournament;
import ba2.demo.Repository.ArcherRepository;
import ba2.demo.Repository.DivisionRepository;
import ba2.demo.Repository.TournamentRepository;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
#Component
public class TournamentServiceImpl implements TournamentService {
#Autowired
private TournamentRepository tournamentRepository;
#Autowired
private ArcherRepository archerRepository;
#Autowired
private DivisionRepository divisionRepository;
#Autowired
private ModelMapper modelMapper;
#Override
public List<Tournament> getAllTournaments() {
return null;
}
#Override
public Tournament getTournamentById(int id) {
Tournament obj = tournamentRepository.findById(id).get();
return obj;
}
#Override
public TournamentDTO createTournament(TournamentDTO tournamentDTO) {
Tournament tournamentModel = new Tournament()
.setName(tournamentDTO.getName())
.setStatusCode(tournamentDTO.getStatusCode());
tournamentRepository.save(tournamentModel);
return modelMapper.map(tournamentModel, TournamentDTO.class);
}
#Override
public void editTournament(TournamentDTO tournamentDTO) {
}
#Override
public void deleteTournament(int id) {
}
#Override
public ArcherDTO registerArcher(ArcherDTO archerDTO, DivisionDTO divisionDTO) {
Archer archerModel = new Archer()
.setFirstName(archerDTO.getFirstName())
.setLastName(archerDTO.getLastName())
.setDivisionName(divisionDTO.getName());
archerRepository.save(archerModel);
return modelMapper.map(archerModel, ArcherDTO.class);
}
}
Archer-Model:
package ba2.demo.Model;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.annotation.Id;
#Getter
#Setter
#NoArgsConstructor
public class Archer {
#Id
private String id;
private String firstName;
private String lastName;
private Division division;
private ShootingStyle shootingStyle;
}
ArcherDTO:
package ba2.demo.DTO;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.Id;
#Getter
#Setter
#ToString
#NoArgsConstructor
public class ArcherDTO {
#Id
private String id;
private String firstName;
private String lastName;
private String divisionName;
private String shootingStyleName;
}
The error message:
java: cannot find symbol
symbol: method getName()
location: variable tournamentDTO of type ba2.demo.DTO.TournamentDTO
I am new to developing REST api, and trying to create a small dummy REST API.
I am using tomcat version 8.5.X. Eclipse Version: 2019-12 (4.14.0).
Below is my code.
MessageResuroce.java:
package org.vaibhavc.practice.microservice.messanger.resources;
import java.util.List;
import org.vaibhavc.practice.microservice.messanger.model.Message;
import org.vaibhavc.practice.microservice.messanger.service.MessageService;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.GenericEntity;
#Path("/messages")
public class MessageResource {
MessageService messageService = new MessageService();
#GET
#Produces(MediaType.APPLICATION_XML)
public Response getMessage() {
List<Message> newMessage = messageService.getAllMessages();
GenericEntity<List<Message>> list = new GenericEntity<List<Message>>(newMessage) {};
return Response.ok(list).build();
}
}
Message.java
package org.vaibhavc.practice.microservice.messanger.model;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Message {
private long id;
private String message;
private Date created;
private String author;
public Message(){
}
public Message(long id, String message, String author) {
this.id = id;
this.message = message;
this.created = new Date();
this.author = author;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
MessageService.java
package org.vaibhavc.practice.microservice.messanger.service;
import java.util.ArrayList;
import java.util.List;
import org.vaibhavc.practice.microservice.messanger.model.Message;
public class MessageService {
public List<Message> getAllMessages(){
Message m1 = new Message(1L,"Hello world!","Vaibhav");
Message m2 = new Message(2L,"Hello jersery!","Vaibhav");
List<Message> list = new ArrayList<>();
list.add(m1);
list.add(m2);
return list;
}
}
code built and compiled successfully.
When I trying to access url "http://localhost:8080/messanger/webapi/messages" I am getting error as follow:
SEVERE: MessageBodyWriter not found for media type=application/xml, type=class java.util.ArrayList, genericType=java.util.List.
Any idea what I am missing here?
Please add jersey-media-moxy library in your class path and check
Maven Code Snippet
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.31</version>
I am learning restful api with jax rs(jersey) and I making a messageResource class in which I am getting messages .everything works fine with xml but get function is not working with json .I have tried content type and accept headers too but its not working and returning 500 error and content type text/html.
Even the maven dependency moxy is also set in pom.xml
Can anybody help me finding the error.
package org.restfulapi.messenger.resources;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.restfulapi.messenger.services.DataNotFoundException;
import org.restfulapi.messenger.services.Link;
import org.restfulapi.messenger.services.Message;
import org.restfulapi.messenger.services.MessageService;
#Path("messages")
#Produces(value= {MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
#Consumes(value= {MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public class MessageResource
{
MessageService service=new MessageService();
#GET
#Path("/{messageID}")
public Message getMessage(#PathParam("messageID")int id,#Context UriInfo uriinfo )
{
Message msg=service.getMessage(id);
if(service.getMessage(id)==null)
{
throw new DataNotFoundException("message with id "+id+"not found");
}
return msg;
}
#GET
public List<Message> getMessages(#QueryParam("year")int year,
#QueryParam("start") int start,
#QueryParam("size") int size)
{
if(year>0)
{
return service.getbyyear(year);
}
if(start>0 & size>0)
{
return service.get(start, size);
}
return service.getMessages();
}
#POST
public Response addMessage(Message msg) throws URISyntaxException
{
return Response.created(new URI("/messenger/webapi/messages"+msg.getId())).entity(service.addMessage(msg)).build();
}
package org.restfulapi.messenger.services;
import java.util.List;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class MessageService {
private HashMap<Integer, Message> messages = Database.getMessages();
public MessageService()
{
}
public ArrayList<Message> getMessages() {
return new ArrayList<Message>(messages.values());
}
;
public Message getMessage(int id) {
return messages.get(id);
}
public ArrayList<Message> getbyyear(int year)
{
ArrayList<Message> result =new ArrayList();
Calendar cal=Calendar.getInstance();
for(Message msg:messages.values())
{
cal.setTime(msg.getCreated());
if(cal.get(Calendar.YEAR)==year)
result.add(msg);
}
return result;
}
public List<Message> get(int start,int size)
{
ArrayList<Message> result =new ArrayList<Message>(messages.values());
return result.subList(start, start+size);
}
public Message addMessage(Message message) {
message.setId(messages.size() + 1);
messages.put(message.getId(), message);
return message;
}
}
package org.restfulapi.messenger.services;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Message {
private int id;
private String msg;
private Date created;
private String author;
private ArrayList<Link> links=new ArrayList();
public ArrayList<Link> getLinks() {
return links;
}
public void setLinks(ArrayList<Link> links) {
this.links = links;
}
public Message()
{
}
public Message(int id, String msg, String author) {
this.id = id;
this.msg = msg;
this.author = author;
this.created = new Date();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public void addLink(String uri, String rel) {
Link l=new Link(uri,rel);
links.add(l);
}
}
public class Database
{
private static HashMap<Integer,Message> messages=new HashMap();
public static HashMap<Integer,Message> getMessages()
{
return messages;
}
}
When react native require this native ui component multiple time, starting from the second one, the previous became black.
Any ideas?
#Override
public String getName()
{
return "JWPlayer";
}
#Override
public JWPlayerView createViewInstance(ThemedReactContext context)
{
PlayerConfig playerConfig = new PlayerConfig.Builder().build();
playerView = new JWPlayerView(context.getCurrentActivity(), playerConfig);
playerView.setFullscreen(false, false);
playerView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
playerView.addOnFullscreenListener(this);
playerView.addOnPauseListener(this);
playerView.addOnPlayListener(this);
playerView.addOnSetupErrorListener(this);
playerView.addOnErrorListener(this);
return playerView;
}
I also met this question.
I solved the problem.
see same question ,
this
JWView.java :
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.WritableMap;
import com.longtailvideo.jwplayer.JWPlayerView;
import com.longtailvideo.jwplayer.configuration.PlayerConfig;
public class JWView extends FrameLayout {
private final Context _context;
private Activity activity = null;
public JWView(Context context) {
super(context);
this._context = context;
this.activity = ((ReactContext) getContext()).getCurrentActivity();
PlayerConfig playerConfig = new PlayerConfig.Builder()
.file("http://img.ksbbs.com/asset/Mon_1605/25d705200a4eab4.mp4")
.autostart(false)
.build();
JWPlayerView playerView = new JWPlayerView(this.activity, playerConfig);
addView(playerView);
}
private final Runnable measureAndLayout = new Runnable() {
#Override
public void run() {
measure(
MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
layout(getLeft(), getTop(), getRight(), getBottom());
}
};
#Override
public void requestLayout() {
super.requestLayout();
// The spinner relies on a measure + layout pass happening after it calls requestLayout().
// Without this, the widget never actually changes the selection and doesn't call the
// appropriate listeners. Since we override onLayout in our ViewGroups, a layout pass never
// happens after a call to requestLayout, so we simulate one here.
post(measureAndLayout);
}
}
JWPlayerViewManager.java:
import java.util.List;
import java.util.ArrayList;
import android.app.Activity;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.longtailvideo.jwplayer.JWPlayerView;
import com.longtailvideo.jwplayer.configuration.PlayerConfig;
public class JWPlayerViewManager extends SimpleViewManager<JWView>
{
#Override
public String getName()
{
return "Jwplayer";
}
#Override
public JWView createViewInstance(ThemedReactContext context)
{
return new JWView(context);
}
}