How would I make a Bukkit webserver? - bukkit

I am trying to start a bukkit plugin that allows you to control your server online! I am having a slight error though. I have no idea how to do that. I will write the code for the website, I just need the code to handle the http request. Please help!

I'm trying to make something like this. You can use com.sun packages, it is very useful, but #Deprecated. I did it like this:
Public class HttpProcessor {
public HttpProcessor(MainClass plug) {
HttpServer server = HttpServer.Create(new InetSocketAddress(9090), 0);
server.createContext("/returnstaticvalue", new RSVhandler());
}
static class RSVhandler implements HttpHandler {
public void handle (HttpExchange h) throws IOException {
h.getResponseHeaders().set("Access-Control-Allow-Origin", "*");
HttpProcessor.writeResponse(h, "The static value");
}
}
public static void writeResponse(HttpExchange httpExchange, String response) throws IOException {
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}

Related

How can I use MockWebServer for Junit test cases of webclient?

I have a spring-boot application which calls some third party URL (let's say http://example.com/someUri) using webclient(I have used application-dev.properties for injecting this url in my application to achieve loose coupling) and consumes the response and use it in my application.
It's my first time when I am going to write test cases for webclient. and there I used #SprintBootTest.
I found that there are two ways where I can test my webclient with third party Api call by mocking the api call and make it call to my local url(which will be using url(http://localhost:{portNumber}/someUri) from my testing properties file: src/test/resources/application.properties) where It will be giving some mockedResponse in return to my real client:
Using wiremock
Using MockWebServer
consider above code for better understanding:
#Service
Class SampleService{
#Value("${sample.url}")
private String sampleUrl;
public String dummyClient() {
String sample =webClient.get()
.uri(sampleUrl)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.retrieve()
.bodyToMono(String.class)
.block();
return sample;
}
}
application-dev.properties:
sample.url:http://example.com/someUri
src/test/resouces/application.properties:
http://localhost:8090/someUri
Testing class:
#SpringBootTest
public class sampleTestingClass {
#Autowired
private SampleService sampleService;
#Value("${sample.url}")
private String sampleUrl;
public static MockWebServer mockWebServer = new MockWebServer();
#BeforeAll
static void setUp() throws IOException {
mockWebServer.start(8090);
}
#AfterAll
static void tearUp() throws IOException {
mockWebServer.close();
}
HttpUrl url = mockWebServer.url("/someUri");
mockWebServer
.enqueue(
new MockResponse()
.setResponseCode(200)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody("Sample Successful"));
String sample = sampleService.dummyClient();
assertEquals(sample ,matches("Sample Successful"));
}
}
but this code isn't working. it's giving me above error:
java.lang.NullPointerException
It will be really helpful if anybody knows how this can be fixed to achieve my unit testing using mocked Url? Thanks in advance!
Here is a working example:
#Component
public class QuotesClient {
private final WebClient webClient;
public QuotesClient(WebClient.Builder builder, #Value("${client.baseUrl}") String baseUrl) {
this.webClient = builder.baseUrl(baseUrl).build();
}
public JsonNode getData() {
return this.webClient
.get()
.retrieve()
.bodyToMono(JsonNode.class)
.block();
}
}
Using the WebClient.Builder is optional.
The corresponding test can look like the following:
class QuotesClientTest {
private QuotesClient quotesClient;
private MockWebServer server;
#BeforeEach
public void setup() {
this.server = new MockWebServer();
this.quotesClient = new QuotesClient(WebClient.builder(), server.url("/").toString());
}
#Test
public void test() {
server.enqueue(new MockResponse()
.setStatus("HTTP/1.1 200")
.setBody("{\"bar\":\"barbar\",\"foo\":\"foofoo\"}")
.addHeader("Content-Type", "application/json"));
JsonNode data = quotesClient.getData();
assertNotNull(data);
System.out.println(data);
}
}
If you are searching for a similar setup using WireMock, Spring Boot, and JUnit 5, take a look at the linked guide.

Robolectric: simulate network error in test

How is it possible to produce the same exception like during a real connection-error in robolectric tests?
I want to how the program acts if the network is currently not available. Is there a possibility to produce the same exception for my HttpClient?
I already tried:
Robolectric.getFakeHttpLayer().interceptHttpRequests(false); // with real network to a non existent IP
and
WifiManager wifiManager = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
and
Robolectric.addPendingHttpResponse(404, null);
but none of them produces the same reactions like a real connection-loosing.
Thank you
I've checked Robolectric's FakeHttpLayer and haven't found way to simulate throwing an IOException.
So use mocking to make it working for you. First introduce HttpClientFactory (if you use HttpClient, you can use same approach for HttpUrlConnection):
public class HttpClientFactory {
public HttpClient createClient() {
return new DefaultHttpClient();
}
}
And now in your networking layer use factory instead of constructors (let for simplicity assume that it is synchronous):
public class HttpTransportLayer {
private final HttpClientFactory clientFactory;
public HttpTransportLayer() {
this(new HttpClientFactory());
}
// For tests only
HttpTransportLayer(HttpClientFactory clientFactory) {
this.clientFactory = clientFactory;
}
public String requestData(String url) {
HttpClient client = factory.createClient();
...
}
}
So now you can in tests use Mockito:
HttpClient mockedClient = mock(HttpClient.class);
#Before
public void setUp() {
HttpClientFactory factory = mock(HttpClientFactory.class);
when(factory.createClient()).thenReturn(mockedClient);
target = new HttpTransportLayer(factory);
}
#Test
public void whenIOExceptionThenReturnNull() {
when(mockedClient.execute(any(HtptUriRequest.class))).thenThrow(new IOException());
String data = target.requestData("http://google.com");
assertThat(data).isNull();
}
That is dummy test and usually nobody will return null in case of error.
You could also task look to some dependency injection framework like Dagger to minimise injection code.
If you use any good framework for networking like Retrofit or Volley then it is even simpler - you don't need to mock anything and just invoke you error callback.
Hope it helps

JUnit on failure callback/method

Is there any possibility to trigger a method whenever a testcase or assertion fails, in order to do some things when a testcase fails (e.g. Screenshot while UI-Testing, writing an error log, and so on...).
Maybe there is something like an annotation, I did not yet notice.
Thanks in advance!
You can use the TestWatcher rule and implement your own failed method to take a screenshot or whatever you need to do upon test failure. Slightly modified example from the official documentation:
public static class WatchmanTest {
private static String watchedLog;
#Rule
public TestRule watchman = new TestWatcher() {
#Override
protected void failed(Throwable e, Description description) {
watchedLog += d + "\n";
// take screenshot, etc.
}
};
#Test
public void fails() {
fail();
}
}

Error when using Code First in web service "System.Data.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string."

I'm using Code First. Everything works just fine (inserts, updates, selects) everything is tested. The problem comes when I try to use the web services. I get the error "System.Data.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string.". Looking at the inner exception I get this message "Could not determine storage version; a valid storage connection or a version hint is required.".
The web service Code:
/// <summary>
/// Summary description for UserServices
/// </summary>
[WebService(Namespace = "http://localhost:3955/WebServices/UserServices")]
//[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class UserServices : System.Web.Services.WebService
{
[WebMethod]
public bool LoginControlPanelUser(string user, string password)
{
if(Membership.ValidateUser(user, password))
{
return DbUsersDAO.HasAuthenticationType(user, password);
}
return false;
}
}
The DAO code:
public static bool HasAuthenticationType(string user, string authenticationTypeCode)
{
try
{
using (VirtusCloudCoreContext ctx = new VirtusCloudCoreContext())
{
DBUser User = ctx.DBUsers.SingleOrDefault(u => u.Login.Equals(user) && u.Active.Equals(true));
if (User != null)
{
return DBAuthenticationTypesDAO.GetById(User.DBAuthenticationTypeId).Name.Equals("Admin");
}
}
return false;
}
catch (Exception ex)
{
ErrorsHelper.InsertError(ex);
throw ex;
}
}
The Context class:
public VirtusCloudCoreContext()
{
Database.SetInitializer<VirtusCloudCoreContext>(new VirtusCloudCoreContextInitializer());
this.Database.Connection.ConnectionString = "Data Source=localhost\SQLEXPRESS;Database=DatabaseName;User Id=******;Password=*******;" ;
}
I get the exception when I try to get the user.... Any ideas?
This error occurs often when the connection string is wrong but I think in your case it's because you're trying to manually set the connection string.
Try making your context inherit from DbContext and take a connection string in your constructor which it passes through to the base constructor, like this:
public class VirtualCloudCoreContext : DbContext {
public VirtualCloudCoreContext(string connectionString)
: base (connectionString) {
}
}
I'm using a new DB-generated EDMX in VS2012 Web Project with a separate class file - both projects have EF 6.1.1 installed. Even though I'm using SQL 2012, I had to edit the EDMX file directly and change it to ProviderManifestToken="2008" from 2012.
Not sure if related to Telerik Grid/EntityDataSource or not. More mention of this issue here but related to VS2013.

How do I unit test routes for web forms?

I have a web form such as mysite.com/list.aspx?state=florida&city=miami that I want users to browse using mysite.com/florida/miami/ and I'm using routing to do so. Then instead of using query string parameters, I end up having to use HttpContext.Current.Items[key] to retrieve the values on my list.aspx page. I have included the code below.
I would like to know what the best practices are to unit test this. Also, is there a better way to implement this without changing my code on the list.aspx page?
Code:
Sample of my Global.asax file:
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add(new Route("{state}", new CustomRouteHandler("/list.aspx")));
routes.Add(new Route("{state}/{city}", new CustomRouteHandler("/list.aspx")));
}
Sample of the CustomerRouteHandler:
public class CustomRouteHandler : IRouteHandler
{
public CustomRouteHandler(string virtualPath)
{
this.VirtualPath = virtualPath;
}
public string VirtualPath { get; private set; }
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
foreach (var urlParm in requestContext.RouteData.Values)
{
requestContext.HttpContext.Items[urlParm.Key] = urlParm.Value;
}
IHttpHandler page = BuildManager.CreateInstanceFromVirtualPath (VirtualPath, typeof(Page)) as IHttpHandler;
return page;
}
}
You could use HttpUnit to test that all the url endpoints work correctly.