Padding Strings with format method on Java

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String s1 = sc.next();
    int x = sc.nextInt();

    PadLeft(s1);
    System.out.printf("%03d", x);
    System.out.println();

    PadRight(s1);
    System.out.printf("%03d", x);
}

private static void PadRight(String s)
{
    System.out.printf("%1$15s", s);
}

private static void PadLeft(String s)
{
    System.out.printf("%1$-15s", s);
}

15 represents the minimal width of the String

Input

Hello
12

Output

Hello          012
          Hello012

References
https://stackoverflow.com/questions/13475388/generate-fixed-length-strings-filled-with-whitespaces
http://www.rgagnon.com/javadetails/java-0448.html

How can we prevent a Service from being killed by Android

    @Override
    public void onDestroy() {

        super.onDestroy();

        Intent forceIntent=new Intent("net.pupli.monitoring.action.ForceRestart");
        sendBroadcast(forceIntent);
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {

        super.onTaskRemoved(rootIntent);

        Intent forceIntent=new Intent("net.pupli.monitoring.action.ForceRestart");
        sendBroadcast(forceIntent);
    }
public class ForceRestartReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Intent forceIntent = new Intent(context, MonitoringService.class);
            context.startService(forceIntent);
        } catch (Exception ex) {
            ex.printStackTrace();
            MyLog.ex(ex);
        }

    }
}
        <receiver
            android:name=".ForceRestartReceiver">
            <intent-filter>
                <action android:name="net.pupli.monitoring.action.ForceRestart" />
            </intent-filter>
        </receiver>

References
https://stackoverflow.com/questions/9696861/how-can-we-prevent-a-service-from-being-killed-by-os
https://stackoverflow.com/questions/8537630/trouble-broadcasting-an-intent-to-android-service-from-application-class
https://stackoverflow.com/questions/30525784/android-keep-service-running-when-app-is-killed

Configure gson in Spring using GsonHttpMessageConverter [deprecated]

WebMvcConfigurerAdapter is deprecated. As of Spring 5.0 do this, so this is not working any more and we should use Force Spring Boot to use Gson instead of Jackson

Excluding jackson from classpath

@SpringBootApplication
@EnableAutoConfiguration(exclude = { JacksonAutoConfiguration.class })
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Using java config

@Configuration
@EnableWebMvc
public class Application extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter < ? >> converters) {
        GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
        converters.add(gsonHttpMessageConverter);
    }
}

References
https://www.leveluplunch.com/java/tutorials/023-configure-integrate-gson-spring-boot/

OkHttp Post Body as JSON

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

References
https://stackoverflow.com/questions/34179922/okhttp-post-body-as-json

Sort Java Strings in a Collection using Collator

           Collections.sort(parentList, new Comparator<ListParentAdapter.Parent>() {
                @Override
                public int compare(ListParentAdapter.Parent o1, ListParentAdapter.Parent o2) {

                    //return o1.getName().compareToIgnoreCase(o2.getName());

                    Locale locale=new Locale("fa","IR");
                    Collator collator= Collator.getInstance(locale);
                    return collator.compare(o1.getName(),o2.getName());
                }
            });

References
http://tutorials.jenkov.com/java-internationalization/collator.html
https://stackoverflow.com/questions/16949074/sorting-arabic-words-in-java

Spring CORS No ‘Access-Control-Allow-Origin’ header is present

Enabling CORS for the whole application is as simple as:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

To enable CORS for the whole controller:

@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {

    @RequestMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

To enable CORS for the method:

@RestController
@RequestMapping("/account")
public class AccountController {
  @CrossOrigin
  @RequestMapping("/{id}")
  public Account retrieve(@PathVariable Long id) {
    // ...
  }
}

References
https://stackoverflow.com/questions/35091524/spring-cors-no-access-control-allow-origin-header-is-present

Java BACnet

Build.gradle

repositories {
    maven {
        url "https://maven.mangoautomation.net/repository/ias-release/"
    }
}
compile group: 'com.serotonin', name: 'bacnet4j', version: '4.0.1'

Read and Write Values

public class Main {

    private static LocalDevice localDevice;
    private static RemoteDevice remoteDevice;

    public static void main(String[] args) {
        try {

            IpNetwork network = new IpNetworkBuilder().
                    withBroadcast("192.168.1.255", 24).
                    build();

            Transport transport = new DefaultTransport(network);
            localDevice = new LocalDevice(6, transport);


            localDevice.initialize();

            remoteDevice = localDevice.getRemoteDeviceBlocking(6);

            DiscoveryUtils.getExtendedDeviceInformation(localDevice, remoteDevice);

            /*List oids = ((SequenceOf) RequestUtils.sendReadPropertyAllowNull(localDevice, remoteDevice,
                    remoteDevice.getObjectIdentifier(), PropertyIdentifier.objectList)).getValues();*/

            List<ObjectIdentifier> objectIdentifierList = new ArrayList<ObjectIdentifier>();

            /*for (Object obj : oids) {
                if (obj.getClass().equals(ObjectIdentifier.class)) {
                    ObjectIdentifier oid = (ObjectIdentifier) obj;

                    if (oid.getInstanceNumber() == 85) {
                        if (oid.getObjectType() == ObjectType.binaryOutput) {
                            objectIdentifierList.add(oid);
                        }
                    }
                }
            }*/

            ObjectIdentifier objectIdentifier = new ObjectIdentifier(ObjectType.binaryOutput, 85);
            objectIdentifierList.add(objectIdentifier);
            readPresentValues(objectIdentifierList);
            //readPresentValue(objectIdentifier);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static void readPresentValues(List<ObjectIdentifier> oids) throws BACnetException {
        PropertyReferences references = new PropertyReferences();

        for (ObjectIdentifier oid : oids) {
            references.add(oid, PropertyIdentifier.presentValue);
        }

        PropertyValues values = RequestUtils.readProperties(localDevice, remoteDevice, references, null);

        for (ObjectIdentifier oid : oids) {
            System.out.println(values.getString(oid, PropertyIdentifier.presentValue));
        }
    }

    private static void readPresentValue(ObjectIdentifier oid) throws Exception {
        ReadPropertyRequest rpr = new ReadPropertyRequest(oid,
                PropertyIdentifier.presentValue);
        ReadPropertyAck ack = (ReadPropertyAck) localDevice.send(remoteDevice, rpr);
        System.out.println("Present value: " + ack.getValue());
    }

    private static void setPresentValue(ObjectIdentifier oid, Encodable value, int priority) throws Exception {
        WritePropertyRequest wpr = new WritePropertyRequest(oid,
                PropertyIdentifier.presentValue, null, value, new UnsignedInteger(priority));
        localDevice.send(remoteDevice, wpr);
    }

    private static void getPriorityArray(ObjectIdentifier oid) throws Exception {
        ReadPropertyRequest rpr = new ReadPropertyRequest(oid,
                PropertyIdentifier.priorityArray);
        ReadPropertyAck ack = (ReadPropertyAck) localDevice.send(remoteDevice, rpr);
        System.out.println("Priority array: " + ack.getValue());
    }
}

References
https://github.com/infiniteautomation/BACnet4J
https://www.csimn.com/CSI_pages/BACnet101.html
https://github.com/openmucextensions/bacnet/wiki