code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright 2012 Google 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. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE; import static com.google.android.gcm.GCMConstants.EXTRA_ERROR; import static com.google.android.gcm.GCMConstants.EXTRA_REGISTRATION_ID; import static com.google.android.gcm.GCMConstants.EXTRA_SPECIAL_MESSAGE; import static com.google.android.gcm.GCMConstants.EXTRA_TOTAL_DELETED; import static com.google.android.gcm.GCMConstants.EXTRA_UNREGISTERED; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_MESSAGE; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK; import static com.google.android.gcm.GCMConstants.VALUE_DELETED_MESSAGES; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import java.util.Random; import java.util.concurrent.TimeUnit; /** * Skeleton for application-specific {@link IntentService}s responsible for * handling communication from Google Cloud Messaging service. * <p> * The abstract methods in this class are called from its worker thread, and * hence should run in a limited amount of time. If they execute long * operations, they should spawn new threads, otherwise the worker thread will * be blocked. * <p> * Subclasses must provide a public no-arg constructor. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public abstract class GCMBaseIntentService extends IntentService { /** * Old TAG used for logging. Marked as deprecated since it should have * been private at first place. */ @Deprecated public static final String TAG = "GCMBaseIntentService"; private final GCMLogger mLogger = new GCMLogger("GCMBaseIntentService", "[" + getClass().getName() + "]: "); // wakelock private static final String WAKELOCK_KEY = "GCM_LIB"; private static PowerManager.WakeLock sWakeLock; // Java lock used to synchronize access to sWakelock private static final Object LOCK = GCMBaseIntentService.class; private final String[] mSenderIds; // instance counter private static int sCounter = 0; private static final Random sRandom = new Random(); private static final int MAX_BACKOFF_MS = (int) TimeUnit.SECONDS.toMillis(3600); // 1 hour /** * Constructor that does not set a sender id, useful when the sender id * is context-specific. * <p> * When using this constructor, the subclass <strong>must</strong> * override {@link #getSenderIds(Context)}, otherwise methods such as * {@link #onHandleIntent(Intent)} will throw an * {@link IllegalStateException} on runtime. */ protected GCMBaseIntentService() { this(getName("DynamicSenderIds"), null); } /** * Constructor used when the sender id(s) is fixed. */ protected GCMBaseIntentService(String... senderIds) { this(getName(senderIds), senderIds); } private GCMBaseIntentService(String name, String[] senderIds) { super(name); // name is used as base name for threads, etc. mSenderIds = senderIds; mLogger.log(Log.VERBOSE, "Intent service name: %s", name); } private static String getName(String senderId) { String name = "GCMIntentService-" + senderId + "-" + (++sCounter); return name; } private static String getName(String[] senderIds) { String flatSenderIds = GCMRegistrar.getFlatSenderIds(senderIds); return getName(flatSenderIds); } /** * Gets the sender ids. * * <p>By default, it returns the sender ids passed in the constructor, but * it could be overridden to provide a dynamic sender id. * * @throws IllegalStateException if sender id was not set on constructor. */ protected String[] getSenderIds(Context context) { if (mSenderIds == null) { throw new IllegalStateException("sender id not set on constructor"); } return mSenderIds; } /** * Called when a cloud message has been received. * * @param context application's context. * @param intent intent containing the message payload as extras. */ protected abstract void onMessage(Context context, Intent intent); /** * Called when the GCM server tells pending messages have been deleted * because the device was idle. * * @param context application's context. * @param total total number of collapsed messages */ protected void onDeletedMessages(Context context, int total) { } /** * Called on a registration error that could be retried. * * <p>By default, it does nothing and returns {@literal true}, but could be * overridden to change that behavior and/or display the error. * * @param context application's context. * @param errorId error id returned by the GCM service. * * @return if {@literal true}, failed operation will be retried (using * exponential backoff). */ protected boolean onRecoverableError(Context context, String errorId) { return true; } /** * Called on registration or unregistration error. * * @param context application's context. * @param errorId error id returned by the GCM service. */ protected abstract void onError(Context context, String errorId); /** * Called after a device has been registered. * * @param context application's context. * @param registrationId the registration id returned by the GCM service. */ protected abstract void onRegistered(Context context, String registrationId); /** * Called after a device has been unregistered. * * @param registrationId the registration id that was previously registered. * @param context application's context. */ protected abstract void onUnregistered(Context context, String registrationId); @Override public final void onHandleIntent(Intent intent) { try { Context context = getApplicationContext(); String action = intent.getAction(); if (action.equals(INTENT_FROM_GCM_REGISTRATION_CALLBACK)) { GCMRegistrar.setRetryBroadcastReceiver(context); handleRegistration(context, intent); } else if (action.equals(INTENT_FROM_GCM_MESSAGE)) { // checks for special messages String messageType = intent.getStringExtra(EXTRA_SPECIAL_MESSAGE); if (messageType != null) { if (messageType.equals(VALUE_DELETED_MESSAGES)) { String sTotal = intent.getStringExtra(EXTRA_TOTAL_DELETED); if (sTotal != null) { try { int total = Integer.parseInt(sTotal); mLogger.log(Log.VERBOSE, "Received notification for %d deleted" + "messages", total); onDeletedMessages(context, total); } catch (NumberFormatException e) { mLogger.log(Log.ERROR, "GCM returned invalid " + "number of deleted messages (%d)", sTotal); } } } else { // application is not using the latest GCM library mLogger.log(Log.ERROR, "Received unknown special message: %s", messageType); } } else { onMessage(context, intent); } } else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) { String packageOnIntent = intent.getPackage(); if (packageOnIntent == null || !packageOnIntent.equals( getApplicationContext().getPackageName())) { mLogger.log(Log.ERROR, "Ignoring retry intent from another package (%s)", packageOnIntent); return; } // retry last call if (GCMRegistrar.isRegistered(context)) { GCMRegistrar.internalUnregister(context); } else { String[] senderIds = getSenderIds(context); GCMRegistrar.internalRegister(context, senderIds); } } } finally { // Release the power lock, so phone can get back to sleep. // The lock is reference-counted by default, so multiple // messages are ok. // If onMessage() needs to spawn a thread or do something else, // it should use its own lock. synchronized (LOCK) { // sanity check for null as this is a public method if (sWakeLock != null) { sWakeLock.release(); } else { // should never happen during normal workflow mLogger.log(Log.ERROR, "Wakelock reference is null"); } } } } /** * Called from the broadcast receiver. * <p> * Will process the received intent, call handleMessage(), registered(), * etc. in background threads, with a wake lock, while keeping the service * alive. */ static void runIntentInService(Context context, Intent intent, String className) { synchronized (LOCK) { if (sWakeLock == null) { // This is called from BroadcastReceiver, there is no init. PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY); } } sWakeLock.acquire(); intent.setClassName(context, className); context.startService(intent); } private void handleRegistration(final Context context, Intent intent) { GCMRegistrar.cancelAppPendingIntent(); String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID); String error = intent.getStringExtra(EXTRA_ERROR); String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED); mLogger.log(Log.DEBUG, "handleRegistration: registrationId = %s, " + "error = %s, unregistered = %s", registrationId, error, unregistered); // registration succeeded if (registrationId != null) { GCMRegistrar.resetBackoff(context); GCMRegistrar.setRegistrationId(context, registrationId); onRegistered(context, registrationId); return; } // unregistration succeeded if (unregistered != null) { // Remember we are unregistered GCMRegistrar.resetBackoff(context); String oldRegistrationId = GCMRegistrar.clearRegistrationId(context); onUnregistered(context, oldRegistrationId); return; } // last operation (registration or unregistration) returned an error; // Registration failed if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) { boolean retry = onRecoverableError(context, error); if (retry) { int backoffTimeMs = GCMRegistrar.getBackoff(context); int nextAttempt = backoffTimeMs / 2 + sRandom.nextInt(backoffTimeMs); mLogger.log(Log.DEBUG, "Scheduling registration retry, backoff = %d (%d)", nextAttempt, backoffTimeMs); Intent retryIntent = new Intent(INTENT_FROM_GCM_LIBRARY_RETRY); retryIntent.setPackage(context.getPackageName()); PendingIntent retryPendingIntent = PendingIntent .getBroadcast(context, 0, retryIntent, 0); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + nextAttempt, retryPendingIntent); // Next retry should wait longer. if (backoffTimeMs < MAX_BACKOFF_MS) { GCMRegistrar.setBackoff(context, backoffTimeMs * 2); } } else { mLogger.log(Log.VERBOSE, "Not retrying failed operation"); } } else { // Unrecoverable error, notify app onError(context, error); } } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.os.Build; import android.util.Log; import java.sql.Timestamp; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Utilities for device registration. * <p> * <strong>Note:</strong> this class uses a private {@link SharedPreferences} * object to keep track of the registration token. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public final class GCMRegistrar { /** * Default lifespan (7 days) of the {@link #isRegisteredOnServer(Context)} * flag until it is considered expired. */ // NOTE: cannot use TimeUnit.DAYS because it's not available on API Level 8 public static final long DEFAULT_ON_SERVER_LIFESPAN_MS = 1000 * 3600 * 24 * 7; private static final String TAG = "GCMRegistrar"; private static final String BACKOFF_MS = "backoff_ms"; private static final String GSF_PACKAGE = "com.google.android.gsf"; private static final String PREFERENCES = "com.google.android.gcm"; private static final int DEFAULT_BACKOFF_MS = 3000; private static final String PROPERTY_REG_ID = "regId"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final String PROPERTY_ON_SERVER = "onServer"; private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME = "onServerExpirationTime"; private static final String PROPERTY_ON_SERVER_LIFESPAN = "onServerLifeSpan"; /** * {@link GCMBroadcastReceiver} instance used to handle the retry intent. * * <p> * This instance cannot be the same as the one defined in the manifest * because it needs a different permission. */ // guarded by GCMRegistrar.class private static GCMBroadcastReceiver sRetryReceiver; // guarded by GCMRegistrar.class private static Context sRetryReceiverContext; // guarded by GCMRegistrar.class private static String sRetryReceiverClassName; // guarded by GCMRegistrar.class private static PendingIntent sAppPendingIntent; /** * Checks if the device has the proper dependencies installed. * <p> * This method should be called when the application starts to verify that * the device supports GCM. * * @param context application context. * @throws UnsupportedOperationException if the device does not support GCM. */ public static void checkDevice(Context context) { int version = Build.VERSION.SDK_INT; if (version < 8) { throw new UnsupportedOperationException("Device must be at least " + "API Level 8 (instead of " + version + ")"); } PackageManager packageManager = context.getPackageManager(); try { packageManager.getPackageInfo(GSF_PACKAGE, 0); } catch (NameNotFoundException e) { throw new UnsupportedOperationException( "Device does not have package " + GSF_PACKAGE); } } /** * Checks that the application manifest is properly configured. * <p> * A proper configuration means: * <ol> * <li>It creates a custom permission called * {@code PACKAGE_NAME.permission.C2D_MESSAGE}. * <li>It defines at least one {@link BroadcastReceiver} with category * {@code PACKAGE_NAME}. * <li>The {@link BroadcastReceiver}(s) uses the * {@value com.google.android.gcm.GCMConstants#PERMISSION_GCM_INTENTS} * permission. * <li>The {@link BroadcastReceiver}(s) handles the 2 GCM intents * ({@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE} * and * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}). * </ol> * ...where {@code PACKAGE_NAME} is the application package. * <p> * This method should be used during development time to verify that the * manifest is properly set up, but it doesn't need to be called once the * application is deployed to the users' devices. * * @param context application context. * @throws IllegalStateException if any of the conditions above is not met. */ public static void checkManifest(Context context) { PackageManager packageManager = context.getPackageManager(); String packageName = context.getPackageName(); String permissionName = packageName + ".permission.C2D_MESSAGE"; // check permission try { packageManager.getPermissionInfo(permissionName, PackageManager.GET_PERMISSIONS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Application does not define permission " + permissionName); } // check receivers PackageInfo receiversInfo; try { receiversInfo = packageManager.getPackageInfo( packageName, PackageManager.GET_RECEIVERS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Could not get receivers for package " + packageName); } ActivityInfo[] receivers = receiversInfo.receivers; if (receivers == null || receivers.length == 0) { throw new IllegalStateException("No receiver for package " + packageName); } log(context, Log.VERBOSE, "number of receivers for %s: %d", packageName, receivers.length); Set<String> allowedReceivers = new HashSet<String>(); for (ActivityInfo receiver : receivers) { if (GCMConstants.PERMISSION_GCM_INTENTS.equals( receiver.permission)) { allowedReceivers.add(receiver.name); } } if (allowedReceivers.isEmpty()) { throw new IllegalStateException("No receiver allowed to receive " + GCMConstants.PERMISSION_GCM_INTENTS); } checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK); checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_MESSAGE); } private static void checkReceiver(Context context, Set<String> allowedReceivers, String action) { PackageManager pm = context.getPackageManager(); String packageName = context.getPackageName(); Intent intent = new Intent(action); intent.setPackage(packageName); List<ResolveInfo> receivers = pm.queryBroadcastReceivers(intent, PackageManager.GET_INTENT_FILTERS); if (receivers.isEmpty()) { throw new IllegalStateException("No receivers for action " + action); } log(context, Log.VERBOSE, "Found %d receivers for action %s", receivers.size(), action); // make sure receivers match for (ResolveInfo receiver : receivers) { String name = receiver.activityInfo.name; if (!allowedReceivers.contains(name)) { throw new IllegalStateException("Receiver " + name + " is not set with permission " + GCMConstants.PERMISSION_GCM_INTENTS); } } } /** * Initiate messaging registration for the current application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with * either a {@link GCMConstants#EXTRA_REGISTRATION_ID} or * {@link GCMConstants#EXTRA_ERROR}. * * @param context application context. * @param senderIds Google Project ID of the accounts authorized to send * messages to this application. * @throws IllegalStateException if device does not have all GCM * dependencies installed. */ public static void register(Context context, String... senderIds) { GCMRegistrar.resetBackoff(context); internalRegister(context, senderIds); } static void internalRegister(Context context, String... senderIds) { String flatSenderIds = getFlatSenderIds(senderIds); log(context, Log.VERBOSE, "Registering app for senders %s", flatSenderIds); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION); intent.setPackage(GSF_PACKAGE); setPackageNameExtra(context, intent); intent.putExtra(GCMConstants.EXTRA_SENDER, flatSenderIds); context.startService(intent); } /** * Unregister the application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with an * {@link GCMConstants#EXTRA_UNREGISTERED} extra. */ public static void unregister(Context context) { GCMRegistrar.resetBackoff(context); internalUnregister(context); } static void internalUnregister(Context context) { log(context, Log.VERBOSE, "Unregistering app"); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION); intent.setPackage(GSF_PACKAGE); setPackageNameExtra(context, intent); context.startService(intent); } static String getFlatSenderIds(String... senderIds) { if (senderIds == null || senderIds.length == 0) { throw new IllegalArgumentException("No senderIds"); } StringBuilder builder = new StringBuilder(senderIds[0]); for (int i = 1; i < senderIds.length; i++) { builder.append(',').append(senderIds[i]); } return builder.toString(); } /** * Clear internal resources. * * <p> * This method should be called by the main activity's {@code onDestroy()} * method. */ public static synchronized void onDestroy(Context context) { if (sRetryReceiver != null) { log(context, Log.VERBOSE, "Unregistering retry receiver"); sRetryReceiverContext.unregisterReceiver(sRetryReceiver); sRetryReceiver = null; sRetryReceiverContext = null; } } static synchronized void cancelAppPendingIntent() { if (sAppPendingIntent != null) { sAppPendingIntent.cancel(); sAppPendingIntent = null; } } private synchronized static void setPackageNameExtra(Context context, Intent intent) { if (sAppPendingIntent == null) { log(context, Log.VERBOSE, "Creating pending intent to get package name"); sAppPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(), 0); } intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT, sAppPendingIntent); } /** * Lazy initializes the {@link GCMBroadcastReceiver} instance. */ static synchronized void setRetryBroadcastReceiver(Context context) { if (sRetryReceiver == null) { if (sRetryReceiverClassName == null) { // should never happen log(context, Log.ERROR, "internal error: retry receiver class not set yet"); sRetryReceiver = new GCMBroadcastReceiver(); } else { Class<?> clazz; try { clazz = Class.forName(sRetryReceiverClassName); sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance(); } catch (Exception e) { log(context, Log.ERROR, "Could not create instance of %s. " + "Using %s directly.", sRetryReceiverClassName, GCMBroadcastReceiver.class.getName()); sRetryReceiver = new GCMBroadcastReceiver(); } } String category = context.getPackageName(); IntentFilter filter = new IntentFilter( GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY); filter.addCategory(category); log(context, Log.VERBOSE, "Registering retry receiver"); sRetryReceiverContext = context; sRetryReceiverContext.registerReceiver(sRetryReceiver, filter); } } /** * Sets the name of the retry receiver class. */ static synchronized void setRetryReceiverClassName(Context context, String className) { log(context, Log.VERBOSE, "Setting the name of retry receiver class to %s", className); sRetryReceiverClassName = className; } /** * Gets the current registration id for application on GCM service. * <p> * If result is empty, the registration has failed. * * @return registration id, or empty string if the registration is not * complete. */ public static String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); // check if app was updated; if so, it must clear registration id to // avoid a race condition if GCM sends a message int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int newVersion = getAppVersion(context); if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) { log(context, Log.VERBOSE, "App version changed from %d to %d;" + "resetting registration id", oldVersion, newVersion); clearRegistrationId(context); registrationId = ""; } return registrationId; } /** * Checks whether the application was successfully registered on GCM * service. */ public static boolean isRegistered(Context context) { return getRegistrationId(context).length() > 0; } /** * Clears the registration id in the persistence store. * * <p>As a side-effect, it also expires the registeredOnServer property. * * @param context application's context. * @return old registration id. */ static String clearRegistrationId(Context context) { setRegisteredOnServer(context, null, 0); return setRegistrationId(context, ""); } /** * Sets the registration id in the persistence store. * * @param context application's context. * @param regId registration id */ static String setRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGCMPreferences(context); String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, ""); int appVersion = getAppVersion(context); log(context, Log.VERBOSE, "Saving regId on app version %d", appVersion); Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); return oldRegistrationId; } /** * Sets whether the device was successfully registered in the server side. */ public static void setRegisteredOnServer(Context context, boolean flag) { // set the flag's expiration date long lifespan = getRegisterOnServerLifespan(context); long expirationTime = System.currentTimeMillis() + lifespan; setRegisteredOnServer(context, flag, expirationTime); } private static void setRegisteredOnServer(Context context, Boolean flag, long expirationTime) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); if (flag != null) { editor.putBoolean(PROPERTY_ON_SERVER, flag); log(context, Log.VERBOSE, "Setting registeredOnServer flag as %b until %s", flag, new Timestamp(expirationTime)); } else { log(context, Log.VERBOSE, "Setting registeredOnServer expiration to %s", new Timestamp(expirationTime)); } editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime); editor.commit(); } /** * Checks whether the device was successfully registered in the server side, * as set by {@link #setRegisteredOnServer(Context, boolean)}. * * <p>To avoid the scenario where the device sends the registration to the * server but the server loses it, this flag has an expiration date, which * is {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} by default (but can be changed * by {@link #setRegisterOnServerLifespan(Context, long)}). */ public static boolean isRegisteredOnServer(Context context) { final SharedPreferences prefs = getGCMPreferences(context); boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false); log(context, Log.VERBOSE, "Is registered on server: %b", isRegistered); if (isRegistered) { // checks if the information is not stale long expirationTime = prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1); if (System.currentTimeMillis() > expirationTime) { log(context, Log.VERBOSE, "flag expired on: %s", new Timestamp(expirationTime)); return false; } } return isRegistered; } /** * Gets how long (in milliseconds) the {@link #isRegistered(Context)} * property is valid. * * @return value set by {@link #setRegisteredOnServer(Context, boolean)} or * {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} if not set. */ public static long getRegisterOnServerLifespan(Context context) { final SharedPreferences prefs = getGCMPreferences(context); long lifespan = prefs.getLong(PROPERTY_ON_SERVER_LIFESPAN, DEFAULT_ON_SERVER_LIFESPAN_MS); return lifespan; } /** * Sets how long (in milliseconds) the {@link #isRegistered(Context)} * flag is valid. */ public static void setRegisterOnServerLifespan(Context context, long lifespan) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putLong(PROPERTY_ON_SERVER_LIFESPAN, lifespan); editor.commit(); } /** * Gets the application version. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (NameNotFoundException e) { // should never happen throw new RuntimeException("Coult not get package name: " + e); } } /** * Resets the backoff counter. * <p> * This method should be called after a GCM call succeeds. * * @param context application's context. */ static void resetBackoff(Context context) { log(context, Log.VERBOSE, "Resetting backoff"); setBackoff(context, DEFAULT_BACKOFF_MS); } /** * Gets the current backoff counter. * * @param context application's context. * @return current backoff counter, in milliseconds. */ static int getBackoff(Context context) { final SharedPreferences prefs = getGCMPreferences(context); return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS); } /** * Sets the backoff counter. * <p> * This method should be called after a GCM call fails, passing an * exponential value. * * @param context application's context. * @param backoff new backoff counter, in milliseconds. */ static void setBackoff(Context context, int backoff) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putInt(BACKOFF_MS, backoff); editor.commit(); } private static SharedPreferences getGCMPreferences(Context context) { return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); } /** * Logs a message on logcat. * * @param context application's context. * @param priority logging priority * @param template message's template * @param args list of arguments */ private static void log(Context context, int priority, String template, Object... args) { if (Log.isLoggable(TAG, priority)) { String message = String.format(template, args); Log.println(priority, TAG, "[" + context.getPackageName() + "]: " + message); } } private GCMRegistrar() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm; /** * Constants used by the GCM library. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public final class GCMConstants { /** * Intent sent to GCM to register the application. */ public static final String INTENT_TO_GCM_REGISTRATION = "com.google.android.c2dm.intent.REGISTER"; /** * Intent sent to GCM to unregister the application. */ public static final String INTENT_TO_GCM_UNREGISTRATION = "com.google.android.c2dm.intent.UNREGISTER"; /** * Intent sent by GCM indicating with the result of a registration request. */ public static final String INTENT_FROM_GCM_REGISTRATION_CALLBACK = "com.google.android.c2dm.intent.REGISTRATION"; /** * Intent used by the GCM library to indicate that the registration call * should be retried. */ public static final String INTENT_FROM_GCM_LIBRARY_RETRY = "com.google.android.gcm.intent.RETRY"; /** * Intent sent by GCM containing a message. */ public static final String INTENT_FROM_GCM_MESSAGE = "com.google.android.c2dm.intent.RECEIVE"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION} * to indicate which senders (Google API project ids) can send messages to * the application. */ public static final String EXTRA_SENDER = "sender"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION} * to get the application info. */ public static final String EXTRA_APPLICATION_PENDING_INTENT = "app"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} * to indicate that the application has been unregistered. */ public static final String EXTRA_UNREGISTERED = "unregistered"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} * to indicate an error when the registration fails. * See constants starting with ERROR_ for possible values. */ public static final String EXTRA_ERROR = "error"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} * to indicate the registration id when the registration succeeds. */ public static final String EXTRA_REGISTRATION_ID = "registration_id"; /** * Type of message present in the * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE} * intent. * This extra is only set for special messages sent from GCM, not for * messages originated from the application. */ public static final String EXTRA_SPECIAL_MESSAGE = "message_type"; /** * Special message indicating the server deleted the pending messages. */ public static final String VALUE_DELETED_MESSAGES = "deleted_messages"; /** * Number of messages deleted by the server because the device was idle. * Present only on messages of special type * {@value com.google.android.gcm.GCMConstants#VALUE_DELETED_MESSAGES} */ public static final String EXTRA_TOTAL_DELETED = "total_deleted"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE} * to indicate which sender (Google API project id) sent the message. */ public static final String EXTRA_FROM = "from"; /** * Permission necessary to receive GCM intents. */ public static final String PERMISSION_GCM_INTENTS = "com.google.android.c2dm.permission.SEND"; /** * @see GCMBroadcastReceiver */ public static final String DEFAULT_INTENT_SERVICE_CLASS_NAME = ".GCMIntentService"; /** * The device can't read the response, or there was a 500/503 from the * server that can be retried later. The application should use exponential * back off and retry. */ public static final String ERROR_SERVICE_NOT_AVAILABLE = "SERVICE_NOT_AVAILABLE"; /** * There is no Google account on the phone. The application should ask the * user to open the account manager and add a Google account. */ public static final String ERROR_ACCOUNT_MISSING = "ACCOUNT_MISSING"; /** * Bad password. The application should ask the user to enter his/her * password, and let user retry manually later. Fix on the device side. */ public static final String ERROR_AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED"; /** * The request sent by the phone does not contain the expected parameters. * This phone doesn't currently support GCM. */ public static final String ERROR_INVALID_PARAMETERS = "INVALID_PARAMETERS"; /** * The sender account is not recognized. Fix on the device side. */ public static final String ERROR_INVALID_SENDER = "INVALID_SENDER"; /** * Incorrect phone registration with Google. This phone doesn't currently * support GCM. */ public static final String ERROR_PHONE_REGISTRATION_ERROR = "PHONE_REGISTRATION_ERROR"; private GCMConstants() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm; import android.util.Log; /** * Custom logger. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated class GCMLogger { private final String mTag; // can't use class name on TAG since size is limited to 23 chars private final String mLogPrefix; GCMLogger(String tag, String logPrefix) { mTag = tag; mLogPrefix = logPrefix; } /** * Logs a message on logcat. * * @param priority logging priority * @param template message's template * @param args list of arguments */ protected void log(int priority, String template, Object... args) { if (Log.isLoggable(mTag, priority)) { String message = String.format(template, args); Log.println(priority, mTag, mLogPrefix + message); } } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * {@link BroadcastReceiver} that receives GCM messages and delivers them to * an application-specific {@link GCMBaseIntentService} subclass. * <p> * By default, the {@link GCMBaseIntentService} class belongs to the application * main package and is named * {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class, * the {@link #getGCMIntentServiceClassName(Context)} must be overridden. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public class GCMBroadcastReceiver extends BroadcastReceiver { private static boolean mReceiverSet = false; private final GCMLogger mLogger = new GCMLogger("GCMBroadcastReceiver", "[" + getClass().getName() + "]: "); @Override public final void onReceive(Context context, Intent intent) { mLogger.log(Log.VERBOSE, "onReceive: %s", intent.getAction()); // do a one-time check if app is using a custom GCMBroadcastReceiver if (!mReceiverSet) { mReceiverSet = true; GCMRegistrar.setRetryReceiverClassName(context, getClass().getName()); } String className = getGCMIntentServiceClassName(context); mLogger.log(Log.VERBOSE, "GCM IntentService class: %s", className); // Delegates to the application-specific intent service. GCMBaseIntentService.runIntentInService(context, intent, className); setResult(Activity.RESULT_OK, null /* data */, null /* extra */); } /** * Gets the class name of the intent service that will handle GCM messages. */ protected String getGCMIntentServiceClassName(Context context) { return getDefaultIntentServiceClassName(context); } /** * Gets the default class name of the intent service that will handle GCM * messages. */ static final String getDefaultIntentServiceClassName(Context context) { String className = context.getPackageName() + DEFAULT_INTENT_SERVICE_CLASS_NAME; return className; } }
Java
/** Automatically generated file. DO NOT MODIFY */ package com.google.android.gcm; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message to all registered devices. * <p> * This servlet is used just by the browser (i.e., not device). */ @SuppressWarnings("serial") public class SendAllMessagesServlet extends BaseServlet { private static final int MULTICAST_SIZE = 1000; private Sender sender; private static final Executor threadPool = Executors.newFixedThreadPool(5); @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { List<String> devices = Datastore.getDevices(); String status; if (devices.isEmpty()) { status = "Message ignored as there is no device registered!"; } else { // NOTE: check below is for demonstration purposes; a real application // could always send a multicast, even for just one recipient if (devices.size() == 1) { // send a single message using plain post String registrationId = devices.get(0); Message message = new Message.Builder().build(); Result result = sender.send(message, registrationId, 5); status = "Sent message to one device: " + result; } else { // send a multicast message using JSON // must split in chunks of 1000 devices (GCM limit) int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; int tasks = 0; for (String device : devices) { counter++; partialDevices.add(device); int partialSize = partialDevices.size(); if (partialSize == MULTICAST_SIZE || counter == total) { asyncSend(partialDevices); partialDevices.clear(); tasks++; } } status = "Asynchronously sending " + tasks + " multicast messages to " + total + " devices"; } } req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString()); getServletContext().getRequestDispatcher("/home").forward(req, resp); } private void asyncSend(List<String> partialDevices) { // make a copy final List<String> devices = new ArrayList<String>(partialDevices); threadPool.execute(new Runnable() { public void run() { Message message = new Message.Builder().build(); MulticastResult multicastResult; try { multicastResult = sender.send(message, devices, 5); } catch (IOException e) { logger.log(Level.SEVERE, "Error posting messages", e); return; } List<Result> results = multicastResult.getResults(); // analyze the results for (int i = 0; i < devices.size(); i++) { String regId = devices.get(i); Result result = results.get(i); String messageId = result.getMessageId(); if (messageId != null) { logger.fine("Succesfully sent message to device: " + regId + "; messageId = " + messageId); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { // same device has more than on registration id: update it logger.info("canonicalRegId " + canonicalRegId); Datastore.updateRegistration(regId, canonicalRegId); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it logger.info("Unregistered device: " + regId); Datastore.unregister(regId); } else { logger.severe("Error sending message to " + regId + ": " + error); } } } }}); } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is thread-safe but not persistent (it will lost the data when the * app is restarted) - it is meant just as an example. */ public final class Datastore { private static final List<String> regIds = new ArrayList<String>(); private static final Logger logger = Logger.getLogger(Datastore.class.getName()); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. */ public static void register(String regId) { logger.info("Registering " + regId); synchronized (regIds) { regIds.add(regId); } } /** * Unregisters a device. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); synchronized (regIds) { regIds.remove(regId); } } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); synchronized (regIds) { regIds.remove(oldId); regIds.add(newId); } } /** * Gets all registered devices. */ public static List<String> getDevices() { synchronized (regIds) { return new ArrayList<String>(regIds); } } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ @SuppressWarnings("serial") abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } protected boolean isEmptyOrNull(String value) { return value == null || value.trim().length() == 0; } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from a * {@value #PATH} file located in the classpath (typically under * {@code WEB-INF/classes}). */ public class ApiKeyInitializer implements ServletContextListener { static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String PATH = "/api.key"; private final Logger logger = Logger.getLogger(getClass().getName()); public void contextInitialized(ServletContextEvent event) { logger.info("Reading " + PATH + " from resources (probably from " + "WEB-INF/classes"); String key = getKey(); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, key); } /** * Gets the access key. */ protected String getKey() { InputStream stream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(PATH); if (stream == null) { throw new IllegalStateException("Could not find file " + PATH + " on web resources)"); } BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { String key = reader.readLine(); return key; } catch (IOException e) { throw new RuntimeException("Could not read file " + PATH, e); } finally { try { reader.close(); } catch (IOException e) { logger.log(Level.WARNING, "Exception closing " + PATH, e); } } } public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds display number of devices and button to send a message. * <p> * This servlet is used just by the browser (i.e., not device) and contains the * main page of the demo app. */ @SuppressWarnings("serial") public class HomeServlet extends BaseServlet { static final String ATTRIBUTE_STATUS = "status"; /** * Displays the existing messages and offer the option to send a new one. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head>"); out.print(" <title>GCM Demo</title>"); out.print(" <link rel='icon' href='favicon.png'/>"); out.print("</head>"); String status = (String) req.getAttribute(ATTRIBUTE_STATUS); if (status != null) { out.print(status); } List<String> devices = Datastore.getDevices(); if (devices.isEmpty()) { out.print("<h2>No devices registered!</h2>"); } else { out.print("<h2>" + devices.size() + " device(s) registered!</h2>"); out.print("<form name='form' method='POST' action='sendAll'>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); } out.print("</body></html>"); resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.DISPLAY_MESSAGE_ACTION; import static com.google.android.gcm.demo.app.CommonUtilities.EXTRA_MESSAGE; import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID; import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL; import com.google.android.gcm.GCMRegistrar; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; /** * Main UI for the demo app. */ public class DemoActivity extends Activity { TextView mDisplay; AsyncTask<Void, Void, Void> mRegisterTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkNotNull(SERVER_URL, "SERVER_URL"); checkNotNull(SENDER_ID, "SENDER_ID"); // Make sure the device has the proper dependencies. GCMRegistrar.checkDevice(this); // Make sure the manifest was properly set - comment out this line // while developing the app, then uncomment it when it's ready. GCMRegistrar.checkManifest(this); setContentView(R.layout.main); mDisplay = (TextView) findViewById(R.id.display); registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION)); final String regId = GCMRegistrar.getRegistrationId(this); if (regId.equals("")) { // Automatically registers application on startup. GCMRegistrar.register(this, SENDER_ID); } else { // Device is already registered on GCM, check server. if (GCMRegistrar.isRegisteredOnServer(this)) { // Skips registration. mDisplay.append(getString(R.string.already_registered) + "\n"); } else { // Try to register again, but not in the UI thread. // It's also necessary to cancel the thread onDestroy(), // hence the use of AsyncTask instead of a raw thread. final Context context = this; mRegisterTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { ServerUtilities.register(context, regId); return null; } @Override protected void onPostExecute(Void result) { mRegisterTask = null; } }; mRegisterTask.execute(null, null, null); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { /* * Typically, an application registers automatically, so options * below are disabled. Uncomment them if you want to manually * register or unregister the device (you will also need to * uncomment the equivalent options on options_menu.xml). */ /* case R.id.options_register: GCMRegistrar.register(this, SENDER_ID); return true; case R.id.options_unregister: GCMRegistrar.unregister(this); return true; */ case R.id.options_clear: mDisplay.setText(null); return true; case R.id.options_exit: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onDestroy() { if (mRegisterTask != null) { mRegisterTask.cancel(true); } unregisterReceiver(mHandleMessageReceiver); GCMRegistrar.onDestroy(this); super.onDestroy(); } private void checkNotNull(Object reference, String name) { if (reference == null) { throw new NullPointerException( getString(R.string.error_config, name)); } } private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String newMessage = intent.getExtras().getString(EXTRA_MESSAGE); mDisplay.append(newMessage + "\n"); } }; }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL; import static com.google.android.gcm.demo.app.CommonUtilities.TAG; import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage; import com.google.android.gcm.GCMRegistrar; import android.content.Context; import android.util.Log; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; /** * Helper class used to communicate with the demo server. */ public final class ServerUtilities { private static final int MAX_ATTEMPTS = 5; private static final int BACKOFF_MILLI_SECONDS = 2000; private static final Random random = new Random(); /** * Register this account/device pair within the server. * */ static void register(final Context context, final String regId) { Log.i(TAG, "registering device (regId = " + regId + ")"); String serverUrl = SERVER_URL + "/register"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); // Once GCM returns a registration id, we need to register it in the // demo server. As the server might be down, we will retry it a couple // times. for (int i = 1; i <= MAX_ATTEMPTS; i++) { Log.d(TAG, "Attempt #" + i + " to register"); try { displayMessage(context, context.getString( R.string.server_registering, i, MAX_ATTEMPTS)); post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, true); String message = context.getString(R.string.server_registered); CommonUtilities.displayMessage(context, message); return; } catch (IOException e) { // Here we are simplifying and retrying on any error; in a real // application, it should retry only on unrecoverable errors // (like HTTP error code 503). Log.e(TAG, "Failed to register on attempt " + i + ":" + e); if (i == MAX_ATTEMPTS) { break; } try { Log.d(TAG, "Sleeping for " + backoff + " ms before retry"); Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. Log.d(TAG, "Thread interrupted: abort remaining retries!"); Thread.currentThread().interrupt(); return; } // increase backoff exponentially backoff *= 2; } } String message = context.getString(R.string.server_register_error, MAX_ATTEMPTS); CommonUtilities.displayMessage(context, message); } /** * Unregister this account/device pair within the server. */ static void unregister(final Context context, final String regId) { Log.i(TAG, "unregistering device (regId = " + regId + ")"); String serverUrl = SERVER_URL + "/unregister"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); try { post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, false); String message = context.getString(R.string.server_unregistered); CommonUtilities.displayMessage(context, message); } catch (IOException e) { // At this point the device is unregistered from GCM, but still // registered in the server. // We could try to unregister again, but it is not necessary: // if the server tries to send a message to the device, it will get // a "NotRegistered" error message and should unregister the device. String message = context.getString(R.string.server_unregister_error, e.getMessage()); CommonUtilities.displayMessage(context, message); } } /** * Issue a POST request to the server. * * @param endpoint POST address. * @param params request parameters. * * @throws IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=') .append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); Log.v(TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.app; import android.content.Context; import android.content.Intent; /** * Helper class providing methods and constants common to other classes in the * app. */ public final class CommonUtilities { /** * Base URL of the Demo Server (such as http://my_host:8080/gcm-demo) */ static final String SERVER_URL = null; /** * Google API project id registered to use GCM. */ static final String SENDER_ID = null; /** * Tag used on log messages. */ static final String TAG = "GCMDemo"; /** * Intent used to display a message in the screen. */ static final String DISPLAY_MESSAGE_ACTION = "com.google.android.gcm.demo.app.DISPLAY_MESSAGE"; /** * Intent's extra that contains the message to be displayed. */ static final String EXTRA_MESSAGE = "message"; /** * Notifies UI to display a message. * <p> * This method is defined in the common helper because it's used both by * the UI and the background service. * * @param context application's context. * @param message message to be displayed. */ static void displayMessage(Context context, String message) { Intent intent = new Intent(DISPLAY_MESSAGE_ACTION); intent.putExtra(EXTRA_MESSAGE, message); context.sendBroadcast(intent); } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID; import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; import com.google.android.gcm.GCMBaseIntentService; /** * IntentService responsible for handling GCM messages. */ public class GCMIntentService extends GCMBaseIntentService { @SuppressWarnings("hiding") private static final String TAG = "GCMIntentService"; public GCMIntentService() { super(SENDER_ID); } @Override protected void onRegistered(Context context, String registrationId) { Log.i(TAG, "Device registered: regId = " + registrationId); displayMessage(context, getString(R.string.gcm_registered, registrationId)); ServerUtilities.register(context, registrationId); } @Override protected void onUnregistered(Context context, String registrationId) { Log.i(TAG, "Device unregistered"); displayMessage(context, getString(R.string.gcm_unregistered)); ServerUtilities.unregister(context, registrationId); } @Override protected void onMessage(Context context, Intent intent) { Log.i(TAG, "Received message. Extras: " + intent.getExtras()); String message = getString(R.string.gcm_message); displayMessage(context, message); // notifies user generateNotification(context, message); } @Override protected void onDeletedMessages(Context context, int total) { Log.i(TAG, "Received deleted messages notification"); String message = getString(R.string.gcm_deleted, total); displayMessage(context, message); // notifies user generateNotification(context, message); } @Override public void onError(Context context, String errorId) { Log.i(TAG, "Received error: " + errorId); displayMessage(context, getString(R.string.gcm_error, errorId)); } @Override protected boolean onRecoverableError(Context context, String errorId) { // log message Log.i(TAG, "Received recoverable error: " + errorId); displayMessage(context, getString(R.string.gcm_recoverable_error, errorId)); return super.onRecoverableError(context, errorId); } /** * Issues a notification to inform the user that server has sent a message. */ private static void generateNotification(Context context, String message) { int icon = R.drawable.ic_stat_gcm; long when = System.currentTimeMillis(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(icon, message, when); String title = context.getString(R.string.app_name); Intent notificationIntent = new Intent(context, DemoActivity.class); // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, title, message, intent); notification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, notification); } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message to all registered devices. * <p> * This servlet is used just by the browser (i.e., not device). */ @SuppressWarnings("serial") public class SendAllMessagesServlet extends BaseServlet { /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { List<String> devices = Datastore.getDevices(); String status; if (devices.isEmpty()) { status = "Message ignored as there is no device registered!"; } else { Queue queue = QueueFactory.getQueue("gcm"); // NOTE: check below is for demonstration purposes; a real application // could always send a multicast, even for just one recipient if (devices.size() == 1) { // send a single message using plain post String device = devices.get(0); queue.add(withUrl("/send").param( SendMessageServlet.PARAMETER_DEVICE, device)); status = "Single message queued for registration id " + device; } else { // send a multicast message using JSON // must split in chunks of 1000 devices (GCM limit) int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; int tasks = 0; for (String device : devices) { counter++; partialDevices.add(device); int partialSize = partialDevices.size(); if (partialSize == Datastore.MULTICAST_SIZE || counter == total) { String multicastKey = Datastore.createMulticast(partialDevices); logger.fine("Queuing " + partialSize + " devices on multicast " + multicastKey); TaskOptions taskOptions = TaskOptions.Builder .withUrl("/send") .param(SendMessageServlet.PARAMETER_MULTICAST, multicastKey) .method(Method.POST); queue.add(taskOptions); partialDevices.clear(); tasks++; } } status = "Queued tasks to send " + tasks + " multicast messages to " + total + " devices"; } } req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString()); getServletContext().getRequestDispatcher("/home").forward(req, resp); } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that sends a message to a device. * <p> * This servlet is invoked by AppEngine's Push Queue mechanism. */ @SuppressWarnings("serial") public class SendMessageServlet extends BaseServlet { private static final String HEADER_QUEUE_COUNT = "X-AppEngine-TaskRetryCount"; private static final String HEADER_QUEUE_NAME = "X-AppEngine-QueueName"; private static final int MAX_RETRY = 3; static final String PARAMETER_DEVICE = "device"; static final String PARAMETER_MULTICAST = "multicastKey"; private Sender sender; @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Indicates to App Engine that this task should be retried. */ private void retryTask(HttpServletResponse resp) { resp.setStatus(500); } /** * Indicates to App Engine that this task is done. */ private void taskDone(HttpServletResponse resp) { resp.setStatus(200); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (req.getHeader(HEADER_QUEUE_NAME) == null) { throw new IOException("Missing header " + HEADER_QUEUE_NAME); } String retryCountHeader = req.getHeader(HEADER_QUEUE_COUNT); logger.fine("retry count: " + retryCountHeader); if (retryCountHeader != null) { int retryCount = Integer.parseInt(retryCountHeader); if (retryCount > MAX_RETRY) { logger.severe("Too many retries, dropping task"); taskDone(resp); return; } } String regId = req.getParameter(PARAMETER_DEVICE); if (regId != null) { sendSingleMessage(regId, resp); return; } String multicastKey = req.getParameter(PARAMETER_MULTICAST); if (multicastKey != null) { sendMulticastMessage(multicastKey, resp); return; } logger.severe("Invalid request!"); taskDone(resp); return; } private Message createMessage() { Message message = new Message.Builder().build(); return message; } private void sendSingleMessage(String regId, HttpServletResponse resp) { logger.info("Sending message to device " + regId); Message message = createMessage(); Result result; try { result = sender.sendNoRetry(message, regId); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); taskDone(resp); return; } if (result == null) { retryTask(resp); return; } if (result.getMessageId() != null) { logger.info("Succesfully sent message to device " + regId); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { // same device has more than on registration id: update it logger.finest("canonicalRegId " + canonicalRegId); Datastore.updateRegistration(regId, canonicalRegId); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } else { logger.severe("Error sending message to device " + regId + ": " + error); } } } private void sendMulticastMessage(String multicastKey, HttpServletResponse resp) { // Recover registration ids from datastore List<String> regIds = Datastore.getMulticast(multicastKey); Message message = createMessage(); MulticastResult multicastResult; try { multicastResult = sender.sendNoRetry(message, regIds); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); multicastDone(resp, multicastKey); return; } boolean allDone = true; // check if any registration id must be updated if (multicastResult.getCanonicalIds() != 0) { List<Result> results = multicastResult.getResults(); for (int i = 0; i < results.size(); i++) { String canonicalRegId = results.get(i).getCanonicalRegistrationId(); if (canonicalRegId != null) { String regId = regIds.get(i); Datastore.updateRegistration(regId, canonicalRegId); } } } if (multicastResult.getFailure() != 0) { // there were failures, check if any could be retried List<Result> results = multicastResult.getResults(); List<String> retriableRegIds = new ArrayList<String>(); for (int i = 0; i < results.size(); i++) { String error = results.get(i).getErrorCodeName(); if (error != null) { String regId = regIds.get(i); logger.warning("Got error (" + error + ") for regId " + regId); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } if (error.equals(Constants.ERROR_UNAVAILABLE)) { retriableRegIds.add(regId); } } } if (!retriableRegIds.isEmpty()) { // update task Datastore.updateMulticast(multicastKey, retriableRegIds); allDone = false; retryTask(resp); } } if (allDone) { multicastDone(resp, multicastKey); } else { retryTask(resp); } } private void multicastDone(HttpServletResponse resp, String encodedKey) { Datastore.deleteMulticast(encodedKey); taskDone(resp); } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Transaction; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is neither persistent (it will lost the data when the app is * restarted) nor thread safe. */ public final class Datastore { static final int MULTICAST_SIZE = 1000; private static final String DEVICE_TYPE = "Device"; private static final String DEVICE_REG_ID_PROPERTY = "regId"; private static final String MULTICAST_TYPE = "Multicast"; private static final String MULTICAST_REG_IDS_PROPERTY = "regIds"; private static final FetchOptions DEFAULT_FETCH_OPTIONS = FetchOptions.Builder .withPrefetchSize(MULTICAST_SIZE).chunkSize(MULTICAST_SIZE); private static final Logger logger = Logger.getLogger(Datastore.class.getName()); private static final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. * * @param regId device's registration id. */ public static void register(String regId) { logger.info("Registering " + regId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity != null) { logger.fine(regId + " is already registered; ignoring."); return; } entity = new Entity(DEVICE_TYPE); entity.setProperty(DEVICE_REG_ID_PROPERTY, regId); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Unregisters a device. * * @param regId device's registration id. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity == null) { logger.warning("Device " + regId + " already unregistered"); } else { Key key = entity.getKey(); datastore.delete(key); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(oldId); if (entity == null) { logger.warning("No device for registration id " + oldId); return; } entity.setProperty(DEVICE_REG_ID_PROPERTY, newId); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Gets all registered devices. */ public static List<String> getDevices() { List<String> devices; Transaction txn = datastore.beginTransaction(); try { Query query = new Query(DEVICE_TYPE); Iterable<Entity> entities = datastore.prepare(query).asIterable(DEFAULT_FETCH_OPTIONS); devices = new ArrayList<String>(); for (Entity entity : entities) { String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY); devices.add(device); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return devices; } /** * Gets the number of total devices. */ public static int getTotalDevices() { Transaction txn = datastore.beginTransaction(); try { Query query = new Query(DEVICE_TYPE).setKeysOnly(); List<Entity> allKeys = datastore.prepare(query).asList(DEFAULT_FETCH_OPTIONS); int total = allKeys.size(); logger.fine("Total number of devices: " + total); txn.commit(); return total; } finally { if (txn.isActive()) { txn.rollback(); } } } private static Entity findDeviceByRegId(String regId) { Query query = new Query(DEVICE_TYPE) .addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId); PreparedQuery preparedQuery = datastore.prepare(query); List<Entity> entities = preparedQuery.asList(DEFAULT_FETCH_OPTIONS); Entity entity = null; if (!entities.isEmpty()) { entity = entities.get(0); } int size = entities.size(); if (size > 0) { logger.severe( "Found " + size + " entities for regId " + regId + ": " + entities); } return entity; } /** * Creates a persistent record with the devices to be notified using a * multicast message. * * @param devices registration ids of the devices. * @return encoded key for the persistent record. */ public static String createMulticast(List<String> devices) { logger.info("Storing multicast for " + devices.size() + " devices"); String encodedKey; Transaction txn = datastore.beginTransaction(); try { Entity entity = new Entity(MULTICAST_TYPE); entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); datastore.put(entity); Key key = entity.getKey(); encodedKey = KeyFactory.keyToString(key); logger.fine("multicast key: " + encodedKey); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return encodedKey; } /** * Gets a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. */ public static List<String> getMulticast(String encodedKey) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = datastore.beginTransaction(); try { entity = datastore.get(key); @SuppressWarnings("unchecked") List<String> devices = (List<String>) entity.getProperty(MULTICAST_REG_IDS_PROPERTY); txn.commit(); return devices; } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return Collections.emptyList(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. * @param devices new list of registration ids of the devices. */ public static void updateMulticast(String encodedKey, List<String> devices) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = datastore.beginTransaction(); try { try { entity = datastore.get(key); } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return; } entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Deletes a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. */ public static void deleteMulticast(String encodedKey) { Transaction txn = datastore.beginTransaction(); try { Key key = KeyFactory.stringToKey(encodedKey); datastore.delete(key); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ @SuppressWarnings("serial") abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } protected boolean isEmptyOrNull(String value) { return value == null || value.trim().length() == 0; } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from the App Engine datastore. */ public class ApiKeyInitializer implements ServletContextListener { static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String ENTITY_KIND = "Settings"; private static final String ENTITY_KEY = "MyKey"; private static final String ACCESS_KEY_FIELD = "ApiKey"; private final Logger logger = Logger.getLogger(getClass().getName()); public void contextInitialized(ServletContextEvent event) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); Entity entity; try { entity = datastore.get(key); } catch (EntityNotFoundException e) { entity = new Entity(key); // NOTE: it's not possible to change entities in the local server, so // it will be necessary to hardcode the API key below if you are running // it locally. entity.setProperty(ACCESS_KEY_FIELD, "replace_this_text_by_your_Simple_API_Access_key"); datastore.put(entity); logger.severe("Created fake key. Please go to App Engine admin " + "console, change its value to your API Key (the entity " + "type is '" + ENTITY_KIND + "' and its field to be changed is '" + ACCESS_KEY_FIELD + "'), then restart the server!"); } String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey); } public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 2012 Google 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. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds display number of devices and button to send a message. * <p> * This servlet is used just by the browser (i.e., not device) and contains the * main page of the demo app. */ @SuppressWarnings("serial") public class HomeServlet extends BaseServlet { static final String ATTRIBUTE_STATUS = "status"; /** * Displays the existing messages and offer the option to send a new one. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head>"); out.print(" <title>GCM Demo</title>"); out.print(" <link rel='icon' href='favicon.png'/>"); out.print("</head>"); String status = (String) req.getAttribute(ATTRIBUTE_STATUS); if (status != null) { out.print(status); } int total = Datastore.getTotalDevices(); if (total == 0) { out.print("<h2>No devices registered!</h2>"); } else { out.print("<h2>" + total + " device(s) registered!</h2>"); out.print("<form name='form' method='POST' action='sendAll'>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); } out.print("</body></html>"); resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } }
Java
package binarytree; class Main { public static void main(String[] args) { binarytree<Integer> b= new binarytree<Integer>(); b.add(5); b.add(3); b.add(2); b.add(4); b.add(7); b.add(6); b.getLeaves(); System.out.println("/n"); b.show(); } }
Java
package knight; import java.util.ArrayList; public class program2knight { static int N = 8; static int[][] board = new int[N][N]; static int[][] boardMove = new int[N][N]; public static void main(String[] args) { int c=0; int x=0; int y=0; boardMove[0][0]=c; board[0][0]=99; while(c < 63){ c++; Point p = findNext(x,y); x=p.getX(); y=p.getY(); boardMove[p.getX()][p.getY()]=c; board[p.getX()][p.getY()]=99; updateBoard(); } printArray(); } public static Point findNext(int x, int y){ ArrayList<Point> list = new ArrayList<Point>(); int min=100; int bufI = 100; if(onBoard(x+2,y-1)){ list.add(new Point(x+2,y-1)); } if(onBoard(x+2,y+1)){ list.add(new Point(x+2,y+1)); } if(onBoard(x-2,y+1)){ list.add(new Point(x-2,y+1)); } if(onBoard(x-2,y-1)){ list.add(new Point(x-2,y-1)); } if(onBoard(x+1,y+2)){ list.add(new Point(x+1,y+2)); } if(onBoard(x-1,y+2)){ list.add(new Point(x-1,y+2)); } if(onBoard(x+1,y-2)){ list.add(new Point(x+1,y-2)); } if(onBoard(x-1,y-2)){ list.add(new Point(x-1,y-2)); } for(int i = 0; i < list.size();i++){ if(board[list.get(i).getX()][list.get(i).getY()] < min){ min = board[list.get(i).getX()][list.get(i).getY()]; bufI=i; } } return list.get(bufI); } public static void updateBoard(){ int count=0; for(int x = 0; x< N; x++) for(int y = 0; y < N; y++){ count=0; if(onBoard(x+2,y-1)){ count++; } if(onBoard(x+2,y+1)){ count++; } if(onBoard(x-2,y+1)){ count++; } if(onBoard(x-2,y-1)){ count++; } if(onBoard(x+1,y+2)){ count++; } if(onBoard(x-1,y+2)){ count++; } if(onBoard(x+1,y-2)){ count++; } if(onBoard(x-1,y-2)){ count++; } if(board[x][y] != 99) board[x][y]=count; } } public static boolean onBoard(int x, int y){ if(x < N && x >= 0 && y < N && y >=0) if(board[x][y] != 99) return true; return false; } public static void printArray(){ for(int i = 0; i<N; i++){ for(int j = 0; j < N; j++){ System.out.print(" "+boardMove[i][j]); } System.out.println(); } } } class Point{ private int x; private int y; public Point(int x, int y){ this.x=x; this.y=y; } public int getX() { return x; } public int getY() { return y; } }
Java
package Fibonachi; public class program3 { public static void main(String[] args) { int n0 = 1, n1 = 1, n2; System.out.print(n0+" "+n1+" "); for(int i = 0; i < 18; i++){ n2=n0+n1; System.out.print(n2+" "); n0=n1; n1=n2; } System.out.println(); } }
Java
package factorial; import java.util.Scanner; class Factorial { public static void main(String args[]) { int n, c, fact = 1; System.out.println("Enter an integer to calculate it's factorial"); Scanner in = new Scanner(System.in); n = in.nextInt(); if ( n < 0 ) System.out.println("Number should be non-negative."); else { for ( c = 1 ; c <= n ; c++ ) fact = fact*c; System.out.println("Factorial of "+n+" is = "+fact); } } }
Java
package multiplucation; public class multiplication { static long x = 1234567890; static long y = 2121212121; static int counter1=0; static int counter2=0; static long[] mar1 = new long[100]; static long[][] mar2 = new long[100][100]; public static void multi(long x, long y) { int count=0; int c1=0,c2=0; while(y!=0){ count++; long a=x; int ost=0; while(a!=0){ mar2[counter1][counter2] = ((y%10)*(a%10)+ost)%10; ost=(int)(((y%10)*(a%10)+ost)/10); a=a/10; counter2++; if(a==0){ mar2[counter1][counter2] = ost; ost=0; } } y=y/10; c1=counter1; c2=counter2; counter2=count; counter1++; } for(int i=c2; i>=0; i--){ for(int j=c1; j>=0; j--){ mar1[i] += mar2[j][i]; } } } public static void main(String[] args) { System.out.print(x + " * " + y + " = "); multi(x,y); for(int i=counter1; i>=0; i--){ System.out.print(mar1[i]); } } }
Java
package slojenie; public class slojenie { public static int[] mar1; public static int[] mar2; public static int[] mar3; public static int shirina=5; public static int n=0; public static void create() { for(int i=1;i<shirina;i++) { mar1[i]=(int) (Math.random() * 9); } for(int i=0;i<shirina-1;i++) { mar2[i]=(int) (Math.random() * 9); } } public static void print() { for(int i=0;i<shirina;i++){ System.out.print(mar1[i]); } System.out.println(); for(int i=0;i<shirina;i++) { System.out.print(mar2[i]); } System.out.println(); for(int i=0;i<shirina;i++) { System.out.print(mar3[i]); } } public static void sloj() { for(int i=shirina-1;i>=0;i--) { mar3[i]=mar1[i]+mar2[i]+n; n=0; if(mar3[i]>=10) { mar3[i]=mar3[i]%10; n=1; } } } public static void main(String[] args) { mar1 = new int[shirina]; mar2 = new int[shirina]; mar3 = new int[shirina]; create(); sloj(); print(); } }
Java
import java.util.Random; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; public class main { public static void main(String[] args) { bubble_sort q = new bubble_sort(); bubble_sort w = new bubble_sort(); long time_start = 0; int max = 20000; System.out.printf("Bubble\n"); for (int n = 5000; n <= max; n = n+1000){ int[] array = new int[n]; Random ran = new Random(); for (int i = 0; i<n; i++) { array[i]=Math.abs(ran.nextInt(10000)); } time_start = System.currentTimeMillis(); q.Bubble_sort(array, n); System.out.printf("n = "+ n + " Time is " + (System.currentTimeMillis() - time_start)+ "\n"); } System.out.printf("My Bubble\n"); for (int n = 5000; n <= max; n = n+1000){ int[] array = new int[n]; Random ran = new Random(); for (int i = 0; i<n; i++) { array[i]=Math.abs(ran.nextInt(10000)); } time_start = System.currentTimeMillis(); q.my_Bubble_sort(array, n); System.out.printf("my n = "+ n + " Time is " + (System.currentTimeMillis() - time_start)+ "\n"); } } }
Java
public class bubble_sort { public void Bubble_sort(int array[], int n) { for (int i = 0; i < n; i++) for (int j = n - 1; j > 0; j--) if (array[j - 1] > array[j]) { int tmp = array[j - 1]; array[j - 1] = array[j]; array[j] = tmp; } } public void my_Bubble_sort(int array[], int n) { int i = n - 1; while (i > 0) { int fl = 0; for (int j = 0; j < i; j++) if (array[j + 1] < array[j]) { int tmp = array[j + 1]; array[j + 1] = array[j]; array[j] = tmp; fl = j; } i = fl; } } }
Java
package bin_search; public class search { public int bin_search (int array[], int n, int x) { int first = 0; int last = n; int mid = (last - first) / 2; if (last == 0) { return 0; } else if (array[0] > x) { return 0; } else if (array[n-1] < x) { return 0; } while (first < last) { if (x < array[mid]) { last = mid; } else if (x == array [mid]) { return mid+1; } else { first = mid + 1; } mid = first + (last - first) / 2; } return 0; } }
Java
package bin_search; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; public class main { public static void main(String[] args) { search w = new search(); long time_start = 0; int max = 15; int x =7; int[] array = new int[max]; Random ran = new Random(); for (int i = 0; i<max; i++) { array[i]=Math.abs(ran.nextInt(20)); System.out.printf(array[i] + "\t"); } System.out.printf("\n"); int tmp = 0; for (int j = 0; j < max - 1; j++) { for (int i = 0; i < max - j - 1; i++) { if (array[i] > array[i+1]) { tmp = array[i]; array[i] = array[i+1]; array[i+1] = tmp; } } } for (int i = 0; i<max; i++) { System.out.printf(array[i] + "\t"); } time_start = System.currentTimeMillis(); System.out.printf("\nPosition is " + w.bin_search(array, max, x)); } }
Java
public class fib { public static int fibonachi(int n) { if (n < 2) return 1; main.oper +=1; return fibonachi(n-1) + fibonachi(n-2); } public static int fib_cycle(int n) { int i = 2; int fib_sum = 0; int fib1 = 1; int fib2 = 1; while (i < n) { fib_sum = fib2 + fib1; fib1 = fib2; fib2 = fib_sum; i += 1; main.oper+=4; } return fib_sum; } }
Java
public class nod { public long evklid_func (long a, long b) { while (b !=0) { long tmp = a % b; a = b; b = tmp; } return a; } public long my_func (long a, long b) { long c = 1; long nod = 0; if (a < b) c = a; else c = b; for (int i = 1; i<=c; i++) { if (a % i == 0 && b % i == 0) nod = i; } return nod; } }
Java
package factorial; public class fact { public static long fact(long n) { main.oper +=1; if (n==1) return 1; return (n*fact(n-1)); } }
Java
package merge_sort; public class quick { void Quick_sort (int[] array, int start, int end) { int pivot; if ( start >= end ) { return; } int marker = start; for ( int i = start; i <= end; i++ ) { if ( array[i] <= array[end] ) { int temp = array[marker]; array[marker] = array[i]; array[i] = temp; marker += 1; } } pivot = marker - 1; Quick_sort (array, start, pivot-1); Quick_sort (array, pivot+1, end); } }
Java
package merge_sort; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; public class main { public static void main(String[] args) { quick q = new quick(); long time_start = 0; int max = 500000; System.out.printf("Merge\n"); for (int n = 100000; n <= max; n=n+50000){ int[] array = new int[n]; Random r = new Random(); for (int i = 0; i<n; i++) { array[i]=Math.abs(r.nextInt(10000)); } time_start = System.currentTimeMillis(); merge.Merge_Sort(array); System.out.printf("merge n = "+ n + " Time is " + (System.currentTimeMillis() - time_start)+ "\n"); } System.out.printf("Quick\n"); for (int n = 100000; n <= max; n=n+50000){ int[] array = new int[n]; Random r = new Random(); for (int i = 0; i<n; i++) { array[i]=Math.abs(r.nextInt(10000)); } time_start = System.currentTimeMillis(); q.Quick_sort(array, 0, n-1); System.out.printf("quick n = "+ n + " Time is " + (System.currentTimeMillis() - time_start)+ "\n"); } } }
Java
package merge_sort; public class merge { static int[] Merge_Sort(int[] massive) { if (massive.length <= 1) return massive; int mid_point = massive.length / 2; return Merge(Merge_Sort(java.util.Arrays.copyOfRange(massive, 0, mid_point-1)), Merge_Sort(java.util.Arrays.copyOfRange(massive, mid_point, massive.length-1))); } static int[] Merge(int[] mass1, int[] mass2) { int a = 0, b = 0; int[] merged = new int[mass1.length + mass2.length]; for (int i = 0; i < mass1.length + mass2.length; i++) { if (b < mass2.length && a < mass1.length) if (mass1[a] > mass2[b] && b < mass2.length) merged[i] = mass2[b++]; else merged[i] = mass1[a++]; else if (b < mass2.length) merged[i] = mass2[b++]; else merged[i] = mass1[a++]; } return merged; } }
Java
package horse; public class horse { int level; int stor; int count = 0; int horse(int w, int h, int[][] mass, int level) { //проверка ходов mass[w][h] = level; int flag = 1; if (level == stor*stor ) {count = count+1; printArr(mass, stor, stor);} if((0 <= h+2) && (h+2 < stor) && (0 <= w+1) && (w+1 < stor) && (mass[w+1][h+2] == 0)) {flag = horse(w+1, h+2, mass, level+1);} if((0 <= h+1) && (h+1 < stor) && (0 <= w+2) && (w+2 < stor) && (mass[w+2][h+1] == 0)) {flag = horse(w+2, h+1, mass, level+1);} if((0 <= h-2) && (h-2 < stor) && (0 <= w-1) && (w-1 < stor) && (mass[w-1][h-2] == 0)) {flag = horse(w-1, h-2, mass, level+1);} if((0 <= h-1) && (h-1 < stor) && (0 <= w-2) && (w-2 < stor) && (mass[w-2][h-1] == 0)) {flag = horse(w-2, h-1, mass, level+1);} if((0 <= h+2) && (h+2 < stor) && (0 <= w-1) && (w-1 < stor) && (mass[w-1][h+2] == 0)) {flag = horse(w-1, h+2, mass, level+1);} if((0 <= h+1) && (h+1 < stor) && (0 <= w-2) && (w-2 < stor) && (mass[w-2][h+1] == 0)) {flag = horse(w-2, h+1, mass, level+1);} if((0 <= h-2) && (h-2 < stor) && (0 <= w+1) && (w+1 < stor) && (mass[w+1][h-2] == 0)) {flag = horse(w+1, h-2, mass, level+1);} if((0 <= h-1) && (h-1 < stor) && (0 <= w+2) && (w+2 < stor) && (mass[w+2][h-1] == 0)) {flag = horse(w+2, h-1, mass, level+1);} if (flag == 1) { mass[w][h] = 0; return 1;} return 0; } public static void printArr(int arr[][], int a, int b) { for(int k = 0; k < a; k++) { for(int l = 0; l < b; l++) System.out.print(arr[k][l] + "\t"); System.out.println(); } System.out.println(); } }
Java
package horse; public class main { public static void main(String[] args) { horse horse = new horse(); int imax = 5; int jmax = 5; int [][] array = new int[imax][jmax]; horse.stor=5; for (int i = 0; i < horse.stor; i++) { for(int j = 0; j < horse.stor; j++) { horse.horse(i, j, array, 1); } } System.out.print("All decisions: "+horse.count+"\n"); } }
Java
package algorithms; import java.io.File; public class Tree { }
Java
package algorithms; public class Tree { public Element head = null; public Element min(){ Element current = head; while(current.left!=null){ current = current.left; } return current; } public Element max(){ Element current = head; while(current.right!=null){ current = current.right; } return current; } public void add(Element elem){ if(head==null){ head = elem; }else{ Element current = head; while(true){ if (current.key>elem.key){ if(current.left==null){ current.left=elem; elem.parent=current; return; }else{ current=current.left; } } if (current.key<elem.key){ if(current.right==null){ current.right=elem; elem.parent=current; return; }else{ current=current.right; } } } } } public void print(Element elem, int count) { if(elem.right!=null) { print(elem.right,count+1); } for(int i=0; i<count; i++){ System.out.print('\t'); } System.out.println(elem.key); if(elem.left!=null) { print(elem.left,count+1); } } public void delete(Element elem, int a, char b) { if(elem.right!=null) { delete(elem.right,a,b); } if(elem.key == a && elem.value == b) { if(elem.left == null && elem.right == null) { //System.out.println("elem.left == null && elem.right == null"); if(elem.parent!=null) { if(elem.parent.right == elem) { elem.parent.right = null; } if(elem.parent.left == elem) { elem.parent.left = null; } } else elem=null; } if(elem.right==null && elem.left!=null) { //System.out.println("elem.right==null && elem.left!=null"); if(elem.parent!=null) { if(elem.parent.right == elem) { elem.parent.right = elem.left; elem.left.parent = elem.parent; } if(elem.parent.left == elem) { elem.parent.left = elem.left; elem.left.parent = elem.parent; } } } if(elem.right!=null && elem.left==null) { //System.out.println("elem.right!=null && elem.left==null"); if(elem.parent!=null) { if(elem.parent.right == elem) { elem.parent.right = elem.right; elem.right.parent = elem.parent; } if(elem.parent.left == elem) { elem.parent.left = elem.right; elem.right.parent = elem.parent; } } } if(elem.right!=null && elem.left!=null) { //System.out.println("elem.right!=null && elem.left!=null"); Element cur = elem.right; while(cur.left!=null) { cur=cur.left; } if(elem.parent!=null) { if(elem.parent.left == elem) { cur.parent=elem.left; elem.parent.left=elem.left; cur.parent.right=cur; } if(elem.parent.right == elem) { cur.left=elem.left; if(cur.right==null) { elem.parent.right=cur.parent.left; cur.parent.left = null; cur.right=elem.right; } else { cur.left=elem.left; elem.parent.right=cur; } } } else { if(elem.right!=null) { elem.right.left=null; cur.right=elem.right; cur.right.parent=cur; elem.right=cur; } if(elem.left!=null) { elem.left.parent = cur; cur.left=elem.left; } head=cur; } } } if(elem.left!=null) { delete(elem.left,a,b); } } }
Java
package algorithms; public class Element { public Element right; public Element left; public Element parent; public int key; public char value; Element(int Key, char Value){ value = Value; key = Key; } }
Java
package algorithms; public class Element { public Element next; public int ch; public Element(int ch){ this.ch = ch; } }
Java
package algorithms; public class Element { public Element next; public String key; public String value; public Element(String key, String value){ this.key = key; this.value = value; } }
Java
package algorithms; public class Map { public Element head = null; public void Key_list(){ if(head == null){ System.out.println("Error: Map is empty!"); }else{ Element cur = head; System.out.print("Key list: "); while(cur.next!=null){ System.out.print(cur.key+" "); cur = cur.next; } System.out.println(); } } public void Add_Map(Element elem){ if(head== null){ head = elem; }else{ if(head.next == null) { if(head.key.compareTo(elem.key)<0){ head.next = elem; return; } if(head.key.compareTo(elem.key)>0){ elem.next = head; head = elem; return; } if(head.key.compareTo(elem.key)==0){ System.out.println("Error: key '"+head.key+"' already used! ('"+head.value+"','"+elem.value+"')"); return; } } if(head.key.compareTo(elem.key)<0){ elem.next = head.next; head.next = elem; return; } if(head.key.compareTo(elem.key)>0){ elem.next = head; head = elem; return; } if(head.key.compareTo(elem.key)==0){ System.out.println("Error: key '"+head.key+"' already used! ('"+head.value+"','"+elem.value+"')"); return; } Element cur = head; while(cur.next!=null){ if(cur.key.compareTo(elem.key)>0 || elem.key.compareTo(cur.next.key)<0) { elem.next=cur.next; cur.next=elem; return; } cur = cur.next; } cur.next = elem; } } public String Get_Map(String key){ if(head==null){ System.out.println("Error: Map is empty!"); return null; }else{ if(head.key == key){ return head.value; }else{ Element cur = head; while(cur.next!=null){ if(cur.key == key){ return cur.value; } cur = cur.next; } System.out.println("Error: there isn't record with the key '"+key+"'!"); return null; } } } public void Delete_Key(String key){ if(head.key == key){ head = head.next; }else{ Element cur = head; while(cur.next!=null){ if(cur.next.key == key){ cur.next = cur.next.next; return; } cur = cur.next; } } } public void Delete_Value(String value){ int flag=0; if(head == null) return; if(head.value == value){ if(head.next!=null){ head = head.next; } else{ head = null; return; } while(head.value==value) if(head.next!=null){ head = head.next; } else{ head = null; return; } }; Element cur = head; while(cur.next!=null){ if(cur.next.value == value){ cur.next = cur.next.next; flag=1; } if(flag==0){ cur = cur.next; } else{ flag=0; } } } public void Delete_KeyAndValue(String key, String value){ if(head.key == key && head.value == value){ head = head.next; }else{ Element cur = head; while(cur.next!=null){ if(cur.next.key == key && cur.next.value == value){ cur.next = cur.next.next; return; } cur = cur.next; } } } public String toString(){ StringBuffer sb = new StringBuffer(); Element current = head; sb.append("KEY\t"); sb.append("VALUE\n"); while (current != null){ sb.append(current.key + "\t"); sb.append(current.value + "\n"); current = current.next; } return sb.toString(); } }
Java
package algorithms; public class Element { public Element next; public int ch; public Element(int ch){ this.ch = ch; } }
Java
package algorithms; public class TestCalendar { public static void main(String[] args) { Calendar c = new Calendar(); System.out.println(c.GetDay(new Day(31,4,2008))); } }
Java
package algorithms; public class Day { public int Number; public int Mounth; public int Year; public Day(int Number, int Mounth, int Year){ this.Number = Number; this.Mounth = Mounth; this.Year = Year; } }
Java
package algorithms; public class Element { public int key; public String value; Element(int Key,String Value){ key=Key; value=Value; } }
Java
package algorithms; public class Peak { public String [] next; public String c; public Peak(String c){ this.c = c; } }
Java
package algorithms; public class TestGraph { public static void main(String[] args) { Graph graph = new Graph(); String [] Peaks1 = {"B","G",null}; graph.Add_Peak(new Peak("A"),Peaks1); String [] Peaks2 = {"C","D", null}; graph.Add_Peak(new Peak("B"),Peaks2); String [] Peaks3 = {"E", null}; graph.Add_Peak(new Peak("C"),Peaks3); String [] Peaks4 = {"E","F", null}; graph.Add_Peak(new Peak("D"),Peaks4); String [] Peaks5 = {"H", null}; graph.Add_Peak(new Peak("E"),Peaks5); String [] Peaks6 = {"H", null}; graph.Add_Peak(new Peak("F"),Peaks6); String [] Peaks7 = {"H", null}; graph.Add_Peak(new Peak("G"),Peaks7); String [] Peaks8 = {"",null}; graph.Add_Peak(new Peak("H"),Peaks8); System.out.println(graph.m); //System.out.println(graph.m.Get_Map("H").next[0]); graph.Table(); } }
Java
package algorithms; public class Element { public Element next; public String key; public Peak value; public Element(Peak value){ this.key = value.c; this.value = value; } }
Java
package algorithms; public class Element { public Element next; public int ch; public Element(int ch){ this.ch = ch; } }
Java
package algorithms; public class Stack { public Element head = null; public void PUSH(Element elem){ if(head == null){ head = elem; return; } if(head != null){ elem.next = head; head = elem; return; } } public Element POP(){ Element cur = head; head = head.next; return cur; } public String toString(){ StringBuffer sb = new StringBuffer(); sb.append("[ "); Element current = head; while (current != null){ sb.append(current.ch + " "); current = current.next; } sb.append("]"); return sb.toString(); } }
Java
package algorithms; public class Element { public Element next; public Element previous; public int ch; public Element(int ch){ this.ch = ch; } public Element(){ this.next=this; this.previous=this; } }
Java
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class bisearch { @SuppressWarnings("resource") public static void main(String[] args) { int num=10; ArrayList<Integer> list = new ArrayList<Integer>(num); for(int i=0;i<num;i++){ list.add(i); } Collections.shuffle(list); System.out.println(list); buble(list,num); System.out.println(list); Scanner sc = new Scanner(System.in); int p = sc.nextInt(); System.out.println(BinarySearch(list,p,0,num-1)); } public static int BinarySearch(ArrayList<Integer> list, int p, int s, int e){ int i=(s+e)/2; if (list.get(i)==p) return i; if (list.get(i)<p) return BinarySearch(list,p,i+1,e); else return BinarySearch(list, p,s,i-1); } public static void buble(ArrayList<Integer> list,int num) { for(int i=0;i<num-1;i++){ for(int j=0;j<num-i-1;j++){ if(list.get(j)>list.get(j+1)){ int tmp=list.get(j); list.set(j,list.get(j+1)); list.set(j+1, tmp); } } } } }
Java
package fgd; public class SpisokTest { public static void main(String[] args) { Spisok s= new Spisok(); Spisok sp= new Spisok(); int []mas = new int[10]; for( int i=0; i<mas.length;i++) { mas[i] = (int)Math.round(Math.random()*(-10)); s.add(new Element(mas[i])); s.add_end(new Element(mas[i])); s.bubble_sort(new Element(mas[i])); } System.out.print(s); s.add_begin(new Element(2)); System.out.print(s); s.add_after(new Element(3), 3); System.out.print(s); /*s.add(new Element(10)); s.add(new Element(11)); s.add(new Element(2)); s.add(new Element(13)); s.add(new Element(14));*/ } }
Java
package fgd; public class Spisok { Element head = null; public void add(Element elem){ if(head == null) { head = elem; } else{ Element current = head; while (current.next != null) { current = current.next; } current.next = elem; } } public void add_begin(Element elem) { if(head==null) head=elem; else elem.next = head; head = elem; } public void add_after(Element elem ,int elem1){ if(head == null){ head = elem; } else { Element cur = head; while(cur.next != null){ if(cur.i == elem1){ elem.next=cur.next; cur.next=elem; return; } cur = cur.next; } }} public void bubble_sort(Element elem){ boolean swapped = true; int j = 0; if(head == null){ head = elem; } else { Element cur = head; while(cur.next != null){ do{ if(j!=0){ j=0; cur = head; } swapped = false; if(cur.i>cur.next.i){ j++; int tmp = cur.i; cur.i = cur.next.i; cur.next.i = tmp; swapped = true; }}while(swapped); cur = cur.next; }}} public void add_end(Element elem){ if(head == null){ head = elem; } else { Element cur = head; while(cur.next != null){ cur = cur.next; } cur.next = elem; } } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[ "); Element current = head; while (current != null){ sb.append(current.i + " "); current=current.next; } sb.append("]"); return sb.toString(); } }
Java
package fgd; public class Element { public int i; public Element next = null; public Element(int i){ this.i=i; } }
Java
// programma hod konem! import java.util.Scanner; public class knight { static int lenght = 5; static int arr[][]; public static void main(String[] args) { Scanner cin = new Scanner(System.in); System.out.print("Input the size of the board: "); lenght = cin.nextInt(); arr = new int[lenght][lenght]; System.out.print("Input start coordinate for x: "); int x = cin.nextInt(); System.out.print("Input start coordinate for y: "); int y = cin.nextInt(); int sum = 0; for(int i = 0; i < arr.length; i++) for(int j = 0; j < arr[0].length; j++) sum += knight(i, j); System.out.println("Number of options (" + x + ";" + y + "): " + knight(x, y)); } private static void printArr(int arr[][]) { System.out.println(); for(int i = 0; i < arr.length; i++) { for(int j = 0; j < arr[0].length; j++) System.out.print(arr[i][j] + " "); System.out.println(); } } private static int knight(int x, int y) { return knight(x, y, 1); } private static int knight(int x, int y, int level) { if(x >= 0 && x <= lenght-1) if(y >= 0 && y <= lenght-1) if(arr[x][y] == 0) { arr[x][y] = level; if(level == lenght*lenght) { printArr(arr); arr[x][y] = 0; return 1; } else { int sum = 0; sum += knight(x-2, y-1, level+1); sum += knight(x-1, y-2, level+1); sum += knight(x+1, y-2, level+1); sum += knight(x+2, y-1, level+1); sum += knight(x+2, y+1, level+1); sum += knight(x+1, y+2, level+1); sum += knight(x-1, y+2, level+1); sum += knight(x-2, y+1, level+1); arr[x][y] = 0; return sum; } } return 0; } }
Java
public class list { public element head = new element(); public void add_end(element elem){ if(head.next == head){ head.next=elem; head.prev=elem; elem.next=head; elem.prev=head; }else{ element cur = head; while(cur.next!=head){ cur = cur.next; } cur.next = elem; elem.prev = cur; elem.next = head; head.prev = elem; } } public void add_begin(element elem){ if(head.next == head){ head.next=elem; head.prev=elem; elem.next=head; elem.prev=head; }else{ element cur = head.next; head.next = elem; elem.prev = head; elem.next = cur; cur.prev = elem; } } public String toString(){ StringBuffer sb = new StringBuffer(); sb.append("[ "); element current = head.next; while (current != head){ sb.append(current.i + " "); current = current.next; } sb.append("]"); return sb.toString(); } }
Java
public class element { public element next; public element prev; public int i; public element(int i){ this.i = i; } public element(){ this.next=this; this.prev=this; } }
Java
public class binarytree { public class Element { int num; Element left; Element right; public Element parent; public Element(int num, Element parent) { this.num = num; this.left = null; this.right = null; this.parent = parent; } } Element root; int lenght; public Element add(int num) { lenght++; if(root == null) { root = new Element(num, null); return root; } Element tree1 = root; while(tree1 != null) if(num >= tree1.num) if(tree1.right == null) { tree1.right = new Element(num, tree1); return tree1.right; } else tree1 = tree1.right; else if(num < tree1.num) if(tree1.left == null) { tree1.left = new Element(num, tree1); return tree1.left; } else tree1 = tree1.left; lenght--; return null; } public void printTree(Element Elem, int level) { if(Elem.right != null) printTree(Elem.right, level+1); for(int k = 0; k < level; k++) System.out.print("\t"); System.out.println(Elem.num); if(Elem.left != null) printTree(Elem.left, level+1); } public Element max(){ Element tree1 = root; while(tree1.right!=null){ tree1 = tree1.right; } return tree1; } public Element min() { Element tree1 = root; while(tree1.left != null) tree1 = tree1.left; return tree1; } public static void main(String[] args) { bin tree = new bin(); tree.add(7); tree.add(2); tree.add(5); tree.add(3); tree.add(9); tree.add(6); tree.add(11); tree.add(13); tree.add(1); tree.printTree(tree.root, 0); } }
Java
public class multiplication { static long x = 1234567890; static long y = 2123456789; static int counter1=0; static int counter2=0; static long[] arr1 = new long[100]; static long[][] arr2 = new long[100][100]; public static void multi(long x, long y) { int count=0; int c1=0,c2=0; while(y!=0){ count++; long a=x; int ost=0; while(a!=0){ arr2[counter1][counter2] = ((y%10)*(a%10)+ost)%10; ost=(int)(((y%10)*(a%10)+ost)/10); a=a/10; counter2++; if(a==0){ arr2[counter1][counter2] = ost; ost=0; } } y=y/10; c1=counter1; c2=counter2; counter2=count; counter1++; } for(int i=c2; i>=0; i--){ for(int j=c1; j>=0; j--){ arr1[i] += arr2[j][i]; } } } public static void main(String[] args) { System.out.print(x + " * " + y + " = "); multi(x,y); for(int i=counter1; i>=0; i--){ System.out.print(arr1[i]); } }}
Java
package stolbik; public class slojenie { public static int[] arr1; public static int[] arr2; public static int[] arr3; public static int length=5; public static int n=0; public static void create() { for(int i=1;i<length;i++) { arr1[i]=(int) (Math.random() * 9); } for(int i=0;i<length-1;i++) { arr2[i]=(int) (Math.random() * 9); } } public static void print() { for(int i=0;i<length;i++){ System.out.print(arr1[i]); } System.out.println(); for(int i=0;i<length;i++) { System.out.print(arr2[i]); } System.out.println(); for(int i=0;i<length;i++) { System.out.print(arr3[i]); } } public static void sloj() { for(int i=length-1;i>=0;i--) { arr3[i]=arr1[i]+arr2[i]+n; n=0; if(arr3[i]>=10) { arr3[i]=arr3[i]%10; n=1; } } } public static void main(String[] args) { arr1 = new int[length]; arr2 = new int[length]; arr3 = new int[length]; create(); sloj(); print(); } }
Java
import java.util.Random; public class numberone { public static int num = 5; public static int crutch = 0; public static int howmuch(int x,int y,int arr [][]) { int count = 0; if(x+1<num && y+2<num && arr[y+2][x+1] == 0){count++;} if(x+2<num && y+1<num && arr[y+1][x+2] == 0){count++;} if(y-2>=0 && x+1<num && arr[y-2][x+1] == 0){count++;} if(y-1>=0 && x+2<num && arr[y-1][x+2] == 0){count++;} if(x-1>=0 && y+2<num && arr[y+2][x-1] == 0){count++;} if(x-2>=0 && y+1<num && arr[y+1][x-2] == 0){count++;} if(x-1>=0 && y-2>=0 && arr[y-2][x-1] == 0){count++;} if(x-2>=0 && y-1>=0 && arr[y-1][x-2] == 0){count++;} return count; } public static int quatrefoil(int x,int y,int arr [][]) { int[] Arr = {10,10,10,10,10,10,10,10}; if(x+1<num && y+2<num && arr[y+2][x+1] == 0){Arr[0] = howmuch(x+1,y+2,arr);} if(x+2<num && y+1<num && arr[y+1][x+2] == 0){Arr[1] = howmuch(x+2,y+1,arr);} if(y-2>=0 && x+1<num && arr[y-2][x+1] == 0){Arr[2] = howmuch(x+1,y-2,arr);} if(y-1>=0 && x+2<num && arr[y-1][x+2] == 0){Arr[3] = howmuch(x+2,y-1,arr);} if(x-1>=0 && y+2<num && arr[y+2][x-1] == 0){Arr[4] = howmuch(x-1,y+2,arr);} if(x-2>=0 && y+1<num && arr[y+1][x-2] == 0){Arr[5] = howmuch(x-2,y+1,arr);} if(x-1>=0 && y-2>=0 && arr[y-2][x-1] == 0){Arr[6] = howmuch(x-1,y-2,arr);} if(x-2>=0 && y-1>=0 && arr[y-1][x-2] == 0){Arr[7] = howmuch(x-2,y-1,arr);} int min = 10; int cp = 10; for(int i = 0;i < 8;i++) { if(cp > Arr[i] && Arr[i] != 10) { cp = Arr[i]; min = i; //if(cp == 0) //min = 10; } } return min; } public static void main(String[] args) { int[][] arr = new int[num][num]; for(int i = 0;i < num;i++) { for(int j = 0;j < num;j++) { arr[i][i] = 0; } } int x,y; x = new Random(System.currentTimeMillis()).nextInt(num); System.out.println(x); y = new Random(System.currentTimeMillis()).nextInt(num); //int count = 0; System.out.println(y); arr[y][x]++; int pa = 11; while(pa != 10) { for(int i = 0;i < 5;i++) { for(int j = 0;j < 4;j++) { System.out.print(arr[i][j]); } System.out.println(arr[i][4]); } System.out.println(7); pa = quatrefoil(x,y,arr); if(pa == 0) {x=x+1;y=y+2;} if(pa == 1) {x=x+2;y=y+1;} if(pa == 2) {x=x+1;y=y-2;} if(pa == 3) {x=x+2;y=y-1;} if(pa == 4) {x=x-1;y=y+2;} if(pa == 5) {x=x-2;y=y+1;} if(pa == 6) {x=x-1;y=y-2;} if(pa == 7) {x=x-2;y=y-1;} arr[y][x]++; crutch++; int c = 0; for(int i = 0;i < num;i++) for(int j = 0;j < num;j++) { if(arr[i][j] == 0) c++; } if((crutch > 24 && c > 0) || (pa == 10 && c > 0)) { pa = 11; crutch = 0; x = new Random(System.currentTimeMillis()).nextInt(num); y = new Random(System.currentTimeMillis()).nextInt(num); for(int i = 0;i < num;i++) for(int j = 0;j < num;j++) { arr[i][j] = 0; } } c = 0; for(int i = 0;i < num;i++) for(int j = 0;j < num;j++) { if(arr[i][j] == 0) c++; } if(c == 0) continue; System.out.println(c); System.out.println(crutch); System.out.print(x);System.out.print(" ");System.out.println(y); } // System.out.println(x); // System.out.println(y); } }
Java
public class algs03 { public static int Mult(int max, int min, int t,int mult){ if(t>=min) { return mult; } else { mult = mult + max; return Mult(max,min,t+1,mult); } // return mult; } public static void main(String[] args) { int a = 2222; int b = 11; int mult = 0; int t = 0; int i = Mult(a,b,t,mult); System.out.println(i); } }
Java
public class algs02 { public static long searchN(long x){ long N = 1; while(N < x) N = N * 10; if(N > 1) N = N / 10; return N; } public static long searchT(long x){ long T = 0; for(int N = 1; N < x; N=N*10){ T++; } return T; } public static void main(String[] args) { long a = 123456789; long b = 987456321; long min; long max; if (a < b) min = a; else min = b; if(a < b) max = b; else max = a; long n = searchN(min); long t = searchT(min); long Mult = 0; while(t > 0){ Mult = (Mult + max*(min/n))*n; min = min - (min/n)*n; n = searchN(min); t--; System.out.println(Mult); } } }
Java
public class algs04 { public static int searchT(int x){ int T = 0; for(int N = 1; N < x; N=N*10){ T++; } return T; } public static int xtn(int x,int n){ int a = x; for(int iter = 1; iter < n; iter++) a = a * x; return a; } public static void main(String[] args) { int a = 2222; int b = 1111; int n = searchT(a); int m = n/2; int i; int a0,a1,b0,b1; a0 = a; b0 = b; for(i = 0;i < m;i++) { a0 = a0 / 10; b0 = b0 / 10; } a1 = a - a0* xtn(10,m); b1 = b - b0* xtn(10,m); System.out.println(a1); System.out.println(a0); System.out.println(b1); System.out.println(b0); int mult = a0*b0 +(a0*b1 + a1*b0)* (xtn(10,m)) + a1*b1*(xtn(10,(2*m))); System.out.println(mult); } }
Java
public class algs01 { public static int searchN(int x){ int N = 10; while(N < x) N = N * 10; N = N / 10; return N; } public static int searchT(int x){ int T = 0; for(int N = 1; N < x; N=N*10){ T++; } return T; } public static void main(String[] args) { int x = 123456789; int y = 987654321; int a,b; int t;//counter int max; int Sum = 0; if(x > y) max = x; else max = y; t = searchT(max); while(t > 0){ a = searchN(x); b = searchN(y); Sum = Sum + (x/a)*a + (y/b)*b; x = x - (x / a)*a; y = y - (y / b)*b; t--; /*System.out.println(x / 1000); a = x / a; b = y / b; System.out.println(a+b);*/ } System.out.println(Sum); } }
Java
public class Fib { static int count = 0; public static int fibo_native(int N){ if(N < 2) return N; count++; //System.out.print(" " + N); return fibo_native(N - 2) + fibo_native(N - 1); } public static void main(String[] args) { long start = System.nanoTime(); System.out.println(fibo_native(1)); System.out.println(count); long estTime = System.nanoTime() - start; System.out.println(estTime); } }
Java
import java.util.ArrayList; import java.util.Collections; public class bublesort { public static int num = 10; public static ArrayList<Integer> list = new ArrayList<Integer> (num); public static ArrayList<Integer> justbubsor(){ int t = num - 1; for(int j = 0;j < t; j++){ for(int i = 0;i < t; i++){ if(list.get(i) > list.get(i + 1)){ int tmp = list.get(i); list.set(i, list.get(i + 1)); //a[i] = a[i + 1] list.set(i+1, tmp);} } } return list; } public static ArrayList<Integer> flagbubsor(){ int t = num - 1; int flag = t; for(int j = 0; j < flag ; j++){ for(int i = 0; i < t; i++){ if(list.get(i) > list.get(i + 1)){ int tmp = list.get(i); list.set(i, list.get(i + 1)); //a[i] = a[i + 1] list.set(i+1, tmp); //a[i + 1] = tmp } } flag--; } return list; } public static void main(String[] args) { for (int i = 0; i < num; i++){ list.add(i); } Collections.shuffle(list); System.out.println(list); long start = System.nanoTime(); flagbubsor(); long estTime = System.nanoTime() - start; System.out.println(estTime); System.out.println(list); } }
Java
public class NOD { public static int del(int n,int m){ int count; int exit; if(n < m){ count = m % n; if(count != 0) return del(n,m % n); else exit = n; } else{ count = n % m; if(count != 0) return del(n % m,m); else exit = m; } return exit; } public static int Evc(int a, int b){ while(a != 0 && b != 0){ if(a > b) a = a % b; else b = b % a; } return(a + b); } public static int all(int x,int y){ if(x > y && x % y == 0) return y; if(y <= x && y % x == 0) return x; int count; if(x < y){ count = x - 1; while((y % count != 0 || x % count != 0) && count > 0) count--; } else { count = y - 1; while((x % count != 0 || y % count != 0) && count > 0) count--; } return count; } public static void main(String[] args) { int a = 170; int b = 230; long start = System.nanoTime(); all(a,b); long estTime = System.nanoTime() - start; System.out.println(estTime); System.out.println(all(a,b)); } }
Java
public class factorial { public static void main(String[] args){ int x = 12; int fac = 1; for(int i = 1;i <= 12;i++){ fac = fac * i; System.out.println(fac); } } }
Java
import java.util.Random; public class numberone { public static int num = 5; public static int crutch = 0; public static int howmuch(int x,int y,int arr [][]) { int count = 0; if(x+1<num && y+2<num && arr[y+2][x+1] == 0){count++;} if(x+2<num && y+1<num && arr[y+1][x+2] == 0){count++;} if(y-2>=0 && x+1<num && arr[y-2][x+1] == 0){count++;} if(y-1>=0 && x+2<num && arr[y-1][x+2] == 0){count++;} if(x-1>=0 && y+2<num && arr[y+2][x-1] == 0){count++;} if(x-2>=0 && y+1<num && arr[y+1][x-2] == 0){count++;} if(x-1>=0 && y-2>=0 && arr[y-2][x-1] == 0){count++;} if(x-2>=0 && y-1>=0 && arr[y-1][x-2] == 0){count++;} return count; } public static int quatrefoil(int x,int y,int arr [][]) { int[] Arr = {10,10,10,10,10,10,10,10}; if(x+1<num && y+2<num && arr[y+2][x+1] == 0){Arr[0] = howmuch(x+1,y+2,arr);} if(x+2<num && y+1<num && arr[y+1][x+2] == 0){Arr[1] = howmuch(x+2,y+1,arr);} if(y-2>=0 && x+1<num && arr[y-2][x+1] == 0){Arr[2] = howmuch(x+1,y-2,arr);} if(y-1>=0 && x+2<num && arr[y-1][x+2] == 0){Arr[3] = howmuch(x+2,y-1,arr);} if(x-1>=0 && y+2<num && arr[y+2][x-1] == 0){Arr[4] = howmuch(x-1,y+2,arr);} if(x-2>=0 && y+1<num && arr[y+1][x-2] == 0){Arr[5] = howmuch(x-2,y+1,arr);} if(x-1>=0 && y-2>=0 && arr[y-2][x-1] == 0){Arr[6] = howmuch(x-1,y-2,arr);} if(x-2>=0 && y-1>=0 && arr[y-1][x-2] == 0){Arr[7] = howmuch(x-2,y-1,arr);} int min = 10; int cp = 10; for(int i = 0;i < 8;i++) { if(cp > Arr[i] && Arr[i] != 10) { cp = Arr[i]; min = i; //if(cp == 0) //min = 10; } } return min; } public static void main(String[] args) { int[][] arr = new int[num][num]; for(int i = 0;i < num;i++) { for(int j = 0;j < num;j++) { arr[i][i] = 0; } } int x,y; x = new Random(System.currentTimeMillis()).nextInt(num); System.out.println(x); y = new Random(System.currentTimeMillis()).nextInt(num); //int count = 0; System.out.println(y); arr[y][x]++; int pa = 11; while(pa != 10) { for(int i = 0;i < 5;i++) { for(int j = 0;j < 4;j++) { System.out.print(arr[i][j]); } System.out.println(arr[i][4]); } System.out.println(7); pa = quatrefoil(x,y,arr); if(pa == 0) {x=x+1;y=y+2;} if(pa == 1) {x=x+2;y=y+1;} if(pa == 2) {x=x+1;y=y-2;} if(pa == 3) {x=x+2;y=y-1;} if(pa == 4) {x=x-1;y=y+2;} if(pa == 5) {x=x-2;y=y+1;} if(pa == 6) {x=x-1;y=y-2;} if(pa == 7) {x=x-2;y=y-1;} arr[y][x]++; crutch++; int c = 0; for(int i = 0;i < num;i++) for(int j = 0;j < num;j++) { if(arr[i][j] == 0) c++; } if((crutch > 24 && c > 0) || (pa == 10 && c > 0)) { pa = 11; crutch = 0; x = new Random(System.currentTimeMillis()).nextInt(num); y = new Random(System.currentTimeMillis()).nextInt(num); for(int i = 0;i < num;i++) for(int j = 0;j < num;j++) { arr[i][j] = 0; } } c = 0; for(int i = 0;i < num;i++) for(int j = 0;j < num;j++) { if(arr[i][j] == 0) c++; } if(c == 0) continue; System.out.println(c); System.out.println(crutch); System.out.print(x);System.out.print(" ");System.out.println(y); } // System.out.println(x); // System.out.println(y); } }
Java
package Algorithms; import java.util.ArrayList; public class BS { public static int num = 10; public static ArrayList<Integer> list = new ArrayList<Integer> (num); public static int bs(int x){ int l = list.get(0); int i = num - 1; int r = list.get(i); while(x != list.get(i)){ i = (l+r)/2; if(x < list.get(i)) r = i; if(x > list.get(i)) l = i; } return i; } public static void main(String[] args) { for(int i = 0; i < num; i++){ list.add(i+1); } int x = 5; int i = bs(x); System.out.println(i); } }
Java
public class test { public static void main(String[] args) { map director = new map(); mkv test = new mkv(); director.create(test, 6); director.add(test,"Name","Aleks"); director.add(test,"Sirname","Stown"); director.add(test,"Age","37"); director.printmap(test); director.justsearc(test,"Name"); director.delete(test,"Name"); director.delete(test,"Name"); director.justsearc(test,"Name"); // ;;;;; } }
Java
import java.util.ArrayList; public class mkv { public ArrayList<String> key = new ArrayList<String>(); public ArrayList<String> value = new ArrayList<String>(); }
Java
public class map { public void create(mkv MapArr,int size) { for(int i = 0;i < size;i++) { MapArr.key.add(null); MapArr.value.add(null); } } public void add(mkv MapArr,String Key,String Value) { int check = 0; int size = MapArr.key.size(); for(int i = 0;i < size;i++) { if(MapArr.key.get(i) == Key) { check++; } } if(check > 0) { System.out.println("This element already exists"); } else { for(int i = 0;i < size;i++) { if(MapArr.key.get(i) == null) { MapArr.key.set(i, Key); MapArr.value.set(i, Value); i = size; } } } } public void delete(mkv MapArr,String Key) { int size = MapArr.key.size(); int check = 0; for(int i = 0;i < size;i++) { if(MapArr.key.get(i) == Key) { MapArr.key.remove(i); MapArr.value.remove(i); check++; i = size; } } if(check > 0) System.out.println("This element has been successfully removed"); else System.out.println("Such element does not exist or it has already been removed"); } public void justsearc(mkv MapArr,String Key) { int size = MapArr.key.size(); int check = 0; for(int i = 0;i < size;i++) { if(MapArr.key.get(i) == Key) { System.out.println(MapArr.value.get(i)); i = size; check++; } } if(check == 0) System.out.println("Such element does not exist"); } public void printmap(mkv MapArr) { int size = MapArr.key.size(); for(int i = 0;i < size;i++) { if(MapArr.key.get(i) != null) { System.out.print(MapArr.key.get(i)); System.out.print(":"); System.out.println(MapArr.value.get(i)); } } System.out.println(" "); } }
Java
import java.util.ArrayList; import java.util.Collections; public class Merge { public static int num = 8; public static ArrayList<Integer> list = new ArrayList<Integer> (num); public static ArrayList<Integer> mergesort(ArrayList<Integer> arr) { int x = arr.size(); ArrayList<Integer> left = new ArrayList<Integer> (x/2); ArrayList<Integer> right = new ArrayList<Integer> (x/2); ArrayList<Integer> result=new ArrayList<Integer> (x); if (arr.size() <= 1) return arr; else { int center = arr.size() / 2; for(int i = 0 ; i < center;i++) { left.add(arr.get(i)); } System.out.println(left); for(int i = center; i< arr.size();i++) { right.add(arr.get(i)); } System.out.println(right); left = mergesort(left); right = mergesort(right); result = merge(left, right); return result; } } public static ArrayList<Integer> merge(ArrayList<Integer> left,ArrayList<Integer> right) { ArrayList<Integer> result = new ArrayList<Integer> (left.size() + right.size()); int ind=0; while (left.size() > 0 && right.size() > 0) { if (left.get(0) <= right.get(0)) { result.add(ind, left.get(0)); left.remove(0); ind++; } else { result.add(ind, right.get(0)); right.remove(0); ind++; } } if (left.size() > 0) result.addAll(ind, left); if (right.size() > 0) result.addAll(ind, right); return result; } public static void main(String[] args) { for (int i = 0; i < num; i++) { list.add(i); } Collections.shuffle(list); System.out.println(list); list = mergesort(list); System.out.println(list); } }
Java
public class spisok { public element head = null; public void delbeg(element elem) { if(head == null) { head = elem; } else { head=null; elem=null; } } public void delend(element elem){ if(head == null) { head = elem; } else { element cur = head; while(cur.next.next != null){ cur = cur.next; } cur.next=null; } } public void bubblesort(element elem) { boolean swapped = true; int j = 0; if(head == null){ head = elem; } else { element cur = head; while(cur.next != null){ do { if(j!=0) { j=0; cur = head; } swapped = false; if(cur.i>cur.next.i) { j++; int tmp = cur.i; cur.i = cur.next.i; cur.next.i = tmp; swapped = true; } } while(swapped); cur = cur.next; } } } public void addafter(element elem ,int elem1) { if(head == null) { head = elem; } else { element cur = head; while(cur.next != null) { if(cur.i == elem1) { elem.next=cur.next; cur.next=elem; return; } cur = cur.next; } } } public void addstart(element elem) { if(head == null) { head = elem; } else { elem.next = head; head = elem; } } public void addend(element elem) { if(head == null) { head = elem; } else { element cur = head; while(cur.next != null) { cur = cur.next; } cur.next = elem; } } public String toString() { StringBuffer sb= new StringBuffer(); sb.append("["); element current = head; while (current != null) { sb.append(current.i + " "); current = current.next; } sb.append("]"); return sb.toString(); } }
Java
public class element { public element next; public int i; public element(int i) { this.i = i; } }
Java
public class AlgEv { }
Java
public class lists { Element head = null; public void addend (Element elem) { if (head == null) { head = elem; } else { Element cur = head; while (cur.next != null) { cur = cur.next; } cur.next = elem; } } public void addbeg (Element elem) { elem.next = head; head = elem; } public void addafter (Element elem, Element aelem) { if(head==null) head = elem; else { Element cur = head; while (cur.i != aelem.i) { cur = cur.next; } elem.next = cur.next; cur.next = elem; cur = cur.next; } } public void addbefore (Element elem, Element belem) { if (head.i==elem.i) { addbeg(belem); } else { Element cur = head; while (cur.next.i != belem.i) { cur = cur.next; } elem.next = cur.next; cur.next = elem; } } public void delelem (Element elem) { if(head.i == elem.i) { head = head.next; } else { Element cur = head; while (cur.next.i != elem.i) { cur = cur.next; } cur.next = cur.next.next; } } public int howmuch() { int count=0; Element current = head; while (current != null) { current=current.next; count++; } return count; } public void search (int i) { Element current = head; while (current != null) { if (current.i == i) { System.out.println("Element " + i + " was found"); return; } else { current=current.next; } } System.out.println ("Element " + i + " was not found"); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("{ "); Element current = head; while (current != null) { sb.append (current.i + " "); current = current.next; } sb.append("}"); return sb.toString(); } }
Java
public class Element { public Element next = null; public int i; Element (int i) { this.i=i; } }
Java
import java.util.Scanner; public class DateOfBirth { public static void Data(int day, int month, int year) { int wd=0; if(month <= 2) { year=year-1; day=day+3; } wd = (1 + (day + year + year/4 - year/100 + year/400 + (31*month + 10)/12))%7; switch (wd) { case 0: {System.out.println("Your's day of birth was Sunday"); break;} case 1: {System.out.println("Your's day of birth was Monday"); break;} case 2: {System.out.println("Your's day of birth was Tuesday"); break;} case 3: {System.out.println("Your's day of birth was Wednesday"); break;} case 4: {System.out.println("Your's day of birth was Thursday"); break;} case 5: {System.out.println("Your's day of birth was Friday"); break;} case 6: {System.out.println("Your's day of birth was Saturday"); break;} } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter your date of birth (date month year): "); int day = sc.nextInt(); int month = sc.nextInt(); int year = sc.nextInt(); Data(day, month, year); } }
Java
class Element { public Element next = null; public int i; Element (int i) { this.i=i; } } public class StackOnLists { Element head = null; public String toString() { StringBuffer sb = new StringBuffer(); sb.append("{ "); Element current = head; while (current != null) { sb.append (current.i + " "); current = current.next; } sb.append("}"); return sb.toString(); } public void push(int i) { Element elem = new Element(i); elem.next = head; head = elem; } public int pop() { int p = head.i; head = head.next; return p; } public static void main(String[] args) { StackOnLists stack = new StackOnLists(); System.out.println("\tPush in stack"); for (int i=0; i<10; i++) { int k = (int)(Math.random()*100); stack.push(k); } System.out.println("Stack: " + stack); for (int i=0; i<10; i++) { int k = stack.pop(); System.out.println("Pop " + k + " form stack " + stack); } } }
Java
package pack; public class fibo { public static void main(String[] args) { long start; start = System.nanoTime(); System.out.println(fibo(7)); System.out.println("Time of running: "+(System.nanoTime()-start)+" nanosec"); start = System.nanoTime(); System.out.println(fibo_rec(10)); System.out.println("Time of running: "+(System.nanoTime()-start)+" nanosec"); } public static int fibo_rec(int n) { if(n <= 0) return 0; else if(n == 1) return 1; else return fibo_rec(n-1) + fibo_rec(n-2); } public static int fibo(int n) { int a = 1, b = 1; int fib = 2, i = 2; while (i < n) { fib = a + b; a = b; b = fib; i++; } return fib; } }
Java
package pack; public class BinaryTree { public class Node { int num; Node left; Node right; Node iam; Node parent; public Node(int num, Node parent) { this.num = num; this.left = null; this.right = null; this.iam = this; this.parent = parent; } } Node root; int lenght; public BinaryTree() { root = null; lenght = 0; } public BinaryTree(int num) { root = new Node(num, null); lenght = 1; } public Node insert(int num) { lenght++; if(root == null) { root = new Node(num, null); return root; } Node node = root; while(node != null) if(num >= node.num) if(node.right == null) { node.right = new Node(num, node); return node.right; } else node = node.right; else if(num < node.num) if(node.left == null) { node.left = new Node(num, node); return node.left; } else node = node.left; lenght--; return null; } public void printTree() { System.out.println("\nLenght: " + lenght); printTree(root, 0); } private void printTree(Node node, int level) { if(node.right != null) printTree(node.right, level+1); for(int k = 0; k < level; k++) System.out.print("\t"); System.out.println(node.num); if(node.left != null) printTree(node.left, level+1); } public Node search(int num) { Node minNode = root; Node maxNode = root; Node node = root; while(node != null) if(num == node.num) return node; else if(num > node.num) { if(maxNode.num < node.num) maxNode = node; minNode = node; node = node.right; } else if(num < node.num) { if(minNode.num > node.num) minNode = node; maxNode = node; node = node.left; } if(maxNode.num - num <= num - minNode.num) return maxNode; else return minNode; } public Node getMax() { Node node = root; while(node.right != null) node = node.right; return node; } public Node getMin() { Node node = root; while(node.left != null) node = node.left; return node; } public boolean remove(int num) { return remove(num, root); } private boolean remove(int num, Node node) { while(node != null) { if(num < node.num) node = node.left; else if(num > node.num) node = node.right; else if(num == node.num) { if(node.left != null && node.right != null) { if(node.right.left == null) { node.right.left = node.left; if(node == root) root = node.right; else if(node.parent.left == node) node.parent.left = node.right; else if(node.parent.right == node) node.parent.right = node.right; lenght--; return true; } else { Node nodeLeft = node.right.left; while(nodeLeft.left != null) nodeLeft = nodeLeft.left; node.num = nodeLeft.num; return remove(nodeLeft.num, nodeLeft); } } else { if(node.left == null && node.right == null) { if(node == root) root = null; else if(node.parent.left == node) node.parent.left = null; else if(node.parent.right == node) node.parent.right = null; } else if(node.left != null) { if(node == root) root = node.left; else if(node.parent.left == node) node.parent.left = node.left; else if(node.parent.right == node) node.parent.right = node.left; } else if(node.right != null) { if(node == root) root = node.right; else if(node.parent.left == node) node.parent.left = node.right; else if(node.parent.right == node) node.parent.right = node.right; } lenght--; return true; } } } return false; } public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int amount = 5; for(int k = 0; k < amount; k++) { int number = (int) (Math.random()*amount*2-amount); System.out.print(number + ","); tree.insert(number); } tree.printTree(); System.out.println("Remove: " + 4 + " : " + tree.remove(4)); int search = (int) (Math.random()*amount*2-amount); int searchNum = tree.search(search).num; System.out.println("Search: " + search); System.out.println("Search Num: " + searchNum); System.out.println("Remove: " + searchNum + " : " + tree.remove(searchNum)); System.out.println("Remove: " + searchNum/2 + " : " + tree.remove(searchNum/2)); System.out.println("Min: " + tree.getMin()); System.out.println("Max: " + tree.getMax()); tree.printTree(); } }
Java
package pack; import java.util.Scanner; public class searchs { public static void randomArr(int arr[]) { for(int k = 0; k < arr.length; k++) arr[k] = (int)(Math.random()*arr.length); } public static void printArr(int arr[]) { for(int k = 0; k < arr.length; k++) System.out.print(arr[k] + " "); System.out.println(); } public static void main(String[] args) { int num = 100; int arr[] = new int[num]; randomArr(arr); sort.qSort(arr); printArr(arr); Scanner cin = new Scanner(System.in); System.out.print("Print find number: "); int enter = cin.nextInt(); System.out.println("Enter: " + enter); System.out.println("Number: " + binarySearch(arr, enter)); } public static int binarySearch(int arr[], int enter) { return binarySearch(arr, enter, 0, arr.length-1); } private static int binarySearch(int[] arr, int enter, int left, int right) { if(left > right) return -1; int mid = left + (right - left) / 2; if(enter < arr[mid]) return binarySearch(arr, enter, left, mid-1); else if(enter > arr[mid]) return binarySearch(arr, enter, mid+1, right); else return mid; } }
Java
package pack; public class nod { public static void main(String[] args) { int a = 300000; int b = 1701; long start; start = System.nanoTime(); System.out.println("Nod: " + nod(a, b)); System.out.println("Time of running: "+(System.nanoTime()-start)+" nanosec"); start = System.nanoTime(); System.out.println("Evclid: " + evclid(a, b)); System.out.println("Time of running: "+(System.nanoTime()-start)+" nanosec"); } public static int nod(int a, int b) { if (b == 0) return a; int x = a % b; return nod(b, x); } public static int evclid(int a, int b) { while (b !=0) { int tmp = a % b; a = b; b = tmp; } return a; } }
Java
package pack; public class TreeHeap { int arr[]; public TreeHeap() { // int mass[] = {0,2,3,2,4,5,7,9,6,8,9,11,8,9}; arr = new int[11]; } private int getLeft(int i) { if(0 < 2*i && 2*i < arr.length) return arr[2*i]; return 0; } private int getRight(int i) { if(0 < 2*i+1 && 2*i+1 < arr.length) return arr[2*i+1]; return 0; } public int getMin() { return arr[1]; } public void printTree() { printTree(1, 0); } private void printTree(int num, int level) { if(getLeft(num) != 0) printTree(2*num, level+1); for(int i = 0; i < level; i++) System.out.print("\t"); System.out.println(arr[num]); if(getRight(num) != 0) printTree(2*num+1, level+1); } public void insert(int num) { int i = arr.length-1; if(arr[i] != 0) makeNewArray(); else while(arr[i] == 0 && i > 0) i--; // System.out.println("Insert - arr[" + i + "]: " + arr[i]); arr[++i] = num; while(arr[i/2] > arr[i]) { swap(i/2, i); i = i/2; } } private void swap(int a, int b) { int tmp = arr[a]; arr[a] = arr[b]; arr[b] = tmp; } private void makeNewArray() { int mass[] = new int[ (int) (arr.length*3/2) ]; for(int i = 0; i < arr.length; i++) mass[i] = arr[i]; arr = mass; } public int removeMin() { int exitNum = arr[1]; int i = arr.length-1; while(arr[i] == 0) i--; arr[1] = arr[i]; arr[i] = 0; i = 1; while(arr[i] > getLeft(i) && getLeft(i) != 0 || arr[i] > getRight(i) && getRight(i) != 0) if(arr[i] > getLeft(i) && getLeft(i) != 0 && getLeft(i) < getRight(i) && getRight(i) != 0) { swap(i, 2*i); i = 2*i; } else { swap(i, 2*i+1); i = 2*i+1; } return exitNum; } public static void main(String[] args) { TreeHeap tree = new TreeHeap(); for(int k = 0; k < 15; k++) tree.insert((int)(Math.random()*10+1)); tree.printTree(); System.out.println("-------------------------------"); tree.removeMin(); tree.printTree(); } }
Java
package pack; public class TwoThreeFourTree { public class Node { int type; int nodes; int num1; int num2; int num3; Node node1; Node node2; Node node3; Node node4; Node parent; public Node(int num) { this.type = 1; this.nodes = 0; this.num1 = num; this.parent = null; } public boolean insert(int num) { if(type == 1) { if(num < num1) { num2 = num1; num1 = num; node3 = node2; node2 = node1; node1 = null; } else if(num >= num1) { num2 = num; // node3 = null; } type++; if(nodes != 0) nodes++; return true; } else if(type == 2) { if(num < num1) { num3 = num2; num2 = num1; num1 = num; node4 = node3; node3 = node2; node2 = node1; node1 = null; } else if(num >= num1 && num < num2) { num3 = num2; num2 = num; node4 = node3; node3 = node2; } else if(num >= num2) { num3 = num; // node4 = null; } type++; if(nodes != 0) nodes++; return true; } return false; } } Node root; int lenght; public TwoThreeFourTree() { this.root = null; this.lenght = 0; } public TwoThreeFourTree(int mass[]) { this.root = null; this.lenght = 0; for(int k = 0; k < mass.length; k++) { insert(mass[k]); System.out.println("\nInsert: " + mass[k]); printTree(); } } public Node insert(int num) { lenght++; if(root == null) { root = new Node(num); return root; } return insert(num, root); } private Node insert(int num, Node node) { if(node.type == 3) { Node newNode = new Node(node.num2); newNode.node1 = new Node(node.num1); newNode.node2 = new Node(node.num3); newNode.nodes = 2; newNode.node1.node1 = node.node1; newNode.node1.node2 = node.node2; newNode.node2.node1 = node.node3; newNode.node2.node2 = node.node4; if(newNode.node1.node1 != null) { newNode.node1.nodes++; newNode.node1.node1.parent = newNode.node1; } if(newNode.node1.node2 != null) { newNode.node1.nodes++; newNode.node1.node2.parent = newNode.node1; } if(newNode.node2.node1 != null) { newNode.node2.nodes++; newNode.node2.node1.parent = newNode.node2; } if(newNode.node2.node2 != null) { newNode.node2.nodes++; newNode.node2.node2.parent = newNode.node2; } if(node == root) { newNode.node1.parent = newNode; newNode.node2.parent = newNode; root = newNode; } else { if(node.parent.insert(node.num2)) { newNode.node1.parent = node.parent; newNode.node2.parent = node.parent; if(node.parent.type == 3 && node.parent.num3 == node.num2) { node.parent.node4 = newNode.node2; node.parent.node3 = newNode.node1; } else if(node.parent.type >= 2 && node.parent.num2 == node.num2) { node.parent.node3 = newNode.node2; node.parent.node2 = newNode.node1; } else if(node.parent.type >= 1 && node.parent.num1 == node.num2) { node.parent.node2 = newNode.node2; node.parent.node1 = newNode.node1; } } else System.out.println("1node.insert Bad!"); } if(num < newNode.num1) node = newNode.node1; else if(num >= newNode.num1) node = newNode.node2; } if(node.nodes == 0) { if(!node.insert(num)) System.out.println("2node.insert Bad!"); else return node; } else if(node.nodes == 2) { if(num < node.num1) node = insert(num, node.node1); else node = insert(num, node.node2); } else if(node.nodes == 3) { if(num < node.num1) node = insert(num, node.node1); else if(num >= node.num1 && num < node.num2) node = insert(num, node.node2); else if(num >= node.num3) node = insert(num, node.node3); } return node; } public void printTree() { // System.out.println("\nLenght: " + lenght); // System.out.println(); if(root != null) printTree(root, 0, 1); } private void printTree(Node node, int level, int trail) { if(node.node4 != null) printTree(node.node4, level+1, 4); if(node.node3 != null) printTree(node.node3, level+1, 3); if(node.type == 1) if(node.node2 != null) printTree(node.node2, level+1, 2); for(int k = 0; k < level; k++) System.out.print("\t"); System.out.println(printNode(node)); if(node.type != 1) if(node.node2 != null) printTree(node.node2, level+1, 2); if(node.node1 != null) printTree(node.node1, level+1, 1); } public String printNode(Node node) { if(node != null) { int trail = 0; if(node == root || node.parent.node1 == node) trail = 1; else if(node.parent.node2 == node) trail = 2; else if(node.parent.node3 == node) trail = 3; else if(node.parent.node4 == node) trail = 4; if(node.type == 1) return (String) (/*node.type + "|" + node.nodes + */trail + "[" + node.num1 + "]"); else if(node.type == 2) return (String) (/*node.type + "|" + node.nodes + */trail + "[" + node.num1 + ", " + node.num2 + "]"); else if(node.type == 3) return (String) (/*node.type + "|" + node.nodes + */trail + "[" + node.num1 + ", " + node.num2 + ", " + node.num3 + "]"); } return null; } public Node search(int num) { Node parent = root; Node node = root; while(node != null) { int type = node.type; int num1 = node.num1; int num2 = node.num2; int num3 = node.num3; if((type == 3 && num3 == num) || (type >= 2 && num2 == num) || (type >= 1 && num1 == num)) return node; else { parent = node; if(type == 3 && num > num3) node = node.node4; else if(type >= 2 && num > num2) node = node.node3; else if(type >= 1 && num > num1) node = node.node2; else node = node.node1; } } return parent; } public static void main(String[] args) { // int mass[] = {-9,-4,-5,5,4,4,2,5,6,0}; // TwoThreeFourTree tree = new TwoThreeFourTree(mass); TwoThreeFourTree tree = new TwoThreeFourTree(); int amount = 10; for(int k = 0; k < amount; k++) { int number = (int) (Math.random()*amount*2-amount); System.out.print(number + ","); tree.insert(number); } System.out.println(); tree.printTree(); // System.out.println("Remove: " + 4 + " : " + tree.remove(4)); int search = (int) (Math.random()*amount*2-amount); Node searchNode = tree.search(search); System.out.println("Search: " + search); System.out.println("Node: " + tree.printNode(searchNode)); // System.out.println("Remove: " + searchNum + " : " + tree.remove(searchNum)); // System.out.println("Remove: " + searchNum/2 + " : " + tree.remove(searchNum/2)); // System.out.println(tree.getMin()); // System.out.println(tree.getMax()); // // tree.printTree(); } }
Java
package pack; class ElementStack { int num; ElementStack next; public ElementStack(int num) { this.num = num; next = null; } } public class Stack { ElementStack head = null; int lenght = 0; public Stack() { this.head = null; lenght = 0; } private String toStr() { StringBuffer sb = new StringBuffer(); ElementStack current = head; sb.append("["); while(current != null) { sb.append(current.num); current = current.next; if(current != null) sb.append(","); } sb.append("]"); return sb.toString(); } private void push(int num) { ElementStack newElement = new ElementStack(num); newElement.next = head; head = newElement; } private int pop() { int exitNum = head.num; head = head.next; return exitNum; } private int top() { return head.num; } public static void main(String[] args) { int num = 10; Stack stack = new Stack(); stack.push(10); for(int k = 0; k < num; k++) stack.push((int)(Math.random()*num)); // stack.push(0); System.out.println(stack.toStr()); System.out.println(stack.top()); System.out.println(stack.toStr()); System.out.println(stack.pop()); System.out.println(stack.toStr()); } }
Java
package pack; class ElementCycled { int num; ElementCycled next; ElementCycled prev; public ElementCycled(int num) { this.num = num; next = this; prev = this; } } public class CycledList { ElementCycled sentry = null; int lenght = 0; public CycledList() { sentry = new ElementCycled(0); lenght = 0; } private String toStr() { StringBuffer sb = new StringBuffer(); ElementCycled current = sentry.next; sb.append("["); while(current != sentry) { sb.append(current.num); current = current.next; if(current != sentry) sb.append(","); } sb.append("]"); return sb.toString(); } private int lenght() { return lenght; } private void addToEnd(int num) { ElementCycled newElement = new ElementCycled(num); sentry.prev.next = newElement; newElement.prev = sentry.prev; newElement.next = sentry; sentry.prev = newElement; lenght++; } private void addToBegin(int num) { ElementCycled newElement = new ElementCycled(num); sentry.next.prev = newElement; newElement.next = sentry.next; newElement.prev = sentry; sentry.next = newElement; lenght++; } private ElementCycled search(int num) { ElementCycled current = sentry.next; while(current != sentry) { if(current.num == num) return current; current = current.next; } return null; } private boolean remove(int num) { ElementCycled current = sentry.next; while(current != sentry) { if(current.num == num) { current.next.prev = current.prev; current.prev.next = current.next; lenght--; return true; } current = current.next; } return false; } public static void main(String[] args) { CycledList list = new CycledList(); list.addToEnd(-1); list.addToBegin(0); list.addToEnd(1); list.addToEnd(2); list.addToBegin(3); System.out.println(list.toStr()); list.remove(3); list.remove(-1); list.remove(2); // System.out.println(list.search(-1)); System.out.println(list.toStr()); } }
Java
package pack; import java.awt.List; import java.io.File; import java.util.Vector; class Trunk { String path; int iByte; Vector<Trunk> sons; public Trunk(String path) { this.path = path; this.iByte = 0; sons = new Vector<Trunk>(); } } public class TreeForDirectory { Trunk root; public TreeForDirectory(String path) { root = new Trunk(path); root.iByte = createTree(root); } private int createTree(Trunk trunk) { int sizeByte = 0; File tmp = new File(trunk.path); File[] files = tmp.listFiles(); for(int k = 0; k < files.length; k++) if(files[k].isDirectory()) { Trunk tmpTrunk = new Trunk(files[k].getPath()); tmpTrunk.iByte = createTree(tmpTrunk); sizeByte += tmpTrunk.iByte; trunk.sons.add(tmpTrunk); } else sizeByte += files[k].length(); return sizeByte; } public void printTree() { printTree(root, 0); } private void printTree(Trunk trunk, int level) { for(int k = 0; k < level; k++) System.out.print("\t"); System.out.println(trunk.path + " - " + trunk.iByte + "b"); for(int k = 0; k < trunk.sons.size(); k++) printTree(trunk.sons.get(k), level+1); } public static void main(String[] args) { TreeForDirectory tree = new TreeForDirectory(".."); tree.printTree(); } }
Java