Java tutorial
/* * Author: Patrick Reilly <preilly@php.net> * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package me.preilly; import java.util.UUID; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.daemon.*; import com.notnoop.apns.APNS; import com.notnoop.apns.ApnsDelegate; import com.notnoop.apns.ApnsNotification; import com.notnoop.apns.ApnsService; import com.notnoop.apns.ApnsServiceBuilder; import com.notnoop.apns.DeliveryError; import com.notnoop.apns.internal.Utilities; import org.apache.commons.configuration.PropertiesConfiguration; import me.preilly.util.*; import me.preilly.Globals; import me.preilly.core.IdWorker; import me.preilly.exceptions.InvalidSystemClock; import me.preilly.exceptions.InvalidUserAgentError; /** * Generate a unique number in a push notification * */ public class SimplePush implements Daemon { private String simplePayload; private ArrayList sendingList = null; private static final Logger LOGGER = LoggerFactory.getLogger(SimplePush.class); private static String propertiesFileName; private static String environmentKey; private static String certName; private static String certPass; private static String[] args; private static SimplePush instance = null; /** * Constructor * */ public SimplePush() { } public static SimplePush getInstance() { if (instance == null) { instance = new SimplePush(); } return instance; } @Override public void init(DaemonContext dc) throws DaemonInitException { LOGGER.info("initializing got deamoncontext {}", dc); args = dc.getArguments(); } @Override public void start() throws Exception { LOGGER.info("starting simple push..."); main(args); } @Override public void stop() throws Exception { LOGGER.info("stopping simple push..."); } @Override public void destroy() { LOGGER.info("simple push done!"); } public static void main(String[] args) throws Exception { /* Parse command line arguments */ Options opt = new Options(); opt.addOption("d", false, "Debug"); opt.addOption("e", true, "Environment to run in"); opt.addOption("h", false, "Print help for this application"); BasicParser parser = new BasicParser(); CommandLine cl = parser.parse(opt, args); boolean err = false; if (cl.hasOption("e")) { environmentKey = cl.getOptionValue("e"); } if (err || cl.hasOption("h")) { HelpFormatter hf = new HelpFormatter(); hf.printHelp("java -jar SimplePush.jar -c cookie [-d -p -e [-f filename]]", opt); System.exit(0); } ConfigFactory factory = ConfigFactory.getInstance(); PropertiesConfiguration config = factory.getConfigProperties(environmentKey, propertiesFileName); Globals.getInstance(config); certName = config.getString(Const.CERT_NAME); certPass = config.getString(Const.CERT_PASSWORD); SimplePush obj = new SimplePush(); obj.pushMessage(); } public void pushMessage() { ApnsService service = null; try { InputStream certStream = this.getClass().getClassLoader().getResourceAsStream(certName); service = APNS.newService().withNoErrorDetection().withCert(certStream, certPass) .withSandboxDestination().build(); service.start(); System.out.println("Start..."); ArrayList clients = new ArrayList(); clients.add("50f10bbdea425f18b420cdc4447c8fe4a64ecfb2b9692dd5daf67d03d4558ce5"); System.out.println("Sending " + clients.size() + " messages"); try { String message = "Trulia test message with ID:" + this.generateUniqueKey(); String sound = "default"; int badge = 0; simplePayload = APNS.newPayload().alertBody(message).badge(badge).sound(sound).build(); sendingList = (ArrayList) clients.clone(); Iterator<String> iterator = sendingList.iterator(); while (iterator.hasNext()) { String token = iterator.next(); service.push(token, simplePayload); } } catch (Exception ex) { ex.printStackTrace(); } } catch (Exception ex) { // more logging ex.printStackTrace(); } finally { // check if the service was // successfull initialized and // stop it here, if it was if (service != null) { System.out.println("No more messages to send"); service.stop(); } } } public String generateUniqueKey() { SimplePush simplepush = SimplePush.getInstance(); long id = simplepush.getId("simplepush"); String s = String.valueOf(id); return s; } /** * Get a new ID and handle any thrown exceptions * * @param agent * User Agent * @return generated ID */ public Long getId(final String agent) { IdWorker idWorker = IdWorker.getInstance(1, 1); Long snowflakeId = 0L; try { snowflakeId = idWorker.getId(agent); } catch (InvalidUserAgentError e) { LOGGER.error("Invalid user agent ({})", agent); } catch (InvalidSystemClock e) { LOGGER.error("Invalid system clock", e); } return snowflakeId; } }