fbpx

Create String from an array in Java

String.join(",", collection);

The above statement uses join function within the String class to join the elements of the collection into the String. The elements are joint using the specified delimiter which is a “,” in this case.

final List<String> collection = new ArrayList<>();
collection.add("Hello");
collection.add("World");

final String joinedString = String.join(",", collection);

System.out.println(joinedString);

The above examples joins an array list collection of Strings to create a single comma delimited string.

Output

Hello,World

Integer Collection to String

The String.join function only works on String collections. However if you do happen to have a collection of Integers and need to join these integers into a single string delimited by comma, the below example shows how.

final  List<Integer> intList = new ArrayList<>();
intList.add(10);
intList.add(20);
intList.add(30);

final String joinedIntString = String.join(",", intList.stream().map(x -> "" + x).collect(Collectors.toList()));

System.out.println(joinedIntString);

Output

10,20,30

The .map function maps each Integer element into a String element simply by appending the Integer to an empty string.

 

Increase Storage Space on AIX Platform

Use the chfs command to increase, decrease or set the size of a mounted volume / file system on AIX platform.

chfs -a size=54132736 /usr

Sets the size of the /usr mount point to the specified size in bytes. The size can also specified in short form. The below command will set the size of /usr to 25 GB.

chfs -a size=25G /usr

Instead of setting the size, one can also increase the size of a mount point. The below command increases the size of /usr by 1GB

chfs -a size=+1G /usr

Just the way a size increase is possible, a size decrease is also possible. The below command decreases the size of /usr by 1GB.

chfs -a size=-1G /usr

Key Considerations

To increase the size of a file system or mount point, you must have enough disk space available on the logical volume. The operation succeeds only if the necessary disk space is available.

When decreasing the size of a file system, you must have the necessary amount of free space on the file system. What this means is if you have a 25GB file system and have 20 GB of data loaded on it, a 2GB size decrease operation would succeed to have a revised sizes of 23GB. However if you had 24GB of data on the file system, you could reduce the size by only 1GB and not by 2GB.

Read Excel sheet in Java

The example below shows opening and reading Excel documents, using Apache POI library.

File file = new File("sample.xlsx");
Workbook workbook = WorkbookFactory.create(file);

workbook.sheetIterator().forEachRemaining(sheet -> {
    for(int i = 0; i < sheet.getLastRowNum(); i++) {
        Row row = sheet.getRow(i);
        for(int j = 0; j < row.getLastCellNum(); j++) {
            Cell cell = row.getCell(j);
            System.out.println(cell.getStringCellValue());
        }
    }
});

The above example prints a string value of all cells in a sequential order, for all sheets present inside the workbook.

Maven import for Apache POI library is mentioned below. The library can be downloaded from other sources as well.

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>

The Workbook object represents a single Excel document. The Excel may contain multiple sheets within it, wherein each sheet is represented by the Sheet object.

workbook.sheetIterator().forEachRemaining(sheet -> {});

Is used to iterate over all sheets present inside the Workbook. It is possible for the Workbook to not have any sheet.

sheet.getLastRowNum();

Gets the number of rows present in the respective sheet. This value is used to iterate through all rows present in the sheet. The row count is expected to differ per sheet.

Row row = sheet.getRow(i);

Gets the complete row at the specified row index. The row indexes start from 0. A row is a collection of cells, where each cell is a column. A row does not contain data values. A Row contains cells and each Cell in the Row contains a data value.

row.getLastCellNum();

Is used to get the number of cells in the Row. Typically each row in the sheet is expected to have same number of cells. However if some rows have merged cells, the number of cells in one row maybe different than the number of cells in another row in the same sheet. It is thereby important to get the cell count for each row and then iterate through each cell in the respective row.

Cell cell = row.getCell(j);

Gets a single Cell present at position j from within the row. The cell index starts from 0.

cell.getStringCellValue();

Assuming the cell contains a String value, the same can be got by using the getStringCellValue() function on the cell object. The cell may however contain numerical data, date-time field or maybe a formula. The contents of the cell need to be picked up appropriately to prevent errors.

Access-Control-Allow-Origin setting in NodeJS

The example shows setting CORS on NodeJS Express engine based web services.

var router = express.Router();
router.options('/', function(req, res, next){

res.setHeader('Access-Control-Allow-Origin', '*');

res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');

res.setHeader('Access-Control-Allow-Credentials', false);

res.setHeader('Access-Control-Max-Age', '86400'); // 24 hours

res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');

next();

});

Add support for the options mentioned inside every service implementation. The * indicates that requests will be allowed from any originating service. Such a configuration should be used in Sandbox / Test mode only.

For production use it is recommended to allow requests from a specific domain only, as in with the below code.

res.setHeader('Access-Control-Allow-Origin', '*.mywebsite.com');

 

Reverse a Java List, Array

Since Java 8, the order of elements in a List or its subclasses such as ArrayList can be reversed using a utility function provided as part of the Collections class.

Collections.reverse(list);

The list is reversed in place, which means the elements in the list are reversed inside the same object.

Collections.reverse(array); //DOES NOT WORK!

The implementation works only on an implementation of List. However if you would like to reverse the order of elements in an Array, and would like to do so with brevity of code without being concerned about expense of the operation, then a possible solution is as follows

List<Integer> list = Arrays.asList(array);
Collections.reverse(list);
array = list.toArray(new Integer[list.size()]);

The above code converts the array to list, reverses the list and then converts the list back to array. Please avoid this if possible, and use a List throughout your program instead of using Arrays.

JSON.equals in Java to compare two JSONs

JSON.areEqual(json1,json2)

The function returns true if the two JSON’s are equals and false if they are unequal. The parameter can be a JSONObject of type org.json.JSONObject or a JSON String.

The JSON utility is available as part of BlobCity Commons

Download JAR | View Source on GitHub

com.blobcity.json.JSON.areEqual("{}", "{}"); -> true
JSON.areEqual("{\"a\": \"1\"}", "{}"); -> false

The function checks for the complete JSON. Every element of the JSON must be equal for the equals check to pass. The following gives areEquals => false

{
  "name": "Tom",
  "country": "USA"
}
{
  "name": "Tom",
  "country": "US"
}

Deeps checks are also support. Nested JSON’s must be equal for the JSON to be equal. The below 2 conditions emails the same.

areEqual => true

{
  "name": "Tom",
  "country": "USA",
  "address": {
    "line1": "Lane 1, USA"
  }
}
{
  "name": "Tom",
  "country": "USA",
  "address": {
    "line1": "Lane 1, USA"
  }
}

areEqual => false

{
  "name": "Tom",
  "country": "USA",
  "address": {
    "line1": "Lane 1, USA"
  }
}
{
  "name": "Tom",
  "country": "USA",
  "address": {
    "line1": "My lane"
  }
}

areEqual => false

{
  "name": "Tom",
  "country": "USA",
  "address": {
    "line1": "Lane 1, USA"
  }
}
{
  "name": "Tom",
  "country": "USA",
  "address": {
    "line1": "Lane 1, USA",
    "zip": "19700"
  }
}

Array comparions are also supported, and array elements must be in same order in both JSON’s for the equals to pass.

areEqual => true

{
  "name": "Tom",
  "roles": ["admin", "user"]
}
{
  "name": "Tom",
  "roles": ["admin", "user"]
}

areEqual => false

{
  "name": "Tom",
  "roles": ["user", "admin"]
}
{
  "name": "Tom",
  "roles": ["admin", "user"]
}

 

Iterate Over Keys of JSONObject – Java

JSON’s are commonly used in many Java programs, with most common libraries being org.json and com.google.gson. The examples below show how to iterate over keys of both json objects in Java 8.

With com.json.JSONObject

jsonObject.keys().forEachRemaining(key -> System.out.println(key));
jsonObject.keySet().forEach(key -> System.out.println(key));
jsonObject.keySet().parallelStream().forEach(key -> System.out.println(key));

The above methods simply iterate through all the first level keys within a JSONObject and print them to the console. The .keys() function returns an Iterator and does not support parallel execution. The .keySet() function returns a Set of the keys and maybe integrated in a single thread or in parallel.

If printing to console was the only objective, the lambda expression can be better used as

jsonObject.keySet().forEach(System.out::println);

With com.google.gson.JsonObject

jsonObject.entrySet().forEach(entry -> System.out.println(entry.getKey()));
jsonObject.entrySet().parallelStream().forEach(entry -> System.out.println(entry.getKey()));

The Google’s JsonObject implementation provides for iteration over the key-value pairs inside the JsonObject. So it is not just the key, but the value also can be obtained using a single iteration.

jsonObject.entrySet().parallelStream().forEach(entry -> {
    System.out.println(entry.getKey());
    System.out.println(entry.getValue().getAsString());
});

You will be charged on how you drive

Ever wondered that how you drive, and how much you drive could define the insurance premium for your vehicle?

Usage Based Insurance is seeing substantial adoption by insurance companies. It is changing flat rate insurance structures, with more dynamic insurance structures for your vehicles.

Usage Based Insurance systems encompass:

  1. Pay-As-You-Drive
  2. Pay-How-You-Drive
  3. Pay-As-You-Go
  4. Pay-By-Distance

Distance Analysis

Charges for your car could be based on the distance you drive. For the days or months that you are out of town and don’t use the car, you could actually land up paying near zero premiums for those months.

Behaviour Analysis

Your driving behaviour and discipline could define the insurance premium you pay. If you are rash driver, then UBI policies are not for you. But if you are in your 50s, have a car, and are a peaceful and safe driver, a UBI policy could help you save a lot of money on your premiums.

Supporting Technology

A simple electronic telematic device can be connected to your car by your insurance provider. Some cars come pre-installed with such devices, and the insurance company will accept data from such devices for setting your UBI based premiums.

Who offers this

Progressive Insurance Company and General Motors Assurance Company, started a distance linked insurance discount scheme for car owners. It used telematics that captures the distance car moved, with the insurance rate being dynamic computed, by the amount of time the car was actually running.

Who is benefited

Both customers and insurance companies are equally benefited. Customers get the option of choosing an incentive based policy. This translates to more accurately priced insurance premiums and discounts for good driving behaviour. The insurance companies are also benefited by repeating substantial returns on investments, and being able to secure a strong book of business with reduced losses.

Interesting reads & References

5 reasons why AI will not cost you your job

We have seen automation take up a lot of jobs, and AI is one of the biggest automation created by mankind.

With AI did mankind create its own killer?

The answer very definitely is a NO. The possibility of AI talking over the world and out smarting humans is very far fetched and unlikely even in the remotest of possibilities. Even if AI was built powerful enough to rule the world, why would the machines want the humans to be extinct or be ruled?

But having said that, AI can make us loose our jobs. How true is that? 

1.  AI is not intelligent enough to build itself

While AI grows to automate some of the human labour jobs, it also creates jobs for humans who will build and maintain the AI system itself. As penetration of AI increases across industries, the jobs to support the penetration also increase. Humans who would do laborious jobs would now have a revised job profile of observing the work of AI or building and improving the AI system itself.

2.  Machines need training data to learn, who produces this?

All of the AI systems need training data to learn. Yes there are unsupervised learning systems, but they are used for very specific requirements that are not widely acceptable for the jobs AI will do. Automation with AI requires a training data set to be fed to the AI system. The AI system will only be ask good as the training data provided. This creates a classic need for having the perfect training data set. Humans are the guinea pigs. They will have to produce all the training data for AI systems to learn. More so producing training data is not a one person affair, but will need thousands of people to do the same thing. This means rather than humans doing the actual laborious task, they will do the task in a controlled and recorded environment. Their movement and actions will be recorded to help machines learns.

3. Our kids will not be unemployed, they will just have different jobs than us

Evolution is inevitable and we have to embrace it. While we are building AI systems and discovering that AI can take over lot of the human jobs. We have to acknowledge that the Generation Z is grown up by seeing these technology advancements. While technology can baffle us, it is a part of life for Generation Z. If we think that the next generation will be out of jobs, that is completely wrong. They will just have different jobs, most of which they will create for themselves. Their jobs will embrace the technology advancements and will be targeted towards solving the problems that technology has not yet solved.

4. We can’t yet travel through solar systems

It is good that AI can take over most of the work we do to keep our world running. This means that humans can now work on solving problems that are not yet solved. We have travelled to the moon and that is just about how far it has ever gotten. A human on mars is still several years away. But what’s worse is travelling to other solar systems in search for life or to explore the expanse of the universe would take another 2-3 generations of research. If we get AI to run our world as we know it, then humans can spend their energies in exploring the rest of the universe out there and building technological disruptions that allow faster travel through solar systems and possibility even teleportation.

5. Humans are intelligent, machines are sudo intelligent

Machines portray intelligence, but humans have intelligence. This why intelligence of machines is called “Artificial” intelligence. We will never let machines take us over. We will just use them to make our lives simpler and help us do things that are not physically possible for humans. So the though of AI taking over our jobs is absolutely ridiculous. AI will do our jobs for us because we want it to do it. And we will want it to do our current jobs only because we found ourselves something better to do instead!

How to Dockerize an AngularJS App

Do you have an AngularJS project that you would like to build into a Docker container? If   yes, you will have to start with making a Dockerfile inside your projects base folder.

### STAGE 1: Build the AngularJS app ###

FROM node:8-alpine as builder
COPY package.json package-lock.json ./
RUN npm set progress=false && npm config set depth 0 && npm cache clean --force
RUN npm i && mkdir /ng-app && cp -R ./node_modules ./ng-app
WORKDIR /ng-app
COPY . .
## Production mode build
RUN $(npm bin)/ng build --env=staging --prod --build-optimizer


### STAGE 2: Add Nginx for hosting the AngularJS app ###

FROM nginx:1.13.3-alpine
## Removes the default nginx html files
RUN rm -rf /usr/share/nginx/html/*
COPY --from=builder /ng-app/dist /usr/share/nginx/html
CMD ["nginx", "-g", "daemon off;"]
Place the above contents in a filed called Dockerfile, and place this file in your projects base folder

Once you have the Dockerfile placed, you can use Docker itself to build the AngularJS project. You do not need to build your AngularJS project separately.

Building the Docker container

Run the following command from your project’s base folder. This is the same location as where you placed your Dockerfile.

docker build .

You can also build your container by naming and tagging it, with the following command

docker build -t blobcity/angular-app:latest .

This will create the container blobcity/angular-app with the tag latest

Running the Docker container

You can start the container using the following docker run command. When the container is started, the AngularJS app is deployed and ready to use.

docker run blobcity/angular-app:latest

If you are running this command on your own computer, then open the browser at the following URL to use your AngularJS application

http://localhost:80

If you have started the Docker container on a remote server, you will need a public IP address to that server for using your AngularJS app

http://<server-ip>:80