/* * #%L * FlatPack Demonstration Client * %% * Copyright (C) 2012 Perka Inc. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.getperka.flatpack.demo.client; import java.math.BigDecimal; import java.net.URI; import java.util.Collections; import java.util.Map; import java.util.Random; import com.getperka.flatpack.Configuration; import com.getperka.flatpack.FlatPack; import com.getperka.flatpack.FlatPackEntity; public class DemoClient { public static void main(String[] args) throws Exception { System.exit(new DemoClient().exec() ? 0 : 1); } public boolean exec() throws Exception { /* * Configuration of a client-side FlatPack stack is very similar to the server-side * configuration. */ Configuration configuration = new Configuration() /* * The ClientTypeSource is generated by the code-gen tool and contains all of the types * generated from the ApiDescription. */ .addTypeSource(ClientTypeSource.get()) /* * Enabling this flag is usually the right choice for a client app, where old clients * talking to new servers should ignore unrecognized types in the payload (since they won't * have any property definitions of that type). */ .withIgnoreUnresolvableTypes(true) // Turning on PrettyPrint and Verbose for demonstration purposes .withPrettyPrint(true) .withVerbose(true); // This ClientApi type is generated ClientApi api = new ClientApi(FlatPack.create(configuration)); api.setServerBase(new URI("http://localhost:8080")); // A simple query for all Products. This is another generated type. for (Product product : api.productsGet().execute().getValue()) { System.out.println(product.getName() + " " + product.getPrice() + " " + product.getNotes()); } // Creating a new product is fairly straightforward Product p = new Product(); p.setName("DemoClient"); p.setNotes("Created by " + System.getProperty("user.name")); p.setPrice(BigDecimal.valueOf(new Random().nextInt(100))); FlatPackEntity<Void> returnValue = api.productsPut(Collections.singletonList(p)).execute(); // Server implementations may make ConstraintViolaions available via the extra errors map if (!returnValue.getExtraErrors().isEmpty()) { for (Map.Entry<String, String> entry : returnValue.getExtraErrors().entrySet()) { System.err.println(entry.getKey() + " : " + entry.getValue()); } } return true; } }