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

Latest Articles - DZone

article thumbnail
Modern Database Design by Example
The database design task, which was once monotonous, has now become an exciting task which requires a lot of creativity.
July 6, 2015
by Anh Tuan Nguyen
· 13,306 Views · 1 Like
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,472 Views
article thumbnail
Debugging ARM Cortex-M Hard Faults with GDB Custom Command
In “A Processor Expert Component to Help with Hard Faults” I’m using a C handler with some assembly code, created with Processor Expert, to help me with debugging hard faults on ARM Cortex-M. Inspired by a GNU gdb script here, I have now an alternative way. As this approach is using the GDB command line approach, it works both with an Eclipse GUI and with using GDB in command line mode only :-). -- GDB script to debug ARM Hard Faults The idea is: Set a breakpoint in the hard fault exception handler When a hard fault occurs, the CPU will call the hard fault exception handler, and the debugger will stop the target Execute the ‘armex’ (ARM Exception) script/command in GDB to dump the stacked registers to show the program counter where the problem happened. .gdbinit Script There are several ways to extend GDB with own commands. One easy way is to add the extra functions into the .gdbinit scrip which is loaded by GDB on startup. I have added the following to my .gdbinit file to define my ‘armex’ command: define armex printf "EXEC_RETURN (LR):\n", info registers $lr if $lr & 0x4 == 0x4 printf "Uses MSP 0x%x return.\n", $MSP set $armex_base = $MSP else printf "Uses PSP 0x%x return.\n", $PSP set $armex_base = $PSP end printf "xPSR 0x%x\n", *($armex_base+28) printf "ReturnAddress 0x%x\n", *($armex_base+24) printf "LR (R14) 0x%x\n", *($armex_base+20) printf "R12 0x%x\n", *($armex_base+16) printf "R3 0x%x\n", *($armex_base+12) printf "R2 0x%x\n", *($armex_base+8) printf "R1 0x%x\n", *($armex_base+4) printf "R0 0x%x\n", *($armex_base) printf "Return instruction:\n" x/i *($armex_base+24) printf "LR instruction:\n" x/i *($armex_base+20) end document armex ARMv7 Exception entry behavior. xPSR, ReturnAddress, LR (R14), R12, R3, R2, R1, and R0 end You can place the .gdbinit file anywhere. I have it placed where my gdb is located inside the Freescale Kinetis Design Studio (C:\Freescale\KDS_3.0.0\toolchain\bin). To make sure GDB finds the .gdbinit, I specify the path to it in the Eclipse workspace preferences: -- GDB Command File in Eclipse Workspace Preferences Debugging Hard Fault To debug a hard fault, I set a breakpoint in my hard fault interrupt handler to stop the debugger when the fault happens: -- stopped on hard fault To find out where the problem occurred, I use now the ‘armex’ command in the gdb console: Use the ‘triangle’ menu of the console to switch to the arm-none-eabi-gdb view -- armex command in gdb console The armex command lists the stacked registers (same as with my handler shown in “Debugging Hard Faults on ARM Cortex-M“). The important information is either the return instruction or the LR instruction information. I can enter that address in the disassembly view to find out where the problem happened: Disassembly View of Hard Fault Reason In the above example, the LR (Link Register or Return Address) was 0xbd2 (0xbd3 with the Thumb Bit set). In the disassembly view this is the address where the handler would return to, so the problem must be just before that. Checking the assembly code there is a branch register indirect blx r3 The stacked register shows R3 0x0 Which causes the hard fault. If the problem is not that clear, then simply set a breakpoint around that location and restart the application to debug what happens before the hardfault is triggered. With this, it should be hopefully easy to find and fix the problem. Summary I have now yet another way to debug my hard faults: using my custom gdb command to dump the stacked registers. The advantage of this approach is that it does not need any additional resources on the target (no extra handler in the code and no variables), compared to my earlier solution. And the added benefit is now that I know how to extend GDB with my custom commands :-).
July 6, 2015
by Erich Styger
· 5,438 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,526 Views · 2 Likes
article thumbnail
Download and Display Image in Android GridView
This example is an improved version of my previous example Android GridView Example. Instead of using static images to display the grid items, let's make this example more realistic by downloading the data in real-time from the server and rendering the grid items. The following video depicts the output of this example. Without wasting much time, let us jump straight into what it takes to build this kind of GridView. You need to follow the following steps to complete this example. 1. Add GridView in Activity Layout First, create a new android project. For this example, I prefer to use Android Studio. Create a new layout file to your project res/layout folder and name it as activity_grid_view.xml. And add the following code blocks. The above layout is pretty straightforward. We have declared an GridView and a ProgressBar in activity layout. The progress bar will be displayed when the data is downloaded. 2. Declare GridView Item Layout Let us now add another file named grid_item_layout.xml to res/layout folder. This layout will be used by a custom grid adapter for laying out individual grid items. For the sake of simplicity, we are adding an ImageView and a TextView. 3. Adding Internet Permission You might be aware that, the Android application must declare all the permissions that are required for the application. As we need to download the data from the server, we need to add INTERNET permission. Add the following line to AndroidManifest.xml the file. Notice that we have also declared all the activities used in the application. 4. Adding Picasso Image Downloading Library Android open-source developer community brings some interesting libraries that can be integrated easily into Android applications. They serve a great deal of purpose and save a lot of time. Here in this example, I am talking about Picasso the image-loading library. We will add the Picasso library for downloading and caching images. Visit here to learn more about how to use the Picasso library on Android. You can add the Picasso library by adding the following dependency to the build.gradle file. dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:21.0.3' compile 'com.squareup.picasso:picasso:2.5.2' } 5. Create a GridView Custom Adapter A grid view is an adapter view. It requires an adapter to render the collection of data items. Add a new class named GridViewAdapter.java to your project and add the following code snippets. package com.javatechig.gridviewexample; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; public class GridViewAdapter extends ArrayAdapter { private Context mContext; private int layoutResourceId; private ArrayList mGridData = new ArrayList(); public GridViewAdapter(Context mContext, int layoutResourceId, ArrayList mGridData) { super(mContext, layoutResourceId, mGridData); this.layoutResourceId = layoutResourceId; this.mContext = mContext; this.mGridData = mGridData; } /** * Updates grid data and refresh grid items. * @param mGridData */ public void setGridData(ArrayList mGridData) { this.mGridData = mGridData; notifyDataSetChanged(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; ViewHolder holder; if (row == null) { LayoutInflater inflater = ((Activity) mContext).getLayoutInflater(); row = inflater.inflate(layoutResourceId, parent, false); holder = new ViewHolder(); holder.titleTextView = (TextView) row.findViewById(R.id.grid_item_title); holder.imageView = (ImageView) row.findViewById(R.id.grid_item_image); row.setTag(holder); } else { holder = (ViewHolder) row.getTag(); } GridItem item = mGridData.get(position); holder.titleTextView.setText(Html.fromHtml(item.getTitle())); Picasso.with(mContext).load(item.getImage()).into(holder.imageView); return row; } static class ViewHolder { TextView titleTextView; ImageView imageView; } } Notice the following in the above code snippets, The setGridData() method updates the data display on GridView. The Picasso.with().load() the method is used to download the image from the URL and display it on the image view. The GridViewAdapter class constructor requires the id of the grid item layout and the list of data to operate on. You might be surprised, where the GridItem class came from. It's not magic, we need to add GridItem.java class to our project. The GridItem class looks as follows. 6. Download Data and Hook it to the Activity Now we will be heading towards hooking the adapter to GridView and making it functional. Create a new Java class and name it as GridViewActivity.java and perform the following steps. Override the onCreate() method and set the layout by calling setContentView() method Initialize the GridView and ProgressBar components by using their declared layout id. Initialize the CustomGridView adapter bypassing the grid row layout id and the list of GridItem objects. Use AsyncTask to download data from the server, once the download is successful read the stream JSON response. Parse the JSON string into the list of GridItem objects. Once downloading and parsing is completed, in onPostExecute() callback update the UI elements. The following code does all the above steps as described. Add the following code to GridViewActivity class. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ProgressBar; import android.widget.Toast; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class GridViewActivity extends ActionBarActivity { private static final String TAG = GridViewActivity.class.getSimpleName(); private GridView mGridView; private ProgressBar mProgressBar; private GridViewAdapter mGridAdapter; private ArrayList mGridData; private String FEED_URL = "http://javatechig.com/?json=get_recent_posts&count=45"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gridview); mGridView = (GridView) findViewById(R.id.gridView); mProgressBar = (ProgressBar) findViewById(R.id.progressBar); //Initialize with empty data mGridData = new ArrayList<>(); mGridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout, mGridData); mGridView.setAdapter(mGridAdapter); //Start download new AsyncHttpTask().execute(FEED_URL); mProgressBar.setVisibility(View.VISIBLE); } //Downloading data asynchronously public class AsyncHttpTask extends AsyncTask { @Override protected Integer doInBackground(String... params) { Integer result = 0; try { // Create Apache HttpClient HttpClient httpclient = new DefaultHttpClient(); HttpResponse httpResponse = httpclient.execute(new HttpGet(params[0])); int statusCode = httpResponse.getStatusLine().getStatusCode(); // 200 represents HTTP OK if (statusCode == 200) { String response = streamToString(httpResponse.getEntity().getContent()); parseResult(response); result = 1; // Successful } else { result = 0; //"Failed } } catch (Exception e) { Log.d(TAG, e.getLocalizedMessage()); } return result; } @Override protected void onPostExecute(Integer result) { // Download complete. Let us update UI if (result == 1) { mGridAdapter.setGridData(mGridData); } else { Toast.makeText(GridViewActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show(); } mProgressBar.setVisibility(View.GONE); } } String streamToString(InputStream stream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream)); String line; String result = ""; while ((line = bufferedReader.readLine()) != null) { result += line; } // Close stream if (null != stream) { stream.close(); } return result; } /** * Parsing the feed results and get the list * @param result */ private void parseResult(String result) { try { JSONObject response = new JSONObject(result); JSONArray posts = response.optJSONArray("posts"); GridItem item; for (int i = 0; i < posts.length(); i++) { JSONObject post = posts.optJSONObject(i); String title = post.optString("title"); item = new GridItem(); item.setTitle(title); JSONArray attachments = post.getJSONArray("attachments"); if (null != attachments && attachments.length() > 0) { JSONObject attachment = attachments.getJSONObject(0); if (attachment != null) item.setImage(attachment.getString("url")); } mGridData.add(item); } } catch (JSONException e) { e.printStackTrace(); } } } At this point, you will be able to run the app and notice that the app will download the data from the server and display it on GridView. 7. Handle GridView Click Event Right now GridView is not responding to user clicks. Let us make it more functional by adding the following code. mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { //Get item at position GridItem item = (GridItem) parent.getItemAtPosition(position); //Pass the image title and url to DetailsActivity Intent intent = new Intent(GridViewActivity.this, DetailsActivity.class); intent.putExtra("title", item.getTitle()); intent.putExtra("image", item.getImage()); //Start details activity startActivity(intent); } }); When a user clicks on a grid item, we will start another activity that displays the full-screen image. You can start one activity from another by calling startActivity() method. We need to pass the details of the item such as the title, and image URL for displaying it on DetailsActivity. 8. Create Details Activity Layout Add a new layout file to res/layout directory, and name it as activity_details_view.xml and add the following code snippets. 9. Completing the Details Activity The DetailsActivity retrieves the details passed from GridViewActivity and renders the details on the screen. Create a new class named DetailsActivity and add the following code snippets. package com.javatechig.gridviewexample; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.text.Html; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; public class DetailsActivity extends ActionBarActivity { private TextView titleTextView; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details_view); ActionBar actionBar = getSupportActionBar(); actionBar.hide(); String title = getIntent().getStringExtra("title"); String image = getIntent().getStringExtra("image"); titleTextView = (TextView) findViewById(R.id.title); imageView = (ImageView) findViewById(R.id.grid_item_image); titleTextView.setText(Html.fromHtml(title)); Picasso.with(this).load(image).into(imageView); } } 10. Download the Complete Example Download from GitHub. 11. Custom Activity Transition in GridView Continue reading in our next tutorial.
July 6, 2015
by Nilanchala Panigrahy
· 43,553 Views · 1 Like
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,784 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
· 89,030 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
· 63,016 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,820 Views
article thumbnail
Microservices Design Principles
Get a crash course in understanding microservices and the difficulties in implementing them.
July 5, 2015
by Saravanan Subramanian
· 62,521 Views · 10 Likes
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,943 Views
article thumbnail
Recycling Wastewater: How It Save Manufacturers Money
Regardless of a manufacturer's altruistic goals to reduce their impact on water resources, they have to juggle them with daily operations in a cost-effective way. The reality of implementing industrial water recycling equipment comes down to dollars-and sense. Many manufacturers find their return on investment to be well worth the capital expense. They find savings on water purchases, water treatment, and costs associated with discharge permits and compliance infractions. These savings can actually lower overall operating costs. Cost Savings: Purchasing Water Manufacturers actually buy the same water back from the city after discharging it. If they recycle this water instead, they can eliminate the repeated steps of discharging and purchasing again. The volume that is purchased at a time is greatly reduced and so is the frequency of discharging. The can remove a significant strain on the public treatment facility (POTW). More importantly, it cuts down on water costs. Cost Savings: Pretreatment A lot of facilities require pretreatment of the incoming city water before it can be used in their facility. Water treatment systems require consumables such as chemicals and filters in addition to resources to operate it. These are ongoing costs on top of purchasing the water. Recycled water is a higher quality than city water, in most cases; sore using that water can actually eliminate the pretreatment step and associated costs. Cost Savings: Permits and Non-Compliance Facilities who do not meet their discharge permits can face fines and even litigation, costing them more money related to their wastewater and potentially damaging their reputation in their community and market. That can impact the bottom line. Recycling wastewater reduces significantly the risk of discharge permit noncompliance. The concentrate from wastewater recycling equipment is also a good candidate for zero liquid discharge equipment such as evaporation or solidification. Those systems eliminate the need for a discharge permit completely. Other cost factors to consider Improved sales: While it's difficult to quantify, recycling and reusing wastewater does have a positive impact on the company's public image. Drought protection: Facilities located in a region that experiences drought should consider the financial benefits that a water recycling system offers during drought. Operations personnel: In many cases, if a facility were to adopt water recycling, they would need to hire additional personnel to operate and maintain it. That sounds like more money not savings. Depending upon the vendor, however, facilities may utilize outsourcing services. Doing so lowers the overheard cost of having an operator because the employee is contracted. Production impacts: The process of installing the new equipment should have little impact to production. Choose an end-of-pipe or add-on system. These are a practical and effective choice, offering a smaller footprint at a more digestible price--and with quaffable results. Extended equipment life: The high quality of recycled water can actually extend the life of your manufacturing and treatment equipment. That can be a huge cost savings.This can be further improved by your treatment program. Is it designed with your specific equipment in mind? Will recycling wastewater save your facility money? Do the math: Calculate what you currently spend on water related expenses. Calculate what that cost is per gallon of water used per day. Compare the costs per gallon per day with the estimated cost per gallon to treat and recycle the same water (via your prospective vendor). Remember to consider other factors that can mean added benefits of water recycling. Lacy M. Hatcher invites you to read more about industrial water solutions at http://www.prochemwater.com. When you work with ProChem Inc., your water solution is tailored to your facility's needs, providing you with results, customized support, and access to everything you need to meet your unique water goals. Article Source: http://EzineArticles.com/?expert=Lacy_M._Hatcher
July 3, 2015
by Prochem Water
· 565 Views
article thumbnail
Efficiency of the pbs kids games is incomparable
The pbs kids games are the organization of discovery and invention. These are designed by the company that is the epicenter of technology. They are presenting innovative and technical games that have vast demand in all over the world. They offer a great deal efficiency and sharp mindedness and many other items related to new technology. They have a trust worthy place in the world of fun and entertainment. The achievements of the online gaming cannot be measured in some years because they render trust and belief in the form of pbs games in the market. They love to serve humanity and kids are working happily to prosperous the human as well. They embrace new technology at every aspect to be succeeded. 1. Variety of games The good thing is that they offer a variety of games for pbs kids. These games are contributing for the good fare of the kids in terms of sharpening up their memory. The main objective behind these online games is to improve the conditions of environment and empower the mind skills of kids, in the same way. 2. Exploring the new things The central mission is obvious and simple that these pbs kids game give you the opportunity to avail us to explore and discover the new world of technology. They open the doors of opportunities and possibilities by rendering the variety of games that are based on recent technology. We are living in the world of transition so, we should change our ways as the world changes because change is the spice of life. We must need to peruse the objective of quality standards of recent technology. We have formed the light standard products in extreme innovative and unique style technology is our strategy. 3. Simple to use The simple to-utilize, the complete online interface gives clients complete control of the outline and requesting methodology from beginning to end, including content, shades, plan components, textual styles, and illustrations. Utilize an elite outline formats and realistic components to construct your item without any preparation, or transfer your own illustrations, pictures and plans. Dissimilar to most custom online gaming, you won't be hit with a setup expense. Whether you require a single game or require different online games, pbs kids games offer an extensive variety of sizes and top quality entertainment. Best of everything, you can finish your request whenever, on any day, from anyplace over the world. 4. True Source of amusement: The expert designers have a present day methodology and they design for the kids of exquisite identities. The pbs kids games guarantee you to provide complete pleasure with the immense help of efficient game that provides amusement entirely. These games are designed in the way to provide an extreme efficiency and fun to the pbs kids . It is sufficient to tell your most elevated taste and shrewdness. This online game is adequate to increase the skills and sharpen up the memory of the kids by learning new techniques. It is highly beneficial for you stay at home with the variety of these games and have great fun.
July 3, 2015
by Tayyab Mehmood
· 636 Views
article thumbnail
5 Code Snippets That WordPress Users Can Follow For Theme Customization
When it comes to modifying or extending a theme's capability, we have a tendency to use WordPress plugins to accomplish our goals. However, searching for the suitable plugin from thousands of options available to you from the WordPress Plugins Repository can turn out to be a daunting task. However, you can choose to make a few edits to your website functions that helps in customizing it in some way. For doing so, you will need to insert code snippets into your theme files. Below is a list of 5 useful code snippets that you can use to customize your WordPress theme effectively: Lessen Post Revisions WordPress comes with a feature that saves a draft of a page and post – when an article is saved. This feature helps bloggers to review the drafts containing the previous versions of their work, especially during a lost connection. However, the drafts take a lot of space in the database and as they grow in number, your site's performance will eventually degrade. To resolve this issue, it is recommended that you should set the number of revisions you would like to save in your site's database. For this purpose, simply copy and paste the following code snippet in your wp-config.php file: define('WP_POST_REVISIONS', 6); You can also choose to disable WordPress revision, using the code as follows: define('WP_POST_REVISIONS', false); Remove Links From Comments Often while providing feedback users insert links in the comments. As soon as the comments are approved and posted on your site, a link turns becomes clickable. However, spammers can exploit those links by replacing them with a link that leads to a "spammy" page. A viable alternative to avoid such situation is to add filter to keep the links added in the comments as plain text, by disabling their click-ability (as shown in the below given code): remove_filter('comment_text', 'make_clickable', 8); Empty Your Trash Folder WordPress keeps a copy of all your website posts, pages and comments that you delete. In order to delete the things permanently, you will need to go to the trash folder. While this saves you from losing your data from being lost, it consumes more memory. Though, WordPress clean up the trash automatically after 30 days, but you can reduce it by adding the below code snippet in wp-config.php file: define ('EMPTY_TRASH_DAYS', 5); // this will empty your trash after 5 days In order to optimize your database, you will need to make sure that unnecessary items are not stored in your database. For this, you can disable the trash system just add the following line of code to your wp-config.php file: define ('EMPTY_TRASH_DAYS', 0); Changing “Howdy” Text You may have stumbled upon a number of WordPress sites featuring the 'Howdy' text. If you don't want this text to appear on your site, all you need to do is to add the below given code to your functions.php file: function change_howdy($translated, $text, $domain) { if (false !== strpos($translated, 'Howdy')) return str_replace('Howdy', 'Hello', $translated); return $translated; } add_filter('gettext', 'change_howdy', 10, 3); Adding a Favicon to Your Blog Adding a favicon to your blog helps in making it a separate identity. Here's a simple code that lets you add a favicon in your site's header section. Make sure to add this code in your header.php file, or you can even add the code in your functions.php file: function blog_favicon() { echo ''; } add_action('wp_head', 'blog_favicon');Note: When developing your theme, make certain to upload the “.ico” file in your theme's root folder (i.e. the one where the blog is uploaded). Doing so, can eliminate constant worry about changing the favicon's URL. Conclusion Here's hoping that the aforementioned code snippets will help you customize your theme in an effective and quick manner. This contribution of awesome post is given Samuel Dawson- a top-notch professional in Designs2HTML Ltd a convincing markup conversion firm which involves in the process of html to wordpress with efficient tactics. Samuel also do very deep research in this field.
July 3, 2015
by Samuel Dawson
· 820 Views
article thumbnail
Good revision techniques- NCERT Solution for class 10 online
Scholar’s learning is one of the best educational web portals. The revision notes prepared is strictly according to the syllabus of the exam. The Revision Notes For Class 10 Physicsavailable over here is going to help the students score good marks in NCERT Solutions For Class 10 Chemistry. Science is one of the scoring papers in class 10. But it is not so easy to score good marks so preparation should be excellent to score in this paper. The revision notes for class 10 science would help you to add marks to your score card. A good score in exams is always appreciated by everyone and especially when you are in class 10 you need to work hard for marks since they are going to stay with you throughout your life. For few students scoring marks is not a big deal but for the others who are not so good it is a tough job. The importance of revision A lot of techniques are there to score good marks but the most important one among them is proper revision of the subject. No matter how much you study but if you will not revise you may miss out few things in your exam. So, students of class 10 must not forget to go through the Online Tuition For Class 10 Mathematics. Revision means going through the important topics and points of the subject in brief. It is not at all time consuming and it enhances the confidence among the students. The more the students revise the more confident they are while appearing for their exam NCERT Solutions For Class 10 Biology. Scoring in Science As we all know in Science, if your answers are correct you can score full marks also. Hence, work on this subject since it will help you to achieve a good percentage in your boards Online Test Practice For Class 10 Chemistry. Tips to score good marks in science: · Go through each chapter in detail while you study. · Try to understand the reasoning part. · Have proper understanding of the subject instead of memorizing the topics. · Prepare revision notes and keep revising the subject at regular intervals. How Revision Notes For Class 10 Mathematics help Revision notes serve as a boon to the students who are nervous about their exams. These notes in less time can help the students have an overview of the subject. These notes consist of the following things: · The points and topics which are important for the exam are included in these notes. · Science is all about diagrams and reasons. The Revision Notes For Class 10 Biology also include the properly labeled diagrams so that the students can revise the diagrams properly. · These notes also include the important definitions and the keywords which are important to write in the exam for scoring marks. With your revision notes in hand you do not need to open your books and read the chapters in hand. It is going to save a lot of time and energy. Taking education online Now, Revision Notes For Class 10 Geography are also available online. If the students do not have revision notes they can easily find them on the internet. The revision notes available online are: · Prepared strictly according to the syllabus of class 10 science. · Includes all the important topics to be studied. · These notes are prepared in an interesting way so that the students feel like reading them. The students can go through the online revision notes and NCERT Solutions For Class 10 Physics anytime they want. The students are going to benefit from these notes.
July 3, 2015
by Scholars Learning
· 1,678 Views
article thumbnail
Webpack Lazy Loading On Rails With CDN Support
Webpack is the best module bundler I’ve ever used. Just this week I used it to reduce the JS footprint of an app from 906KB to 87KB for mobile visitors. An 800KB difference! Webpack‘s core premise is that you can require('./foo') your JavaScripts. That sea of
July 3, 2015
by Swizec Teller
· 13,402 Views
article thumbnail
Online Designer Wedding Collection Sale Mumbai
Ninecolours.com provides latest wedding collections with an affordable price. Visit here for more update collections http://www.ninecolours.com/wedding-collection
July 3, 2015
by Nine Colours
· 785 Views
article thumbnail
Online Designer Wedding Collection Sale Mumbai
July 3, 2015
by Nine Colours
· 770 Views
article thumbnail
Exclusive Collection
TROLEE is online shopping portal based in India tendering fashion products to the customers worldwide. TROLEE offering wide range of products in the category of designer sarees, Salwar kameez, Kurtis, Exclusive Wedding Collection, Indian designer collection, Western outfits, Jeans, T-shirts, and Women’s Apparels at wholesale price in India. Metaphorically, TROLEE has been known as Shopping Paradise as customer always feel to Shop bigger than ever in each events organized by TROLEE. On each order shipping facility available free of cost in India and delivery can be done Worldwide. We have been appreciated by our customer for the Best Festival Offers and discounts with Assured Service, quality products. Just visit us trolee.com
July 3, 2015
by Kamlesh Gohil
· 998 Views
article thumbnail
Exclusive Collection
TROLEE is online shopping portal based in India tendering fashion products to the customers worldwide. TROLEE offering wide range of products in the category of designer sarees, Salwar kameez, Kurtis, Exclusive Wedding Collection, Indian designer collection, Western outfits, Jeans, T-shirts, and Women’s Apparels at wholesale price in India. Metaphorically, TROLEE has been known as Shopping Paradise as customer always feel to Shop bigger than ever in each events organized by TROLEE. On each order shipping facility available free of cost in India and delivery can be done Worldwide. We have been appreciated by our customer for the Best Festival Offers and discounts with Assured Service, quality products. Just visit us trolee.com
July 3, 2015
by Kamlesh Gohil
· 699 Views
  • Previous
  • ...
  • 1454
  • 1455
  • 1456
  • 1457
  • 1458
  • 1459
  • 1460
  • 1461
  • 1462
  • 1463
  • ...
  • 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
×