code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* 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.
*/
/**
* Test utilities for the {@code com.google.api.client.googleapis} package.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.testing.services;
| Java |
/*
* 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.api.client.googleapis.testing.services;
import com.google.api.client.googleapis.services.AbstractGoogleClient;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.UriTemplate;
/**
* Thread-safe mock Google request.
*
* @param <T> type of the response
* @since 1.12
* @author Yaniv Inbar
*/
public class MockGoogleClientRequest<T> extends AbstractGoogleClientRequest<T> {
/**
* @param client Google client
* @param method HTTP Method
* @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/"
* the base path from the base URL will be stripped out. The URI template can also be a
* full URL. URI template expansion is done using
* {@link UriTemplate#expand(String, String, Object, boolean)}
* @param content HTTP content or {@code null} for none
* @param responseClass response class to parse into
*/
public MockGoogleClientRequest(AbstractGoogleClient client, String method, String uriTemplate,
HttpContent content, Class<T> responseClass) {
super(client, method, uriTemplate, content, responseClass);
}
@Override
public MockGoogleClientRequest<T> setDisableGZipContent(boolean disableGZipContent) {
return (MockGoogleClientRequest<T>) super.setDisableGZipContent(disableGZipContent);
}
@Override
public MockGoogleClientRequest<T> setRequestHeaders(HttpHeaders headers) {
return (MockGoogleClientRequest<T>) super.setRequestHeaders(headers);
}
}
| Java |
/*
* Copyright (c) 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.
*/
/**
* Test utilities for the Subscriptions extension package.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.14
* @author Matthias Linder (mlinder)
*/
package com.google.api.client.googleapis.testing.subscriptions;
| Java |
/*
* Copyright (c) 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.api.client.googleapis.testing.subscriptions;
import com.google.api.client.googleapis.subscriptions.NotificationCallback;
import com.google.api.client.googleapis.subscriptions.Subscription;
import com.google.api.client.googleapis.subscriptions.UnparsedNotification;
/**
* Mock for the {@link NotificationCallback} class.
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@SuppressWarnings("rawtypes")
public class MockNotificationCallback implements NotificationCallback {
private static final long serialVersionUID = 0L;
/** True if this handler was called. */
private boolean wasCalled = false;
/** Returns {@code true} if this handler was called. */
public boolean wasCalled() {
return wasCalled;
}
public MockNotificationCallback() {
}
public void handleNotification(
Subscription subscription, UnparsedNotification notification) {
wasCalled = true;
}
}
| Java |
/*
* Copyright (c) 2010 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.api.client.googleapis;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.util.Key;
/**
* Generic Google URL providing for some common query parameters used in Google API's such as the
* {@link #alt} and {@link #fields} parameters.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.0
* @author Yaniv Inbar
* @deprecated (scheduled to be removed in 1.14) Use {@link GenericUrl}
*/
@Deprecated
public class GoogleUrl extends GenericUrl {
/** Whether to pretty print the output. */
@Key("prettyPrint")
private Boolean prettyprint;
/** Alternate wire format. */
@Key
private String alt;
/** Partial fields mask. */
@Key
private String fields;
/**
* API key as described in the <a href="https://code.google.com/apis/console-help/">Google APIs
* Console documentation</a>.
*/
@Key
private String key;
/**
* User IP used to enforce per-user limits for server-side applications, as described in the <a
* href="https://code.google.com/apis/console-help/#EnforceUserLimits">Google APIs Console
* documentation</a>.
*/
@Key("userIp")
private String userip;
public GoogleUrl() {
}
/**
* @param encodedUrl encoded URL, including any existing query parameters that should be parsed
*/
public GoogleUrl(String encodedUrl) {
super(encodedUrl);
}
@Override
public GoogleUrl clone() {
return (GoogleUrl) super.clone();
}
/**
* Returns whether to pretty print the output.
*
* @since 1.8
*/
public Boolean getPrettyPrint() {
return prettyprint;
}
/**
* Sets whether to pretty print the output.
*
* @since 1.8
*/
public void setPrettyPrint(Boolean prettyPrint) {
this.prettyprint = prettyPrint;
}
/**
* Returns the alternate wire format.
*
* @since 1.8
*/
public final String getAlt() {
return alt;
}
/**
* Sets the alternate wire format.
*
* @since 1.8
*/
public final void setAlt(String alt) {
this.alt = alt;
}
/**
* Returns the partial fields mask.
*
* @since 1.8
*/
public final String getFields() {
return fields;
}
/**
* Sets the partial fields mask.
*
* @since 1.8
*/
public final void setFields(String fields) {
this.fields = fields;
}
/**
* Returns the API key as described in the <a
* href="https://code.google.com/apis/console-help/">Google APIs Console documentation</a>.
*
* @since 1.8
*/
public final String getKey() {
return key;
}
/**
* Sets the API key as described in the <a
* href="https://code.google.com/apis/console-help/">Google APIs Console documentation</a>.
*
* @since 1.8
*/
public final void setKey(String key) {
this.key = key;
}
/**
* Returns the user IP used to enforce per-user limits for server-side applications, as described
* in the <a href="https://code.google.com/apis/console-help/#EnforceUserLimits">Google APIs
* Console documentation</a>.
*
* @since 1.8
*/
public final String getUserIp() {
return userip;
}
/**
* Sets the user IP used to enforce per-user limits for server-side applications, as described in
* the <a href="https://code.google.com/apis/console-help/#EnforceUserLimits">Google APIs Console
* documentation</a>.
*
* @since 1.8
*/
public final void setUserIp(String userip) {
this.userip = userip;
}
}
| Java |
/*
* Copyright (c) 2010 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.api.client.googleapis;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.util.Key;
import com.google.api.client.util.escape.PercentEscaper;
/**
* HTTP headers for Google API's.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.0
* @author Yaniv Inbar
* @deprecated (scheduled to be removed in 1.14) Use {@link HttpHeaders}
*/
@Deprecated
public class GoogleHeaders extends HttpHeaders {
/** Escaper for the {@link #slug} header. */
public static final PercentEscaper SLUG_ESCAPER =
new PercentEscaper(" !\"#$&'()*+,-./:;<=>?@[\\]^_`{|}~", false);
/** {@code "GData-Version"} header. */
@Key("GData-Version")
private String gdataVersion;
/**
* Escaped {@code "Slug"} header value, which must be escaped using {@link #SLUG_ESCAPER}.
*
* @see #setSlugFromFileName(String)
*/
@Key("Slug")
private String slug;
/** {@code "X-GData-Client"} header. */
@Key("X-GData-Client")
private String gdataClient;
/**
* {@code "X-GData-Key"} header, which must be of the form {@code "key=[developerId]"}.
*
* @see #setDeveloperId(String)
*/
@Key("X-GData-Key")
private String gdataKey;
/** {@code "X-HTTP-Method-Override"} header. */
@Key("X-HTTP-Method-Override")
private String methodOverride;
/** {@code "X-Upload-Content-Length"} header. */
@Key("X-Upload-Content-Length")
private Long uploadContentLength;
/** {@code "X-Upload-Content-Type"} header. */
@Key("X-Upload-Content-Type")
private String uploadContentType;
/**
* Creates an empty GoogleHeaders object.
*/
public GoogleHeaders() {
}
/**
* Creates a GoogleHeaders object using the headers present in the specified {@link HttpHeaders}.
*
* @param headers HTTP headers object including set headers
* @since 1.11
*/
public GoogleHeaders(HttpHeaders headers) {
this.fromHttpHeaders(headers);
}
/**
* Sets the {@code "Slug"} header for the given file name, properly escaping the header value. See
* <a href="http://tools.ietf.org/html/rfc5023#section-9.7">The Slug Header</a>.
*/
public void setSlugFromFileName(String fileName) {
slug = SLUG_ESCAPER.escape(fileName);
}
/**
* Sets the {@code "User-Agent"} header of the form
* {@code "[company-id]-[app-name]/[app-version]"}, for example {@code "Google-Sample/1.0"}.
*/
public void setApplicationName(String applicationName) {
setUserAgent(applicationName);
}
/** Sets the {@link #gdataKey} header using the given developer ID. */
public void setDeveloperId(String developerId) {
gdataKey = "key=" + developerId;
}
/**
* Sets the Google Login {@code "Authorization"} header for the given authentication token.
*/
public void setGoogleLogin(String authToken) {
setAuthorization(getGoogleLoginValue(authToken));
}
/**
* Returns the {@code "X-Upload-Content-Length"} header or {@code null} for none.
*
* <p>
* Upgrade warning: this method now returns a {@link Long}. In prior version 1.11 it returned a
* {@code long}.
* </p>
*
* @since 1.7
*/
public final Long getUploadContentLength() {
return uploadContentLength;
}
/**
* Sets the {@code "X-Upload-Content-Length"} header or {@code null} for none.
*
* @since 1.12
*/
public final void setUploadContentLength(Long uploadContentLength) {
this.uploadContentLength = uploadContentLength;
}
/**
* Sets the {@code "X-Upload-Content-Length"} header.
*
* @since 1.7
*/
@Deprecated
public final void setUploadContentLength(long uploadContentLength) {
this.uploadContentLength = uploadContentLength;
}
/**
* Returns the {@code "X-Upload-Content-Type"} header or {@code null} for none.
*
* @since 1.7
*/
public final String getUploadContentType() {
return uploadContentType;
}
/**
* Sets the {@code "X-Upload-Content-Type"} header or {@code null} for none.
*
* @since 1.7
*/
public final void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
/**
* Returns Google Login {@code "Authorization"} header value based on the given authentication
* token.
* @deprecated (scheduled to be removed in 1.14) Use
* {@code ClientLogin.getAuthorizationHeaderValue}
*/
@Deprecated
public static String getGoogleLoginValue(String authToken) {
return "GoogleLogin auth=" + authToken;
}
/**
* Returns the {@code "GData-Version"} header.
*
* @since 1.8
*/
public final String getGDataVersion() {
return gdataVersion;
}
/**
* Sets the {@code "GData-Version"} header.
*
* @since 1.8
*/
public final void setGDataVersion(String gdataVersion) {
this.gdataVersion = gdataVersion;
}
/**
* Returns the escaped {@code "Slug"} header value, which must be escaped using
* {@link #SLUG_ESCAPER}.
*
* @since 1.8
*/
public final String getSlug() {
return slug;
}
/**
* Sets the escaped {@code "Slug"} header value, which must be escaped using
* {@link #SLUG_ESCAPER}.
*
* @since 1.8
*/
public final void setSlug(String slug) {
this.slug = slug;
}
/**
* Returns the {@code "X-GData-Client"} header.
*
* @since 1.8
*/
public final String getGDataClient() {
return gdataClient;
}
/**
* Sets the {@code "X-GData-Client"} header.
*
* @since 1.8
*/
public final void setGDataClient(String gdataClient) {
this.gdataClient = gdataClient;
}
/**
* Returns the {@code "X-GData-Key"} header, which must be of the form {@code "key=[developerId]"}
* .
*
* @since 1.8
*/
public final String getGDataKey() {
return gdataKey;
}
/**
* Sets the {@code "X-GData-Key"} header, which must be of the form {@code "key=[developerId]"}.
*
* @since 1.8
*/
public final void setGDataKey(String gdataKey) {
this.gdataKey = gdataKey;
}
/**
* Returns the {@code "X-HTTP-Method-Override"} header.
*
* @since 1.8
*/
public final String getMethodOverride() {
return methodOverride;
}
/**
* Sets the {@code "X-HTTP-Method-Override"} header.
*
* @since 1.8
*/
public final void setMethodOverride(String methodOverride) {
this.methodOverride = methodOverride;
}
}
| Java |
/*
* Copyright (c) 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.api.client.googleapis.extensions.android.accounts;
import com.google.common.base.Preconditions;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
/**
* Account manager wrapper for Google accounts.
*
* @since 1.11
* @author Yaniv Inbar
*/
public final class GoogleAccountManager {
/** Google account type. */
public static final String ACCOUNT_TYPE = "com.google";
/** Account manager. */
private final AccountManager manager;
/**
* @param accountManager account manager
*/
public GoogleAccountManager(AccountManager accountManager) {
this.manager = Preconditions.checkNotNull(accountManager);
}
/**
* @param context context from which to retrieve the account manager
*/
public GoogleAccountManager(Context context) {
this(AccountManager.get(context));
}
/**
* Returns the account manager.
*
* @since 1.8
*/
public AccountManager getAccountManager() {
return manager;
}
/**
* Returns all Google accounts.
*
* @return array of Google accounts
*/
public Account[] getAccounts() {
return manager.getAccountsByType("com.google");
}
/**
* Returns the Google account of the given {@link Account#name}.
*
* @param accountName Google account name or {@code null} for {@code null} result
* @return Google account or {@code null} for none found or for {@code null} input
*/
public Account getAccountByName(String accountName) {
if (accountName != null) {
for (Account account : getAccounts()) {
if (accountName.equals(account.name)) {
return account;
}
}
}
return null;
}
/**
* Invalidates the given Google auth token by removing it from the account manager's cache (if
* necessary) for example if the auth token has expired or otherwise become invalid.
*
* @param authToken auth token
*/
public void invalidateAuthToken(String authToken) {
manager.invalidateAuthToken(ACCOUNT_TYPE, authToken);
}
}
| Java |
/*
* Copyright (c) 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.
*/
/**
* Utilities for Account Manager for Google accounts on Android Eclair (SDK 2.1) and later.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.11
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.extensions.android.accounts;
| Java |
/*
* 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.api.client.googleapis.extensions.android.gms.auth;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.common.base.Preconditions;
import java.io.IOException;
/**
* Wraps a {@link GoogleAuthException} into an {@link IOException} so it can be caught directly.
*
* <p>
* Use {@link #getCause()} to get the wrapped {@link GoogleAuthException}.
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
public class GoogleAuthIOException extends IOException {
private static final long serialVersionUID = 1L;
/**
* @param wrapped wrapped {@link GoogleAuthException}
*/
GoogleAuthIOException(GoogleAuthException wrapped) {
initCause(Preconditions.checkNotNull(wrapped));
}
@Override
public GoogleAuthException getCause() {
return (GoogleAuthException) super.getCause();
}
}
| Java |
/*
* 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.
*/
/**
* Utilities based on <a href="https://developers.google.com/android/google-play-services/">Google
* Play services</a>.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.extensions.android.gms.auth;
| Java |
/*
* 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.api.client.googleapis.extensions.android.gms.auth;
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
import com.google.android.gms.common.GooglePlayServicesUtil;
import android.app.Activity;
import java.io.IOException;
/**
* Wraps a {@link GooglePlayServicesAvailabilityException} into an {@link IOException} so it can be
* caught directly.
*
* <p>
* Use {@link #getConnectionStatusCode()} to display the error dialog. Alternatively, use
* {@link #getCause()} to get the wrapped {@link GooglePlayServicesAvailabilityException}. Example
* usage:
* </p>
*
* <pre>
} catch (final GooglePlayServicesAvailabilityIOException availabilityException) {
myActivity.runOnUiThread(new Runnable() {
public void run() {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
availabilityException.getConnectionStatusCode(),
myActivity,
MyActivity.REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
});
* </pre>
*
* @since 1.12
* @author Yaniv Inbar
*/
public class GooglePlayServicesAvailabilityIOException extends UserRecoverableAuthIOException {
private static final long serialVersionUID = 1L;
GooglePlayServicesAvailabilityIOException(GooglePlayServicesAvailabilityException wrapped) {
super(wrapped);
}
@Override
public GooglePlayServicesAvailabilityException getCause() {
return (GooglePlayServicesAvailabilityException) super.getCause();
}
/**
* Returns the error code to use with
* {@link GooglePlayServicesUtil#getErrorDialog(int, Activity, int)}.
*/
public final int getConnectionStatusCode() {
return getCause().getConnectionStatusCode();
}
}
| Java |
/*
* 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.api.client.googleapis.extensions.android.gms.auth;
import com.google.android.gms.auth.UserRecoverableAuthException;
import android.app.Activity;
import android.content.Intent;
import java.io.IOException;
/**
* Wraps a {@link UserRecoverableAuthException} into an {@link IOException} so it can be caught
* directly.
*
* <p>
* Use {@link #getIntent()} to allow user interaction to recover. Alternatively, use
* {@link #getCause()} to get the wrapped {@link UserRecoverableAuthException}. Example usage:
* </p>
*
* <pre>
} catch (UserRecoverableAuthIOException userRecoverableException) {
myActivity.startActivityForResult(
userRecoverableException.getIntent(), MyActivity.REQUEST_AUTHORIZATION);
}
* </pre>
*
* @since 1.12
* @author Yaniv Inbar
*/
public class UserRecoverableAuthIOException extends GoogleAuthIOException {
private static final long serialVersionUID = 1L;
UserRecoverableAuthIOException(UserRecoverableAuthException wrapped) {
super(wrapped);
}
@Override
public UserRecoverableAuthException getCause() {
return (UserRecoverableAuthException) super.getCause();
}
/**
* Returns the {@link Intent} that when supplied to
* {@link Activity#startActivityForResult(Intent, int)} will allow user intervention.
*/
public final Intent getIntent() {
return getCause().getIntent();
}
}
| Java |
/*
* 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.api.client.googleapis.extensions.android.gms.auth;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.AccountPicker;
import com.google.api.client.googleapis.extensions.android.accounts.GoogleAccountManager;
import com.google.api.client.http.BackOffPolicy;
import com.google.api.client.http.ExponentialBackOffPolicy;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpUnsuccessfulResponseHandler;
import com.google.common.base.Preconditions;
import android.accounts.Account;
import android.content.Context;
import android.content.Intent;
import java.io.IOException;
/**
* Manages authorization and account selection for Google accounts.
*
* <p>
* When fetching a token, any thrown {@link GoogleAuthException} would be wrapped:
* <ul>
* <li>{@link GooglePlayServicesAvailabilityException} would be wrapped inside of
* {@link GooglePlayServicesAvailabilityIOException}</li>
* <li>{@link UserRecoverableAuthException} would be wrapped inside of
* {@link UserRecoverableAuthIOException}</li>
* <li>{@link GoogleAuthException} when be wrapped inside of {@link GoogleAuthIOException}</li>
* </ul>
* </p>
*
* @since 1.12
* @author Yaniv Inbar
*/
public class GoogleAccountCredential implements HttpRequestInitializer {
/** Context. */
final Context context;
/** Scope to use on {@link GoogleAuthUtil#getToken}. */
final String scope;
/** Google account manager. */
private final GoogleAccountManager accountManager;
/**
* Selected Google account name (e-mail address), for example {@code "johndoe@gmail.com"}, or
* {@code null} for none.
*/
private String accountName;
/** Selected Google account or {@code null} for none. */
private Account selectedAccount;
/**
* @param context context
* @param scope scope to use on {@link GoogleAuthUtil#getToken}
*/
public GoogleAccountCredential(Context context, String scope) {
accountManager = new GoogleAccountManager(context);
this.context = context;
this.scope = scope;
}
/**
* Constructor a new instance using OAuth 2.0 scopes.
*
* @param context context
* @param scope first OAuth 2.0 scope
* @param extraScopes any additional OAuth 2.0 scopes
* @return new instance
*/
public static GoogleAccountCredential usingOAuth2(
Context context, String scope, String... extraScopes) {
StringBuilder scopeBuilder = new StringBuilder("oauth2:").append(scope);
for (String extraScope : extraScopes) {
scopeBuilder.append(' ').append(extraScope);
}
return new GoogleAccountCredential(context, scopeBuilder.toString());
}
/**
* Sets the audience scope to use with Google Cloud Endpoints.
*
* @param context context
* @param audience audience
* @return new instance
*/
public static GoogleAccountCredential usingAudience(Context context, String audience) {
Preconditions.checkArgument(audience.length() != 0);
return new GoogleAccountCredential(context, "audience:" + audience);
}
/**
* Sets the selected Google account name (e-mail address) -- for example
* {@code "johndoe@gmail.com"} -- or {@code null} for none.
*/
public final GoogleAccountCredential setSelectedAccountName(String accountName) {
selectedAccount = accountManager.getAccountByName(accountName);
// check if account has been deleted
this.accountName = selectedAccount == null ? null : accountName;
return this;
}
public void initialize(HttpRequest request) {
RequestHandler handler = new RequestHandler();
request.setInterceptor(handler);
request.setUnsuccessfulResponseHandler(handler);
}
/** Returns the context. */
public final Context getContext() {
return context;
}
/** Returns the scope to use on {@link GoogleAuthUtil#getToken}. */
public final String getScope() {
return scope;
}
/** Returns the Google account manager. */
public final GoogleAccountManager getGoogleAccountManager() {
return accountManager;
}
/** Returns all Google accounts or {@code null} for none. */
public final Account[] getAllAccounts() {
return accountManager.getAccounts();
}
/** Returns the selected Google account or {@code null} for none. */
public final Account getSelectedAccount() {
return selectedAccount;
}
/**
* Returns the selected Google account name (e-mail address), for example
* {@code "johndoe@gmail.com"}, or {@code null} for none.
*/
public final String getSelectedAccountName() {
return accountName;
}
/**
* Returns an intent to show the user to select a Google account, or create a new one if there are
* none on the device yet.
*
* <p>
* Must be run from the main UI thread.
* </p>
*/
public final Intent newChooseAccountIntent() {
return AccountPicker.newChooseAccountIntent(selectedAccount,
null,
new String[] {GoogleAccountManager.ACCOUNT_TYPE},
true,
null,
null,
null,
null);
}
/**
* Returns an OAuth 2.0 access token.
*
* <p>
* Must be run from a background thread, not the main UI thread.
* </p>
*/
public final String getToken() throws IOException, GoogleAuthException {
BackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
while (true) {
try {
return GoogleAuthUtil.getToken(context, accountName, scope);
} catch (IOException e) {
// network or server error, so retry using exponential backoff
long backOffMillis = backOffPolicy.getNextBackOffMillis();
if (backOffMillis == BackOffPolicy.STOP) {
throw e;
}
// sleep
try {
Thread.sleep(backOffMillis);
} catch (InterruptedException e2) {
// ignore
}
}
}
}
class RequestHandler implements HttpExecuteInterceptor, HttpUnsuccessfulResponseHandler {
/** Whether we've received a 401 error code indicating the token is invalid. */
boolean received401;
String token;
public void intercept(HttpRequest request) throws IOException {
try {
token = getToken();
request.getHeaders().setAuthorization("Bearer " + token);
} catch (GooglePlayServicesAvailabilityException e) {
throw new GooglePlayServicesAvailabilityIOException(e);
} catch (UserRecoverableAuthException e) {
throw new UserRecoverableAuthIOException(e);
} catch (GoogleAuthException e) {
throw new GoogleAuthIOException(e);
}
}
public boolean handleResponse(
HttpRequest request, HttpResponse response, boolean supportsRetry) {
if (response.getStatusCode() == 401 && !received401) {
received401 = true;
GoogleAuthUtil.invalidateToken(context, token);
return true;
}
return false;
}
}
}
| Java |
/*
* Copyright (c) 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.api.client.googleapis.extensions.appengine.subscriptions;
import com.google.api.client.googleapis.extensions.servlet.subscriptions.AbstractWebHookServlet;
import com.google.api.client.googleapis.extensions.servlet.subscriptions.WebHookDeliveryMethod;
/**
* Builds delivery method strings for subscribing to notifications via WebHook on AppEngine.
*
* <p>
* Should be used in conjunction with a {@link AbstractWebHookServlet}.
* </p>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
private static final String DELIVERY_METHOD =
new AppEngineWebHookDeliveryMethod("https://example.appspot.com/notifications").build();
...
request.subscribe(DELIVERY_METHOD, ...).execute();
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public class AppEngineWebHookDeliveryMethod extends WebHookDeliveryMethod {
/**
* Builds delivery method strings for subscribing to notifications via WebHook on AppEngine.
*
* @param callbackUrl The full URL of the registered Notification-Servlet. Should start with
* https://.
*/
public AppEngineWebHookDeliveryMethod(String callbackUrl) {
super(callbackUrl);
getUrl().set("appEngine", "true");
}
@Override
public AppEngineWebHookDeliveryMethod setHost(String host) {
super.setHost(host);
return this;
}
@Override
public AppEngineWebHookDeliveryMethod setPayloadRequested(boolean isPayloadRequested) {
super.setPayloadRequested(isPayloadRequested);
return this;
}
}
| Java |
/*
* Copyright (c) 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.
*/
/**
* Support for creating subscriptions and receiving notifications on AppEngine.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.14
* @author Matthias Linder (mlinder)
*/
package com.google.api.client.googleapis.extensions.appengine.subscriptions;
| Java |
/*
* Copyright (c) 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.api.client.googleapis.extensions.appengine.subscriptions;
import com.google.api.client.googleapis.subscriptions.Subscription;
import com.google.api.client.googleapis.subscriptions.SubscriptionStore;
import com.google.appengine.api.memcache.Expiration;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import java.io.IOException;
/**
* Implementation of a persistent {@link SubscriptionStore} making use of native DataStore and
* the Memcache API on AppEngine.
*
* <p>
* Implementation is thread-safe.
* </p>
*
* <p>
* On AppEngine you should prefer this SubscriptionStore over others due to performance and quota
* reasons.
* </p>
*
* <b>Example usage:</b>
* <pre>
service.setSubscriptionStore(new CachedAppEngineSubscriptionStore());
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public final class CachedAppEngineSubscriptionStore extends AppEngineSubscriptionStore {
/** Cache expiration time in seconds. */
private static final int EXPIRATION_TIME = 3600;
/** The service instance used to access the Memcache API. */
private MemcacheService memCache = MemcacheServiceFactory.getMemcacheService(
CachedAppEngineSubscriptionStore.class.getCanonicalName());
@Override
public void removeSubscription(Subscription subscription) throws IOException {
super.removeSubscription(subscription);
memCache.delete(subscription.getSubscriptionId());
}
@Override
public void storeSubscription(Subscription subscription) throws IOException {
super.storeSubscription(subscription);
memCache.put(subscription.getSubscriptionId(), subscription);
}
@Override
public Subscription getSubscription(String subscriptionId) throws IOException {
if (memCache.contains(subscriptionId)) {
return (Subscription) memCache.get(subscriptionId);
}
Subscription subscription = super.getSubscription(subscriptionId);
memCache.put(subscriptionId, subscription, Expiration.byDeltaSeconds(EXPIRATION_TIME));
return subscription;
}
}
| Java |
/*
* Copyright (c) 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.api.client.googleapis.extensions.appengine.subscriptions;
import com.google.api.client.googleapis.subscriptions.Subscription;
import com.google.api.client.googleapis.subscriptions.SubscriptionStore;
import com.google.appengine.api.datastore.Blob;
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.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.common.collect.Lists;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
/**
* Persistent {@link SubscriptionStore} making use of native DataStore on AppEngine.
*
* <p>
* Implementation is thread-safe.
* </p>
*
* <b>Example usage:</b>
* <pre>
service.setSubscriptionStore(new AppEngineSubscriptionStore());
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public class AppEngineSubscriptionStore implements SubscriptionStore {
/** Name of the table in the AppEngine datastore. */
private static final String KIND = AppEngineSubscriptionStore.class.getName();
/** Name of the field in which the subscription is stored. */
private static final String FIELD_SUBSCRIPTION = "serializedSubscription";
/**
* Creates a new {@link AppEngineSubscriptionStore}.
*/
public AppEngineSubscriptionStore() { }
/** Serializes the specified object into a Blob using an {@link ObjectOutputStream}. */
private Blob serialize(Object obj) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
new ObjectOutputStream(baos).writeObject(obj);
return new Blob(baos.toByteArray());
} finally {
baos.close();
}
}
/** Deserializes the specified object from a Blob using an {@link ObjectInputStream}. */
@SuppressWarnings("unchecked")
private <T> T deserialize(Blob data, Class<T> dataType) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes());
try {
Object obj = new ObjectInputStream(bais).readObject();
if (!dataType.isAssignableFrom(obj.getClass())) {
return null;
}
return (T) obj;
} catch (ClassNotFoundException exception) {
throw new IOException("Failed to deserialize object", exception);
} finally {
bais.close();
}
}
/** Parses the specified Entity and returns the contained Subscription object. */
private Subscription getSubscriptionFromEntity(Entity entity) throws IOException {
Blob serializedSubscription = (Blob) entity.getProperty(FIELD_SUBSCRIPTION);
return deserialize(serializedSubscription, Subscription.class);
}
@Override
public void storeSubscription(Subscription subscription) throws IOException {
DatastoreService service = DatastoreServiceFactory.getDatastoreService();
Entity entity = new Entity(KIND, subscription.getSubscriptionId());
entity.setProperty(FIELD_SUBSCRIPTION, serialize(subscription));
service.put(entity);
}
@Override
public void removeSubscription(Subscription subscription) throws IOException {
if (subscription == null) {
return;
}
DatastoreService service = DatastoreServiceFactory.getDatastoreService();
service.delete(KeyFactory.createKey(KIND, subscription.getSubscriptionId()));
}
@Override
public List<Subscription> listSubscriptions() throws IOException {
List<Subscription> list = Lists.newArrayList();
DatastoreService service = DatastoreServiceFactory.getDatastoreService();
PreparedQuery results = service.prepare(new Query(KIND));
for (Entity entity : results.asIterable()) {
list.add(getSubscriptionFromEntity(entity));
}
return list;
}
@Override
public Subscription getSubscription(String subscriptionId) throws IOException {
try {
DatastoreService service = DatastoreServiceFactory.getDatastoreService();
Entity entity = service.get(KeyFactory.createKey(KIND, subscriptionId));
return getSubscriptionFromEntity(entity);
} catch (EntityNotFoundException exception) {
return null;
}
}
}
| Java |
/*
* Copyright (c) 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.
*/
/**
* Google App Engine utilities for OAuth 2.0 for Google APIs.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.extensions.appengine.auth.oauth2;
| Java |
/*
* Copyright (c) 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.api.client.googleapis.extensions.appengine.auth.oauth2;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.appengine.api.appidentity.AppIdentityService;
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import com.google.appengine.api.appidentity.AppIdentityServiceFailureException;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.util.List;
/**
* OAuth 2.0 credential in which a client Google App Engine application needs to access data that it
* owns, based on <a href="http://code.google.com/appengine/docs/java/appidentity/overview.html
* #Asserting_Identity_to_Google_APIs">Asserting Identity to Google APIs</a>.
*
* <p>
* Sample usage:
* </p>
*
* <pre>
public static HttpRequestFactory createRequestFactory(
HttpTransport transport, JsonFactory jsonFactory, TokenResponse tokenResponse) {
return transport.createRequestFactory(
new AppIdentityCredential("https://www.googleapis.com/auth/urlshortener"));
}
* </pre>
*
* <p>
* Implementation is immutable and thread-safe.
* </p>
*
* @since 1.7
* @author Yaniv Inbar
*/
public class AppIdentityCredential implements HttpRequestInitializer, HttpExecuteInterceptor {
/** App Identity Service that provides the access token. */
private final AppIdentityService appIdentityService;
/** OAuth scopes. */
private final ImmutableList<String> scopes;
/**
* @param scopes OAuth scopes
*/
public AppIdentityCredential(Iterable<String> scopes) {
this(AppIdentityServiceFactory.getAppIdentityService(), ImmutableList.copyOf(scopes));
}
/**
* @param scopes OAuth scopes
*/
public AppIdentityCredential(String... scopes) {
this(AppIdentityServiceFactory.getAppIdentityService(), ImmutableList.copyOf(scopes));
}
/**
* @param appIdentityService App Identity Service that provides the access token
* @param scopes OAuth scopes
*
* @since 1.12
*/
protected AppIdentityCredential(AppIdentityService appIdentityService, List<String> scopes) {
this.appIdentityService = Preconditions.checkNotNull(appIdentityService);
this.scopes = ImmutableList.copyOf(scopes);
}
@Override
public void initialize(HttpRequest request) throws IOException {
request.setInterceptor(this);
}
/**
* Intercept the request by using the access token obtained from the {@link AppIdentityService}.
*
* <p>
* Upgrade warning: in prior version 1.11 {@link AppIdentityServiceFailureException} was wrapped
* with an {@link IOException}, but now it is no longer wrapped because it is a
* {@link RuntimeException}.
* </p>
*/
@Override
public void intercept(HttpRequest request) throws IOException {
String accessToken = appIdentityService.getAccessToken(scopes).getAccessToken();
BearerToken.authorizationHeaderAccessMethod().intercept(request, accessToken);
}
/**
* Gets the App Identity Service that provides the access token.
*
* @since 1.12
*/
public final AppIdentityService getAppIdentityService() {
return appIdentityService;
}
/**
* Gets the OAuth scopes.
*
* @since 1.12
*/
public final List<String> getScopes() {
return scopes;
}
/**
* Builder for {@link AppIdentityCredential}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.12
*/
public static class Builder {
/** App Identity Service that provides the access token. */
private AppIdentityService appIdentityService;
/** OAuth scopes. */
private final ImmutableList<String> scopes;
/**
* Returns an instance of a new builder.
*
* @param scopes OAuth scopes
*/
public Builder(Iterable<String> scopes) {
this.scopes = ImmutableList.copyOf(scopes);
}
/**
* Returns an instance of a new builder.
*
* @param scopes OAuth scopes
*/
public Builder(String... scopes) {
this.scopes = ImmutableList.copyOf(scopes);
}
/**
* Sets the App Identity Service that provides the access token.
* <p>
* If not explicitly set, the {@link AppIdentityServiceFactory#getAppIdentityService()} method
* will be used to provide the App Identity Service.
* </p>
*
* <p>
* Overriding is only supported for the purpose of calling the super implementation and changing
* the return type, but nothing else.
* </p>
*/
public Builder setAppIdentityService(AppIdentityService appIdentityService) {
this.appIdentityService = Preconditions.checkNotNull(appIdentityService);
return this;
}
/**
* Returns a new {@link AppIdentityCredential}.
*/
public AppIdentityCredential build() {
AppIdentityService appIdentityService = this.appIdentityService;
if (appIdentityService == null) {
// Lazily retrieved rather than setting as the default value in order to not add runtime
// dependencies on AppIdentityServiceFactory unless it is actually being used.
appIdentityService = AppIdentityServiceFactory.getAppIdentityService();
}
return new AppIdentityCredential(appIdentityService, scopes);
}
}
}
| Java |
/*
* Copyright (c) 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.
*/
/**
* Google OAuth 2.0 utilities that help simplify the authorization flow on Java 6.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.11
* @author Yaniv Inbar
*/
package com.google.api.client.googleapis.extensions.java6.auth.oauth2;
| Java |
/*
* Copyright (c) 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.api.client.googleapis.extensions.java6.auth.oauth2;
import com.google.api.client.extensions.java6.auth.oauth2.AbstractPromptReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants;
import java.io.IOException;
/**
* Google OAuth 2.0 abstract verification code receiver that prompts user to paste the code copied
* from the browser.
*
* <p>
* Implementation is thread-safe.
* </p>
*
* @since 1.11
* @author Yaniv Inbar
*/
public class GooglePromptReceiver extends AbstractPromptReceiver {
@Override
public String getRedirectUri() throws IOException {
return GoogleOAuthConstants.OOB_REDIRECT_URI;
}
}
| Java |
/*
* Copyright (c) 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.
*/
/**
* Support for subscribing to topics and receiving notifications on servlet-based platforms.
*
* <p>
* <b>Warning: this package is experimental, and its content may be changed in incompatible ways or
* possibly entirely removed in a future version of the library</b>
* </p>
*
* @since 1.14
* @author Matthias Linder (mlinder)
*/
package com.google.api.client.googleapis.extensions.servlet.subscriptions;
| Java |
/*
* Copyright (c) 2011 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.api.client.googleapis.extensions.servlet.subscriptions;
import com.google.api.client.googleapis.subscriptions.Subscription;
import com.google.api.client.googleapis.subscriptions.SubscriptionStore;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
/**
* {@link SubscriptionStore} making use of JDO.
*
* <p>
* Implementation is thread-safe.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
service.setSubscriptionStore(new JdoSubscriptionStore());
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public final class JdoSubscriptionStore implements SubscriptionStore {
/** Persistence manager factory. */
private final PersistenceManagerFactory persistenceManagerFactory;
/**
* @param persistenceManagerFactory persistence manager factory
*/
public JdoSubscriptionStore(PersistenceManagerFactory persistenceManagerFactory) {
this.persistenceManagerFactory = persistenceManagerFactory;
}
/** Container class for storing subscriptions in the JDO DataStore. */
@PersistenceCapable
private static final class StoredSubscription {
@Persistent(serialized = "true")
private Subscription subscription;
@Persistent
@PrimaryKey
private String subscriptionId;
@SuppressWarnings("unused")
StoredSubscription() {
}
/**
* Creates a stored subscription from an existing subscription.
*
* @param s subscription to store
*/
public StoredSubscription(Subscription s) {
setSubscription(s);
}
/**
* Returns the stored subscription.
*/
public Subscription getSubscription() {
return subscription;
}
/**
* Returns the subscription ID.
*/
@SuppressWarnings("unused")
public String getSubscriptionId() {
return subscriptionId;
}
/**
* Changes the subscription stored in this database entry.
*
* @param subscription The new subscription to store
*/
public void setSubscription(Subscription subscription) {
this.subscription = subscription;
this.subscriptionId = subscription.getSubscriptionId();
}
}
public void storeSubscription(Subscription subscription) {
Preconditions.checkNotNull(subscription);
StoredSubscription dbEntry = getStoredSubscription(subscription.getSubscriptionId());
PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager();
try {
// Check if this subscription is being updated or newly created
if (dbEntry != null) {
// Existing entry
dbEntry.setSubscription(subscription);
} else {
// New entry
dbEntry = new StoredSubscription(subscription);
persistenceManager.makePersistent(dbEntry);
}
} finally {
persistenceManager.close();
}
}
public void removeSubscription(Subscription subscription) {
StoredSubscription dbEntry = getStoredSubscription(subscription.getSubscriptionId());
if (dbEntry != null) {
PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager();
try {
persistenceManager.deletePersistent(dbEntry);
} finally {
persistenceManager.close();
}
}
}
@SuppressWarnings("unchecked")
public List<Subscription> listSubscriptions() {
// Copy the results into a db-detached list.
List<Subscription> list = Lists.newArrayList();
PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager();
try {
Query listQuery = persistenceManager.newQuery(StoredSubscription.class);
Iterable<StoredSubscription> resultList = (Iterable<StoredSubscription>) listQuery.execute();
for (StoredSubscription dbEntry : resultList) {
list.add(dbEntry.getSubscription());
}
} finally {
persistenceManager.close();
}
return list;
}
@SuppressWarnings("unchecked")
private StoredSubscription getStoredSubscription(String subscriptionID) {
Iterable<StoredSubscription> results = null;
PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager();
try {
Query getByIDQuery = persistenceManager.newQuery(StoredSubscription.class);
getByIDQuery.setFilter("subscriptionId == idParam");
getByIDQuery.declareParameters("String idParam");
getByIDQuery.setRange(0, 1);
results = (Iterable<StoredSubscription>) getByIDQuery.execute(subscriptionID);
// return the first result
for (StoredSubscription dbEntry : results) {
return dbEntry;
}
return null;
} finally {
persistenceManager.close();
}
}
public Subscription getSubscription(String subscriptionID) {
StoredSubscription dbEntry = getStoredSubscription(subscriptionID);
return dbEntry == null ? null : dbEntry.getSubscription();
}
}
| Java |
/*
* Copyright (c) 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.api.client.googleapis.extensions.servlet.subscriptions;
import com.google.api.client.http.GenericUrl;
import com.google.common.base.Preconditions;
/**
* Builds delivery method strings for subscribing to notifications via WebHook.
*
* <p>
* Should be used in conjunction with a {@link AbstractWebHookServlet}.
* </p>
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
private static final String DELIVERY_METHOD =
new WebHookDeliveryMethod("https://example.com/notifications").build();
...
request.subscribe(DELIVERY_METHOD, ...).execute();
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
public class WebHookDeliveryMethod {
/** The URL which is being built. */
private GenericUrl url;
/**
* Builds delivery method strings for subscribing to notifications via WebHook.
*
* @param callbackURL The full URL of the registered Notification-Servlet. Should start with
* https://.
*/
public WebHookDeliveryMethod(String callbackURL) {
// Build the Callback URL and verify it.
Preconditions.checkArgument(new GenericUrl(callbackURL).getScheme().equalsIgnoreCase("https"),
"Callback scheme has to be https://");
// Build the Subscription URL. Only the path and query parameters will actually get.
GenericUrl url = new GenericUrl("http://example.com/web_hook");
url.set("url", callbackURL);
this.url = url;
}
/**
* Returns the URL this builder is currently building.
*/
public final GenericUrl getUrl() {
return url;
}
/**
* Builds and returns the resulting delivery method string.
*/
public final String build() {
return url.buildRelativeUrl().substring("/".length());
}
/**
* Gets the host query parameter.
*/
public final String getHost() {
return (String) url.get("host");
}
/**
* Sets the host query parameter.
*
* @param host New value for the host parameter
*/
public WebHookDeliveryMethod setHost(String host) {
url.set("host", host);
return this;
}
/**
* Returns {@code} true if notifications should contain a payload, or {@code false} if only
* invalidations should be received.
*
* <p>
* Default is {@code true}.
* </p>
*/
public final boolean isPayloadRequested() {
return !Boolean.valueOf((String) url.get("invalidate"));
}
/**
* Sets whether notifications should contain a payload, or whether only
* invalidations should be received.
*
* <p>
* Default is {@code true}.
* </p>
*/
public WebHookDeliveryMethod setPayloadRequested(boolean isPayloadRequested) {
url.set("invalidate", String.valueOf(!isPayloadRequested));
return this;
}
}
| Java |
/*
* Copyright (c) 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.api.client.googleapis.extensions.servlet.subscriptions;
import com.google.api.client.googleapis.subscriptions.NotificationHeaders;
import com.google.api.client.googleapis.subscriptions.SubscriptionHeaders;
import com.google.api.client.googleapis.subscriptions.SubscriptionStore;
import com.google.api.client.googleapis.subscriptions.UnparsedNotification;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* WebHook-Servlet used in conjunction with the {@link WebHookDeliveryMethod} to receive
* {@link UnparsedNotification}.
*
* <p>
* In order to use this servlet you should create a class inheriting from
* {@link AbstractWebHookServlet} and register the servlet in your web.xml.
* </p>
*
* <p>
* Implementation is thread-safe.
* </p>
*
* <b>Example usage:</b>
*
* <pre>
public class NotificationServlet extends AbstractWebHookServlet {
private static final long serialVersionUID = 1L;
{@literal @}Override
protected SubscriptionStore createSubscriptionStore() {
return new CachedAppEngineSubscriptionStore();
}
}
* </pre>
*
* <b>web.xml setup:</b>
*
* <pre>
<servlet>
<servlet-name>NotificationServlet</servlet-name>
<servlet-class>com.mypackage.NotificationServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NotificationServlet</servlet-name>
<url-pattern>/notificiations</url-pattern>
</servlet-mapping>
<security-constraint>
<!-- Lift any ACL imposed upon the servlet -->
<web-resource-collection>
<web-resource-name>any</web-resource-name>
<url-pattern>/notifications</url-pattern>
</web-resource-collection>
</security-constraint>
* </pre>
*
* @author Matthias Linder (mlinder)
* @since 1.14
*/
@SuppressWarnings("serial")
public abstract class AbstractWebHookServlet extends HttpServlet {
/**
* Name of header for the ID of the subscription for which you no longer wish to receive
* notifications (used in the response to a WebHook notification).
*/
public static final String UNSUBSCRIBE_HEADER = "X-Goog-Unsubscribe";
/** Subscription store or {@code null} before initialized in {@link #getSubscriptionStore()}. */
private static SubscriptionStore subscriptionStore;
/**
* Used to get access to the subscription store in order to handle incoming notifications.
*/
protected abstract SubscriptionStore createSubscriptionStore();
/** Returns the (cached) subscription store. */
public final SubscriptionStore getSubscriptionStore() {
if (subscriptionStore == null) {
subscriptionStore = createSubscriptionStore();
}
return subscriptionStore;
}
/**
* Responds to a notification with a 200 OK response with the X-Unsubscribe header which causes
* the subscription to be removed.
*/
protected void sendUnsubscribeResponse(
HttpServletResponse resp, UnparsedNotification notification) {
// Subscriptions can be removed by sending an 200 OK with the X-Unsubscribe header.
resp.setStatus(HttpServletResponse.SC_OK);
resp.setHeader(UNSUBSCRIBE_HEADER, notification.getSubscriptionId());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Parse the relevant headers and create an unparsed notification.
String subscriptionId = req.getHeader(SubscriptionHeaders.SUBSCRIPTION_ID);
String topicId = req.getHeader(SubscriptionHeaders.TOPIC_ID);
String topicUri = req.getHeader(SubscriptionHeaders.TOPIC_URI);
String eventType = req.getHeader(NotificationHeaders.EVENT_TYPE_HEADER);
String clientToken = req.getHeader(SubscriptionHeaders.CLIENT_TOKEN);
String messageNumber = req.getHeader(NotificationHeaders.MESSAGE_NUMBER_HEADER);
String changeType = req.getHeader(NotificationHeaders.CHANGED_HEADER);
if (subscriptionId == null || topicId == null || topicUri == null || eventType == null
|| messageNumber == null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
"Notification did not contain all required information.");
return;
}
// Hand over the unparsed notification to the subscription manager.
InputStream contentStream = req.getInputStream();
try {
UnparsedNotification notification = new UnparsedNotification(subscriptionId,
topicId,
topicUri,
clientToken,
Long.valueOf(messageNumber),
eventType,
changeType,
req.getContentType(),
contentStream);
if (!notification.deliverNotification(getSubscriptionStore())) {
sendUnsubscribeResponse(resp, notification);
}
} finally {
contentStream.close();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}
}
| Java |
package com.example.tenmins;
import java.util.ArrayList;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Setting_adapter extends BaseAdapter {
Context context;
ArrayList<Alarm_data> data;
LayoutInflater inflater;
static Database db;
public Setting_adapter(Context c, ArrayList<Alarm_data> data){
this.context = c;
db = new Database(c);
db.open();
this.data = data;
inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
db.close();
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.get(position).getTime();
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView == null)
convertView = inflater.inflate(R.layout.list_layout, parent, false);
if(data.get(position) != null){
ImageView clock = (ImageView)convertView.findViewById(R.id.clock);
clock.setImageResource(data.get(position).getClock());
final TextView time = (TextView)convertView.findViewById(R.id.time);
time.setText(data.get(position).getTime());
final ImageView monday = (ImageView)convertView.findViewById(R.id.monday);
monday.setImageResource(data.get(position).getDay_mon());
final ImageView tuesday = (ImageView)convertView.findViewById(R.id.tuesday);
tuesday.setImageResource(data.get(position).getDay_tue());
final ImageView wednesday = (ImageView)convertView.findViewById(R.id.wednesday);
wednesday.setImageResource(data.get(position).getDay_wed());
final ImageView thursday = (ImageView)convertView.findViewById(R.id.thursday);
thursday.setImageResource(data.get(position).getDay_thu());
final ImageView friday = (ImageView)convertView.findViewById(R.id.friday);
friday.setImageResource(data.get(position).getDay_fri());
final ImageView saturday = (ImageView)convertView.findViewById(R.id.saturday);
saturday.setImageResource(data.get(position).getDay_sat());
final ImageView sunday = (ImageView)convertView.findViewById(R.id.sunday);
sunday.setImageResource(data.get(position).getDay_sun());
//final ToggleButton on_off = (ToggleButton)convertView.findViewById(R.id.on_off);
ImageView delete = (ImageView)convertView.findViewById(R.id.delete);
delete.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
int id = data.get(position).getId();
//Setting_alarm.cancelAlarm(data.get(position).getId());
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, PopupActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.cancel(pi);
Toast.makeText(context,"알람이 해제되었습니다",Toast.LENGTH_SHORT).show();
Database ndb = new Database(context);
ndb.open();
ndb.deleteAlarmList(id);
ArrayList<Alarm_data> list = MainActivity.data;
list.remove(position);
notifyDataSetChanged();
ndb.close();
return;
}
});
final TextView am_pm = (TextView)convertView.findViewById(R.id.am_pm);
am_pm.setText(data.get(position).getAm_Pm());
convertView.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Setting_alarm.ISNEW = false;
Setting_alarm.POSITION = position;
Intent info = new Intent(context, Setting_alarm.class);
context.startActivity(info);
}
});
//convertView.setOnCreateContextMenuListener(MainActivity.contextmenu);
}
return convertView;
}
/*
public static void deleteAlarm(MenuItem item){
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getOrder();
Alarm_data selected = MainActivity.data.get(info.position);
int id = selected.getId();
db.deleteAlarmList(id);
MainActivity.data.clear();
MainActivity.setData();
MainActivity.adapter.notifyDataSetChanged();
}
*/
}
| Java |
package com.example.tenmins;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.Timer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
public class PopupActivity extends Activity{
Button exit, delay;
TextView time,hour,min;
public static int id;
Context context;
int alarmHour, alarmMin;
Timer timeTimer;
Database db;
MediaPlayer mMediaPlayer;
AudioManager audioManager;
Thread thread;
int runnable_m;
int runnable_s;
TextView popup_time;
MyHandler handler;
public static ArrayList<Activity> at_m = new ArrayList<Activity>();
public static ArrayList<Activity> at_t = new ArrayList<Activity>();
public static ArrayList<Activity> at_d = new ArrayList<Activity>();
@Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
// 키잠금 해제하기
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
// 화면 켜기
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
id = getIntent().getIntExtra("reqCode", 0);
Log.e("popup", "create");
db = new Database(this);
db.open();
GregorianCalendar currentCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"));
int date = currentCalendar.get(Calendar.DAY_OF_WEEK);
Log.e("popup", "create2"+id);
switch(date){
case 1: // sun
if(!db.isCheckedSun(id))
return;
break;
case 2: // mon
if(!db.isCheckedMon(id))
return;
break;
case 3: // sun
if(!db.isCheckedTue(id))
return;
break;
case 4: // sun
if(!db.isCheckedWed(id))
return;
break;
case 5: // sun
if(!db.isCheckedThu(id))
return;
break;
case 6: // sun
if(!db.isCheckedFri(id))
return;
break;
case 7: // sun
if(!db.isCheckedSat(id))
return;
break;
}
super.onCreate(savedInstanceState);
setContentView(R.layout.popup);
exit = (Button) findViewById(R.id.delete_popup);
delay = (Button) findViewById(R.id.delay_btn);
time = (TextView) findViewById(R.id.popup_time);
hour = (TextView) findViewById(R.id.popup_hour);
min = (TextView) findViewById(R.id.popup_min);
long time = System.currentTimeMillis();
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
int h = c.get(Calendar.HOUR_OF_DAY);
int m = c.get(Calendar.MINUTE);
if(h < 10)
hour.setText("0" + Integer.toString(h));
else
hour.setText(Integer.toString(h));
if(m < 10)
min.setText("0" + Integer.toString(m));
else
min.setText(Integer.toString(m));
exit.setOnClickListener(l);
delay.setOnClickListener(l);
context = getApplicationContext();
alarmHour = db.getHour(id);
alarmMin = db.getMin(id);
//timeTimer = new Timer();
//timeTimer.schedule(timeTimerTask, 30, 1000);
popup_time = (TextView)findViewById(R.id.popup_time);
handler = new MyHandler();
BackThread thread = new BackThread();
thread.setDaemon(true);
thread.start();
mMediaPlayer = new MediaPlayer();
audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
int setting_volume = db.getVolume(id);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, setting_volume, AudioManager.FLAG_PLAY_SOUND);
String musicID = db.getMusicID(id);
Uri uri = Uri.withAppendedPath(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, "" + musicID);
playAudio(uri);
at_m.add(this);
at_t.add(this);
at_d.add(this);
}
public void playAudio(Uri uri){
try {
mMediaPlayer.reset();
mMediaPlayer.setDataSource(this, uri);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onDestroy() {
super.onDestroy();
/* Release resources allocated to player */
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
}
class BackThread extends Thread{
public void run(){
while(true){
runnable_s++;
if(runnable_s > 59){
runnable_s = 0;
runnable_m++;
}
Message msg = Message.obtain(handler, 0, runnable_s, 0);
handler.sendMessage(msg);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
;
}
}
}
}
class MyHandler extends Handler{
@Override
public void handleMessage(Message msg){
if(msg.what == 0)
popup_time.setText(runnable_m + "분 " + msg.arg1 + "초가 지났습니다");
}
}
Button.OnClickListener l = new Button.OnClickListener(){
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.delete_popup:
int game = db.getGame(id);
switch(game){
case 0:
finish();
break;
case 1:
Intent text = new Intent(PopupActivity.this, Text.class);
startActivity(text);
break;
case 2 :
Intent multi = new Intent(PopupActivity.this, Multi.class);
startActivity(multi);
break;
}
break;
case R.id.delay_btn:
Intent delay = new Intent(PopupActivity.this, DelayAlarm.class);
delay.putExtra("id", id);
startActivity(delay);
break;
}
}
};
}
| Java |
package com.example.tenmins;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ListView list;
public static Setting_adapter adapter;
public static ArrayList<Alarm_data> data;
public static Alarm_data da;
TextView add_t;
ImageButton add;
Typeface font;
public static Database db;
static Cursor result = null;
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.add_alarm);
add_t = (TextView)findViewById(R.id.add_text);
font = Typeface.createFromAsset(getAssets(), "font1.TTF");
add_t.setTypeface(font, Typeface.BOLD);
add_t.setTextSize(20);
add_t.setOnClickListener(addListener_t);
add = (ImageButton)findViewById(R.id.add);
add.setOnClickListener(addListener);
db = new Database(this);
db.open();
setData();
adapter = new Setting_adapter(this, data);
list = (ListView)findViewById(R.id.listView1);
list.setAdapter(adapter);
db.close();
}
TextView.OnClickListener addListener_t = new TextView.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Setting_alarm.ISNEW = true;
Intent info = new Intent(MainActivity.this, Setting_alarm.class);
startActivity(info);
}
};
ImageButton.OnClickListener addListener = new ImageButton.OnClickListener(){
@Override
public void onClick(View v) {
Setting_alarm.ISNEW = true;
Intent info = new Intent(MainActivity.this, Setting_alarm.class);
startActivity(info);
}
};
public void setData(){
db = new Database(getApplicationContext());
db.open();
int hour = 0, minute = 0;
String am_pm = "";
String time = "";
int mon = 0, tue = 0, wed = 0, thu = 0, fri = 0, sat = 0, sun = 0;
int mon_image = R.drawable.monday_list,
tue_image = R.drawable.tuesday_list,
wed_image = R.drawable.wednesday_list,
thu_image = R.drawable.thursday_list,
fri_image = R.drawable.friday_list,
sat_image = R.drawable.saturday_list,
sun_image = R.drawable.sunday_list;
result = db.getAlarmList();
data = new ArrayList<Alarm_data>();
if(result.getCount() == 0)
data.clear();
if(result.moveToFirst()){
do{
hour = result.getInt(0);
minute = result.getInt(1);
time = hour + "시" + minute + "분";
am_pm = result.getString(2);
if((mon = result.getInt(3)) == 1)
mon_image = R.drawable.monday_list_checked;
if((tue = result.getInt(4)) == 1)
tue_image = R.drawable.tuesday_list_checked;
if((wed = result.getInt(5)) == 1)
wed_image = R.drawable.wednesday_list_checked;
if((thu = result.getInt(6)) == 1)
thu_image = R.drawable.thursday_list_checked;
if((fri = result.getInt(7)) == 1)
fri_image = R.drawable.friday_list_checked;
if((sat = result.getInt(8)) == 1)
sat_image = R.drawable.saturday_list_checked;
if((sun = result.getInt(9)) == 1)
sun_image = R.drawable.sunday_list_checked;
int id = result.getInt(13);
da = new Alarm_data(
R.drawable.alarm,
time,
mon_image,
tue_image,
wed_image,
thu_image,
fri_image,
sat_image,
sun_image,
am_pm,
id);
data.add(da);
mon = 0;
tue = 0;
wed = 0;
thu = 0;
fri = 0;
sat = 0;
sun = 0;
mon_image = R.drawable.monday_list;
tue_image = R.drawable.tuesday_list;
wed_image = R.drawable.wednesday_list;
thu_image = R.drawable.thursday_list;
fri_image = R.drawable.friday_list;
sat_image = R.drawable.saturday_list;
sun_image = R.drawable.sunday_list;
}while(result.moveToNext());
}
else
data.add(null);
db.close();
}
@Override
public void onRestart(){
super.onRestart();
adapter.notifyDataSetChanged();
}
@Override
public void onResume(){
super.onResume();
adapter.notifyDataSetChanged();
}
}
| Java |
package com.example.tenmins;
import java.util.Random;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Multi extends Activity {
Button btn[];
String input_text;
TextView num1, num2, input;
Random generator;
int n1, n2;
int result;
Toast mToast;
LinearLayout linear1, linear2;
Typeface font;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multi);
// TODO Auto-generated method stub
btn = new Button[12];
btn[0] = (Button)findViewById(R.id.btn1);
btn[1] = (Button)findViewById(R.id.btn2);
btn[2] = (Button)findViewById(R.id.btn3);
btn[3] = (Button)findViewById(R.id.btn4);
btn[4] = (Button)findViewById(R.id.btn5);
btn[5] = (Button)findViewById(R.id.btn6);
btn[6] = (Button)findViewById(R.id.btn7);
btn[7] = (Button)findViewById(R.id.btn8);
btn[8] = (Button)findViewById(R.id.btn9);
btn[9] = (Button)findViewById(R.id.btn10);
btn[10] = (Button)findViewById(R.id.btn11);
btn[11] = (Button)findViewById(R.id.btn12);
btn[0].setOnClickListener(btnListener);
btn[1].setOnClickListener(btnListener);
btn[2].setOnClickListener(btnListener);
btn[3].setOnClickListener(btnListener);
btn[4].setOnClickListener(btnListener);
btn[5].setOnClickListener(btnListener);
btn[6].setOnClickListener(btnListener);
btn[7].setOnClickListener(btnListener);
btn[8].setOnClickListener(btnListener);
btn[9].setOnClickListener(btnListener);
btn[10].setOnClickListener(btnListener);
btn[11].setOnClickListener(btnListener);
input_text = "";
num1 = (TextView)findViewById(R.id.num1);
num2 = (TextView)findViewById(R.id.num2);
input = (TextView)findViewById(R.id.result);
n1 = 0;
n2 = 0;
generator = new Random();
n1 = generator.nextInt(9) + 1;
n2 = generator.nextInt(9) + 1;
font = Typeface.createFromAsset(getAssets(), "font1.TTF");
num1.setTypeface(font, Typeface.BOLD);
num2.setTypeface(font, Typeface.BOLD);
num1.setText(Integer.toString(n1));
num2.setText(Integer.toString(n2));
result = n1 * n2;
mToast = new Toast(Multi.this);
linear1 = (LinearLayout)View.inflate(Multi.this, R.layout.correct, null);
linear2 = (LinearLayout)View.inflate(Multi.this, R.layout.incorrect, null);
PopupActivity.at_m.add(this);
}
Button.OnClickListener btnListener = new Button.OnClickListener(){
int n = 0;
int length = 0;
String str = "";
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.btn1:
input_text += 1;
input.setText(input_text);
break;
case R.id.btn2:
input_text += 2;
input.setText(input_text);
break;
case R.id.btn3:
input_text += 3;
input.setText(input_text);
break;
case R.id.btn4:
input_text += 4;
input.setText(input_text);
break;
case R.id.btn5:
input_text += 5;
input.setText(input_text);
break;
case R.id.btn6:
input_text += 6;
input.setText(input_text);
break;
case R.id.btn7:
input_text += 7;
input.setText(input_text);
break;
case R.id.btn8:
input_text += 8;
input.setText(input_text);
break;
case R.id.btn9:
input_text += 9;
input.setText(input_text);
break;
case R.id.btn11:
input_text += 0;
input.setText(input_text);
break;
case R.id.btn10:
length = input.getText().toString().length();
if(length == 0 || length == 1){
str = "";
input_text = "";
}
else {
str = input.getText().toString().substring(0, length-1);
input_text = str;
}
input.setText(str);
break;
case R.id.btn12:
if(result == (n=Integer.parseInt(input.getText().toString()))){
//맞았?�니??
mToast.setView(linear1);
mToast.show();
for(int i = 0; i < PopupActivity.at_m.size(); i++)
PopupActivity.at_m.get(i).finish();
}
else{
//??��?�니??
mToast.setView(linear2);
mToast.show();
}
break;
}
}
};
}
| Java |
package com.example.tenmins;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Setting_alarm extends Activity {
public static Boolean ISNEW = false;
public static int POSITION = 0;
public static int ID ;
private static final String INTENT_ACTION = "com.example.tenmins";
// �쒓컙
int hour, minute;
TextView hour_t, minute_t, am_pm_t;
TextView hour_plus, hour_minus, minute_plus, minute_minus;
// �붿씪
ImageView mon, tue, wed, thu, fri, sat, sun;
boolean checked_mon, checked_tue, checked_wed, checked_thu, checked_fri,
checked_sat, checked_sun;
// �뚮엺��
ArrayList<String> musicList;
ArrayAdapter<String> musicAdapter;
RadioGroup sound;
RadioButton radio_btn;
TextView musicTitle;
String title;
String music_id;
private SharedPreferences sharedPref;
private SharedPreferences.Editor sharedEditor;
SeekBar volume;
int volume_control;
Spinner spin;
ArrayList<Alarm_data> data ;
ArrayAdapter<?> adapter;
String game;
ImageButton complete;
static Context context;
Calendar cal = Calendar.getInstance();
//GregorianCalendar currentCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"));
GregorianCalendar currentCalendar = (GregorianCalendar) Calendar.getInstance(TimeZone.getTimeZone("GMT+09:00"));
AlarmManager alarmManager;
// ��옣
Button save;
Database db;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_alarm);
context = getApplicationContext();
sharedPref = getPreferences(Context.MODE_PRIVATE);
sharedEditor = sharedPref.edit();
data = MainActivity.data;
db = new Database(this);
db.open();
hour_t = (TextView) findViewById(R.id.hour);
minute_t = (TextView) findViewById(R.id.min);
am_pm_t = (TextView) findViewById(R.id.AM);
long time = System.currentTimeMillis();
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
mon = (ImageView) findViewById(R.id.mon);
tue = (ImageView) findViewById(R.id.tue);
wed = (ImageView) findViewById(R.id.wed);
thu = (ImageView) findViewById(R.id.thu);
fri = (ImageView) findViewById(R.id.fri);
sat = (ImageView) findViewById(R.id.sat);
sun = (ImageView) findViewById(R.id.sun);
radio_btn = (RadioButton)findViewById(R.id.radio0);
musicTitle = (TextView)findViewById(R.id.musicTitle);
musicTitle.setOnClickListener(musicTitleListener);
spin = (Spinner) findViewById(R.id.spinner1);
adapter = ArrayAdapter.createFromResource(this, R.array.method,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(gameListener);
game = "";
volume = (SeekBar) findViewById(R.id.seekBar1);
volume.setOnSeekBarChangeListener(volumeListener);
volume.setMax(100);
volume.incrementProgressBy(1);
if (ISNEW == true) {
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
if (c.get(Calendar.AM_PM)==Calendar.AM) {
am_pm_t.setText("AM");
}else{
if(hour == 12)
;
else
hour = hour - 12;
am_pm_t.setText("PM");
}
if (hour < 10)
hour_t.setText("0" + Integer.toString(hour));
else
hour_t.setText(Integer.toString(hour));
if (minute < 10)
minute_t.setText("0" + Integer.toString(minute));
else
minute_t.setText(Integer.toString(minute));
ID = db.getLastId()+1;
checked_mon = false;
checked_tue = false;
checked_wed = false;
checked_thu = false;
checked_fri = false;
checked_sat = false;
checked_sun = false;
alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setTimeZone("GMT+09:00");
}
else {
Alarm_data selectedAlarm = MainActivity.data.get(POSITION);
//String hour_minute = selectedAlarm.getTime();
//Scanner scan = new Scanner(hour_minute);
//scan.useDelimiter("시");
ID = selectedAlarm.getId();
/*String h = scan.next();
if(Integer.parseInt(h) < 10)
h = "0" + h;
String m = scan.next();
if(m.length() == 3){
m = m.substring(1, 2);
m = "0" + m;
}
else if(m.length() == 4)
m = m.substring(1, 3);*/
int t_h = db.getHour(ID);
int t_m = db.getMin(ID);
String h = "";
String m = "";
if(t_h < 10)
h = "0" + t_h;
else
h = "" + t_h;
if(t_m < 10)
m = "0" + t_m;
else
m = "" + t_m;
hour_t.setText(h);
minute_t.setText(m);
am_pm_t.setText(selectedAlarm.getAm_Pm());
if(selectedAlarm.getDay_mon() == R.drawable.monday_checked + 2)
mon.setImageResource(R.drawable.monday_checked);
else
mon.setImageResource(R.drawable.monday);
if(selectedAlarm.getDay_tue() == R.drawable.tuesday_checked + 2)
tue.setImageResource(R.drawable.tuesday_checked);
else
tue.setImageResource(R.drawable.tuesday);
if(selectedAlarm.getDay_wed() == R.drawable.wednesday_checked + 2)
wed.setImageResource(R.drawable.wednesday_checked);
else
wed.setImageResource(R.drawable.wednesday);
if(selectedAlarm.getDay_thu() == R.drawable.thursday_checked + 2)
thu.setImageResource(R.drawable.thursday_checked);
else
thu.setImageResource(R.drawable.thursday);
if(selectedAlarm.getDay_fri() == R.drawable.friday_checked + 2)
fri.setImageResource(R.drawable.friday_checked);
else
fri.setImageResource(R.drawable.friday);
if(selectedAlarm.getDay_sat() == R.drawable.saturday_checked + 2)
sat.setImageResource(R.drawable.saturday_checked);
else
sat.setImageResource(R.drawable.saturday);
if(selectedAlarm.getDay_sun() == R.drawable.sunday_checked + 2)
sun.setImageResource(R.drawable.sunday_checked);
else
sun.setImageResource(R.drawable.sunday);
checked_mon = db.isCheckedMon(ID);
checked_tue = db.isCheckedTue(ID);
checked_wed = db.isCheckedWed(ID);
checked_thu = db.isCheckedThu(ID);
checked_fri = db.isCheckedFri(ID);
checked_sat = db.isCheckedSat(ID);
checked_sun = db.isCheckedSun(ID);
musicTitle.setText(db.getMusicTitle(ID));
volume.setProgress(db.getVolume(ID));
spin.setSelection(db.getGame(ID));
}
hour_plus = (TextView) findViewById(R.id.hour_plus);
hour_minus = (TextView) findViewById(R.id.hour_minus);
minute_plus = (TextView) findViewById(R.id.minute_plus);
minute_minus = (TextView) findViewById(R.id.minute_minus);
hour_plus.setOnClickListener(buttonListener);
hour_minus.setOnClickListener(buttonListener);
minute_plus.setOnClickListener(buttonListener);
minute_minus.setOnClickListener(buttonListener);
am_pm_t.setOnClickListener(buttonListener);
mon.setOnClickListener(dayListener);
tue.setOnClickListener(dayListener);
wed.setOnClickListener(dayListener);
thu.setOnClickListener(dayListener);
fri.setOnClickListener(dayListener);
sat.setOnClickListener(dayListener);
sun.setOnClickListener(dayListener);
sound = (RadioGroup) findViewById(R.id.radioGroup1);
sound.setOnCheckedChangeListener(soundListener);
title = musicTitle.getText().toString();
musicList = new ArrayList<String>();
musicList = getMusicList();
musicAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, musicList);
save = (Button) findViewById(R.id.save);
save.setOnClickListener(saveListener);
db.close();
}
Button.OnClickListener saveListener = new Button.OnClickListener() {
int h = 0, m = 0, vc = 0;
String ap = "", g = "", s = "";
int check_mon = 0,
check_tue = 0,
check_wed = 0,
check_thu = 0,
check_fri = 0,
check_sat = 0,
check_sun = 0;
int reqCode = ID ;
@Override
public void onClick(View arg0) {
if (checked_mon)
check_mon = 1;
if (checked_tue)
check_tue = 1;
if (checked_wed)
check_wed = 1;
if (checked_thu)
check_thu = 1;
if (checked_fri)
check_fri = 1;
if (checked_sat)
check_sat = 1;
if (checked_sun)
check_sun = 1;
h = Integer.parseInt(hour_t.getText().toString());
//if(am_pm_t.getText().equals("PM"))
// h = h + 12;
m = Integer.parseInt(minute_t.getText().toString());
ap = am_pm_t.getText().toString();
g = game;
s = title;
vc = volume_control;
if((check_mon+check_tue+check_tue+check_wed+check_thu+check_fri+check_sat+check_sun)==0){
Toast.makeText(context, "요일을 선택하세요", Toast.LENGTH_SHORT).show();
return;
}
/*if(sound.getCheckedRadioButtonId()==-1){
Toast.makeText(context, "알람음을 선택하세요", Toast.LENGTH_SHORT).show();
return;
}*/
if(musicTitle.getText().toString().equals("")){
Toast.makeText(context, "알람음을 선택하세요", Toast.LENGTH_SHORT).show();
return;
}
getData();
int hh = Integer.parseInt(hour_t.getText().toString());
int mm = Integer.parseInt(minute_t.getText().toString());
String ampm = am_pm_t.getText().toString();
GregorianCalendar gregorianCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"));
int reqCode = ID;
Intent intent = new Intent(context, PopupActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Intent intent = new Intent(I);
intent.putExtra("reqCode", reqCode);
gregorianCalendar.set(Calendar.HOUR, hh);
gregorianCalendar.set(Calendar.MINUTE, mm);
if(ampm.equals("am"))
gregorianCalendar.set(Calendar.AM_PM, Calendar.AM);
else
gregorianCalendar.set(Calendar.AM_PM, Calendar.PM);
gregorianCalendar.set(Calendar.SECOND, 0);
//Log.i("TAG",gregorianCalendar.getTimeInMillis()+":");
reqCode = ID;
//intent.putExtra("reqCode", reqCode);
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//Log.i("id", "id:"+reqCode);
//intent.putExtra("reqCode", reqCode+gregorianCalendar.getTimeInMillis()+"/"+cal.getTimeInMillis());
PendingIntent pi = PendingIntent.getActivity(Setting_alarm.this, reqCode, intent,PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, gregorianCalendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pi);
finish();
}
public void getData(){
Database db = new Database(getApplicationContext());
db.open();
if(ISNEW == true){
db.addAlarmList(h, m, ap, check_mon, check_tue, check_wed,
check_thu, check_fri, check_sat, check_sun, g, s, vc);
ID = db.getLastId();
int index = musicList.indexOf(s);
music_id = getMusicID(index);
db.addMusicList(music_id);
int mon_image = R.drawable.monday_list,
tue_image = R.drawable.tuesday_list,
wed_image = R.drawable.wednesday_list,
thu_image = R.drawable.thursday_list,
fri_image = R.drawable.friday_list,
sat_image = R.drawable.saturday_list,
sun_image = R.drawable.sunday_list;
if(check_mon == 1) mon_image = R.drawable.monday_list_checked;
if(check_tue == 1) tue_image = R.drawable.tuesday_list_checked;
if(check_wed == 1) wed_image = R.drawable.wednesday_list_checked;
if(check_thu == 1) thu_image = R.drawable.thursday_list_checked;
if(check_fri == 1) fri_image = R.drawable.friday_list_checked;
if(check_sat == 1) sat_image = R.drawable.saturday_list_checked;
if(check_sun == 1) sun_image = R.drawable.sunday_list_checked;
Alarm_data newAlarm = new Alarm_data(R.drawable.alarm, h + "시" + m + " 분", mon_image, tue_image, wed_image,
thu_image, fri_image, sat_image, sun_image, ap, ID);
data.add(newAlarm);
//MainActivity.data.add(newAlarm);
//MainActivity.adapter.notifyDataSetChanged();
}else{
int mon_image = R.drawable.monday_list,
tue_image = R.drawable.tuesday_list,
wed_image = R.drawable.wednesday_list,
thu_image = R.drawable.thursday_list,
fri_image = R.drawable.friday_list,
sat_image = R.drawable.saturday_list,
sun_image = R.drawable.sunday_list;
db.updateAlarmList(h, m, ap, check_mon, check_tue, check_wed,
check_thu, check_fri, check_sat, check_sun, g, s, vc, ID);
if(check_mon == 1) mon_image = R.drawable.monday_list_checked;
if(check_tue == 1) tue_image = R.drawable.tuesday_list_checked;
if(check_wed == 1) wed_image = R.drawable.wednesday_list_checked;
if(check_thu == 1) thu_image = R.drawable.thursday_list_checked;
if(check_fri == 1) fri_image = R.drawable.friday_list_checked;
if(check_sat == 1) sat_image = R.drawable.saturday_list_checked;
if(check_sun == 1) sun_image = R.drawable.sunday_list_checked;
Alarm_data newAlarm = new Alarm_data(R.drawable.alarm, h + "시" + m + " 분", mon_image, tue_image, wed_image,
thu_image, fri_image, sat_image, sun_image, ap, ID);
int index = musicList.indexOf(s);
music_id = getMusicID(index);
data.remove(POSITION);
data.add(POSITION, newAlarm);
db.updateMusicList(music_id, ID);
}
db.close();
}
};
Spinner.OnItemSelectedListener gameListener = new Spinner.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
game = spin.getSelectedItem().toString();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
public ArrayList<String> getMusicList() {
ArrayList<String> list = new ArrayList<String>();
String[] proj = {
MediaStore.Audio.Media.TITLE };
Cursor cursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null,
null);
if (cursor != null && cursor.moveToFirst()) {
String title;
int musicTitleCol = cursor
.getColumnIndex(MediaStore.Audio.Media.TITLE);
do {
title = cursor.getString(musicTitleCol);
list.add(title);
} while (cursor.moveToNext());
}
//cursor.close();
return list;
}
public String getMusicID(int index){
ArrayList<String> list = new ArrayList<String>();
String[] proj = {
MediaStore.Audio.Media._ID };
Cursor cursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null,
null);
if (cursor != null && cursor.moveToFirst()) {
String musicID;
int musicIDCol = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
do {
musicID = cursor.getString(musicIDCol);
list.add(musicID);
} while (cursor.moveToNext());
}
//cursor.close();
return list.get(index);
}
SeekBar.OnSeekBarChangeListener volumeListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
volume_control = progress;
}
};
ImageView.OnClickListener dayListener = new ImageView.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.mon:
if (!checked_mon) {
mon.setImageResource(R.drawable.monday_checked);
checked_mon = true;
} else {
mon.setImageResource(R.drawable.monday);
checked_mon = false;
}
break;
case R.id.tue:
if (!checked_tue) {
tue.setImageResource(R.drawable.tuesday_checked);
checked_tue = true;
} else {
tue.setImageResource(R.drawable.tuesday);
checked_tue = false;
}
break;
case R.id.wed:
if (!checked_wed) {
wed.setImageResource(R.drawable.wednesday_checked);
checked_wed = true;
} else {
wed.setImageResource(R.drawable.wednesday);
checked_wed = false;
}
break;
case R.id.thu:
if (!checked_thu) {
thu.setImageResource(R.drawable.thursday_checked);
checked_thu = true;
} else {
thu.setImageResource(R.drawable.thursday);
checked_thu = false;
}
break;
case R.id.fri:
if (!checked_fri) {
fri.setImageResource(R.drawable.friday_checked);
checked_fri = true;
} else {
fri.setImageResource(R.drawable.friday);
checked_fri = false;
}
break;
case R.id.sat:
if (!checked_sat) {
sat.setImageResource(R.drawable.saturday_checked);
checked_sat = true;
} else {
sat.setImageResource(R.drawable.saturday);
checked_sat = false;
}
break;
case R.id.sun:
if (!checked_sun) {
sun.setImageResource(R.drawable.sunday_checked);
checked_sun = true;
} else {
sun.setImageResource(R.drawable.sunday);
checked_sun = false;
}
break;
}
}
};
Button.OnClickListener buttonListener = new Button.OnClickListener() {
String before = "";
int after = 0;
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.hour_plus:
before = hour_t.getText().toString();
if (before.equals("12"))
hour_t.setText("01");
else {
after = Integer.parseInt(before) + 1;
if (after < 10)
hour_t.setText("0" + Integer.toString(after));
else
hour_t.setText(Integer.toString(after));
}
break;
case R.id.hour_minus:
before = hour_t.getText().toString();
if (before.equals("01"))
hour_t.setText("12");
else {
after = Integer.parseInt(before) - 1;
if (after < 10)
hour_t.setText("0" + Integer.toString(after));
else
hour_t.setText(Integer.toString(after));
}
break;
case R.id.minute_plus:
before = minute_t.getText().toString();
if (before.equals("59"))
minute_t.setText("00");
else {
after = Integer.parseInt(before) + 1;
if (after < 10)
minute_t.setText("0" + Integer.toString(after));
else
minute_t.setText(Integer.toString(after));
}
break;
case R.id.minute_minus:
before = minute_t.getText().toString();
if (before.equals("00"))
minute_t.setText("59");
else {
after = Integer.parseInt(before) - 1;
if (after < 10)
minute_t.setText("0" + Integer.toString(after));
else
minute_t.setText(Integer.toString(after));
}
break;
case R.id.AM:
before = am_pm_t.getText().toString();
if (before.equals("AM"))
am_pm_t.setText("PM");
else
am_pm_t.setText("AM");
}
}
};
TextView.OnClickListener musicTitleListener = new TextView.OnClickListener(){
int index = 0;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AlertDialog.Builder(Setting_alarm.this)
.setTitle("음악 목록")
.setAdapter(musicAdapter,
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface arg0, int arg1) {
title = musicList.get(arg1);
index = musicList.indexOf(title);
music_id = getMusicID(index);
musicTitle.setText(title);
}
}).create().show();
}
};
RadioGroup.OnCheckedChangeListener soundListener = new RadioGroup.OnCheckedChangeListener() {
int index = 0;
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if (group.getId() == R.id.radioGroup1) {
switch (checkedId) {
case R.id.radio0:
new AlertDialog.Builder(Setting_alarm.this)
.setTitle("음악 목록")
.setAdapter(musicAdapter,
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface arg0, int arg1) {
title = musicList.get(arg1);
index = musicList.indexOf(title);
music_id = getMusicID(index);
musicTitle.setText(title);
}
}).create().show();
break;
}
}
}
};
}
| Java |
package com.example.tenmins;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class DelayAlarm extends Activity {
TextView delaymin;
Button up, down, more;
Context context;
int id;
@Override
public void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
// 키잠금 해제하기
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
// 화면 켜기
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
super.onCreate(savedInstanceState);
setContentView(R.layout.delay_time);
delaymin = (TextView) findViewById(R.id.delaymin);
up = (Button) findViewById(R.id.up);
down = (Button) findViewById(R.id.down);
more = (Button) findViewById(R.id.moresleep);
up.setOnClickListener(upmin);
down.setOnClickListener(downmin);
more.setOnClickListener(moresleep);
context = getApplicationContext();
Intent data = getIntent();
id = data.getIntExtra("id", 0);
PopupActivity.at_d.add(this);
}
OnClickListener upmin = new OnClickListener() {
@Override
public void onClick(View arg0) {
if (delaymin.getText().equals("59"))
delaymin.setText("00");
else {
int min = Integer.parseInt(delaymin.getText().toString());
min++;
if(min < 10)
delaymin.setText("0" + min);
else delaymin.setText(String.valueOf(min));
}
}
};
OnClickListener downmin = new OnClickListener() {
@Override
public void onClick(View arg0) {
if (delaymin.getText().equals("00"))
delaymin.setText("59");
else {
int min = Integer.parseInt(delaymin.getText().toString());
min--;
if(min < 10)
delaymin.setText("0"+min);
else delaymin.setText(String.valueOf(min));
}
}
};
OnClickListener moresleep = new OnClickListener() {
@Override
public void onClick(View arg0) {
GregorianCalendar currentCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"));
GregorianCalendar gregorianCalendar = currentCalendar;
Database db = new Database(context);
db.open();
int hh = db.getHour(id);
int mm = db.getMin(id);
String ampm = db.getAMPM(id);
if(ampm.equals("am"))
gregorianCalendar.set(Calendar.AM_PM, Calendar.AM);
else
gregorianCalendar.set(Calendar.AM_PM, Calendar.PM);
gregorianCalendar.set(Calendar.SECOND, 0);
int delaymm = Integer.parseInt(delaymin.getText().toString());
gregorianCalendar.add(Calendar.MINUTE, delaymm);
Intent intent = new Intent(DelayAlarm.this, PopupActivity.class);
intent.putExtra("reqCode", id);
PendingIntent pi = PendingIntent.getActivity(DelayAlarm.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, gregorianCalendar.getTimeInMillis(), pi);
for(int i = 0; i < PopupActivity.at_d.size(); i++)
PopupActivity.at_d.get(i).finish();
}
};
}
| Java |
package com.example.tenmins;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Database {
private static String DB_NAME = "alarm";
private static int DB_VERSION = 10;
private final Context context;
private DatabaseHelper mDbHelper;
private static SQLiteDatabase db;
public static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper (Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE list(hour INT, minute INT, am_pm TEXT,"
+ " mon INT, tue INT, wed INT, thu INT, fri INT, sat INT, sun INT,"
+ " game TEXT, sound TEXT, volume INT, id INT)";
db.execSQL(sql);
String sql_create_music = "CREATE TABLE musicList(musicID TEXT, id INT)";
db.execSQL(sql_create_music);
String sql2 = "CREATE TABLE last_id(id INT)";
String sql3 = "INSERT INTO last_id(id) VALUES (1);";
db.execSQL(sql2);
db.execSQL(sql3);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS list; ");
db.execSQL("DROP TABLE IF EXISTS last_id;");
db.execSQL("DROP TABLE IF EXISTS musicList;");
onCreate(db);
}
}
public Database(Context context) {
this.context = context;
}
public Database open() throws SQLException {
mDbHelper = new DatabaseHelper(context);
db = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public void addAlarmList(int hour, int minute, String am_pm, int mon,
int tue, int wed, int thu, int fri, int sat, int sun, String game,
String sound, int volume) {
int id = getLastId();
id++;
db.execSQL("INSERT INTO list(hour, minute, am_pm, mon, tue, wed, thu, fri, sat, sun, game, sound, volume, id)" +
" VALUES (" + hour + "," + minute + ",'"
+ am_pm + "'" + "," + mon + "," + tue + "," + wed + "," + thu
+ "," + fri + "," + sat + "," + sun + ",'" + game + "'" + ",'"
+ sound + "'," + volume + ","+id+");");
db.execSQL("UPDATE last_id SET id = "+id+" WHERE id="+(id-1)+";");
}
public void addMusicList(String musicID) {
int id = getLastId();
id++;
db.execSQL("INSERT INTO musicList(musicID, id)" +
" VALUES ('" + musicID + "'," + id + ");");
}
public void deleteAlarmList(int id) {
db.execSQL("DELETE FROM list WHERE id ="+id+";");
}
public void updateAlarmList(int hour, int minute, String am_pm, int mon,
int tue, int wed, int thu, int fri, int sat, int sun, String game,
String sound, int volume, int id) {
db.execSQL("UPDATE list SET hour ="+hour+", minute ="+minute+", am_pm ='"+am_pm+"', mon ="+mon+
", tue="+tue+", wed="+wed+", thu="+thu+", fri="+fri+", sat="+sat+", sun="+sun+", game='"+game+
"', sound='"+sound+"', volume="+volume+" WHERE id ="+id+";");
}
public void updateMusicList(String musicID, int id) {
db.execSQL("UPDATE musicList SET musicID ='"+musicID+"', id ="+id+";");
}
public Cursor getAlarmList() {
Cursor c = db.rawQuery("SELECT * FROM list;", null);
if (c != null && c.getCount() != 0)
c.moveToFirst();
return c;
}
public int getLastId(){
Cursor c= db.rawQuery("SELECT id FROM last_id;",null);
c.moveToFirst();
return c.getInt(0);
}
public int getGame(int id){
Cursor c= db.rawQuery("SELECT game FROM list WHERE id ="+id+";", null);
c.moveToFirst();
String game = c.getString(0);
if(game.equals("없음"))
return 0;
else if(game.equals("문자입력"))
return 1;
else // 구구??
return 2;
}
public String getMusicID(int id){
Cursor c= db.rawQuery("SELECT musicID FROM musicList WHERE id ='"+id+"';", null);
c.moveToFirst();
String musicID = c.getString(0);
return musicID;
}
public int getHour(int id){
Log.e("tag", "id:"+id);
Cursor c= db.rawQuery("SELECT hour FROM list WHERE id ="+id+"", null);
c.moveToFirst();
return c.getInt(0);
}
public int getMin(int id){
Log.e("tag", "id:"+id);
Cursor c= db.rawQuery("SELECT minute FROM list WHERE id ="+id+"", null);
c.moveToFirst();
return c.getInt(0);
}
public String getAMPM(int id)
{
Log.e("tag", "id:"+id);
Cursor c= db.rawQuery("SELECT am_pm FROM list WHERE id ="+id+"", null);
c.moveToFirst();
return c.getString(0);
}
public boolean isCheckedMon(int id){
Cursor c = db.rawQuery("SELECT mon FROM list WHERE id="+id+";", null);
c.moveToFirst();
if(c.getInt(0)==0)
return false;
else
return true;
}
public boolean isCheckedTue(int id){
Cursor c = db.rawQuery("SELECT tue FROM list WHERE id="+id+";", null);
c.moveToFirst();
if(c.getInt(0)==0)
return false;
else
return true;
}
public boolean isCheckedWed(int id){
Cursor c = db.rawQuery("SELECT wed FROM list WHERE id="+id+";", null);
c.moveToFirst();
if(c.getInt(0)==0)
return false;
else
return true;
}
public boolean isCheckedThu(int id){
Cursor c = db.rawQuery("SELECT thu FROM list WHERE id="+id+";", null);
c.moveToFirst();
if(c.getInt(0)==0)
return false;
else
return true;
}
public boolean isCheckedFri(int id){
Cursor c = db.rawQuery("SELECT fri FROM list WHERE id="+id+";", null);
c.moveToFirst();
if(c.getInt(0)==0)
return false;
else
return true;
}
public boolean isCheckedSat(int id){
Cursor c = db.rawQuery("SELECT sat FROM list WHERE id="+id+";", null);
c.moveToFirst();
if(c.getInt(0)==0)
return false;
else
return true;
}
public boolean isCheckedSun(int id){
Cursor c = db.rawQuery("SELECT sun FROM list WHERE id="+id+";", null);
c.moveToFirst();
if(c.getInt(0)==0)
return false;
else
return true;
}
public int getVolume(int id){
Cursor c= db.rawQuery("SELECT volume FROM list WHERE id ="+id+"", null);
c.moveToFirst();
int volume = c.getInt(0);
return volume;
}
public String getMusicTitle(int id){
Cursor c= db.rawQuery("SELECT sound FROM list WHERE id ="+id+"", null);
c.moveToFirst();
String title = c.getString(0);
return title;
}
}
| Java |
package com.example.tenmins;
public class Alarm_data{
private int id;
private int clock;
private String time;
private int monday;
private int tuesday;
private int wednesday;
private int thursday;
private int friday;
private int saturday;
private int sunday;
private String am_pm;
public Alarm_data(int clock, String time,
int monday, int tuesday, int wednesday, int thursday,
int friday, int saturday, int sunday, String am_pm, int id) {
this.id = id;
this.clock = clock;
this.time = time;
this.monday = monday;
this.tuesday = tuesday;
this.wednesday = wednesday;
this.thursday = thursday;
this.friday = friday;
this.saturday = saturday;
this.sunday = sunday;
this.am_pm = am_pm;
}
public int getClock(){
return clock;
}
public String getTime(){
return time;
}
public int getDay_mon() {
return monday;
}
public int getDay_tue() {
return tuesday;
}
public int getDay_wed() {
return wednesday;
}
public int getDay_thu() {
return thursday;
}
public int getDay_fri() {
return friday;
}
public int getDay_sat() {
return saturday;
}
public int getDay_sun() {
return sunday;
}
public String getAm_Pm() {
return am_pm;
}
public int getId(){
return id;
}
}
| Java |
package com.example.tenmins;
import java.util.Random;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Text extends Activity {
String[] str = {
"설마 오늘도 쌩얼로 가려고?",
"일찍 일어나는 새가 벌레를 많이 먹는다는데",
"잠만보야 일어나",
"미인은 잠꾸러기라는데 넌...",
"일어나",
"짹짹",
"일어나시지",
"일어날래?",
"지금 안 일어나면 오늘도 쌩얼이다",
"다른 사람들의 눈도 존중해줘야지..."
};
Random generator;
int index;
TextView text;
EditText input;
Button complete;
String user_input;
Toast mToast;
LinearLayout linear1, linear2;
Typeface font;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
// TODO Auto-generated method stub
generator = new Random();
index = generator.nextInt(10);
text = (TextView)findViewById(R.id.text);
font = Typeface.createFromAsset(getAssets(), "font1.TTF");
text.setTypeface(font, Typeface.BOLD);
text.setText(str[index]);
input = (EditText)findViewById(R.id.input);
complete = (Button)findViewById(R.id.input_complete);
complete.setOnClickListener(buttonListener);
mToast = new Toast(Text.this);
linear1 = (LinearLayout)View.inflate(Text.this, R.layout.correct, null);
linear2 = (LinearLayout)View.inflate(Text.this, R.layout.incorrect, null);
PopupActivity.at_t.add(this);
}
Button.OnClickListener buttonListener = new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
user_input = input.getText().toString();
if(user_input.equals(text.getText().toString())){
//맞았?�니??
mToast.setView(linear1);
mToast.show();
for(int i = 0; i < PopupActivity.at_t.size(); i++)
PopupActivity.at_t.get(i).finish();
}
else{
//??��?�니??
mToast.setView(linear2);
mToast.show();
}
}
};
}
| Java |
package com.example.ten_minutes_more;
import java.util.ArrayList;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class Setting_adapter extends BaseAdapter {
Context context;
ArrayList<Alarm_data> data;
LayoutInflater inflater;
static Database db;
public Setting_adapter(Context c, ArrayList<Alarm_data> data){
this.context = c;
db = new Database(c);
db.open();
this.data = data;
inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.get(position).getTime();
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView == null)
convertView = inflater.inflate(R.layout.list_layout, parent, false);
if(data.get(position) != null){
ImageView clock = (ImageView)convertView.findViewById(R.id.clock);
clock.setImageResource(data.get(position).getClock());
final TextView time = (TextView)convertView.findViewById(R.id.time);
time.setText(data.get(position).getTime());
final ImageView monday = (ImageView)convertView.findViewById(R.id.monday);
monday.setImageResource(data.get(position).getDay_mon());
final ImageView tuesday = (ImageView)convertView.findViewById(R.id.tuesday);
tuesday.setImageResource(data.get(position).getDay_tue());
final ImageView wednesday = (ImageView)convertView.findViewById(R.id.wednesday);
wednesday.setImageResource(data.get(position).getDay_wed());
final ImageView thursday = (ImageView)convertView.findViewById(R.id.thursday);
thursday.setImageResource(data.get(position).getDay_thu());
final ImageView friday = (ImageView)convertView.findViewById(R.id.friday);
friday.setImageResource(data.get(position).getDay_fri());
final ImageView saturday = (ImageView)convertView.findViewById(R.id.saturday);
saturday.setImageResource(data.get(position).getDay_sat());
final ImageView sunday = (ImageView)convertView.findViewById(R.id.sunday);
sunday.setImageResource(data.get(position).getDay_sun());
//final ToggleButton on_off = (ToggleButton)convertView.findViewById(R.id.on_off);
ImageView delete = (ImageView)convertView.findViewById(R.id.delete);
delete.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
int id = data.get(position).getId();
//Setting_alarm.cancelAlarm(data.get(position).getId());
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, PopupActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.cancel(pi);
Toast.makeText(context, "알람이 해제되었습니다",Toast.LENGTH_SHORT).show();
db.deleteAlarmList(data.get(position).getId());
MainActivity.data.remove(position);
MainActivity.adapter.notifyDataSetChanged();
}
});
final TextView am_pm = (TextView)convertView.findViewById(R.id.am_pm);
am_pm.setText(data.get(position).getAm_Pm());
convertView.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Setting_alarm.ISNEW = false;
Setting_alarm.POSITION = position;
Intent info = new Intent(context, Setting_alarm.class);
context.startActivity(info);
}
});
//convertView.setOnCreateContextMenuListener(MainActivity.contextmenu);
}
return convertView;
}
/*
public static void deleteAlarm(MenuItem item){
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getOrder();
Alarm_data selected = MainActivity.data.get(info.position);
int id = selected.getId();
db.deleteAlarmList(id);
MainActivity.data.clear();
MainActivity.setData();
MainActivity.adapter.notifyDataSetChanged();
}
*/
}
| Java |
package com.example.ten_minutes_more;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.Timer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class PopupActivity extends Activity{
Button exit, delay;
TextView time,hour,min;
public static int id;
Context context;
int alarmHour, alarmMin;
Timer timeTimer;
Database db;
MediaPlayer mMediaPlayer;
AudioManager audioManager;
Thread thread;
int runnable_m;
int runnable_s;
TextView popup_time;
MyHandler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
id = getIntent().getIntExtra("reqCode", 0);
Database db = new Database(PopupActivity.this);
db.open();
GregorianCalendar currentCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"));
int date = currentCalendar.get(Calendar.DAY_OF_WEEK);
switch(date){
case 1: // sun
if(!db.isCheckedSun(id))
return;
break;
case 2: // mon
if(!db.isCheckedMon(id))
return;
break;
case 3: // sun
if(!db.isCheckedTue(id))
return;
break;
case 4: // sun
if(!db.isCheckedWed(id))
return;
break;
case 5: // sun
if(!db.isCheckedThu(id))
return;
break;
case 6: // sun
if(!db.isCheckedFri(id))
return;
break;
case 7: // sun
if(!db.isCheckedSat(id))
return;
break;
}
super.onCreate(savedInstanceState);
setContentView(R.layout.popup);
db = new Database(context);
db.open();
exit = (Button) findViewById(R.id.delete_popup);
delay = (Button) findViewById(R.id.delay_btn);
time = (TextView) findViewById(R.id.popup_time);
hour = (TextView) findViewById(R.id.popup_hour);
min = (TextView) findViewById(R.id.popup_min);
long time = System.currentTimeMillis();
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
int h = c.get(Calendar.HOUR_OF_DAY);
int m = c.get(Calendar.MINUTE);
hour.setText(Integer.toString(h));
min.setText(Integer.toString(m));
exit.setOnClickListener(l);
delay.setOnClickListener(l);
context = getApplicationContext();
alarmHour = db.getHour(id);
alarmMin = db.getMin(id);
//timeTimer = new Timer();
//timeTimer.schedule(timeTimerTask, 30, 1000);
popup_time = (TextView)findViewById(R.id.popup_time);
handler = new MyHandler();
BackThread thread = new BackThread();
thread.setDaemon(true);
thread.start();
mMediaPlayer = new MediaPlayer();
audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
int setting_volume = db.getVolume(id);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, setting_volume, AudioManager.FLAG_PLAY_SOUND);
String musicID = db.getMusicID(id);
Uri uri = Uri.withAppendedPath(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, "" + musicID);
playAudio(uri);
}
public void playAudio(Uri uri){
try {
mMediaPlayer.reset();
mMediaPlayer.setDataSource(this, uri);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onDestroy() {
super.onDestroy();
/* Release resources allocated to player */
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
}
class BackThread extends Thread{
public void run(){
while(true){
runnable_s++;
if(runnable_s > 59){
runnable_s = 0;
runnable_m++;
}
Message msg = Message.obtain(handler, 0, runnable_s, 0);
handler.sendMessage(msg);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
;
}
}
}
}
class MyHandler extends Handler{
@Override
public void handleMessage(Message msg){
if(msg.what == 0)
popup_time.setText(runnable_m + "분 " + msg.arg1 + "초가 지났습니다");
}
}
Button.OnClickListener l = new Button.OnClickListener(){
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.delete_popup:
// 게임 실행
int game = db.getGame(id);
switch(game){
case 0:
finish();
break;
case 1:
Intent text = new Intent(PopupActivity.this, Text.class);
startActivity(text);
finish();
break;
case 2 :
Intent multi = new Intent(PopupActivity.this, Multi.class);
startActivity(multi);
finish();
break;
}
break;
case R.id.delay_btn:
// 알람 지연 화면 실행
Intent delay = new Intent(PopupActivity.this, DelayAlarm.class);
delay.putExtra("id", id);
startActivity(delay);
finish();
break;
}
}
};
/*
TimerTask timeTimerTask = new TimerTask(){
public void run(){
GregorianCalendar currentCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"));
final int curHour = currentCalendar.get(Calendar.HOUR);
final int curMin = currentCalendar.get(Calendar.MINUTE);
final String after = "초기알람시간("+alarmHour+":"+alarmMin+")으로 부터\n+"
+(curHour-alarmHour)+":"+(curMin-alarmMin);
Handler timeHandler = time.getHandler();
timeHandler.post(new Runnable(){
public void run(){
Log.d("timeTimerTask", "Time : " + time);
time.setText(after);
hour.setText(String.valueOf(curHour));
min.setText(String.valueOf(curMin));
}
});
} //end run
}; //end TimerTask
protected void onStop() {
timeTimerTask.cancel();
timeTimer.cancel();
super.onStop();
}*/
}
| Java |
package com.example.ten_minutes_more;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ListView list;
public static Setting_adapter adapter;
public static ArrayList<Alarm_data> data;
static Alarm_data da;
TextView add_t;
ImageButton add;
Typeface font;
public static Database db;
static Cursor result = null;
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.add_alarm);
add_t = (TextView)findViewById(R.id.add_text);
font = Typeface.createFromAsset(getAssets(), "font1.TTF");
add_t.setTypeface(font, Typeface.BOLD);
add_t.setTextSize(20);
add_t.setOnClickListener(addListener_t);
add = (ImageButton)findViewById(R.id.add);
add.setOnClickListener(addListener);
db = new Database(this);
db.open();
setData();
adapter = new Setting_adapter(this, data);
list = (ListView)findViewById(R.id.listView1);
list.setAdapter(adapter);
}
TextView.OnClickListener addListener_t = new TextView.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Setting_alarm.ISNEW = true;
Intent info = new Intent(MainActivity.this, Setting_alarm.class);
startActivity(info);
}
};
ImageButton.OnClickListener addListener = new ImageButton.OnClickListener(){
@Override
public void onClick(View v) {
Setting_alarm.ISNEW = true;
Intent info = new Intent(MainActivity.this, Setting_alarm.class);
startActivity(info);
}
};
public static void setData(){
int hour = 0, minute = 0;
String am_pm = "";
String time = "";
int mon = 0, tue = 0, wed = 0, thu = 0, fri = 0, sat = 0, sun = 0;
int mon_image = R.drawable.monday_list,
tue_image = R.drawable.tuesday_list,
wed_image = R.drawable.wednesday_list,
thu_image = R.drawable.thursday_list,
fri_image = R.drawable.friday_list,
sat_image = R.drawable.saturday_list,
sun_image = R.drawable.sunday_list;
result = db.getAlarmList();
data = new ArrayList<Alarm_data>();
if(result.moveToFirst()){
do{
hour = result.getInt(0);
minute = result.getInt(1);
time = hour + "시 " + minute + "분";
am_pm = result.getString(2);
if((mon = result.getInt(3)) == 1)
mon_image = R.drawable.monday_list_checked;
if((tue = result.getInt(4)) == 1)
tue_image = R.drawable.tuesday_list_checked;
if((wed = result.getInt(5)) == 1)
wed_image = R.drawable.wednesday_list_checked;
if((thu = result.getInt(6)) == 1)
thu_image = R.drawable.thursday_list_checked;
if((fri = result.getInt(7)) == 1)
fri_image = R.drawable.friday_list_checked;
if((sat = result.getInt(8)) == 1)
sat_image = R.drawable.saturday_list_checked;
if((sun = result.getInt(9)) == 1)
sun_image = R.drawable.sunday_list_checked;
int id = result.getInt(13);
da = new Alarm_data(
R.drawable.alarm,
time,
mon_image,
tue_image,
wed_image,
thu_image,
fri_image,
sat_image,
sun_image,
am_pm,
id);
data.add(da);
mon = 0;
tue = 0;
wed = 0;
thu = 0;
fri = 0;
sat = 0;
sun = 0;
mon_image = R.drawable.monday_list;
tue_image = R.drawable.tuesday_list;
wed_image = R.drawable.wednesday_list;
thu_image = R.drawable.thursday_list;
fri_image = R.drawable.friday_list;
sat_image = R.drawable.saturday_list;
sun_image = R.drawable.sunday_list;
}while(result.moveToNext());
}
else
data.add(null);
}
public static OnCreateContextMenuListener contextmenu = new OnCreateContextMenuListener(){
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuinfo) {
menu.add(0,1,0,"수정");
menu.add(0,2,0,"삭제");
}
};
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case 1: // 수정
Setting_alarm.ISNEW = true;
Intent edit = new Intent(MainActivity.this, Setting_alarm.class);
startActivity(edit);
break;
case 2: // 삭제
//Setting_adapter.deleteAlarm(item);
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
}
| Java |
package com.example.ten_minutes_more;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AlarmReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Log.e("tag", "broadcast");
int id = intent.getIntExtra("reqCode", 0);
PopupActivity.id = id;
Intent popup = new Intent(context, PopupActivity.class);
context.startActivity(popup);
}
}
| Java |
package com.example.ten_minutes_more;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Multi extends Activity {
Button btn[];
String input_text;
TextView num1, num2, input;
Random generator;
int n1, n2;
int result;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multi);
// TODO Auto-generated method stub
btn = new Button[12];
btn[0] = (Button)findViewById(R.id.btn1);
btn[1] = (Button)findViewById(R.id.btn2);
btn[2] = (Button)findViewById(R.id.btn3);
btn[3] = (Button)findViewById(R.id.btn4);
btn[4] = (Button)findViewById(R.id.btn5);
btn[5] = (Button)findViewById(R.id.btn6);
btn[6] = (Button)findViewById(R.id.btn7);
btn[7] = (Button)findViewById(R.id.btn8);
btn[8] = (Button)findViewById(R.id.btn9);
btn[9] = (Button)findViewById(R.id.btn10);
btn[10] = (Button)findViewById(R.id.btn11);
btn[11] = (Button)findViewById(R.id.btn12);
btn[0].setOnClickListener(btnListener);
btn[1].setOnClickListener(btnListener);
btn[2].setOnClickListener(btnListener);
btn[3].setOnClickListener(btnListener);
btn[4].setOnClickListener(btnListener);
btn[5].setOnClickListener(btnListener);
btn[6].setOnClickListener(btnListener);
btn[7].setOnClickListener(btnListener);
btn[8].setOnClickListener(btnListener);
btn[9].setOnClickListener(btnListener);
btn[10].setOnClickListener(btnListener);
btn[11].setOnClickListener(btnListener);
input_text = "";
num1 = (TextView)findViewById(R.id.num1);
num2 = (TextView)findViewById(R.id.num2);
input = (TextView)findViewById(R.id.result);
n1 = 0;
n2 = 0;
generator = new Random();
n1 = generator.nextInt(9) + 1;
n2 = generator.nextInt(9) + 1;
num1.setText(Integer.toString(n1));
num2.setText(Integer.toString(n2));
result = n1 * n2;
}
Button.OnClickListener btnListener = new Button.OnClickListener(){
int n = 0;
int length = 0;
String str = "";
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.btn1:
input_text += 1;
input.setText(input_text);
break;
case R.id.btn2:
input_text += 2;
input.setText(input_text);
break;
case R.id.btn3:
input_text += 3;
input.setText(input_text);
break;
case R.id.btn4:
input_text += 4;
input.setText(input_text);
break;
case R.id.btn5:
input_text += 5;
input.setText(input_text);
break;
case R.id.btn6:
input_text += 6;
input.setText(input_text);
break;
case R.id.btn7:
input_text += 7;
input.setText(input_text);
break;
case R.id.btn8:
input_text += 8;
input.setText(input_text);
break;
case R.id.btn9:
input_text += 9;
input.setText(input_text);
break;
case R.id.btn11:
input_text += 0;
input.setText(input_text);
break;
case R.id.btn10:
length = input.getText().toString().length();
if(length == 0 || length == 1){
str = "";
input_text = "";
}
else {
str = input.getText().toString().substring(0, length-1);
input_text = str;
}
input.setText(str);
break;
case R.id.btn12:
if(result == (n=Integer.parseInt(input.getText().toString())))
//맞았습니다!
;
else
//틀렸습니다!
;
break;
}
}
};
}
| Java |
package com.example.ten_minutes_more;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
import java.util.TimeZone;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Setting_alarm extends Activity {
public static Boolean ISNEW = false;
public static int POSITION = 0;
public static int ID ;
// 시간
int hour, minute;
TextView hour_t, minute_t, am_pm_t;
TextView hour_plus, hour_minus, minute_plus, minute_minus;
// 요일
ImageView mon, tue, wed, thu, fri, sat, sun;
boolean checked_mon, checked_tue, checked_wed, checked_thu, checked_fri,
checked_sat, checked_sun;
// 알람음
ArrayList<String> musicList;
ArrayAdapter<String> musicAdapter;
RadioGroup sound;
RadioButton radio_btn;
TextView musicTitle;
String title;
String music_id;
// 알람음 크기
SeekBar volume;
int volume_control;
// 알람해제
Spinner spin;
ArrayAdapter<?> adapter;
String game;
ImageButton complete;
static Context context;
GregorianCalendar currentCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"));
AlarmManager alarmManager;
// 저장
Button save;
Database db;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_alarm);
context = getApplicationContext();
db = new Database(this);
db.open();
hour_t = (TextView) findViewById(R.id.hour);
minute_t = (TextView) findViewById(R.id.min);
am_pm_t = (TextView) findViewById(R.id.AM);
long time = System.currentTimeMillis();
Calendar c = Calendar.getInstance();
c.setTimeInMillis(time);
mon = (ImageView) findViewById(R.id.mon);
tue = (ImageView) findViewById(R.id.tue);
wed = (ImageView) findViewById(R.id.wed);
thu = (ImageView) findViewById(R.id.thu);
fri = (ImageView) findViewById(R.id.fri);
sat = (ImageView) findViewById(R.id.sat);
sun = (ImageView) findViewById(R.id.sun);
radio_btn = (RadioButton)findViewById(R.id.radio0);
musicTitle = (TextView) findViewById(R.id.musicTitle);
spin = (Spinner) findViewById(R.id.spinner1);
adapter = ArrayAdapter.createFromResource(this, R.array.method,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(gameListener);
game = "";
volume = (SeekBar) findViewById(R.id.seekBar1);
volume.setOnSeekBarChangeListener(volumeListener);
volume.setMax(100);
volume.incrementProgressBy(1);
if (ISNEW == true) {
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
if (hour > 12) {
hour = hour - 12;
am_pm_t.setText("PM");
}
if (hour < 10)
hour_t.setText("0" + Integer.toString(hour));
else
hour_t.setText(Integer.toString(hour));
if (minute < 10)
minute_t.setText("0" + Integer.toString(minute));
else
minute_t.setText(Integer.toString(minute));
checked_mon = false;
checked_tue = false;
checked_wed = false;
checked_thu = false;
checked_fri = false;
checked_sat = false;
checked_sun = false;
}
else {
Alarm_data selectedAlarm = MainActivity.data.get(POSITION);
String hour_minute = selectedAlarm.getTime();
Scanner scan = new Scanner(hour_minute);
scan.useDelimiter("시");
String h = scan.next();
if(Integer.parseInt(h) < 10)
h = "0" + h;
String m = scan.next();
if(m.length() == 3){
m = m.substring(1, 2);
m = "0" + m;
}
else if(m.length() == 4)
m = m.substring(1, 3);
//데이터 불러오기
hour_t.setText(h);
minute_t.setText(m);
am_pm_t.setText(selectedAlarm.getAm_Pm());
ID = selectedAlarm.getId();
//월
if(selectedAlarm.getDay_mon() == R.drawable.monday_checked + 2)
mon.setImageResource(R.drawable.monday_checked);
else
mon.setImageResource(R.drawable.monday);
//화
if(selectedAlarm.getDay_tue() == R.drawable.tuesday_checked + 2)
tue.setImageResource(R.drawable.tuesday_checked);
else
tue.setImageResource(R.drawable.tuesday);
//수
if(selectedAlarm.getDay_wed() == R.drawable.wednesday_checked + 2)
wed.setImageResource(R.drawable.wednesday_checked);
else
wed.setImageResource(R.drawable.wednesday);
//목
if(selectedAlarm.getDay_thu() == R.drawable.thursday_checked + 2)
thu.setImageResource(R.drawable.thursday_checked);
else
thu.setImageResource(R.drawable.thursday);
//금
if(selectedAlarm.getDay_fri() == R.drawable.friday_checked + 2)
fri.setImageResource(R.drawable.friday_checked);
else
fri.setImageResource(R.drawable.friday);
//토
if(selectedAlarm.getDay_sat() == R.drawable.saturday_checked + 2)
sat.setImageResource(R.drawable.saturday_checked);
else
sat.setImageResource(R.drawable.saturday);
//일
if(selectedAlarm.getDay_sun() == R.drawable.sunday_checked + 2)
sun.setImageResource(R.drawable.sunday_checked);
else
sun.setImageResource(R.drawable.sunday);
checked_mon = db.isCheckedMon(ID);
checked_tue = db.isCheckedTue(ID);
checked_wed = db.isCheckedWed(ID);
checked_thu = db.isCheckedThu(ID);
checked_fri = db.isCheckedFri(ID);
checked_sat = db.isCheckedSat(ID);
checked_sun = db.isCheckedSun(ID);
musicTitle.setText(db.getMusicTitle(ID));
volume.setProgress(db.getVolume(ID));
spin.setSelection(db.getGame(ID));
}
hour_plus = (TextView) findViewById(R.id.hour_plus);
hour_minus = (TextView) findViewById(R.id.hour_minus);
minute_plus = (TextView) findViewById(R.id.minute_plus);
minute_minus = (TextView) findViewById(R.id.minute_minus);
hour_plus.setOnClickListener(buttonListener);
hour_minus.setOnClickListener(buttonListener);
minute_plus.setOnClickListener(buttonListener);
minute_minus.setOnClickListener(buttonListener);
am_pm_t.setOnClickListener(buttonListener);
mon.setOnClickListener(dayListener);
tue.setOnClickListener(dayListener);
wed.setOnClickListener(dayListener);
thu.setOnClickListener(dayListener);
fri.setOnClickListener(dayListener);
sat.setOnClickListener(dayListener);
sun.setOnClickListener(dayListener);
sound = (RadioGroup) findViewById(R.id.radioGroup1);
sound.setOnCheckedChangeListener(soundListener);
title = musicTitle.getText().toString();
musicList = new ArrayList<String>();
musicList = getMusicList();
musicAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, musicList);
save = (Button) findViewById(R.id.save);
save.setOnClickListener(saveListener);
}
Button.OnClickListener saveListener = new Button.OnClickListener() {
int h = 0, m = 0, vc = 0;
String ap = "", g = "", s = "";
int check_mon = 0,
check_tue = 0,
check_wed = 0,
check_thu = 0,
check_fri = 0,
check_sat = 0,
check_sun = 0;
int reqCode = ID ; // 알람 고유 id 및 인텐트로 데이터 전송
@Override
public void onClick(View arg0) {
if (checked_mon)
check_mon = 1;
if (checked_tue)
check_tue = 1;
if (checked_wed)
check_wed = 1;
if (checked_thu)
check_thu = 1;
if (checked_fri)
check_fri = 1;
if (checked_sat)
check_sat = 1;
if (checked_sun)
check_sun = 1;
if((check_mon+check_tue+check_tue+check_wed+check_thu+check_fri+check_sat+check_sun)==0){
Toast.makeText(context, "요일을 선택해주세요", Toast.LENGTH_SHORT).show();
return;
}
if(musicTitle.getText().toString().equals("")){
Toast.makeText(context, "알람음을 선택해주세요", Toast.LENGTH_SHORT).show();
return;
}
getData();
int hh = Integer.parseInt(hour_t.getText().toString());
int mm = Integer.parseInt(minute_t.getText().toString());
String ampm = am_pm_t.getText().toString();
GregorianCalendar gregorianCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"));
gregorianCalendar = currentCalendar;
gregorianCalendar.set(Calendar.HOUR, hh);
gregorianCalendar.set(Calendar.MINUTE, mm);
if(ampm.equals("am"))
gregorianCalendar.set(Calendar.AM_PM, Calendar.AM);
else
gregorianCalendar.set(Calendar.AM_PM, Calendar.PM);
gregorianCalendar.set(Calendar.SECOND, 0);
Log.i("TAG",gregorianCalendar.getTimeInMillis()+":");
Intent intent = new Intent(Setting_alarm.this, PopupActivity.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
reqCode = db.getLastId();
Log.i("id", "id:"+reqCode);
intent.putExtra("reqCode", reqCode);
PendingIntent pi = PendingIntent.getActivity(Setting_alarm.this, reqCode, intent,PendingIntent.FLAG_ONE_SHOT );
alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, gregorianCalendar.getTimeInMillis() ,AlarmManager.INTERVAL_DAY, pi);
Intent main = new Intent(context,MainActivity.class);
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
finish();
}
public void getData(){
h = Integer.parseInt(hour_t.getText().toString());
//if(am_pm_t.getText().equals("PM"))
// h = h + 12;
m = Integer.parseInt(minute_t.getText().toString());
ap = am_pm_t.getText().toString();
g = game;
s = title;
vc = volume_control;
if(ISNEW == true){
db.addAlarmList(h, m, ap, check_mon, check_tue, check_wed,
check_thu, check_fri, check_sat, check_sun, g, s, vc);
db.addMusicList(music_id);
ID = db.getLastId();
}else{
db.updateAlarmList(h, m, ap, check_mon, check_tue, check_wed,
check_thu, check_fri, check_sat, check_sun, g, s, vc, ID);
db.updateMusicList(music_id, ID);
}
}
};
Spinner.OnItemSelectedListener gameListener = new Spinner.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
game = spin.getSelectedItem().toString();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
public ArrayList<String> getMusicList() {
ArrayList<String> list = new ArrayList<String>();
String[] proj = {
MediaStore.Audio.Media.TITLE };
Cursor cursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null,
null);
if (cursor != null && cursor.moveToFirst()) {
String title;
int musicTitleCol = cursor
.getColumnIndex(MediaStore.Audio.Media.TITLE);
do {
title = cursor.getString(musicTitleCol);
list.add(title);
} while (cursor.moveToNext());
}
//cursor.close();
return list;
}
public String getMusicID(int index){
ArrayList<String> list = new ArrayList<String>();
String[] proj = {
MediaStore.Audio.Media._ID };
Cursor cursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null,
null);
if (cursor != null && cursor.moveToFirst()) {
String musicID;
int musicIDCol = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
do {
musicID = cursor.getString(musicIDCol);
list.add(musicID);
} while (cursor.moveToNext());
}
//cursor.close();
return list.get(index);
}
SeekBar.OnSeekBarChangeListener volumeListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
volume_control = progress;
}
};
ImageView.OnClickListener dayListener = new ImageView.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.mon:
if (!checked_mon) {
mon.setImageResource(R.drawable.monday_checked);
checked_mon = true;
} else {
mon.setImageResource(R.drawable.monday);
checked_mon = false;
}
break;
case R.id.tue:
if (!checked_tue) {
tue.setImageResource(R.drawable.tuesday_checked);
checked_tue = true;
} else {
tue.setImageResource(R.drawable.tuesday);
checked_tue = false;
}
break;
case R.id.wed:
if (!checked_wed) {
wed.setImageResource(R.drawable.wednesday_checked);
checked_wed = true;
} else {
wed.setImageResource(R.drawable.wednesday);
checked_wed = false;
}
break;
case R.id.thu:
if (!checked_thu) {
thu.setImageResource(R.drawable.thursday_checked);
checked_thu = true;
} else {
thu.setImageResource(R.drawable.thursday);
checked_thu = false;
}
break;
case R.id.fri:
if (!checked_fri) {
fri.setImageResource(R.drawable.friday_checked);
checked_fri = true;
} else {
fri.setImageResource(R.drawable.friday);
checked_fri = false;
}
break;
case R.id.sat:
if (!checked_sat) {
sat.setImageResource(R.drawable.saturday_checked);
checked_sat = true;
} else {
sat.setImageResource(R.drawable.saturday);
checked_sat = false;
}
break;
case R.id.sun:
if (!checked_sun) {
sun.setImageResource(R.drawable.sunday_checked);
checked_sun = true;
} else {
sun.setImageResource(R.drawable.sunday);
checked_sun = false;
}
break;
}
}
};
Button.OnClickListener buttonListener = new Button.OnClickListener() {
String before = "";
int after = 0;
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.hour_plus:
before = hour_t.getText().toString();
if (before.equals("12"))
hour_t.setText("01");
else {
after = Integer.parseInt(before) + 1;
if (after < 10)
hour_t.setText("0" + Integer.toString(after));
else
hour_t.setText(Integer.toString(after));
}
break;
case R.id.hour_minus:
before = hour_t.getText().toString();
if (before.equals("01"))
hour_t.setText("12");
else {
after = Integer.parseInt(before) - 1;
if (after < 10)
hour_t.setText("0" + Integer.toString(after));
else
hour_t.setText(Integer.toString(after));
}
break;
case R.id.minute_plus:
before = minute_t.getText().toString();
if (before.equals("59"))
minute_t.setText("00");
else {
after = Integer.parseInt(before) + 1;
if (after < 10)
minute_t.setText("0" + Integer.toString(after));
else
minute_t.setText(Integer.toString(after));
}
break;
case R.id.minute_minus:
before = minute_t.getText().toString();
if (before.equals("00"))
minute_t.setText("59");
else {
after = Integer.parseInt(before) - 1;
if (after < 10)
minute_t.setText("0" + Integer.toString(after));
else
minute_t.setText(Integer.toString(after));
}
break;
case R.id.AM:
before = am_pm_t.getText().toString();
if (before.equals("AM"))
am_pm_t.setText("PM");
else
am_pm_t.setText("AM");
}
}
};
RadioGroup.OnCheckedChangeListener soundListener = new RadioGroup.OnCheckedChangeListener() {
int index = 0;
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if (group.getId() == R.id.radioGroup1) {
switch (checkedId) {
case R.id.radio0:
new AlertDialog.Builder(Setting_alarm.this)
.setTitle("음악 목록 보기")
.setAdapter(musicAdapter,
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface arg0, int arg1) {
title = musicList.get(arg1);
index = musicList.indexOf(title);
music_id = getMusicID(index);
musicTitle.setText(title);
radio_btn.setChecked(false);
}
}).create().show();
break;
}
}
}
};
}
| Java |
package com.example.ten_minutes_more;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class DelayAlarm extends Activity {
TextView delaymin;
Button up, down, more;
Context context;
int id;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.delay_time);
delaymin = (TextView) findViewById(R.id.delaymin);
up = (Button) findViewById(R.id.up);
down = (Button) findViewById(R.id.down);
more = (Button) findViewById(R.id.moresleep);
up.setOnClickListener(upmin);
down.setOnClickListener(downmin);
more.setOnClickListener(moresleep);
context = getApplicationContext();
Intent data = getIntent();
id = data.getIntExtra("id", 0);
}
OnClickListener upmin = new OnClickListener() {
@Override
public void onClick(View arg0) {
if (delaymin.getText().equals("59"))
delaymin.setText("00");
else {
int min = Integer.parseInt(delaymin.getText().toString());
min++;
delaymin.setText(String.valueOf(min));
}
}
};
OnClickListener downmin = new OnClickListener() {
@Override
public void onClick(View arg0) {
if (delaymin.getText().equals("00"))
delaymin.setText("59");
else {
int min = Integer.parseInt(delaymin.getText().toString());
min--;
delaymin.setText(String.valueOf(min));
}
}
};
OnClickListener moresleep = new OnClickListener() {
@Override
public void onClick(View arg0) {
GregorianCalendar currentCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"));
GregorianCalendar gregorianCalendar = currentCalendar;
Database db = new Database(context);
db.open();
int hh = db.getHour(id);
int mm = db.getMin(id);
String ampm = db.getAMPM(id);
if(ampm.equals("am"))
gregorianCalendar.set(Calendar.AM_PM, Calendar.AM);
else
gregorianCalendar.set(Calendar.AM_PM, Calendar.PM);
gregorianCalendar.set(Calendar.SECOND, 0);
int delaymm = Integer.parseInt(delaymin.getText().toString());
gregorianCalendar.add(Calendar.MINUTE, delaymm);
Intent intent = new Intent(DelayAlarm.this, PopupActivity.class);
intent.putExtra("reqCode", 0);
PendingIntent pi = PendingIntent.getActivity(DelayAlarm.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, gregorianCalendar.getTimeInMillis(), pi);
finish();
}
};
}
| Java |
package com.example.ten_minutes_more;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Database {
private static String DB_NAME = "alarm";
private static int DB_VERSION = 7;
private final Context context;
private DatabaseHelper mDbHelper;
private static SQLiteDatabase db;
public static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper (Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE list(hour INT, minute INT, am_pm TEXT,"
+ " mon INT, tue INT, wed INT, thu INT, fri INT, sat INT, sun INT,"
+ " game TEXT, sound TEXT, volume INT, id INT)";
db.execSQL(sql);
String sql_create_music = "CREATE TABLE musicList(musicID TEXT, id INT)";
db.execSQL(sql_create_music);
String sql2 = "CREATE TABLE last_id(id INT)";
String sql3 = "INSERT INTO last_id(id) VALUES (1);";
db.execSQL(sql2);
db.execSQL(sql3);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS list; DROP TABLE IF EXISTS last_id;");
onCreate(db);
}
}
public Database(Context context) {
this.context = context;
}
public Database open() throws SQLException {
mDbHelper = new DatabaseHelper(context);
db = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public void addAlarmList(int hour, int minute, String am_pm, int mon,
int tue, int wed, int thu, int fri, int sat, int sun, String game,
String sound, int volume) {
int id = getLastId();
id++;
db.execSQL("INSERT INTO list(hour, minute, am_pm, mon, tue, wed, thu, fri, sat, sun, game, sound, volume, id)" +
" VALUES (" + hour + "," + minute + ",'"
+ am_pm + "'" + "," + mon + "," + tue + "," + wed + "," + thu
+ "," + fri + "," + sat + "," + sun + ",'" + game + "'" + ",'"
+ sound + "'," + volume + ","+id+");");
db.execSQL("UPDATE last_id SET id = "+id+" WHERE id="+(id-1)+";");
}
public void addMusicList(String musicID) {
int id = getLastId();
id++;
db.execSQL("INSERT INTO musicList(musicID, id)" +
" VALUES ('" + musicID + "'," + id + ");");
}
public void deleteAlarmList(int id) {
db.execSQL("DELETE FROM list WHERE id ="+id+";");
}
public void updateAlarmList(int hour, int minute, String am_pm, int mon,
int tue, int wed, int thu, int fri, int sat, int sun, String game,
String sound, int volume, int id) {
db.execSQL("UPDATE list SET hour ="+hour+", minute ="+minute+", am_pm ='"+am_pm+"', mon ="+mon+
", tue="+tue+", wed="+wed+", thu="+thu+", fri="+fri+", sat="+sat+", sun="+sun+", game='"+game+
"', sound='"+sound+"', volume="+volume+" WHERE id ="+id+";");
}
public void updateMusicList(String musicID, int id) {
db.execSQL("UPDATE musicList SET musicID ='"+musicID+"', id ="+id+";");
}
public Cursor getAlarmList() {
Cursor c = db.rawQuery("SELECT * FROM list;", null);
if (c != null && c.getCount() != 0)
c.moveToFirst();
return c;
}
public int getLastId(){
Cursor c= db.rawQuery("SELECT id FROM last_id;",null);
c.moveToFirst();
return c.getInt(0);
}
public int getGame(int id){
Log.e("tag", "id:"+id);
Cursor c= db.rawQuery("SELECT game FROM list WHERE id ="+id+"", null);
c.moveToFirst();
String game = c.getString(0);
if(game.equals("없음"))
return 0;
else if(game.equals("문자입력"))
return 1;
else // 구구단
return 2;
}
public String getMusicID(int id){
Cursor c= db.rawQuery("SELECT musicID FROM musicList WHERE id ='"+id+"';", null);
c.moveToFirst();
String musicID = c.getString(0);
return musicID;
}
public int getHour(int id){
Log.e("tag", "id:"+id);
Cursor c= db.rawQuery("SELECT hour FROM list WHERE id ="+id+"", null);
c.moveToFirst();
return c.getInt(0);
}
public int getMin(int id){
Log.e("tag", "id:"+id);
Cursor c= db.rawQuery("SELECT minute FROM list WHERE id ="+id+"", null);
c.moveToFirst();
return c.getInt(0);
}
public String getAMPM(int id)
{
Log.e("tag", "id:"+id);
Cursor c= db.rawQuery("SELECT am_pm FROM list WHERE id ="+id+"", null);
c.moveToFirst();
return c.getString(0);
}
public boolean isCheckedMon(int id){
Cursor c = db.rawQuery("SELECT mon FROM list WHERE id="+id+";", null);
c.moveToFirst();
if(c.getInt(0)==0)
return false;
else
return true;
}
public boolean isCheckedTue(int id){
Cursor c = db.rawQuery("SELECT tue FROM list WHERE id="+id+";", null);
c.moveToFirst();
if(c.getInt(0)==0)
return false;
else
return true;
}
public boolean isCheckedWed(int id){
Cursor c = db.rawQuery("SELECT wed FROM list WHERE id="+id+";", null);
c.moveToFirst();
if(c.getInt(0)==0)
return false;
else
return true;
}
public boolean isCheckedThu(int id){
Cursor c = db.rawQuery("SELECT thu FROM list WHERE id="+id+";", null);
c.moveToFirst();
if(c.getInt(0)==0)
return false;
else
return true;
}
public boolean isCheckedFri(int id){
Cursor c = db.rawQuery("SELECT fri FROM list WHERE id="+id+";", null);
c.moveToFirst();
if(c.getInt(0)==0)
return false;
else
return true;
}
public boolean isCheckedSat(int id){
Cursor c = db.rawQuery("SELECT sat FROM list WHERE id="+id+";", null);
c.moveToFirst();
if(c.getInt(0)==0)
return false;
else
return true;
}
public boolean isCheckedSun(int id){
Cursor c = db.rawQuery("SELECT sun FROM list WHERE id="+id+";", null);
c.moveToFirst();
if(c.getInt(0)==0)
return false;
else
return true;
}
public int getVolume(int id){
Cursor c= db.rawQuery("SELECT volume FROM list WHERE id ="+id+"", null);
c.moveToFirst();
int volume = c.getInt(0);
return volume;
}
public String getMusicTitle(int id){
Cursor c= db.rawQuery("SELECT sound FROM list WHERE id ="+id+"", null);
c.moveToFirst();
String title = c.getString(0);
return title;
}
}
| Java |
package com.example.ten_minutes_more;
public class Alarm_data{
private int id;
private int clock;
private String time;
private int monday;
private int tuesday;
private int wednesday;
private int thursday;
private int friday;
private int saturday;
private int sunday;
private String am_pm;
public Alarm_data(int clock, String time,
int monday, int tuesday, int wednesday, int thursday,
int friday, int saturday, int sunday, String am_pm, int id) {
this.id = id;
this.clock = clock;
this.time = time;
this.monday = monday;
this.tuesday = tuesday;
this.wednesday = wednesday;
this.thursday = thursday;
this.friday = friday;
this.saturday = saturday;
this.sunday = sunday;
this.am_pm = am_pm;
}
public int getClock(){
return clock;
}
public String getTime(){
return time;
}
public int getDay_mon() {
return monday;
}
public int getDay_tue() {
return tuesday;
}
public int getDay_wed() {
return wednesday;
}
public int getDay_thu() {
return thursday;
}
public int getDay_fri() {
return friday;
}
public int getDay_sat() {
return saturday;
}
public int getDay_sun() {
return sunday;
}
public String getAm_Pm() {
return am_pm;
}
public int getId(){
return id;
}
}
| Java |
package com.example.ten_minutes_more;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Text extends Activity {
String[] str = {
"설마 오늘도 쌩얼로 가려고?",
"일찍 일어나는 새가 벌레를 많이 먹는다는데",
"잠만보야 일어나",
"미인은 잠꾸러기라는데 넌...",
"일어나",
"짹짹",
"일어나시지",
"일어날래?",
"지금 안 일어나면 오늘도 쌩얼이다",
"다른 사람들의 눈도 존중해줘야지..."
};
Random generator;
int index;
TextView text;
EditText input;
Button complete;
String user_input;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
// TODO Auto-generated method stub
generator = new Random();
index = generator.nextInt(10);
text = (TextView)findViewById(R.id.text);
text.setText(str[index]);
input = (EditText)findViewById(R.id.input);
complete = (Button)findViewById(R.id.input_complete);
complete.setOnClickListener(buttonListener);
}
Button.OnClickListener buttonListener = new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
user_input = input.getText().toString();
if(user_input.equals(text.getText().toString()))
//맞았습니다!
;
else
//틀렸습니다!
;
}
};
}
| Java |
/**
* @file EclairMotionEvent.java
* @brief
*
* Copyright (C)2010-2012 Magnus Uppman <magnus.uppman@gmail.com>
* License: GPLv3+
*/
package com.linuxfunkar.mousekeysremote;
import android.view.MotionEvent;
public class EclairMotionEvent extends WrapMotionEvent {
protected EclairMotionEvent(MotionEvent event)
{
super(event);
}
public final int findPointerIndex(int pointerId) {
return event.findPointerIndex(pointerId);
}
public final int getPointerCount() {
return event.getPointerCount();
}
public final int getPointerId(int pointerIndex) {
return event.getPointerId(pointerIndex);
}
public final float getX(int pointerIndex) {
return event.getX(pointerIndex);
}
public final float getY(int pointerIndex) {
return event.getY(pointerIndex);
}
}
| Java |
package com.linuxfunkar.mousekeysremote;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import android.util.Base64;
class Security {
private static final String algorithm = "PBEWithMD5AndDES";
private static final byte[] salt = new byte[] { 67, (byte) 222, 18,
(byte) 174, 59, (byte) 243, 69, 125 };
private SecretKey key;
private Cipher cipher;
public Security(String password) throws NoSuchAlgorithmException,
InvalidKeyException, InvalidKeySpecException,
NoSuchPaddingException, InvalidAlgorithmParameterException {
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
char[] pass = password.toCharArray();
key = factory.generateSecret(new PBEKeySpec(pass));
cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, 2048));
}
public String encrypt(String msg) throws InvalidKeyException,
BadPaddingException, IllegalBlockSizeException,
UnsupportedEncodingException {
byte[] inputBytes = msg.getBytes("UTF-8");
byte[] encbytes = cipher.doFinal(inputBytes);
String ret = Base64.encodeToString(encbytes, Base64.NO_WRAP);
return ret;
}
}
| Java |
/**
* @file ColorPickerDialog.java
* @brief
*
* Copyright (C)2012 Magnus Uppman <magnus.uppman@gmail.com>
* License: GPLv3+
*/
package com.linuxfunkar.mousekeysremote;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
public class ColorPickerDialog extends Dialog {
public static final String PROP_INITIAL_COLOR = "InitialColor";
public static final String PROP_PARENT_WIDTH = "Width";
public static final String PROP_PARENT_HEIGHT = "Height";
public static final String PROP_COLORELEM = "ColorElement";
private int measuredWidth;
private int measuredHeight;
public interface OnColorChangedListener {
void colorChanged(int color, int elem);
}
protected OnColorChangedListener colorChangedListener;
private int mInitialColor;
private int colorElem;
private class ColorPickerView extends View {
private Paint mPaint;
private Paint mCenterPaint;
private final int[] mColors;
private OnColorChangedListener mListener;
ColorPickerView(Context context, int color) {
super(context);
mColors = new int[] { 0xFFFF0000, 0xFFFF00FF, 0xFF0000FF,
0xFF00FFFF, 0xFF88FF88, 0xFFFFFF00, 0xFFFF0000, 0xFF000000,
0xFF888888, 0xFF00FF00, 0xFFFF0000
// 0xFF000000, 0xFF0000FF, 0xFFFFFFFF, 0xFF00FF00, 0xFF000000,
// 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFF00, 0xFF000000, 0xFFFFFFFF,
// 0xFF00FFFF, 0xFF000000
};
// 0xFFFFFFFF, 0xFF000000
Shader s = new SweepGradient(0, 0, mColors, null);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setShader(s);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(32);
mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterPaint.setColor(color);
mCenterPaint.setStrokeWidth(5);
}
private boolean mTrackingCenter;
private boolean mHighlightCenter;
private void setOnColorChangedListener(OnColorChangedListener listener) {
mListener = listener;
}
@Override
protected void onDraw(Canvas canvas) {
float r = CENTER_X - mPaint.getStrokeWidth() * 0.5f;
canvas.translate(CENTER_X, CENTER_X);
canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);
if (mTrackingCenter) {
int c = mCenterPaint.getColor();
mCenterPaint.setStyle(Paint.Style.STROKE);
if (mHighlightCenter) {
mCenterPaint.setAlpha(0xFF);
} else {
mCenterPaint.setAlpha(0x80);
}
canvas.drawCircle(0, 0,
CENTER_RADIUS + mCenterPaint.getStrokeWidth(),
mCenterPaint);
mCenterPaint.setStyle(Paint.Style.FILL);
mCenterPaint.setColor(c);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
MouseKeysRemote.debug("x: " + measuredWidth + "y: "
+ measuredHeight);
// setMeasuredDimension(widthMeasureSpec / 2, heightMeasureSpec /2);
setMeasuredDimension(CENTER_X * 2, CENTER_Y * 2);
}
private int CENTER_X = measuredWidth / 3; // 100;
private int CENTER_Y = measuredWidth / 3;
private int CENTER_RADIUS = measuredWidth / 6;
private int floatToByte(float x) {
int n = java.lang.Math.round(x);
return n;
}
private int pinToByte(int n) {
if (n < 0) {
n = 0;
} else if (n > 255) {
n = 255;
}
return n;
}
private int ave(int s, int d, float p) {
return s + java.lang.Math.round(p * (d - s));
}
private int interpColor(int colors[], float unit) {
if (unit <= 0) {
return colors[0];
}
if (unit >= 1) {
return colors[colors.length - 1];
}
float p = unit * (colors.length - 1);
int i = (int) p;
p -= i;
// now p is just the fractional part [0...1) and i is the index
int c0 = colors[i];
int c1 = colors[i + 1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
return Color.argb(a, r, g, b);
}
private int rotateColor(int color, float rad) {
float deg = rad * 180 / 3.1415927f;
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
ColorMatrix cm = new ColorMatrix();
ColorMatrix tmp = new ColorMatrix();
cm.setRGB2YUV();
tmp.setRotate(0, deg);
cm.postConcat(tmp);
tmp.setYUV2RGB();
cm.postConcat(tmp);
final float[] a = cm.getArray();
int ir = floatToByte(a[0] * r + a[1] * g + a[2] * b);
int ig = floatToByte(a[5] * r + a[6] * g + a[7] * b);
int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b);
return Color.argb(Color.alpha(color), pinToByte(ir), pinToByte(ig),
pinToByte(ib));
}
private static final float PI = 3.1415926f;
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX() - CENTER_X;
float y = event.getY() - CENTER_Y;
boolean inCenter = java.lang.Math.sqrt(x * x + y * y) <= CENTER_RADIUS;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTrackingCenter = inCenter;
if (inCenter) {
mHighlightCenter = true;
invalidate();
break;
}
case MotionEvent.ACTION_MOVE:
if (mTrackingCenter) {
if (mHighlightCenter != inCenter) {
mHighlightCenter = inCenter;
invalidate();
}
} else {
float angle = (float) java.lang.Math.atan2(y, x);
// need to turn angle [-PI ... PI] into unit [0....1]
float unit = angle / (2 * PI);
if (unit < 0) {
unit += 1;
}
mCenterPaint.setColor(interpColor(mColors, unit));
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (mTrackingCenter) {
if (inCenter) {
mListener.colorChanged(mCenterPaint.getColor(),
colorElem);
}
mTrackingCenter = false; // so we draw w/o halo
invalidate();
}
break;
}
return true;
}
}
public ColorPickerDialog(Context context, Bundle props) {
super(context);
mInitialColor = props.getInt(PROP_INITIAL_COLOR, 0);
measuredWidth = props.getInt(PROP_PARENT_WIDTH, 640);
measuredHeight = props.getInt(PROP_PARENT_HEIGHT, 480);
colorElem = props.getInt(PROP_COLORELEM, 0);
}
public void setColorChangedListener(OnColorChangedListener listener) {
colorChangedListener = listener;
}
protected void fireColorChangedListener(int color, int colorElem) {
colorChangedListener.colorChanged(color, colorElem);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnColorChangedListener l = new OnColorChangedListener() {
public void colorChanged(int color, int colorElem) {
fireColorChangedListener(color, colorElem);
dismiss();
}
};
ColorPickerView colorPickerView = new ColorPickerView(getContext(),
mInitialColor);
colorPickerView.setOnColorChangedListener(l);
setContentView(colorPickerView);
setTitle("Pick a Color");
}
} | Java |
/**
* @file CustomDrawableView.java
* @brief
*
* Copyright (C)2010-2012 Magnus Uppman <magnus.uppman@gmail.com>
* License: GPLv3+
*/
package com.linuxfunkar.mousekeysremote;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.view.View;
import com.linuxfunkar.mousekeysremote.MouseKeysRemote.EditMode;
public class CustomDrawableView extends View {
private static final String MARK_S = "(s)";
private static final String MARK_C = "(C)";
private static final String MARK_HASH = "(#)";
private static final String MARK_STAR = "(*)";
private ShapeDrawable mDrawable, backGround, wheel;
private int measuredHeight = 0;
private int measuredWidth = 0;
private int keyWidth = 0;
private int keyHeight = 0;
private RectF keyRect;
private Paint rectPaint, textPaint, textLayoutPaint, textLabelLayoutPaint;
// Convert the dps to pixels
final float scale = getContext().getResources().getDisplayMetrics().density;
final float xdpi = getContext().getResources().getDisplayMetrics().xdpi;
float tsize, t_layout_size, l_layout_size;
private String mark;
private EditMode mode = EditMode.None;
public CustomDrawableView(Context context) {
super(context);
// private int a = (RemotePC.)
// colorObj = new Color();
keyRect = new RectF();
rectPaint = new Paint();
textPaint = new Paint();
textLayoutPaint = new Paint();
textLabelLayoutPaint = new Paint();
rectPaint.setStyle(Paint.Style.FILL_AND_STROKE);
textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
// textPaint.setFakeBoldText(true);
textLabelLayoutPaint.setAntiAlias(true);
textPaint.setAntiAlias(true);
textPaint.setTextAlign(Paint.Align.CENTER);
// rectPaint.setColor(R.color.key_color);
// rectPaint.setColor(0xff74AC23);
// rectPaint.setColor(0xff333333);
textPaint.setColor(0xffffffff);
// textPaint.setColor(0xff333333);
// textPaint.setStrokeWidth(1);
// textPaint.set
tsize = textPaint.getFontSpacing();
textLayoutPaint.setColor(0xffffffff); // Layout number
textLabelLayoutPaint.setColor(0xaa00ff00); // Layout label
mDrawable = new ShapeDrawable(new RectShape()); // Mousepad
// mDrawable.getPaint().setColor(0xff000088); // Blue
mDrawable.getPaint().setColor(0xff2222ff); // Blue
wheel = new ShapeDrawable(new RectShape()); // Mousepad wheel
// wheel.getPaint().setColor(0xff555588); //
wheel.getPaint().setColor(0xff8888ff); //
backGround = new ShapeDrawable(new RectShape()); // Keys background
// backGround.getPaint().setColor(0xff8888ff); // Blue
backGround.getPaint().setColor(0xff000000); // Black
MouseKeysRemote.mouseWheelWidth = (int) (xdpi / 2);
}
public void setMark(EditMode mode) {
this.mode = mode;
if (mode == EditMode.Binding) {
mark = MARK_STAR;
} else if (mode == EditMode.Name) {
mark = MARK_HASH;
} else if (mode == EditMode.Color) {
mark = MARK_C;
} else if (mode == EditMode.Sticky) {
mark = MARK_S;
this.mode = EditMode.None;
} else {
mark = "";
}
}
@Override
protected void onMeasure(int wMeasureSpec, int hMeasureSpec) {
measuredHeight = MeasureSpec.getSize(hMeasureSpec);
measuredWidth = MeasureSpec.getSize(wMeasureSpec);
/*
* if (RemotePC2.enableMouseWheel) // Fill entire right hand side. Maybe
* later.. { RemotePC2.xOffsetRight = (int)(xdpi/2); } else
* RemotePC2.xOffsetRight = 0;
*/
if (MouseKeysRemote.enableMousePad) {
float calc = (float) measuredHeight
* (((float) MouseKeysRemote.mousepadRelativeSize / 100));
// RemotePC2.debug ((int)calc);
MouseKeysRemote.yOffsetBottom = (int) calc; // 200; //measuredHeight
// -
// measuredHeight/(RemotePC2.mousepadRelativeSize/10);
// // Size of
// keypad/mousepad
} else
MouseKeysRemote.yOffsetBottom = 0;
try {
keyWidth = ((measuredWidth - MouseKeysRemote.xOffsetRight) - MouseKeysRemote.xOffsetLeft)
/ MouseKeysRemote.numberOfKeyCols;
keyHeight = ((measuredHeight - MouseKeysRemote.yOffsetBottom) - MouseKeysRemote.yOffsetTop)
/ MouseKeysRemote.numberOfKeyRows;
} catch (Exception e) {
MouseKeysRemote.debug(e.toString());
}
// RemotePC2.debug("measuredHeight: " + measuredHeight +
// " measuredWidth: " + measuredWidth);
// RemotePC2.debug("keyWidth: " + keyWidth + "keyHeight: " + keyHeight);
// textLayoutPaint.setTextSize(measuredHeight);
textLabelLayoutPaint.setTextSize(measuredHeight / 16);
// t_layout_size = textLayoutPaint.getFontSpacing();
l_layout_size = textLabelLayoutPaint.getFontSpacing();
// RemotePC2.debug("t_layout_size: " + t_layout_size);
// textPaint.setTextSize(keyHeight/6);
MouseKeysRemote.keyWidth = keyWidth;
MouseKeysRemote.keyHeight = keyHeight;
setMeasuredDimension(measuredWidth, measuredHeight);
}
protected void onDraw(Canvas canvas) {
// RemotePC.debug("onDraw: h:" + getMeasuredHeight() +" w: " +
// getMeasuredWidth());
backGround.getPaint().setColor(MouseKeysRemote.backCol);
backGround.setBounds(0, 0, measuredWidth, measuredHeight);
backGround.draw(canvas);
textPaint.setTextScaleX(MouseKeysRemote.textSize);
if (MouseKeysRemote.calibrate == true) {
canvas.drawText("Calibrate sensors", 0, measuredHeight / 4,
textLabelLayoutPaint);
canvas.drawText("Touch when ready!", 0, measuredHeight / 2,
textLabelLayoutPaint);
} else {
drawMousepad(canvas);
drawKeys(canvas);
drawLayoutlabel(canvas);
}
}
private void drawLayoutlabel(Canvas canvas) {
// Draw layout label
String layoutLabel = MouseKeysRemote.keys_layout_name;
float layoutLabelWidth = textLabelLayoutPaint.measureText(layoutLabel);
canvas.drawText(layoutLabel,
(measuredWidth / 2) - layoutLabelWidth / 2, measuredHeight
- (l_layout_size / 2), textLabelLayoutPaint);
}
private void drawKeys(Canvas canvas) {
int keyCnt = 0;
int keyCol;
for (int i = 0; i < MouseKeysRemote.numberOfKeyRows; i++) {
// yCnt = yCnt + (keyHeight * i); // Row
for (int j = 0; j < MouseKeysRemote.numberOfKeyCols; j++) {
MouseKeysRemote.x1Pos[keyCnt] = MouseKeysRemote.xOffsetLeft
+ (keyWidth * j);
MouseKeysRemote.y1Pos[keyCnt] = MouseKeysRemote.yOffsetTop
+ (keyHeight * i);
MouseKeysRemote.x2Pos[keyCnt] = MouseKeysRemote.xOffsetLeft
+ (keyWidth * j) + keyWidth;
MouseKeysRemote.y2Pos[keyCnt] = MouseKeysRemote.yOffsetTop
+ (keyHeight * i) + keyHeight;
// RemotePC2.debug("keyRect.toString: " +
// keyRect.toString());
int sticky = 0; // MouseKeysRemote.getKeyValueSticky(keyCnt +
// 1);
keyCol = MouseKeysRemote.mySharedPreferences.getInt("KeyColor"
+ "layout" + MouseKeysRemote.keys_layout + "key"
+ (keyCnt + 1), 0xff2222bb);
//
// int r = Color.red(keyCol);
// int g = Color.green(keyCol);
// int b = Color.blue(keyCol);
// newCol = Color.argb(255, (255 -r)*2 & 0xFF, (255 -g)*2 &
// 0xFF ,(255 -b)*2 & 0xFF);
//
if ((MouseKeysRemote.keyState[keyCnt] == MouseKeysRemote.KEY_STATE_UP || (MouseKeysRemote
.getKeyValue(keyCnt + 1) == Constants.DUMMY && mode == EditMode.None))
&& sticky == MouseKeysRemote.UNSTUCK_KEY) // Button
// up
{
rectPaint.setStyle(Paint.Style.FILL_AND_STROKE);
rectPaint.setColor(keyCol);
keyRect.set(
MouseKeysRemote.x1Pos[keyCnt] + (keyWidth / 10),
MouseKeysRemote.y1Pos[keyCnt] + (keyHeight / 10),
MouseKeysRemote.x2Pos[keyCnt] - (keyWidth / 10),
MouseKeysRemote.y2Pos[keyCnt] - (keyHeight / 10));
canvas.drawRoundRect(keyRect, (float) keyWidth / 4,
(float) keyHeight / 4, rectPaint);
rectPaint.setStyle(Paint.Style.STROKE);
// rectPaint.setColor(newCol);
rectPaint.setColor(0xffffffff); // Outer
keyRect.set(
MouseKeysRemote.x1Pos[keyCnt] + (keyWidth / 10),
MouseKeysRemote.y1Pos[keyCnt] + (keyHeight / 10),
MouseKeysRemote.x2Pos[keyCnt] - (keyWidth / 10),
MouseKeysRemote.y2Pos[keyCnt] - (keyHeight / 10));
canvas.drawRoundRect(keyRect, (float) keyWidth / 4,
(float) keyHeight / 4, rectPaint);
} else // Down
{
rectPaint.setStyle(Paint.Style.FILL_AND_STROKE);
rectPaint.setColor(0xff999999); // Key down
keyRect.set(
MouseKeysRemote.x1Pos[keyCnt] + (keyWidth / 10),
MouseKeysRemote.y1Pos[keyCnt] + (keyHeight / 10),
MouseKeysRemote.x2Pos[keyCnt] - (keyWidth / 10)
- (keyWidth / 10) / 2,
MouseKeysRemote.y2Pos[keyCnt] - (keyHeight / 10)
- (keyHeight / 10) / 2);
canvas.drawRoundRect(keyRect, (float) keyWidth / 4,
(float) keyHeight / 4, rectPaint);
}
if (MouseKeysRemote.getKeyValue(keyCnt + 1) == Constants.DUMMY
&& mode == EditMode.None) {
} else {
String keyName;
if (mode == EditMode.Binding) {
keyName = mark
+ Constants.getActionName(MouseKeysRemote
.getKeyValue(keyCnt + 1));
} else {
keyName = mark
+ MouseKeysRemote.mySharedPreferences
.getString(
"nameOfKey"
+ "layout"
+ MouseKeysRemote.keys_layout
+ "key" + (keyCnt + 1),
Constants
.getActionName(MouseKeysRemote
.getKeyValue(keyCnt + 1)));
}
// MouseKeysRemote.debug("nameOfKey" + "layout" +
// MouseKeysRemote.keys_layout + "key" + (keyCnt + 1));
// float keyNameWidth =
// backGround.getPaint().measureText(keyName);
// RemotePC2.debug("tsize: " + tsize);
// canvas.drawText (keyName,
// MouseKeysRemote.x1Pos[keyCnt] + (keyWidth/2) -
// (keyNameWidth/2), MouseKeysRemote.y1Pos[keyCnt]+
// keyHeight/2 + (int)tsize/2, textPaint);
// canvas.drawText (keyName,
// MouseKeysRemote.x1Pos[keyCnt] + (keyWidth/10) + 2,
// MouseKeysRemote.y1Pos[keyCnt]+ keyHeight/2 +
// (int)tsize/2, textPaint);
textPaint.setColor(MouseKeysRemote.textCol);
canvas.drawText(keyName, MouseKeysRemote.x1Pos[keyCnt]
+ (keyWidth / 2), MouseKeysRemote.y1Pos[keyCnt]
+ keyHeight / 2 + (int) tsize / 2, textPaint);
}
keyCnt++;
}
}
}
private void drawMousepad(Canvas canvas) {
// Draw mouse pad
if (MouseKeysRemote.enableMousePad) {
// Mousepad background
mDrawable.getPaint().setColor(MouseKeysRemote.mousepadCol);
mDrawable.setBounds(0,
(measuredHeight - MouseKeysRemote.yOffsetBottom),
measuredWidth, measuredHeight);
mDrawable.draw(canvas);
// RemotePC2.debug("scale: " + scale+ "xdpi: " + xdpi);
// Mousewheel background
if (MouseKeysRemote.enableMouseWheel) {
// wheel.setBounds(measuredWidth -
// (int)(xdpi/2),(RemotePC2.yOffsetTop), measuredWidth ,
// measuredHeight);
wheel.getPaint().setColor(MouseKeysRemote.mousewheelCol);
wheel.setBounds(
measuredWidth - MouseKeysRemote.mouseWheelWidth,
(measuredHeight - MouseKeysRemote.yOffsetBottom),
measuredWidth, measuredHeight);
wheel.draw(canvas);
}
// canvas.save();
}
}
}
| Java |
package com.linuxfunkar.mousekeysremote;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SimpleTextDialog extends Dialog {
private TextView lbl;
private EditText txt;
private String oldText = "";
private OnTextChangedListener listener;
public SimpleTextDialog(Context context) {
super(context);
}
public void show(String title, String label) {
super.show();
setTitle(title);
lbl.setText(label);
txt.setText(oldText);
}
public void show(String title, String label, String oldText) {
this.oldText = oldText;
show(title, label);
}
public void setOnTextChangedListener(OnTextChangedListener listener) {
this.listener = listener;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setCancelable(true);
setContentView(R.layout.simple_text_dialog);
lbl = (TextView) findViewById(R.id.stdialog_label);
txt = (EditText) findViewById(R.id.stdialog_text);
txt.addTextChangedListener(new TextWatcherAdapter() {
@Override
public void afterTextChanged(Editable s) {
Button ok = (Button) findViewById(R.id.stdialog_pbOkay);
ok.setEnabled(!s.toString().equals(oldText));
}
});
Button ok = (Button) findViewById(R.id.stdialog_pbOkay);
ok.setEnabled(false);
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onTextChanged(txt.getText().toString());
dismiss();
}
});
Button cancel = (Button) findViewById(R.id.stdialog_pbCancel);
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancel();
}
});
}
public interface OnTextChangedListener {
void onTextChanged(String text);
}
}
| Java |
package com.linuxfunkar.mousekeysremote;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.LightingColorFilter;
import android.util.AttributeSet;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
public class ButtonView extends TableLayout {
private SharedPreferences prefs;
private int layout = 0;
private Button lastButton;
private OnKeyListener keyListener;
private AdapterView.AdapterContextMenuInfo menuInfo;
public ButtonView(Context context) {
super(context);
}
public ButtonView(Context context, AttributeSet attrs) {
super(context, attrs);
}
private void init(Context context) {
prefs = context.getSharedPreferences("MY_PREFS", Activity.MODE_PRIVATE);
layout = prefs.getInt("layout", 0);
int numberOfKeyRows = prefs.getInt("numberOfKeyRows" + layout, 7);
int numberOfKeyCols = prefs.getInt("numberOfKeyCols" + layout, 7);
createButtons(numberOfKeyRows, numberOfKeyCols);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
if (!isInEditMode())
init(getContext());
}
private void createButtons(int rows, int cols) {
this.setWeightSum(rows);
for (int i = 0; i < rows; i++) {
TableRow row = new TableRow(getContext());
row.setWeightSum(cols);
for (int j = 0; j < cols; j++) {
Button b = new Button(getContext());
int key_num = i * cols + j + 1;
b.setText(Preferences.getInstance(getContext()).getKeyLabel(
key_num));
b.setTag(R.id.button_id, "" + key_num);
b.setTag(R.id.button_sticky, Boolean.valueOf(Preferences
.getInstance(getContext()).isButtonSticky(key_num)));
b.setTag(Integer.valueOf(Preferences.getInstance(getContext())
.getKeyValue(key_num)));
b.setVisibility((Preferences.getInstance(getContext())
.isButtonVisible(key_num)) ? View.VISIBLE
: View.INVISIBLE);
int color = Preferences.getInstance(getContext()).getKeyColor(
key_num);
if (color != -1)
b.getBackground().setColorFilter(
new LightingColorFilter(color,
android.R.color.black));
b.setClickable(false);
b.setLongClickable(true);
b.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
lastButton = (Button) v;
showContextMenuForChild(v);
return true;
}
});
b.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
lastButton = (Button) v;
int key_num = Integer.valueOf(lastButton.getTag(
R.id.button_id).toString());
boolean sticky = Preferences.getInstance(getContext())
.isButtonSticky(key_num);
if (sticky) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (event.getEventTime() - event.getDownTime() < 2000) {
lastButton.setPressed(!lastButton
.isPressed());
if (lastButton.isPressed())
lastButton.setText(Preferences
.getInstance(getContext())
.getKeyLabel(key_num)
.toUpperCase());
else
lastButton.setText(Preferences
.getInstance(getContext())
.getKeyLabel(key_num));
} else {
showContextMenuForChild(v);
return true;
}
}
onTouchEvent(event);
return true;
}
onTouchEvent(event);
return false;
}
});
row.addView(b);
b.setLayoutParams(new TableRow.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 1));
}
addView(row);
row.setLayoutParams(new TableLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 1));
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (lastButton != null) {
int keyValue = Integer.valueOf(lastButton.getTag().toString())
.intValue();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
onKeyListener(lastButton, keyValue, new KeyEvent(
KeyEvent.ACTION_DOWN, keyValue));
return true;
case MotionEvent.ACTION_UP:
onKeyListener(lastButton, keyValue, new KeyEvent(
KeyEvent.ACTION_UP, keyValue));
return true;
}
lastButton = null;
}
return false;
}
public void unhideAll() {
unhideAll(this);
}
private void unhideAll(ViewGroup root) {
int i = 0;
View child = root.getChildAt(i++);
while (child != null) {
if (!(child instanceof ViewGroup)) {
child.setVisibility(View.VISIBLE);
if (child instanceof Button) {
Preferences.getInstance(getContext()).setButtonVisible(
Integer.valueOf(child.getTag(R.id.button_id)
.toString()), true);
}
} else
unhideAll((ViewGroup) child);
child = root.getChildAt(i++);
}
}
@Override
public boolean showContextMenuForChild(View originalView) {
menuInfo = new AdapterView.AdapterContextMenuInfo(originalView, -1, -1);
return super.showContextMenuForChild(originalView);
}
@Override
protected ContextMenuInfo getContextMenuInfo() {
return menuInfo;
}
protected void onKeyListener(View view, int keyValue, KeyEvent event) {
if (keyListener != null)
keyListener.onKey(view, keyValue, event);
}
public void setOnKeyListener(OnKeyListener listener) {
keyListener = listener;
}
}
| Java |
/**
* @file MouseKeysRemote.java
* @brief
*
* Copyright (C)2010-2012 Magnus Uppman <magnus.uppman@gmail.com>
* License: GPLv3+
*/
/**
* Changelog:
* 20101219 v.1.1
* Bugfix. New keys don't have a valid state when changing rows and cols.
* Bugfix. Settings screen isn't scrollable.
* Added key N/C for the possibility of dummy keys.
* 20101229 v.1.2
* Bugfix: Mouse wheel buttons didn't work.
* 2011-01-07 v.1.3
* Added mouseclick on tap
* "Send text" now always send a CR/LF at the end.
* Reduced mousewheel sensitivity
* Fixed back button
* Added mouse wheel on touchpad
* Changed postInvalidate to invalidate in keypad+
* 2011-01-17 v1.4
* Added password
* Changed icon
* 2011-03-??
* Changed name to MouseKeys..
* 2011-03-29 v1.04
* Removed transparency for buttons. Reverted to black background.
*
* Changed name to MouseKeysRemote
* 2011-05-20 v1.01
* DEFAULT_TOUCH_TIME = 200
* Added sticky keys
*
* 2011-07-24 v1.03
* Keyboard is now displayed automatically
* Layouts can be named.
* Increased number of layouts to 16.
*
* Notes:
* Special characters and zoom:
* Must enable Compose and Meta key in KDE.
* System settings -> Keyboard layout -> Advanced
* Free version exactly the same except only one layout.
* DEFAULT_TOUCH_TIME = 100
*
* 2011-08-17 v1.03.1
* Better sensitivity control to avoid jumping mouse.
* 2011-09-02 v1.03.2
* Further improvements to mouse and mousewheel sensitivity control.
* Each layout can now be set to portrait, landscape or auto-rotate.
* Display can be set to always on per layout.
* Wifi is now never disabled when the app is running.
* Bugfix where pinch to zoom was wrongly activated when pressing a button after moving the mouse.
* Haptic feedback is now configurable per layout.
* 2011-09-03 v1.03.3
* Bugfix where tap on touch didn't work on some devices.
* 2011-09-11 v1.03.4
* Added support for install to SD-card.
* Language setting is now sent to the server on resume.
* Added sensor-assisted cursor movement.
* 2011-09-13 v1.03.5
* Reduced mouse sensitivity when a finger is lifted to avoid jumping mouse.
* 2011-09-24 v1.03.6
* Improved mouse accuracy.
* More sensor features.
* 2011-09-27 v1.03.7
* Added North, South etc.. keys which maps to the cursor keys. The key North-W maps for example to both cursor up and cursor left.
* Reduced the size of the hit-rectangle on keys to better match the actual graphics.
* 2011-10-17 v1.03.8
* Added checkbox for enable/disable click on tap.
* 2012-01-10 v1.03.9
* Button colors can be changed as a separate edit mode.
* Background and text colors can be changed (from settings).
* 2012-01-27 v1.03.10
* Fix for password and keyboard bug. Thanks to "Carl" for the bug report!
* Increased text size.
* 2012-02-20 v.104.1
* Added checkbox for enable/disable pinch zoom.
* Increased mouse sensitivity by removing the 25ms deadzone before moving the mouse.
* Minor color changes to the color picker.
* 2012-10-10 2.0 (Banbury)
* Major rewrite.
*/
package com.linuxfunkar.mousekeysremote;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import yuku.ambilwarna.AmbilWarnaDialog;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.LightingColorFilter;
import android.graphics.Paint;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener;
import android.view.Surface;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MouseKeysRemote extends Activity implements
ColorPickerDialog.OnColorChangedListener, OnClickListener,
OnItemClickListener, OnItemSelectedListener, SensorEventListener {
private static final String TAG = "MouseKeysRemote";
private static final boolean debug = false;
// private static final boolean debug=true;
private SensorManager mSensorManager;
private PowerManager mPowerManager;
private WindowManager mWindowManager;
private Display mDisplay;
private WakeLock mWakeLock;
private Sensor mAccelerometer;
private WifiManager mWifiManager;
public static final int KEYPAD_STATE_COMPAT = 0;
public static final int KEYPAD_STATE_TOUCH = 1;
public static final int KEY_STATE_DOWN = 0;
public static final int KEY_STATE_UP = 1;
public static final int KEY_STATE_DOWN_PENDING_UP = 2;
public static final int KEY_STATE_DOWN_PENDING_CONFIRMED_DOWN = 3;
public static final int MOUSE_NO_GESTURE = 0;
public static final int MOUSE_AWAITING_GESTURE = 1;
public static final int MOUSE_ZOOM = 2;
private static final int MENU_QUIT = 1;
private static final int MENU_MORE = 2;
private static final int MENU_LAYOUT = 3;
private static final int MENU_MAIN = 4;
private static final int MENU_EDIT = 5;
private static final int MENU_KP_TOUCH = 6;
private static final int MENU_STICK = 7;
private static final int MENU_UNSTICK = 8;
private static final int MENU_ABOUT = 9;
private static final int MENU_CALIBRATE = 10;
private static final int MENU_COLOR = 11;
private static final int MENU_UNHIDE = 12;
private enum ColorElement {
Text(0), Back(1), MousePad(2), MouseWheel(3), Button(4);
private final int value;
private ColorElement(int value) {
this.value = value;
}
public int toInt() {
return value;
}
}
private static final int SENSORS_MOUSE = 0;
private static final int SENSORS_CURSOR = 1;
private static final int SENSORS_MOUSE_GAME = 2;
private static final int MAX_KEYS = 200;
private static final int DEFAULT_NUM_ROWS = 5;
private static final int DEFAULT_NUM_COLS = 4;
private static final int DEFAULT_MP_SIZE = 50;
private static final int DEFAULT_LAYOUTS = 32;
private static final int DEFAULT_MOUSE_ACC = 2;
private static final float DEFAULT_TEXT_SIZE = 1.2f;
private static final int DEFAULT_LANGUAGE = 1; // English (0 = Custom, for
// more languages update
// lang_array in
// strings.xml)
public static final int STUCK_KEY = 0;
public static final int UNSTUCK_KEY = 1;
public static final int UNSTUCK_KEY_PENDING_RELEASE = 2;
// public static final int NO_EDIT = 0;
// public static final int KEY_BINDING_EDIT = 1;
// public static final int KEY_NAME_EDIT = 2;
// public static final int KEY_COL_EDIT = 3;
public enum EditMode {
None, Binding, Name, Color, Sticky
}
public static final int DEFAULT_SENSOR_DELAY = SensorManager.SENSOR_DELAY_FASTEST;
// public static final int DEFAULT_SENSOR_DELAY =
// SensorManager.SENSOR_DELAY_GAME;
// public static final int DEFAULT_SENSOR_DELAY =
// SensorManager.SENSOR_DELAY_NORMAL;
public static final float DEFAULT_SENSOR_SENSITIVTY = 1f;
private EditMode edit = EditMode.None;
private boolean sticky = false;
public String passwd; // = new String("");
public String host;
static public int lang_pos;
static public int mouse_speed_pos;
static public int layout_mode_pos;
static public boolean calibrate = false;
static public int keys_layout;
static public int key_to_edit;
TextView heading;
EditText ip;
Button send;
Spinner spinner;
Spinner mouse_spinner;
Spinner layout_mode_spinner;
private LinearLayout layout_action;
private ListView choose_action;
private EditText edCmd;
TextView action_text;
LinearLayout layout_select;
ListView choose_layout;
TextView layout_text;
EditText key_name;
float mLastTouchX = -1;
float mLastTouchY = -1;
float mPosX = -1;
float mPosY = -1;
int accX = -1;
float accXFloat = -1;
float xPosLast;
int accY = -1;
float accYFloat = -1;
float yPosLast;
float mouseMovePressure;
float currentMousePressure;
long down;
long up;
long last_up = 0;
int action;
int xPos = -1;
int yPos = -1;
float xPosFloat = -1;
float yPosFloat = -1;
int pointerIndex = -1;
int pointerCnt = 1;
float calibrate_x = 0;
float calibrate_y = 0;
CustomDrawableView keyPadView;
static public int[] keyState; // key current state (up/down)
static public int[] x1Pos;
static public int[] y1Pos;
static public int[] x2Pos;
static public int[] y2Pos;
static public int numberOfKeyRows = DEFAULT_NUM_ROWS;
static public int numberOfKeyCols = DEFAULT_NUM_COLS;
static public int mousepadRelativeSize = DEFAULT_MP_SIZE;
static public float textSize = DEFAULT_TEXT_SIZE;
static public int xOffsetLeft = 0;
static public int xOffsetRight = 0;
static public int yOffsetTop = 0;
static public int yOffsetBottom = 0; // Will be automatically calculated
static int[] key_actions; // Available actions
static int number_of_keycodes; // Number of currently defined key bindings
public String[] EDIT_Names; // Keys
public String[] LAYOUT_Names = { // Layouts
"Layout 1", "Layout 2", "Layout 3", "Layout 4", "Layout 5", "Layout 6",
"Layout 7", "Layout 8", "Layout 9", "Layout 10", "Layout 11",
"Layout 12", "Layout 13", "Layout 14", "Layout 15", "Layout 16" };
public String[] LAYOUT_Names3 = new String[DEFAULT_LAYOUTS];
static public boolean enableMouseWheel;
public static int mouseWheelWidth = 0;
static public boolean enableVibrate;
static public boolean enableMousePad;
static public boolean enableAlwaysOn;
static public boolean enableSensors;
static public boolean enableSensorsX;
static public boolean enableSensorsY;
static public boolean enableClickOnTap;
static public boolean enablePinchZoom;
static public WrapMotionEvent ev;
NotificationManager nm;
Notification vibrateNotification;
static public SharedPreferences mySharedPreferences;
static public String keys_layout_name;
private int sensors_mode;
float oldDist = 1f;
int port;
int old_zoom;
float xPosFirstFloat;
float yPosFirstFloat;
float accXFloatOld;
float accYFloatOld;
float accXFloatDiff;
float accYFloatDiff;
int mouseMovePointer;
float sensorRotateLeft = DEFAULT_SENSOR_SENSITIVTY;
float sensorRotateRight = -DEFAULT_SENSOR_SENSITIVTY;
float sensorRotateForward = DEFAULT_SENSOR_SENSITIVTY;
float sensorRotateBack = -DEFAULT_SENSOR_SENSITIVTY;
// float sensorOffsetZ = 4f;
float sensorOffsetY = 0f;
float sensorHysteris = 0.2f;
public static final int ROTATE_X_NONE = 0;
public static final int ROTATE_X_LEFT = 1;
public static final int ROTATE_X_RIGHT = 2;
public static final int ROTATE_Z_NONE = 0;
public static final int ROTATE_Z_FORWARD = 1;
public static final int ROTATE_Z_BACK = 2;
public static final int ROTATE_Y_NONE = 0;
public static final int ROTATE_Y_FORWARD = 1;
public static final int ROTATE_Y_BACK = 2;
int sensorStateX = ROTATE_X_NONE;
int sensorStateZ = ROTATE_Z_NONE;
int sensorStateY = ROTATE_Y_NONE;
float mSensorX = 0;
float mSensorY = 0;
float mSensorZ = 0;
PowerManager.WakeLock wl;
private WifiLock wifiLock = null;
static public int keyWidth = 0;
static public int keyHeight = 0;
private View mousePanel;
private GestureDetector mouseDetector;
private ScaleGestureDetector zoomDetector;
private View mouseWheelPanel;
private GestureDetector mouseWheelDetector;
private ButtonView buttonView;
public static Paint mPaint;
// private MaskFilter mEmboss;
// private MaskFilter mBlur;
public static int textCol;
public static int backCol;
public static int mousepadCol;
public static int mousewheelCol;
private ServiceConnection pingServiceConnection;
private Security security;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
security = new Security(Preferences.getInstance(this).getPassword());
} catch (Exception ex) {
debug(ex.toString());
}
// Should remember all button states?
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xFFFF0000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
// mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 },
// 0.4f, 6, 3.5f);
// mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);
last_up = 0;
// try {
// Get an instance of the SensorManager
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// Get an instance of the PowerManager
mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
// Create a bright wake lock
wl = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, getClass().getName());
// wl.setReferenceCounted(false);
// Get an instance of the WindowManager
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mDisplay = mWindowManager.getDefaultDisplay();
mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
// Create a Wifi wakelock
wifiLock = mWifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL,
"MyWifiLock");
if (!wifiLock.isHeld()) {
wifiLock.acquire();
}
mAccelerometer = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
vibrateNotification = new Notification();
vibrateNotification.vibrate = new long[] { 0, 40 };
mySharedPreferences = getSharedPreferences("MY_PREFS",
Activity.MODE_PRIVATE);
keyState = new int[MAX_KEYS];
x1Pos = new int[MAX_KEYS];
y1Pos = new int[MAX_KEYS];
x2Pos = new int[MAX_KEYS];
y2Pos = new int[MAX_KEYS];
for (int i = 0; i < MAX_KEYS; i++) {
keyState[i] = KEY_STATE_UP;
}
// Store available actions. Used when editing layouts.
number_of_keycodes = storeActions();
EDIT_Names = new String[number_of_keycodes];
for (int i = 0; i < number_of_keycodes; i++) {
// debug(getActionName(key_actions[i]));
EDIT_Names[i] = Constants.getActionName(key_actions[i]);
}
reload_settings();
debug("onCreate - layout_mode_pos: " + layout_mode_pos);
setDefaultKeys();
layout_action = new LinearLayout(this);
layout_action.setOrientation(LinearLayout.VERTICAL);
action_text = new TextView(this);
action_text.setText("Choose action:");
edCmd = new EditText(this);
edCmd.addTextChangedListener(new TextWatcherAdapter() {
@Override
public void afterTextChanged(Editable s) {
Preferences.getInstance(getApplicationContext())
.setKeyCustomCommand(key_to_edit, s.toString());
}
});
choose_action = new ListView(this);
choose_action.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, EDIT_Names);
choose_action.setClickable(true);
choose_action.setOnItemClickListener(this);
choose_action.setAdapter(adapter);
choose_action.setTextFilterEnabled(true);
layout_action.addView(action_text);
layout_action.addView(edCmd);
layout_action.addView(choose_action);
layout_select = new LinearLayout(this);
layout_select.setOrientation(LinearLayout.VERTICAL);
layout_text = new TextView(this);
layout_text.setText("Choose layout:");
choose_layout = new ListView(this);
choose_layout.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ArrayAdapter<String> adapter_layout = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, LAYOUT_Names);
choose_layout.setClickable(true);
choose_layout.setOnItemClickListener(this);
choose_layout.setAdapter(adapter_layout);
choose_layout.setTextFilterEnabled(true);
layout_select.addView(layout_text);
layout_select.addView(choose_layout);
sendLanguage();
showMainView();
}
private void showMainView() {
setContentView(R.layout.layout_view);
setupGui();
}
@Override
protected void onStart() {
super.onStart();
startPing();
}
private void setupGui() {
mousePanel = (View) findViewById(R.id.mousePanel);
mouseWheelPanel = (View) findViewById(R.id.mouseWheelPanel);
mouseDetector = getMouseDetector();
zoomDetector = getZoomDetector();
mouseWheelDetector = getMouseWheelDetector();
mousePanel.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mouseDetector.onTouchEvent(event)) {
return true;
} else {
return zoomDetector.onTouchEvent(event);
}
}
});
mouseWheelPanel.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return mouseWheelDetector.onTouchEvent(event);
}
});
buttonView = (ButtonView) findViewById(R.id.buttonView);
registerForContextMenu(buttonView);
buttonView
.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.button_edit_menu, menu);
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
if (Preferences
.getInstance(MouseKeysRemote.this)
.isButtonSticky(
Integer.valueOf(
((Button) info.targetView)
.getTag(R.id.button_id)
.toString()).intValue())) {
menu.findItem(R.id.mnuSticky).setChecked(true);
}
}
});
buttonView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Button b = (Button) v;
boolean sticky = Boolean.valueOf(b.getTag(R.id.button_sticky)
.toString());
String cmd = Preferences.getInstance(getApplicationContext())
.getKeyCustomCommand(
Integer.valueOf(b.getTag(R.id.button_id)
.toString()));
switch (event.getAction()) {
case KeyEvent.ACTION_DOWN:
if (cmd.equals("")) {
if (!sticky)
sendUDP(Constants.getActionPress(keyCode));
} else {
sendUDP(cmd);
}
vibrate();
return true;
case KeyEvent.ACTION_UP:
if (cmd.equals("")) {
if (sticky) {
if (b.isPressed())
sendUDP(Constants.getActionPress(keyCode));
else
sendUDP(Constants.getActionRelease(keyCode));
} else
sendUDP(Constants.getActionRelease(keyCode));
}
return true;
}
return false;
}
private void vibrate() {
if (enableVibrate) {
nm.notify(1, vibrateNotification);
}
}
});
}
private void startPing() {
pingServiceConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
};
Intent intent = new Intent(this, PingService.class);
bindService(intent, pingServiceConnection, Context.BIND_AUTO_CREATE);
}
private GestureDetector getMouseDetector() {
return new GestureDetector(
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDoubleTap(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
if (e1.getPointerCount() > 1
|| e2.getPointerCount() > 1)
return false;
if (distanceX != 0) { // Only move if there has been a
// movement
String msg = "XMM" + (int) -distanceX
* (mouse_speed_pos + 1);
sendUDP(msg);
}
if (distanceY != 0) { // Only move if there has been a
// movement
String msg = "YMM" + (int) -distanceY
* (mouse_speed_pos + 1);
sendUDP(msg);
}
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (e.getPointerCount() > 1)
return false;
if (enableClickOnTap) {
String msg = "MLC";
sendUDP(msg);
msg = "MLR";
sendUDP(msg);
if (enableVibrate) {
nm.notify(1, vibrateNotification);
}
return true;
}
return false;
}
});
}
private ScaleGestureDetector getZoomDetector() {
return new ScaleGestureDetector(this,
new SimpleOnScaleGestureListener() {
@Override
public boolean onScale(ScaleGestureDetector detector) {
if (enablePinchZoom && detector.getScaleFactor() != 1) {
int zoom_diff = (int) (detector.getCurrentSpan() - detector
.getPreviousSpan());
String msg = "MPZ" + zoom_diff; // Mouse Pinch
// Zoom.. Positive
// values means zoom
// in and
// negative zoom
// out.
sendUDP(msg);
return true;
}
return false;
}
});
}
private GestureDetector getMouseWheelDetector() {
return new GestureDetector(
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
if (Math.abs(distanceY) > Math.abs(distanceX)) {
int newAccY = (int) (distanceY / 6);
if (newAccY != 0) {
sendUDP("MWS" + newAccY);
} else {// Make sure that something happens even for
// small movements
if (distanceY > 0) {
sendUDP("MWS1");
} else {
sendUDP("MWS-1");
}
}
} else {
return true;
}
return false;
}
});
}
private int storeActions() {
key_actions = new int[200];
key_actions[0] = Constants.CUR_RIGHT;
key_actions[1] = Constants.CUR_LEFT;
key_actions[2] = Constants.CUR_UP;
key_actions[3] = Constants.CUR_DOWN;
key_actions[4] = Constants.MOUSE_RIGHT;
key_actions[5] = Constants.MOUSE_LEFT;
key_actions[6] = Constants.MOUSE_UP;
key_actions[7] = Constants.MOUSE_DOWN;
key_actions[8] = Constants.MOUSE_LCLICK;
key_actions[9] = Constants.MOUSE_RCLICK;
key_actions[10] = Constants.ESC;
key_actions[11] = Constants.CR;
key_actions[12] = Constants.NUM_KP_0;
key_actions[13] = Constants.NUM_KP_1;
key_actions[14] = Constants.NUM_KP_2;
key_actions[15] = Constants.NUM_KP_3;
key_actions[16] = Constants.NUM_KP_4;
key_actions[17] = Constants.NUM_KP_5;
key_actions[18] = Constants.NUM_KP_6;
key_actions[19] = Constants.NUM_KP_7;
key_actions[20] = Constants.NUM_KP_8;
key_actions[21] = Constants.NUM_KP_9;
key_actions[22] = Constants.SPACE;
key_actions[23] = Constants.MOUSE_WUP;
key_actions[24] = Constants.MOUSE_WDOWN;
key_actions[25] = Constants.F1;
key_actions[26] = Constants.F2;
key_actions[27] = Constants.F3;
key_actions[28] = Constants.F4;
key_actions[29] = Constants.F5;
key_actions[30] = Constants.F6;
key_actions[31] = Constants.F7;
key_actions[32] = Constants.F8;
key_actions[33] = Constants.F9;
key_actions[34] = Constants.F10;
key_actions[35] = Constants.F11;
key_actions[36] = Constants.F12;
key_actions[37] = Constants.LCTRL;
key_actions[38] = Constants.DEL;
key_actions[39] = Constants.LSHIFT;
key_actions[40] = Constants.LALT;
key_actions[41] = Constants.INS;
key_actions[42] = Constants.CHRA;
key_actions[43] = Constants.CHRB;
key_actions[44] = Constants.CHRC;
key_actions[45] = Constants.CHRD;
key_actions[46] = Constants.CHRE;
key_actions[47] = Constants.CHRF;
key_actions[48] = Constants.CHRG;
key_actions[49] = Constants.CHRH;
key_actions[50] = Constants.CHRI;
key_actions[51] = Constants.CHRJ;
key_actions[52] = Constants.CHRK;
key_actions[53] = Constants.CHRL;
key_actions[54] = Constants.CHRM;
key_actions[55] = Constants.CHRN;
key_actions[56] = Constants.CHRO;
key_actions[57] = Constants.CHRP;
key_actions[58] = Constants.CHRQ;
key_actions[59] = Constants.CHRR;
key_actions[60] = Constants.CHRS;
key_actions[61] = Constants.CHRT;
key_actions[62] = Constants.CHRU;
key_actions[63] = Constants.CHRV;
key_actions[64] = Constants.CHRW;
key_actions[65] = Constants.CHRX;
key_actions[66] = Constants.CHRY;
key_actions[67] = Constants.CHRZ;
key_actions[68] = Constants.CHR0;
key_actions[69] = Constants.CHR1;
key_actions[70] = Constants.CHR2;
key_actions[71] = Constants.CHR3;
key_actions[72] = Constants.CHR4;
key_actions[73] = Constants.CHR5;
key_actions[74] = Constants.CHR6;
key_actions[75] = Constants.CHR7;
key_actions[76] = Constants.CHR8;
key_actions[77] = Constants.CHR9;
key_actions[78] = Constants.PLUS;
key_actions[79] = Constants.MINUS;
key_actions[80] = Constants.TAB;
key_actions[81] = Constants.PGUP;
key_actions[82] = Constants.PGDOWN;
key_actions[83] = Constants.COMMA;
key_actions[84] = Constants.PERIOD;
key_actions[85] = Constants.END;
key_actions[86] = Constants.HOME;
key_actions[87] = Constants.BACKSPACE;
key_actions[88] = Constants.DUMMY;
key_actions[89] = Constants.SEMI_COLON;
key_actions[90] = Constants.BACKSLASH;
key_actions[91] = Constants.AT;
key_actions[92] = Constants.SLASH;
key_actions[93] = Constants.COLON;
key_actions[94] = Constants.EQUALS;
key_actions[95] = Constants.QUESTION;
key_actions[96] = Constants.ZOOM_IN;
key_actions[97] = Constants.ZOOM_OUT;
key_actions[98] = Constants.ZOOM_RESET;
key_actions[99] = Constants.NORTH;
key_actions[100] = Constants.SOUTH;
key_actions[101] = Constants.WEST;
key_actions[102] = Constants.EAST;
key_actions[103] = Constants.NORTHWEST;
key_actions[104] = Constants.NORTHEAST;
key_actions[105] = Constants.SOUTHWEST;
key_actions[106] = Constants.SOUTHEAST;
return key_actions.length;
}
@Override
protected void onStop() {
debug("onStop");
release_locks();
stopSensors();
super.onStop();
}
private void release_locks() {
if (wl.isHeld()) {
wl.release();
}
if (wifiLock.isHeld()) {
wifiLock.release();
}
}
@Override
protected void onDestroy() {
debug("onDestroy");
release_locks();
stopSensors();
unbindService(pingServiceConnection);
super.onDestroy();
}
@Override
protected void onResume() {
debug("onResume");
super.onResume();
/*
* when the activity is resumed, we acquire a wake-lock so that the
* screen stays on, since the user will likely not be fiddling with the
* screen or buttons.
*/
// mWakeLock.acquire();
set_locks();
sendLanguage();
accXFloatOld = 0;
accYFloatOld = 0;
last_up = 0;
if (enableSensors) {
// Activate sensors
if (sensors_mode == SENSORS_MOUSE_GAME
&& (enableSensorsX || enableSensorsY)) {
sendUDP("MMC"); // Center mouse
}
mSensorManager.registerListener(this, mAccelerometer,
DEFAULT_SENSOR_DELAY);
} else {
stopSensors();
}
}
private void set_locks() {
if (enableAlwaysOn) {
if (!wl.isHeld()) {
wl.acquire();
}
}
if (!wifiLock.isHeld()) {
wifiLock.acquire();
}
}
@Override
protected void onPause() {
debug("onPause");
super.onPause();
/*
* When the activity is paused, we make sure to stop the simulation,
* release our sensor resources and wake locks
*/
stopSensors();
// and release our wake-lock
release_locks();
// mWakeLock.release();
}
void stopSensors() {
mSensorManager.unregisterListener(this);
if (sensors_mode == SENSORS_CURSOR) {
if (sensorStateX == ROTATE_X_LEFT) {
// stop left
sendUDP("KBR" + 37);
} else if (sensorStateX == ROTATE_X_RIGHT) {
// stop right
sendUDP("KBR" + 39);
}
if (sensorStateY == ROTATE_Y_FORWARD) {
// stop forward
sendUDP("KBR" + 38);
} else if (sensorStateY == ROTATE_Y_BACK) {
// stop back
sendUDP("KBR" + 40);
}
} else if (sensors_mode == SENSORS_MOUSE
&& (enableSensorsX || enableSensorsY)) {
sendUDP("MSR");
sendUDP("MSL");
sendUDP("MSU");
sendUDP("MSD");
}
}
@Override
public void onSensorChanged(SensorEvent event) {
// debug(event.toString());
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
return;
/*
* record the accelerometer data, the event's timestamp as well as the
* current time. The latter is needed so we can calculate the "present"
* time during rendering. In this application, we need to take into
* account how the screen is rotated with respect to the sensors (which
* always return data in a coordinate space aligned to with the screen
* in its native orientation).
*/
// debug(event.toString());
/*
* debug("-------"); debug(event.values[0]); debug(event.values[1]);
* debug(event.values[2]); debug("-------");
*/
// mSensorZ = event.values[2];
switch (mDisplay.getOrientation()) {
case Surface.ROTATION_0:
// debug("0");
mSensorX = event.values[0];
mSensorY = -event.values[1];
break;
case Surface.ROTATION_90:
// debug("90");
mSensorX = -event.values[1];
mSensorY = -event.values[0];
break;
case Surface.ROTATION_180:
// debug("180");
mSensorX = -event.values[0];
mSensorY = event.values[1];
break;
case Surface.ROTATION_270:
// debug("270");
mSensorX = event.values[1];
mSensorY = event.values[0];
break;
}
// debug("mSensorX: " + mSensorX + " mSensorY: " + mSensorY +
// " mSensorZ: " + mSensorZ);
if (calibrate == true) {
calibrate_x = mSensorX;
calibrate_y = mSensorY;
} else {
if (sensors_mode == SENSORS_MOUSE_GAME) {
sensorsMoveMouse();
} else {
sensorsMoveCursorOrMouse();
}
}
}
void sensorsMoveMouse() {
// debug("Move mouse");
/*
* Kolla om ändring av X eller Y, om större än 0 flytta musen. Skala
* upp sensorvärdena med faktor 5? Utgångsvärden alltid lika med
* värden för plant läge. Behövs manuell kalibreringsfunktion. Kolla
* flera värden på raken för att få ett stabilt?
*/
accXFloat = -(mSensorX - calibrate_x) * 5;
accYFloat = -(mSensorY - calibrate_y) * 5;
// debug("xPosFirstFloat:" + xPosFirstFloat + " yPosFirstFloat:" +
// yPosFirstFloat);
// debug("accXFloat:" + accXFloat + " accYFloat:" + accYFloat);
// Calculate any change in distance
accXFloatDiff = -(accXFloatOld - accXFloat);
accYFloatDiff = -(accYFloatOld - accYFloat);
// Convert change in distance to int
accX = (int) accXFloatDiff;
accY = (int) accYFloatDiff;
// debug("accX:" + accX + " accY:" + accY);
if (accX != 0 && enableSensorsX) // Only move if there has been a
// movement!
{
// store new distance
accXFloatOld = accXFloat;
// debug("accX: "+ accX);
String msg = "XMM" + accX * (mouse_speed_pos + 1);
// debug("UDP msg: " + msg);
sendUDP(msg);
// store new distance
}
if (accY != 0 && enableSensorsY) // Only move if there has been a
// movement!
{
accYFloatOld = accYFloat;
// debug("accY: "+ accY);
String msg = "YMM" + accY * (mouse_speed_pos + 1);
// debug("UDP msg: " + msg);
sendUDP(msg);
}
}
void sensorsMoveCursorOrMouse() {
if (mSensorX - calibrate_x > (sensorRotateLeft + sensorHysteris)
&& enableSensorsX) {
// debug("Left");
if (sensorStateX == ROTATE_X_NONE) {
// start left
if (sensors_mode == SENSORS_MOUSE) {
sendUDP("MML");
} else {
sendUDP("KBP" + 37);
}
} else if (sensorStateX == ROTATE_X_RIGHT) {
// stop right and start left
if (sensors_mode == SENSORS_MOUSE) {
sendUDP("MSR");
sendUDP("MML");
} else {
sendUDP("KBR" + 39);
sendUDP("KBP" + 37);
}
}
sensorStateX = ROTATE_X_LEFT;
} else if (mSensorX - calibrate_x > sensorRotateLeft
&& mSensorX <= (sensorRotateLeft + sensorHysteris)) {
// debug("ignorning left hysteresis");
} else if (mSensorX - calibrate_x < (sensorRotateRight - sensorHysteris)
&& enableSensorsX) {
// debug("Right");
if (sensorStateX == ROTATE_X_NONE) {
// start right
if (sensors_mode == SENSORS_MOUSE) {
sendUDP("MMR");
} else {
sendUDP("KBP" + 39);
}
} else if (sensorStateX == ROTATE_X_LEFT) {
// stop left and start right
if (sensors_mode == SENSORS_MOUSE) {
sendUDP("MSL");
sendUDP("MMR");
} else {
sendUDP("KBR" + 37);
sendUDP("KBP" + 39);
}
}
sensorStateX = ROTATE_X_RIGHT;
} else if (mSensorX - calibrate_x < sensorRotateRight
&& mSensorX >= (sensorRotateRight - sensorHysteris)) {
// debug("ignorning right hysteresis");
} else if (enableSensorsX) {
// debug("CenterX");
if (sensorStateX == ROTATE_X_LEFT) {
// stop left
// debug("CenterX");
if (sensors_mode == SENSORS_MOUSE) {
sendUDP("MSL");
} else {
sendUDP("KBR" + 37);
}
} else if (sensorStateX == ROTATE_X_RIGHT) {
// stop right
// debug("CenterX");
if (sensors_mode == SENSORS_MOUSE) {
sendUDP("MSR");
} else {
sendUDP("KBR" + 39);
}
}
sensorStateX = ROTATE_X_NONE;
}
if (mSensorY - calibrate_y > sensorOffsetY
+ (sensorRotateForward + sensorHysteris)
&& enableSensorsY) {
// debug("Forward");
if (sensorStateY == ROTATE_Y_NONE) {
// start forward
if (sensors_mode == SENSORS_MOUSE) {
sendUDP("MMU");
} else {
sendUDP("KBP" + 38);
}
} else if (sensorStateY == ROTATE_Y_BACK) {
// stop back and start forward
if (sensors_mode == SENSORS_MOUSE) {
sendUDP("MSD");
sendUDP("MMU");
} else {
sendUDP("KBR" + 40);
sendUDP("KBP" + 38);
}
}
sensorStateY = ROTATE_Y_FORWARD;
} else if (mSensorY - calibrate_y > sensorOffsetY + sensorRotateForward
&& mSensorY <= sensorOffsetY
+ (sensorRotateForward + sensorHysteris)) {
// debug("ignorning forward hysteris");
} else if (mSensorY - calibrate_y < sensorOffsetY
+ (sensorRotateBack - sensorHysteris)
&& enableSensorsY) {
// debug("Back");
if (sensorStateY == ROTATE_Y_NONE) {
// start back
if (sensors_mode == SENSORS_MOUSE) {
sendUDP("MMD");
} else {
sendUDP("KBP" + 40);
}
} else if (sensorStateY == ROTATE_Y_FORWARD) {
// stop forward and start back
if (sensors_mode == SENSORS_MOUSE) {
sendUDP("MSU");
sendUDP("MMD");
} else {
sendUDP("KBR" + 38);
sendUDP("KBP" + 40);
}
}
sensorStateY = ROTATE_Y_BACK;
} else if (mSensorY - calibrate_y < sensorOffsetY + sensorRotateBack
&& mSensorY >= sensorOffsetY
+ (sensorRotateBack - sensorHysteris)) {
// debug("ignorning back hysteris");
} else if (enableSensorsY) {
// debug("CenterY");
if (sensorStateY == ROTATE_Y_FORWARD) {
// stop forward
// debug("CenterY");
if (sensors_mode == SENSORS_MOUSE) {
sendUDP("MSU");
} else {
sendUDP("KBR" + 38);
}
} else if (sensorStateY == ROTATE_Y_BACK) {
// stop back
// debug("CenterY");
if (sensors_mode == SENSORS_MOUSE) {
sendUDP("MSD");
} else {
sendUDP("KBR" + 40);
}
}
sensorStateY = ROTATE_Y_NONE;
}
}
void setDefaultKeys() {
SharedPreferences.Editor editor = mySharedPreferences.edit();
if (!mySharedPreferences.contains("layout" + keys_layout + "key1")) {
// Set default values if layouts are empty
editor.putInt("layout" + keys_layout + "key1", Constants.ESC);
editor.putInt("layout" + keys_layout + "key2", Constants.LCTRL);
editor.putInt("layout" + keys_layout + "key3", Constants.CUR_UP);
editor.putInt("layout" + keys_layout + "key4", Constants.CR);
editor.putInt("layout" + keys_layout + "key5", Constants.SPACE);
editor.putInt("layout" + keys_layout + "key6", Constants.CUR_LEFT);
editor.putInt("layout" + keys_layout + "key7", Constants.DUMMY);
editor.putInt("layout" + keys_layout + "key8", Constants.CUR_RIGHT);
editor.putInt("layout" + keys_layout + "key9", Constants.TAB);
editor.putInt("layout" + keys_layout + "key10", Constants.MOUSE_UP);
editor.putInt("layout" + keys_layout + "key11", Constants.CUR_DOWN);
editor.putInt("layout" + keys_layout + "key12", Constants.PLUS);
editor.putInt("layout" + keys_layout + "key13",
Constants.MOUSE_LEFT);
editor.putInt("layout" + keys_layout + "key14", Constants.DUMMY);
editor.putInt("layout" + keys_layout + "key15",
Constants.MOUSE_RIGHT);
editor.putInt("layout" + keys_layout + "key16", Constants.MINUS);
editor.putInt("layout" + keys_layout + "key17",
Constants.MOUSE_LCLICK);
editor.putInt("layout" + keys_layout + "key18",
Constants.MOUSE_DOWN);
editor.putInt("layout" + keys_layout + "key19",
Constants.MOUSE_RCLICK);
editor.putInt("layout" + keys_layout + "key20", Constants.DUMMY);
editor.commit();
}
}
/** Creates the menu items **/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_MAIN, 0, "Virtual keyboard");
menu.add(0, MENU_KP_TOUCH, 0, "Mouse/Keypad");
menu.add(0, MENU_UNHIDE, 0,
getResources().getString(R.string.unhide_all));
menu.add(0, MENU_LAYOUT, 0, "Select layout");
menu.add(0, MENU_STICK, 0, "Toggle sticky keys");
menu.add(0, MENU_MORE, 0, "Settings");
menu.add(0, MENU_CALIBRATE, 0, "Calibrate sensors");
menu.add(0, MENU_ABOUT, 0, "About");
menu.add(0, MENU_QUIT, 0, "Exit");
return true;
}
/* Handles item selections */
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_MAIN: // Virtual keyboard...
setContentView(R.layout.main);
EditText sendtext = (EditText) findViewById(R.id.keyboard_input);
sendtext.setText("");
sendtext.requestFocusFromTouch();
sendtext.requestFocus();
sendtext.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (count - before > 0) { // Char added
char ch = s.charAt(start + count - 1);
sendUDP("KBP" + (int) ch);
sendUDP("KBR" + (int) ch);
} else if (before - count == 1) {
// Backspace
sendUDP("KBP" + 8);
sendUDP("KBR" + 8);
}
}
});
InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMgr.toggleSoftInput(0, 0);
return true;
case MENU_KP_TOUCH:
sendLanguage();
showMainView();
return true;
case MENU_EDIT:
if (edit == EditMode.None)
edit = EditMode.Binding;
else if (edit == EditMode.Binding)
edit = EditMode.Name;
else if (edit == EditMode.Name)
edit = EditMode.Color;
else if (edit == EditMode.Color)
edit = EditMode.None;
if (sticky)
keyPadView.setMark(EditMode.Sticky);
else
keyPadView.setMark(edit);
showMainView();
return true;
case MENU_ABOUT:
setContentView(R.layout.info);
return true;
case MENU_COLOR:
// showColorPicker(mPaint.getColor());
return true;
case MENU_QUIT:
quit();
return true;
case MENU_CALIBRATE:
debug("calibrate");
calibrate = true;
showMainView();
return true;
case MENU_LAYOUT:
setContentView(layout_select);
for (int i = 0; i < DEFAULT_LAYOUTS; i++) {
LAYOUT_Names3[i] = mySharedPreferences.getString(
"layout_name" + i, "Layout " + (i + 1));
}
ArrayAdapter<String> adapter_layout = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1,
LAYOUT_Names3);
choose_layout.setAdapter(adapter_layout);
return true;
case MENU_MORE:
setContentView(R.layout.settings);
try {
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter_lang = ArrayAdapter
.createFromResource(this, R.array.lang_array,
android.R.layout.simple_spinner_item);
adapter_lang
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter_lang);
spinner.setSelection(lang_pos, true);
spinner.setOnItemSelectedListener(this);
} catch (Exception e) {
debug(e.toString());
}
try {
mouse_spinner = (Spinner) findViewById(R.id.mouse_spinner);
ArrayAdapter<CharSequence> adapter_mouse = ArrayAdapter
.createFromResource(this,
R.array.mouse_speed_array,
android.R.layout.simple_spinner_item);
adapter_mouse
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mouse_spinner.setAdapter(adapter_mouse);
mouse_spinner.setSelection(mouse_speed_pos);
mouse_spinner.setOnItemSelectedListener(this);
} catch (Exception e) {
debug(e.toString());
}
try {
layout_mode_spinner = (Spinner) findViewById(R.id.layout_mode_spinner);
ArrayAdapter<CharSequence> adapter_layout_mode = ArrayAdapter
.createFromResource(this,
R.array.layout_mode_array,
android.R.layout.simple_spinner_item);
adapter_layout_mode
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
layout_mode_spinner.setAdapter(adapter_layout_mode);
layout_mode_spinner.setSelection(layout_mode_pos);
layout_mode_spinner.setOnItemSelectedListener(this);
} catch (Exception e) {
debug(e.toString());
}
TextView lang_text = (TextView) findViewById(R.id.keyboard_lang);
TextView mouse_speed_text = (TextView) findViewById(R.id.mouse_speed);
EditText ed = (EditText) findViewById(R.id.entry_ip);
EditText port_ed = (EditText) findViewById(R.id.entry_port);
EditText mousepadentry = (EditText) findViewById(R.id.mousepadentry);
EditText colsentry = (EditText) findViewById(R.id.entry_kpcols);
EditText rowsentry = (EditText) findViewById(R.id.entry_kprows);
EditText passentry = (EditText) findViewById(R.id.password_entry);
EditText layoutentry = (EditText) findViewById(R.id.layout_entry);
EditText textSizeEntry = (EditText) findViewById(R.id.entry_text_size);
CheckBox mousewheel = (CheckBox) findViewById(R.id.mousewheel);
CheckBox vibrate = (CheckBox) findViewById(R.id.vibrate);
CheckBox mousepad = (CheckBox) findViewById(R.id.mousepad);
CheckBox always_on = (CheckBox) findViewById(R.id.always_on);
CheckBox sensors = (CheckBox) findViewById(R.id.sensors);
CheckBox sensors_x = (CheckBox) findViewById(R.id.sensors_x);
CheckBox sensors_y = (CheckBox) findViewById(R.id.sensors_y);
CheckBox clickontap = (CheckBox) findViewById(R.id.clickontap);
CheckBox pinchzoom = (CheckBox) findViewById(R.id.pinch_zoom);
RadioButton sensors_cursor = (RadioButton) findViewById(R.id.sensors_cursor);
RadioButton sensors_mouse = (RadioButton) findViewById(R.id.sensors_mouse);
RadioButton sensors_mouse_game = (RadioButton) findViewById(R.id.sensors_mouse_game);
// mouse_speed_text.setText("Mouse speed (" +
// mouse_spinner.getItemAtPosition(mouse_speed_pos).toString() +
// ")");
// lang_text.setText("PC keyboard type (" +
// spinner.getItemAtPosition(lang_pos).toString() + ")");
Button text_col = (Button) findViewById(R.id.textcol);
text_col.setBackgroundColor(textCol);
Button back_col = (Button) findViewById(R.id.background_col);
back_col.setBackgroundColor(backCol);
Button mousepad_col = (Button) findViewById(R.id.mousepad_col);
mousepad_col.setBackgroundColor(mousepadCol);
Button mousewheel_col = (Button) findViewById(R.id.mousewheel_col);
mousewheel_col.setBackgroundColor(mousewheelCol);
text_col.setOnClickListener(this);
back_col.setOnClickListener(this);
mousepad_col.setOnClickListener(this);
mousewheel_col.setOnClickListener(this);
ed.setText(host);
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
host = (s.toString()).trim();
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putString("host", host);
editor.commit();
}
});
port_ed.setText("" + port);
port_ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// debug("e3");
// debug(s.toString() + " start: " + start + " before: "
// +
// before + " count: " + count);
try {
int val = Integer.parseInt((s.toString()).trim());
if (val >= 0 & val <= 65535) {
port = val;
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putInt("port", port);
editor.commit();
}
} catch (Exception e) {
debug(e.toString());
}
}
});
passentry.setText(passwd);
passentry.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
passwd = (s.toString()).trim();
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putString("password", passwd);
try {
security = new Security(passwd);
} catch (Exception ex) {
debug(ex.toString());
}
editor.commit();
}
});
mousepadentry.setText("" + mousepadRelativeSize);
mousepadentry.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
try {
int val = Integer.parseInt((s.toString()).trim());
if (val >= 0 & val <= 100) {
mousepadRelativeSize = val;
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putInt("mousepadRelativeSize"
+ keys_layout, mousepadRelativeSize);
editor.commit();
keyPadView.postInvalidate();
}
} catch (Exception e) {
debug(e.toString());
}
}
});
colsentry.setText("" + numberOfKeyCols);
colsentry.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
try {
int val = Integer.parseInt((s.toString()).trim());
if (val >= 0 & val <= 100
& (val * numberOfKeyRows < 200)) {
numberOfKeyCols = val;
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putInt("numberOfKeyCols" + keys_layout,
numberOfKeyCols);
editor.commit();
keyPadView.postInvalidate();
}
} catch (Exception e) {
debug(e.toString());
}
}
});
rowsentry.setText("" + numberOfKeyRows);
rowsentry.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
try {
int val = Integer.parseInt((s.toString()).trim());
if (val >= 0 & val <= 100
& (val * numberOfKeyCols < 200)) {
numberOfKeyRows = val;
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putInt("numberOfKeyRows" + keys_layout,
numberOfKeyRows);
editor.commit();
keyPadView.postInvalidate();
}
} catch (Exception e) {
debug(e.toString());
}
}
});
textSizeEntry.setText("" + textSize);
textSizeEntry.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
try {
float val = Float.parseFloat((s.toString()).trim());
if (val > 0) {
textSize = val;
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putFloat("textSize" + keys_layout,
textSize);
editor.commit();
keyPadView.postInvalidate();
}
} catch (Exception e) {
debug(e.toString());
}
}
});
layoutentry.setText(keys_layout_name);
layoutentry.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
keys_layout_name = (s.toString()).trim();
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putString("layout_name" + keys_layout,
keys_layout_name);
editor.commit();
keyPadView.postInvalidate();
}
});
mousepad.setChecked(enableMousePad);
mousepad.setOnClickListener(this);
mousewheel.setChecked(enableMouseWheel);
mousewheel.setOnClickListener(this);
vibrate.setChecked(enableVibrate);
vibrate.setOnClickListener(this);
always_on.setChecked(enableAlwaysOn);
always_on.setOnClickListener(this);
sensors.setChecked(enableSensors);
sensors.setOnClickListener(this);
sensors_x.setChecked(enableSensorsX);
sensors_x.setOnClickListener(this);
sensors_y.setChecked(enableSensorsY);
sensors_y.setOnClickListener(this);
clickontap.setChecked(enableClickOnTap);
clickontap.setOnClickListener(this);
pinchzoom.setChecked(enablePinchZoom);
pinchzoom.setOnClickListener(this);
// send = (Button)findViewById(R.id.send);
// send.setOnClickListener(this);
if (sensors_mode == SENSORS_MOUSE) {
sensors_mouse.setChecked(true);
} else if (sensors_mode == SENSORS_MOUSE_GAME) {
sensors_mouse_game.setChecked(true);
} else {
sensors_cursor.setChecked(true);
}
sensors_cursor.setOnClickListener(this);
sensors_mouse.setOnClickListener(this);
sensors_mouse_game.setOnClickListener(this);
return true;
case MENU_STICK:
sticky = !sticky;
showMainView();
return true;
case MENU_UNHIDE:
buttonView.unhideAll();
return true;
}
return false;
}
private void sendLanguage() {
String msg = "LNG" + lang_pos;
// debug("UDP msg: " + msg);
sendUDP(msg);
}
void quit() {
this.finish();
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
debug(parent.getItemAtPosition(pos).toString());
debug(parent.toString());
// Toast.makeText(parent.getContext(), "The planet is " +
// parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
if (parent == spinner) {
debug("lang");
lang_pos = pos;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("lang_pos", lang_pos);
editor.commit();
sendLanguage();
} else if (parent == mouse_spinner) {
debug("mouse");
mouse_speed_pos = pos;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("mouse_speed_pos" + keys_layout, mouse_speed_pos);
editor.commit();
} else if (parent == layout_mode_spinner) {
debug("layout_mode");
layout_mode_pos = pos;
debug(pos);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("layout_mode_pos" + keys_layout, layout_mode_pos);
editor.commit();
setOrientation();
}
}
// Events from keyboard
// Implement the OnKeyDown callback
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK: {
debug("back");
sendLanguage();
if (findViewById(R.id.layout_view) == null)
showMainView();
else
quit();
}
}
return false;
}
// Events from views
// Implement the OnItemClickListener callback
public void onItemClick(AdapterView<?> v, View w, int i, long l) {
// do something when the button is clicked
debug("onItemClick: " + v.toString());
debug("i:" + i + " l:" + l);
if (v == choose_action) // Edit key action
{
debug("choose_action");
debug(Constants.getActionName(key_actions[i]));
// SharedPreferences mySharedPreferences =
// getSharedPreferences("MY_PREFS", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("layout" + keys_layout + "key" + key_to_edit,
key_actions[i]);
editor.commit();
sendLanguage();
showMainView();
} else if (v == choose_layout) // Select layout
{
debug("choose_layout");
keys_layout = i;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("layout", i);
editor.commit();
reload_settings();
setDefaultKeys();
sendLanguage();
showMainView();
}
}
private void reload_settings() {
// Global values
host = mySharedPreferences.getString("host", "192.168.10.184");
port = mySharedPreferences.getInt("port", Constants.UDP_PORT);
keys_layout = mySharedPreferences.getInt("layout", 0);
lang_pos = mySharedPreferences.getInt("lang_pos", DEFAULT_LANGUAGE);
passwd = mySharedPreferences.getString("password", "");
// Values unique per layout
keys_layout_name = mySharedPreferences.getString("layout_name"
+ keys_layout, "Layout " + (keys_layout + 1));
mouse_speed_pos = mySharedPreferences.getInt("mouse_speed_pos"
+ keys_layout, DEFAULT_MOUSE_ACC - 1); // List index starts at
// zero, add one when
// using..
numberOfKeyRows = mySharedPreferences.getInt("numberOfKeyRows"
+ keys_layout, DEFAULT_NUM_ROWS);
numberOfKeyCols = mySharedPreferences.getInt("numberOfKeyCols"
+ keys_layout, DEFAULT_NUM_COLS);
mousepadRelativeSize = mySharedPreferences.getInt(
"mousepadRelativeSize" + keys_layout, DEFAULT_MP_SIZE);
enableMouseWheel = mySharedPreferences.getBoolean("enableMouseWheel"
+ keys_layout, true);
enableVibrate = mySharedPreferences.getBoolean("enableVibrate"
+ keys_layout, true);
enableMousePad = mySharedPreferences.getBoolean("enableMousePad"
+ keys_layout, true);
textSize = mySharedPreferences.getFloat("textSize" + keys_layout,
DEFAULT_TEXT_SIZE);
enableAlwaysOn = mySharedPreferences.getBoolean("enableAlwaysOn"
+ keys_layout, false);
enableSensors = mySharedPreferences.getBoolean("enableSensors"
+ keys_layout, false);
enableSensorsX = mySharedPreferences.getBoolean("enableSensorsX"
+ keys_layout, true);
enableSensorsY = mySharedPreferences.getBoolean("enableSensorsY"
+ keys_layout, true);
layout_mode_pos = mySharedPreferences.getInt("layout_mode_pos"
+ keys_layout, 0);
sensors_mode = mySharedPreferences.getInt("sensors_mode" + keys_layout,
SENSORS_MOUSE);
enableClickOnTap = mySharedPreferences.getBoolean("enableClickOnTap"
+ keys_layout, true);
enablePinchZoom = mySharedPreferences.getBoolean("enablePinchZoom"
+ keys_layout, false);
backCol = mySharedPreferences.getInt("background_col" + keys_layout,
0xff000000);
textCol = mySharedPreferences.getInt("text_col" + keys_layout,
0xffffffff);
mousepadCol = mySharedPreferences.getInt("mousepad_col" + keys_layout,
0xff2222ff);
mousewheelCol = mySharedPreferences.getInt("mousewheel_col"
+ keys_layout, 0xff8888ff);
if (enableAlwaysOn) {
if (!wl.isHeld()) {
wl.acquire();
}
} else {
if (wl.isHeld()) {
wl.release();
}
}
if (enableSensors) {
// Activate sensors
mSensorManager.registerListener(this, mAccelerometer,
DEFAULT_SENSOR_DELAY);
if (sensors_mode == SENSORS_MOUSE_GAME
&& (enableSensorsX || enableSensorsY)) {
sendUDP("MMC"); // Center mouse
}
} else {
stopSensors();
}
setOrientation();
}
private void setOrientation() {
if (layout_mode_pos == 0) {
// Auto rotate
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
} else if (layout_mode_pos == 1) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else if (layout_mode_pos == 2) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
// Implement the OnClickListener callback
public void onClick(View v) {
// do something when the button is clicked
debug("onClick:" + v.toString());
CheckBox mousewheel = (CheckBox) findViewById(R.id.mousewheel);
CheckBox vibrate = (CheckBox) findViewById(R.id.vibrate);
CheckBox mousepad = (CheckBox) findViewById(R.id.mousepad);
CheckBox always_on = (CheckBox) findViewById(R.id.always_on);
CheckBox sensors = (CheckBox) findViewById(R.id.sensors);
CheckBox sensors_x = (CheckBox) findViewById(R.id.sensors_x);
CheckBox sensors_y = (CheckBox) findViewById(R.id.sensors_y);
RadioButton sensors_cursor = (RadioButton) findViewById(R.id.sensors_cursor);
RadioButton sensors_mouse = (RadioButton) findViewById(R.id.sensors_mouse);
RadioButton sensors_mouse_game = (RadioButton) findViewById(R.id.sensors_mouse_game);
CheckBox clickontap = (CheckBox) findViewById(R.id.clickontap);
CheckBox pinchzoom = (CheckBox) findViewById(R.id.pinch_zoom);
Button text_col = (Button) findViewById(R.id.textcol);
Button back_col = (Button) findViewById(R.id.background_col);
Button mousepad_col = (Button) findViewById(R.id.mousepad_col);
Button mousewheel_col = (Button) findViewById(R.id.mousewheel_col);
if (v == mousewheel) {
debug("mousewheel changed");
try {
enableMouseWheel = mousewheel.isChecked();
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putBoolean("enableMouseWheel" + keys_layout,
enableMouseWheel);
editor.commit();
keyPadView.postInvalidate();
} catch (Exception e) {
debug(e.toString());
}
} else if (v == vibrate) {
debug("vibrate changed");
try {
enableVibrate = vibrate.isChecked();
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putBoolean("enableVibrate" + keys_layout, enableVibrate);
editor.commit();
keyPadView.postInvalidate();
} catch (Exception e) {
debug(e.toString());
}
} else if (v == mousepad) {
debug("mousepad changed");
try {
enableMousePad = mousepad.isChecked();
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putBoolean("enableMousePad" + keys_layout,
enableMousePad);
editor.commit();
keyPadView.postInvalidate();
} catch (Exception e) {
debug(e.toString());
}
} else if (v == always_on) {
debug("always on changed");
if (enableAlwaysOn) {
if (wl.isHeld()) {
wl.release();
}
} else {
if (!wl.isHeld()) {
wl.acquire();
}
}
try {
enableAlwaysOn = always_on.isChecked();
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putBoolean("enableAlwaysOn" + keys_layout,
enableAlwaysOn);
editor.commit();
} catch (Exception e) {
debug(e.toString());
}
} else if (v == sensors) {
debug("sensors changed");
try {
enableSensors = sensors.isChecked();
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putBoolean("enableSensors" + keys_layout, enableSensors);
editor.commit();
} catch (Exception e) {
debug(e.toString());
}
if (enableSensors) {
// Activate sensors
accXFloatOld = 0;
accYFloatOld = 0;
mSensorManager.registerListener(this, mAccelerometer,
DEFAULT_SENSOR_DELAY);
} else {
stopSensors();
}
} else if (v == sensors_x) {
debug("sensors_x changed");
try {
enableSensorsX = sensors_x.isChecked();
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putBoolean("enableSensorsX" + keys_layout,
enableSensorsX);
editor.commit();
} catch (Exception e) {
debug(e.toString());
}
if (enableSensorsX) {
} else {
sendUDP("MSL");
sendUDP("MSR");
}
} else if (v == sensors_y) {
debug("sensors_y changed");
try {
enableSensorsY = sensors_y.isChecked();
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putBoolean("enableSensorsY" + keys_layout,
enableSensorsY);
editor.commit();
} catch (Exception e) {
debug(e.toString());
}
if (enableSensorsY) {
} else {
sendUDP("MSU");
sendUDP("MSD");
}
} else if (v == sensors_mouse) {
debug("sensors mouse changed");
sensors_mode = SENSORS_MOUSE;
accXFloatOld = 0;
accYFloatOld = 0;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("sensors_mode" + keys_layout, sensors_mode);
editor.commit();
} else if (v == sensors_mouse_game) {
debug("sensors mouse game changed");
sensors_mode = SENSORS_MOUSE_GAME;
accXFloatOld = 0;
accYFloatOld = 0;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("sensors_mode" + keys_layout, sensors_mode);
editor.commit();
sendUDP("MMC"); // Center mouse
} else if (v == sensors_cursor) {
debug("sensors cursor changed");
sendUDP("MSR");
sendUDP("MSL");
sendUDP("MSU");
sendUDP("MSD");
sensors_mode = SENSORS_CURSOR;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("sensors_mode" + keys_layout, sensors_mode);
editor.commit();
} else if (v == clickontap) {
debug("clickontap changed");
try {
enableClickOnTap = clickontap.isChecked();
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putBoolean("enableClickOnTap" + keys_layout,
enableClickOnTap);
editor.commit();
keyPadView.postInvalidate();
} catch (Exception e) {
debug(e.toString());
}
} else if (v == pinchzoom) {
debug("pinchzoom changed");
try {
enablePinchZoom = pinchzoom.isChecked();
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putBoolean("enablePinchZoom" + keys_layout,
enablePinchZoom);
editor.commit();
keyPadView.postInvalidate();
} catch (Exception e) {
debug(e.toString());
}
} else if (v == text_col) {
showColorPicker(mPaint.getColor(), ColorElement.Text);
} else if (v == back_col) {
showColorPicker(mPaint.getColor(), ColorElement.Back);
} else if (v == mousepad_col) {
showColorPicker(mPaint.getColor(), ColorElement.MousePad);
} else if (v == mousewheel_col) {
showColorPicker(mPaint.getColor(), ColorElement.MouseWheel);
} else // catch all, return to menu
{
debug("catch all, return to menu");
}
}
private void showColorPicker(int color, ColorElement elem) {
Bundle b = new Bundle();
b.putInt(ColorPickerDialog.PROP_INITIAL_COLOR, color);
b.putInt(ColorPickerDialog.PROP_PARENT_WIDTH,
keyPadView.getMeasuredWidth());
b.putInt(ColorPickerDialog.PROP_PARENT_HEIGHT,
keyPadView.getMeasuredHeight());
b.putInt(ColorPickerDialog.PROP_COLORELEM, elem.toInt());
ColorPickerDialog cpd = new ColorPickerDialog(this, b);
cpd.setColorChangedListener(this);
cpd.show();
}
private void display_edit_name_layout() {
setContentView(R.layout.edit_key_name);
EditText name = (EditText) findViewById(R.id.keyboard_input);
name.setText(mySharedPreferences.getString("nameOfKey" + "layout"
+ keys_layout + "key" + key_to_edit,
Constants.getActionName(getKeyValue(key_to_edit))));
name.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
String name = (s.toString()).trim();
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("nameOfKey" + "layout" + keys_layout + "key"
+ key_to_edit, name);
editor.commit();
}
});
}
static public int getKeyValue(int key_num) {
int value = mySharedPreferences.getInt("layout" + keys_layout + "key"
+ key_num, Constants.DUMMY);
return value;
}
void sendUDP(String msg_plain) {
try {
String msg = security.encrypt(msg_plain);
try {
DatagramSocket s = new DatagramSocket();
InetAddress local = InetAddress.getByName(host);
int msg_length = msg.length();
byte[] message = msg.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length,
local, port);
s.send(p);
} catch (Exception e) {
debug(e.toString());
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),
getString(R.string.security_context_failed_),
Toast.LENGTH_LONG).show();
debug(ex.toString());
}
}
static void debug(String s) {
if (debug)
Log.d(TAG, s);
}
static void debug(int i) {
if (debug)
debug("" + i);
}
static void debug(float f) {
if (debug)
debug("" + f);
}
public void colorChanged_int(int color, ColorElement elem) {
mPaint.setColor(color);
// int keys_layout = MouseKeysRemote.keys_layout;
if (elem == ColorElement.Button) {
debug("color: " + color + "key: " + key_to_edit);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("KeyColor" + "layout" + keys_layout + "key"
+ key_to_edit, color);
editor.commit();
keyPadView.invalidate();
} else if (elem == ColorElement.Text) {
debug("text color: " + color + " layout: " + keys_layout);
textCol = color;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("text_col" + keys_layout, color);
editor.commit();
keyPadView.postInvalidate();
showMainView();
} else if (elem == ColorElement.Back) {
backCol = color;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("background_col" + keys_layout, color);
editor.commit();
keyPadView.postInvalidate();
showMainView();
} else if (elem == ColorElement.MousePad) {
mousepadCol = color;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("mousepad_col" + keys_layout, color);
editor.commit();
keyPadView.postInvalidate();
showMainView();
} else if (elem == ColorElement.MouseWheel) {
mousewheelCol = color;
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putInt("mousewheel_col" + keys_layout, color);
editor.commit();
keyPadView.postInvalidate();
showMainView();
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
key_to_edit = Integer.valueOf(
info.targetView.getTag(R.id.button_id).toString()).intValue();
switch (item.getItemId()) {
case R.id.mnuCommand:
setContentView(layout_action);
edCmd.setText(Preferences.getInstance(getApplicationContext())
.getKeyCustomCommand(key_to_edit));
return true;
case R.id.mnuLabel:
// display_edit_name_layout();
SimpleTextDialog dlg = new SimpleTextDialog(this);
dlg.setOnTextChangedListener(new SimpleTextDialog.OnTextChangedListener() {
@Override
public void onTextChanged(String text) {
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putString("layout" + keys_layout + "label"
+ key_to_edit, text);
editor.commit();
((Button) info.targetView).setText(text);
}
});
dlg.show(getResources().getString(R.string.edit_label),
getResources().getString(R.string.name),
((Button) info.targetView).getText().toString());
return true;
case R.id.mnuColor:
AmbilWarnaDialog cdlg = new AmbilWarnaDialog(this,
android.R.color.white,
new AmbilWarnaDialog.OnAmbilWarnaListener() {
@Override
public void onOk(AmbilWarnaDialog dialog, int color) {
SharedPreferences.Editor editor = mySharedPreferences
.edit();
editor.putInt("KeyColor" + "layout"
+ keys_layout + "key" + key_to_edit,
color);
editor.commit();
((Button) info.targetView).getBackground()
.setColorFilter(
new LightingColorFilter(color,
android.R.color.white));
}
@Override
public void onCancel(AmbilWarnaDialog dialog) {
}
});
cdlg.show();
return true;
case R.id.mnuSticky:
Preferences.getInstance(this).setButtonSticky(
key_to_edit,
!Preferences.getInstance(this).isButtonSticky(
key_to_edit));
return true;
case R.id.mnuVisible:
Preferences.getInstance(this).setButtonVisible(key_to_edit,
false);
((Button) info.targetView).setVisibility(View.INVISIBLE);
return true;
}
return false;
}
@Override
public void colorChanged(int color, int elem) {
colorChanged_int(color, ColorElement.valueOf("" + elem));
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
| Java |
package com.linuxfunkar.mousekeysremote;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
public class Preferences {
private static Preferences preferences;
private SharedPreferences prefs;
public static Preferences getInstance(Context context) {
if (preferences == null)
preferences = new Preferences(context);
return preferences;
}
private Preferences(Context context) {
prefs = context.getSharedPreferences("MY_PREFS", Activity.MODE_PRIVATE);
}
public boolean isButtonSticky(int key_num) {
return prefs.getBoolean("KeySticky" + "layout" + getLayout() + "key"
+ key_num, false);
}
public void setButtonSticky(int key_num, boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("KeySticky" + "layout" + getLayout() + "key"
+ key_num, value);
editor.commit();
}
public boolean isButtonVisible(int key_num) {
return prefs.getBoolean("KeyVisible" + "layout" + getLayout() + "key"
+ key_num, true);
}
public void setButtonVisible(int key_num, boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("KeyVisible" + "layout" + getLayout() + "key"
+ key_num, value);
editor.commit();
}
public String getHost() {
return prefs.getString("host", "192.168.10.184");
}
public int getPort() {
return prefs.getInt("port", Constants.UDP_PORT);
}
public String getPassword() {
return prefs.getString("password", "");
}
public int getLayout() {
return prefs.getInt("layout", Constants.DUMMY);
}
public int getKeyValue(int key_num) {
int value = prefs.getInt("layout" + getLayout() + "key" + key_num,
Constants.DUMMY);
return value;
}
public String getKeyLabel(int key_num) {
return prefs.getString("layout" + getLayout() + "label" + key_num,
Constants.getActionName(getKeyValue(key_num)));
}
public int getKeyColor(int key_num) {
return prefs.getInt("KeyColor" + "layout" + getLayout() + "key"
+ key_num, -1);
}
public String getKeyCustomCommand(int key_num) {
return prefs.getString("KeyCustom" + "layout" + getLayout() + "key"
+ key_num, "");
}
public void setKeyCustomCommand(int key_num, String value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(
"KeyCustom" + "layout" + getLayout() + "key" + key_num, value);
editor.commit();
}
}
| Java |
package com.linuxfunkar.mousekeysremote;
import android.text.Editable;
import android.text.TextWatcher;
public abstract class TextWatcherAdapter implements TextWatcher {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
}
| Java |
/**
* @file WrapMotionEvent.java
* @brief
*
* Copyright (C)2010-2012 Magnus Uppman <magnus.uppman@gmail.com>
* License: GPLv3+
*/
package com.linuxfunkar.mousekeysremote;
import android.view.MotionEvent;
public class WrapMotionEvent {
protected MotionEvent event;
protected WrapMotionEvent(MotionEvent event)
{
this.event = event;
}
static public WrapMotionEvent wrap(MotionEvent event)
{
try
{
//System.out.println("EclairMotionEvent");
return new EclairMotionEvent(event);
} catch (VerifyError e)
{
//System.out.println("WrapMotionEvent");
return new WrapMotionEvent(event);
}
}
public final long getDownTime() {
return event.getDownTime();
}
public final long getEventTime() {
return event.getEventTime();
}
public int findPointerIndex(int pointerId) {
return 0;
}
public final int getAction() {
return event.getAction();
}
public int getPointerCount() {
return 1;
}
public int getPointerId(int pointerIndex) {
return 0;
}
public final float getX() {
return event.getX();
}
public float getX(int pointerIndex) {
return event.getX();
}
public final float getY() {
return event.getY();
}
public float getY(int pointerIndex) {
return event.getY();
}
public final float getPressure() {
return event.getPressure();
}
public final float getPressure(int pointerIndex) {
return event.getPressure();
}
}
| Java |
package com.linuxfunkar.mousekeysremote;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
public class PingService extends Service {
private final IBinder binder = new PingBinder();
private Handler handler;
private Runnable timer;
private boolean connected = false;
@Override
public void onCreate() {
super.onCreate();
handler = new Handler();
timer = new Runnable() {
@Override
public void run() {
String host = getHost();
int port = getPort();
if (!host.equals("")) {
if (!connected) {
connected = ping(host, port);
if (connected) {
Toast.makeText(
getApplicationContext(),
getString(R.string.connection_established_with)
+ host + ":" + port,
Toast.LENGTH_SHORT).show();
}
} else {
boolean c = ping(host, port);
if (c == false) {
Toast.makeText(
getApplicationContext(),
getString(R.string.connection_lost) + host
+ ":" + port, Toast.LENGTH_LONG)
.show();
}
connected = c;
}
}
handler.postDelayed(timer, 10000);
}
};
handler.postDelayed(timer, 100);
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(timer);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return binder;
}
public class PingBinder extends Binder {
PingService getService() {
return PingService.this;
}
}
private boolean ping(String host, int port) {
try {
Security security = new Security(Preferences.getInstance(this)
.getPassword());
DatagramSocket socket = new DatagramSocket();
socket.connect(new InetSocketAddress(host, port));
byte[] msg = security.encrypt("ping").getBytes("UTF-8");
socket.send(new DatagramPacket(msg, msg.length));
socket.setSoTimeout(5000);
DatagramPacket response = new DatagramPacket(msg, 4);
socket.receive(response);
BufferedReader input = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(response.getData()),
Charset.forName("UTF-8")));
String s = input.readLine();
if (!s.startsWith("pong")) {
Toast.makeText(
getApplicationContext(),
getString(R.string.wrong_response_from_server_at)
+ host + ":" + port, Toast.LENGTH_LONG).show();
}
socket.close();
} catch (Exception ex) {
Toast.makeText(
getApplicationContext(),
getString(R.string.connection_failed_with) + host + ":"
+ port, Toast.LENGTH_LONG).show();
return false;
}
return true;
}
private String getHost() {
SharedPreferences prefs = getApplicationContext().getSharedPreferences(
"MY_PREFS", Activity.MODE_PRIVATE);
return prefs.getString("host", "");
}
private int getPort() {
SharedPreferences prefs = getApplicationContext().getSharedPreferences(
"MY_PREFS", Activity.MODE_PRIVATE);
return prefs.getInt("port", Constants.UDP_PORT);
}
}
| Java |
/** Automatically generated file. DO NOT MODIFY */
package com.linuxfunkar.mousekeysremote;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MyDatabase;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Vector;
/**
*
* @author HUYNHLOC
*/
public class Data implements Serializable {
Vector<Database> _databases;
public Data() {
_databases = new Vector<Database>();
}
public Database getDatabase(String name) {
for (int i = 0; i < _databases.size(); i++) {
if (_databases.elementAt(i).getName().equals(name)) {
return (Database) _databases.elementAt(i);
}
}
return null;
}
public ArrayList getAllNameDatabases(){
ArrayList list = new ArrayList<String>();
for(int i=0;i<_databases.size();i++){
list.add(_databases.elementAt(i).getName());
}
return list;
}
public boolean addDatabase(Database database) {
for (int i = 0; i < _databases.size(); i++) {
if (_databases.elementAt(i).getName().equals(database.getName())) {
return false;
}
}
_databases.add(database);
return true;
}
public boolean deleteDatabase(String namedatabase) {
for (int i = 0; i < _databases.size(); i++) {
if (_databases.elementAt(i).getName().equals(namedatabase)) {
_databases.remove(i);
return true;
}
}
return false;
}
public void show() {
for (int i = 0; i < _databases.size(); i++) {
_databases.elementAt(i).showDatabase();
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MyDatabase;
import java.io.Serializable;
/**
*
* @author HUYNHLOC
*/
public class Command implements Serializable {
public static enum CommandType {
Message, // mot thong bao
Query, // cau truy van
TableData, // du lieu bang
ValueData, // du lieu gia tri
Login,
LoginFail,
LoginSuccess,
ListNameDatabase,
}
private CommandType _cmdType;
private String _UserSender;
private String _Message;
private Table _TableData;
public Command(CommandType cmdtype, String message) {
_cmdType = cmdtype;
_Message = message;
}
public Command(CommandType cmdtype, Table tabledata) {
_cmdType = cmdtype;
_TableData = tabledata;
}
/**
* @return the _cmdType
*/
public CommandType getCmdType() {
return _cmdType;
}
/**
* @param cmdType the _cmdType to set
*/
public void setCmdType(CommandType cmdType) {
this._cmdType = cmdType;
}
/**
* @return the _UserSender
*/
public String getUserSender() {
return _UserSender;
}
/**
* @param UserSender the _UserSender to set
*/
public void setUserSender(String UserSender) {
this._UserSender = UserSender;
}
/**
* @return the Message
*/
public String getMessage() {
return _Message;
}
/**
* @param Message the Message to set
*/
public void setMessage(String Message) {
this._Message = Message;
}
/**
* @return the _TableData
*/
public Table getTableData() {
return _TableData;
}
/**
* @param TableData the _TableData to set
*/
public void setTableData(Table TableData) {
this._TableData = TableData;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MyDatabase;
import java.io.*;
/**
*
* @author HUYNHLOC
*/
public class Server_Data {
//Seriable một đối tượng xuống file
public static void SerialDatabase(String fileName, Data data) throws FileNotFoundException, IOException
{
//Tạo luồng ghi file
FileOutputStream fos = new FileOutputStream(fileName);
//Tạo luồng để seriable đối tượng
ObjectOutputStream oos = new ObjectOutputStream(fos);
//Chuyển tải đối tượng tới tập tin
oos.writeObject(data);
oos.flush();
fos.close();
oos.close();
}
//Deseriable một đối tượng đã được seriable trước đó
public static Data Deseriable(String fileName) throws FileNotFoundException, IOException, ClassNotFoundException
{
Data result = null;
//Tạo luồng đọc file đã được seriable
FileInputStream fis = new FileInputStream(fileName);
//Tạo luồng để deseriable đối tượng
ObjectInputStream ois= new ObjectInputStream(new BufferedInputStream(fis));
//Tiến hành khôi phục đối tượng
result = ((Data)ois.readObject());
ois.close();
fis.close();
return result;
}
}
| Java |
package MyDatabase;
import java.io.Serializable;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Sunlang
*/
public class Column implements Serializable{
String _nameCol;
String _nameRefCol;
Table _tableRef;
int _type;
boolean _boolPrimaryKey;
boolean _boolForeignKey;
public Column() {
this("", "", null, 0, false, false);
}
public Column(String nameCol, String nameRefCol, Table tableRef,
int type, boolean primaryKey, boolean foreignKey)
{
this._nameCol = nameCol.trim().toUpperCase();
if(_nameRefCol != null)
this._nameRefCol = nameRefCol.trim().toUpperCase();
else
this._nameRefCol = nameRefCol;
this._tableRef = tableRef;
this._type = type;
this._boolPrimaryKey = primaryKey;
this._boolForeignKey = foreignKey;
}
public String getNameCol()
{
return _nameCol;
}
public String getNameRefCol()
{
return _nameRefCol;
}
public Table getTableRef()
{
return _tableRef;
}
public int getType()
{
return _type;
}
public boolean isPrimaryKey()
{
return _boolPrimaryKey;
}
public boolean isForeignKey()
{
return _boolForeignKey;
}
}
| Java |
package MyDatabase;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Vector;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Sunlang
*/
public class Database implements Serializable{
private String _name;
Vector<Table> _tables;
public Database(String name)
{
_name = name;
_tables = new Vector<Table>();
}
public ArrayList getAllNameTable(){
ArrayList listname = new ArrayList();
for(int i=0;i<_tables.size();i++){
listname.add(_tables.elementAt(i).getNameTable());
}
return listname;
}
public boolean addTable(Table table)
{
for(int i = 0; i<_tables.size(); i++)
{
if(_tables.elementAt(i).getNameTable().compareTo(table.getNameTable()) == 0)
{
return false;
}
}
_tables.add(table);
return true;
}
public Table getTable(String nameTable)
{
for(int i = 0; i<_tables.size(); i++)
{
if(_tables.elementAt(i).getNameTable().compareTo(nameTable) == 0)
{
return _tables.elementAt(i);
}
}
return null;
}
public void showDatabase()
{
for(int i = 0; i<_tables.size(); i++)
{
_tables.elementAt(i).showTable();
}
}
/**
* @return the _name
*/
public String getName() {
return _name;
}
/**
* @param name the _name to set
*/
public void setName(String name) {
this._name = name;
}
//tich hop 12/6
//lay ten bang theo chi so
//chua kiem tra i nhap vao co trong gioi han hay khong
public Table GetTable(int i)
{
Table result;
result= _tables.get(i);
return result;
}
public int getSizeDatabase()
{
return _tables.size();
}
}
| Java |
package MyDatabase;
import java.io.Serializable;
import java.util.Vector;
/*
* To change this template, choose Tools | Templates and open the template in
* the editor.
*/
/**
*
* @author Sunlang
*/
public class Table implements Serializable {
String _nameTable;
Vector<Column> _columns;
Vector<Vector<Object>> _rows;
public Table(String nameTable) {
this._nameTable = nameTable.trim().toUpperCase();
this._columns = new Vector<Column>();
this._rows = new Vector<Vector<Object>>();
}
public String getNameTable() {
return this._nameTable;
}
public void setNameTable(String nameTable) {
this._nameTable = nameTable;
}
public Vector<Column> getColumns() {
return this._columns;
}
public void setColumns(Vector<Column> columns) {
this._columns = columns;
}
public Vector<Vector<Object>> getRows() {
return this._rows;
}
public void setRows(Vector<Vector<Object>> rows) {
this._rows = rows;
}
public Column getPrimaryKeyCol() {
for (int i = 0; i < this._columns.size(); i++) {
if (this._columns.elementAt(i).isPrimaryKey()) {
return _columns.elementAt(i);
}
}
return null;
}
public Vector<Column> getForeignKeyCols() {
Vector<Column> foreignKeyCols = new Vector<Column>();
for (int i = 0; i < this._columns.size(); i++) {
if (this._columns.elementAt(i).isForeignKey()) {
foreignKeyCols.add(_columns.elementAt(i));
}
}
return foreignKeyCols;
}
public int getIndexColumn(String nameCol) {
for (int i = 0; i < _columns.size(); i++) {
if (_columns.elementAt(i).getNameCol().equals(nameCol)) {
return i;
}
}
return -1;
}
public int getTypeCol(int index) {
return this._columns.elementAt(index).getType();
}
public String getNameCol(int index) {
return this._columns.elementAt(index).getNameCol();
}
public boolean isPrimaryKeyCol(int index) {
return this._columns.elementAt(index).isPrimaryKey();
}
public boolean isForeignKeyCol(int index) {
return this._columns.elementAt(index).isForeignKey();
}
public String getNameRefCol(int index) {
return this._columns.elementAt(index).getNameRefCol();
}
public Table getTableRef(int index) {
return this._columns.elementAt(index).getTableRef();
}
public boolean addColumn(String nameCol, String nameRefCol, Table tableRef,
int type, boolean boolPrimaryKey, boolean boolForeignKey) {
if (boolForeignKey) {
int indexRefCol = tableRef.getIndexColumn(nameRefCol);
if (indexRefCol == -1) {
return false;
}
if (!tableRef.getColumns().elementAt(indexRefCol).isPrimaryKey()) {
return false;
}
}
Column tempCol = new Column(nameCol, nameRefCol, tableRef, type, boolPrimaryKey, boolForeignKey);
this._columns.add(tempCol);
return true;
}
//Trả về Table với các column được chọn, so sánh giá trị column tên colChoose của Object
public Table getTableWithNameCols(Vector<String> nameCols, String colChoose, Object value) {
Table result = new Table("New_Table");
//Nếu chọn tất cả các Column
if (nameCols == null || nameCols.isEmpty()) {
result.setColumns(this._columns);
} else {
for (int i = 0; i < nameCols.size(); i++) {
//Chỉ add các cột nào được chọn thôi
//EXCEPTION:SANG
result.getColumns().add(this._columns.elementAt(
this.getIndexColumn(nameCols.elementAt(i))));
}
}
//Nếu chọn tất cả các dòng
if (value == null) {
for (int i = 0; i < this._rows.size(); i++) {
Vector<Object> tempRow = new Vector<Object>();
for (int j = 0; j < result.getColumns().size(); j++) {
tempRow.add(this._rows.elementAt(i).elementAt(
this.getIndexColumn(result.getColumns().elementAt(j).getNameCol())));
}
result.getRows().add(tempRow);
}
} else {
int indexColChoose = this.getIndexColumn(colChoose);
int typeColChoose = this._columns.elementAt(indexColChoose)._type;
for (int i = 0; i < this._rows.size(); i++) {
if (typeColChoose == 0) {
if (Integer.parseInt(this._rows.elementAt(i).elementAt(indexColChoose).toString())
== Integer.parseInt(value.toString())) {
Vector<Object> tempRow = new Vector<Object>();
for (int j = 0; j < result.getColumns().size(); j++) {
tempRow.add(this._rows.elementAt(i).elementAt(
this.getIndexColumn(result.getColumns().elementAt(j).getNameCol())));
}
result.getRows().add(tempRow);
}
} else {
if (this._rows.elementAt(i).elementAt(indexColChoose).toString().equals(value.toString())) {
Vector<Object> tempRow = new Vector<Object>();
for (int j = 0; j < result.getColumns().size(); j++) {
tempRow.add(this._rows.elementAt(i).elementAt(
this.getIndexColumn(result.getColumns().elementAt(j).getNameCol())));
}
result.getRows().add(tempRow);
}
}
}
}
return result;
}
public boolean deleteAllRow() {
this._rows.clear();
return true;
}
//CHi moi xu ly truong hop a=b
public boolean DeleteWithCondition(String Column, String Condition, String Value) {
int indexColName = this.getIndexColumn(Column.trim());
if (indexColName == -1) {
return false;
}
String strValue = Value.trim().toString();
for (int i = 0; i < this._rows.size(); i++) {
String str = this._rows.elementAt(i).elementAt(indexColName).toString();
if (str.compareTo(strValue) == 0) {
this._rows.removeElementAt(i);
}
}
return true;
}
// Bo ngoac kep tra ra chuoi
public String getStringValid(String str){
String temp = "";
if(str.contains("\"") )
temp = "\"";
if(str.contains("\'"))
temp = "'";
int indexdaunhaybatdau = str.indexOf(temp);
if(indexdaunhaybatdau == -1 || indexdaunhaybatdau > 0)
return "";
int count = str.length();
int indexdaunhayketthuc = str.lastIndexOf(temp);
if(indexdaunhayketthuc != count -1)
return "";
return str.substring(indexdaunhaybatdau+1, indexdaunhayketthuc);
}
public boolean DeleteWithConditionAndOr(String[] column, String[] condition, String[] Value, String DieuKien) {
if (DieuKien.trim().equals("AND")) {
int indexColName1 = this.getIndexColumn(column[0].trim());
if (indexColName1 == -1) {
return false;
}
int indexColName2 = this.getIndexColumn(column[1].trim());
if (indexColName2 == -1) {
return false;
}
//cho nay xu ly kieu du lieu la chuoi thoi
String strValue1 = getStringValid(Value[0]).trim().toString();
String strValue2 = getStringValid(Value[1]).trim().toString();
for (int i = 0; i < this._rows.size(); i++) {
String str1 = this._rows.elementAt(i).elementAt(indexColName1).toString();
String str2 = this._rows.elementAt(i).elementAt(indexColName2).toString();
if ((str1.compareTo(strValue1) == 0)&&(str2.compareTo(strValue2) == 0))
{
this._rows.removeElementAt(i);
}
}
return true;
}
if (DieuKien.trim().equals("OR")) {
if (DeleteWithCondition(column[0], condition[0], Value[0]) && DeleteWithCondition(column[1], condition[1], Value[1])) {
return true;
}
}
return false;
}
//lấy tên hàm tham chiếu
public String GetTableReferent() {
String result = null;
for (int i = 0; i < _columns.size(); i++) {
if (_columns.elementAt(i).getTableRef() != null) {
return _columns.elementAt(i).getTableRef().getNameTable();
}
}
return result;
}
public boolean updateValue(Vector<String> nameColsUpdate, Vector<Object> valuesUpdate,
String namCol, Object value, String nameCol2, Object value2) {
if (nameCol2 == null) {
int indexColName = this.getIndexColumn(namCol);
//Trường hợp nameCol và value là null
if (indexColName == -1) {
//return false;
for (int i = 0; i < this._rows.size(); i++) {
for (int j = 0; j < nameColsUpdate.size(); j++) {
this._rows.elementAt(i).setElementAt(
valuesUpdate.elementAt(j), this.getIndexColumn(nameColsUpdate.elementAt(j)));
}
}
return true;
}
String strValue = value.toString();
for (int i = 0; i < this._rows.size(); i++) {
String str = this._rows.elementAt(i).elementAt(indexColName).toString();
if (str.compareTo(strValue) == 0) {
for (int j = 0; j < nameColsUpdate.size(); j++) {
if (this.getIndexColumn(nameColsUpdate.elementAt(j)) == -1) {
return false;
}
}
for (int j = 0; j < nameColsUpdate.size(); j++) {
this._rows.elementAt(i).setElementAt(
valuesUpdate.elementAt(j), this.getIndexColumn(nameColsUpdate.elementAt(j)));
}
}
}
}
//Trường hợp where ở update có 2 điều kiện (AND_OR)
else
{
int indexColName = this.getIndexColumn(namCol);
int indexColName2 = this.getIndexColumn(nameCol2);
String strValue = value.toString();
String strValue2 = value2.toString();
for (int i = 0; i < this._rows.size(); i++) {
String str = this._rows.elementAt(i).elementAt(indexColName).toString().toUpperCase().trim();
String str2 = this._rows.elementAt(i).elementAt(indexColName2).toString().toUpperCase().trim();
if (str.compareTo(strValue) == 0 && str2.compareTo(strValue2) == 0) {
for (int j = 0; j < nameColsUpdate.size(); j++) {
if (this.getIndexColumn(nameColsUpdate.elementAt(j)) == -1) {
return false;
}
}
for (int j = 0; j < nameColsUpdate.size(); j++) {
this._rows.elementAt(i).setElementAt(
valuesUpdate.elementAt(j), this.getIndexColumn(nameColsUpdate.elementAt(j)));
}
}
}
}
return true;
}
public boolean deleteColumn(String nameCol, Object value) {
int indexColName = this.getIndexColumn(nameCol);
if (indexColName == -1) {
return false;
}
String strValue = value.toString();
for (int i = 0; i < this._rows.size(); i++) {
String str = this._rows.elementAt(i).elementAt(indexColName).toString();
if (str.compareTo(strValue) == 0) {
this._rows.removeElementAt(i);
}
}
return true;
}
public void showTable() {
System.out.println("Ten Bang: " + this._nameTable);
for (int iCol = 0; iCol < this._columns.size(); iCol++) {
System.out.print(this.getNameCol(iCol)
+ "(Type: " + this._columns.elementAt(iCol).getType() + ")" + " ");
}
System.out.println();
System.out.println();
for (int i = 0; i < this._rows.size(); i++) {
for (int j = 0; j < this._columns.size(); j++) {
System.out.print(this._rows.elementAt(i).elementAt(j).toString() + " ");
}
System.out.println();
}
}
public boolean addRow(Vector<Object> row) {
for (int i = 0; i < this._columns.size(); i++) {
//Type của column hiện tại
int typeCurrentCol = this._columns.elementAt(i).getType();
//Nếu column đó là thuộc tính khóa chính
if (this._columns.elementAt(i).isPrimaryKey()) {
//Nếu thuộc tính khóa chính của row là null
if (row.elementAt(i) == null) {
return false;
}
String primaryKeyInput = row.elementAt(i).toString();
for (int j = 0; j < this._rows.size(); j++) {
if (this._rows.elementAt(j).elementAt(i).toString().equals(primaryKeyInput)) {
return false;
}
}
}
//Nếu column đó là thuộc tính khóa ngoại
if (this._columns.elementAt(i).isForeignKey()) {
Column foreignCol = this._columns.elementAt(i);
//tableRef = Table mà thuộc tính khóa ngoại này tham chiếu tới
Table tableRef = foreignCol.getTableRef();
int index = tableRef.getIndexColumn(foreignCol.getNameRefCol());
//Nếu 2 thuộc tính này khác type
if (typeCurrentCol != tableRef.getColumns().elementAt(index).getType()) {
return false;
} else {
String foreignKeyInput = row.elementAt(i).toString().toUpperCase();
for (int j = 0; j < tableRef.getRows().size(); j++) {
//Nếu tồn tại foreignKey này bên bảng mà nó tham chiếu
if (tableRef.getRows().elementAt(j).elementAt(index).toString().toUpperCase().equals(foreignKeyInput)) {
break;
} else {
if (j == tableRef.getRows().size() - 1) {
return false;
}
}
}
}
}
}
_rows.add(row);
return true;
}
public Table joinTable(Table table2, String nameCol1, String nameCol2) {
Table result = new Table("Table_JOIN");
Vector<Column> columnsTable2 = table2.getColumns();
Vector<Vector<Object>> rowsTable2 = table2.getRows();
int indexNameCol1 = getIndexColumn(nameCol1);
int indexNameCol2 = table2.getIndexColumn(nameCol2);
int typeNameCol1 = _columns.elementAt(indexNameCol1).getType();
int typeNameCol2 = columnsTable2.elementAt(indexNameCol2).getType();
if (typeNameCol1 != typeNameCol2) {
return null;
}
for (int i = 0; i < _columns.size(); i++) {
result._columns.add(_columns.elementAt(i));
}
for (int i = 0; i < columnsTable2.size(); i++) {
result._columns.add(columnsTable2.elementAt(i));
}
for (int i = 0; i < _rows.size(); i++) {
String valueNameCol1 = _rows.elementAt(i).elementAt(indexNameCol1).toString();
for (int j = 0; j < rowsTable2.size(); j++) {
String valueNameCol2 = rowsTable2.elementAt(j).elementAt(indexNameCol2).toString();
if (valueNameCol1.compareTo(valueNameCol2) == 0) {
Vector<Object> tempRow = new Vector<Object>();
for (int k = 0; k < _columns.size(); k++) {
tempRow.add(_rows.elementAt(i).elementAt(k));
}
for (int k = 0; k < columnsTable2.size(); k++) {
tempRow.add(rowsTable2.elementAt(j).elementAt(k));
}
result._rows.add(tempRow);
}
}
}
return result;
}
} | Java |
package client;
import java.net.Socket;
import MyDatabase.*;
interface LoginWindowConnectListener{
public void handleConnectSusscess(Socket socket);
}
interface CommandListener{
public void handleReceiveCommand(Command cmd);
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package client;
/**
*
* @author HUYNHLOC
*/
public class TableResult extends javax.swing.JFrame {
/**
* Creates new form TableResult
*/
public TableResult() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
jLabel1.setText("Table result");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(93, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package client;
import javax.swing.table.DefaultTableModel;
/**
*
* @author HUYNHLOC
*/
public class TableValues extends DefaultTableModel{
TableValues(String[] colNames, int i) {
super(colNames, i);
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package client;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import MyDatabase.*;
import java.io.*;
/**
*
* @author HUYNHLOC
*/
public class ClientThread extends Thread {
CommandListener _commandListener;
private Socket _socket;
private ObjectInputStream ois;
private ObjectOutputStream oos;
public ClientThread(Socket socket) {
try {
_socket = socket;
oos = new ObjectOutputStream(new BufferedOutputStream(_socket.getOutputStream()));
oos.flush();
ois = new ObjectInputStream(new BufferedInputStream(_socket.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
// set nguoi lang nghe su kien
public void SetCommandListener(CommandListener cmdlistener) {
_commandListener = cmdlistener;
}
// day su kien nhan 1 command ra ngoai
public void fireReceiveCommandEvent(Command cmd) {
_commandListener.handleReceiveCommand(cmd);
}
synchronized public void SendCommand(Command cmd) {
SendCommandToServer Sender = new SendCommandToServer(cmd);
Sender.start();
}
class SendCommandToServer extends Thread {
private Command _cmdSend;
public SendCommandToServer(Command cmd) {
_cmdSend = cmd;
}
public void run() {
try {
oos.writeObject(_cmdSend);
oos.flush();
} catch (IOException ex) {
//Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex);
}
this.interrupt();
System.gc();
}
}
public void run() {
while (_socket.isConnected()) {
try {
Command cmdrec = (Command) ois.readObject();
fireReceiveCommandEvent(cmdrec);
} catch (Exception ex) {
//ex.printStackTrace();
break;
}
}
Disconnect();
}
public void Disconnect() {
if (_socket != null && _socket.isConnected()) {
try {
ois.close();
oos.close();
_socket.shutdownInput();
_socket.shutdownOutput();
_socket.close();
_socket = null;
} catch (IOException ex) {
//Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package client;
import MyDatabase.Column;
import MyDatabase.Command;
import MyDatabase.Table;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
/**
*
* @author HUYNHLOC
*/
public class MainWindow extends javax.swing.JFrame {
// socket giao tiếp với server(nhan duoc tu loginwindow)
private LoginWindow loginWindow;
private ClientThread _client;
private Socket _socket;
private TableValues model;
/**
* Creates new form MainWindow
*/
public MainWindow() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea_query = new javax.swing.JTextArea();
jButton_query = new javax.swing.JButton();
jComboBox1 = new javax.swing.JComboBox();
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable_main = new javax.swing.JTable();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
jPanel1.setBackground(java.awt.SystemColor.activeCaption);
jTextArea_query.setColumns(20);
jTextArea_query.setRows(5);
jScrollPane2.setViewportView(jTextArea_query);
jButton_query.setText("query");
jButton_query.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_queryActionPerformed(evt);
}
});
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
jLabel1.setText("List Database");
jTable_main.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jTable_main.setName("");
jScrollPane1.setViewportView(jTable_main);
jLabel2.setText("Table Result :");
jLabel3.setText("Type Query: ");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 318, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGap(25, 25, 25)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_query, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 509, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(jButton_query))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
// TODO add your handling code here:
_client = new ClientThread((_socket));
_client.SetCommandListener(new ReceiveCommandListener());
_client.start();
}//GEN-LAST:event_formWindowOpened
private void jButton_queryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_queryActionPerformed
// TODO add your handling code here:
String query = jTextArea_query.getText().trim();
if (query.equals("")) {
JOptionPane.showMessageDialog(MainWindow.this, "nhap cau quey", "Thong bao", 1);
} else {
query += "/" + (String) jComboBox1.getSelectedItem();
Command cmdQuery = new Command(Command.CommandType.Query, query);
try {
_client.SendCommand(cmdQuery);
} catch (Exception e) {
JOptionPane.showMessageDialog(MainWindow.this, "Loi ket noi", "Loi", 1);
}
}
}//GEN-LAST:event_jButton_queryActionPerformed
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
// TODO add your handling code here:
}//GEN-LAST:event_formWindowActivated
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_query;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable_main;
private javax.swing.JTextArea jTextArea_query;
// End of variables declaration//GEN-END:variables
/**
* @param loginWindow the loginWindow to set
*/
public void setLoginWindow(LoginWindow loginWindow) {
this.loginWindow = loginWindow;
loginWindow.SetConnectListener(new LoginConnectSusscessListener());
}
class LoginConnectSusscessListener implements LoginWindowConnectListener {
@Override
public void handleConnectSusscess(Socket socket) {
_socket = socket;
//JOptionPane.showMessageDialog(MainWindow.this, "Da nhan duoc socket " + _socket.getPort(), "thong bao", 1);
loginWindow.dispose();
//_client.start();
}
}
// su ly cac command nhan duoc
class ReceiveCommandListener implements CommandListener {
@Override
public void handleReceiveCommand(Command cmd) {
Command.CommandType cmdType = (Command.CommandType) cmd.getCmdType();
switch (cmdType) {
case Message:
JOptionPane.showMessageDialog(MainWindow.this, cmd.getMessage(), "Thong bao", 1);
break;
// nhan duoc du lieu dang table
case TableData:
Table table = cmd.getTableData();
Vector colums = table.getColumns();
String[] colnames = new String[colums.size()];
for (int i = 0; i < colums.size(); i++) {
colnames[i] = ((Column) colums.elementAt(i)).getNameCol();
}
Vector rows = table.getRows();
model = new TableValues(colnames, 0);
for (int i = 0; i < rows.size(); i++) {
model.addRow((Vector) rows.elementAt(i));
}
try {
// set tablevalues
SwingUtilities.invokeAndWait(SetTableValues);
} catch (InterruptedException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
break;
// nhan gia tri
case ValueData:
break;
// neu nhan duoc danh sach ten cac database
case ListNameDatabase:
jComboBox1.removeAll();
String[] list = cmd.getMessage().split(" ");
for (int i = 0; i < list.length; i++) {
jComboBox1.addItem(list[i]);
}
break;
}
}
}
// set TableValues cho table
Runnable SetTableValues = new Runnable() {
@Override
public void run() {
jTable_main.setModel(model);
}
};
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package client;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import javax.swing.JOptionPane;
/**
*
* @author HUYNHLOC
*/
public class LoginWindow extends javax.swing.JFrame {
// interface sử lý viec ket noi thanh cong hay that bai
LoginWindowConnectListener connectListener;
// socket det noi toi server
Socket socket;
/**
* Creates new form LoginWindow
*/
public LoginWindow() {
initComponents();
}
public void SetConnectListener(LoginWindowConnectListener listener){
connectListener = listener;
}
public void fireConnectSusscessEvent(){
connectListener.handleConnectSusscess(socket);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton_connect = new javax.swing.JButton();
jTextField_port = new javax.swing.JTextField();
jTextField_serverip = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("LoginWindow");
setBackground(new java.awt.Color(0, 153, 255));
setResizable(false);
jPanel1.setBackground(new java.awt.Color(153, 153, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton_connect.setText("Connect");
jButton_connect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_connectActionPerformed(evt);
}
});
jTextField_port.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextField_portKeyTyped(evt);
}
});
jTextField_serverip.setText("localhost");
jLabel2.setText("Port");
jLabel1.setText("SerIP");
jLabel3.setText("Nhập serverIp và Port :");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton_connect)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel3)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField_serverip))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jTextField_port, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(19, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_serverip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(27, 27, 27)
.addComponent(jButton_connect)
.addGap(29, 29, 29))
);
jTextField_port.getAccessibleContext().setAccessibleName("txt_port");
jTextField_serverip.getAccessibleContext().setAccessibleName("txt_serverip");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton_connectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_connectActionPerformed
// TODO add your handling code here:
if(jTextField_serverip.getText().trim().equals("")||jTextField_port.getText().trim().equals("")){
JOptionPane.showMessageDialog(LoginWindow.this, "Thieu thong tin input", "Loi", 1);
}else{
try{
socket = new Socket(jTextField_serverip.getText().trim(),
Integer.parseInt(jTextField_port.getText().trim()));
MainWindow mainWindow = new MainWindow();
mainWindow.setLoginWindow(this);
mainWindow.setLocation(400, 200);
mainWindow.setVisible(true);
//JOptionPane.showMessageDialog(LoginWindow.this, "ket noi thanh cong", "thong bao", 1);
fireConnectSusscessEvent();
}catch(Exception e){
//e.printStackTrace();
JOptionPane.showMessageDialog(LoginWindow.this, "Loi ket noi", "Loi", 1);
}
}
}//GEN-LAST:event_jButton_connectActionPerformed
private void jTextField_portKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField_portKeyTyped
// TODO add your handling code here:
Character c = evt.getKeyChar();
if(c>'9'|| c<'0'){
evt.consume();
}
}//GEN-LAST:event_jTextField_portKeyTyped
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
LoginWindow loginWindow = new LoginWindow();
loginWindow.setLocation(400, 200);
loginWindow.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_connect;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField_port;
private javax.swing.JTextField jTextField_serverip;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package SQLParse;
import MyDatabase.Database;
import MyDatabase.Table;
import MyQuery.Query_PhepToan;
import MyQuery.String_Query;
import java.util.Vector;
/**
*
* @author HUYNHLOC
*/
public class SQLParser {
String Query;
String_Query QueryParser;
String DKNhanDuoc;
String ColumnNhanDuoc;
String ValueNhanDuoc;
String[] DSColumnNhanDuoc;
String[] DSValueNhanDuoc;
String[] DSDieuKienNhanDuoc;
String[] DSColumn;
String[] DSTable;
String[] DSValue;//Them cho truong hop insert update
private Table TableResult; //Ket qua tra ve cho truong hop select
//Thêm vào ngày 11/6-SANG
private int _soDKOWhere;
private String _DKOWhere; // là AND hay là OR
private Database _database;
private int _queryLevels;
public SQLParser() {
QueryParser = new String_Query();
}
public SQLParser(String query, Database database) {
_database = database;
Query = query;
_soDKOWhere = QueryParser.getSoDKOWhere();
_queryLevels = QueryParser.getQueryLevels();
}
public boolean SQLResult() {
switch (QueryParser.GetConmmandQuery()) {
case "SELECT": {
Vector<String> vtColumns = new Vector<>();
DSColumn = QueryParser.getDsColumn();
if (DSColumn != null) {
if (DSColumn.length <= 0) {
TableResult = null;
return false;
}
for (int iCol = 0; iCol < DSColumn.length; iCol++) {
vtColumns.add(DSColumn[iCol]);
}
}
//Danh sách bảng: trường hợp này chỉ dùng khi có kết 2 bảng
//Thông thường thì DSTable chỉ có một bảng
DSTable = QueryParser.getDsTable();
if (DSTable.length <= 0) {
TableResult = null;
return false;
} else {// neu danh sac table truy van khong co trong database thi return false
for (int i = 0; i < DSTable.length; i++) {
if ((_database.getTable(DSTable[i])) == null) {
return false;
}
}
}
if (_soDKOWhere == 0) {
TableResult = _database.getTable(DSTable[0]).getTableWithNameCols(vtColumns, null, null);
if (TableResult == null) {
System.out.println("TableResult = null trong SQLParser.java");
return false;
}
return true;
}
if (_soDKOWhere == 1 && _queryLevels == 1 && !QueryParser.isKetBang()) {
DKNhanDuoc = QueryParser.getDKNhanDuoc();
ColumnNhanDuoc = QueryParser.getColumnNhanDuoc();
ValueNhanDuoc = QueryParser.getValueNhanDuoc();
Query_PhepToan query = new Query_PhepToan(_database.getTable(DSTable[0]),
ColumnNhanDuoc, ValueNhanDuoc);
TableResult = query.ResultCap1(query.LayPhepToan(DKNhanDuoc)).getTableWithNameCols(vtColumns, null, null);
if (TableResult == null) {
System.out.println("TableResult = null trong SQLParser.java");
return false;
}
return true;
}
if (_soDKOWhere == 2 && DSTable.length == 1) {
_DKOWhere = QueryParser.getDkOWhere();
DSColumnNhanDuoc = QueryParser.getDsColumnNhanDuoc();
DSValueNhanDuoc = QueryParser.getDsValueNhanDuoc();
DSDieuKienNhanDuoc = QueryParser.getDsDieuKienNhanDuoc();
Query_PhepToan query = new Query_PhepToan(_database.getTable(DSTable[0]),
DSColumnNhanDuoc[0], DSValueNhanDuoc[0]);
Table tableresult1 = query.ResultCap1(query.LayPhepToan(DSDieuKienNhanDuoc[0]));
Query_PhepToan queryPhepToan2 = new Query_PhepToan(tableresult1, DSColumnNhanDuoc[1], DSValueNhanDuoc[1]);
TableResult = queryPhepToan2.ResultCap1(queryPhepToan2.LayPhepToanCap1(
DSDieuKienNhanDuoc[1])).getTableWithNameCols(vtColumns, null, null);
if (TableResult == null) {
System.out.println("TableResult = null trong SQLParser.java");
return false;
}
return true;
}
if (_soDKOWhere == 1 && _queryLevels == 2) {
Table temp = QueryParser.getTableTempForLongCap();
DKNhanDuoc = QueryParser.getDKNhanDuoc();
Query_PhepToan query = new Query_PhepToan(_database.getTable(DSTable[0]),
temp.getNameCol(0), null);
String nameCol2 = temp.getNameCol(0);
int iPhepToan = query.LayPhepToanCap2(DKNhanDuoc);
Table result = query.ResultCap2(temp, nameCol2, iPhepToan);
TableResult = result.getTableWithNameCols(vtColumns, null, null);
if (TableResult == null) {
System.out.println("TableResult = null trong SQLParser.java");
return false;
}
return true;
}
//Trường hợp kết đơn giản
//select hocsinh.mssv, hocsinh.hoten, lophoc.giaovienchunhiem where hocsinh.ma_lop = lophoc.malop
if (_soDKOWhere == 1 && QueryParser.isKetBang()) {
DKNhanDuoc = QueryParser.getDKNhanDuoc();
ColumnNhanDuoc = QueryParser.getColumnNhanDuoc();
ValueNhanDuoc = QueryParser.getValueNhanDuoc();
//DSTable nhận được thì giữ nguyên
//Danh sách cột thì kèm theo danh sách bảng với thứ tự đó nữa
//Ví dụ câu trên thì DSColumn trả về là hocsinh.mssv + hocsinh.hoten + lophoc.giaovienchunhiem
//ColumnNhanDuoc = hocsinh.ma_lop;
//ValueNhanDuoc = lophoc.malop
//Cần tách một cái là DScolumn = mssv + hoten + giaovienchunhiem
if (DSColumn != null) {
for (int iCol = 0; iCol < DSColumn.length; iCol++) {
DSColumn[iCol] = DSColumn[iCol].split("\\.")[1];
}
vtColumns = new Vector<>();
for (int iCol = 0; iCol < DSColumn.length; iCol++) {
vtColumns.add(DSColumn[iCol]);
}
}
//So sánh để lấy đúng bảng và cột so sánh
//Ví dụ hocsinh thì ma_lop còn lophoc thì malop
String colName1 = "";
String colName2 = "";
if (ColumnNhanDuoc.split("\\.")[0].compareTo(DSTable[0]) == 0) {
colName1 = ColumnNhanDuoc.split("\\.")[1];
colName2 = ValueNhanDuoc.split("\\.")[1];
} else {
colName2 = ColumnNhanDuoc.split("\\.")[1];
colName1 = ValueNhanDuoc.split("\\.")[1];
}
Table result = _database.getTable(DSTable[0]).joinTable(_database.getTable(DSTable[1]),
colName1, colName2);
TableResult = result.getTableWithNameCols(vtColumns, null, null);
return true;
}
}
case "INSERT": {
DSTable = QueryParser.getDsTable();
if (DSTable.length != 1) {
return false;
}
DSValue = QueryParser.getDsValue();
Table table1 = _database.getTable(DSTable[0]);
if (table1 == null) {//kiểm tra database có bảng hay không nếu không có thì return false
return false;
}
Vector<Object> row = new Vector<>();
for (int i = 0; i < DSValue.length; i++) {
row.add(Query_PhepToan.getStringValid(DSValue[i].trim().toUpperCase()));
}
if (!table1.addRow(row)) {
System.out.println("table1 không addRow được trong SQLParser.java");
return false;
}
TableResult = table1;
if (TableResult == null) {
System.out.println("TableResult = null trong SQLParser.java");
return false;
}
return true;
}
case "UPDATE": {
DSColumn = QueryParser.getDsColumn();
Vector<String> rowColumn = new Vector<String>();
for (int i = 0; i < DSColumn.length; i++) {
rowColumn.add(DSColumn[i].trim().toUpperCase());
}
DSValue = QueryParser.getDsValue();
Vector<Object> rowValue = new Vector<Object>();
for (int i = 0; i < DSValue.length; i++) {
rowValue.add(Query_PhepToan.getStringValid(DSValue[i].trim().toUpperCase()));
}
Table temp = QueryParser.getTableUpdate();
boolean kq = false;
if (QueryParser.getSoDKOWhere() == 0) {
kq = temp.updateValue(rowColumn, rowValue, null, null, null, null);
}
if (QueryParser.getSoDKOWhere() == 1) {
kq = temp.updateValue(rowColumn, rowValue, QueryParser.getColumnNhanDuoc(),
Query_PhepToan.getStringValid(QueryParser.getValueNhanDuoc().trim().toUpperCase()), null, null);
}
if (QueryParser.getSoDKOWhere() == 2) {
kq = temp.updateValue(rowColumn, rowValue,
QueryParser.getDsColumnNhanDuoc()[0],
Query_PhepToan.getStringValid(QueryParser.getDsValueNhanDuoc()[0]).trim().toUpperCase(),
QueryParser.getDsColumnNhanDuoc()[1],
Query_PhepToan.getStringValid(QueryParser.getDsValueNhanDuoc()[1]).trim().toUpperCase());
}
TableResult = temp;
if(TableResult == null)
{
System.out.println("TableResult = null trong SQLParser.java");
return false;
}
return kq;
}
//delete from sinhvien where mssv='0912389'
//delete from sinhvien
//delete from sinhvien where mssv='0912389' and ma_lop='Ma_Lop_01'
case "DELETE": {
_soDKOWhere = QueryParser.getSoDKOWhere();
DSTable = QueryParser.getDsTable();
if (DSTable.length != 1) {
return false;
}
Table tabledelete = _database.getTable(DSTable[0]);
if (tabledelete == null)//nếu không có table trong database
{
return false;
}
String tableReferent = LayBangThamChieu(tabledelete);
if (_soDKOWhere == 0) {//nếu không có điều kiện where thì xóa hết
if (tableReferent == null)//không bị tham chiếu từ bảng khác
{
if (tabledelete.deleteAllRow()) {
return true;
}
return false;
} else//nếu bị tham chiếu từ bảng khác thì không xóa
{
return false;
}
}
if (_soDKOWhere == 1) {
//xóa Bảng với điều kiện
DKNhanDuoc = QueryParser.getDKNhanDuoc();
ValueNhanDuoc = Query_PhepToan.getStringValid(QueryParser.getValueNhanDuoc());
ColumnNhanDuoc = QueryParser.getColumnNhanDuoc();
//kiểm tra kết quả trả về của các giá trị có bằng null hay không
if ((DKNhanDuoc == null) && (ValueNhanDuoc == null) && (ColumnNhanDuoc == null)) {
return false;
}
if (tableReferent == null) {
if (tabledelete.DeleteWithCondition(ColumnNhanDuoc, DKNhanDuoc, ValueNhanDuoc)) {
System.out.println("Xoa truong hop 2 thanh cong");
TableResult = tabledelete;
return true;
} else {
System.out.println("Xoa truong hop 2 that bai");
return false;
}
} else {
return false;//co tham chieu tu bang khac
//o day chua xu ly truong hop co tham chieu tu bang khac
//nhung gia tri can xoa khong bi tham chieu
}
}
if (_soDKOWhere == 2) {
//xóa cot voi dieu kien
DSColumnNhanDuoc = QueryParser.getDsColumnNhanDuoc();
DSDieuKienNhanDuoc = QueryParser.getDsDieuKienNhanDuoc();
DSValueNhanDuoc = QueryParser.getDsValueNhanDuoc();
//kết quả trả về quá phạm vi
if ((DSColumnNhanDuoc.length != 2) && (DSDieuKienNhanDuoc.length != 2) && (DSValueNhanDuoc.length != 2)) {
return false;
}
_DKOWhere = QueryParser.getDkOWhere();
//không lấy được loại điều kiện
if (_DKOWhere == null) {
return false;
}
if (tabledelete.DeleteWithConditionAndOr(DSColumnNhanDuoc, DSColumnNhanDuoc, DSValueNhanDuoc, _DKOWhere)) {
TableResult = tabledelete;
return true;
}
return false;
} else {
return false;//co tham chieu tu bang khac
//o day chua xu ly truong hop co tham chieu tu bang khac
//nhung gia tri can xoa khong bi tham chieu
}
}
}
return false;
}
public String LayNoiDung(String str) {
int index = str.indexOf("\"");
if (index == -1) {
return str;
} else {
return str.substring(1, str.length() - 1);
}
}
/**
* @return the TableResult
*/
public Table getTableResult() {
return TableResult;
}
public String GetQueryComment() {
return QueryParser.GetConmmandQuery();
}
//tham so table la table muon tim bang tham chieu
//chi ho tro cho 1 bang tham chieu
private String LayBangThamChieu(Table table) {
String result = null;
int DatabaseSize = _database.getSizeDatabase();
for (int i = 0; i < DatabaseSize; i++)//
{
//lay bang ten bang tham chieu cua bang dang xet
if (_database.GetTable(i).GetTableReferent() != null) {
if (_database.GetTable(i).GetTableReferent().equals(table.getNameTable())) {
return _database.GetTable(i).getNameTable();
}
}
}
return result;
}
//Set cau truy van va database hien tai
//public void setQuery(String query, Database database)
//ham tra ve kieu boolean
public boolean setQuery(String query, Database database) {
Query = query;
_database = database;
QueryParser.SetStrQuery(query);
QueryParser.SetTrDatabase(database);
//kiểm tra có parse được hay không
if (QueryParser.Parse()) {//kiểm tra có truy vấn được hay không
_soDKOWhere = QueryParser.getSoDKOWhere();
_queryLevels = QueryParser.getQueryLevels();
if (SQLResult()) {
return true;
}
}
return false;
}
// lay danh sac table duoc truy van
public String[] getDStable() {
return DSTable;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MyQuery;
/**
*
* @author Sunlang
*/
//Where a = 3 and b >2
//Where a = 3 or b>2
public class WhereParse {
private String _strDieuKienWhere;
private String[] _dsColumnNhanDuoc;
private String[] _dsValueNhanDuoc;
private String[] _dsDieuKienNhanDuoc;
private String AND_OR;
public WhereParse(String strDieuKien)
{
_dsColumnNhanDuoc = new String[2];
_dsDieuKienNhanDuoc = new String[2];
_dsValueNhanDuoc = new String[2];
_strDieuKienWhere = strDieuKien.trim();
if(_strDieuKienWhere.contains("AND")){
AND_OR = "AND";
}
else{
AND_OR = "OR";
}
String[] temp = _strDieuKienWhere.split(AND_OR);
String strDk1 = temp[0].trim();
String strDk2 = temp[1].trim();
_dsColumnNhanDuoc[0] = SeparateStrDieuKien(strDk1)[0];
_dsDieuKienNhanDuoc[0] = SeparateStrDieuKien(strDk1)[1];
_dsValueNhanDuoc[0] = SeparateStrDieuKien(strDk1)[2];
_dsColumnNhanDuoc[1] = SeparateStrDieuKien(strDk2)[0];
_dsDieuKienNhanDuoc[1] = SeparateStrDieuKien(strDk2)[1];
_dsValueNhanDuoc[1] = SeparateStrDieuKien(strDk2)[2];
}
public String[] SeparateStrDieuKien(String strDK)//Trả về cột, phép toán, giá trị
{
//a>b
String[] result = new String[3];
for (int i = 0; i < String_Query._dsDKKiemTra.length; i++) {
if (strDK.contains(String_Query._dsDKKiemTra[i])) {
result[1] = String_Query._dsDKKiemTra[i].trim(); //>
result[0] = strDK.split(result[1])[0].trim();//a
result[2] = strDK.split(result[1])[1].trim(); //b
//break; Vì > và >=
}
}
return result;
}
public String getDK()
{
return AND_OR;
}
public String[] getDSCotNhanDuoc()
{
return _dsColumnNhanDuoc;
}
public String[] getDSValueNhanDuoc()
{
return _dsValueNhanDuoc;
}
public String[] getDSDKNhanDuoc()
{
return _dsDieuKienNhanDuoc;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MyQuery;
import MyDatabase.Column;
import MyDatabase.Table;
import java.util.Vector;
/**
*
* @author Sunlang
*/
public class Query_PhepToan {
Table _table;
String _colName;
Object _valueCol;
String[] PhepToanCap1 = {"=", "!=", "<", "<=", ">", ">="};
String[] PhepToanCap2 = {"IN", "NOT IN", ">ALL", ">=ALL", "<ALL", "<=ALL"};
String[] PhepToan_All = {"=", "!=", "<", "<=", ">", ">=", "IN", "NOT IN", ">ALL", ">=ALL", "<ALL", "<=ALL"};
//int _iPhepToan;
//Result Cấp 1: == : 0, !=: 1 , <: 2, <= 3, > 4, >= 5
//Result Cấp 2: IN: 0, NOT In :1,
//Result Cấp 2: Lớn hơn so với tất cả: 2, Lớn hoặc bằng so với tất cả: 3
//Result Cấp 2: <All: 4, <=All 5
public Query_PhepToan(Table _table, String _colName, Object _valueCol) {
this._table = _table;
this._colName = _colName;
this._valueCol = _valueCol;
}
public int LayPhepToanCap1(String str) {
for (int i = 0; i < PhepToanCap1.length; i++) {
if (PhepToanCap1[i].equals(str)) {
return i;
}
}
return -1;
}
public int LayPhepToanCap2(String str) {
for (int i = 0; i < PhepToanCap1.length; i++) {
if (PhepToanCap2[i].equals(str)) {
return i;
}
}
return -1;
}
public int LayPhepToan(String str) {
for (int i = 0; i < PhepToan_All.length; i++) {
if (PhepToan_All[i].equals(str)) {
return i;
}
}
return -1;
}
public Table ResultCap1(int _iPhepToan) {
Table result = new Table("Table_Result");
int indexCol = _table.getIndexColumn(_colName);
if (indexCol == -1) {
return null;
}
for (int i = 0; i < _table.getColumns().size(); i++) {
result.getColumns().add(_table.getColumns().elementAt(i));
}
int typeCol = _table.getColumns().elementAt(indexCol).getType();
if (typeCol == 0) {
int valueCol = Integer.parseInt(_valueCol.toString());
for (int i = 0; i < _table.getRows().size(); i++) {
boolean boolCheck = false;
int value = Integer.parseInt(
_table.getRows().elementAt(i).elementAt(indexCol).toString());
Vector<Object> tempRow = new Vector<Object>();
switch (_iPhepToan) {
case 0:
if (valueCol == value) {
boolCheck = true;
}
break;
case 1:
if (valueCol != value) {
boolCheck = true;
}
break;
case 2:
if (valueCol > value) {
boolCheck = true;
}
break;
case 3:
if (valueCol >= value) {
boolCheck = true;
}
break;
case 4:
if (valueCol < value) {
boolCheck = true;
}
break;
case 5:
if (valueCol <= value) {
boolCheck = true;
}
break;
}
if (boolCheck) {
for (int j = 0; j < _table.getColumns().size(); j++) {
tempRow.add(_table.getRows().elementAt(i).elementAt(j));
}
result.addRow(tempRow);
}
}
} else {
String valueCol = getStringValid(_valueCol.toString()).toUpperCase().trim();
if (valueCol.equals("")) {
return null;
}
for (int i = 0; i < _table.getRows().size(); i++) {
boolean boolCheck = false;
String value = _table.getRows().elementAt(i).elementAt(indexCol).toString().toUpperCase().trim();
Vector<Object> tempRow = new Vector<Object>();
switch (_iPhepToan) {
case 0:
if (valueCol.compareTo(value) == 0) {
boolCheck = true;
}
break;
case 1:
if (valueCol.compareTo(value) != 0) {
boolCheck = true;
}
break;
case 2:
if (valueCol.compareTo(value) > 0) {
boolCheck = true;
}
break;
case 3:
if (valueCol.compareTo(value) >= 0) {
boolCheck = true;
}
break;
case 4:
if (valueCol.compareTo(value) < 0) {
boolCheck = true;
}
break;
case 5:
if (valueCol.compareTo(value) <= 0) {
boolCheck = true;
}
break;
}
if (boolCheck) {
for (int j = 0; j < _table.getColumns().size(); j++) {
tempRow.add(_table.getRows().elementAt(i).elementAt(j));
}
result.addRow(tempRow);
}
}
}
return result;
}
// Bo ngoac kep tra ra chuoi
public static String getStringValid(String str) {
String temp = "";
if (str.contains("\"")) {
temp = "\"";
}
if (str.contains("\'")) {
temp = "'";
}
int indexdaunhaybatdau = str.indexOf(temp);
if (indexdaunhaybatdau == -1 || indexdaunhaybatdau > 0) {
return str;
}
int count = str.length();
int indexdaunhayketthuc = str.lastIndexOf(temp);
if (indexdaunhayketthuc != count - 1) {
return str;
}
return str.substring(indexdaunhaybatdau + 1, indexdaunhayketthuc);
}
//Lồng cấp 2
//Select * from SINHVIEN where MSSV IN select Ma_so_sv from SV_CNTT
//_table là SINHVIEN, _nameCol là MSSV
//table2 là SV_CNTT, nameCol2 là Ma_so_sv
//Ở đây ko sử dụng _valueCol;
public Table ResultCap2(Table table2, String nameCol2, int _iPhepToan) {
Table result = new Table("Result_Table");
Vector<Column> columnsTable1 = _table.getColumns();
Vector<Column> columnsTable2 = table2.getColumns();
Vector<Vector<Object>> rowsTable1 = _table.getRows();
Vector<Vector<Object>> rowsTable2 = table2.getRows();
int indexNameCol1 = _table.getIndexColumn(_colName);
int indexNameCol2 = table2.getIndexColumn(nameCol2);
int typeNameCol1 = columnsTable1.elementAt(indexNameCol1).getType();
int typeNameCol2 = columnsTable2.elementAt(indexNameCol2).getType();
if (typeNameCol1 != typeNameCol2) {
return null;
}
if (indexNameCol1 == -1 || indexNameCol2 == -1) {
return null;
}
for (int i = 0; i < columnsTable1.size(); i++) {
result.getColumns().add(columnsTable1.elementAt(i));
}
if (_iPhepToan == 0) {
for (int i = 0; i < rowsTable1.size(); i++) {
String valueCol1 = rowsTable1.elementAt(i).elementAt(indexNameCol1).toString();
for (int j = 0; j < rowsTable2.size(); j++) {
String valueCol2 = rowsTable2.elementAt(j).elementAt(indexNameCol2).toString();
if (valueCol1.compareTo(valueCol2) == 0) {
Vector<Object> tempRow = new Vector<Object>();
for (int k = 0; k < columnsTable1.size(); k++) {
tempRow.add(rowsTable1.elementAt(i).elementAt(k));
}
result.addRow(tempRow);
break;
}
}
}
return result;
} else {
if (_iPhepToan == 1) {
boolean boolCheck = true;
for (int i = 0; i < rowsTable1.size(); i++) {
String valueCol1 = rowsTable1.elementAt(i).elementAt(indexNameCol1).toString();
for (int j = 0; j < rowsTable2.size(); j++) {
String valueCol2 = rowsTable2.elementAt(j).elementAt(indexNameCol2).toString();
if (valueCol1.compareTo(valueCol2) == 0) {
boolCheck = false;
break;
}
}
if (boolCheck) {
Vector<Object> tempRow = new Vector<Object>();
for (int j = 0; j < columnsTable1.size(); j++) {
tempRow.add(rowsTable1.elementAt(i).elementAt(j));
}
result.addRow(tempRow);
}
}
} else {
if (typeNameCol1 == 0) {
boolean boolCheck = true;
for (int i = 0; i < columnsTable1.size(); i++) {
int valueCol1 = Integer.parseInt(
rowsTable1.elementAt(i).elementAt(indexNameCol1).toString());
Vector<Object> tempRow = new Vector<Object>();
for (int j = 0; j < columnsTable2.size(); j++) {
int valueCol2 = Integer.parseInt(
rowsTable2.elementAt(j).elementAt(indexNameCol2).toString());
switch (_iPhepToan) {
//Trường hợp thứ 2
case 2:
if (valueCol1 <= valueCol2) {
boolCheck = false;
}
break;
case 3:
if (valueCol1 < valueCol2) {
boolCheck = false;
}
break;
case 4:
if (valueCol1 >= valueCol2) {
boolCheck = false;
}
break;
case 5:
if (valueCol1 > valueCol2) {
boolCheck = false;
}
break;
}
}
if (boolCheck) {
for (int j = 0; j < _table.getColumns().size(); j++) {
tempRow.add(_table.getRows().elementAt(i).elementAt(j));
}
result.addRow(tempRow);
}
}
} else {
boolean boolCheck = true;
for (int i = 0; i < columnsTable1.size(); i++) {
String valueCol1 = rowsTable1.elementAt(i).elementAt(indexNameCol1).toString();
Vector<Object> tempRow = new Vector<Object>();
for (int j = 0; j < columnsTable2.size(); j++) {
String valueCol2 = rowsTable2.elementAt(j).elementAt(indexNameCol2).toString();
switch (_iPhepToan) {
case 2:
if (valueCol1.compareTo(valueCol2) <= 0) {
boolCheck = false;
}
break;
case 3:
if (valueCol1.compareTo(valueCol2) < 0) {
boolCheck = false;
}
break;
case 4:
if (valueCol1.compareTo(valueCol2) >= 0) {
boolCheck = false;
}
break;
case 5:
if (valueCol1.compareTo(valueCol2) > 0) {
boolCheck = false;
}
break;
}
}
if (boolCheck) {
for (int j = 0; j < _table.getColumns().size(); j++) {
tempRow.add(_table.getRows().elementAt(i).elementAt(j));
}
result.addRow(tempRow);
}
}
}
}
return result;
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MyQuery;
import MyDatabase.Database;
import MyDatabase.Table;
import java.util.Vector;
/**
*
* @author Sunlang
*/
//Trường hợp
//SELECT MSSV FROM SINHVIEN WHERE MSSV (In, Not In, >All, >=All, <All, <=All)
//(SELECT Ma_so FROM table2 WHERE Colum =, > .... value)<--
//CHỈ CẦN TRẢ VỀ TÊN BẢNG VÀ TÊN CỘT RỒI SỦ DỤNG String_PhepToan.ResultCap2 o ben ngoai
public class WhereParse_HaveSelect {
private Database _database;
private String _strDKWhereHaveSelect;
private String _strKhongCoWhereThuNhat;
private String _columnNameOWhere;
private Table _tableReturnHaveColumnName;
public WhereParse_HaveSelect(String strDKWhereHaveSelect, Database database) {
_database = database;
_strDKWhereHaveSelect = strDKWhereHaveSelect.trim().toUpperCase();
//TableReturnHaveColumnFromSelect();
}
public void ExecuteTableReturnHaveColumnFromSelect() {
boolean isWhereThu2 = true;
int indexSelect = _strDKWhereHaveSelect.indexOf("SELECT");
_strKhongCoWhereThuNhat = _strDKWhereHaveSelect.substring(
indexSelect, _strDKWhereHaveSelect.length()-1).trim();//-1 bỏ dấu )
indexSelect = 0;
int indexFrom = _strKhongCoWhereThuNhat.indexOf("FROM");
int indexWhere = _strKhongCoWhereThuNhat.indexOf("WHERE");
if (indexWhere == -1) {
isWhereThu2 = false;
indexWhere = _strKhongCoWhereThuNhat.length();
}
_columnNameOWhere = _strKhongCoWhereThuNhat.substring(indexSelect + 6, indexFrom).trim();
_tableReturnHaveColumnName = new Table("Table_" + _columnNameOWhere);
String nameTableSauWhere = _strKhongCoWhereThuNhat.substring(indexFrom + 4, indexWhere).trim();
Vector<String> nameCols = new Vector<>();
nameCols.add(_columnNameOWhere);
if (!isWhereThu2) {
_tableReturnHaveColumnName = _database.getTable(nameTableSauWhere).getTableWithNameCols(nameCols, null, null);
} else {
String strDieuKien = _strKhongCoWhereThuNhat.substring(
indexWhere + 5, _strKhongCoWhereThuNhat.length()).trim();
String dieukien = null;
String cot = null;
String giatri = null;
for (int i = 0; i < String_Query._dsDKKiemTra.length; i++) {
if (strDieuKien.contains(String_Query._dsDKKiemTra[i])) {
dieukien = String_Query._dsDKKiemTra[i];
cot = strDieuKien.split(dieukien)[0].trim();
giatri = strDieuKien.split(dieukien)[1].trim();
//break; Vì > và >=
}
}
Query_PhepToan query1 = new Query_PhepToan(
_database.getTable(nameTableSauWhere), cot, (Object) giatri);
_tableReturnHaveColumnName = query1.ResultCap1(query1.LayPhepToan(dieukien));
}
}
public Table getTable() {
return _tableReturnHaveColumnName;
}
public String getNameCol() {
return _columnNameOWhere;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MyQuery;
import MyDatabase.Database;
import MyDatabase.Table;
/**
*
* @author Sunlang
*/
public class String_Query {
String _strQuery;
String _commandQuery;
int _queryLevels;
static String[] _dsDKKiemTra = {"=", "!=", "<", "<=", ">", ">=", " IN ", "NOT IN", ">ALL", ">=ALL", "<ALL", "<=ALL"};
static String[] _dsDKKiemTra2 = {"=", "!=", "<", "<=", ">"};//thêm vô cho xử lý trường hợp delete tránh bị lỗi
//nếu cột hay tên có kí từ in thì sẽ bị lỗi
private String _DKNhanDuoc;
private String _ColumnNhanDuoc;
private String _valueNhanDuoc;
private String[] _dsColumnNhanDuoc;
private String[] _dsValueNhanDuoc;
private String[] _dsDieuKienNhanDuoc;
private String _dkOWhere;
private String[] _dsColumn;
private String[] _dsTable;
//luan danh sach value dung cho ham insert update
private String[] _dsValue;
//Bảng chỉ trả về cho trường hợp update
private Table _tableUpdate;
//Thêm vào ngày 11/6 - Sang
private int _soDKOWhere; //Nếu _dkOWhwere != null (= AND_OR) thì soDKOWhere = 2
//Nếu _dkOWhere == null, tức là chỉ có 1 điều kiện thì soDKWhere bằng 1;
//Mếu không có _dkOWhere thì _soDKOwhere = 0;
private Database _database;
private Table _tempTableForLongCap;
private boolean _isKetBang = false;//Trường hợp kết bảng hay không, chỉ sử dụng 1 lần ở select
public String_Query() {
_strQuery = "";
}
//Neu xu ly co loi trong xulylenh()
public boolean Parse() {
//Chuẩn hóa chuỗi và xem chuỗi query thuộc loại nào
_strQuery = _strQuery.toUpperCase().trim();
if (_strQuery.startsWith("SELECT ")) {
_commandQuery = "SELECT";
} else if (_strQuery.startsWith("INSERT ")) {
_commandQuery = "INSERT";
} else if (_strQuery.startsWith("UPDATE ")) {
_commandQuery = "UPDATE";
} else if (_strQuery.startsWith("DELETE ")) {
_commandQuery = "DELETE";
} else {
System.out.println("----------------LOI----------------");
return false;
}
if (XuLyLenh()) {
return true;
}
return false;
}
// set strQuery
public void SetStrQuery(String str) {
_strQuery = str;
}
public void SetTrDatabase(Database database) {
_database = database;
}
public String GetConmmandQuery() {
return _commandQuery;
}
public boolean CheckQuery() {
if (_queryLevels < 1) {
return false;
}
if ((_commandQuery.compareTo("SELECT") == 0 && _queryLevels > 2)
|| (_commandQuery.compareTo("UPDATE") == 0 && _queryLevels > 1)
|| (_commandQuery.compareTo("DELETE") == 0 && _queryLevels > 1)) {
return false;
}
return true;
}
private int CountString(String subStr, String str) {
int count = 0;
int index = 0;
while (true) {
index = str.indexOf(subStr, index);
if (index != -1) {
count++;
index += subStr.length();
} else {
break;
}
}
return count;
}
public boolean XuLyLenh() {
switch (_commandQuery) {
case "SELECT":
if (!XuLyLenhSELECT()) {
return false;
}
break;
case "INSERT":
if (!XuLyLenhINSERT()) {
return false;
}
break;
case "UPDATE":
if (!XuLyLenhUPDATE()) {
return false;
}
break;
case "DELETE":
if (!XuLyDELETE()) {
return false;
}
break;
}
return true;
}
//Sử lý trường hợp là lệnh SELECT
private boolean XuLyLenhSELECT() {
boolean isDKWhere = true;
_queryLevels = CountString("SELECT", _strQuery);
int indexSelect = _strQuery.indexOf("SELECT");
int indexFrom = _strQuery.indexOf("FROM");
if (indexFrom == -1) {
return false;
}
int indexWhere = _strQuery.indexOf("WHERE");
if (indexWhere == -1) {
_soDKOWhere = 0;
isDKWhere = false;
indexWhere = _strQuery.length();
}
//Sang thêm trường hợp cho select *
if (_strQuery.contains("*")) {
_dsColumn = null;
} else {
_dsColumn = _strQuery.substring(indexSelect + 6, indexFrom).trim().split(",");
System.out.print("Danh sach cot duoc chon: ");
for (int i = 0; i < _dsColumn.length; i++) {
_dsColumn[i] = _dsColumn[i].trim();
System.out.print(_dsColumn[i] + " ");
}
}
_dsTable = _strQuery.substring(indexFrom + 4, indexWhere).trim().split(",");
System.out.println("Cac chi so SELECT, FROM, WHERE: "
+ indexSelect + " " + indexFrom + " " + indexWhere);
System.out.println();
System.out.print("Danh sach bang duoc chon: ");
for (int i = 0; i < _dsTable.length; i++) {
_dsTable[i] = _dsTable[i].trim();
System.out.print(_dsTable[i] + " ");
}
System.out.println();
if (!isDKWhere) {
setDKNhanDuoc(null);
setDsColumnNhanDuoc(null);
setDsDieuKienNhanDuoc(null);
return true;
}
String strDieuKien = _strQuery.substring(indexWhere + 5).trim();
System.out.println("Chuoi dieu kien: " + strDieuKien);
//Trường hợp lồng đơn giản
WhereParse_HaveSelect parseSelect = null;
if (_queryLevels == 2) {
//select mssv, hoten from sinhvien where mssv in (select mssv from sinhvien)
parseSelect = new WhereParse_HaveSelect(strDieuKien, _database);
parseSelect.ExecuteTableReturnHaveColumnFromSelect();
_tempTableForLongCap = parseSelect.getTable();
//Đổi lại strDieuKien chỉ từ where tới "("
strDieuKien = _strQuery.substring(indexWhere + 5, _strQuery.indexOf("("));
_soDKOWhere = 1;
for (int i = 0; i < _dsDKKiemTra.length; i++) {
if (strDieuKien.contains(_dsDKKiemTra[i])) {
setDKNhanDuoc(_dsDKKiemTra[i]);
System.out.println("Dieu kien " + _dsDKKiemTra[i]);
}
}
} else {
//Trường hợp where nhiều hơn một điều kiện
if (strDieuKien.contains("OR") || strDieuKien.contains("AND")) {
_soDKOWhere = 2;
WhereParse wp = new WhereParse(strDieuKien);
setDsColumnNhanDuoc(wp.getDSCotNhanDuoc());
setDsDieuKienNhanDuoc(wp.getDSDKNhanDuoc());
setDsValueNhanDuoc(wp.getDSValueNhanDuoc());
setDkOWhere(wp.getDK());
for (int i = 0; i < 2; i++) {
System.out.println(getDsColumnNhanDuoc()[i] + getDsDieuKienNhanDuoc()[i] + getDsValueNhanDuoc()[i]);
}
} //Trường hợp where chỉ có một điều kiện đơn thuần
else {
_soDKOWhere = 1;
for (int i = 0; i < _dsDKKiemTra.length; i++) {
if (strDieuKien.contains(_dsDKKiemTra[i])) {
setDKNhanDuoc(_dsDKKiemTra[i]);
setColumnNhanDuoc(strDieuKien.split(getDKNhanDuoc())[0].trim());
setValueNhanDuoc(strDieuKien.split(getDKNhanDuoc())[1].trim());
System.out.println("Dieu kien " + _dsDKKiemTra[i]);
System.out.println("Column " + getColumnNhanDuoc());
System.out.println("Gia tri " + getValueNhanDuoc());
//Trường hợp này cũng tương tự trường hợp khi có kết,
//Khác ở chỗ ValueNhanDuoc này là cột thứ 2. Xử lý ở SQLParse
//select hocsinh.mssv, hocsinh.hoten, lophoc.giaovienchunhiem where hocsinh.ma_lop = lophoc.malop
//Quy định là khi kết thì đều phải có .
if (_ColumnNhanDuoc.contains(".") && _valueNhanDuoc.contains(".")) {
_isKetBang = true;
if (_dsColumn != null) {
for (int iCol = 0; iCol < _dsColumn.length; iCol++) {
if (!_dsColumn[iCol].contains(".")) {
_isKetBang = false;
break;
}
}
break;
}
}
}
}
}
}
return true;
}
public String catCotTuChuoi(String str) {
int index = str.indexOf(".");
if (index == -1) {
return str;
}
return str.substring(index);
}
private boolean XuLyLenhUPDATE() {
boolean isDKWhere = false;
int indexUpdate = _strQuery.indexOf("UPDATE");
int indexSet = _strQuery.indexOf("SET");
int indexWhere = _strQuery.indexOf("WHERE");
if (indexWhere == -1) {
indexWhere = _strQuery.length();
isDKWhere = true;
}
String tableUpdate = _strQuery.substring(indexUpdate + 6, indexSet).toUpperCase().trim();
_tableUpdate = _database.getTable(tableUpdate);
if (_tableUpdate == null) {
System.out.println("_tableUpdate = null trong String_Query");
return false;
}
String[] strColumnValueSet = _strQuery.substring(indexSet + 3, indexWhere).trim().split("=");
int numberColumnUpdate = strColumnValueSet.length - 1;
_dsColumn = new String[numberColumnUpdate];
_dsValue = new String[numberColumnUpdate];
System.out.println(tableUpdate);
int iColumn = 0;
int iValue = 0;
for (int i = 0; i < numberColumnUpdate; i++) {
if (!strColumnValueSet[i].contains(",")) {
_dsColumn[iColumn] = strColumnValueSet[i].trim();
iColumn++;
} else {
_dsValue[iValue] = strColumnValueSet[i].split(",", 2)[0].trim().toUpperCase();
iValue++;
_dsColumn[iColumn] = strColumnValueSet[i].split(",", 2)[1].trim();
iColumn++;
}
}
_dsValue[iValue] = strColumnValueSet[numberColumnUpdate].trim().toUpperCase();
iValue++;
for (int i = 0; i < numberColumnUpdate; i++) {
System.out.print(_dsColumn[i] + " ");
}
System.out.println();
for (int i = 0; i < numberColumnUpdate; i++) {
System.out.print(_dsValue[i] + " ");
}
System.out.println();
if (isDKWhere) {
System.out.println("Khong co dieu kien where");
} else {
String strDieuKien = _strQuery.substring(indexWhere + 5).trim();
System.out.println("Chuoi dieu kien: " + strDieuKien);
//Trường hợp where nhiều hơn một điều kiện
if (strDieuKien.contains("OR") || strDieuKien.contains("AND")) {
_soDKOWhere = 2;
WhereParse wp = new WhereParse(strDieuKien);
setDsColumnNhanDuoc(wp.getDSCotNhanDuoc());
setDsDieuKienNhanDuoc(wp.getDSDKNhanDuoc());
setDsValueNhanDuoc(wp.getDSValueNhanDuoc());
setDkOWhere(wp.getDK());
for (int i = 0; i < 2; i++) {
System.out.println(getDsColumnNhanDuoc()[i] + getDsDieuKienNhanDuoc()[i] + getDsValueNhanDuoc()[i]);
}
} else {
for (int i = 0; i < _dsDKKiemTra.length; i++) {
if (strDieuKien.contains(_dsDKKiemTra[i])) {
_soDKOWhere = 1;
setDKNhanDuoc(_dsDKKiemTra[i]);
setColumnNhanDuoc(strDieuKien.split(getDKNhanDuoc())[0].trim());
setValueNhanDuoc(strDieuKien.split(getDKNhanDuoc())[1].trim());
System.out.println("Dieu kien " + _dsDKKiemTra[i]);
System.out.println("Column " + getColumnNhanDuoc());
System.out.println("Gia tri " + getValueNhanDuoc());
}
}
}
}
return true;
}
//DELETE FROM Persons
//WHERE LastName='Tjessem' AND FirstName='Jakob'
private boolean XuLyDELETE() {
boolean isDKWhere = true;
int indexDELETE = _strQuery.indexOf("DELETE");
int indexFROM = _strQuery.indexOf(" FROM ");
if (indexFROM == -1)//nếu không có mệnh đề from
{
return false;
}
int indexWHERE = _strQuery.indexOf(" WHERE ");
if (indexWHERE == -1) {
indexWHERE = _strQuery.length();
isDKWhere = false;
}
_dsTable = _strQuery.substring(indexFROM + 5, indexWHERE).trim().split(",");
if (_dsTable.length != 1) {
return false;
}
System.out.println("Bang ma co delete: " + _dsTable[0]);
if (!isDKWhere) {//Delete From SinhVien
_soDKOWhere = 0;
System.out.println("Xoa het noi dung bang: " + _dsTable[0]);
} else {
String strDieuKien = _strQuery.substring(indexWHERE + 6).trim();
System.out.println("Chuoi dieu kien: " + strDieuKien);
//Trường hợp where nhiều hơn một điều kiện
if (strDieuKien.contains("OR") || strDieuKien.contains("AND")) {
_soDKOWhere = 2;
WhereParse wp = new WhereParse(strDieuKien);
setDsColumnNhanDuoc(wp.getDSCotNhanDuoc());
setDsDieuKienNhanDuoc(wp.getDSDKNhanDuoc());
setDsValueNhanDuoc(wp.getDSValueNhanDuoc());
setDkOWhere(wp.getDK());
for (int i = 0; i < 2; i++) {
System.out.println(getDsColumnNhanDuoc()[i] + getDsDieuKienNhanDuoc()[i] + getDsValueNhanDuoc()[i]);
}
} else {
_soDKOWhere = 1;
for (int i = 0; i < _dsDKKiemTra.length; i++) {
if (strDieuKien.contains(_dsDKKiemTra2[i])) {
setDKNhanDuoc(_dsDKKiemTra2[i]);
setColumnNhanDuoc(strDieuKien.split(getDKNhanDuoc())[0].trim());
setValueNhanDuoc(strDieuKien.split(getDKNhanDuoc())[1].trim());
System.out.println("Dieu kien " + _dsDKKiemTra2[i]);
System.out.println("Column " + getColumnNhanDuoc());
System.out.println("Gia tri " + getValueNhanDuoc());
//break; Vì > và >=
}
return true;
}
}
}
return true;
}
/*
* Hàm Insert Lấy Table insert Tại bảng _dsTable; Hàm Insert Lấy Value tại
* bảng _dsValue
*/
private boolean XuLyLenhINSERT() {
//INSERT INTO table_name VALUES (value1, value2, value3,...)
_commandQuery = "INSERT";
int IntoPos = _strQuery.indexOf(" INTO ");
int ValuesPos = _strQuery.indexOf(" VALUES");
int BeginBrack = _strQuery.indexOf("(");
int EndBrack = _strQuery.indexOf(")");
//kiểm tra nếu không có 1 trong 4 trường trên thì sẽ bị lỗi
if ((IntoPos != -1) && (ValuesPos != -1) && (BeginBrack != -1) && (EndBrack != -1)) {
_dsTable = _strQuery.substring(IntoPos + 5, ValuesPos).trim().split(",");
if (_dsTable.length != 1) //kiểm tra nếu khác 1 bảng
{
return false;
}
_dsValue = _strQuery.substring(BeginBrack + 1, EndBrack).trim().split(",");
if (_dsValue.length <= 0)//kiểm tra nếu không có dữ liệu thêm vào
{
return false;
}
return true;
}
return false;
}
/**
* @return the _DKNhanDuoc
*/
public String getDKNhanDuoc() {
return _DKNhanDuoc;
}
/**
* @param DKNhanDuoc the _DKNhanDuoc to set
*/
public void setDKNhanDuoc(String DKNhanDuoc) {
this._DKNhanDuoc = DKNhanDuoc;
}
/**
* @return the _ColumnNhanDuoc
*/
public String getColumnNhanDuoc() {
return _ColumnNhanDuoc;
}
/**
* @param ColumnNhanDuoc the _ColumnNhanDuoc to set
*/
public void setColumnNhanDuoc(String ColumnNhanDuoc) {
this._ColumnNhanDuoc = ColumnNhanDuoc;
}
/**
* @return the _valueNhanDuoc
*/
public String getValueNhanDuoc() {
return _valueNhanDuoc;
}
/**
* @param valueNhanDuoc the _valueNhanDuoc to set
*/
public void setValueNhanDuoc(String valueNhanDuoc) {
this._valueNhanDuoc = valueNhanDuoc;
}
/**
* @return the _dsColumnNhanDuoc
*/
public String[] getDsColumnNhanDuoc() {
return _dsColumnNhanDuoc;
}
/**
* @param dsColumnNhanDuoc the _dsColumnNhanDuoc to set
*/
public void setDsColumnNhanDuoc(String[] dsColumnNhanDuoc) {
this._dsColumnNhanDuoc = dsColumnNhanDuoc;
}
/**
* @return the _dsValueNhanDuoc
*/
public String[] getDsValueNhanDuoc() {
return _dsValueNhanDuoc;
}
/**
* @param dsValueNhanDuoc the _dsValueNhanDuoc to set
*/
public void setDsValueNhanDuoc(String[] dsValueNhanDuoc) {
this._dsValueNhanDuoc = dsValueNhanDuoc;
}
/**
* @return the _dsDieuKienNhanDuoc
*/
public String[] getDsDieuKienNhanDuoc() {
return _dsDieuKienNhanDuoc;
}
/**
* @param dsDieuKienNhanDuoc the _dsDieuKienNhanDuoc to set
*/
public void setDsDieuKienNhanDuoc(String[] dsDieuKienNhanDuoc) {
this._dsDieuKienNhanDuoc = dsDieuKienNhanDuoc;
}
/**
* @return the _dkOWhere
*/
public String getDkOWhere() {
return _dkOWhere;
}
/**
* @param dkOWhere the _dkOWhere to set
*/
public void setDkOWhere(String dkOWhere) {
this._dkOWhere = dkOWhere;
}
//dsColumn và dsValue cho trương hợp comment update
public String[] getDsColumn() {
return _dsColumn;
}
public String[] getDsValue() {
return _dsValue;
}
/**
* @return the _dsTable
*/
public String[] getDsTable() {
return _dsTable;
}
/**
* @param dsTable the _dsTable to set
*/
public void setDsTable(String[] dsTable) {
this._dsTable = dsTable;
}
public int getSoDKOWhere() {
return _soDKOWhere;
}
/**
* @return the _dsValue
*/
public Table getTableTempForLongCap() {
return _tempTableForLongCap;
}
public int getQueryLevels() {
return _queryLevels;
}
public Table getTableUpdate() {
return _tableUpdate;
}
public boolean isKetBang() {
return _isKetBang;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package server;
import MyDatabase.Command;
import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author HUYNHLOC
*/
public class Client extends Thread {
private Socket _client;
private int _index;
private ObjectInputStream ois;
private ObjectOutputStream oos;
CommandListener _comCommandListener;
DisconnectListener _disConnectListener;
public Client(Socket client, int index) {
try {
_client = client;
_index = index;
oos = new ObjectOutputStream(new BufferedOutputStream(_client.getOutputStream()));
oos.flush();
ois = new ObjectInputStream(new BufferedInputStream(_client.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void SetCommandListener(CommandListener cmdlistener) {
_comCommandListener = cmdlistener;
}
public void SetDisconnectListener(DisconnectListener disconnectlistener) {
_disConnectListener = disconnectlistener;
}
// day su kien nhan 1 command ra ngoai
public void fireReceiveCommandEvent(Command cmd) {
_comCommandListener.handleReceiveCommand(this, cmd);
}
public void fireDisconnectEvent() {
_disConnectListener.handleDisconnect(_index);
}
synchronized public void SendCommand(Command cmd) {
SendCommandToClient Sender = new SendCommandToClient(cmd);
Sender.start();
}
/**
* @return the _index
*/
public int getIndex() {
return _index;
}
/**
* @param index the _index to set
*/
public void setIndex(int index) {
this._index = index;
}
class SendCommandToClient extends Thread {
private Command _cmdSend;
public SendCommandToClient(Command cmd) {
_cmdSend = cmd;
}
@Override
public void run() {
try {
oos.writeObject(_cmdSend);
oos.flush();
} catch (IOException ex) {
//Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
this.interrupt();
System.gc();
}
}
public void run() {
while (_client.isConnected()) {
try {
Command cmdrec = (Command) ois.readObject();
fireReceiveCommandEvent(cmdrec);
} catch (Exception ex) {
//ex.printStackTrace();
break;
}
}
fireDisconnectEvent();
Disconnect();
}
public void Disconnect() {
if (_client != null && _client.isConnected()) {
try {
ois.close();
oos.close();
_client.shutdownInput();
_client.shutdownOutput();
_client.close();
_client = null;
} catch (IOException ex) {
//Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
| Java |
package server;
import MyDatabase.Command;
interface CommandListener{
void handleReceiveCommand(Client sender,Command cmd);
}
interface DisconnectListener{
void handleDisconnect(int index);
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package server;
import MyDatabase.Column;
import MyDatabase.Database;
import MyDatabase.Table;
import java.io.File;
import java.util.EventObject;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author HUYNHLOC
*/
public class TableValues extends DefaultTableModel {
TableValues(String[] colNames, int i) {
super(colNames, i);
}
@Override
public Class getColumnClass(int column) {
Class dataType = super.getColumnClass(column);
if (column == 2) {
dataType = Boolean.class;
}
return dataType;
}
@Override
public boolean isCellEditable(int row, int column) {
if (column == 3 || column == 4) {
Boolean b = (Boolean) getValueAt(row, 2);
if (b == null) {
b = false;
}
if (b) {
return false;
}
}
return true;
}
@Override
public void setValueAt(Object value, int row, int column) {
super.setValueAt(value, row, column);
if (column == 2) {
for (int i = 0; i < getRowCount(); i++) {
if (i != row) {
super.setValueAt(false, i, column);
}
}
Boolean b = (Boolean) getValueAt(row, column);
if (b == null) {
b = false;
}
if (b) {
super.setValueAt(null, row, 3);
super.setValueAt(null, row, 4);
}
}
}
// kiem tra co du lieu hay khong
public Boolean AllDataValid() {
Vector Datas = this.getDataVector();
for (int i = 0; i < Datas.size(); i++) {
if (!this.isValid((Vector) Datas.elementAt(i))) {
return false;
}
}
return true;
}
//kiem tra hop le cua mot row
public boolean isValid(Vector data) {
if (data.elementAt(0) == null
|| data.elementAt(0).toString().trim().equals("")
|| data.elementAt(1) == null
|| data.elementAt(1).toString().trim().equals("")) {
return false;
}
if (data.elementAt(3) == null
|| data.elementAt(3).toString().trim().equals("")){
if (data.elementAt(4) != null
&& !data.elementAt(4).toString().trim().equals(""))
return false;
}
if (data.elementAt(4) == null
|| data.elementAt(4).toString().trim().equals("")){
if (data.elementAt(3) != null
&& !data.elementAt(3).toString().trim().equals(""))
return false;
}
return true;
}
// chuyen du lieu thanh kieu Table
public boolean WriteTableToDatabase(String tablename, Database database) {
if (!this.AllDataValid()) {
return false;
}
Table table = new Table(tablename);
Vector Datas = this.getDataVector();
for (int i = 0; i < Datas.size(); i++) {
Vector data = (Vector) Datas.elementAt(i);
if (this.isValid(data)) {
String namecol = data.elementAt(0).toString().trim();
String strtype = data.elementAt(1).toString().trim();
int type = strtype.equals("String") ? 1 : 0;
Boolean isprimarykey = (Boolean) data.elementAt(2);
if (isprimarykey == null) {
isprimarykey = false;
}
Boolean isforeignkey;
String namecolref;
String nametableref;
Table taberef = null;
if (data.elementAt(3) == null
|| data.elementAt(3).toString().trim().equals("")) {
isforeignkey = false;
namecolref = "";
nametableref = "";
} else {
isforeignkey = true;
namecolref = data.elementAt(3).toString().trim();
nametableref = data.elementAt(4).toString().trim();
taberef = database.getTable(nametableref);
if (taberef == null) {
return false;
}
}
if (!table.addColumn(namecol, namecolref, taberef, type, isprimarykey, isforeignkey)) {
return false;
}
}
}
/*
* // vi du tao table SINHVIEN va add row vao Vector<Object> row1 = new
* Vector<Object>(); row1.add("0912268"); row1.add("Huynh Van Loc");
* table.addRow(row1); Vector<Object> row2 = new Vector<Object>();
* row2.add("0912359"); row2.add("Pham Duy Phuong"); table.addRow(row2);
*
*/
if (!database.addTable(table)) {
return false;
}
database.showDatabase();
return true;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package server;
import MyDatabase.*;
import SQLParse.SQLParser;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Vector;
/**
*
* @author HUYNHLOC
*/
public class ServerListener extends Thread {
// so client dang connect
private int countClient = 0;
private int _port;
// danh sach client
Vector<Client> _listClien;
//database
Data _myData;
// SqlParse
SQLParser _sqlLParser;
public ServerListener(int port, Data data) {
_port = port;
_listClien = new Vector<Client>();
_myData = data;
_sqlLParser = new SQLParser();
_myData.show();
}
public void run() {
try {
// lang nghe ket noi
ServerSocket serverSocket = new ServerSocket(_port);
while (true) {
// socket lang nghe ket noi
Socket soc = serverSocket.accept();
countClient++;
Client client = new Client(soc, countClient);
client.SetCommandListener(new ReceiveCommandListener());
client.SetDisconnectListener(new ClientDisconnectListener());
_listClien.add(client);
client.start();
this.BroadCastListDatabase();
}
} catch (IOException ex) {
//Logger.getLogger(ServerListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void Disconnect() {
for (int i = 0; i < _listClien.size(); i++) {
((Client) _listClien.elementAt(i)).Disconnect();
}
_listClien.clear();
this.interrupt();
}
// su ly command nhan duoc
class ReceiveCommandListener implements CommandListener {
@Override
synchronized public void handleReceiveCommand(Client sender, Command cmd) {
Client client = (Client) sender;
Command.CommandType cmdType = (Command.CommandType) cmd.getCmdType();
switch (cmdType) {
case Query:
//JOptionPane.showMessageDialog(null, cmd.getMessage(), "Query", 1);
/*
* Table table = _myDatabase.getTable(cmd.getMessage());
* Command cmdsend = new
* Command(Command.CommandType.TableData, table);
* client.SendCommand(cmdsend);
*
*/
/*
* SQLParser qLParser = new SQLParser(cmd.getMessage());
* Table table = qLParser.SQLResult(_myDatabase); if(table
* == null){ //Command cmdSend = new
* Command(Command.CommandType.Message, "Loi hoac ko co du
* lieu"); client.SendCommand(cmdSend); }else{ // co du lieu
* Command cmdSend = new
* Command(Command.CommandType.TableData, table);
* client.SendCommand(cmdSend); }
*
*/
String[] queryanddatabase = cmd.getMessage().split("/");
String query = queryanddatabase[0].trim();
String nameDatabase = queryanddatabase[1].trim();
Database database = _myData.getDatabase(nameDatabase);
// query
//nkluan doi lai cho nay thanh kieu boolean
boolean Kiemtra = _sqlLParser.setQuery(query, database);
//Table table = qLParser.SQLResult();
//boolean Kiemtra = _sqlLParser.SQLResult();
if (Kiemtra) {
if (_sqlLParser.GetQueryComment().compareTo("SELECT") == 0) {//neu kiem tra dung va do la menh de select
Table table = _sqlLParser.getTableResult();
if (table == null) {
Command cmdSend = new Command(Command.CommandType.Message, "Loi hoac ko co du lieu");
client.SendCommand(cmdSend);
} else {
// co du lieu
Command cmdSend = new Command(Command.CommandType.TableData, table);
client.SendCommand(cmdSend);
}
} else//khong phai menh de select thao tac thanh cong
{
////////////SANG
Table table = _sqlLParser.getTableResult();
if (table == null) {
Command cmdSend = new Command(Command.CommandType.Message, "Loi hoac ko co du lieu");
client.SendCommand(cmdSend);
} else {
// co du lieu
String queryGetTableDisplay = "select * from " + table.getNameTable();
_sqlLParser.setQuery(queryGetTableDisplay, database);
Table tableDisplay = _sqlLParser.getTableResult();
//Lệnh này là select nên sử lý lại select thành công
Command cmdSend = new Command(Command.CommandType.TableData, tableDisplay);
client.SendCommand(cmdSend);
}
/*
* try { Thread.sleep(1000); } catch
* (InterruptedException ex) {
* Logger.getLogger(ServerListener.class.getName()).log(Level.SEVERE,
* null, ex); } Table result =
* database.getTable(_sqlLParser.getDStable()[0]);
* Command cmdSend = new
* Command(Command.CommandType.TableData, result);
* client.SendCommand(cmdSend);
*
*/
}
} else//thao tac khong thanh cong
{
Command cmdSend = new Command(Command.CommandType.Message, "Thao tac that bai");
client.SendCommand(cmdSend);
}
break;
// nhan duoc mot message
case Message:
break;
}
}
}
// broadcasdt command
public void BroadCastCommand(Command cmd) {
for (int i = 0; i < _listClien.size(); i++) {
_listClien.get(i).SendCommand(cmd);
}
}
// broadcasd danh sach database
public void BroadCastListDatabase() {
ArrayList list = _myData.getAllNameDatabases();
String message = " ";
for (int i = 0; i < list.size(); i++) {
message += " " + (String) list.get(i);
}
Command cmd = new Command(Command.CommandType.ListNameDatabase, message.trim());
this.BroadCastCommand(cmd);
}
class ClientDisconnectListener implements DisconnectListener {
@Override
public void handleDisconnect(int index) {
for (int i = 0; i < _listClien.size(); i++) {
if (((Client) _listClien.elementAt(i)).getIndex() == index) {
_listClien.remove(i);
}
}
}
}
public Data getData() {
return _myData;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package server;
import MyDatabase.*;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
/**
*
* @author HUYNHLOC
*/
public class MainWindow extends javax.swing.JFrame {
/**
* Creates new form MainWSindow
*/
TableValues model;
Document doc; // tai lieu xml
ServerListener server;
Data _myData;
JComboBox jcb_forTableNameRef;
//list name table trong mot database
ArrayList _listNameTable;
public MainWindow() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton_start = new javax.swing.JButton();
jButton_stop = new javax.swing.JButton();
jTextField_port = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jTextField_nametable = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jTextField_namedatabase = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jButton_createdatabase = new javax.swing.JButton();
jComboBox_database = new javax.swing.JComboBox();
jLabel3 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable_maintable = new javax.swing.JTable();
jButton_addrow = new javax.swing.JButton();
jButton_deleterow = new javax.swing.JButton();
jButton_createtable = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("MainWindow");
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
public void windowClosed(java.awt.event.WindowEvent evt) {
formWindowClosed(evt);
}
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
jPanel1.setBackground(java.awt.SystemColor.activeCaption);
jButton_start.setText("Start");
jButton_start.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_startActionPerformed(evt);
}
});
jButton_stop.setText("Stop");
jButton_stop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_stopActionPerformed(evt);
}
});
jTextField_port.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextField_portKeyTyped(evt);
}
});
jLabel2.setText("Port");
jLabel1.setText("Name table :");
jLabel4.setText("Name Database");
jButton_createdatabase.setText("Create Database");
jButton_createdatabase.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_createdatabaseActionPerformed(evt);
}
});
jComboBox_database.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox_databaseActionPerformed(evt);
}
});
jLabel3.setText("List Database");
jTable_maintable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable_maintable);
jButton_addrow.setText("Add Column");
jButton_addrow.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_addrowActionPerformed(evt);
}
});
jButton_deleterow.setText("Delete Column");
jButton_deleterow.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_deleterowActionPerformed(evt);
}
});
jButton_createtable.setText("Create Table");
jButton_createtable.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_createtableActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton_start, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton_stop, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 139, Short.MAX_VALUE)
.addComponent(jButton_createdatabase, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField_port, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField_nametable, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(50, 50, 50)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(21, 21, 21)
.addComponent(jComboBox_database, 0, 174, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField_namedatabase))))))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton_addrow)
.addGap(14, 14, 14)
.addComponent(jButton_deleterow)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton_createtable)
.addGap(8, 8, 8)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField_port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(jTextField_namedatabase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_start)
.addComponent(jButton_stop)
.addComponent(jButton_createdatabase))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 62, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField_nametable, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jComboBox_database, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_addrow)
.addComponent(jButton_deleterow)
.addComponent(jButton_createtable))
.addGap(11, 11, 11))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
// TODO add your handling code here:
}//GEN-LAST:event_formWindowActivated
private void jButton_addrowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_addrowActionPerformed
// TODO add your handling code here:
//model.insertRow(model.getRowCount(), new Object[]{});
model.addRow(new Object[]{});
}//GEN-LAST:event_jButton_addrowActionPerformed
private void jButton_createtableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_createtableActionPerformed
// TODO add your handling code here:
if (jTextField_nametable.getText().trim().equals("") || !model.AllDataValid()) {
JOptionPane.showMessageDialog(MainWindow.this, "Chưa nhập tên hoặc dữ liệu không hơp lệ", "Loi", 1);
} else { // ghi table xuong database
if (model.WriteTableToDatabase(jTextField_nametable.getText().trim(), _myData.getDatabase((String) jComboBox_database.getSelectedItem()))) {
JOptionPane.showMessageDialog(rootPane, "Tạo bảng thành công", "Thong bao", 1);
_listNameTable.add(jTextField_nametable.getText().trim());
// delete old table
for (int i = 0; i < model.getDataVector().size(); i++) {
model.removeRow(i);
}
model.removeRow(0);
// them danh sach table
String databaseSelected = (String) jComboBox_database.getSelectedItem();
Database database = _myData.getDatabase(databaseSelected);
if (database != null) {
_listNameTable.clear();
_listNameTable = database.getAllNameTable();
jcb_forTableNameRef.removeAllItems();
for (int i = 0; i < _listNameTable.size(); i++) {
jcb_forTableNameRef.addItem(_listNameTable.get(i));
}
jcb_forTableNameRef.addItem(" ");
}
} else {
JOptionPane.showMessageDialog(rootPane, "Tên hoặc dữ liệu không hợp lệ", "Thong bao", 1);
}
}
}//GEN-LAST:event_jButton_createtableActionPerformed
private void jButton_startActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_startActionPerformed
// TODO add your handling code here:
try {
if (jTextField_port.getText().trim().equals("")) {
JOptionPane.showMessageDialog(MainWindow.this, "Thieu thong tin input", "Loi", 1);
} else {
server = new ServerListener(Integer.parseInt(jTextField_port.getText().trim()), _myData);
server.start();
jButton_start.setVisible(false);
jButton_stop.setVisible(true);
}
} catch (Exception e) {
}
}//GEN-LAST:event_jButton_startActionPerformed
private void jTextField_portKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField_portKeyTyped
// TODO add your handling code here:
Character c = evt.getKeyChar();
if (c > '9' || c < '0') {
evt.consume();
}
}//GEN-LAST:event_jTextField_portKeyTyped
private void jButton_stopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_stopActionPerformed
// TODO add your handling code here:
// luu da ta xuong co so du lieu
server.Disconnect();
jButton_start.setVisible(true);
jButton_stop.setVisible(false);
}//GEN-LAST:event_jButton_stopActionPerformed
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
// TODO add your handling code here:
initGUI();
jButton_start.setVisible(true);
jButton_stop.setVisible(false);
}//GEN-LAST:event_formWindowOpened
private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
// TODO add your handling code here:
server.Disconnect();
}//GEN-LAST:event_formWindowClosed
private void jButton_deleterowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_deleterowActionPerformed
// TODO add your handling code here:
if (jTable_maintable.getSelectedRow() >= 0) {
model.removeRow(jTable_maintable.getSelectedRow());
}
}//GEN-LAST:event_jButton_deleterowActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
// TODO add your handling code here:
if (server != null) {
server.Disconnect();
}
try {
// ghi du lieu xuong file
if (_myData != null) {
Server_Data.SerialDatabase("MyData.txt", _myData);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_formWindowClosing
private void jButton_createdatabaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_createdatabaseActionPerformed
// TODO add your handling code here:
if (jTextField_namedatabase.getText().trim().equals("")) {
JOptionPane.showMessageDialog(MainWindow.this, "Nhập tên database", "Loi", 1);
} else {
Database database = new Database(jTextField_namedatabase.getText().trim());
if (_myData.addDatabase(database)) {
JOptionPane.showMessageDialog(MainWindow.this, "Thao tác thành công", "Thong bao", 1);
jComboBox_database.addItem(database.getName());
if (server != null) {
// gởi danh sach cac database
server.BroadCastListDatabase();
}
} else {
JOptionPane.showMessageDialog(MainWindow.this, "Database da ton tai", "Loi", 1);
}
}
}//GEN-LAST:event_jButton_createdatabaseActionPerformed
private void jComboBox_databaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_databaseActionPerformed
// TODO add your handling code here:
String databaseSelected = (String) jComboBox_database.getSelectedItem();
Database database = _myData.getDatabase(databaseSelected);
if (database != null) {
_listNameTable.clear();
_listNameTable = database.getAllNameTable();
jcb_forTableNameRef.removeAllItems();
for (int i = 0; i < _listNameTable.size(); i++) {
jcb_forTableNameRef.addItem(_listNameTable.get(i));
}
jcb_forTableNameRef.addItem(" ");
}
}//GEN-LAST:event_jComboBox_databaseActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
MainWindow mainWindow = new MainWindow();
mainWindow.setLocation(400, 200);
mainWindow.setVisible(true);
}
});
}
public void initGUI() {
String[] colNames = {"Field", "DataType", "PrimaryKey", "ColNameRef", "TableNameref"};
model = new TableValues(colNames, 1);
jTable_maintable.setModel(model);
JComboBox jComboBox = new JComboBox();
jComboBox.addItem("String");
jComboBox.addItem("Int");
DefaultCellEditor dce = new DefaultCellEditor(jComboBox);
TableColumnModel tcm = jTable_maintable.getColumnModel();
TableColumn tc = tcm.getColumn(1);
tc.setCellEditor(dce);
jcb_forTableNameRef = new JComboBox();
_listNameTable = new ArrayList();
try {// load data
File f = new File("MyData.txt");
if (!f.exists()) {
f.createNewFile();
Data data = new Data();
Database systemdatabase = new Database("SYSTEM");
data.addDatabase(systemdatabase);
Server_Data.SerialDatabase("MyData.txt", data);
}
_myData = Server_Data.Deseriable("MyData.txt");
ArrayList nameDatabases = _myData.getAllNameDatabases();
for (int i = 0; i < nameDatabases.size(); i++) {
jComboBox_database.addItem((String) nameDatabases.get(i));
}
} catch (FileNotFoundException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
DefaultCellEditor dce_tablenameref = new DefaultCellEditor(jcb_forTableNameRef);
TableColumnModel tcm_tablenameref = jTable_maintable.getColumnModel();
TableColumn tc_tablenameref = tcm.getColumn(4);
tc_tablenameref.setCellEditor(dce_tablenameref);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton_addrow;
private javax.swing.JButton jButton_createdatabase;
private javax.swing.JButton jButton_createtable;
private javax.swing.JButton jButton_deleterow;
private javax.swing.JButton jButton_start;
private javax.swing.JButton jButton_stop;
private javax.swing.JComboBox jComboBox_database;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable_maintable;
private javax.swing.JTextField jTextField_namedatabase;
private javax.swing.JTextField jTextField_nametable;
private javax.swing.JTextField jTextField_port;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* Copyright (C) 2011 Jacquet Wong
*
* 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.musicg.experiment.math.cluster;
public class Segment {
private int startPosition;
private int size;
private double mean;
public int getStartPosition() {
return startPosition;
}
public void setStartPosition(int startPosition) {
this.startPosition = startPosition;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public double getMean() {
return mean;
}
public void setMean(double mean) {
this.mean = mean;
}
} | Java |
/*
* Copyright (C) 2011 Jacquet Wong
*
* 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.musicg.experiment.math.cluster;
import java.util.LinkedList;
import java.util.List;
import com.musicg.pitch.PitchHandler;
public class SegmentCluster{
private double diffThreshold;
public SegmentCluster(){
this.diffThreshold=1;
}
public SegmentCluster(double diffThreshold){
this.diffThreshold=diffThreshold;
}
public void setDiffThreshold(double diffThreshold){
this.diffThreshold=diffThreshold;
}
public List<Segment> getSegments(double[] array){
PitchHandler pitchHandler=new PitchHandler();
List<Segment> segmentList=new LinkedList<Segment>();
double segmentMean=0;
int segmentSize=0;
if (array.length>0){
segmentMean=array[1];
segmentSize=1;
}
for (int i=1; i<array.length; i++){
double diff=Math.abs(pitchHandler.getToneChanged(array[i], segmentMean));
if (diff<diffThreshold){
// same cluster, add to the cluster and change the cluster data
segmentMean=(segmentMean*segmentSize+array[i])/(++segmentSize);
}
else{
// not the cluster, create a new one
//System.out.println("New Cluster: "+clusterMean);
Segment segment=new Segment();
segment.setMean(segmentMean);
segment.setStartPosition(i-segmentSize);
segment.setSize(segmentSize);
segmentList.add(segment);
// end current cluster
// set new cluster
segmentMean=array[i];
segmentSize=1;
}
}
// add the last cluster
Segment segment=new Segment();
segment.setMean(segmentMean);
segment.setStartPosition(array.length-segmentSize);
segment.setSize(segmentSize);
segmentList.add(segment);
return segmentList;
}
} | Java |
/*
* Copyright (C) 2011 Jacquet Wong
*
* 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.musicg.math.statistics;
/**
* Evaluate the standard deviation of an array
*
* @author Jacquet Wong
*
*/
public class StandardDeviation extends MathStatistics{
private Mean mean=new Mean();
public StandardDeviation(){
}
public StandardDeviation(double[] values){
setValues(values);
}
public double evaluate(){
mean.setValues(values);
double meanValue=mean.evaluate();
int size=values.length;
double diffSquare=0;
double sd=Double.NaN;
for (int i=0; i<size; i++){
diffSquare+=Math.pow(values[i]-meanValue,2);
}
if (size>0){
sd=Math.sqrt(diffSquare/size);
}
return sd;
}
} | Java |
/*
* Copyright (C) 2011 Jacquet Wong
*
* 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.musicg.math.statistics;
/**
* Evaluate the centroid of an array
*
* @author Jacquet Wong
*
*/
public class DataCentroid extends MathStatistics{
public DataCentroid(){
}
public DataCentroid(double[] values){
setValues(values);
}
public double evaluate(){
double sumCentroid=0;
double sumIntensities=0;
int size=values.length;
for (int i=0; i<size; i++){
if (values[i]>0){
sumCentroid+=i*values[i];
sumIntensities+=values[i];
}
}
double avgCentroid=sumCentroid/sumIntensities;
return avgCentroid;
}
}
| Java |
/*
* Copyright (C) 2011 Jacquet Wong
*
* 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.musicg.math.statistics;
/**
* Abstract class for mathematics & statistics
*
* @author Jacquet Wong
*
*/
public abstract class MathStatistics{
protected double[] values;
public void setValues(double[] values){
this.values=values;
}
public abstract double evaluate();
} | Java |
/*
* Copyright (C) 2011 Jacquet Wong
*
* 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.musicg.math.statistics;
/**
* Evaluate the zero crossing rate of a signal
*
* @author Jacquet Wong
*
*/
public class ZeroCrossingRate{
private short[] signals;
private double lengthInSecond;
/**
* Constructor
*
* @param signals input signal array
* @param lengthInSecond length of the signal (in second)
*/
public ZeroCrossingRate(short[] signals, double lengthInSecond){
setSignals(signals,1);
}
/**
* set the signals
*
* @param signals input signal array
* @param lengthInSecond length of the signal (in second)
*/
public void setSignals(short[] signals, double lengthInSecond){
this.signals=signals;
this.lengthInSecond=lengthInSecond;
}
public double evaluate(){
int numZC=0;
int size=signals.length;
for (int i=0; i<size-1; i++){
if((signals[i]>=0 && signals[i+1]<0) || (signals[i]<0 && signals[i+1]>=0)){
numZC++;
}
}
return numZC/lengthInSecond;
}
} | Java |
/*
* Copyright (C) 2011 Jacquet Wong
*
* 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.musicg.math.statistics;
/**
* Evaluate the spectral centroid of an array
*
* @author Jacquet Wong
*
*/
public class SpectralCentroid extends MathStatistics{
public SpectralCentroid(){
}
public SpectralCentroid(double[] values){
setValues(values);
}
public double evaluate(){
double sumCentroid=0;
double sumIntensities=0;
int size=values.length;
for (int i=0; i<size; i++){
if (values[i]>0){
sumCentroid+=i*values[i];
sumIntensities+=values[i];
}
}
double avgCentroid=sumCentroid/sumIntensities;
return avgCentroid;
}
}
| Java |
/*
* Copyright (C) 2011 Jacquet Wong
*
* 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.musicg.math.statistics;
/**
* Evaluate the sum of an array
*
* @author Jacquet Wong
*
*/
public class Sum extends MathStatistics{
public Sum(){
}
public Sum(double[] values){
setValues(values);
}
public double evaluate(){
double sum=0;
int size=values.length;
for (int i=0 ;i<size; i++){
sum+=values[i];
}
return sum;
}
public int size(){
return values.length;
}
} | Java |
/*
* Copyright (C) 2011 Jacquet Wong
*
* 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.musicg.math.statistics;
/**
* Evaluate the mean of an array
* @author Jacquet Wong
*
*/
public class Mean extends MathStatistics{
private Sum sum=new Sum();
public Mean(){
}
public Mean(double[] values){
setValues(values);
}
public double evaluate(){
sum.setValues(values);
double mean=sum.evaluate()/sum.size();
return mean;
}
} | Java |
package com.musicg.math.rank;
import java.util.List;
public interface MapRank{
public List getOrderedKeyList(int numKeys, boolean sharpLimit);
} | Java |
package com.musicg.math.rank;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class MapRankInteger implements MapRank{
private Map map;
private boolean acsending=true;
public MapRankInteger(Map<?,Integer> map, boolean acsending){
this.map=map;
this.acsending=acsending;
}
public List getOrderedKeyList(int numKeys, boolean sharpLimit){ // if sharp limited, will return sharp numKeys, otherwise will return until the values not equals the exact key's value
Set mapEntrySet=map.entrySet();
List keyList=new LinkedList();
// if the numKeys is larger than map size, limit it
if (numKeys>map.size()){
numKeys=map.size();
}
// end if the numKeys is larger than map size, limit it
if (map.size()>0){
int[] array=new int[map.size()];
int count=0;
// get the pass values
Iterator<Entry> mapIterator=mapEntrySet.iterator();
while (mapIterator.hasNext()){
Entry entry=mapIterator.next();
array[count++]=(Integer)entry.getValue();
}
// end get the pass values
int targetindex;
if (acsending){
targetindex=numKeys;
}
else{
targetindex=array.length-numKeys;
}
int passValue=getOrderedValue(array,targetindex); // this value is the value of the numKey-th element
// get the passed keys and values
Map passedMap=new HashMap();
List<Integer> valueList=new LinkedList<Integer>();
mapIterator=mapEntrySet.iterator();
while (mapIterator.hasNext()){
Entry entry=mapIterator.next();
int value=(Integer)entry.getValue();
if ((acsending && value<=passValue) || (!acsending && value>=passValue)){
passedMap.put(entry.getKey(), value);
valueList.add(value);
}
}
// end get the passed keys and values
// sort the value list
Integer[] listArr=new Integer[valueList.size()];
valueList.toArray(listArr);
Arrays.sort(listArr);
// end sort the value list
// get the list of keys
int resultCount=0;
int index;
if (acsending){
index=0;
}
else{
index=listArr.length-1;
}
if (!sharpLimit){
numKeys=listArr.length;
}
while (true){
int targetValue=(Integer)listArr[index];
Iterator<Entry> passedMapIterator=passedMap.entrySet().iterator();
while(passedMapIterator.hasNext()){
Entry entry=passedMapIterator.next();
if ((Integer)entry.getValue()==targetValue){
keyList.add(entry.getKey());
passedMapIterator.remove();
resultCount++;
break;
}
}
if (acsending){
index++;
}
else{
index--;
}
if (resultCount>=numKeys){
break;
}
}
// end get the list of keys
}
return keyList;
}
private int getOrderedValue(int[] array, int index){
locate(array,0,array.length-1,index);
return array[index];
}
// sort the partitions by quick sort, and locate the target index
private void locate(int[] array, int left, int right, int index) {
int mid=(left+right)/2;
//System.out.println(left+" to "+right+" ("+mid+")");
if (right==left){
//System.out.println("* "+array[targetIndex]);
//result=array[targetIndex];
return;
}
if(left < right) {
int s = array[mid];
int i = left - 1;
int j = right + 1;
while(true) {
while(array[++i] < s) ;
while(array[--j] > s) ;
if(i >= j)
break;
swap(array, i, j);
}
//System.out.println("2 parts: "+left+"-"+(i-1)+" and "+(j+1)+"-"+right);
if (i>index){
// the target index in the left partition
//System.out.println("left partition");
locate(array, left, i-1,index);
}
else{
// the target index in the right partition
//System.out.println("right partition");
locate(array, j+1, right,index);
}
}
}
private void swap(int[] array, int i, int j) {
int t = array[i];
array[i] = array[j];
array[j] = t;
}
} | Java |
package com.musicg.math.rank;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class MapRankDouble implements MapRank{
private Map map;
private boolean acsending=true;
public MapRankDouble(Map<?,Double> map, boolean acsending){
this.map=map;
this.acsending=acsending;
}
public List getOrderedKeyList(int numKeys, boolean sharpLimit){ // if sharp limited, will return sharp numKeys, otherwise will return until the values not equals the exact key's value
Set mapEntrySet=map.entrySet();
List keyList=new LinkedList();
// if the numKeys is larger than map size, limit it
if (numKeys>map.size()){
numKeys=map.size();
}
// end if the numKeys is larger than map size, limit it
if (map.size()>0){
double[] array=new double[map.size()];
int count=0;
// get the pass values
Iterator<Entry> mapIterator=mapEntrySet.iterator();
while (mapIterator.hasNext()){
Entry entry=mapIterator.next();
array[count++]=(Double)entry.getValue();
}
// end get the pass values
int targetindex;
if (acsending){
targetindex=numKeys;
}
else{
targetindex=array.length-numKeys;
}
double passValue=getOrderedValue(array,targetindex); // this value is the value of the numKey-th element
// get the passed keys and values
Map passedMap=new HashMap();
List<Double> valueList=new LinkedList<Double>();
mapIterator=mapEntrySet.iterator();
while (mapIterator.hasNext()){
Entry entry=mapIterator.next();
double value=(Double)entry.getValue();
if ((acsending && value<=passValue) || (!acsending && value>=passValue)){
passedMap.put(entry.getKey(), value);
valueList.add(value);
}
}
// end get the passed keys and values
// sort the value list
Double[] listArr=new Double[valueList.size()];
valueList.toArray(listArr);
Arrays.sort(listArr);
// end sort the value list
// get the list of keys
int resultCount=0;
int index;
if (acsending){
index=0;
}
else{
index=listArr.length-1;
}
if (!sharpLimit){
numKeys=listArr.length;
}
while (true){
double targetValue=(Double)listArr[index];
Iterator<Entry> passedMapIterator=passedMap.entrySet().iterator();
while(passedMapIterator.hasNext()){
Entry entry=passedMapIterator.next();
if ((Double)entry.getValue()==targetValue){
keyList.add(entry.getKey());
passedMapIterator.remove();
resultCount++;
break;
}
}
if (acsending){
index++;
}
else{
index--;
}
if (resultCount>=numKeys){
break;
}
}
// end get the list of keys
}
return keyList;
}
private double getOrderedValue(double[] array, int index){
locate(array,0,array.length-1,index);
return array[index];
}
// sort the partitions by quick sort, and locate the target index
private void locate(double[] array, int left, int right, int index) {
int mid=(left+right)/2;
//System.out.println(left+" to "+right+" ("+mid+")");
if (right==left){
//System.out.println("* "+array[targetIndex]);
//result=array[targetIndex];
return;
}
if(left < right) {
double s = array[mid];
int i = left - 1;
int j = right + 1;
while(true) {
while(array[++i] < s) ;
while(array[--j] > s) ;
if(i >= j)
break;
swap(array, i, j);
}
//System.out.println("2 parts: "+left+"-"+(i-1)+" and "+(j+1)+"-"+right);
if (i>index){
// the target index in the left partition
//System.out.println("left partition");
locate(array, left, i-1,index);
}
else{
// the target index in the right partition
//System.out.println("right partition");
locate(array, j+1, right,index);
}
}
}
private void swap(double[] array, int i, int j) {
double t = array[i];
array[i] = array[j];
array[j] = t;
}
} | Java |
package com.musicg.math.rank;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class MapRankShort implements MapRank{
private Map map;
private boolean acsending=true;
public MapRankShort(Map<?,Short> map, boolean acsending){
this.map=map;
this.acsending=acsending;
}
public List getOrderedKeyList(int numKeys, boolean sharpLimit){ // if sharp limited, will return sharp numKeys, otherwise will return until the values not equals the exact key's value
Set mapEntrySet=map.entrySet();
List keyList=new LinkedList();
// if the numKeys is larger than map size, limit it
if (numKeys>map.size()){
numKeys=map.size();
}
// end if the numKeys is larger than map size, limit it
if (map.size()>0){
short[] array=new short[map.size()];
int count=0;
// get the pass values
Iterator<Entry> mapIterator=mapEntrySet.iterator();
while (mapIterator.hasNext()){
Entry entry=mapIterator.next();
array[count++]=(Short)entry.getValue();
}
// end get the pass values
int targetindex;
if (acsending){
targetindex=numKeys;
}
else{
targetindex=array.length-numKeys;
}
short passValue=getOrderedValue(array,targetindex); // this value is the value of the numKey-th element
// get the passed keys and values
Map passedMap=new HashMap();
List<Short> valueList=new LinkedList<Short>();
mapIterator=mapEntrySet.iterator();
while (mapIterator.hasNext()){
Entry entry=mapIterator.next();
short value=(Short)entry.getValue();
if ((acsending && value<=passValue) || (!acsending && value>=passValue)){
passedMap.put(entry.getKey(), value);
valueList.add(value);
}
}
// end get the passed keys and values
// sort the value list
Short[] listArr=new Short[valueList.size()];
valueList.toArray(listArr);
Arrays.sort(listArr);
// end sort the value list
// get the list of keys
int resultCount=0;
int index;
if (acsending){
index=0;
}
else{
index=listArr.length-1;
}
if (!sharpLimit){
numKeys=listArr.length;
}
while (true){
short targetValue=(Short)listArr[index];
Iterator<Entry> passedMapIterator=passedMap.entrySet().iterator();
while(passedMapIterator.hasNext()){
Entry entry=passedMapIterator.next();
if ((Short)entry.getValue()==targetValue){
keyList.add(entry.getKey());
passedMapIterator.remove();
resultCount++;
break;
}
}
if (acsending){
index++;
}
else{
index--;
}
if (resultCount>=numKeys){
break;
}
}
// end get the list of keys
}
return keyList;
}
private short getOrderedValue(short[] array, int index){
locate(array,0,array.length-1,index);
return array[index];
}
// sort the partitions by quick sort, and locate the target index
private void locate(short[] array, int left, int right, int index) {
int mid=(left+right)/2;
//System.out.println(left+" to "+right+" ("+mid+")");
if (right==left){
//System.out.println("* "+array[targetIndex]);
//result=array[targetIndex];
return;
}
if(left < right) {
short s = array[mid];
int i = left - 1;
int j = right + 1;
while(true) {
while(array[++i] < s) ;
while(array[--j] > s) ;
if(i >= j)
break;
swap(array, i, j);
}
//System.out.println("2 parts: "+left+"-"+(i-1)+" and "+(j+1)+"-"+right);
if (i>index){
// the target index in the left partition
//System.out.println("left partition");
locate(array, left, i-1,index);
}
else{
// the target index in the right partition
//System.out.println("right partition");
locate(array, j+1, right,index);
}
}
}
private void swap(short[] array, int i, int j) {
short t = array[i];
array[i] = array[j];
array[j] = t;
}
} | Java |
/*
* Copyright (C) 2011 Jacquet Wong
*
* 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.musicg.math.rank;
public class ArrayRankDouble {
/**
* Get the index position of maximum value the given array
* @param array
* @return index of the max value in array
*/
public int getMaxValueIndex(double[] array) {
int index = 0;
double max = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
index = i;
}
}
return index;
}
/**
* Get the index position of minimum value in the given array
* @param array
* @return index of the min value in array
*/
public int getMinValueIndex(double[] array) {
int index = 0;
double min = Integer.MAX_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
index = i;
}
}
return index;
}
/**
* Get the n-th value in the array after sorted
* @param array
* @param n
* @param ascending is ascending order or not
* @return
*/
public double getNthOrderedValue(double[] array, int n, boolean ascending) {
if (n > array.length) {
n = array.length;
}
int targetindex;
if (ascending) {
targetindex = n;
} else {
targetindex = array.length - n;
}
// this value is the value of the numKey-th element
double passValue = getOrderedValue(array, targetindex);
return passValue;
}
private double getOrderedValue(double[] array, int index) {
locate(array, 0, array.length - 1, index);
return array[index];
}
// sort the partitions by quick sort, and locate the target index
private void locate(double[] array, int left, int right, int index) {
int mid = (left + right) / 2;
// System.out.println(left+" to "+right+" ("+mid+")");
if (right == left) {
// System.out.println("* "+array[targetIndex]);
// result=array[targetIndex];
return;
}
if (left < right) {
double s = array[mid];
int i = left - 1;
int j = right + 1;
while (true) {
while (array[++i] < s)
;
while (array[--j] > s)
;
if (i >= j)
break;
swap(array, i, j);
}
// System.out.println("2 parts: "+left+"-"+(i-1)+" and "+(j+1)+"-"+right);
if (i > index) {
// the target index in the left partition
// System.out.println("left partition");
locate(array, left, i - 1, index);
} else {
// the target index in the right partition
// System.out.println("right partition");
locate(array, j + 1, right, index);
}
}
}
private void swap(double[] array, int i, int j) {
double t = array[i];
array[i] = array[j];
array[j] = t;
}
} | Java |
package com.musicg.math.quicksort;
public class QuickSortDouble extends QuickSort{
private int[] indexes;
private double[] array;
public QuickSortDouble(double[] array){
this.array=array;
indexes=new int[array.length];
for (int i=0; i<indexes.length; i++){
indexes[i]=i;
}
}
public int[] getSortIndexes(){
sort();
return indexes;
}
private void sort() {
quicksort(array, indexes, 0, indexes.length - 1);
}
// quicksort a[left] to a[right]
private void quicksort(double[] a, int[] indexes, int left, int right) {
if (right <= left) return;
int i = partition(a, indexes, left, right);
quicksort(a, indexes, left, i-1);
quicksort(a, indexes, i+1, right);
}
// partition a[left] to a[right], assumes left < right
private int partition(double[] a, int[] indexes, int left, int right) {
int i = left - 1;
int j = right;
while (true) {
while (a[indexes[++i]]<a[indexes[right]]); // find item on left to swap, a[right] acts as sentinel
while (a[indexes[right]]<a[indexes[--j]]){ // find item on right to swap
if (j == left) break; // don't go out-of-bounds
}
if (i >= j) break; // check if pointers cross
swap(a, indexes, i, j); // swap two elements into place
}
swap(a, indexes, i, right); // swap with partition element
return i;
}
// exchange a[i] and a[j]
private void swap(double[] a, int[] indexes, int i, int j) {
int swap = indexes[i];
indexes[i] = indexes[j];
indexes[j] = swap;
}
} | Java |
package com.musicg.math.quicksort;
public abstract class QuickSort{
public abstract int[] getSortIndexes();
} | Java |
package com.musicg.math.quicksort;
public class QuickSortIndexPreserved {
private QuickSort quickSort;
public QuickSortIndexPreserved(int[] array){
quickSort=new QuickSortInteger(array);
}
public QuickSortIndexPreserved(double[] array){
quickSort=new QuickSortDouble(array);
}
public QuickSortIndexPreserved(short[] array){
quickSort=new QuickSortShort(array);
}
public int[] getSortIndexes(){
return quickSort.getSortIndexes();
}
} | Java |
package com.musicg.math.quicksort;
public class QuickSortShort extends QuickSort{
private int[] indexes;
private short[] array;
public QuickSortShort(short[] array){
this.array=array;
indexes=new int[array.length];
for (int i=0; i<indexes.length; i++){
indexes[i]=i;
}
}
public int[] getSortIndexes(){
sort();
return indexes;
}
private void sort() {
quicksort(array, indexes, 0, indexes.length - 1);
}
// quicksort a[left] to a[right]
private void quicksort(short[] a, int[] indexes, int left, int right) {
if (right <= left) return;
int i = partition(a, indexes, left, right);
quicksort(a, indexes, left, i-1);
quicksort(a, indexes, i+1, right);
}
// partition a[left] to a[right], assumes left < right
private int partition(short[] a, int[] indexes, int left, int right) {
int i = left - 1;
int j = right;
while (true) {
while (a[indexes[++i]]<a[indexes[right]]); // find item on left to swap, a[right] acts as sentinel
while (a[indexes[right]]<a[indexes[--j]]){ // find item on right to swap
if (j == left) break; // don't go out-of-bounds
}
if (i >= j) break; // check if pointers cross
swap(a, indexes, i, j); // swap two elements into place
}
swap(a, indexes, i, right); // swap with partition element
return i;
}
// exchange a[i] and a[j]
private void swap(short[] a, int[] indexes, int i, int j) {
int swap = indexes[i];
indexes[i] = indexes[j];
indexes[j] = swap;
}
} | Java |
package com.musicg.math.quicksort;
public class QuickSortInteger extends QuickSort{
private int[] indexes;
private int[] array;
public QuickSortInteger(int[] array){
this.array=array;
indexes=new int[array.length];
for (int i=0; i<indexes.length; i++){
indexes[i]=i;
}
}
public int[] getSortIndexes(){
sort();
return indexes;
}
private void sort() {
quicksort(array, indexes, 0, indexes.length - 1);
}
// quicksort a[left] to a[right]
private void quicksort(int[] a, int[] indexes, int left, int right) {
if (right <= left) return;
int i = partition(a, indexes, left, right);
quicksort(a, indexes, left, i-1);
quicksort(a, indexes, i+1, right);
}
// partition a[left] to a[right], assumes left < right
private int partition(int[] a, int[] indexes, int left, int right) {
int i = left - 1;
int j = right;
while (true) {
while (a[indexes[++i]]<a[indexes[right]]); // find item on left to swap, a[right] acts as sentinel
while (a[indexes[right]]<a[indexes[--j]]){ // find item on right to swap
if (j == left) break; // don't go out-of-bounds
}
if (i >= j) break; // check if pointers cross
swap(a, indexes, i, j); // swap two elements into place
}
swap(a, indexes, i, right); // swap with partition element
return i;
}
// exchange a[i] and a[j]
private void swap(int[] a, int[] indexes, int i, int j) {
int swap = indexes[i];
indexes[i] = indexes[j];
indexes[j] = swap;
}
} | Java |
package com.musicg.wave;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import com.musicg.api.WhistleApi;
public class WaveTypeDetector {
private Wave wave;
public WaveTypeDetector(Wave wave) {
this.wave = wave;
}
public double getWhistleProbability() {
double probability = 0;
WaveHeader wavHeader = wave.getWaveHeader();
// fft size 1024, no overlap
int fftSampleSize = 1024;
int fftSignalByteLength = fftSampleSize * wavHeader.getBitsPerSample() / 8;
byte[] audioBytes = wave.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(audioBytes);
WhistleApi whistleApi = new WhistleApi(wavHeader);
// read the byte signals
try {
int numFrames = inputStream.available() / fftSignalByteLength;
byte[] bytes = new byte[fftSignalByteLength];
int checkLength = 3;
int passScore = 3;
ArrayList<Boolean> bufferList = new ArrayList<Boolean>();
int numWhistles = 0;
int numPasses = 0;
// first 10(checkLength) frames
for (int frameNumber = 0; frameNumber < checkLength; frameNumber++) {
inputStream.read(bytes);
boolean isWhistle = whistleApi.isWhistle(bytes);
bufferList.add(isWhistle);
if (isWhistle) {
numWhistles++;
}
if (numWhistles >= passScore) {
numPasses++;
}
// System.out.println(frameNumber+": "+numWhistles);
}
// other frames
for (int frameNumber = checkLength; frameNumber < numFrames; frameNumber++) {
inputStream.read(bytes);
boolean isWhistle = whistleApi.isWhistle(bytes);
if (bufferList.get(0)) {
numWhistles--;
}
bufferList.remove(0);
bufferList.add(isWhistle);
if (isWhistle) {
numWhistles++;
}
if (numWhistles >= passScore) {
numPasses++;
}
// System.out.println(frameNumber+": "+numWhistles);
}
probability = (double) numPasses / numFrames;
} catch (IOException e) {
e.printStackTrace();
}
return probability;
}
} | Java |
/*
* Copyright (C) 2011 Jacquet Wong
*
* 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.musicg.wave;
import java.io.IOException;
import java.io.InputStream;
/**
* WAV File Specification
* https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
*
* @author Jacquet Wong
*/
public class WaveHeader {
public static final String RIFF_HEADER = "RIFF";
public static final String WAVE_HEADER = "WAVE";
public static final String FMT_HEADER = "fmt ";
public static final String DATA_HEADER = "data";
public static final int HEADER_BYTE_LENGTH = 44; // 44 bytes for header
private boolean valid;
private String chunkId; // 4 bytes
private long chunkSize; // unsigned 4 bytes, little endian
private String format; // 4 bytes
private String subChunk1Id; // 4 bytes
private long subChunk1Size; // unsigned 4 bytes, little endian
private int audioFormat; // unsigned 2 bytes, little endian
private int channels; // unsigned 2 bytes, little endian
private long sampleRate; // unsigned 4 bytes, little endian
private long byteRate; // unsigned 4 bytes, little endian
private int blockAlign; // unsigned 2 bytes, little endian
private int bitsPerSample; // unsigned 2 bytes, little endian
private String subChunk2Id; // 4 bytes
private long subChunk2Size; // unsigned 4 bytes, little endian
public WaveHeader(){
// init a 8k 16bit mono wav
chunkSize=36;
subChunk1Size=16;
audioFormat=1;
channels=1;
sampleRate=8000;
byteRate=16000;
blockAlign=2;
bitsPerSample=16;
subChunk2Size=0;
valid=true;
}
public WaveHeader(InputStream inputStream) {
valid = loadHeader(inputStream);
}
private boolean loadHeader(InputStream inputStream) {
byte[] headerBuffer = new byte[HEADER_BYTE_LENGTH];
try {
inputStream.read(headerBuffer);
// read header
int pointer = 0;
chunkId = new String(new byte[] { headerBuffer[pointer++],
headerBuffer[pointer++], headerBuffer[pointer++],
headerBuffer[pointer++] });
// little endian
chunkSize = (long) (headerBuffer[pointer++] & 0xff)
| (long) (headerBuffer[pointer++] & 0xff) << 8
| (long) (headerBuffer[pointer++] & 0xff) << 16
| (long) (headerBuffer[pointer++] & 0xff << 24);
format = new String(new byte[] { headerBuffer[pointer++],
headerBuffer[pointer++], headerBuffer[pointer++],
headerBuffer[pointer++] });
subChunk1Id = new String(new byte[] { headerBuffer[pointer++],
headerBuffer[pointer++], headerBuffer[pointer++],
headerBuffer[pointer++] });
subChunk1Size = (long) (headerBuffer[pointer++] & 0xff)
| (long) (headerBuffer[pointer++] & 0xff) << 8
| (long) (headerBuffer[pointer++] & 0xff) << 16
| (long) (headerBuffer[pointer++] & 0xff) << 24;
audioFormat = (int) ((headerBuffer[pointer++] & 0xff) | (headerBuffer[pointer++] & 0xff) << 8);
channels = (int) ((headerBuffer[pointer++] & 0xff) | (headerBuffer[pointer++] & 0xff) << 8);
sampleRate = (long) (headerBuffer[pointer++] & 0xff)
| (long) (headerBuffer[pointer++] & 0xff) << 8
| (long) (headerBuffer[pointer++] & 0xff) << 16
| (long) (headerBuffer[pointer++] & 0xff) << 24;
byteRate = (long) (headerBuffer[pointer++] & 0xff)
| (long) (headerBuffer[pointer++] & 0xff) << 8
| (long) (headerBuffer[pointer++] & 0xff) << 16
| (long) (headerBuffer[pointer++] & 0xff) << 24;
blockAlign = (int) ((headerBuffer[pointer++] & 0xff) | (headerBuffer[pointer++] & 0xff) << 8);
bitsPerSample = (int) ((headerBuffer[pointer++] & 0xff) | (headerBuffer[pointer++] & 0xff) << 8);
subChunk2Id = new String(new byte[] { headerBuffer[pointer++],
headerBuffer[pointer++], headerBuffer[pointer++],
headerBuffer[pointer++] });
subChunk2Size = (long) (headerBuffer[pointer++] & 0xff)
| (long) (headerBuffer[pointer++] & 0xff) << 8
| (long) (headerBuffer[pointer++] & 0xff) << 16
| (long) (headerBuffer[pointer++] & 0xff) << 24;
// end read header
// the inputStream should be closed outside this method
// dis.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
if (bitsPerSample!=8 && bitsPerSample!=16){
System.err.println("WaveHeader: only supports bitsPerSample 8 or 16");
return false;
}
// check the format is support
if (chunkId.toUpperCase().equals(RIFF_HEADER)
&& format.toUpperCase().equals(WAVE_HEADER) && audioFormat == 1) {
return true;
}
else{
System.err.println("WaveHeader: Unsupported header format");
}
return false;
}
public boolean isValid() {
return valid;
}
public String getChunkId() {
return chunkId;
}
public long getChunkSize() {
return chunkSize;
}
public String getFormat() {
return format;
}
public String getSubChunk1Id() {
return subChunk1Id;
}
public long getSubChunk1Size() {
return subChunk1Size;
}
public int getAudioFormat() {
return audioFormat;
}
public int getChannels() {
return channels;
}
public int getSampleRate() {
return (int) sampleRate;
}
public int getByteRate() {
return (int) byteRate;
}
public int getBlockAlign() {
return blockAlign;
}
public int getBitsPerSample() {
return bitsPerSample;
}
public String getSubChunk2Id() {
return subChunk2Id;
}
public long getSubChunk2Size() {
return subChunk2Size;
}
public void setSampleRate(int sampleRate){
int newSubChunk2Size = (int)(this.subChunk2Size * sampleRate / this.sampleRate);
// if num bytes for each sample is even, the size of newSubChunk2Size also needed to be in even number
if ((bitsPerSample/8)%2==0){
if (newSubChunk2Size%2!=0){
newSubChunk2Size++;
}
}
this.sampleRate = sampleRate;
this.byteRate = sampleRate*bitsPerSample/8;
this.chunkSize = newSubChunk2Size+36;
this.subChunk2Size = newSubChunk2Size;
}
public void setChunkId(String chunkId) {
this.chunkId = chunkId;
}
public void setChunkSize(long chunkSize) {
this.chunkSize = chunkSize;
}
public void setFormat(String format) {
this.format = format;
}
public void setSubChunk1Id(String subChunk1Id) {
this.subChunk1Id = subChunk1Id;
}
public void setSubChunk1Size(long subChunk1Size) {
this.subChunk1Size = subChunk1Size;
}
public void setAudioFormat(int audioFormat) {
this.audioFormat = audioFormat;
}
public void setChannels(int channels) {
this.channels = channels;
}
public void setByteRate(long byteRate) {
this.byteRate = byteRate;
}
public void setBlockAlign(int blockAlign) {
this.blockAlign = blockAlign;
}
public void setBitsPerSample(int bitsPerSample) {
this.bitsPerSample = bitsPerSample;
}
public void setSubChunk2Id(String subChunk2Id) {
this.subChunk2Id = subChunk2Id;
}
public void setSubChunk2Size(long subChunk2Size) {
this.subChunk2Size = subChunk2Size;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("chunkId: " + chunkId);
sb.append("\n");
sb.append("chunkSize: " + chunkSize);
sb.append("\n");
sb.append("format: " + format);
sb.append("\n");
sb.append("subChunk1Id: " + subChunk1Id);
sb.append("\n");
sb.append("subChunk1Size: " + subChunk1Size);
sb.append("\n");
sb.append("audioFormat: " + audioFormat);
sb.append("\n");
sb.append("channels: " + channels);
sb.append("\n");
sb.append("sampleRate: " + sampleRate);
sb.append("\n");
sb.append("byteRate: " + byteRate);
sb.append("\n");
sb.append("blockAlign: " + blockAlign);
sb.append("\n");
sb.append("bitsPerSample: " + bitsPerSample);
sb.append("\n");
sb.append("subChunk2Id: " + subChunk2Id);
sb.append("\n");
sb.append("subChunk2Size: " + subChunk2Size);
return sb.toString();
}
} | Java |
/*
* Copyright (C) 2011 Jacquet Wong
*
* 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.musicg.wave;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import com.musicg.fingerprint.FingerprintManager;
import com.musicg.fingerprint.FingerprintSimilarity;
import com.musicg.fingerprint.FingerprintSimilarityComputer;
import com.musicg.wave.extension.NormalizedSampleAmplitudes;
import com.musicg.wave.extension.Spectrogram;
/**
* Read WAVE headers and data from wave input stream
*
* @author Jacquet Wong
*/
public class Wave implements Serializable{
private static final long serialVersionUID = 1L;
private WaveHeader waveHeader;
private byte[] data; // little endian
private byte[] fingerprint;
/**
* Constructor
*
*/
public Wave() {
this.waveHeader=new WaveHeader();
this.data=new byte[0];
}
/**
* Constructor
*
* @param filename
* Wave file
*/
public Wave(String filename) {
try {
InputStream inputStream = new FileInputStream(filename);
initWaveWithInputStream(inputStream);
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Constructor
*
* @param inputStream
* Wave file input stream
*/
public Wave(InputStream inputStream) {
initWaveWithInputStream(inputStream);
}
/**
* Constructor
*
* @param WaveHeader
* waveHeader
* @param byte[]
* data
*/
public Wave(WaveHeader waveHeader, byte[] data) {
this.waveHeader = waveHeader;
this.data = data;
}
private void initWaveWithInputStream(InputStream inputStream) {
// reads the first 44 bytes for header
waveHeader = new WaveHeader(inputStream);
if (waveHeader.isValid()) {
// load data
try {
data = new byte[inputStream.available()];
inputStream.read(data);
} catch (IOException e) {
e.printStackTrace();
}
// end load data
} else {
System.err.println("Invalid Wave Header");
}
}
/**
* Trim the wave data
*
* @param leftTrimNumberOfSample
* Number of sample trimmed from beginning
* @param rightTrimNumberOfSample
* Number of sample trimmed from ending
*/
public void trim(int leftTrimNumberOfSample, int rightTrimNumberOfSample) {
long chunkSize = waveHeader.getChunkSize();
long subChunk2Size = waveHeader.getSubChunk2Size();
long totalTrimmed = leftTrimNumberOfSample + rightTrimNumberOfSample;
if (totalTrimmed > subChunk2Size) {
leftTrimNumberOfSample = (int) subChunk2Size;
}
// update wav info
chunkSize -= totalTrimmed;
subChunk2Size -= totalTrimmed;
if (chunkSize>=0 && subChunk2Size>=0){
waveHeader.setChunkSize(chunkSize);
waveHeader.setSubChunk2Size(subChunk2Size);
byte[] trimmedData = new byte[(int) subChunk2Size];
System.arraycopy(data, (int) leftTrimNumberOfSample, trimmedData, 0,
(int) subChunk2Size);
data = trimmedData;
}
else{
System.err.println("Trim error: Negative length");
}
}
/**
* Trim the wave data from beginning
*
* @param numberOfSample
* numberOfSample trimmed from beginning
*/
public void leftTrim(int numberOfSample) {
trim(numberOfSample, 0);
}
/**
* Trim the wave data from ending
*
* @param numberOfSample
* numberOfSample trimmed from ending
*/
public void rightTrim(int numberOfSample) {
trim(0, numberOfSample);
}
/**
* Trim the wave data
*
* @param leftTrimSecond
* Seconds trimmed from beginning
* @param rightTrimSecond
* Seconds trimmed from ending
*/
public void trim(double leftTrimSecond, double rightTrimSecond) {
int sampleRate = waveHeader.getSampleRate();
int bitsPerSample = waveHeader.getBitsPerSample();
int channels = waveHeader.getChannels();
int leftTrimNumberOfSample = (int) (sampleRate * bitsPerSample / 8
* channels * leftTrimSecond);
int rightTrimNumberOfSample = (int) (sampleRate * bitsPerSample / 8
* channels * rightTrimSecond);
trim(leftTrimNumberOfSample, rightTrimNumberOfSample);
}
/**
* Trim the wave data from beginning
*
* @param second
* Seconds trimmed from beginning
*/
public void leftTrim(double second) {
trim(second, 0);
}
/**
* Trim the wave data from ending
*
* @param second
* Seconds trimmed from ending
*/
public void rightTrim(double second) {
trim(0, second);
}
/**
* Get the wave header
*
* @return waveHeader
*/
public WaveHeader getWaveHeader() {
return waveHeader;
}
/**
* Get the wave spectrogram
*
* @return spectrogram
*/
public Spectrogram getSpectrogram(){
return new Spectrogram(this);
}
/**
* Get the wave spectrogram
*
* @param fftSampleSize number of sample in fft, the value needed to be a number to power of 2
* @param overlapFactor 1/overlapFactor overlapping, e.g. 1/4=25% overlapping, 0 for no overlapping
*
* @return spectrogram
*/
public Spectrogram getSpectrogram(int fftSampleSize, int overlapFactor) {
return new Spectrogram(this,fftSampleSize,overlapFactor);
}
/**
* Get the wave data in bytes
*
* @return wave data
*/
public byte[] getBytes() {
return data;
}
/**
* Data byte size of the wave excluding header size
*
* @return byte size of the wave
*/
public int size() {
return data.length;
}
/**
* Length of the wave in second
*
* @return length in second
*/
public float length() {
float second = (float) waveHeader.getSubChunk2Size() / waveHeader.getByteRate();
return second;
}
/**
* Timestamp of the wave length
*
* @return timestamp
*/
public String timestamp() {
float totalSeconds = this.length();
float second = totalSeconds % 60;
int minute = (int) totalSeconds / 60 % 60;
int hour = (int) (totalSeconds / 3600);
StringBuffer sb = new StringBuffer();
if (hour > 0) {
sb.append(hour + ":");
}
if (minute > 0) {
sb.append(minute + ":");
}
sb.append(second);
return sb.toString();
}
/**
* Get the amplitudes of the wave samples (depends on the header)
*
* @return amplitudes array (signed 16-bit)
*/
public short[] getSampleAmplitudes(){
int bytePerSample = waveHeader.getBitsPerSample() / 8;
int numSamples = data.length / bytePerSample;
short[] amplitudes = new short[numSamples];
int pointer = 0;
for (int i = 0; i < numSamples; i++) {
short amplitude = 0;
for (int byteNumber = 0; byteNumber < bytePerSample; byteNumber++) {
// little endian
amplitude |= (short) ((data[pointer++] & 0xFF) << (byteNumber * 8));
}
amplitudes[i] = amplitude;
}
return amplitudes;
}
public String toString(){
StringBuffer sb=new StringBuffer(waveHeader.toString());
sb.append("\n");
sb.append("length: " + timestamp());
return sb.toString();
}
public double[] getNormalizedAmplitudes() {
NormalizedSampleAmplitudes amplitudes=new NormalizedSampleAmplitudes(this);
return amplitudes.getNormalizedAmplitudes();
}
public byte[] getFingerprint(){
if (fingerprint==null){
FingerprintManager fingerprintManager=new FingerprintManager();
fingerprint=fingerprintManager.extractFingerprint(this);
}
return fingerprint;
}
public FingerprintSimilarity getFingerprintSimilarity(Wave wave){
FingerprintSimilarityComputer fingerprintSimilarityComputer=new FingerprintSimilarityComputer(this.getFingerprint(),wave.getFingerprint());
return fingerprintSimilarityComputer.getFingerprintsSimilarity();
}
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.