DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Coding Topics

article thumbnail
Docker in Action: The Shared Memory Namespace
In this article, excerpted from the book Docker in Action, I will show you how to open access to shared memory between containers. Linux provides a few tools for sharing memory between processes running on the same computer. This form of inter-process communication (IPC) performs at memory speeds. It is often used when the latency associated with network or pipe based IPC drags software performance below requirements. The best examples of shared memory based IPC usage is in scientific computing and some popular database technologies like PostgreSQL. Docker creates a unique IPC namespace for each container by default. The Linux IPC namespace partitions shared memory primitives like named shared memory blocks and semaphores, as well as message queues. It is okay if you are not sure what these are. Just know that they are tools used by Linux programs to coordinate processing. The IPC namespace prevents processes in one container from accessing the memory on the host or in other containers. Sharing IPC Primitives Between Containers I’ve created an image named allingeek/ch6_ipc that contains both a producer and consumer. They communicate using shared memory. Listing 1 will help you understand the problem with running these in separate containers. Listing 1: Launch a Communicating Pair of Programs # start a producer docker -d -u nobody --name ch6_ipc_producer \ allingeek/ch6_ipc -producer # start the consumer docker -d -u nobody --name ch6_ipc_consumer \ allingeek/ch6_ipc -consumer Listing 1 starts two containers. The first creates a message queue and starts broadcasting messages on it. The second should pull from the message queue and write the messages to the logs. You can see what each is doing by using the following commands to inspect the logs of each: docker logs ch6_ipc_producer docker logs ch6_ipc_consumer If you executed the commands in Listing 1 something should be wrong. The consumer never sees any messages on the queue. Each process used the same key to identify the shared memory resource but they referred to different memory. The reason is that each container has its own shared memory namespace. If you need to run programs that communicate with shared memory in different containers, then you will need to join their IPC namespaces with the --ipc flag. The --ipc flag has a container mode that will create a new container in the same IPC namespace as another target container. Listing 2: Joining Shared Memory Namespaces # remove the original consumer docker rm -v ch6_ipc_consumer # start a new consumer with a joined IPC namespace docker -d --name ch6_ipc_consumer \ --ipc container:ch6_ipc_producer \ allingeek/ch6_ipc -consumer Listing 2 rebuilds the consumer container and reuses the IPC namespace of the ch6_ipc_producer container. This time the consumer should be able to access the same memory location where the server is writing. You can see this working by using the following commands to inspect the logs of each: docker logs ch6_ipc_producer docker logs ch6_ipc_consumer Remember to cleanup your running containers before moving on: # remember: the v option will clean up volumes, # the f option will kill the container if it is running, # and the rm command takes a list of containers docker rm -vf ch6_ipc_producer ch6_ipc_consumer There are obvious security implications to reusing the shared memory namespaces of containers. But this option is available if you need it. Sharing memory between containers is safer alternative to sharing memory with the host.
July 9, 2015
by Jeff Nickoloff
· 39,395 Views · 1 Like
article thumbnail
Mapping Complex JSON Structures With JDK8 Nashorn
Wondering how you can map a complex JSON structure to another JSON structure using Java? Read this awesome tutorial on mapping complex JSON structures.
July 8, 2015
by Jethro Bakker
· 13,060 Views
article thumbnail
Where Am I? Collecting GPS Data With Apache Camel
In this article I will tell you how Apache Camel can turn a full-stack Linux microcomputer (like Raspberry Pi) into a device collecting the GPS coordinates.
July 8, 2015
by Henryk Konsek
· 5,751 Views · 1 Like
article thumbnail
Java 8: Master Permutations
Using Permutations, you can try all combinations of an input set.
July 7, 2015
by Per-Åke Minborg
· 39,870 Views · 11 Likes
article thumbnail
Optional Parameters in Java 8 Lambda Expressions
Yeah, they don't really exist, but we can use polymorphism, method overloading and default methods instead to make it a bit more convenient to use our APIs. As an example, here's an event bus implementation where I can register event handlers with an optional header parameter. Bus bus = new Bus(); bus.register(event -> System.out.println("I gots an event")); bus.register((event,header) -> System.out.println("I gots an event w/ header")); Here are the dirty details on how you can do this (and - when dispatching - events, use default methods to avoid type coercion.
July 7, 2015
by Jochen Bedersdorfer
· 7,640 Views · 1 Like
article thumbnail
Standalone Java application with Jersey and Jetty
I’ve built a small example of running a standalone Java application that both serves static HTML, JavaScript, CSS content, and also publishes a REST web service.
July 7, 2015
by Alan Hohn
· 40,028 Views · 3 Likes
article thumbnail
Casting in Java 8 (and Beyond?)
Casting an instance to a type reeks of bad design. Still, there are situations where there is no other choice. The ability to do this has always been part of Java.
July 6, 2015
by Nicolai Parlog
· 22,441 Views
article thumbnail
60 Most Commonly Used R Packages in R Programming Language
A comprehensive list of 60 most commonly used R packages for data science and analytics.
July 6, 2015
by Ajitesh Kumar
· 10,478 Views · 2 Likes
article thumbnail
More Compact Mockito with Java 8 and Lambda Expressions
Mockito-Java8 is a set of Mockito add-ons leveraging Java 8 and lambda expressions to make mocking with Mockito even more compact. At the beginning of 2015 I gave my flash talk Java 8 brings power to testing! at GeeCON TDD 2015 and DevConf.cz 2015. In my speech using 4 examples I showed how Java 8 – namely lambda expressions – can simplify testing tools and testing in general. One of those tools was Mokcito. To not let my PoC code die on slides and to make it simply available for others I have released a small project with two, useful in specified case, Java 8 add-ons for Mockito. Quick introduction As a prerequisite, let's assume we have the following data structure: @Immutable class ShipSearchCriteria { int minimumRange; int numberOfPhasers; } and a class we want to stub/mock: public class TacticalStation { public int findNumberOfShipsInRangeByCriteria( ShipSearchCriteria searchCriteria) { ... } } The library provides two add-ons: Lambda matcher - allows to define matcher logic within a lambda expression. given(ts.findNumberOfShipsInRangeByCriteria( argLambda(sc -> sc.getMinimumRange() > 1000))).willReturn(4); Argument Captor - Java 8 edition - allows to use `ArgumentCaptor` in a one line (here with AssertJ): verify(ts).findNumberOfShipsInRangeByCriteria( assertArg(sc -> assertThat(sc.getMinimumRange()).isLessThan(2000))); Lambda matcher With a help of the static method argLambda a lambda matcher instance is created which can be used to define matcher logic within a lambda expression (here for stubbing). It could be especially useful when working with complex classes pass as an argument. @Test public void shouldAllowToUseLambdaInStubbing() { //given given(ts.findNumberOfShipsInRangeByCriteria( argLambda(sc -> sc.getMinimumRange() > 1000))).willReturn(4); //expect assertThat(ts.findNumberOfShipsInRangeByCriteria( new ShipSearchCriteria(1500, 2))).isEqualTo(4); //expect assertThat(ts.findNumberOfShipsInRangeByCriteria( new ShipSearchCriteria(700, 2))).isEqualTo(0); } In comparison the same logic implemented with a custom Answer in Java 7: @Test public void stubbingWithCustomAsnwerShouldBeLonger() { //old way //given given(ts.findNumberOfShipsInRangeByCriteria(any())).willAnswer(new Answer() { @Override public Integer answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); ShipSearchCriteria criteria = (ShipSearchCriteria) args[0]; if (criteria.getMinimumRange() > 1000) { return 4; } else { return 0; } } }); //expect assertThat(ts.findNumberOfShipsInRangeByCriteria( new ShipSearchCriteria(1500, 2))).isEqualTo(4); //expect assertThat(ts.findNumberOfShipsInRangeByCriteria( new ShipSearchCriteria(700, 2))).isEqualTo(0); } Even Java 8 and less readable constructions don't help too much: @Test public void stubbingWithCustomAsnwerShouldBeLongerEvenAsLambda() { //old way //given given(ts.findNumberOfShipsInRangeByCriteria(any())).willAnswer(invocation -> { ShipSearchCriteria criteria = (ShipSearchCriteria) invocation.getArguments()[0]; return criteria.getMinimumRange() > 1000 ? 4 : 0; }); //expect assertThat(ts.findNumberOfShipsInRangeByCriteria( new ShipSearchCriteria(1500, 2))).isEqualTo(4); //expect assertThat(ts.findNumberOfShipsInRangeByCriteria( new ShipSearchCriteria(700, 2))).isEqualTo(0); } Argument Captor - Java 8 edition A static method assertArg creates an argument matcher which implementation internally uses ArgumentMatcher with an assertion provided in a lambda expression. The example below uses AssertJ to provide meaningful error message, but any assertions (like native from TestNG or JUnit) could be used (if really needed). This allows to have inlined ArgumentCaptor: @Test public void shouldAllowToUseAssertionInLambda() { //when ts.findNumberOfShipsInRangeByCriteria(searchCriteria); //then verify(ts).findNumberOfShipsInRangeByCriteria( assertArg(sc -> assertThat(sc.getMinimumRange()).isLessThan(2000))); } In comparison to 3 lines in the classic way: @Test public void shouldAllowToUseArgumentCaptorInClassicWay() { //old way //when ts.findNumberOfShipsInRangeByCriteria(searchCriteria); //then ArgumentCaptor captor = ArgumentCaptor.forClass(ShipSearchCriteria.class); verify(ts).findNumberOfShipsInRangeByCriteria(captor.capture()); assertThat(captor.getValue().getMinimumRange()).isLessThan(2000); } Summary The presented add-ons were created as PoC for my conference speech, but should be fully functional and potentially useful in the specific cases. To use it in your project it is enough to use Mockito 1.10.x or 2.0.x-beta, add `mockito-java8` as a dependency and of course compile your project with Java 8+. More details are available on the project webpage: https://github.com/szpak/mockito-java8
July 6, 2015
by Marcin Zajączkowski
· 33,750 Views · 2 Likes
article thumbnail
Migrate from Struts to Spring MVC in 6 Steps
A step-by-step guide for migrating a web application from Struts to Spring MVC, covering essential changes in libraries, configurations, and code structure.
July 6, 2015
by Das Nic
· 88,925 Views · 5 Likes
article thumbnail
JavaFX Collection's ObservableList and ObservableMap
Collections in JavaFX are defined by the javafx.collections package, which consists of the following interfaces and classes: Interfaces: ObservableList: A list that enables listeners to track changes when they occur ListChangeListener: An interface that receives notifications of changes to an ObservableList ObservableMap: A map that enables observers to track changes when they occur MapChangeListener: An interface that receives notifications of changes to an ObservableMap Classes: FXCollections: A utility class that consists of static methods that are one-to-one copies of java.util.Collections methods ListChangeListener.Change: Represents a change made to an ObservableList MapChangeListener.Change: Represents a change made to an ObservableMap Example of ObservableList Here a standard List is first created. It is then wrapped with an ObservableList. A ListChangeListener is then registered, and will receive notification whenever a change is made on the ObservableList : packageorg.attune.collection; importjava.util.List; importjava.util.ArrayList; importjavafx.collections.ObservableList; importjavafx.collections.ListChangeListener; importjavafx.collections.FXCollections; public class ObservableListDemo { public static void main(String[] args) { List list = new ArrayList(); ObservableListobservableList = FXCollections.observableList(list); observableList.addListener(new ListChangeListener() { @Override public void onChanged(ListChangeListener.Change change) { System.out.println("Detected a change! "); while (change.next()) { System.out.println("Was added? " + change.wasAdded()); System.out.println("Was removed? " + change.wasRemoved()); } } }); observableList.add("a : item one"); System.out.println("Size: " + observableList.size()+observableList.toString()); list.add("d : item two"); System.out.println("Size: " + observableList.size()+observableList.toString()); observableList.add("f : item Three"); System.out.println("Size: " + observableList.size()+observableList.toString()); list.add("b : item four"); System.out.println("Size: " + observableList.size()+observableList.toString()); observableList.remove(1); System.out.println("Size: " + observableList.size()+observableList.toString()); observableList.sort(null); System.out.println("Size: " + observableList.size()+observableList.toString()); observableList.set(2, "c : item five"); System.out.println("Size: " + observableList.size()+observableList.toString()); } } Here is output of above program: Detected a change! Was added? true Was removed? false Size: 1[a : item one] Size: 2[a : item one, d : item two] Detected a change! Was added? true Was removed? false Size: 3[a : item one, d : item two, f : item Three] Size: 4[a : item one, d : item two, f : item Three, b : item four] Detected a change! Was added? false Was removed? true Size: 3[a : item one, f : item Three, b : item four] Detected a change! Was added? false Was removed? false Size: 3[a : item one, b : item four, f : item Three] Detected a change! Was added? true Was removed? true Size: 3[a : item one, b : item four, c : item five] Example of ObservableMap package org.attune.collection; import java.util.Map; import java.util.HashMap; import javafx.collections.ObservableMap; import javafx.collections.MapChangeListener; import javafx.collections.FXCollections; public class ObservableMapDemo { public static void main(String[] args) { Map map = new HashMap(); ObservableMap observableMap = FXCollections.observableMap(map); observableMap.addListener(new MapChangeListener() { @Override public void onChanged(MapChangeListener.Change change) { System.out.println("Detected a change! "); } }); // Changes to the observableMap WILL be reported. observableMap.put("key 1","value 1"); System.out.println("Size: "+observableMap.size() + observableMap.toString()); // Changes to the underlying map will NOT be reported. map.put("key 2","value 2"); System.out.println("Size: "+observableMap.size()+ observableMap.toString()); // Changes to the observableMap WILL be reported. observableMap.remove("key 1"); System.out.println("Size: "+observableMap.size() + observableMap.toString()); } } Here is the output: Detected a change! Size: 1{key 1=value 1} Size: 2{key 2=value 2, key 1=value 1} Detected a change! Size: 1{key 2=value 2} Stay tuned for More Educational Content Attune World Wide
July 6, 2015
by Attune World Wide
· 62,972 Views · 1 Like
article thumbnail
Improve Your Tests With Mockito’s Capture
Unit Testing mandates to test the unit in isolation. In order to achieve that, the general consensus is to design our classes in a decoupled way using DI. In this paradigm, whether using a framework or not, whether using compile-time or runtime compilation, object instantiation is the responsibility of dedicated factories. In particular, this means the new keyword should be used only in those factories. Sometimes, however, having a dedicated factory just doesn’t fit. This is the case when injecting an narrow-scope instance into a wider scope instance. A use-case I stumbled upon recently concerns event bus, code like this one: public class Sample { private EventBus eventBus; public Sample(EventBus eventBus) { this.eventBus = eventBus; } public void done() { Result result = computeResult() eventBus.post(new DoneEvent(result)); } private Result computeResult() { ... } } With a runtime DI framework – such as the Spring framework, and if the DoneEvent had no argument, this could be changed to a lookup method pattern. public void done() { eventBus.post(getDoneEvent()); } public abstract DoneEvent getDoneEvent(); Unfortunately, the argument just prevents us to use this nifty trick. And it cannot be done with runtime injection anyway. It doesn’t mean the done() method shouldn’t be tested, though. The problem is not only how to assert that when the method is called, a new DoneEvent is posted in the bus, but also check the wrapped result. Experienced software engineers probably know about the Mockito.any(Class) method. This could be used like this: public void doneShouldPostDoneEvent() { EventBus eventBus = Mockito.mock(EventBus.class); Sample sample = new Sample(eventBus); sample.done(); Mockito.verify(eventBus).post(Mockito.any(DoneEvent.class)); } In this case, we make sure an event of the right kind has been posted to the queue, but we are not sure what the result was. And if the result cannot be asserted, the confidence in the code decreases. Mockito to the rescue. Mockito provides captures, that act like placeholders for parameters. The above code can be changed like this: public void doneShouldPostDoneEventWithExpectedResult() { ArgumentCaptor captor = ArgumentCaptor.forClass(DoneEvent.class); EventBus eventBus = Mockito.mock(EventBus.class); Sample sample = new Sample(eventBus); sample.done(); Mockito.verify(eventBus).post(captor.capture()); DoneEvent event = captor.getCapture(); assertThat(event.getResult(), is(expectedResult)); } At line 2, we create a new ArgumentCaptor. At line 6, We replace any() usage with captor.capture() and the trick is done. The result is then captured by Mockito and available through captor.getCapture() at line 7. The final line – using Hamcrest, makes sure the result is the expected one.
July 5, 2015
by Nicolas Fränkel
· 2,807 Views
article thumbnail
Playing with Percona XtraDB Cluster in Docker
[This article was written by Sveta Smirnova] Like any good, thus lazy, engineer I don’t like to start things manually. Creating directories, configuration files, specify paths, ports via command line is too boring. I wrote already how I survive in case when I need to start MySQL server (here). There is also the MySQL Sandbox which can be used for the same purpose. But what to do if you want to start Percona XtraDB Cluster this way? Fortunately we, at Percona, have engineers who created automation solution for starting PXC. This solution uses Docker. To explore it you need: Clone the pxc-docker repository:git clone https://github.com/percona/pxc-docker Install Docker Compose as described here cd pxc-docker/docker-bld Follow instructions from the README file: a) ./docker-gen.sh 5.6 (docker-gen.sh takes a PXC branch as argument, 5.6 is default, and it looks for it on github.com/percona/percona-xtradb-cluster) b) Optional: docker-compose build (if you see it is not updating with changes). c) docker-compose scale bootstrap=1 members=2 for a 3 node cluster Check which ports assigned to containers: $docker port dockerbld_bootstrap_1 3306 0.0.0.0:32768 $docker port dockerbld_members_1 4567 0.0.0.0:32772 $docker port dockerbld_members_2 4568 0.0.0.0:32776 Now you can connect to MySQL clients as usual: $mysql -h 0.0.0.0 -P 32768 -uroot Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 10 Server version: 5.6.21-70.1 MySQL Community Server (GPL), wsrep_25.8.rXXXX Copyright (c) 2009-2015 Percona LLC and/or its affiliates Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or 'h' for help. Type 'c' to clear the current input statement. mysql> 6. To change MySQL options either pass it as a mount at runtime with something like volume: /tmp/my.cnf:/etc/my.cnf in docker-compose.yml or connect to container’s bash (docker exec -i -t container_name /bin/bash), then change my.cnf and run docker restart container_name Notes. If you don’t want to build use ready-to-use images If you don’t want to run Docker Compose as root user add yourself to docker group
July 3, 2015
by Peter Zaitsev
· 4,928 Views
article thumbnail
The UUID Discussion
UUID really start coming in handy is when you start synchronizing data across servers.
July 3, 2015
by Lieven Doclo
· 26,836 Views
article thumbnail
Worthless features of Java - You really know
When you first learn to develop you see overly broad statements about different features to be bad, for design, performance, clarity, maintainability, it feels like a hack, or they just don't like it. In this post, I look at some of the feature people like to hate and why I think that used correctly, they should be a force for good. Features are not as yes/no, good/bad as many like to believe. Checked Exceptions I am often surprised at the degree that developers don't like to think about error handling. New developers don't even like to read error messages. It's hard work, and they complain the application crashed, "it's not working". They have no idea why the exception was thrown when often the error message and stack dump tell them exactly what went wrong if they could only see the clues. When I write out stack traces for tracing purposes, many just see the log shaped like a crash when there was no error. Reading error messages is a skill and at first it can be overwhelming. Similarly, handling exceptions in a useful manner is too often avoided. I have no idea what to do with this exception, I would rather either log the exception and pretend it didn't happen or just blow up and let the operations people or to the GUI user, who have the least ability to deal the error. Many experienced developers hate checked exceptions as a result. However, the more I hear this, the more I am glad Java has checked exception as I am convinced they really will find it too easy ignore the exceptions and just let the application die if they are not annoyed by them. Checked exceptions can be overused of course. The question should be when throwing a checked exception; do I want to annoy the developer calling the code by forcing them to think a little bit about error handling? If the answer is yes, throw a checked exception. Was Thread.currentThread().stop(e) unsafe? The method Thread.stop(Throwable) was unsafe when it could cause another thread to trigger an exception in a random section of code. This could be a checked exception in a portion of code which didn't expect it, or throw an exception which is caught in some portions of the thread but not others leaving you with no idea what it would do. However, the main reason it was unsafe is that it could leave atomic operations in as synchronized of locked section of code in an inconsistent state corrupting the memory in subtle and untestable ways. To add to the confusion, the stack trace of the Throwable didn't match the stack trace of the thread where the exception was actually thrown. But what about Thread.currentThread().stop(e)? This triggers the current thread to throw an exception on the current line. This is no worse than just using throw exception you are performing an operation the compiler can't check. These are only two worthless features but if you want to read full and detail then check Geek On Java - Hub for Android and Java
July 3, 2015
by Das Nic
· 932 Views
article thumbnail
Finding Dependency in Stored Procedure
Introduction Here in this article we are trying to discuss about the finding reference object within stored procedure and also finding the calling procedure references. Hope you like it and it will be informative. What We Want Developers are writing several stored procedure almost every day. Sometimes developers need to know about the information such as what object is used within the stored procedure or from where (SP) the specified stored procedure call. This is the vital information for the developer before working on a particular stored procedure. Here we are representing a pictorial diagram to understand the nature of implementation. Now we have to answer some question 1. What are the DB Object used in Stored Procedure1 and there type. 2. In case of Store Procedure3 which procedure calls the Store Procedure3 So we are not going to read the Stored Procedure to find the answer. Suppose the each procedure have more than 3000 line. How We Solve the Answer To solve the answer first we take the example and create an example scenario to understand it. -- Base Table CREATE TABLE T1 (EMPID INT, EMPNAME VARCHAR(50)); GO CREATE TABLE T2 (EMPID INT, EMPNAME VARCHAR(50)); GO --1 CREATE PROCEDURE [dbo].[Procedure1] AS BEGIN SELECT * FROM T1; SELECT * FROM T2; EXEC [dbo].[Procedure3]; END GO --2 CREATE PROCEDURE [dbo].[Procedure2] AS BEGIN EXEC [dbo].[Procedure3]; END GO --3 CREATE PROCEDURE [dbo].[Procedure3] AS BEGIN SELECT * FROM T1; END GO Now we are going to solve the question What are the DB Object used in Stored Procedure1 and there type. sp_depends Procedure1 In case of Store Procedure3 which procedure calls the Store Procedure3 SELECT OBJECT_NAME(id) AS [Calling SP] FROM syscomments WHERE [text] LIKE '%Procedure3%' GROUP BY OBJECT_NAME(id); Hope you like it.
July 3, 2015
by Joydeep Das
· 12,199 Views
article thumbnail
Git Workflows: The 4 Major Types
Git offers several types of workflows. Learn what they are and which type is best suited for your specific purpose.
July 3, 2015
by Madhuka Udantha
· 34,744 Views · 2 Likes
article thumbnail
Using HA-JDBC with Spring Boot
This is a really simple way to provide high-availability with failover and load balancing to any Java backend using JDBC and Spring Boot .
July 2, 2015
by Lieven Doclo
· 23,249 Views · 1 Like
article thumbnail
Escolhendo a Melhor Hospedagem de Sites
Nessa postagem vamos dar uma breve explicação de forma simples e fácil do que é o que faz um servidor de hospedagem. Hospedagem de sites nada mais é do que o disco virtual que fica online 24 horas por dia que o hospeda os arquivos do seu site, e é justamente por isso que quando você digita o domínio do site a qualquer hora do dia e da noite seu site está sempre no ar. Mas um servidor de hospedagem é muito mais do que um simples disco de armazenamento online que mantém seu site no ar. Poucas pessoas sabem, mas o uso de e-mails está vinculado ao seu serviço de hospedagem, dizemos isso por que as pessoas nunca vinculam a hospedagem com os serviços de e-mail. Enfim, saibam que sempre que contratar uma hospedagem o serviço de envio e recebimento de e-mails também está incluso no pacote. Como escolher uma excelente hospedagem de sites? Bom agora que temos noção do que é uma hospedagem de sites vamos falar sobre quais fatores devemos levar em consideração antes de contratarmos uma empresa que nos preste serviço. Começamos dizendo que preço não é tudo. Muitas pessoas acham que quanto mais cara e de melhor marca a hospedagem de sites é mais seguros estão. Isso é um erro muito comum cometido por diversos usuários novos na internet. Antes de contratar pesquise no Google os seguintes quesitos: Preço, estabilidade do servidor e velocidade e tempo de resposta. Já citamos o primeiro item, que é o preço. Um preço médio de uma boa hospedagem varia entre R$ 10,00 e R$ 30,00, mas como dissemos essa é nossa ultima preocupação, pois o mais importante são os outros fatores envolvidos na qualidade. Estabilidade do Servidor A estabilidade de um servidor de hospedagem esta diretamente ligada à quantidade de banda larga disponibilizada para o servidor que você está hospedado, isso sem contar que se junto ao seu site tiver muitos outros sites hospedados no mesmo servidor com certeza ocorreram quedas frequentes e seu site ficará fora do ar. Por isso colocamos a quantidade de sites que estarão junto ao seu como um de nossos quesitos. Contrate sempre uma hospedagem com no mínimo 100 Giga bytes de tráfego de transferência, se possível com tráfego ilimitado, mas com no mínimo 100 GB você já fica tranquilo com a estabilidade do serviço. Velocidade e Tempo de Resposta Esse é o segundo quesito mais importante em diversos aspectos. O primeiro deles é, se o tempo de carregamento de um site for lento com certeza o usuário vai procurar outro site que ofereça os mesmos serviços que o seu, então sempre consulte o tempo de resposta junto a empresa de hospedagem de sites. O tempo médio de resposta de servidores é um tempo menor que 2 segundos. Outro fator que influencia na velocidade é a localidade do servidor. Se sua empresa está no Brasil tente comprar um serviço de hospedagem onde você saiba onde está localizado o servidor. Não vá me comprar uma hospedagem na China, pois com certeza você terá problemas. A melhor opção é comprar um servidor no Brasil, onde com certeza o tempo de resposta será menor. Mas existem muitos servidores localizados nos Estados Unidos que podemos confiar fielmente. Outro aspecto importante na velocidade é que, se você planeja vender seu negócio pela busca orgânica do Google e seu tempo de resposta for maior do que 2 segundos tenha ciência que você irá perder muito posicionamento nos resultados de busca. Hoje me dia além de termos um site bem assessorado em SEO precisamos também contar um serviço que hospedagem que não nos deixe na mão. Como ultimo fator preste atenção em quantos sites estão hospedados juntos no servidor compartilhado, pois muitos sites ainda fazem muito SPAM e esses spams prejudicam a estabilidade e velocidade do servidor. Sempre ligue para a hospedagem e pergunte se no seu servidor compartilhado eles têm sites suspeitos, se tiver escolha outra empresa de hospedagem. Se tiver um dinheiro sobrando e quiser ter tranquilidade contrate uma hospedagem dedicada, onde o servidor é só seu, mas isso se seu site for daqueles que não pode ficar fora do ar de jeito nenhum, pois em muitas vezes alguns ajustes na taxa de transferência resolvem o problema.
July 2, 2015
by Raphael Acheti
· 740 Views
article thumbnail
Mapping complex JSON structures with JDK8 Nashorn
How can you map a complex JSON structure to another JSON structure in Java? I think there are a few possible solutions in Java. The first solution is to use a serialization framework like Jackson, GSON or smart-json. The mapping is a piece of awkward Java code with a lot of if-else conditions. The result is hard to test and hard to maintain. Schematic it looks like this: JSON -> Java objects -> Mapping -> Java objects -> JSON An second approach is to use a templating framwork (like Freemarker or Velocity) in combination with a serialization framwork. The logic of the mapping has moved to the template. Schematic it looks like this: JSON -> Java objects -> Apply template -> JSON One of the issues with this approach is that the template must enforce that the result is a valid JSON structure. I have tried this approach and it is really hard to produce a valid JSON structure in all use cases. You could also map your JSON to XML and create the mapping with an XSL transformations. Schematic it looks like this: JSON -> XML -> XSL transformation -> XML -> JSON But the ideal schema looks like this: JSON -> Mapping -> JSON With JDK 8 and the Nashorn Javascript engine this becomes possible! This implementation provides JSON.parse() and JSON.stringify() by default. Example Javascript: function convert(val) { var json = JSON.stringify(val); var g = JSON.parse(json); var d = { chunkId: g.chunk.id, timestamp: g.chunk.timestamp }; return JSON.stringify(d); } Java code: private ScriptEngineManager engineManager; private ScriptEngine engine; public MyConverter() { ClassPathResource resource = new ClassPathResource("/converter.js"); InputStreamReader reader = new InputStreamReader(resource.getInputStream()); engineManager = new ScriptEngineManager(); engine = engineManager.getEngineByName("nashorn"); engine.eval(reader); } public String convert(String val){ return (String) engine.eval("convert(" + source + ")"); } I think this is -at this moment- the best approach, Java 9 will ship with native JSON support. Perhaps it will become more easier in the future. More info can be found on my blog.
July 2, 2015
by Jethro Bakker
· 1,479 Views
  • Previous
  • ...
  • 783
  • 784
  • 785
  • 786
  • 787
  • 788
  • 789
  • 790
  • 791
  • 792
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×