repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/model/Token.java
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PUSH = "pipush"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public enum State { // UNFINISHED("unfinished"), // ROLLING_OUT("rolling_out"), // FINISHED("finished"), // AUTHENTICATING("authenticating"); // // String state; // State(String state) { // this.state = state; // } // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TOTP = "totp";
import java.util.ArrayList; import java.util.Date; import static it.netknights.piauthenticator.utils.AppConstants.PUSH; import static it.netknights.piauthenticator.utils.AppConstants.State; import static it.netknights.piauthenticator.utils.AppConstants.State.UNFINISHED; import static it.netknights.piauthenticator.utils.AppConstants.TOTP;
/* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.model; public class Token { private String currentOTP; private byte[] secret; private String label; private String type; private int digits; private int period; private String algorithm = "HmacSHA1"; //default is SHA1 private int counter; private boolean withPIN = false; private boolean isLocked = false; private String pin = ""; private boolean withTapToShow = false; private boolean tapped = false; private boolean persistent = false; private String serial; public String enrollment_credential; public Date rollout_expiration; public String rollout_url; public boolean sslVerify = true; public boolean lastAuthHadError = false; private ArrayList<PushAuthRequest> pendingAuths = new ArrayList<>();
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PUSH = "pipush"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public enum State { // UNFINISHED("unfinished"), // ROLLING_OUT("rolling_out"), // FINISHED("finished"), // AUTHENTICATING("authenticating"); // // String state; // State(String state) { // this.state = state; // } // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TOTP = "totp"; // Path: app/src/main/java/it/netknights/piauthenticator/model/Token.java import java.util.ArrayList; import java.util.Date; import static it.netknights.piauthenticator.utils.AppConstants.PUSH; import static it.netknights.piauthenticator.utils.AppConstants.State; import static it.netknights.piauthenticator.utils.AppConstants.State.UNFINISHED; import static it.netknights.piauthenticator.utils.AppConstants.TOTP; /* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.model; public class Token { private String currentOTP; private byte[] secret; private String label; private String type; private int digits; private int period; private String algorithm = "HmacSHA1"; //default is SHA1 private int counter; private boolean withPIN = false; private boolean isLocked = false; private String pin = ""; private boolean withTapToShow = false; private boolean tapped = false; private boolean persistent = false; private String serial; public String enrollment_credential; public Date rollout_expiration; public String rollout_url; public boolean sslVerify = true; public boolean lastAuthHadError = false; private ArrayList<PushAuthRequest> pendingAuths = new ArrayList<>();
public State state = UNFINISHED;
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/model/Token.java
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PUSH = "pipush"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public enum State { // UNFINISHED("unfinished"), // ROLLING_OUT("rolling_out"), // FINISHED("finished"), // AUTHENTICATING("authenticating"); // // String state; // State(String state) { // this.state = state; // } // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TOTP = "totp";
import java.util.ArrayList; import java.util.Date; import static it.netknights.piauthenticator.utils.AppConstants.PUSH; import static it.netknights.piauthenticator.utils.AppConstants.State; import static it.netknights.piauthenticator.utils.AppConstants.State.UNFINISHED; import static it.netknights.piauthenticator.utils.AppConstants.TOTP;
/* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.model; public class Token { private String currentOTP; private byte[] secret; private String label; private String type; private int digits; private int period; private String algorithm = "HmacSHA1"; //default is SHA1 private int counter; private boolean withPIN = false; private boolean isLocked = false; private String pin = ""; private boolean withTapToShow = false; private boolean tapped = false; private boolean persistent = false; private String serial; public String enrollment_credential; public Date rollout_expiration; public String rollout_url; public boolean sslVerify = true; public boolean lastAuthHadError = false; private ArrayList<PushAuthRequest> pendingAuths = new ArrayList<>(); public State state = UNFINISHED; public Token(byte[] secret, String serial, String label, String type, int digits) { this.secret = secret; this.serial = serial; this.label = label; this.type = type; this.digits = digits;
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PUSH = "pipush"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public enum State { // UNFINISHED("unfinished"), // ROLLING_OUT("rolling_out"), // FINISHED("finished"), // AUTHENTICATING("authenticating"); // // String state; // State(String state) { // this.state = state; // } // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TOTP = "totp"; // Path: app/src/main/java/it/netknights/piauthenticator/model/Token.java import java.util.ArrayList; import java.util.Date; import static it.netknights.piauthenticator.utils.AppConstants.PUSH; import static it.netknights.piauthenticator.utils.AppConstants.State; import static it.netknights.piauthenticator.utils.AppConstants.State.UNFINISHED; import static it.netknights.piauthenticator.utils.AppConstants.TOTP; /* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.model; public class Token { private String currentOTP; private byte[] secret; private String label; private String type; private int digits; private int period; private String algorithm = "HmacSHA1"; //default is SHA1 private int counter; private boolean withPIN = false; private boolean isLocked = false; private String pin = ""; private boolean withTapToShow = false; private boolean tapped = false; private boolean persistent = false; private String serial; public String enrollment_credential; public Date rollout_expiration; public String rollout_url; public boolean sslVerify = true; public boolean lastAuthHadError = false; private ArrayList<PushAuthRequest> pendingAuths = new ArrayList<>(); public State state = UNFINISHED; public Token(byte[] secret, String serial, String label, String type, int digits) { this.secret = secret; this.serial = serial; this.label = label; this.type = type; this.digits = digits;
this.period = this.type.equals(TOTP) ? 30 : 0;
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/model/Token.java
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PUSH = "pipush"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public enum State { // UNFINISHED("unfinished"), // ROLLING_OUT("rolling_out"), // FINISHED("finished"), // AUTHENTICATING("authenticating"); // // String state; // State(String state) { // this.state = state; // } // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TOTP = "totp";
import java.util.ArrayList; import java.util.Date; import static it.netknights.piauthenticator.utils.AppConstants.PUSH; import static it.netknights.piauthenticator.utils.AppConstants.State; import static it.netknights.piauthenticator.utils.AppConstants.State.UNFINISHED; import static it.netknights.piauthenticator.utils.AppConstants.TOTP;
this.counter = 0; } public ArrayList<PushAuthRequest> getPendingAuths() { return pendingAuths; } /** * Add the request if it is not yet present. Comparison is by notificationID and signature. * * @param request Request that should be added * @return true if successful, false if not (duplicate) */ public boolean addPushAuthRequest(PushAuthRequest request) { for (PushAuthRequest req : pendingAuths) { if (req.getNotificationID() == request.getNotificationID() && req.getSignature().equals(request.getSignature())) { return false; } } pendingAuths.add(request); return true; } public void setPendingAuths(ArrayList<PushAuthRequest> pendingAuths) { this.pendingAuths = pendingAuths; } // A push token only contains the serial and a label public Token(String serial, String label) {
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PUSH = "pipush"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public enum State { // UNFINISHED("unfinished"), // ROLLING_OUT("rolling_out"), // FINISHED("finished"), // AUTHENTICATING("authenticating"); // // String state; // State(String state) { // this.state = state; // } // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TOTP = "totp"; // Path: app/src/main/java/it/netknights/piauthenticator/model/Token.java import java.util.ArrayList; import java.util.Date; import static it.netknights.piauthenticator.utils.AppConstants.PUSH; import static it.netknights.piauthenticator.utils.AppConstants.State; import static it.netknights.piauthenticator.utils.AppConstants.State.UNFINISHED; import static it.netknights.piauthenticator.utils.AppConstants.TOTP; this.counter = 0; } public ArrayList<PushAuthRequest> getPendingAuths() { return pendingAuths; } /** * Add the request if it is not yet present. Comparison is by notificationID and signature. * * @param request Request that should be added * @return true if successful, false if not (duplicate) */ public boolean addPushAuthRequest(PushAuthRequest request) { for (PushAuthRequest req : pendingAuths) { if (req.getNotificationID() == request.getNotificationID() && req.getSignature().equals(request.getSignature())) { return false; } } pendingAuths.add(request); return true; } public void setPendingAuths(ArrayList<PushAuthRequest> pendingAuths) { this.pendingAuths = pendingAuths; } // A push token only contains the serial and a label public Token(String serial, String label) {
type = PUSH;
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint;
/* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.utils; public class Endpoint { private boolean sslVerify; private String url; private Map<String, String> data;
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // } // Path: app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint; /* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.utils; public class Endpoint { private boolean sslVerify; private String url; private Map<String, String> data;
private EndpointCallback callback;
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint;
/* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.utils; public class Endpoint { private boolean sslVerify; private String url; private Map<String, String> data; private EndpointCallback callback; public Endpoint(boolean sslVerify, String url, Map<String, String> data, EndpointCallback callback) { this.sslVerify = sslVerify; this.url = url; this.data = data; this.callback = callback; } /** * Establishes a connection to the URL specified in the Constructor. * The data is sent as POST Parameters. * * @return true if the request could be sent, false if not */ public boolean connect() {
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // } // Path: app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint; /* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.utils; public class Endpoint { private boolean sslVerify; private String url; private Map<String, String> data; private EndpointCallback callback; public Endpoint(boolean sslVerify, String url, Map<String, String> data, EndpointCallback callback) { this.sslVerify = sslVerify; this.url = url; this.data = data; this.callback = callback; } /** * Establishes a connection to the URL specified in the Constructor. * The data is sent as POST Parameters. * * @return true if the request could be sent, false if not */ public boolean connect() {
logprint("Setting up connection to " + url);
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint;
/* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.utils; public class Endpoint { private boolean sslVerify; private String url; private Map<String, String> data; private EndpointCallback callback; public Endpoint(boolean sslVerify, String url, Map<String, String> data, EndpointCallback callback) { this.sslVerify = sslVerify; this.url = url; this.data = data; this.callback = callback; } /** * Establishes a connection to the URL specified in the Constructor. * The data is sent as POST Parameters. * * @return true if the request could be sent, false if not */ public boolean connect() { logprint("Setting up connection to " + url); URL url; try { url = new URL(this.url); } catch (MalformedURLException e) {
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // } // Path: app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint; /* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.utils; public class Endpoint { private boolean sslVerify; private String url; private Map<String, String> data; private EndpointCallback callback; public Endpoint(boolean sslVerify, String url, Map<String, String> data, EndpointCallback callback) { this.sslVerify = sslVerify; this.url = url; this.data = data; this.callback = callback; } /** * Establishes a connection to the URL specified in the Constructor. * The data is sent as POST Parameters. * * @return true if the request could be sent, false if not */ public boolean connect() { logprint("Setting up connection to " + url); URL url; try { url = new URL(this.url); } catch (MalformedURLException e) {
callback.updateStatus(STATUS_ENDPOINT_MALFORMED_URL);
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint;
* @return true if the request could be sent, false if not */ public boolean connect() { logprint("Setting up connection to " + url); URL url; try { url = new URL(this.url); } catch (MalformedURLException e) { callback.updateStatus(STATUS_ENDPOINT_MALFORMED_URL); e.printStackTrace(); return false; } HttpURLConnection con; try { if (url.getProtocol().equals("https")) { con = (HttpsURLConnection) url.openConnection(); } else { con = (HttpURLConnection) url.openConnection(); } } catch (IOException e) { e.printStackTrace(); return false; } con.setDoOutput(true); con.setDoInput(true); try { con.setRequestMethod("POST"); } catch (ProtocolException e) { e.printStackTrace(); }
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // } // Path: app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint; * @return true if the request could be sent, false if not */ public boolean connect() { logprint("Setting up connection to " + url); URL url; try { url = new URL(this.url); } catch (MalformedURLException e) { callback.updateStatus(STATUS_ENDPOINT_MALFORMED_URL); e.printStackTrace(); return false; } HttpURLConnection con; try { if (url.getProtocol().equals("https")) { con = (HttpsURLConnection) url.openConnection(); } else { con = (HttpURLConnection) url.openConnection(); } } catch (IOException e) { e.printStackTrace(); return false; } con.setDoOutput(true); con.setDoInput(true); try { con.setRequestMethod("POST"); } catch (ProtocolException e) { e.printStackTrace(); }
con.setReadTimeout(READ_TIMEOUT);
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint;
*/ public boolean connect() { logprint("Setting up connection to " + url); URL url; try { url = new URL(this.url); } catch (MalformedURLException e) { callback.updateStatus(STATUS_ENDPOINT_MALFORMED_URL); e.printStackTrace(); return false; } HttpURLConnection con; try { if (url.getProtocol().equals("https")) { con = (HttpsURLConnection) url.openConnection(); } else { con = (HttpURLConnection) url.openConnection(); } } catch (IOException e) { e.printStackTrace(); return false; } con.setDoOutput(true); con.setDoInput(true); try { con.setRequestMethod("POST"); } catch (ProtocolException e) { e.printStackTrace(); } con.setReadTimeout(READ_TIMEOUT);
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // } // Path: app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint; */ public boolean connect() { logprint("Setting up connection to " + url); URL url; try { url = new URL(this.url); } catch (MalformedURLException e) { callback.updateStatus(STATUS_ENDPOINT_MALFORMED_URL); e.printStackTrace(); return false; } HttpURLConnection con; try { if (url.getProtocol().equals("https")) { con = (HttpsURLConnection) url.openConnection(); } else { con = (HttpURLConnection) url.openConnection(); } } catch (IOException e) { e.printStackTrace(); return false; } con.setDoOutput(true); con.setDoInput(true); try { con.setRequestMethod("POST"); } catch (ProtocolException e) { e.printStackTrace(); } con.setReadTimeout(READ_TIMEOUT);
con.setConnectTimeout(CONNECT_TIMEOUT);
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint;
HttpURLConnection con; try { if (url.getProtocol().equals("https")) { con = (HttpsURLConnection) url.openConnection(); } else { con = (HttpURLConnection) url.openConnection(); } } catch (IOException e) { e.printStackTrace(); return false; } con.setDoOutput(true); con.setDoInput(true); try { con.setRequestMethod("POST"); } catch (ProtocolException e) { e.printStackTrace(); } con.setReadTimeout(READ_TIMEOUT); con.setConnectTimeout(CONNECT_TIMEOUT); if (!sslVerify && (con instanceof HttpsURLConnection)) { con = turnOffSSLVerification((HttpsURLConnection) con); } logprint("Sending..."); OutputStream os; try { os = con.getOutputStream(); } catch (SSLHandshakeException e) { e.printStackTrace();
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // } // Path: app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint; HttpURLConnection con; try { if (url.getProtocol().equals("https")) { con = (HttpsURLConnection) url.openConnection(); } else { con = (HttpURLConnection) url.openConnection(); } } catch (IOException e) { e.printStackTrace(); return false; } con.setDoOutput(true); con.setDoInput(true); try { con.setRequestMethod("POST"); } catch (ProtocolException e) { e.printStackTrace(); } con.setReadTimeout(READ_TIMEOUT); con.setConnectTimeout(CONNECT_TIMEOUT); if (!sslVerify && (con instanceof HttpsURLConnection)) { con = turnOffSSLVerification((HttpsURLConnection) con); } logprint("Sending..."); OutputStream os; try { os = con.getOutputStream(); } catch (SSLHandshakeException e) { e.printStackTrace();
callback.updateStatus(STATUS_ENDPOINT_SSL_ERROR);
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint;
} else { con = (HttpURLConnection) url.openConnection(); } } catch (IOException e) { e.printStackTrace(); return false; } con.setDoOutput(true); con.setDoInput(true); try { con.setRequestMethod("POST"); } catch (ProtocolException e) { e.printStackTrace(); } con.setReadTimeout(READ_TIMEOUT); con.setConnectTimeout(CONNECT_TIMEOUT); if (!sslVerify && (con instanceof HttpsURLConnection)) { con = turnOffSSLVerification((HttpsURLConnection) con); } logprint("Sending..."); OutputStream os; try { os = con.getOutputStream(); } catch (SSLHandshakeException e) { e.printStackTrace(); callback.updateStatus(STATUS_ENDPOINT_SSL_ERROR); return false; } catch (IOException e) { e.printStackTrace();
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // } // Path: app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint; } else { con = (HttpURLConnection) url.openConnection(); } } catch (IOException e) { e.printStackTrace(); return false; } con.setDoOutput(true); con.setDoInput(true); try { con.setRequestMethod("POST"); } catch (ProtocolException e) { e.printStackTrace(); } con.setReadTimeout(READ_TIMEOUT); con.setConnectTimeout(CONNECT_TIMEOUT); if (!sslVerify && (con instanceof HttpsURLConnection)) { con = turnOffSSLVerification((HttpsURLConnection) con); } logprint("Sending..."); OutputStream os; try { os = con.getOutputStream(); } catch (SSLHandshakeException e) { e.printStackTrace(); callback.updateStatus(STATUS_ENDPOINT_SSL_ERROR); return false; } catch (IOException e) { e.printStackTrace();
callback.updateStatus(STATUS_ENDPOINT_UNKNOWN_HOST);
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint;
writer.write(toSend); toSend = "&"; } writer.flush(); writer.close(); os.close(); con.connect(); } catch (IOException e) { e.printStackTrace(); } logprint("Getting response..."); int responsecode = 0; try { responsecode = con.getResponseCode(); } catch (IOException e) { e.printStackTrace(); } logprint("response code: " + responsecode); BufferedReader br; String line; StringBuilder response = new StringBuilder(); try { br = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((line = br.readLine()) != null) { response.append(line); } logprint("response: " + response.toString()); callback.responseReceived(response.toString(), responsecode); } catch (IOException e) {
// Path: app/src/main/java/it/netknights/piauthenticator/interfaces/EndpointCallback.java // public interface EndpointCallback { // void updateStatus(int statusCode); // // void responseReceived(String response, int responseCode); // } // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int CONNECT_TIMEOUT = 15000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int READ_TIMEOUT = 10000; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_ERROR = 4005; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_MALFORMED_URL = 4003; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_SSL_ERROR = 4006; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int STATUS_ENDPOINT_UNKNOWN_HOST = 4002; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // } // Path: app/src/main/java/it/netknights/piauthenticator/utils/Endpoint.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import it.netknights.piauthenticator.interfaces.EndpointCallback; import static it.netknights.piauthenticator.utils.AppConstants.CONNECT_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.READ_TIMEOUT; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_MALFORMED_URL; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_SSL_ERROR; import static it.netknights.piauthenticator.utils.AppConstants.STATUS_ENDPOINT_UNKNOWN_HOST; import static it.netknights.piauthenticator.utils.Util.logprint; writer.write(toSend); toSend = "&"; } writer.flush(); writer.close(); os.close(); con.connect(); } catch (IOException e) { e.printStackTrace(); } logprint("Getting response..."); int responsecode = 0; try { responsecode = con.getResponseCode(); } catch (IOException e) { e.printStackTrace(); } logprint("response code: " + responsecode); BufferedReader br; String line; StringBuilder response = new StringBuilder(); try { br = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((line = br.readLine()) != null) { response.append(line); } logprint("response: " + response.toString()); callback.responseReceived(response.toString(), responsecode); } catch (IOException e) {
callback.updateStatus(STATUS_ENDPOINT_ERROR);
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/utils/SecretKeyWrapper.java
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String KEY_WRAP_ALGORITHM = "RSA/ECB/PKCS1Padding"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // }
import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.security.KeyPairGeneratorSpec; import androidx.annotation.RequiresApi; import java.io.IOException; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.UnrecoverableEntryException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.util.Calendar; import java.util.GregorianCalendar; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.security.auth.x500.X500Principal; import static it.netknights.piauthenticator.utils.AppConstants.KEY_WRAP_ALGORITHM; import static it.netknights.piauthenticator.utils.Util.logprint;
/* Parts from The Android Open Source Project * Copyright (C) 2013 The Android Open Source Project * * privacyIDEA Authenticator * * Authors: Nils Behlen <nils.behlen@netknights.it> * * Copyright (c) 2017-2019 NetKnights GmbH * * 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 it.netknights.piauthenticator.utils; /** * Wraps {@link SecretKey} instances using a public/private key pair stored in * the platform {@link KeyStore}. This allows us to protect symmetric keys with * hardware-backed crypto, if provided by the device. * <p> * See <a href="http://en.wikipedia.org/wiki/Key_Wrap">key wrapping</a> for more * details. * <p> * Not inherently thread safe. */ public class SecretKeyWrapper { private final Cipher mCipher; private final KeyPair mPair; /** * Create a wrapper using the public/private key pair with the given alias. * If no pair with that alias exists, it will be generated. */ @SuppressLint("GetInstance") public SecretKeyWrapper(Context context) throws GeneralSecurityException, IOException {
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String KEY_WRAP_ALGORITHM = "RSA/ECB/PKCS1Padding"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // } // Path: app/src/main/java/it/netknights/piauthenticator/utils/SecretKeyWrapper.java import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.security.KeyPairGeneratorSpec; import androidx.annotation.RequiresApi; import java.io.IOException; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.UnrecoverableEntryException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.util.Calendar; import java.util.GregorianCalendar; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.security.auth.x500.X500Principal; import static it.netknights.piauthenticator.utils.AppConstants.KEY_WRAP_ALGORITHM; import static it.netknights.piauthenticator.utils.Util.logprint; /* Parts from The Android Open Source Project * Copyright (C) 2013 The Android Open Source Project * * privacyIDEA Authenticator * * Authors: Nils Behlen <nils.behlen@netknights.it> * * Copyright (c) 2017-2019 NetKnights GmbH * * 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 it.netknights.piauthenticator.utils; /** * Wraps {@link SecretKey} instances using a public/private key pair stored in * the platform {@link KeyStore}. This allows us to protect symmetric keys with * hardware-backed crypto, if provided by the device. * <p> * See <a href="http://en.wikipedia.org/wiki/Key_Wrap">key wrapping</a> for more * details. * <p> * Not inherently thread safe. */ public class SecretKeyWrapper { private final Cipher mCipher; private final KeyPair mPair; /** * Create a wrapper using the public/private key pair with the given alias. * If no pair with that alias exists, it will be generated. */ @SuppressLint("GetInstance") public SecretKeyWrapper(Context context) throws GeneralSecurityException, IOException {
mCipher = Cipher.getInstance(KEY_WRAP_ALGORITHM);
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/utils/SecretKeyWrapper.java
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String KEY_WRAP_ALGORITHM = "RSA/ECB/PKCS1Padding"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // }
import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.security.KeyPairGeneratorSpec; import androidx.annotation.RequiresApi; import java.io.IOException; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.UnrecoverableEntryException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.util.Calendar; import java.util.GregorianCalendar; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.security.auth.x500.X500Principal; import static it.netknights.piauthenticator.utils.AppConstants.KEY_WRAP_ALGORITHM; import static it.netknights.piauthenticator.utils.Util.logprint;
mCipher.init(Cipher.WRAP_MODE, mPair.getPublic()); return mCipher.wrap(key); } /** * Unwrap a {@link SecretKey} using the private key assigned to this * wrapper. * * @param blob a wrapped {@link SecretKey} as previously returned by * {@link #wrap(SecretKey)}. */ public SecretKey unwrap(byte[] blob) throws GeneralSecurityException { mCipher.init(Cipher.UNWRAP_MODE, mPair.getPrivate()); return (SecretKey) mCipher.unwrap(blob, "AES", Cipher.SECRET_KEY); } /** * Generate a KeyPair and store it with the given alias in the KeyStore. * Return the PublicKey * * @param alias the alias to store the key with * @param context needed for KeyPairGeneratorSpec * @return the PublicKey of the just generated KeyPair */ @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static PublicKey generateKeyPair(String alias, Context context) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, NoSuchProviderException, InvalidAlgorithmParameterException, UnrecoverableEntryException { final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null);
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String KEY_WRAP_ALGORITHM = "RSA/ECB/PKCS1Padding"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // } // Path: app/src/main/java/it/netknights/piauthenticator/utils/SecretKeyWrapper.java import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.security.KeyPairGeneratorSpec; import androidx.annotation.RequiresApi; import java.io.IOException; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.UnrecoverableEntryException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.util.Calendar; import java.util.GregorianCalendar; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.security.auth.x500.X500Principal; import static it.netknights.piauthenticator.utils.AppConstants.KEY_WRAP_ALGORITHM; import static it.netknights.piauthenticator.utils.Util.logprint; mCipher.init(Cipher.WRAP_MODE, mPair.getPublic()); return mCipher.wrap(key); } /** * Unwrap a {@link SecretKey} using the private key assigned to this * wrapper. * * @param blob a wrapped {@link SecretKey} as previously returned by * {@link #wrap(SecretKey)}. */ public SecretKey unwrap(byte[] blob) throws GeneralSecurityException { mCipher.init(Cipher.UNWRAP_MODE, mPair.getPrivate()); return (SecretKey) mCipher.unwrap(blob, "AES", Cipher.SECRET_KEY); } /** * Generate a KeyPair and store it with the given alias in the KeyStore. * Return the PublicKey * * @param alias the alias to store the key with * @param context needed for KeyPairGeneratorSpec * @return the PublicKey of the just generated KeyPair */ @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static PublicKey generateKeyPair(String alias, Context context) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, NoSuchProviderException, InvalidAlgorithmParameterException, UnrecoverableEntryException { final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null);
logprint("generateKeyPair for alias: " + alias);
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/viewcontroller/EnterDetailsActivity.java
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String ALGORITHM = "algorithm"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS = "digits"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS_6_STR = "6"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS_8_STR = "8"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String LABEL = "label"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD = "period"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int PERIOD_30 = 30; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD_30_STR = "30s"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int PERIOD_60 = 60; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD_60_STR = "60s"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SECRET = "secret"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA1 = "SHA1"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA256 = "SHA256"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA512 = "SHA512"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TOTP = "totp"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TYPE = "type"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String WITHPIN = "withpin";
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.constraintlayout.widget.ConstraintLayout; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Base32; import org.apache.commons.codec.binary.Hex; import it.netknights.piauthenticator.R; import static android.view.View.GONE; import static it.netknights.piauthenticator.R.color.PIBLUE; import static it.netknights.piauthenticator.utils.AppConstants.ALGORITHM; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS_6_STR; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS_8_STR; import static it.netknights.piauthenticator.utils.AppConstants.LABEL; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_30; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_30_STR; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_60; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_60_STR; import static it.netknights.piauthenticator.utils.AppConstants.SECRET; import static it.netknights.piauthenticator.utils.AppConstants.SHA1; import static it.netknights.piauthenticator.utils.AppConstants.SHA256; import static it.netknights.piauthenticator.utils.AppConstants.SHA512; import static it.netknights.piauthenticator.utils.AppConstants.TOTP; import static it.netknights.piauthenticator.utils.AppConstants.TYPE; import static it.netknights.piauthenticator.utils.AppConstants.WITHPIN;
private String new_label; private byte[] new_secret; private String new_algorithm; private String new_type; private int new_period; private int new_digits; private boolean new_withpin = false; private RadioButton currentSelectedEncoding = null; TableLayout tl; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_enter_detail); setupButtons(); paintStatusbar(); setupActionBar(); setupTable(); getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); } private void setupTable() { tl = findViewById(R.id.tableLayout); final int supportspinnerid = R.layout.support_simple_spinner_dropdown_item; String[] types = {"HOTP", "TOTP"}; String[] periods = {PERIOD_30_STR, PERIOD_60_STR};
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String ALGORITHM = "algorithm"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS = "digits"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS_6_STR = "6"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS_8_STR = "8"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String LABEL = "label"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD = "period"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int PERIOD_30 = 30; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD_30_STR = "30s"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int PERIOD_60 = 60; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD_60_STR = "60s"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SECRET = "secret"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA1 = "SHA1"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA256 = "SHA256"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA512 = "SHA512"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TOTP = "totp"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TYPE = "type"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String WITHPIN = "withpin"; // Path: app/src/main/java/it/netknights/piauthenticator/viewcontroller/EnterDetailsActivity.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.constraintlayout.widget.ConstraintLayout; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Base32; import org.apache.commons.codec.binary.Hex; import it.netknights.piauthenticator.R; import static android.view.View.GONE; import static it.netknights.piauthenticator.R.color.PIBLUE; import static it.netknights.piauthenticator.utils.AppConstants.ALGORITHM; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS_6_STR; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS_8_STR; import static it.netknights.piauthenticator.utils.AppConstants.LABEL; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_30; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_30_STR; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_60; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_60_STR; import static it.netknights.piauthenticator.utils.AppConstants.SECRET; import static it.netknights.piauthenticator.utils.AppConstants.SHA1; import static it.netknights.piauthenticator.utils.AppConstants.SHA256; import static it.netknights.piauthenticator.utils.AppConstants.SHA512; import static it.netknights.piauthenticator.utils.AppConstants.TOTP; import static it.netknights.piauthenticator.utils.AppConstants.TYPE; import static it.netknights.piauthenticator.utils.AppConstants.WITHPIN; private String new_label; private byte[] new_secret; private String new_algorithm; private String new_type; private int new_period; private int new_digits; private boolean new_withpin = false; private RadioButton currentSelectedEncoding = null; TableLayout tl; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_enter_detail); setupButtons(); paintStatusbar(); setupActionBar(); setupTable(); getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); } private void setupTable() { tl = findViewById(R.id.tableLayout); final int supportspinnerid = R.layout.support_simple_spinner_dropdown_item; String[] types = {"HOTP", "TOTP"}; String[] periods = {PERIOD_30_STR, PERIOD_60_STR};
String[] algorithms = {SHA1, SHA256, SHA512};
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/viewcontroller/EnterDetailsActivity.java
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String ALGORITHM = "algorithm"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS = "digits"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS_6_STR = "6"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS_8_STR = "8"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String LABEL = "label"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD = "period"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int PERIOD_30 = 30; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD_30_STR = "30s"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int PERIOD_60 = 60; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD_60_STR = "60s"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SECRET = "secret"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA1 = "SHA1"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA256 = "SHA256"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA512 = "SHA512"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TOTP = "totp"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TYPE = "type"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String WITHPIN = "withpin";
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.constraintlayout.widget.ConstraintLayout; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Base32; import org.apache.commons.codec.binary.Hex; import it.netknights.piauthenticator.R; import static android.view.View.GONE; import static it.netknights.piauthenticator.R.color.PIBLUE; import static it.netknights.piauthenticator.utils.AppConstants.ALGORITHM; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS_6_STR; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS_8_STR; import static it.netknights.piauthenticator.utils.AppConstants.LABEL; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_30; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_30_STR; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_60; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_60_STR; import static it.netknights.piauthenticator.utils.AppConstants.SECRET; import static it.netknights.piauthenticator.utils.AppConstants.SHA1; import static it.netknights.piauthenticator.utils.AppConstants.SHA256; import static it.netknights.piauthenticator.utils.AppConstants.SHA512; import static it.netknights.piauthenticator.utils.AppConstants.TOTP; import static it.netknights.piauthenticator.utils.AppConstants.TYPE; import static it.netknights.piauthenticator.utils.AppConstants.WITHPIN;
private String new_label; private byte[] new_secret; private String new_algorithm; private String new_type; private int new_period; private int new_digits; private boolean new_withpin = false; private RadioButton currentSelectedEncoding = null; TableLayout tl; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_enter_detail); setupButtons(); paintStatusbar(); setupActionBar(); setupTable(); getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); } private void setupTable() { tl = findViewById(R.id.tableLayout); final int supportspinnerid = R.layout.support_simple_spinner_dropdown_item; String[] types = {"HOTP", "TOTP"}; String[] periods = {PERIOD_30_STR, PERIOD_60_STR};
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String ALGORITHM = "algorithm"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS = "digits"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS_6_STR = "6"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS_8_STR = "8"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String LABEL = "label"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD = "period"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int PERIOD_30 = 30; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD_30_STR = "30s"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int PERIOD_60 = 60; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD_60_STR = "60s"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SECRET = "secret"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA1 = "SHA1"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA256 = "SHA256"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA512 = "SHA512"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TOTP = "totp"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TYPE = "type"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String WITHPIN = "withpin"; // Path: app/src/main/java/it/netknights/piauthenticator/viewcontroller/EnterDetailsActivity.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.constraintlayout.widget.ConstraintLayout; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Base32; import org.apache.commons.codec.binary.Hex; import it.netknights.piauthenticator.R; import static android.view.View.GONE; import static it.netknights.piauthenticator.R.color.PIBLUE; import static it.netknights.piauthenticator.utils.AppConstants.ALGORITHM; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS_6_STR; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS_8_STR; import static it.netknights.piauthenticator.utils.AppConstants.LABEL; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_30; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_30_STR; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_60; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_60_STR; import static it.netknights.piauthenticator.utils.AppConstants.SECRET; import static it.netknights.piauthenticator.utils.AppConstants.SHA1; import static it.netknights.piauthenticator.utils.AppConstants.SHA256; import static it.netknights.piauthenticator.utils.AppConstants.SHA512; import static it.netknights.piauthenticator.utils.AppConstants.TOTP; import static it.netknights.piauthenticator.utils.AppConstants.TYPE; import static it.netknights.piauthenticator.utils.AppConstants.WITHPIN; private String new_label; private byte[] new_secret; private String new_algorithm; private String new_type; private int new_period; private int new_digits; private boolean new_withpin = false; private RadioButton currentSelectedEncoding = null; TableLayout tl; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_enter_detail); setupButtons(); paintStatusbar(); setupActionBar(); setupTable(); getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); } private void setupTable() { tl = findViewById(R.id.tableLayout); final int supportspinnerid = R.layout.support_simple_spinner_dropdown_item; String[] types = {"HOTP", "TOTP"}; String[] periods = {PERIOD_30_STR, PERIOD_60_STR};
String[] algorithms = {SHA1, SHA256, SHA512};
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/viewcontroller/EnterDetailsActivity.java
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String ALGORITHM = "algorithm"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS = "digits"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS_6_STR = "6"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS_8_STR = "8"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String LABEL = "label"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD = "period"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int PERIOD_30 = 30; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD_30_STR = "30s"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int PERIOD_60 = 60; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD_60_STR = "60s"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SECRET = "secret"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA1 = "SHA1"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA256 = "SHA256"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA512 = "SHA512"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TOTP = "totp"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TYPE = "type"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String WITHPIN = "withpin";
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.constraintlayout.widget.ConstraintLayout; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Base32; import org.apache.commons.codec.binary.Hex; import it.netknights.piauthenticator.R; import static android.view.View.GONE; import static it.netknights.piauthenticator.R.color.PIBLUE; import static it.netknights.piauthenticator.utils.AppConstants.ALGORITHM; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS_6_STR; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS_8_STR; import static it.netknights.piauthenticator.utils.AppConstants.LABEL; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_30; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_30_STR; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_60; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_60_STR; import static it.netknights.piauthenticator.utils.AppConstants.SECRET; import static it.netknights.piauthenticator.utils.AppConstants.SHA1; import static it.netknights.piauthenticator.utils.AppConstants.SHA256; import static it.netknights.piauthenticator.utils.AppConstants.SHA512; import static it.netknights.piauthenticator.utils.AppConstants.TOTP; import static it.netknights.piauthenticator.utils.AppConstants.TYPE; import static it.netknights.piauthenticator.utils.AppConstants.WITHPIN;
private String new_label; private byte[] new_secret; private String new_algorithm; private String new_type; private int new_period; private int new_digits; private boolean new_withpin = false; private RadioButton currentSelectedEncoding = null; TableLayout tl; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_enter_detail); setupButtons(); paintStatusbar(); setupActionBar(); setupTable(); getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); } private void setupTable() { tl = findViewById(R.id.tableLayout); final int supportspinnerid = R.layout.support_simple_spinner_dropdown_item; String[] types = {"HOTP", "TOTP"}; String[] periods = {PERIOD_30_STR, PERIOD_60_STR};
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String ALGORITHM = "algorithm"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS = "digits"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS_6_STR = "6"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String DIGITS_8_STR = "8"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String LABEL = "label"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD = "period"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int PERIOD_30 = 30; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD_30_STR = "30s"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final int PERIOD_60 = 60; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PERIOD_60_STR = "60s"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SECRET = "secret"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA1 = "SHA1"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA256 = "SHA256"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SHA512 = "SHA512"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TOTP = "totp"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String TYPE = "type"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String WITHPIN = "withpin"; // Path: app/src/main/java/it/netknights/piauthenticator/viewcontroller/EnterDetailsActivity.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.constraintlayout.widget.ConstraintLayout; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Base32; import org.apache.commons.codec.binary.Hex; import it.netknights.piauthenticator.R; import static android.view.View.GONE; import static it.netknights.piauthenticator.R.color.PIBLUE; import static it.netknights.piauthenticator.utils.AppConstants.ALGORITHM; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS_6_STR; import static it.netknights.piauthenticator.utils.AppConstants.DIGITS_8_STR; import static it.netknights.piauthenticator.utils.AppConstants.LABEL; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_30; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_30_STR; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_60; import static it.netknights.piauthenticator.utils.AppConstants.PERIOD_60_STR; import static it.netknights.piauthenticator.utils.AppConstants.SECRET; import static it.netknights.piauthenticator.utils.AppConstants.SHA1; import static it.netknights.piauthenticator.utils.AppConstants.SHA256; import static it.netknights.piauthenticator.utils.AppConstants.SHA512; import static it.netknights.piauthenticator.utils.AppConstants.TOTP; import static it.netknights.piauthenticator.utils.AppConstants.TYPE; import static it.netknights.piauthenticator.utils.AppConstants.WITHPIN; private String new_label; private byte[] new_secret; private String new_algorithm; private String new_type; private int new_period; private int new_digits; private boolean new_withpin = false; private RadioButton currentSelectedEncoding = null; TableLayout tl; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_enter_detail); setupButtons(); paintStatusbar(); setupActionBar(); setupTable(); getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); } private void setupTable() { tl = findViewById(R.id.tableLayout); final int supportspinnerid = R.layout.support_simple_spinner_dropdown_item; String[] types = {"HOTP", "TOTP"}; String[] periods = {PERIOD_30_STR, PERIOD_60_STR};
String[] algorithms = {SHA1, SHA256, SHA512};
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/viewcontroller/MainActivityBroadcastReceiver.java
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String INTENT_FILTER = "privacyIDEAAuthenticator"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SERIAL = "serial"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SIGNATURE = "signature"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import static it.netknights.piauthenticator.utils.AppConstants.INTENT_FILTER; import static it.netknights.piauthenticator.utils.AppConstants.SERIAL; import static it.netknights.piauthenticator.utils.AppConstants.SIGNATURE; import static it.netknights.piauthenticator.utils.Util.logprint;
/* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.viewcontroller; public class MainActivityBroadcastReceiver extends BroadcastReceiver { private MainActivity main;
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String INTENT_FILTER = "privacyIDEAAuthenticator"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SERIAL = "serial"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SIGNATURE = "signature"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // } // Path: app/src/main/java/it/netknights/piauthenticator/viewcontroller/MainActivityBroadcastReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import static it.netknights.piauthenticator.utils.AppConstants.INTENT_FILTER; import static it.netknights.piauthenticator.utils.AppConstants.SERIAL; import static it.netknights.piauthenticator.utils.AppConstants.SIGNATURE; import static it.netknights.piauthenticator.utils.Util.logprint; /* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.viewcontroller; public class MainActivityBroadcastReceiver extends BroadcastReceiver { private MainActivity main;
public IntentFilter intentFilter = new IntentFilter(INTENT_FILTER);
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/viewcontroller/MainActivityBroadcastReceiver.java
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String INTENT_FILTER = "privacyIDEAAuthenticator"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SERIAL = "serial"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SIGNATURE = "signature"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import static it.netknights.piauthenticator.utils.AppConstants.INTENT_FILTER; import static it.netknights.piauthenticator.utils.AppConstants.SERIAL; import static it.netknights.piauthenticator.utils.AppConstants.SIGNATURE; import static it.netknights.piauthenticator.utils.Util.logprint;
/* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.viewcontroller; public class MainActivityBroadcastReceiver extends BroadcastReceiver { private MainActivity main; public IntentFilter intentFilter = new IntentFilter(INTENT_FILTER); public MainActivityBroadcastReceiver(MainActivity main) { this.main = main; } @Override public void onReceive(Context context, Intent intent) { if (main != null) { if (intent.hasExtra("finished")) {
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String INTENT_FILTER = "privacyIDEAAuthenticator"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SERIAL = "serial"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SIGNATURE = "signature"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // } // Path: app/src/main/java/it/netknights/piauthenticator/viewcontroller/MainActivityBroadcastReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import static it.netknights.piauthenticator.utils.AppConstants.INTENT_FILTER; import static it.netknights.piauthenticator.utils.AppConstants.SERIAL; import static it.netknights.piauthenticator.utils.AppConstants.SIGNATURE; import static it.netknights.piauthenticator.utils.Util.logprint; /* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.viewcontroller; public class MainActivityBroadcastReceiver extends BroadcastReceiver { private MainActivity main; public IntentFilter intentFilter = new IntentFilter(INTENT_FILTER); public MainActivityBroadcastReceiver(MainActivity main) { this.main = main; } @Override public void onReceive(Context context, Intent intent) { if (main != null) { if (intent.hasExtra("finished")) {
main.pushAuthFinishedFor(intent.getStringExtra(SERIAL), intent.getIntExtra("finished", 654321),
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/viewcontroller/MainActivityBroadcastReceiver.java
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String INTENT_FILTER = "privacyIDEAAuthenticator"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SERIAL = "serial"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SIGNATURE = "signature"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import static it.netknights.piauthenticator.utils.AppConstants.INTENT_FILTER; import static it.netknights.piauthenticator.utils.AppConstants.SERIAL; import static it.netknights.piauthenticator.utils.AppConstants.SIGNATURE; import static it.netknights.piauthenticator.utils.Util.logprint;
/* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.viewcontroller; public class MainActivityBroadcastReceiver extends BroadcastReceiver { private MainActivity main; public IntentFilter intentFilter = new IntentFilter(INTENT_FILTER); public MainActivityBroadcastReceiver(MainActivity main) { this.main = main; } @Override public void onReceive(Context context, Intent intent) { if (main != null) { if (intent.hasExtra("finished")) { main.pushAuthFinishedFor(intent.getStringExtra(SERIAL), intent.getIntExtra("finished", 654321),
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String INTENT_FILTER = "privacyIDEAAuthenticator"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SERIAL = "serial"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SIGNATURE = "signature"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // } // Path: app/src/main/java/it/netknights/piauthenticator/viewcontroller/MainActivityBroadcastReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import static it.netknights.piauthenticator.utils.AppConstants.INTENT_FILTER; import static it.netknights.piauthenticator.utils.AppConstants.SERIAL; import static it.netknights.piauthenticator.utils.AppConstants.SIGNATURE; import static it.netknights.piauthenticator.utils.Util.logprint; /* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.viewcontroller; public class MainActivityBroadcastReceiver extends BroadcastReceiver { private MainActivity main; public IntentFilter intentFilter = new IntentFilter(INTENT_FILTER); public MainActivityBroadcastReceiver(MainActivity main) { this.main = main; } @Override public void onReceive(Context context, Intent intent) { if (main != null) { if (intent.hasExtra("finished")) { main.pushAuthFinishedFor(intent.getStringExtra(SERIAL), intent.getIntExtra("finished", 654321),
intent.getStringExtra(SIGNATURE), intent.getBooleanExtra("success", false));
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/viewcontroller/MainActivityBroadcastReceiver.java
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String INTENT_FILTER = "privacyIDEAAuthenticator"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SERIAL = "serial"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SIGNATURE = "signature"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import static it.netknights.piauthenticator.utils.AppConstants.INTENT_FILTER; import static it.netknights.piauthenticator.utils.AppConstants.SERIAL; import static it.netknights.piauthenticator.utils.AppConstants.SIGNATURE; import static it.netknights.piauthenticator.utils.Util.logprint;
/* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.viewcontroller; public class MainActivityBroadcastReceiver extends BroadcastReceiver { private MainActivity main; public IntentFilter intentFilter = new IntentFilter(INTENT_FILTER); public MainActivityBroadcastReceiver(MainActivity main) { this.main = main; } @Override public void onReceive(Context context, Intent intent) { if (main != null) { if (intent.hasExtra("finished")) { main.pushAuthFinishedFor(intent.getStringExtra(SERIAL), intent.getIntExtra("finished", 654321), intent.getStringExtra(SIGNATURE), intent.getBooleanExtra("success", false)); } else if (intent.hasExtra("running")) { main.pushAuthStartedFor(intent.getStringExtra(SERIAL), intent.getIntExtra("running", 654321), intent.getStringExtra(SIGNATURE)); } else {
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String INTENT_FILTER = "privacyIDEAAuthenticator"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SERIAL = "serial"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String SIGNATURE = "signature"; // // Path: app/src/main/java/it/netknights/piauthenticator/utils/Util.java // public static void logprint(String msg) { // if (BuildConfig.DEBUG) { // if (msg == null) // return; // Log.e(TAG, msg); // } // } // Path: app/src/main/java/it/netknights/piauthenticator/viewcontroller/MainActivityBroadcastReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import static it.netknights.piauthenticator.utils.AppConstants.INTENT_FILTER; import static it.netknights.piauthenticator.utils.AppConstants.SERIAL; import static it.netknights.piauthenticator.utils.AppConstants.SIGNATURE; import static it.netknights.piauthenticator.utils.Util.logprint; /* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.viewcontroller; public class MainActivityBroadcastReceiver extends BroadcastReceiver { private MainActivity main; public IntentFilter intentFilter = new IntentFilter(INTENT_FILTER); public MainActivityBroadcastReceiver(MainActivity main) { this.main = main; } @Override public void onReceive(Context context, Intent intent) { if (main != null) { if (intent.hasExtra("finished")) { main.pushAuthFinishedFor(intent.getStringExtra(SERIAL), intent.getIntExtra("finished", 654321), intent.getStringExtra(SIGNATURE), intent.getBooleanExtra("success", false)); } else if (intent.hasExtra("running")) { main.pushAuthStartedFor(intent.getStringExtra(SERIAL), intent.getIntExtra("running", 654321), intent.getStringExtra(SIGNATURE)); } else {
logprint("broadcastreceiver received push request");
privacyidea/privacyidea-authenticator
app/src/main/java/it/netknights/piauthenticator/model/Model.java
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PUSH = "pipush";
import static it.netknights.piauthenticator.utils.AppConstants.PUSH; import static it.netknights.piauthenticator.utils.AppConstants.State.UNFINISHED; import java.util.ArrayList; import java.util.Date;
/* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.model; public class Model { private ArrayList<Token> tokens; private Token currentSelection; public Model() { this.tokens = new ArrayList<>(); } public Model(ArrayList<Token> tokenlist) { if (tokenlist == null) { this.tokens = new ArrayList<>(); } else { this.tokens = tokenlist; } } public void setCurrentSelection(int position) { if (position == -1) this.currentSelection = null; else this.currentSelection = tokens.get(position); } /** * Checks for Pushtoken whose rollout time has expired. * * @return String with the expired tokens serials or null if there are none */ public String checkForExpiredTokens() { ArrayList<Token> upForDeletion = new ArrayList<>(); Date now = new Date(); for (Token t : tokens) {
// Path: app/src/main/java/it/netknights/piauthenticator/utils/AppConstants.java // public static final String PUSH = "pipush"; // Path: app/src/main/java/it/netknights/piauthenticator/model/Model.java import static it.netknights.piauthenticator.utils.AppConstants.PUSH; import static it.netknights.piauthenticator.utils.AppConstants.State.UNFINISHED; import java.util.ArrayList; import java.util.Date; /* privacyIDEA Authenticator Authors: Nils Behlen <nils.behlen@netknights.it> Copyright (c) 2017-2019 NetKnights GmbH 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 it.netknights.piauthenticator.model; public class Model { private ArrayList<Token> tokens; private Token currentSelection; public Model() { this.tokens = new ArrayList<>(); } public Model(ArrayList<Token> tokenlist) { if (tokenlist == null) { this.tokens = new ArrayList<>(); } else { this.tokens = tokenlist; } } public void setCurrentSelection(int position) { if (position == -1) this.currentSelection = null; else this.currentSelection = tokens.get(position); } /** * Checks for Pushtoken whose rollout time has expired. * * @return String with the expired tokens serials or null if there are none */ public String checkForExpiredTokens() { ArrayList<Token> upForDeletion = new ArrayList<>(); Date now = new Date(); for (Token t : tokens) {
if (t.getType().equals(PUSH)) {
frekele/elasticsearch-mapping-builder
src/test/java/org/frekele/elasticsearch/mapping/EmployeeTest.java
// Path: src/test/java/org/frekele/elasticsearch/mapping/entities/model/EmployeeEntity.java // @ElasticDocument(value = "employee", parent = "person") // public class EmployeeEntity { // // @ElasticLongField // private Long id; // // @ElasticKeywordField // private String documentNumber; // // @ElasticTextField // @ElasticKeywordField // private String registerNumber; // // public EmployeeEntity() { // } // } // // Path: src/test/java/org/frekele/elasticsearch/mapping/entities/model/PersonEntity.java // @ElasticDocument(value = "person") // // public class PersonEntity { // // @ElasticLongField // private Long id; // // @ElasticTextField // @ElasticKeywordField // private String name; // // @ElasticTextField // @ElasticKeywordField // private String fullName; // // @ElasticTextField(copyTo = {"name", "fullName"}) // private String fistName; // // @ElasticTextField(copyTo = {"fullName"}) // private String lastName; // // @ElasticObjectField // private List<AddressEntity> multipleAddress; // // public PersonEntity() { // } // }
import org.frekele.elasticsearch.mapping.entities.model.EmployeeEntity; import org.frekele.elasticsearch.mapping.entities.model.PersonEntity; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.*;
package org.frekele.elasticsearch.mapping; /** * @author frekele - Leandro Kersting de Freitas */ public class EmployeeTest { @BeforeMethod public void setUp() throws Exception { } @AfterMethod public void tearDown() throws Exception { } @Test public void buildEmployeeTest() throws Exception { String expected = "{\"mappings\":{\"person\":{\"properties\":{\"id\":{\"type\":\"long\"},\"name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}},\"fullName\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}},\"fistName\":{\"type\":\"text\",\"copy_to\":[\"name\",\"fullName\"]},\"lastName\":{\"type\":\"text\",\"copy_to\":\"fullName\"},\"multipleAddress\":{\"properties\":{\"postalCode\":{\"type\":\"keyword\"},\"street\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"},\"completion\":{\"type\":\"completion\"}}},\"number\":{\"type\":\"long\"}}}}},\"employee\":{\"_parent\":{\"type\":\"person\"},\"properties\":{\"id\":{\"type\":\"long\"},\"documentNumber\":{\"type\":\"keyword\"},\"registerNumber\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}}}}}}"; MappingBuilderImpl mappingBuilder = new MappingBuilderImpl();
// Path: src/test/java/org/frekele/elasticsearch/mapping/entities/model/EmployeeEntity.java // @ElasticDocument(value = "employee", parent = "person") // public class EmployeeEntity { // // @ElasticLongField // private Long id; // // @ElasticKeywordField // private String documentNumber; // // @ElasticTextField // @ElasticKeywordField // private String registerNumber; // // public EmployeeEntity() { // } // } // // Path: src/test/java/org/frekele/elasticsearch/mapping/entities/model/PersonEntity.java // @ElasticDocument(value = "person") // // public class PersonEntity { // // @ElasticLongField // private Long id; // // @ElasticTextField // @ElasticKeywordField // private String name; // // @ElasticTextField // @ElasticKeywordField // private String fullName; // // @ElasticTextField(copyTo = {"name", "fullName"}) // private String fistName; // // @ElasticTextField(copyTo = {"fullName"}) // private String lastName; // // @ElasticObjectField // private List<AddressEntity> multipleAddress; // // public PersonEntity() { // } // } // Path: src/test/java/org/frekele/elasticsearch/mapping/EmployeeTest.java import org.frekele.elasticsearch.mapping.entities.model.EmployeeEntity; import org.frekele.elasticsearch.mapping.entities.model.PersonEntity; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.*; package org.frekele.elasticsearch.mapping; /** * @author frekele - Leandro Kersting de Freitas */ public class EmployeeTest { @BeforeMethod public void setUp() throws Exception { } @AfterMethod public void tearDown() throws Exception { } @Test public void buildEmployeeTest() throws Exception { String expected = "{\"mappings\":{\"person\":{\"properties\":{\"id\":{\"type\":\"long\"},\"name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}},\"fullName\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}},\"fistName\":{\"type\":\"text\",\"copy_to\":[\"name\",\"fullName\"]},\"lastName\":{\"type\":\"text\",\"copy_to\":\"fullName\"},\"multipleAddress\":{\"properties\":{\"postalCode\":{\"type\":\"keyword\"},\"street\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"},\"completion\":{\"type\":\"completion\"}}},\"number\":{\"type\":\"long\"}}}}},\"employee\":{\"_parent\":{\"type\":\"person\"},\"properties\":{\"id\":{\"type\":\"long\"},\"documentNumber\":{\"type\":\"keyword\"},\"registerNumber\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}}}}}}"; MappingBuilderImpl mappingBuilder = new MappingBuilderImpl();
ObjectMapping result = mappingBuilder.build(PersonEntity.class, EmployeeEntity.class);
frekele/elasticsearch-mapping-builder
src/test/java/org/frekele/elasticsearch/mapping/EmployeeTest.java
// Path: src/test/java/org/frekele/elasticsearch/mapping/entities/model/EmployeeEntity.java // @ElasticDocument(value = "employee", parent = "person") // public class EmployeeEntity { // // @ElasticLongField // private Long id; // // @ElasticKeywordField // private String documentNumber; // // @ElasticTextField // @ElasticKeywordField // private String registerNumber; // // public EmployeeEntity() { // } // } // // Path: src/test/java/org/frekele/elasticsearch/mapping/entities/model/PersonEntity.java // @ElasticDocument(value = "person") // // public class PersonEntity { // // @ElasticLongField // private Long id; // // @ElasticTextField // @ElasticKeywordField // private String name; // // @ElasticTextField // @ElasticKeywordField // private String fullName; // // @ElasticTextField(copyTo = {"name", "fullName"}) // private String fistName; // // @ElasticTextField(copyTo = {"fullName"}) // private String lastName; // // @ElasticObjectField // private List<AddressEntity> multipleAddress; // // public PersonEntity() { // } // }
import org.frekele.elasticsearch.mapping.entities.model.EmployeeEntity; import org.frekele.elasticsearch.mapping.entities.model.PersonEntity; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.*;
package org.frekele.elasticsearch.mapping; /** * @author frekele - Leandro Kersting de Freitas */ public class EmployeeTest { @BeforeMethod public void setUp() throws Exception { } @AfterMethod public void tearDown() throws Exception { } @Test public void buildEmployeeTest() throws Exception { String expected = "{\"mappings\":{\"person\":{\"properties\":{\"id\":{\"type\":\"long\"},\"name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}},\"fullName\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}},\"fistName\":{\"type\":\"text\",\"copy_to\":[\"name\",\"fullName\"]},\"lastName\":{\"type\":\"text\",\"copy_to\":\"fullName\"},\"multipleAddress\":{\"properties\":{\"postalCode\":{\"type\":\"keyword\"},\"street\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"},\"completion\":{\"type\":\"completion\"}}},\"number\":{\"type\":\"long\"}}}}},\"employee\":{\"_parent\":{\"type\":\"person\"},\"properties\":{\"id\":{\"type\":\"long\"},\"documentNumber\":{\"type\":\"keyword\"},\"registerNumber\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}}}}}}"; MappingBuilderImpl mappingBuilder = new MappingBuilderImpl();
// Path: src/test/java/org/frekele/elasticsearch/mapping/entities/model/EmployeeEntity.java // @ElasticDocument(value = "employee", parent = "person") // public class EmployeeEntity { // // @ElasticLongField // private Long id; // // @ElasticKeywordField // private String documentNumber; // // @ElasticTextField // @ElasticKeywordField // private String registerNumber; // // public EmployeeEntity() { // } // } // // Path: src/test/java/org/frekele/elasticsearch/mapping/entities/model/PersonEntity.java // @ElasticDocument(value = "person") // // public class PersonEntity { // // @ElasticLongField // private Long id; // // @ElasticTextField // @ElasticKeywordField // private String name; // // @ElasticTextField // @ElasticKeywordField // private String fullName; // // @ElasticTextField(copyTo = {"name", "fullName"}) // private String fistName; // // @ElasticTextField(copyTo = {"fullName"}) // private String lastName; // // @ElasticObjectField // private List<AddressEntity> multipleAddress; // // public PersonEntity() { // } // } // Path: src/test/java/org/frekele/elasticsearch/mapping/EmployeeTest.java import org.frekele.elasticsearch.mapping.entities.model.EmployeeEntity; import org.frekele.elasticsearch.mapping.entities.model.PersonEntity; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.*; package org.frekele.elasticsearch.mapping; /** * @author frekele - Leandro Kersting de Freitas */ public class EmployeeTest { @BeforeMethod public void setUp() throws Exception { } @AfterMethod public void tearDown() throws Exception { } @Test public void buildEmployeeTest() throws Exception { String expected = "{\"mappings\":{\"person\":{\"properties\":{\"id\":{\"type\":\"long\"},\"name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}},\"fullName\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}},\"fistName\":{\"type\":\"text\",\"copy_to\":[\"name\",\"fullName\"]},\"lastName\":{\"type\":\"text\",\"copy_to\":\"fullName\"},\"multipleAddress\":{\"properties\":{\"postalCode\":{\"type\":\"keyword\"},\"street\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"},\"completion\":{\"type\":\"completion\"}}},\"number\":{\"type\":\"long\"}}}}},\"employee\":{\"_parent\":{\"type\":\"person\"},\"properties\":{\"id\":{\"type\":\"long\"},\"documentNumber\":{\"type\":\"keyword\"},\"registerNumber\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}}}}}}"; MappingBuilderImpl mappingBuilder = new MappingBuilderImpl();
ObjectMapping result = mappingBuilder.build(PersonEntity.class, EmployeeEntity.class);
frekele/elasticsearch-mapping-builder
src/test/java/org/frekele/elasticsearch/mapping/ExceptionTest.java
// Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidCustomJsonException.java // public class InvalidCustomJsonException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidCustomJsonException(String message) { // super(message); // } // // public InvalidCustomJsonException(Throwable cause) { // super(cause); // } // // public InvalidCustomJsonException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidCustomJsonException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidDocumentClassException.java // public class InvalidDocumentClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidDocumentClassException(String message) { // super(message); // } // // public InvalidDocumentClassException(Throwable cause) { // super(cause); // } // // public InvalidDocumentClassException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidDocumentClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MappingBuilderException.java // public class MappingBuilderException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MappingBuilderException(String message) { // super(message); // } // // public MappingBuilderException(Throwable cause) { // super(cause); // } // // public MappingBuilderException(String message, Throwable cause) { // super(message, cause); // } // // public MappingBuilderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MaxRecursiveLevelClassException.java // public class MaxRecursiveLevelClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MaxRecursiveLevelClassException(String message) { // super(message); // } // // public MaxRecursiveLevelClassException(Throwable cause) { // super(cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause) { // super(message, cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import org.frekele.elasticsearch.mapping.exceptions.InvalidCustomJsonException; import org.frekele.elasticsearch.mapping.exceptions.InvalidDocumentClassException; import org.frekele.elasticsearch.mapping.exceptions.MappingBuilderException; import org.frekele.elasticsearch.mapping.exceptions.MaxRecursiveLevelClassException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.IOException;
package org.frekele.elasticsearch.mapping; /** * @author frekele - Leandro Kersting de Freitas */ public class ExceptionTest { @BeforeMethod public void setUp() throws Exception { } @AfterMethod public void tearDown() throws Exception { } //InvalidCustomJsonException
// Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidCustomJsonException.java // public class InvalidCustomJsonException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidCustomJsonException(String message) { // super(message); // } // // public InvalidCustomJsonException(Throwable cause) { // super(cause); // } // // public InvalidCustomJsonException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidCustomJsonException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidDocumentClassException.java // public class InvalidDocumentClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidDocumentClassException(String message) { // super(message); // } // // public InvalidDocumentClassException(Throwable cause) { // super(cause); // } // // public InvalidDocumentClassException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidDocumentClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MappingBuilderException.java // public class MappingBuilderException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MappingBuilderException(String message) { // super(message); // } // // public MappingBuilderException(Throwable cause) { // super(cause); // } // // public MappingBuilderException(String message, Throwable cause) { // super(message, cause); // } // // public MappingBuilderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MaxRecursiveLevelClassException.java // public class MaxRecursiveLevelClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MaxRecursiveLevelClassException(String message) { // super(message); // } // // public MaxRecursiveLevelClassException(Throwable cause) { // super(cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause) { // super(message, cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: src/test/java/org/frekele/elasticsearch/mapping/ExceptionTest.java import org.frekele.elasticsearch.mapping.exceptions.InvalidCustomJsonException; import org.frekele.elasticsearch.mapping.exceptions.InvalidDocumentClassException; import org.frekele.elasticsearch.mapping.exceptions.MappingBuilderException; import org.frekele.elasticsearch.mapping.exceptions.MaxRecursiveLevelClassException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.IOException; package org.frekele.elasticsearch.mapping; /** * @author frekele - Leandro Kersting de Freitas */ public class ExceptionTest { @BeforeMethod public void setUp() throws Exception { } @AfterMethod public void tearDown() throws Exception { } //InvalidCustomJsonException
@Test(expectedExceptions = InvalidCustomJsonException.class)
frekele/elasticsearch-mapping-builder
src/test/java/org/frekele/elasticsearch/mapping/ExceptionTest.java
// Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidCustomJsonException.java // public class InvalidCustomJsonException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidCustomJsonException(String message) { // super(message); // } // // public InvalidCustomJsonException(Throwable cause) { // super(cause); // } // // public InvalidCustomJsonException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidCustomJsonException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidDocumentClassException.java // public class InvalidDocumentClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidDocumentClassException(String message) { // super(message); // } // // public InvalidDocumentClassException(Throwable cause) { // super(cause); // } // // public InvalidDocumentClassException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidDocumentClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MappingBuilderException.java // public class MappingBuilderException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MappingBuilderException(String message) { // super(message); // } // // public MappingBuilderException(Throwable cause) { // super(cause); // } // // public MappingBuilderException(String message, Throwable cause) { // super(message, cause); // } // // public MappingBuilderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MaxRecursiveLevelClassException.java // public class MaxRecursiveLevelClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MaxRecursiveLevelClassException(String message) { // super(message); // } // // public MaxRecursiveLevelClassException(Throwable cause) { // super(cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause) { // super(message, cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import org.frekele.elasticsearch.mapping.exceptions.InvalidCustomJsonException; import org.frekele.elasticsearch.mapping.exceptions.InvalidDocumentClassException; import org.frekele.elasticsearch.mapping.exceptions.MappingBuilderException; import org.frekele.elasticsearch.mapping.exceptions.MaxRecursiveLevelClassException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.IOException;
@Test(expectedExceptions = InvalidCustomJsonException.class) public void InvalidCustomJsonExceptionTest1() throws Exception { throw new InvalidCustomJsonException("InvalidCustomJsonException"); } @Test(expectedExceptions = InvalidCustomJsonException.class) public void InvalidCustomJsonExceptionTest2() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidCustomJsonException(ex); } @Test(expectedExceptions = InvalidCustomJsonException.class) public void InvalidCustomJsonExceptionTest3() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidCustomJsonException("InvalidCustomJsonException", ex); } @Test(expectedExceptions = InvalidCustomJsonException.class) public void InvalidCustomJsonExceptionTest4() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidCustomJsonException("InvalidCustomJsonException", ex, true, true); } @Test(expectedExceptions = InvalidCustomJsonException.class) public void InvalidCustomJsonExceptionTest5() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidCustomJsonException("InvalidCustomJsonException", ex, false, false); } //InvalidDocumentClassException
// Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidCustomJsonException.java // public class InvalidCustomJsonException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidCustomJsonException(String message) { // super(message); // } // // public InvalidCustomJsonException(Throwable cause) { // super(cause); // } // // public InvalidCustomJsonException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidCustomJsonException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidDocumentClassException.java // public class InvalidDocumentClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidDocumentClassException(String message) { // super(message); // } // // public InvalidDocumentClassException(Throwable cause) { // super(cause); // } // // public InvalidDocumentClassException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidDocumentClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MappingBuilderException.java // public class MappingBuilderException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MappingBuilderException(String message) { // super(message); // } // // public MappingBuilderException(Throwable cause) { // super(cause); // } // // public MappingBuilderException(String message, Throwable cause) { // super(message, cause); // } // // public MappingBuilderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MaxRecursiveLevelClassException.java // public class MaxRecursiveLevelClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MaxRecursiveLevelClassException(String message) { // super(message); // } // // public MaxRecursiveLevelClassException(Throwable cause) { // super(cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause) { // super(message, cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: src/test/java/org/frekele/elasticsearch/mapping/ExceptionTest.java import org.frekele.elasticsearch.mapping.exceptions.InvalidCustomJsonException; import org.frekele.elasticsearch.mapping.exceptions.InvalidDocumentClassException; import org.frekele.elasticsearch.mapping.exceptions.MappingBuilderException; import org.frekele.elasticsearch.mapping.exceptions.MaxRecursiveLevelClassException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.IOException; @Test(expectedExceptions = InvalidCustomJsonException.class) public void InvalidCustomJsonExceptionTest1() throws Exception { throw new InvalidCustomJsonException("InvalidCustomJsonException"); } @Test(expectedExceptions = InvalidCustomJsonException.class) public void InvalidCustomJsonExceptionTest2() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidCustomJsonException(ex); } @Test(expectedExceptions = InvalidCustomJsonException.class) public void InvalidCustomJsonExceptionTest3() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidCustomJsonException("InvalidCustomJsonException", ex); } @Test(expectedExceptions = InvalidCustomJsonException.class) public void InvalidCustomJsonExceptionTest4() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidCustomJsonException("InvalidCustomJsonException", ex, true, true); } @Test(expectedExceptions = InvalidCustomJsonException.class) public void InvalidCustomJsonExceptionTest5() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidCustomJsonException("InvalidCustomJsonException", ex, false, false); } //InvalidDocumentClassException
@Test(expectedExceptions = InvalidDocumentClassException.class)
frekele/elasticsearch-mapping-builder
src/test/java/org/frekele/elasticsearch/mapping/ExceptionTest.java
// Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidCustomJsonException.java // public class InvalidCustomJsonException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidCustomJsonException(String message) { // super(message); // } // // public InvalidCustomJsonException(Throwable cause) { // super(cause); // } // // public InvalidCustomJsonException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidCustomJsonException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidDocumentClassException.java // public class InvalidDocumentClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidDocumentClassException(String message) { // super(message); // } // // public InvalidDocumentClassException(Throwable cause) { // super(cause); // } // // public InvalidDocumentClassException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidDocumentClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MappingBuilderException.java // public class MappingBuilderException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MappingBuilderException(String message) { // super(message); // } // // public MappingBuilderException(Throwable cause) { // super(cause); // } // // public MappingBuilderException(String message, Throwable cause) { // super(message, cause); // } // // public MappingBuilderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MaxRecursiveLevelClassException.java // public class MaxRecursiveLevelClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MaxRecursiveLevelClassException(String message) { // super(message); // } // // public MaxRecursiveLevelClassException(Throwable cause) { // super(cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause) { // super(message, cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import org.frekele.elasticsearch.mapping.exceptions.InvalidCustomJsonException; import org.frekele.elasticsearch.mapping.exceptions.InvalidDocumentClassException; import org.frekele.elasticsearch.mapping.exceptions.MappingBuilderException; import org.frekele.elasticsearch.mapping.exceptions.MaxRecursiveLevelClassException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.IOException;
@Test(expectedExceptions = InvalidDocumentClassException.class) public void InvalidDocumentClassExceptionTest1() throws Exception { throw new InvalidDocumentClassException("InvalidDocumentClassException"); } @Test(expectedExceptions = InvalidDocumentClassException.class) public void InvalidDocumentClassExceptionTest2() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidDocumentClassException(ex); } @Test(expectedExceptions = InvalidDocumentClassException.class) public void InvalidDocumentClassExceptionTest3() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidDocumentClassException("InvalidDocumentClassException", ex); } @Test(expectedExceptions = InvalidDocumentClassException.class) public void InvalidDocumentClassExceptionTest4() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidDocumentClassException("InvalidDocumentClassException", ex, true, true); } @Test(expectedExceptions = InvalidDocumentClassException.class) public void InvalidDocumentClassExceptionTest5() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidDocumentClassException("InvalidDocumentClassException", ex, false, false); } //MappingBuilderException
// Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidCustomJsonException.java // public class InvalidCustomJsonException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidCustomJsonException(String message) { // super(message); // } // // public InvalidCustomJsonException(Throwable cause) { // super(cause); // } // // public InvalidCustomJsonException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidCustomJsonException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidDocumentClassException.java // public class InvalidDocumentClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidDocumentClassException(String message) { // super(message); // } // // public InvalidDocumentClassException(Throwable cause) { // super(cause); // } // // public InvalidDocumentClassException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidDocumentClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MappingBuilderException.java // public class MappingBuilderException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MappingBuilderException(String message) { // super(message); // } // // public MappingBuilderException(Throwable cause) { // super(cause); // } // // public MappingBuilderException(String message, Throwable cause) { // super(message, cause); // } // // public MappingBuilderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MaxRecursiveLevelClassException.java // public class MaxRecursiveLevelClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MaxRecursiveLevelClassException(String message) { // super(message); // } // // public MaxRecursiveLevelClassException(Throwable cause) { // super(cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause) { // super(message, cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: src/test/java/org/frekele/elasticsearch/mapping/ExceptionTest.java import org.frekele.elasticsearch.mapping.exceptions.InvalidCustomJsonException; import org.frekele.elasticsearch.mapping.exceptions.InvalidDocumentClassException; import org.frekele.elasticsearch.mapping.exceptions.MappingBuilderException; import org.frekele.elasticsearch.mapping.exceptions.MaxRecursiveLevelClassException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.IOException; @Test(expectedExceptions = InvalidDocumentClassException.class) public void InvalidDocumentClassExceptionTest1() throws Exception { throw new InvalidDocumentClassException("InvalidDocumentClassException"); } @Test(expectedExceptions = InvalidDocumentClassException.class) public void InvalidDocumentClassExceptionTest2() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidDocumentClassException(ex); } @Test(expectedExceptions = InvalidDocumentClassException.class) public void InvalidDocumentClassExceptionTest3() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidDocumentClassException("InvalidDocumentClassException", ex); } @Test(expectedExceptions = InvalidDocumentClassException.class) public void InvalidDocumentClassExceptionTest4() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidDocumentClassException("InvalidDocumentClassException", ex, true, true); } @Test(expectedExceptions = InvalidDocumentClassException.class) public void InvalidDocumentClassExceptionTest5() throws Exception { IOException ex = new IOException("IO error"); throw new InvalidDocumentClassException("InvalidDocumentClassException", ex, false, false); } //MappingBuilderException
@Test(expectedExceptions = MappingBuilderException.class)
frekele/elasticsearch-mapping-builder
src/test/java/org/frekele/elasticsearch/mapping/ExceptionTest.java
// Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidCustomJsonException.java // public class InvalidCustomJsonException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidCustomJsonException(String message) { // super(message); // } // // public InvalidCustomJsonException(Throwable cause) { // super(cause); // } // // public InvalidCustomJsonException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidCustomJsonException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidDocumentClassException.java // public class InvalidDocumentClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidDocumentClassException(String message) { // super(message); // } // // public InvalidDocumentClassException(Throwable cause) { // super(cause); // } // // public InvalidDocumentClassException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidDocumentClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MappingBuilderException.java // public class MappingBuilderException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MappingBuilderException(String message) { // super(message); // } // // public MappingBuilderException(Throwable cause) { // super(cause); // } // // public MappingBuilderException(String message, Throwable cause) { // super(message, cause); // } // // public MappingBuilderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MaxRecursiveLevelClassException.java // public class MaxRecursiveLevelClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MaxRecursiveLevelClassException(String message) { // super(message); // } // // public MaxRecursiveLevelClassException(Throwable cause) { // super(cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause) { // super(message, cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import org.frekele.elasticsearch.mapping.exceptions.InvalidCustomJsonException; import org.frekele.elasticsearch.mapping.exceptions.InvalidDocumentClassException; import org.frekele.elasticsearch.mapping.exceptions.MappingBuilderException; import org.frekele.elasticsearch.mapping.exceptions.MaxRecursiveLevelClassException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.IOException;
@Test(expectedExceptions = MappingBuilderException.class) public void MappingBuilderExceptionTest1() throws Exception { throw new MappingBuilderException("MappingBuilderException"); } @Test(expectedExceptions = MappingBuilderException.class) public void MappingBuilderExceptionTest2() throws Exception { IOException ex = new IOException("IO error"); throw new MappingBuilderException(ex); } @Test(expectedExceptions = MappingBuilderException.class) public void MappingBuilderExceptionTest3() throws Exception { IOException ex = new IOException("IO error"); throw new MappingBuilderException("MappingBuilderException", ex); } @Test(expectedExceptions = MappingBuilderException.class) public void MappingBuilderExceptionTest4() throws Exception { IOException ex = new IOException("IO error"); throw new MappingBuilderException("MappingBuilderException", ex, true, true); } @Test(expectedExceptions = MappingBuilderException.class) public void MappingBuilderExceptionTest5() throws Exception { IOException ex = new IOException("IO error"); throw new MappingBuilderException("MappingBuilderException", ex, false, false); } //MaxRecursiveLevelClassException
// Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidCustomJsonException.java // public class InvalidCustomJsonException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidCustomJsonException(String message) { // super(message); // } // // public InvalidCustomJsonException(Throwable cause) { // super(cause); // } // // public InvalidCustomJsonException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidCustomJsonException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/InvalidDocumentClassException.java // public class InvalidDocumentClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public InvalidDocumentClassException(String message) { // super(message); // } // // public InvalidDocumentClassException(Throwable cause) { // super(cause); // } // // public InvalidDocumentClassException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidDocumentClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MappingBuilderException.java // public class MappingBuilderException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MappingBuilderException(String message) { // super(message); // } // // public MappingBuilderException(Throwable cause) { // super(cause); // } // // public MappingBuilderException(String message, Throwable cause) { // super(message, cause); // } // // public MappingBuilderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: src/main/java/org/frekele/elasticsearch/mapping/exceptions/MaxRecursiveLevelClassException.java // public class MaxRecursiveLevelClassException extends RuntimeException implements Serializable { // // private static final long serialVersionUID = 1L; // // public MaxRecursiveLevelClassException(String message) { // super(message); // } // // public MaxRecursiveLevelClassException(Throwable cause) { // super(cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause) { // super(message, cause); // } // // public MaxRecursiveLevelClassException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: src/test/java/org/frekele/elasticsearch/mapping/ExceptionTest.java import org.frekele.elasticsearch.mapping.exceptions.InvalidCustomJsonException; import org.frekele.elasticsearch.mapping.exceptions.InvalidDocumentClassException; import org.frekele.elasticsearch.mapping.exceptions.MappingBuilderException; import org.frekele.elasticsearch.mapping.exceptions.MaxRecursiveLevelClassException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.IOException; @Test(expectedExceptions = MappingBuilderException.class) public void MappingBuilderExceptionTest1() throws Exception { throw new MappingBuilderException("MappingBuilderException"); } @Test(expectedExceptions = MappingBuilderException.class) public void MappingBuilderExceptionTest2() throws Exception { IOException ex = new IOException("IO error"); throw new MappingBuilderException(ex); } @Test(expectedExceptions = MappingBuilderException.class) public void MappingBuilderExceptionTest3() throws Exception { IOException ex = new IOException("IO error"); throw new MappingBuilderException("MappingBuilderException", ex); } @Test(expectedExceptions = MappingBuilderException.class) public void MappingBuilderExceptionTest4() throws Exception { IOException ex = new IOException("IO error"); throw new MappingBuilderException("MappingBuilderException", ex, true, true); } @Test(expectedExceptions = MappingBuilderException.class) public void MappingBuilderExceptionTest5() throws Exception { IOException ex = new IOException("IO error"); throw new MappingBuilderException("MappingBuilderException", ex, false, false); } //MaxRecursiveLevelClassException
@Test(expectedExceptions = MaxRecursiveLevelClassException.class)
frekele/elasticsearch-mapping-builder
src/test/java/org/frekele/elasticsearch/mapping/BookTest.java
// Path: src/test/java/org/frekele/elasticsearch/mapping/entities/model/BookEntity.java // @ElasticDocument("book") // public class BookEntity { // // @ElasticKeywordField // private String isbn; // // @ElasticTextField // @ElasticKeywordField // private String name; // // @ElasticTextField // private String description; // // @ElasticDateField // private OffsetDateTime releaseDate; // // @ElasticBooleanField // private Boolean active; // // @ElasticBinaryField // private String imageBlob; // // @ElasticObjectField // private AuthorEntity author; // // public BookEntity() { // } // }
import org.frekele.elasticsearch.mapping.entities.model.BookEntity; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.*;
package org.frekele.elasticsearch.mapping; /** * @author frekele - Leandro Kersting de Freitas */ public class BookTest { @BeforeMethod public void setUp() throws Exception { } @AfterMethod public void tearDown() throws Exception { } @Test public void buildBookTest() throws Exception { String expected = "{\"mappings\":{\"book\":{\"properties\":{\"isbn\":{\"type\":\"keyword\"},\"name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}},\"description\":{\"type\":\"text\"},\"releaseDate\":{\"type\":\"date\"},\"active\":{\"type\":\"boolean\"},\"imageBlob\":{\"type\":\"binary\"},\"author\":{\"properties\":{\"id\":{\"type\":\"long\"},\"name\":{\"type\":\"text\"},\"artisticName\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}},\"address\":{\"nested\":true,\"properties\":{\"postalCode\":{\"type\":\"keyword\"},\"street\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"},\"completion\":{\"type\":\"completion\"}}},\"number\":{\"type\":\"long\"}}}}}}}}}"; MappingBuilder mappingBuilder = new MappingBuilderImpl();
// Path: src/test/java/org/frekele/elasticsearch/mapping/entities/model/BookEntity.java // @ElasticDocument("book") // public class BookEntity { // // @ElasticKeywordField // private String isbn; // // @ElasticTextField // @ElasticKeywordField // private String name; // // @ElasticTextField // private String description; // // @ElasticDateField // private OffsetDateTime releaseDate; // // @ElasticBooleanField // private Boolean active; // // @ElasticBinaryField // private String imageBlob; // // @ElasticObjectField // private AuthorEntity author; // // public BookEntity() { // } // } // Path: src/test/java/org/frekele/elasticsearch/mapping/BookTest.java import org.frekele.elasticsearch.mapping.entities.model.BookEntity; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.*; package org.frekele.elasticsearch.mapping; /** * @author frekele - Leandro Kersting de Freitas */ public class BookTest { @BeforeMethod public void setUp() throws Exception { } @AfterMethod public void tearDown() throws Exception { } @Test public void buildBookTest() throws Exception { String expected = "{\"mappings\":{\"book\":{\"properties\":{\"isbn\":{\"type\":\"keyword\"},\"name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}},\"description\":{\"type\":\"text\"},\"releaseDate\":{\"type\":\"date\"},\"active\":{\"type\":\"boolean\"},\"imageBlob\":{\"type\":\"binary\"},\"author\":{\"properties\":{\"id\":{\"type\":\"long\"},\"name\":{\"type\":\"text\"},\"artisticName\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"}}},\"address\":{\"nested\":true,\"properties\":{\"postalCode\":{\"type\":\"keyword\"},\"street\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\"},\"completion\":{\"type\":\"completion\"}}},\"number\":{\"type\":\"long\"}}}}}}}}}"; MappingBuilder mappingBuilder = new MappingBuilderImpl();
ObjectMapping result = mappingBuilder.build(BookEntity.class);
frekele/elasticsearch-mapping-builder
src/test/java/org/frekele/elasticsearch/mapping/ProductTest.java
// Path: src/test/java/org/frekele/elasticsearch/mapping/entities/model/ProductEntity.java // @ElasticDocument("product") // public class ProductEntity { // // @ElasticLongField // private Long id; // // //The Array is not included in the mapping. // private List<String> categories; // // @ElasticIntegerField // private Integer size; // // @ElasticFloatField // private Float height; // // @ElasticFloatField // private Float width; // // @ElasticFloatField // private Float depth; // // @ElasticDoubleField // private Float price; // // public ProductEntity() { // } // }
import org.frekele.elasticsearch.mapping.entities.model.ProductEntity; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.*;
package org.frekele.elasticsearch.mapping; /** * @author frekele - Leandro Kersting de Freitas */ public class ProductTest { @BeforeMethod public void setUp() throws Exception { } @AfterMethod public void tearDown() throws Exception { } @Test public void buildProductTest() throws Exception { String expected = "{\"mappings\":{\"product\":{\"properties\":{\"id\":{\"type\":\"long\"},\"size\":{\"type\":\"integer\"},\"height\":{\"type\":\"float\"},\"width\":{\"type\":\"float\"},\"depth\":{\"type\":\"float\"},\"price\":{\"type\":\"double\"}}}}}"; MappingBuilder mappingBuilder = new MappingBuilderImpl();
// Path: src/test/java/org/frekele/elasticsearch/mapping/entities/model/ProductEntity.java // @ElasticDocument("product") // public class ProductEntity { // // @ElasticLongField // private Long id; // // //The Array is not included in the mapping. // private List<String> categories; // // @ElasticIntegerField // private Integer size; // // @ElasticFloatField // private Float height; // // @ElasticFloatField // private Float width; // // @ElasticFloatField // private Float depth; // // @ElasticDoubleField // private Float price; // // public ProductEntity() { // } // } // Path: src/test/java/org/frekele/elasticsearch/mapping/ProductTest.java import org.frekele.elasticsearch.mapping.entities.model.ProductEntity; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.*; package org.frekele.elasticsearch.mapping; /** * @author frekele - Leandro Kersting de Freitas */ public class ProductTest { @BeforeMethod public void setUp() throws Exception { } @AfterMethod public void tearDown() throws Exception { } @Test public void buildProductTest() throws Exception { String expected = "{\"mappings\":{\"product\":{\"properties\":{\"id\":{\"type\":\"long\"},\"size\":{\"type\":\"integer\"},\"height\":{\"type\":\"float\"},\"width\":{\"type\":\"float\"},\"depth\":{\"type\":\"float\"},\"price\":{\"type\":\"double\"}}}}}"; MappingBuilder mappingBuilder = new MappingBuilderImpl();
ObjectMapping result = mappingBuilder.build(ProductEntity.class);
Team-Antimatter-Mod/AntiMatterMod
src/main/java/antimattermod/core/Render/OverlayBlockRender.java
// Path: src/main/java/antimattermod/core/AntiMatterModCore.java // @Mod(modid = AntiMatterModCore.MOD_ID, useMetadata = true, dependencies = "required-after:Forge@[10.13.4.1558,);required-after:YukariLib") // public class AntiMatterModCore { // // public static final String MOD_ID = "AntiMatterModCore"; // @SuppressWarnings("WeakerAccess") // public static final String MOD_NAME = "AntiMatterMod Core"; // @SuppressWarnings("WeakerAccess") // public static final String MOD_VERSION = "1.0.0"; // // @Mod.Metadata // public static ModMetadata modMetadata; // @SidedProxy(clientSide = "antimattermod.core.client.ClientAntiMatterModCoreProxy", serverSide = "antimattermod.core.common.AntiMatterModCoreProxy") // public static AntiMatterModCoreProxy proxy; // // @Mod.Instance(MOD_ID) // public static AntiMatterModCore INSTANCE; // // @Mod.EventHandler // @SuppressWarnings("unused") // public void preinit(FMLPreInitializationEvent event) { // loadMeta(modMetadata); // DeveloperBossTexture.downloadTexture();//開発者のスキンのダウンロード // AntiMatterModRegistry.registerPreInit(event); // AMMRegistry.INSTANCE.handlePreInit(); // OreDictionaryRegister.OreDictionaryRegisterPreInit(event); // proxy.registerClientInfo(); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void init(FMLInitializationEvent event) { // proxy.registerRenderer(); // AntiMatterModRegistry.registerInit(event); // AMMRegistry.INSTANCE.handleInit(); // RecipeRegister.beforeRemoveRecipeinit(event); // RecipeRegister.RecipeRegisterInit(event); // RecipeRegister.afterRemoveRecipeinit(event); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void posinit(FMLPostInitializationEvent event) { // AntiMatterModRegistry.registerPostInit(event); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void serverStarting(FMLServerStartingEvent event) { // event.registerServerCommand(new ExclusiveDeleteBlock()); // event.registerServerCommand(new Createsphere()); // // } // // private void loadMeta(ModMetadata metadata) { // metadata.modId = MOD_ID; // metadata.name = MOD_NAME; // metadata.version = MOD_VERSION; // metadata.authorList.add("C6H2Cl2"); // metadata.authorList.add("Raiti-Chan"); // metadata.authorList.add("Kojin15"); // metadata.authorList.add("Worldofthetakumi"); // metadata.authorList.add("Sora-Suke"); // metadata.description = "Make Anti-Matter in Minecraft!"; // metadata.autogenerated = false; // } // } // // Path: src/main/java/antimattermod/core/Block/OverlayBlockBase.java // public abstract class OverlayBlockBase extends AMMBlock { // // /** // * Blockクラスのコンストラクタといっしょ // * @param material ブロックのマテリアル // */ // protected OverlayBlockBase(Material material){ // super(material); // } // // /** // * ベースのアイコンを返します // * @param world ワールド // * // * @return ベースレイアイコン // */ // public abstract IIcon getBaseIcon(IBlockAccess world, int x, int y, int z); // // /** // * ベースアイコンを返します // * @param meta メタデータ // * @return ベースアイコン // */ // public abstract IIcon getBaseIcon(int meta); // // // /** // * OverlayBlockレンダ―IDを返します。 // * 基本的にOverrideしないで。 // * @return レンダ―ID // */ // @Override // public int getRenderType() { // return OverlayBlockRender.RenderID; // } // // @Override // public boolean renderAsNormalBlock() { // return false; // } // // @Override // public boolean isOpaqueCube() { // return super.isOpaqueCube(); // } // }
import antimattermod.core.AntiMatterModCore; import antimattermod.core.Block.OverlayBlockBase; import org.lwjgl.opengl.GL11; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.world.IBlockAccess;
/* * */ package antimattermod.core.Render; /** <h1>OverlayBlockRender</h1> * <br> * @author Raiti * @version 1.0.0 * */ public class OverlayBlockRender implements ISimpleBlockRenderingHandler{ public static final int RenderID = AntiMatterModCore.proxy.getNewRenderType(); //自身のレンダ―ID(空いてるIDを取得) /* * インベントリでのレンダ―処理 */ @Override public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) {
// Path: src/main/java/antimattermod/core/AntiMatterModCore.java // @Mod(modid = AntiMatterModCore.MOD_ID, useMetadata = true, dependencies = "required-after:Forge@[10.13.4.1558,);required-after:YukariLib") // public class AntiMatterModCore { // // public static final String MOD_ID = "AntiMatterModCore"; // @SuppressWarnings("WeakerAccess") // public static final String MOD_NAME = "AntiMatterMod Core"; // @SuppressWarnings("WeakerAccess") // public static final String MOD_VERSION = "1.0.0"; // // @Mod.Metadata // public static ModMetadata modMetadata; // @SidedProxy(clientSide = "antimattermod.core.client.ClientAntiMatterModCoreProxy", serverSide = "antimattermod.core.common.AntiMatterModCoreProxy") // public static AntiMatterModCoreProxy proxy; // // @Mod.Instance(MOD_ID) // public static AntiMatterModCore INSTANCE; // // @Mod.EventHandler // @SuppressWarnings("unused") // public void preinit(FMLPreInitializationEvent event) { // loadMeta(modMetadata); // DeveloperBossTexture.downloadTexture();//開発者のスキンのダウンロード // AntiMatterModRegistry.registerPreInit(event); // AMMRegistry.INSTANCE.handlePreInit(); // OreDictionaryRegister.OreDictionaryRegisterPreInit(event); // proxy.registerClientInfo(); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void init(FMLInitializationEvent event) { // proxy.registerRenderer(); // AntiMatterModRegistry.registerInit(event); // AMMRegistry.INSTANCE.handleInit(); // RecipeRegister.beforeRemoveRecipeinit(event); // RecipeRegister.RecipeRegisterInit(event); // RecipeRegister.afterRemoveRecipeinit(event); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void posinit(FMLPostInitializationEvent event) { // AntiMatterModRegistry.registerPostInit(event); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void serverStarting(FMLServerStartingEvent event) { // event.registerServerCommand(new ExclusiveDeleteBlock()); // event.registerServerCommand(new Createsphere()); // // } // // private void loadMeta(ModMetadata metadata) { // metadata.modId = MOD_ID; // metadata.name = MOD_NAME; // metadata.version = MOD_VERSION; // metadata.authorList.add("C6H2Cl2"); // metadata.authorList.add("Raiti-Chan"); // metadata.authorList.add("Kojin15"); // metadata.authorList.add("Worldofthetakumi"); // metadata.authorList.add("Sora-Suke"); // metadata.description = "Make Anti-Matter in Minecraft!"; // metadata.autogenerated = false; // } // } // // Path: src/main/java/antimattermod/core/Block/OverlayBlockBase.java // public abstract class OverlayBlockBase extends AMMBlock { // // /** // * Blockクラスのコンストラクタといっしょ // * @param material ブロックのマテリアル // */ // protected OverlayBlockBase(Material material){ // super(material); // } // // /** // * ベースのアイコンを返します // * @param world ワールド // * // * @return ベースレイアイコン // */ // public abstract IIcon getBaseIcon(IBlockAccess world, int x, int y, int z); // // /** // * ベースアイコンを返します // * @param meta メタデータ // * @return ベースアイコン // */ // public abstract IIcon getBaseIcon(int meta); // // // /** // * OverlayBlockレンダ―IDを返します。 // * 基本的にOverrideしないで。 // * @return レンダ―ID // */ // @Override // public int getRenderType() { // return OverlayBlockRender.RenderID; // } // // @Override // public boolean renderAsNormalBlock() { // return false; // } // // @Override // public boolean isOpaqueCube() { // return super.isOpaqueCube(); // } // } // Path: src/main/java/antimattermod/core/Render/OverlayBlockRender.java import antimattermod.core.AntiMatterModCore; import antimattermod.core.Block.OverlayBlockBase; import org.lwjgl.opengl.GL11; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.world.IBlockAccess; /* * */ package antimattermod.core.Render; /** <h1>OverlayBlockRender</h1> * <br> * @author Raiti * @version 1.0.0 * */ public class OverlayBlockRender implements ISimpleBlockRenderingHandler{ public static final int RenderID = AntiMatterModCore.proxy.getNewRenderType(); //自身のレンダ―ID(空いてるIDを取得) /* * インベントリでのレンダ―処理 */ @Override public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) {
if(!(block instanceof OverlayBlockBase)) return;
Team-Antimatter-Mod/AntiMatterMod
src/main/java/antimattermod/core/Item/tool/MiningHammer.java
// Path: src/main/java/antimattermod/core/Util/AMMToolMaterial.java // public enum AMMToolMaterial { // @CraftingToolProperty(maxUse = 10, level = 0)IRON(ToolMaterial.IRON), // DIAMOND(ToolMaterial.EMERALD), // //Raitium(3, 250, 8.0F, 3.0F, 14, new ItemStack(AntiMatterModRegistry.ingot_01, 1, 1)), // //Drantium(3, 250, 6.0F, 2.0F, 22, new ItemStack(AntiMatterModRegistry.ingot_01, 1, 2)), // //Palazirite(3, 400, 6.0F, 2.0F, 14, new ItemStack(AntiMatterModRegistry.ingot_01, 1, 3)), // // ; // //================================================================================================================== // // AMMToolMaterial(int harvestLevel, int maxUse, float efficiency, float damage, int enchantAbility) { // this.toolMaterial = EnumHelper.addToolMaterial(this.toString(), harvestLevel, maxUse, efficiency, damage, enchantAbility); // this.annotationHandle(); // } // // AMMToolMaterial(ToolMaterial material) { // this.toolMaterial = material; // this.annotationHandle(); // } // // AMMToolMaterial(int harvestLevel, int maxUse, float efficiency, float damage, int enchantAbility, ItemStack repairItem) { // this(harvestLevel, maxUse, efficiency, damage, enchantAbility); // this.toolMaterial.setRepairItem(repairItem); // } // // private ToolMaterial toolMaterial; // // public ToolMaterial getToolMaterial() { // return toolMaterial; // } // // private int craftingToolMaxUse; // public int getCraftingToolMaxUse() { // return craftingToolMaxUse; // } // // private int craftingToolLevel = -1; // public int getCraftingToolLevel() { // return craftingToolLevel; // } // // private void annotationHandle() { // Class<? extends AMMToolMaterial> materialClass = this.getClass(); // try { // Field field = materialClass.getField(this.name()); // // //---------------------------------------------------------------------------------------------------------- // CraftingToolProperty cToolProperty = field.getAnnotation(CraftingToolProperty.class); // if (cToolProperty != null) { // this.craftingToolMaxUse = cToolProperty.maxUse(); // this.craftingToolLevel = cToolProperty.level(); // } else this.craftingToolMaxUse = toolMaterial.getMaxUses() / 10; // //---------------------------------------------------------------------------------------------------------- // // } catch (NoSuchFieldException e) { // e.printStackTrace(); // } // } // // @Retention(RetentionPolicy.RUNTIME) // @Target(ElementType.FIELD) // public @interface CraftingToolProperty { // int maxUse(); // // int level(); // } // // }
import antimattermod.core.Util.AMMToolMaterial; import com.google.common.collect.Multimap; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.network.play.server.S23PacketBlockChange; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.world.BlockEvent.BreakEvent; import java.util.List;
package antimattermod.core.Item.tool; /** * Created by Raiti-chan on 2016/10/22. * 範囲採掘ハンマー * * @author Raiti-chan */ public class MiningHammer extends AMMTool { private int harvestRange = 1; /** * 範囲採掘できるマイニングハンマーの作成 * * @param name ツール名 * @param textureName テクスチャ―名 * @param material ツールマテリアル * @param range 採掘範囲 range*2 + 1 平方ブロックの範囲採掘 */
// Path: src/main/java/antimattermod/core/Util/AMMToolMaterial.java // public enum AMMToolMaterial { // @CraftingToolProperty(maxUse = 10, level = 0)IRON(ToolMaterial.IRON), // DIAMOND(ToolMaterial.EMERALD), // //Raitium(3, 250, 8.0F, 3.0F, 14, new ItemStack(AntiMatterModRegistry.ingot_01, 1, 1)), // //Drantium(3, 250, 6.0F, 2.0F, 22, new ItemStack(AntiMatterModRegistry.ingot_01, 1, 2)), // //Palazirite(3, 400, 6.0F, 2.0F, 14, new ItemStack(AntiMatterModRegistry.ingot_01, 1, 3)), // // ; // //================================================================================================================== // // AMMToolMaterial(int harvestLevel, int maxUse, float efficiency, float damage, int enchantAbility) { // this.toolMaterial = EnumHelper.addToolMaterial(this.toString(), harvestLevel, maxUse, efficiency, damage, enchantAbility); // this.annotationHandle(); // } // // AMMToolMaterial(ToolMaterial material) { // this.toolMaterial = material; // this.annotationHandle(); // } // // AMMToolMaterial(int harvestLevel, int maxUse, float efficiency, float damage, int enchantAbility, ItemStack repairItem) { // this(harvestLevel, maxUse, efficiency, damage, enchantAbility); // this.toolMaterial.setRepairItem(repairItem); // } // // private ToolMaterial toolMaterial; // // public ToolMaterial getToolMaterial() { // return toolMaterial; // } // // private int craftingToolMaxUse; // public int getCraftingToolMaxUse() { // return craftingToolMaxUse; // } // // private int craftingToolLevel = -1; // public int getCraftingToolLevel() { // return craftingToolLevel; // } // // private void annotationHandle() { // Class<? extends AMMToolMaterial> materialClass = this.getClass(); // try { // Field field = materialClass.getField(this.name()); // // //---------------------------------------------------------------------------------------------------------- // CraftingToolProperty cToolProperty = field.getAnnotation(CraftingToolProperty.class); // if (cToolProperty != null) { // this.craftingToolMaxUse = cToolProperty.maxUse(); // this.craftingToolLevel = cToolProperty.level(); // } else this.craftingToolMaxUse = toolMaterial.getMaxUses() / 10; // //---------------------------------------------------------------------------------------------------------- // // } catch (NoSuchFieldException e) { // e.printStackTrace(); // } // } // // @Retention(RetentionPolicy.RUNTIME) // @Target(ElementType.FIELD) // public @interface CraftingToolProperty { // int maxUse(); // // int level(); // } // // } // Path: src/main/java/antimattermod/core/Item/tool/MiningHammer.java import antimattermod.core.Util.AMMToolMaterial; import com.google.common.collect.Multimap; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.network.play.server.S23PacketBlockChange; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.world.BlockEvent.BreakEvent; import java.util.List; package antimattermod.core.Item.tool; /** * Created by Raiti-chan on 2016/10/22. * 範囲採掘ハンマー * * @author Raiti-chan */ public class MiningHammer extends AMMTool { private int harvestRange = 1; /** * 範囲採掘できるマイニングハンマーの作成 * * @param name ツール名 * @param textureName テクスチャ―名 * @param material ツールマテリアル * @param range 採掘範囲 range*2 + 1 平方ブロックの範囲採掘 */
public MiningHammer(String name, String textureName, AMMToolMaterial material, int range) {
Team-Antimatter-Mod/AntiMatterMod
src/main/java/antimattermod/core/Util/BlockUtil.java
// Path: src/main/java/antimattermod/core/AntiMatterModCore.java // @Mod(modid = AntiMatterModCore.MOD_ID, useMetadata = true, dependencies = "required-after:Forge@[10.13.4.1558,);required-after:YukariLib") // public class AntiMatterModCore { // // public static final String MOD_ID = "AntiMatterModCore"; // @SuppressWarnings("WeakerAccess") // public static final String MOD_NAME = "AntiMatterMod Core"; // @SuppressWarnings("WeakerAccess") // public static final String MOD_VERSION = "1.0.0"; // // @Mod.Metadata // public static ModMetadata modMetadata; // @SidedProxy(clientSide = "antimattermod.core.client.ClientAntiMatterModCoreProxy", serverSide = "antimattermod.core.common.AntiMatterModCoreProxy") // public static AntiMatterModCoreProxy proxy; // // @Mod.Instance(MOD_ID) // public static AntiMatterModCore INSTANCE; // // @Mod.EventHandler // @SuppressWarnings("unused") // public void preinit(FMLPreInitializationEvent event) { // loadMeta(modMetadata); // DeveloperBossTexture.downloadTexture();//開発者のスキンのダウンロード // AntiMatterModRegistry.registerPreInit(event); // AMMRegistry.INSTANCE.handlePreInit(); // OreDictionaryRegister.OreDictionaryRegisterPreInit(event); // proxy.registerClientInfo(); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void init(FMLInitializationEvent event) { // proxy.registerRenderer(); // AntiMatterModRegistry.registerInit(event); // AMMRegistry.INSTANCE.handleInit(); // RecipeRegister.beforeRemoveRecipeinit(event); // RecipeRegister.RecipeRegisterInit(event); // RecipeRegister.afterRemoveRecipeinit(event); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void posinit(FMLPostInitializationEvent event) { // AntiMatterModRegistry.registerPostInit(event); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void serverStarting(FMLServerStartingEvent event) { // event.registerServerCommand(new ExclusiveDeleteBlock()); // event.registerServerCommand(new Createsphere()); // // } // // private void loadMeta(ModMetadata metadata) { // metadata.modId = MOD_ID; // metadata.name = MOD_NAME; // metadata.version = MOD_VERSION; // metadata.authorList.add("C6H2Cl2"); // metadata.authorList.add("Raiti-Chan"); // metadata.authorList.add("Kojin15"); // metadata.authorList.add("Worldofthetakumi"); // metadata.authorList.add("Sora-Suke"); // metadata.description = "Make Anti-Matter in Minecraft!"; // metadata.autogenerated = false; // } // } // // Path: src/main/java/antimattermod/core/Block/SimpleBlock.java // public class SimpleBlock extends AMMBlock { // public SimpleBlock(Material material) { // super(material); // } // } // // Path: src/main/java/antimattermod/core/Block/SimpleMetaBlock.java // public class SimpleMetaBlock extends AMMBlock{ // // // private IIcon[] icons; // // public SimpleMetaBlock(Material p_i45394_1_, int maxMeta) { // super(p_i45394_1_); // if (maxMeta > 16) throw new IllegalArgumentException("ブロックメタ値の最大は16です"); // icons = new IIcon[maxMeta]; // } // // // @Override // public int damageDropped(int p_149692_1_) { // return p_149692_1_; // } // // @Override // @SuppressWarnings("unchecked") // public void getSubBlocks(Item p_149666_1_, CreativeTabs p_149666_2_, List p_149666_3_) { // for (int i = 0; i < icons.length; i++) { // p_149666_3_.add(new ItemStack(p_149666_1_, 1, i)); // } // } // // @Override // @SideOnly(Side.CLIENT) // public void registerBlockIcons(IIconRegister register) { // for (int i = 0; i < icons.length; i++){ // icons[i] = register.registerIcon(this.getTextureName()+"_"+i); // } // } // // @Override // @SideOnly(Side.CLIENT) // public IIcon getIcon(int side, int meta) { // return icons[meta]; // } // }
import antimattermod.core.AntiMatterModCore; import antimattermod.core.Block.SimpleBlock; import antimattermod.core.Block.SimpleMetaBlock; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
package antimattermod.core.Util; /** * Created by C6H2Cl2 on 2016/09/19. * 無機能なブロックを簡易追加する関数クラス */ public class BlockUtil { /** * 無機能なブロックを追加します * @param name ブロック名 * @param textureName テクスチャ―名 * @param material 材質 * @param hardness 硬さ * @param resistance 耐爆値 * @return Blockオブジェクト */ public static Block CreateBlock(@NotNull String name, @Nullable String textureName, @NotNull Material material, float hardness, float resistance){
// Path: src/main/java/antimattermod/core/AntiMatterModCore.java // @Mod(modid = AntiMatterModCore.MOD_ID, useMetadata = true, dependencies = "required-after:Forge@[10.13.4.1558,);required-after:YukariLib") // public class AntiMatterModCore { // // public static final String MOD_ID = "AntiMatterModCore"; // @SuppressWarnings("WeakerAccess") // public static final String MOD_NAME = "AntiMatterMod Core"; // @SuppressWarnings("WeakerAccess") // public static final String MOD_VERSION = "1.0.0"; // // @Mod.Metadata // public static ModMetadata modMetadata; // @SidedProxy(clientSide = "antimattermod.core.client.ClientAntiMatterModCoreProxy", serverSide = "antimattermod.core.common.AntiMatterModCoreProxy") // public static AntiMatterModCoreProxy proxy; // // @Mod.Instance(MOD_ID) // public static AntiMatterModCore INSTANCE; // // @Mod.EventHandler // @SuppressWarnings("unused") // public void preinit(FMLPreInitializationEvent event) { // loadMeta(modMetadata); // DeveloperBossTexture.downloadTexture();//開発者のスキンのダウンロード // AntiMatterModRegistry.registerPreInit(event); // AMMRegistry.INSTANCE.handlePreInit(); // OreDictionaryRegister.OreDictionaryRegisterPreInit(event); // proxy.registerClientInfo(); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void init(FMLInitializationEvent event) { // proxy.registerRenderer(); // AntiMatterModRegistry.registerInit(event); // AMMRegistry.INSTANCE.handleInit(); // RecipeRegister.beforeRemoveRecipeinit(event); // RecipeRegister.RecipeRegisterInit(event); // RecipeRegister.afterRemoveRecipeinit(event); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void posinit(FMLPostInitializationEvent event) { // AntiMatterModRegistry.registerPostInit(event); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void serverStarting(FMLServerStartingEvent event) { // event.registerServerCommand(new ExclusiveDeleteBlock()); // event.registerServerCommand(new Createsphere()); // // } // // private void loadMeta(ModMetadata metadata) { // metadata.modId = MOD_ID; // metadata.name = MOD_NAME; // metadata.version = MOD_VERSION; // metadata.authorList.add("C6H2Cl2"); // metadata.authorList.add("Raiti-Chan"); // metadata.authorList.add("Kojin15"); // metadata.authorList.add("Worldofthetakumi"); // metadata.authorList.add("Sora-Suke"); // metadata.description = "Make Anti-Matter in Minecraft!"; // metadata.autogenerated = false; // } // } // // Path: src/main/java/antimattermod/core/Block/SimpleBlock.java // public class SimpleBlock extends AMMBlock { // public SimpleBlock(Material material) { // super(material); // } // } // // Path: src/main/java/antimattermod/core/Block/SimpleMetaBlock.java // public class SimpleMetaBlock extends AMMBlock{ // // // private IIcon[] icons; // // public SimpleMetaBlock(Material p_i45394_1_, int maxMeta) { // super(p_i45394_1_); // if (maxMeta > 16) throw new IllegalArgumentException("ブロックメタ値の最大は16です"); // icons = new IIcon[maxMeta]; // } // // // @Override // public int damageDropped(int p_149692_1_) { // return p_149692_1_; // } // // @Override // @SuppressWarnings("unchecked") // public void getSubBlocks(Item p_149666_1_, CreativeTabs p_149666_2_, List p_149666_3_) { // for (int i = 0; i < icons.length; i++) { // p_149666_3_.add(new ItemStack(p_149666_1_, 1, i)); // } // } // // @Override // @SideOnly(Side.CLIENT) // public void registerBlockIcons(IIconRegister register) { // for (int i = 0; i < icons.length; i++){ // icons[i] = register.registerIcon(this.getTextureName()+"_"+i); // } // } // // @Override // @SideOnly(Side.CLIENT) // public IIcon getIcon(int side, int meta) { // return icons[meta]; // } // } // Path: src/main/java/antimattermod/core/Util/BlockUtil.java import antimattermod.core.AntiMatterModCore; import antimattermod.core.Block.SimpleBlock; import antimattermod.core.Block.SimpleMetaBlock; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; package antimattermod.core.Util; /** * Created by C6H2Cl2 on 2016/09/19. * 無機能なブロックを簡易追加する関数クラス */ public class BlockUtil { /** * 無機能なブロックを追加します * @param name ブロック名 * @param textureName テクスチャ―名 * @param material 材質 * @param hardness 硬さ * @param resistance 耐爆値 * @return Blockオブジェクト */ public static Block CreateBlock(@NotNull String name, @Nullable String textureName, @NotNull Material material, float hardness, float resistance){
Block block = new SimpleBlock(material);
Team-Antimatter-Mod/AntiMatterMod
src/main/java/antimattermod/core/Util/BlockUtil.java
// Path: src/main/java/antimattermod/core/AntiMatterModCore.java // @Mod(modid = AntiMatterModCore.MOD_ID, useMetadata = true, dependencies = "required-after:Forge@[10.13.4.1558,);required-after:YukariLib") // public class AntiMatterModCore { // // public static final String MOD_ID = "AntiMatterModCore"; // @SuppressWarnings("WeakerAccess") // public static final String MOD_NAME = "AntiMatterMod Core"; // @SuppressWarnings("WeakerAccess") // public static final String MOD_VERSION = "1.0.0"; // // @Mod.Metadata // public static ModMetadata modMetadata; // @SidedProxy(clientSide = "antimattermod.core.client.ClientAntiMatterModCoreProxy", serverSide = "antimattermod.core.common.AntiMatterModCoreProxy") // public static AntiMatterModCoreProxy proxy; // // @Mod.Instance(MOD_ID) // public static AntiMatterModCore INSTANCE; // // @Mod.EventHandler // @SuppressWarnings("unused") // public void preinit(FMLPreInitializationEvent event) { // loadMeta(modMetadata); // DeveloperBossTexture.downloadTexture();//開発者のスキンのダウンロード // AntiMatterModRegistry.registerPreInit(event); // AMMRegistry.INSTANCE.handlePreInit(); // OreDictionaryRegister.OreDictionaryRegisterPreInit(event); // proxy.registerClientInfo(); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void init(FMLInitializationEvent event) { // proxy.registerRenderer(); // AntiMatterModRegistry.registerInit(event); // AMMRegistry.INSTANCE.handleInit(); // RecipeRegister.beforeRemoveRecipeinit(event); // RecipeRegister.RecipeRegisterInit(event); // RecipeRegister.afterRemoveRecipeinit(event); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void posinit(FMLPostInitializationEvent event) { // AntiMatterModRegistry.registerPostInit(event); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void serverStarting(FMLServerStartingEvent event) { // event.registerServerCommand(new ExclusiveDeleteBlock()); // event.registerServerCommand(new Createsphere()); // // } // // private void loadMeta(ModMetadata metadata) { // metadata.modId = MOD_ID; // metadata.name = MOD_NAME; // metadata.version = MOD_VERSION; // metadata.authorList.add("C6H2Cl2"); // metadata.authorList.add("Raiti-Chan"); // metadata.authorList.add("Kojin15"); // metadata.authorList.add("Worldofthetakumi"); // metadata.authorList.add("Sora-Suke"); // metadata.description = "Make Anti-Matter in Minecraft!"; // metadata.autogenerated = false; // } // } // // Path: src/main/java/antimattermod/core/Block/SimpleBlock.java // public class SimpleBlock extends AMMBlock { // public SimpleBlock(Material material) { // super(material); // } // } // // Path: src/main/java/antimattermod/core/Block/SimpleMetaBlock.java // public class SimpleMetaBlock extends AMMBlock{ // // // private IIcon[] icons; // // public SimpleMetaBlock(Material p_i45394_1_, int maxMeta) { // super(p_i45394_1_); // if (maxMeta > 16) throw new IllegalArgumentException("ブロックメタ値の最大は16です"); // icons = new IIcon[maxMeta]; // } // // // @Override // public int damageDropped(int p_149692_1_) { // return p_149692_1_; // } // // @Override // @SuppressWarnings("unchecked") // public void getSubBlocks(Item p_149666_1_, CreativeTabs p_149666_2_, List p_149666_3_) { // for (int i = 0; i < icons.length; i++) { // p_149666_3_.add(new ItemStack(p_149666_1_, 1, i)); // } // } // // @Override // @SideOnly(Side.CLIENT) // public void registerBlockIcons(IIconRegister register) { // for (int i = 0; i < icons.length; i++){ // icons[i] = register.registerIcon(this.getTextureName()+"_"+i); // } // } // // @Override // @SideOnly(Side.CLIENT) // public IIcon getIcon(int side, int meta) { // return icons[meta]; // } // }
import antimattermod.core.AntiMatterModCore; import antimattermod.core.Block.SimpleBlock; import antimattermod.core.Block.SimpleMetaBlock; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
package antimattermod.core.Util; /** * Created by C6H2Cl2 on 2016/09/19. * 無機能なブロックを簡易追加する関数クラス */ public class BlockUtil { /** * 無機能なブロックを追加します * @param name ブロック名 * @param textureName テクスチャ―名 * @param material 材質 * @param hardness 硬さ * @param resistance 耐爆値 * @return Blockオブジェクト */ public static Block CreateBlock(@NotNull String name, @Nullable String textureName, @NotNull Material material, float hardness, float resistance){ Block block = new SimpleBlock(material); block.setHardness(hardness); block.setResistance(resistance); block.setBlockName(name); if(textureName == null || textureName.isEmpty()){ textureName = name; }
// Path: src/main/java/antimattermod/core/AntiMatterModCore.java // @Mod(modid = AntiMatterModCore.MOD_ID, useMetadata = true, dependencies = "required-after:Forge@[10.13.4.1558,);required-after:YukariLib") // public class AntiMatterModCore { // // public static final String MOD_ID = "AntiMatterModCore"; // @SuppressWarnings("WeakerAccess") // public static final String MOD_NAME = "AntiMatterMod Core"; // @SuppressWarnings("WeakerAccess") // public static final String MOD_VERSION = "1.0.0"; // // @Mod.Metadata // public static ModMetadata modMetadata; // @SidedProxy(clientSide = "antimattermod.core.client.ClientAntiMatterModCoreProxy", serverSide = "antimattermod.core.common.AntiMatterModCoreProxy") // public static AntiMatterModCoreProxy proxy; // // @Mod.Instance(MOD_ID) // public static AntiMatterModCore INSTANCE; // // @Mod.EventHandler // @SuppressWarnings("unused") // public void preinit(FMLPreInitializationEvent event) { // loadMeta(modMetadata); // DeveloperBossTexture.downloadTexture();//開発者のスキンのダウンロード // AntiMatterModRegistry.registerPreInit(event); // AMMRegistry.INSTANCE.handlePreInit(); // OreDictionaryRegister.OreDictionaryRegisterPreInit(event); // proxy.registerClientInfo(); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void init(FMLInitializationEvent event) { // proxy.registerRenderer(); // AntiMatterModRegistry.registerInit(event); // AMMRegistry.INSTANCE.handleInit(); // RecipeRegister.beforeRemoveRecipeinit(event); // RecipeRegister.RecipeRegisterInit(event); // RecipeRegister.afterRemoveRecipeinit(event); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void posinit(FMLPostInitializationEvent event) { // AntiMatterModRegistry.registerPostInit(event); // } // // @Mod.EventHandler // @SuppressWarnings("unused") // public void serverStarting(FMLServerStartingEvent event) { // event.registerServerCommand(new ExclusiveDeleteBlock()); // event.registerServerCommand(new Createsphere()); // // } // // private void loadMeta(ModMetadata metadata) { // metadata.modId = MOD_ID; // metadata.name = MOD_NAME; // metadata.version = MOD_VERSION; // metadata.authorList.add("C6H2Cl2"); // metadata.authorList.add("Raiti-Chan"); // metadata.authorList.add("Kojin15"); // metadata.authorList.add("Worldofthetakumi"); // metadata.authorList.add("Sora-Suke"); // metadata.description = "Make Anti-Matter in Minecraft!"; // metadata.autogenerated = false; // } // } // // Path: src/main/java/antimattermod/core/Block/SimpleBlock.java // public class SimpleBlock extends AMMBlock { // public SimpleBlock(Material material) { // super(material); // } // } // // Path: src/main/java/antimattermod/core/Block/SimpleMetaBlock.java // public class SimpleMetaBlock extends AMMBlock{ // // // private IIcon[] icons; // // public SimpleMetaBlock(Material p_i45394_1_, int maxMeta) { // super(p_i45394_1_); // if (maxMeta > 16) throw new IllegalArgumentException("ブロックメタ値の最大は16です"); // icons = new IIcon[maxMeta]; // } // // // @Override // public int damageDropped(int p_149692_1_) { // return p_149692_1_; // } // // @Override // @SuppressWarnings("unchecked") // public void getSubBlocks(Item p_149666_1_, CreativeTabs p_149666_2_, List p_149666_3_) { // for (int i = 0; i < icons.length; i++) { // p_149666_3_.add(new ItemStack(p_149666_1_, 1, i)); // } // } // // @Override // @SideOnly(Side.CLIENT) // public void registerBlockIcons(IIconRegister register) { // for (int i = 0; i < icons.length; i++){ // icons[i] = register.registerIcon(this.getTextureName()+"_"+i); // } // } // // @Override // @SideOnly(Side.CLIENT) // public IIcon getIcon(int side, int meta) { // return icons[meta]; // } // } // Path: src/main/java/antimattermod/core/Util/BlockUtil.java import antimattermod.core.AntiMatterModCore; import antimattermod.core.Block.SimpleBlock; import antimattermod.core.Block.SimpleMetaBlock; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; package antimattermod.core.Util; /** * Created by C6H2Cl2 on 2016/09/19. * 無機能なブロックを簡易追加する関数クラス */ public class BlockUtil { /** * 無機能なブロックを追加します * @param name ブロック名 * @param textureName テクスチャ―名 * @param material 材質 * @param hardness 硬さ * @param resistance 耐爆値 * @return Blockオブジェクト */ public static Block CreateBlock(@NotNull String name, @Nullable String textureName, @NotNull Material material, float hardness, float resistance){ Block block = new SimpleBlock(material); block.setHardness(hardness); block.setResistance(resistance); block.setBlockName(name); if(textureName == null || textureName.isEmpty()){ textureName = name; }
textureName = AntiMatterModCore.MOD_ID + textureName;
Team-Antimatter-Mod/AntiMatterMod
src/main/java/antimattermod/core/Block/BlockSatStove.java
// Path: src/main/java/antimattermod/core/Block/TileEntity/TileEntitySatStove.java // public class TileEntitySatStove extends TileEntity { // // public TileEntitySatStove(){ // // } // }
import antimattermod.core.Block.TileEntity.TileEntitySatStove; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World;
package antimattermod.core.Block; /** * Created by worldofthetakumi on 2016/10/13. */ public class BlockSatStove extends BlockContainer { public BlockSatStove(){ super(Material.rock); setBlockName("satStove"); setHardness(2.0f); setResistance(0.0f); } //trueで不透過になる @Override public boolean isOpaqueCube() { return false; } //独自レンダーの使用時は-1 public int getRenderType(){ return -1; } //レンダーが普通と違うよってこと @Override public boolean renderAsNormalBlock() { return false; } //Entityの作成 @Override public TileEntity createNewTileEntity(World var1, int var2){
// Path: src/main/java/antimattermod/core/Block/TileEntity/TileEntitySatStove.java // public class TileEntitySatStove extends TileEntity { // // public TileEntitySatStove(){ // // } // } // Path: src/main/java/antimattermod/core/Block/BlockSatStove.java import antimattermod.core.Block.TileEntity.TileEntitySatStove; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; package antimattermod.core.Block; /** * Created by worldofthetakumi on 2016/10/13. */ public class BlockSatStove extends BlockContainer { public BlockSatStove(){ super(Material.rock); setBlockName("satStove"); setHardness(2.0f); setResistance(0.0f); } //trueで不透過になる @Override public boolean isOpaqueCube() { return false; } //独自レンダーの使用時は-1 public int getRenderType(){ return -1; } //レンダーが普通と違うよってこと @Override public boolean renderAsNormalBlock() { return false; } //Entityの作成 @Override public TileEntity createNewTileEntity(World var1, int var2){
return new TileEntitySatStove();
Team-Antimatter-Mod/AntiMatterMod
src/main/java/antimattermod/core/Item/tool/CraftingTool.java
// Path: src/main/java/antimattermod/core/Util/AMMToolMaterial.java // public enum AMMToolMaterial { // @CraftingToolProperty(maxUse = 10, level = 0)IRON(ToolMaterial.IRON), // DIAMOND(ToolMaterial.EMERALD), // //Raitium(3, 250, 8.0F, 3.0F, 14, new ItemStack(AntiMatterModRegistry.ingot_01, 1, 1)), // //Drantium(3, 250, 6.0F, 2.0F, 22, new ItemStack(AntiMatterModRegistry.ingot_01, 1, 2)), // //Palazirite(3, 400, 6.0F, 2.0F, 14, new ItemStack(AntiMatterModRegistry.ingot_01, 1, 3)), // // ; // //================================================================================================================== // // AMMToolMaterial(int harvestLevel, int maxUse, float efficiency, float damage, int enchantAbility) { // this.toolMaterial = EnumHelper.addToolMaterial(this.toString(), harvestLevel, maxUse, efficiency, damage, enchantAbility); // this.annotationHandle(); // } // // AMMToolMaterial(ToolMaterial material) { // this.toolMaterial = material; // this.annotationHandle(); // } // // AMMToolMaterial(int harvestLevel, int maxUse, float efficiency, float damage, int enchantAbility, ItemStack repairItem) { // this(harvestLevel, maxUse, efficiency, damage, enchantAbility); // this.toolMaterial.setRepairItem(repairItem); // } // // private ToolMaterial toolMaterial; // // public ToolMaterial getToolMaterial() { // return toolMaterial; // } // // private int craftingToolMaxUse; // public int getCraftingToolMaxUse() { // return craftingToolMaxUse; // } // // private int craftingToolLevel = -1; // public int getCraftingToolLevel() { // return craftingToolLevel; // } // // private void annotationHandle() { // Class<? extends AMMToolMaterial> materialClass = this.getClass(); // try { // Field field = materialClass.getField(this.name()); // // //---------------------------------------------------------------------------------------------------------- // CraftingToolProperty cToolProperty = field.getAnnotation(CraftingToolProperty.class); // if (cToolProperty != null) { // this.craftingToolMaxUse = cToolProperty.maxUse(); // this.craftingToolLevel = cToolProperty.level(); // } else this.craftingToolMaxUse = toolMaterial.getMaxUses() / 10; // //---------------------------------------------------------------------------------------------------------- // // } catch (NoSuchFieldException e) { // e.printStackTrace(); // } // } // // @Retention(RetentionPolicy.RUNTIME) // @Target(ElementType.FIELD) // public @interface CraftingToolProperty { // int maxUse(); // // int level(); // } // // }
import antimattermod.core.Util.AMMToolMaterial; import com.mojang.realmsclient.gui.ChatFormatting; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.List;
package antimattermod.core.Item.tool; /** * Created by Raiti-chan on 2016/10/14. * クラフティングで耐久値が減るツールのベース * @author Raiti-chan */ @SuppressWarnings("WeakerAccess") public abstract class CraftingTool extends AMMToolNotToolClass {
// Path: src/main/java/antimattermod/core/Util/AMMToolMaterial.java // public enum AMMToolMaterial { // @CraftingToolProperty(maxUse = 10, level = 0)IRON(ToolMaterial.IRON), // DIAMOND(ToolMaterial.EMERALD), // //Raitium(3, 250, 8.0F, 3.0F, 14, new ItemStack(AntiMatterModRegistry.ingot_01, 1, 1)), // //Drantium(3, 250, 6.0F, 2.0F, 22, new ItemStack(AntiMatterModRegistry.ingot_01, 1, 2)), // //Palazirite(3, 400, 6.0F, 2.0F, 14, new ItemStack(AntiMatterModRegistry.ingot_01, 1, 3)), // // ; // //================================================================================================================== // // AMMToolMaterial(int harvestLevel, int maxUse, float efficiency, float damage, int enchantAbility) { // this.toolMaterial = EnumHelper.addToolMaterial(this.toString(), harvestLevel, maxUse, efficiency, damage, enchantAbility); // this.annotationHandle(); // } // // AMMToolMaterial(ToolMaterial material) { // this.toolMaterial = material; // this.annotationHandle(); // } // // AMMToolMaterial(int harvestLevel, int maxUse, float efficiency, float damage, int enchantAbility, ItemStack repairItem) { // this(harvestLevel, maxUse, efficiency, damage, enchantAbility); // this.toolMaterial.setRepairItem(repairItem); // } // // private ToolMaterial toolMaterial; // // public ToolMaterial getToolMaterial() { // return toolMaterial; // } // // private int craftingToolMaxUse; // public int getCraftingToolMaxUse() { // return craftingToolMaxUse; // } // // private int craftingToolLevel = -1; // public int getCraftingToolLevel() { // return craftingToolLevel; // } // // private void annotationHandle() { // Class<? extends AMMToolMaterial> materialClass = this.getClass(); // try { // Field field = materialClass.getField(this.name()); // // //---------------------------------------------------------------------------------------------------------- // CraftingToolProperty cToolProperty = field.getAnnotation(CraftingToolProperty.class); // if (cToolProperty != null) { // this.craftingToolMaxUse = cToolProperty.maxUse(); // this.craftingToolLevel = cToolProperty.level(); // } else this.craftingToolMaxUse = toolMaterial.getMaxUses() / 10; // //---------------------------------------------------------------------------------------------------------- // // } catch (NoSuchFieldException e) { // e.printStackTrace(); // } // } // // @Retention(RetentionPolicy.RUNTIME) // @Target(ElementType.FIELD) // public @interface CraftingToolProperty { // int maxUse(); // // int level(); // } // // } // Path: src/main/java/antimattermod/core/Item/tool/CraftingTool.java import antimattermod.core.Util.AMMToolMaterial; import com.mojang.realmsclient.gui.ChatFormatting; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.List; package antimattermod.core.Item.tool; /** * Created by Raiti-chan on 2016/10/14. * クラフティングで耐久値が減るツールのベース * @author Raiti-chan */ @SuppressWarnings("WeakerAccess") public abstract class CraftingTool extends AMMToolNotToolClass {
protected CraftingTool(@NotNull String name, @NotNull String textureName, AMMToolMaterial material) {
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/BackupAgent.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat";
import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import android.annotation.TargetApi; import android.app.backup.BackupAgentHelper; import android.app.backup.SharedPreferencesBackupHelper; import android.os.Build;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * Copy application preferences to a remote "cloud" storage, using the Android * backup provider. * @author Pixmob */ @TargetApi(Build.VERSION_CODES.FROYO) public class BackupAgent extends BackupAgentHelper { @Override public void onCreate() { super.onCreate();
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // Path: src/org/pixmob/freemobile/netstat/BackupAgent.java import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import android.annotation.TargetApi; import android.app.backup.BackupAgentHelper; import android.app.backup.SharedPreferencesBackupHelper; import android.os.Build; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * Copy application preferences to a remote "cloud" storage, using the Android * backup provider. * @author Pixmob */ @TargetApi(Build.VERSION_CODES.FROYO) public class BackupAgent extends BackupAgentHelper { @Override public void onCreate() { super.onCreate();
final SharedPreferencesBackupHelper prefsHelper = new SharedPreferencesBackupHelper(this, SP_NAME);
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/MonitorServiceStarter.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_ENABLE_AT_BOOT = "pref_enable_at_boot"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat";
import static org.pixmob.freemobile.netstat.Constants.SP_KEY_ENABLE_AT_BOOT; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * This broadcast receiver will start the {@link MonitorService} when the phone * has completed its boot sequence. * @author Pixmob */ public class MonitorServiceStarter extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_ENABLE_AT_BOOT = "pref_enable_at_boot"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // Path: src/org/pixmob/freemobile/netstat/MonitorServiceStarter.java import static org.pixmob.freemobile.netstat.Constants.SP_KEY_ENABLE_AT_BOOT; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * This broadcast receiver will start the {@link MonitorService} when the phone * has completed its boot sequence. * @author Pixmob */ public class MonitorServiceStarter extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
final SharedPreferences p = context.getSharedPreferences(SP_NAME,
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/MonitorServiceStarter.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_ENABLE_AT_BOOT = "pref_enable_at_boot"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat";
import static org.pixmob.freemobile.netstat.Constants.SP_KEY_ENABLE_AT_BOOT; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * This broadcast receiver will start the {@link MonitorService} when the phone * has completed its boot sequence. * @author Pixmob */ public class MonitorServiceStarter extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_ENABLE_AT_BOOT = "pref_enable_at_boot"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // Path: src/org/pixmob/freemobile/netstat/MonitorServiceStarter.java import static org.pixmob.freemobile.netstat.Constants.SP_KEY_ENABLE_AT_BOOT; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * This broadcast receiver will start the {@link MonitorService} when the phone * has completed its boot sequence. * @author Pixmob */ public class MonitorServiceStarter extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
final boolean enabled = p.getBoolean(SP_KEY_ENABLE_AT_BOOT, false);
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/MonitorServiceStarter.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_ENABLE_AT_BOOT = "pref_enable_at_boot"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat";
import static org.pixmob.freemobile.netstat.Constants.SP_KEY_ENABLE_AT_BOOT; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * This broadcast receiver will start the {@link MonitorService} when the phone * has completed its boot sequence. * @author Pixmob */ public class MonitorServiceStarter extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); final boolean enabled = p.getBoolean(SP_KEY_ENABLE_AT_BOOT, false); if (!enabled) {
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_ENABLE_AT_BOOT = "pref_enable_at_boot"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // Path: src/org/pixmob/freemobile/netstat/MonitorServiceStarter.java import static org.pixmob.freemobile.netstat.Constants.SP_KEY_ENABLE_AT_BOOT; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * This broadcast receiver will start the {@link MonitorService} when the phone * has completed its boot sequence. * @author Pixmob */ public class MonitorServiceStarter extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); final boolean enabled = p.getBoolean(SP_KEY_ENABLE_AT_BOOT, false); if (!enabled) {
Log.i(TAG, "Monitor service is not started at boot");
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/SyncService.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // // Path: src/org/pixmob/freemobile/netstat/util/DateUtils.java // public final class DateUtils { // private DateUtils() { // } // // /** // * Format a duration in milliseconds. // */ // public static CharSequence formatDuration(long duration, Context context, CharSequence defaultValue) { // if (duration <= 0) { // return defaultValue; // } // final long ds = duration / 1000; // final StringBuilder buf = new StringBuilder(32); // if (ds < 60) { // buf.append(ds).append(context.getString(R.string.seconds)); // } else if (ds < 3600) { // final long m = ds / 60; // buf.append(m).append(context.getString(R.string.minutes)); // } else if (ds < 86400) { // final long h = ds / 3600; // buf.append(h).append(context.getString(R.string.hours)); // // final long m = (ds - h * 3600) / 60; // if (m != 0) { // if (m < 10) { // buf.append("0"); // } // buf.append(m); // } // } else { // final long d = ds / 86400; // buf.append(d).append(context.getString(R.string.days)); // // final long h = (ds - d * 86400) / 3600; // if (h != 0) { // buf.append(" ").append(h).append(context.getString(R.string.hours)); // } // // final long m = (ds - d * 86400 - h * 3600) / 60; // if (m != 0) { // if (h == 0) { // buf.append(" "); // } else if (m < 10) { // buf.append("0"); // } // buf.append(m); // if (h == 0) { // buf.append(context.getString(R.string.minutes)); // } // } // } // // return buf; // } // // /** // * Format a date. // */ // public static CharSequence formatDate(long d) { // return DateFormat.format("dd/MM/yyyy", d); // } // }
import static org.pixmob.freemobile.netstat.BuildConfig.DEBUG; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.CharArrayBuffer; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.PowerManager; import android.support.v4.util.LongSparseArray; import android.text.format.DateFormat; import android.util.Log; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Calendar; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.DateUtils; import org.pixmob.httpclient.HttpClient; import org.pixmob.httpclient.HttpClientException; import org.pixmob.httpclient.HttpResponse; import org.pixmob.httpclient.HttpResponseHandler;
private SQLiteOpenHelper dbHelper; public SyncService() { super("FreeMobileNetstat/Sync"); } public static void schedule(Context context, boolean enabled) { final Context appContext = context.getApplicationContext(); final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); final PendingIntent syncIntent = PendingIntent.getService(appContext, 0, new Intent(appContext, SyncService.class), PendingIntent.FLAG_CANCEL_CURRENT); am.cancel(syncIntent); if (enabled) { // Set the sync period. long period = AlarmManager.INTERVAL_HOUR; final int syncErrors = context.getSharedPreferences(INTERNAL_SP_NAME, MODE_PRIVATE) .getInt(INTERNAL_SP_KEY_SYNC_ERRORS, 0); if (syncErrors != 0) { // When there was a sync error, the sync period is longer. period = AlarmManager.INTERVAL_HOUR * Math.min(syncErrors, MAX_SYNC_ERRORS); } // Add a random time to prevent concurrent requests for the server. final long fuzz = RANDOM.nextInt(1000 * 60 * 30); period += fuzz; if (DEBUG) {
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // // Path: src/org/pixmob/freemobile/netstat/util/DateUtils.java // public final class DateUtils { // private DateUtils() { // } // // /** // * Format a duration in milliseconds. // */ // public static CharSequence formatDuration(long duration, Context context, CharSequence defaultValue) { // if (duration <= 0) { // return defaultValue; // } // final long ds = duration / 1000; // final StringBuilder buf = new StringBuilder(32); // if (ds < 60) { // buf.append(ds).append(context.getString(R.string.seconds)); // } else if (ds < 3600) { // final long m = ds / 60; // buf.append(m).append(context.getString(R.string.minutes)); // } else if (ds < 86400) { // final long h = ds / 3600; // buf.append(h).append(context.getString(R.string.hours)); // // final long m = (ds - h * 3600) / 60; // if (m != 0) { // if (m < 10) { // buf.append("0"); // } // buf.append(m); // } // } else { // final long d = ds / 86400; // buf.append(d).append(context.getString(R.string.days)); // // final long h = (ds - d * 86400) / 3600; // if (h != 0) { // buf.append(" ").append(h).append(context.getString(R.string.hours)); // } // // final long m = (ds - d * 86400 - h * 3600) / 60; // if (m != 0) { // if (h == 0) { // buf.append(" "); // } else if (m < 10) { // buf.append("0"); // } // buf.append(m); // if (h == 0) { // buf.append(context.getString(R.string.minutes)); // } // } // } // // return buf; // } // // /** // * Format a date. // */ // public static CharSequence formatDate(long d) { // return DateFormat.format("dd/MM/yyyy", d); // } // } // Path: src/org/pixmob/freemobile/netstat/SyncService.java import static org.pixmob.freemobile.netstat.BuildConfig.DEBUG; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.CharArrayBuffer; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.PowerManager; import android.support.v4.util.LongSparseArray; import android.text.format.DateFormat; import android.util.Log; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Calendar; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.DateUtils; import org.pixmob.httpclient.HttpClient; import org.pixmob.httpclient.HttpClientException; import org.pixmob.httpclient.HttpResponse; import org.pixmob.httpclient.HttpResponseHandler; private SQLiteOpenHelper dbHelper; public SyncService() { super("FreeMobileNetstat/Sync"); } public static void schedule(Context context, boolean enabled) { final Context appContext = context.getApplicationContext(); final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); final PendingIntent syncIntent = PendingIntent.getService(appContext, 0, new Intent(appContext, SyncService.class), PendingIntent.FLAG_CANCEL_CURRENT); am.cancel(syncIntent); if (enabled) { // Set the sync period. long period = AlarmManager.INTERVAL_HOUR; final int syncErrors = context.getSharedPreferences(INTERNAL_SP_NAME, MODE_PRIVATE) .getInt(INTERNAL_SP_KEY_SYNC_ERRORS, 0); if (syncErrors != 0) { // When there was a sync error, the sync period is longer. period = AlarmManager.INTERVAL_HOUR * Math.min(syncErrors, MAX_SYNC_ERRORS); } // Add a random time to prevent concurrent requests for the server. final long fuzz = RANDOM.nextInt(1000 * 60 * 30); period += fuzz; if (DEBUG) {
Log.d(TAG, "Scheduling synchronization: next in " + (period / 1000 / 60) + " minutes");
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/SyncService.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // // Path: src/org/pixmob/freemobile/netstat/util/DateUtils.java // public final class DateUtils { // private DateUtils() { // } // // /** // * Format a duration in milliseconds. // */ // public static CharSequence formatDuration(long duration, Context context, CharSequence defaultValue) { // if (duration <= 0) { // return defaultValue; // } // final long ds = duration / 1000; // final StringBuilder buf = new StringBuilder(32); // if (ds < 60) { // buf.append(ds).append(context.getString(R.string.seconds)); // } else if (ds < 3600) { // final long m = ds / 60; // buf.append(m).append(context.getString(R.string.minutes)); // } else if (ds < 86400) { // final long h = ds / 3600; // buf.append(h).append(context.getString(R.string.hours)); // // final long m = (ds - h * 3600) / 60; // if (m != 0) { // if (m < 10) { // buf.append("0"); // } // buf.append(m); // } // } else { // final long d = ds / 86400; // buf.append(d).append(context.getString(R.string.days)); // // final long h = (ds - d * 86400) / 3600; // if (h != 0) { // buf.append(" ").append(h).append(context.getString(R.string.hours)); // } // // final long m = (ds - d * 86400 - h * 3600) / 60; // if (m != 0) { // if (h == 0) { // buf.append(" "); // } else if (m < 10) { // buf.append("0"); // } // buf.append(m); // if (h == 0) { // buf.append(context.getString(R.string.minutes)); // } // } // } // // return buf; // } // // /** // * Format a date. // */ // public static CharSequence formatDate(long d) { // return DateFormat.format("dd/MM/yyyy", d); // } // }
import static org.pixmob.freemobile.netstat.BuildConfig.DEBUG; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.CharArrayBuffer; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.PowerManager; import android.support.v4.util.LongSparseArray; import android.text.format.DateFormat; import android.util.Log; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Calendar; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.DateUtils; import org.pixmob.httpclient.HttpClient; import org.pixmob.httpclient.HttpClientException; import org.pixmob.httpclient.HttpResponse; import org.pixmob.httpclient.HttpResponseHandler;
if (enabled) { // Set the sync period. long period = AlarmManager.INTERVAL_HOUR; final int syncErrors = context.getSharedPreferences(INTERNAL_SP_NAME, MODE_PRIVATE) .getInt(INTERNAL_SP_KEY_SYNC_ERRORS, 0); if (syncErrors != 0) { // When there was a sync error, the sync period is longer. period = AlarmManager.INTERVAL_HOUR * Math.min(syncErrors, MAX_SYNC_ERRORS); } // Add a random time to prevent concurrent requests for the server. final long fuzz = RANDOM.nextInt(1000 * 60 * 30); period += fuzz; if (DEBUG) { Log.d(TAG, "Scheduling synchronization: next in " + (period / 1000 / 60) + " minutes"); } final long syncTime = System.currentTimeMillis() + period; am.set(AlarmManager.RTC_WAKEUP, syncTime, syncIntent); } else { if (DEBUG) { Log.d(TAG, "Synchronization schedule canceled"); } } } @Override public void onCreate() { super.onCreate();
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // // Path: src/org/pixmob/freemobile/netstat/util/DateUtils.java // public final class DateUtils { // private DateUtils() { // } // // /** // * Format a duration in milliseconds. // */ // public static CharSequence formatDuration(long duration, Context context, CharSequence defaultValue) { // if (duration <= 0) { // return defaultValue; // } // final long ds = duration / 1000; // final StringBuilder buf = new StringBuilder(32); // if (ds < 60) { // buf.append(ds).append(context.getString(R.string.seconds)); // } else if (ds < 3600) { // final long m = ds / 60; // buf.append(m).append(context.getString(R.string.minutes)); // } else if (ds < 86400) { // final long h = ds / 3600; // buf.append(h).append(context.getString(R.string.hours)); // // final long m = (ds - h * 3600) / 60; // if (m != 0) { // if (m < 10) { // buf.append("0"); // } // buf.append(m); // } // } else { // final long d = ds / 86400; // buf.append(d).append(context.getString(R.string.days)); // // final long h = (ds - d * 86400) / 3600; // if (h != 0) { // buf.append(" ").append(h).append(context.getString(R.string.hours)); // } // // final long m = (ds - d * 86400 - h * 3600) / 60; // if (m != 0) { // if (h == 0) { // buf.append(" "); // } else if (m < 10) { // buf.append("0"); // } // buf.append(m); // if (h == 0) { // buf.append(context.getString(R.string.minutes)); // } // } // } // // return buf; // } // // /** // * Format a date. // */ // public static CharSequence formatDate(long d) { // return DateFormat.format("dd/MM/yyyy", d); // } // } // Path: src/org/pixmob/freemobile/netstat/SyncService.java import static org.pixmob.freemobile.netstat.BuildConfig.DEBUG; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.CharArrayBuffer; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.PowerManager; import android.support.v4.util.LongSparseArray; import android.text.format.DateFormat; import android.util.Log; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Calendar; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.DateUtils; import org.pixmob.httpclient.HttpClient; import org.pixmob.httpclient.HttpClientException; import org.pixmob.httpclient.HttpResponse; import org.pixmob.httpclient.HttpResponseHandler; if (enabled) { // Set the sync period. long period = AlarmManager.INTERVAL_HOUR; final int syncErrors = context.getSharedPreferences(INTERNAL_SP_NAME, MODE_PRIVATE) .getInt(INTERNAL_SP_KEY_SYNC_ERRORS, 0); if (syncErrors != 0) { // When there was a sync error, the sync period is longer. period = AlarmManager.INTERVAL_HOUR * Math.min(syncErrors, MAX_SYNC_ERRORS); } // Add a random time to prevent concurrent requests for the server. final long fuzz = RANDOM.nextInt(1000 * 60 * 30); period += fuzz; if (DEBUG) { Log.d(TAG, "Scheduling synchronization: next in " + (period / 1000 / 60) + " minutes"); } final long syncTime = System.currentTimeMillis() + period; am.set(AlarmManager.RTC_WAKEUP, syncTime, syncIntent); } else { if (DEBUG) { Log.d(TAG, "Synchronization schedule canceled"); } } } @Override public void onCreate() { super.onCreate();
prefs = getSharedPreferences(SP_NAME, MODE_PRIVATE);
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/SyncService.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // // Path: src/org/pixmob/freemobile/netstat/util/DateUtils.java // public final class DateUtils { // private DateUtils() { // } // // /** // * Format a duration in milliseconds. // */ // public static CharSequence formatDuration(long duration, Context context, CharSequence defaultValue) { // if (duration <= 0) { // return defaultValue; // } // final long ds = duration / 1000; // final StringBuilder buf = new StringBuilder(32); // if (ds < 60) { // buf.append(ds).append(context.getString(R.string.seconds)); // } else if (ds < 3600) { // final long m = ds / 60; // buf.append(m).append(context.getString(R.string.minutes)); // } else if (ds < 86400) { // final long h = ds / 3600; // buf.append(h).append(context.getString(R.string.hours)); // // final long m = (ds - h * 3600) / 60; // if (m != 0) { // if (m < 10) { // buf.append("0"); // } // buf.append(m); // } // } else { // final long d = ds / 86400; // buf.append(d).append(context.getString(R.string.days)); // // final long h = (ds - d * 86400) / 3600; // if (h != 0) { // buf.append(" ").append(h).append(context.getString(R.string.hours)); // } // // final long m = (ds - d * 86400 - h * 3600) / 60; // if (m != 0) { // if (h == 0) { // buf.append(" "); // } else if (m < 10) { // buf.append("0"); // } // buf.append(m); // if (h == 0) { // buf.append(context.getString(R.string.minutes)); // } // } // } // // return buf; // } // // /** // * Format a date. // */ // public static CharSequence formatDate(long d) { // return DateFormat.format("dd/MM/yyyy", d); // } // }
import static org.pixmob.freemobile.netstat.BuildConfig.DEBUG; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.CharArrayBuffer; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.PowerManager; import android.support.v4.util.LongSparseArray; import android.text.format.DateFormat; import android.util.Log; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Calendar; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.DateUtils; import org.pixmob.httpclient.HttpClient; import org.pixmob.httpclient.HttpClientException; import org.pixmob.httpclient.HttpResponse; import org.pixmob.httpclient.HttpResponseHandler;
// Check if the remote server is up. final HttpClient client = createHttpClient(); try { client.head(createServerUrl(null)).execute(); } catch (HttpClientException e) { Log.w(TAG, "Remote server is not available: cannot upload statistics", e); return; } // Upload statistics. Log.i(TAG, "Uploading statistics"); final JSONObject json = new JSONObject(); final String deviceId = getDeviceId(); final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false); for (int i = 0; i < statsLen; ++i) { final long d = stats.keyAt(i); final DailyStat s = stats.get(d); try { json.put("timeOnOrange", s.orange); json.put("timeOnFreeMobile", s.freeMobile); } catch (JSONException e) { final IOException ioe = new IOException("Failed to prepare statistics upload"); ioe.initCause(e); throw ioe; } final String url = createServerUrl("/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d)); if (DEBUG) {
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // // Path: src/org/pixmob/freemobile/netstat/util/DateUtils.java // public final class DateUtils { // private DateUtils() { // } // // /** // * Format a duration in milliseconds. // */ // public static CharSequence formatDuration(long duration, Context context, CharSequence defaultValue) { // if (duration <= 0) { // return defaultValue; // } // final long ds = duration / 1000; // final StringBuilder buf = new StringBuilder(32); // if (ds < 60) { // buf.append(ds).append(context.getString(R.string.seconds)); // } else if (ds < 3600) { // final long m = ds / 60; // buf.append(m).append(context.getString(R.string.minutes)); // } else if (ds < 86400) { // final long h = ds / 3600; // buf.append(h).append(context.getString(R.string.hours)); // // final long m = (ds - h * 3600) / 60; // if (m != 0) { // if (m < 10) { // buf.append("0"); // } // buf.append(m); // } // } else { // final long d = ds / 86400; // buf.append(d).append(context.getString(R.string.days)); // // final long h = (ds - d * 86400) / 3600; // if (h != 0) { // buf.append(" ").append(h).append(context.getString(R.string.hours)); // } // // final long m = (ds - d * 86400 - h * 3600) / 60; // if (m != 0) { // if (h == 0) { // buf.append(" "); // } else if (m < 10) { // buf.append("0"); // } // buf.append(m); // if (h == 0) { // buf.append(context.getString(R.string.minutes)); // } // } // } // // return buf; // } // // /** // * Format a date. // */ // public static CharSequence formatDate(long d) { // return DateFormat.format("dd/MM/yyyy", d); // } // } // Path: src/org/pixmob/freemobile/netstat/SyncService.java import static org.pixmob.freemobile.netstat.BuildConfig.DEBUG; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.CharArrayBuffer; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.PowerManager; import android.support.v4.util.LongSparseArray; import android.text.format.DateFormat; import android.util.Log; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Calendar; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.DateUtils; import org.pixmob.httpclient.HttpClient; import org.pixmob.httpclient.HttpClientException; import org.pixmob.httpclient.HttpResponse; import org.pixmob.httpclient.HttpResponseHandler; // Check if the remote server is up. final HttpClient client = createHttpClient(); try { client.head(createServerUrl(null)).execute(); } catch (HttpClientException e) { Log.w(TAG, "Remote server is not available: cannot upload statistics", e); return; } // Upload statistics. Log.i(TAG, "Uploading statistics"); final JSONObject json = new JSONObject(); final String deviceId = getDeviceId(); final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false); for (int i = 0; i < statsLen; ++i) { final long d = stats.keyAt(i); final DailyStat s = stats.get(d); try { json.put("timeOnOrange", s.orange); json.put("timeOnFreeMobile", s.freeMobile); } catch (JSONException e) { final IOException ioe = new IOException("Failed to prepare statistics upload"); ioe.initCause(e); throw ioe; } final String url = createServerUrl("/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d)); if (DEBUG) {
Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url);
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/SyncService.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // // Path: src/org/pixmob/freemobile/netstat/util/DateUtils.java // public final class DateUtils { // private DateUtils() { // } // // /** // * Format a duration in milliseconds. // */ // public static CharSequence formatDuration(long duration, Context context, CharSequence defaultValue) { // if (duration <= 0) { // return defaultValue; // } // final long ds = duration / 1000; // final StringBuilder buf = new StringBuilder(32); // if (ds < 60) { // buf.append(ds).append(context.getString(R.string.seconds)); // } else if (ds < 3600) { // final long m = ds / 60; // buf.append(m).append(context.getString(R.string.minutes)); // } else if (ds < 86400) { // final long h = ds / 3600; // buf.append(h).append(context.getString(R.string.hours)); // // final long m = (ds - h * 3600) / 60; // if (m != 0) { // if (m < 10) { // buf.append("0"); // } // buf.append(m); // } // } else { // final long d = ds / 86400; // buf.append(d).append(context.getString(R.string.days)); // // final long h = (ds - d * 86400) / 3600; // if (h != 0) { // buf.append(" ").append(h).append(context.getString(R.string.hours)); // } // // final long m = (ds - d * 86400 - h * 3600) / 60; // if (m != 0) { // if (h == 0) { // buf.append(" "); // } else if (m < 10) { // buf.append("0"); // } // buf.append(m); // if (h == 0) { // buf.append(context.getString(R.string.minutes)); // } // } // } // // return buf; // } // // /** // * Format a date. // */ // public static CharSequence formatDate(long d) { // return DateFormat.format("dd/MM/yyyy", d); // } // }
import static org.pixmob.freemobile.netstat.BuildConfig.DEBUG; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.CharArrayBuffer; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.PowerManager; import android.support.v4.util.LongSparseArray; import android.text.format.DateFormat; import android.util.Log; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Calendar; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.DateUtils; import org.pixmob.httpclient.HttpClient; import org.pixmob.httpclient.HttpClientException; import org.pixmob.httpclient.HttpResponse; import org.pixmob.httpclient.HttpResponseHandler;
} } else if (HttpURLConnection.HTTP_OK == sc) { // Update upload database. cv.clear(); cv.put("sync", SYNC_UPLOADED); db.update("daily_stat", cv, "stat_timestamp=?", new String[] {String.valueOf(d) }); if (DEBUG) { Log.d(TAG, "Upload done for " + DateUtils.formatDate(d)); } } } }).execute(); } catch (HttpClientException e) { final IOException ioe = new IOException("Failed to send request with statistics"); ioe.initCause(e); throw ioe; } } } private DailyStat computeDailyStat(long date) { long timeOnOrange = 0; long timeOnFreeMobile = 0; if (DEBUG) { Log.d(TAG, "Computing statistics for " + DateUtils.formatDate(date)); } final Cursor c =
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // // Path: src/org/pixmob/freemobile/netstat/util/DateUtils.java // public final class DateUtils { // private DateUtils() { // } // // /** // * Format a duration in milliseconds. // */ // public static CharSequence formatDuration(long duration, Context context, CharSequence defaultValue) { // if (duration <= 0) { // return defaultValue; // } // final long ds = duration / 1000; // final StringBuilder buf = new StringBuilder(32); // if (ds < 60) { // buf.append(ds).append(context.getString(R.string.seconds)); // } else if (ds < 3600) { // final long m = ds / 60; // buf.append(m).append(context.getString(R.string.minutes)); // } else if (ds < 86400) { // final long h = ds / 3600; // buf.append(h).append(context.getString(R.string.hours)); // // final long m = (ds - h * 3600) / 60; // if (m != 0) { // if (m < 10) { // buf.append("0"); // } // buf.append(m); // } // } else { // final long d = ds / 86400; // buf.append(d).append(context.getString(R.string.days)); // // final long h = (ds - d * 86400) / 3600; // if (h != 0) { // buf.append(" ").append(h).append(context.getString(R.string.hours)); // } // // final long m = (ds - d * 86400 - h * 3600) / 60; // if (m != 0) { // if (h == 0) { // buf.append(" "); // } else if (m < 10) { // buf.append("0"); // } // buf.append(m); // if (h == 0) { // buf.append(context.getString(R.string.minutes)); // } // } // } // // return buf; // } // // /** // * Format a date. // */ // public static CharSequence formatDate(long d) { // return DateFormat.format("dd/MM/yyyy", d); // } // } // Path: src/org/pixmob/freemobile/netstat/SyncService.java import static org.pixmob.freemobile.netstat.BuildConfig.DEBUG; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import static org.pixmob.freemobile.netstat.Constants.TAG; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.CharArrayBuffer; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.PowerManager; import android.support.v4.util.LongSparseArray; import android.text.format.DateFormat; import android.util.Log; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Calendar; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.DateUtils; import org.pixmob.httpclient.HttpClient; import org.pixmob.httpclient.HttpClientException; import org.pixmob.httpclient.HttpResponse; import org.pixmob.httpclient.HttpResponseHandler; } } else if (HttpURLConnection.HTTP_OK == sc) { // Update upload database. cv.clear(); cv.put("sync", SYNC_UPLOADED); db.update("daily_stat", cv, "stat_timestamp=?", new String[] {String.valueOf(d) }); if (DEBUG) { Log.d(TAG, "Upload done for " + DateUtils.formatDate(d)); } } } }).execute(); } catch (HttpClientException e) { final IOException ioe = new IOException("Failed to send request with statistics"); ioe.initCause(e); throw ioe; } } } private DailyStat computeDailyStat(long date) { long timeOnOrange = 0; long timeOnFreeMobile = 0; if (DEBUG) { Log.d(TAG, "Computing statistics for " + DateUtils.formatDate(date)); } final Cursor c =
getContentResolver().query(Events.CONTENT_URI,
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/content/NetstatContentProvider.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // }
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import static org.pixmob.freemobile.netstat.Constants.TAG; import java.util.ArrayList; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.content; /** * The content provider for the application database. * @author Pixmob */ public class NetstatContentProvider extends ContentProvider { private static final String EVENTS_TABLE = "events"; private static final int EVENTS = 1; private static final int EVENT_ID = 2; private static final UriMatcher URI_MATCHER; static { URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI(NetstatContract.AUTHORITY, "events", EVENTS); URI_MATCHER.addURI(NetstatContract.AUTHORITY, "event/*", EVENT_ID); } private SQLiteOpenHelper dbHelper; @Override public boolean onCreate() { try { dbHelper = new DatabaseHelper(getContext()); } catch (Exception e) {
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // Path: src/org/pixmob/freemobile/netstat/content/NetstatContentProvider.java import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import static org.pixmob.freemobile.netstat.Constants.TAG; import java.util.ArrayList; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.content; /** * The content provider for the application database. * @author Pixmob */ public class NetstatContentProvider extends ContentProvider { private static final String EVENTS_TABLE = "events"; private static final int EVENTS = 1; private static final int EVENT_ID = 2; private static final UriMatcher URI_MATCHER; static { URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI(NetstatContract.AUTHORITY, "events", EVENTS); URI_MATCHER.addURI(NetstatContract.AUTHORITY, "event/*", EVENT_ID); } private SQLiteOpenHelper dbHelper; @Override public boolean onCreate() { try { dbHelper = new DatabaseHelper(getContext()); } catch (Exception e) {
Log.e(TAG, "Cannot create content provider", e);
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/content/NetstatContentProvider.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // }
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import static org.pixmob.freemobile.netstat.Constants.TAG; import java.util.ArrayList; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.content; /** * The content provider for the application database. * @author Pixmob */ public class NetstatContentProvider extends ContentProvider { private static final String EVENTS_TABLE = "events"; private static final int EVENTS = 1; private static final int EVENT_ID = 2; private static final UriMatcher URI_MATCHER; static { URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI(NetstatContract.AUTHORITY, "events", EVENTS); URI_MATCHER.addURI(NetstatContract.AUTHORITY, "event/*", EVENT_ID); } private SQLiteOpenHelper dbHelper; @Override public boolean onCreate() { try { dbHelper = new DatabaseHelper(getContext()); } catch (Exception e) { Log.e(TAG, "Cannot create content provider", e); return false; } return true; } @Override public String getType(Uri uri) { switch (URI_MATCHER.match(uri)) { case EVENTS:
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // Path: src/org/pixmob/freemobile/netstat/content/NetstatContentProvider.java import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import static org.pixmob.freemobile.netstat.Constants.TAG; import java.util.ArrayList; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.content; /** * The content provider for the application database. * @author Pixmob */ public class NetstatContentProvider extends ContentProvider { private static final String EVENTS_TABLE = "events"; private static final int EVENTS = 1; private static final int EVENT_ID = 2; private static final UriMatcher URI_MATCHER; static { URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI(NetstatContract.AUTHORITY, "events", EVENTS); URI_MATCHER.addURI(NetstatContract.AUTHORITY, "event/*", EVENT_ID); } private SQLiteOpenHelper dbHelper; @Override public boolean onCreate() { try { dbHelper = new DatabaseHelper(getContext()); } catch (Exception e) { Log.e(TAG, "Cannot create content provider", e); return false; } return true; } @Override public String getType(Uri uri) { switch (URI_MATCHER.match(uri)) { case EVENTS:
return Events.CONTENT_TYPE;
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/ui/ExportTask.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // // Path: src/org/pixmob/freemobile/netstat/util/IOUtils.java // public final class IOUtils { // private IOUtils() { // } // // /** // * Quietly close a stream. This method accepts <code>null</code> values. // * @param stream stream to close // */ // public static void close(Closeable stream) { // if (stream != null) { // try { // stream.close(); // } catch (IOException ignore) { // } // } // } // }
import static org.pixmob.freemobile.netstat.Constants.TAG; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import org.pixmob.freemobile.netstat.R; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.IOUtils; import android.content.Context; import android.database.Cursor; import android.os.AsyncTask; import android.os.Environment; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.widget.Toast;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.ui; /** * Export database to a file on the external storage. * @author Pixmob */ class ExportTask extends AsyncTask<Void, Integer, Boolean> { private static final String DIALOG_TAG = "export"; private static final String LINE_SEP = "\r\n"; private static final String COL_SEP = ";"; private static final String DATE_FORMAT = "dd/MM/yyyy HH:mm:ss"; private final Context context; private FragmentManager fragmentManager; private boolean aborted; public ExportTask(final Context context, final FragmentManager fragmentManager) { this.context = context; this.fragmentManager = fragmentManager; } public void setFragmentManager(FragmentManager fragmentManager) { this.fragmentManager = fragmentManager; } @Override protected Boolean doInBackground(Void... params) { if (aborted) { return false; } try { export();
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // // Path: src/org/pixmob/freemobile/netstat/util/IOUtils.java // public final class IOUtils { // private IOUtils() { // } // // /** // * Quietly close a stream. This method accepts <code>null</code> values. // * @param stream stream to close // */ // public static void close(Closeable stream) { // if (stream != null) { // try { // stream.close(); // } catch (IOException ignore) { // } // } // } // } // Path: src/org/pixmob/freemobile/netstat/ui/ExportTask.java import static org.pixmob.freemobile.netstat.Constants.TAG; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import org.pixmob.freemobile.netstat.R; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.IOUtils; import android.content.Context; import android.database.Cursor; import android.os.AsyncTask; import android.os.Environment; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.widget.Toast; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.ui; /** * Export database to a file on the external storage. * @author Pixmob */ class ExportTask extends AsyncTask<Void, Integer, Boolean> { private static final String DIALOG_TAG = "export"; private static final String LINE_SEP = "\r\n"; private static final String COL_SEP = ";"; private static final String DATE_FORMAT = "dd/MM/yyyy HH:mm:ss"; private final Context context; private FragmentManager fragmentManager; private boolean aborted; public ExportTask(final Context context, final FragmentManager fragmentManager) { this.context = context; this.fragmentManager = fragmentManager; } public void setFragmentManager(FragmentManager fragmentManager) { this.fragmentManager = fragmentManager; } @Override protected Boolean doInBackground(Void... params) { if (aborted) { return false; } try { export();
Log.i(TAG, "Export done");
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/ui/ExportTask.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // // Path: src/org/pixmob/freemobile/netstat/util/IOUtils.java // public final class IOUtils { // private IOUtils() { // } // // /** // * Quietly close a stream. This method accepts <code>null</code> values. // * @param stream stream to close // */ // public static void close(Closeable stream) { // if (stream != null) { // try { // stream.close(); // } catch (IOException ignore) { // } // } // } // }
import static org.pixmob.freemobile.netstat.Constants.TAG; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import org.pixmob.freemobile.netstat.R; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.IOUtils; import android.content.Context; import android.database.Cursor; import android.os.AsyncTask; import android.os.Environment; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.widget.Toast;
} @Override protected void onCancelled(Boolean result) { dismissDialog(); } private void dismissDialog() { final DialogFragment f = (DialogFragment) fragmentManager .findFragmentByTag(DIALOG_TAG); if (f != null) { f.dismiss(); } // Clear reference to avoid memory leaks. fragmentManager = null; } private void export() throws IOException { final File outputFile = new File( Environment.getExternalStorageDirectory(), "freemobilenetstat.csv"); Log.i(TAG, "Exporting database to " + outputFile.getPath()); final DateFormat dateFormatter = new SimpleDateFormat(DATE_FORMAT); final BufferedWriter out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outputFile), "UTF-8")); final Cursor c = context.getContentResolver().query(
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // // Path: src/org/pixmob/freemobile/netstat/util/IOUtils.java // public final class IOUtils { // private IOUtils() { // } // // /** // * Quietly close a stream. This method accepts <code>null</code> values. // * @param stream stream to close // */ // public static void close(Closeable stream) { // if (stream != null) { // try { // stream.close(); // } catch (IOException ignore) { // } // } // } // } // Path: src/org/pixmob/freemobile/netstat/ui/ExportTask.java import static org.pixmob.freemobile.netstat.Constants.TAG; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import org.pixmob.freemobile.netstat.R; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.IOUtils; import android.content.Context; import android.database.Cursor; import android.os.AsyncTask; import android.os.Environment; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.widget.Toast; } @Override protected void onCancelled(Boolean result) { dismissDialog(); } private void dismissDialog() { final DialogFragment f = (DialogFragment) fragmentManager .findFragmentByTag(DIALOG_TAG); if (f != null) { f.dismiss(); } // Clear reference to avoid memory leaks. fragmentManager = null; } private void export() throws IOException { final File outputFile = new File( Environment.getExternalStorageDirectory(), "freemobilenetstat.csv"); Log.i(TAG, "Exporting database to " + outputFile.getPath()); final DateFormat dateFormatter = new SimpleDateFormat(DATE_FORMAT); final BufferedWriter out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outputFile), "UTF-8")); final Cursor c = context.getContentResolver().query(
Events.CONTENT_URI,
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/ui/ExportTask.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // // Path: src/org/pixmob/freemobile/netstat/util/IOUtils.java // public final class IOUtils { // private IOUtils() { // } // // /** // * Quietly close a stream. This method accepts <code>null</code> values. // * @param stream stream to close // */ // public static void close(Closeable stream) { // if (stream != null) { // try { // stream.close(); // } catch (IOException ignore) { // } // } // } // }
import static org.pixmob.freemobile.netstat.Constants.TAG; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import org.pixmob.freemobile.netstat.R; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.IOUtils; import android.content.Context; import android.database.Cursor; import android.os.AsyncTask; import android.os.Environment; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.widget.Toast;
int currentRow = 0; final StringBuilder buf = new StringBuilder(1024); buf.append("Timestamp").append(COL_SEP).append("Mobile Operator") .append(COL_SEP).append("Mobile Connected").append(COL_SEP) .append("Wi-Fi Connected").append(COL_SEP) .append("Screen On").append(COL_SEP).append("Battery") .append(COL_SEP).append("Power On").append(LINE_SEP); out.write(buf.toString()); while (c.moveToNext()) { final long t = c.getLong(0); final String mobOp = c.isNull(1) ? "" : c.getString(1); final int mobConn = c.getInt(2) == 1 ? 1 : 0; final int wifiOn = c.getInt(3) == 1 ? 1 : 0; final int bat = c.getInt(4); final int screenOn = c.getInt(5) == 1 ? 1 : 0; final int powerOn = c.getInt(6) == 1 ? 1 : 0; buf.delete(0, buf.length()); buf.append(dateFormatter.format(t)).append(COL_SEP) .append(mobOp).append(COL_SEP).append(mobConn) .append(COL_SEP).append(wifiOn).append(COL_SEP) .append(screenOn).append(COL_SEP).append(bat) .append(COL_SEP).append(powerOn).append(LINE_SEP); out.write(buf.toString()); publishProgress(++currentRow, rowCount); } } finally {
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // // Path: src/org/pixmob/freemobile/netstat/util/IOUtils.java // public final class IOUtils { // private IOUtils() { // } // // /** // * Quietly close a stream. This method accepts <code>null</code> values. // * @param stream stream to close // */ // public static void close(Closeable stream) { // if (stream != null) { // try { // stream.close(); // } catch (IOException ignore) { // } // } // } // } // Path: src/org/pixmob/freemobile/netstat/ui/ExportTask.java import static org.pixmob.freemobile.netstat.Constants.TAG; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import org.pixmob.freemobile.netstat.R; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import org.pixmob.freemobile.netstat.util.IOUtils; import android.content.Context; import android.database.Cursor; import android.os.AsyncTask; import android.os.Environment; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.widget.Toast; int currentRow = 0; final StringBuilder buf = new StringBuilder(1024); buf.append("Timestamp").append(COL_SEP).append("Mobile Operator") .append(COL_SEP).append("Mobile Connected").append(COL_SEP) .append("Wi-Fi Connected").append(COL_SEP) .append("Screen On").append(COL_SEP).append("Battery") .append(COL_SEP).append("Power On").append(LINE_SEP); out.write(buf.toString()); while (c.moveToNext()) { final long t = c.getLong(0); final String mobOp = c.isNull(1) ? "" : c.getString(1); final int mobConn = c.getInt(2) == 1 ? 1 : 0; final int wifiOn = c.getInt(3) == 1 ? 1 : 0; final int bat = c.getInt(4); final int screenOn = c.getInt(5) == 1 ? 1 : 0; final int powerOn = c.getInt(6) == 1 ? 1 : 0; buf.delete(0, buf.length()); buf.append(dateFormatter.format(t)).append(COL_SEP) .append(mobOp).append(COL_SEP).append(mobConn) .append(COL_SEP).append(wifiOn).append(COL_SEP) .append(screenOn).append(COL_SEP).append(bat) .append(COL_SEP).append(powerOn).append(LINE_SEP); out.write(buf.toString()); publishProgress(++currentRow, rowCount); } } finally {
IOUtils.close(out);
pixmob/freemobilenetstat
deps/httpclient/demo/src/org/pixmob/httpclient/demo/tasks/DownloadFileTask.java
// Path: deps/httpclient/demo/src/org/pixmob/httpclient/demo/Task.java // public abstract class Task { // private final Context context; // private final String name; // private final String sourceCodeUrl; // // public Task(final Context context, final int name) { // this.context = context; // this.name = context.getString(name); // this.sourceCodeUrl = "https://raw.github.com/pixmob/httpclient/master/demo/src/" // + getClass().getName().replace('.', '/') + ".java"; // } // // protected HttpClient createClient() { // final HttpClient hc = new HttpClient(context); // hc.setConnectTimeout(4000); // hc.setReadTimeout(8000); // return hc; // } // // public Context getContext() { // return context; // } // // public String getName() { // return name; // } // // public String getSourceCodeUrl() { // return sourceCodeUrl; // } // // public static void assertEquals(String expected, String tested) throws TaskExecutionFailedException { // if (expected == null && tested == null) { // return; // } // if (expected.equals(tested)) { // return; // } // throw new TaskExecutionFailedException("Expected: " + expected + "; got " + tested); // } // // public final void run() throws TaskExecutionFailedException { // try { // doRun(); // } catch (TaskExecutionFailedException e) { // throw e; // } catch (Exception e) { // throw new TaskExecutionFailedException("Task execution failed", e); // } // } // // protected abstract void doRun() throws Exception; // } // // Path: deps/httpclient/demo/src/org/pixmob/httpclient/demo/TaskExecutionFailedException.java // public class TaskExecutionFailedException extends Exception { // private static final long serialVersionUID = 1L; // // public TaskExecutionFailedException(final String message, // final Throwable cause) { // super(message, cause); // } // // public TaskExecutionFailedException(final String message) { // this(message, null); // } // }
import java.io.File; import org.pixmob.httpclient.HttpClient; import org.pixmob.httpclient.demo.R; import org.pixmob.httpclient.demo.Task; import org.pixmob.httpclient.demo.TaskExecutionFailedException; import android.content.Context;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.httpclient.demo.tasks; /** * {@link Task} implementation for downloading a file. * @author Pixmob */ public class DownloadFileTask extends Task { public DownloadFileTask(final Context context) { super(context, R.string.task_download_file); } @Override protected void doRun() throws Exception { final File imgFile = new File(getContext().getCacheDir(), "google_logo.png"); imgFile.delete(); final HttpClient hc = createClient(); hc.get("http://www.google.fr/images/srpr/logo3w.png").to(imgFile).execute(); if (!imgFile.exists() || imgFile.length() == 0) {
// Path: deps/httpclient/demo/src/org/pixmob/httpclient/demo/Task.java // public abstract class Task { // private final Context context; // private final String name; // private final String sourceCodeUrl; // // public Task(final Context context, final int name) { // this.context = context; // this.name = context.getString(name); // this.sourceCodeUrl = "https://raw.github.com/pixmob/httpclient/master/demo/src/" // + getClass().getName().replace('.', '/') + ".java"; // } // // protected HttpClient createClient() { // final HttpClient hc = new HttpClient(context); // hc.setConnectTimeout(4000); // hc.setReadTimeout(8000); // return hc; // } // // public Context getContext() { // return context; // } // // public String getName() { // return name; // } // // public String getSourceCodeUrl() { // return sourceCodeUrl; // } // // public static void assertEquals(String expected, String tested) throws TaskExecutionFailedException { // if (expected == null && tested == null) { // return; // } // if (expected.equals(tested)) { // return; // } // throw new TaskExecutionFailedException("Expected: " + expected + "; got " + tested); // } // // public final void run() throws TaskExecutionFailedException { // try { // doRun(); // } catch (TaskExecutionFailedException e) { // throw e; // } catch (Exception e) { // throw new TaskExecutionFailedException("Task execution failed", e); // } // } // // protected abstract void doRun() throws Exception; // } // // Path: deps/httpclient/demo/src/org/pixmob/httpclient/demo/TaskExecutionFailedException.java // public class TaskExecutionFailedException extends Exception { // private static final long serialVersionUID = 1L; // // public TaskExecutionFailedException(final String message, // final Throwable cause) { // super(message, cause); // } // // public TaskExecutionFailedException(final String message) { // this(message, null); // } // } // Path: deps/httpclient/demo/src/org/pixmob/httpclient/demo/tasks/DownloadFileTask.java import java.io.File; import org.pixmob.httpclient.HttpClient; import org.pixmob.httpclient.demo.R; import org.pixmob.httpclient.demo.Task; import org.pixmob.httpclient.demo.TaskExecutionFailedException; import android.content.Context; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.httpclient.demo.tasks; /** * {@link Task} implementation for downloading a file. * @author Pixmob */ public class DownloadFileTask extends Task { public DownloadFileTask(final Context context) { super(context, R.string.task_download_file); } @Override protected void doRun() throws Exception { final File imgFile = new File(getContext().getCacheDir(), "google_logo.png"); imgFile.delete(); final HttpClient hc = createClient(); hc.get("http://www.google.fr/images/srpr/logo3w.png").to(imgFile).execute(); if (!imgFile.exists() || imgFile.length() == 0) {
throw new TaskExecutionFailedException("File download failed");
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/util/IntentFactory.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS = "network_operator_settings"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_STATISTICS = "statistics"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_NOTIF_ACTION = "pref_notif_action"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/ui/Netstat.java // @SuppressLint("CommitPrefEdits") // public class Netstat extends FragmentActivity { // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // requestWindowFeature(Window.FEATURE_NO_TITLE); // } // // if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) { // final StatisticsFragment f = new StatisticsFragment(); // getSupportFragmentManager().beginTransaction().add(android.R.id.content, f).commit(); // } // // final Context c = getApplicationContext(); // final Intent i = new Intent(c, MonitorService.class); // c.startService(i); // // SyncService.schedule(this, true); // // final int applicationVersion; // try { // applicationVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; // } catch (NameNotFoundException e) { // // Unlikely to happen. // throw new RuntimeException("Failed to get application version", e); // } // // final String versionKey = "version"; // final SharedPreferences prefs = getPreferences(MODE_PRIVATE); // final int lastKnownVersion = prefs.getInt(versionKey, 0); // if (lastKnownVersion != applicationVersion) { // // Store the current application version. // final SharedPreferences.Editor prefsEditor = prefs.edit(); // prefsEditor.putInt(versionKey, applicationVersion); // Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); // // // The application was updated: let's show changelog. // startActivity(new Intent(this, DocumentBrowser.class).putExtra(DocumentBrowser.INTENT_EXTRA_URL, // "CHANGELOG.html")); // } // } // // @Override // public void onAttachedToWindow() { // super.onAttachedToWindow(); // // // Enable "better" gradients: // // http://stackoverflow.com/a/2932030/422906 // final Window window = getWindow(); // window.setFormat(PixelFormat.RGBA_8888); // window.getDecorView().getBackground().setDither(true); // } // }
import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS; import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_STATISTICS; import static org.pixmob.freemobile.netstat.Constants.SP_KEY_NOTIF_ACTION; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import org.pixmob.freemobile.netstat.ui.Netstat; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.provider.Settings;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.util; /** * Application intents. * @author Pixmob */ public final class IntentFactory { private IntentFactory() { } /** * Open network operator settings activity. */ public static Intent networkOperatorSettings(Context context) { // Check if the network operator settings intent is available. Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); if (!networkOperatorSettingsAvailable) { // The previous intent action is not available with some devices: // http://stackoverflow.com/a/6789616/422906 networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", "com.android.phone.NetworkSetting")); networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); } return networkOperatorSettingsIntent; } /** * Open statistics. */ public static Intent statistics(Context context) {
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS = "network_operator_settings"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_STATISTICS = "statistics"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_NOTIF_ACTION = "pref_notif_action"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/ui/Netstat.java // @SuppressLint("CommitPrefEdits") // public class Netstat extends FragmentActivity { // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // requestWindowFeature(Window.FEATURE_NO_TITLE); // } // // if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) { // final StatisticsFragment f = new StatisticsFragment(); // getSupportFragmentManager().beginTransaction().add(android.R.id.content, f).commit(); // } // // final Context c = getApplicationContext(); // final Intent i = new Intent(c, MonitorService.class); // c.startService(i); // // SyncService.schedule(this, true); // // final int applicationVersion; // try { // applicationVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; // } catch (NameNotFoundException e) { // // Unlikely to happen. // throw new RuntimeException("Failed to get application version", e); // } // // final String versionKey = "version"; // final SharedPreferences prefs = getPreferences(MODE_PRIVATE); // final int lastKnownVersion = prefs.getInt(versionKey, 0); // if (lastKnownVersion != applicationVersion) { // // Store the current application version. // final SharedPreferences.Editor prefsEditor = prefs.edit(); // prefsEditor.putInt(versionKey, applicationVersion); // Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); // // // The application was updated: let's show changelog. // startActivity(new Intent(this, DocumentBrowser.class).putExtra(DocumentBrowser.INTENT_EXTRA_URL, // "CHANGELOG.html")); // } // } // // @Override // public void onAttachedToWindow() { // super.onAttachedToWindow(); // // // Enable "better" gradients: // // http://stackoverflow.com/a/2932030/422906 // final Window window = getWindow(); // window.setFormat(PixelFormat.RGBA_8888); // window.getDecorView().getBackground().setDither(true); // } // } // Path: src/org/pixmob/freemobile/netstat/util/IntentFactory.java import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS; import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_STATISTICS; import static org.pixmob.freemobile.netstat.Constants.SP_KEY_NOTIF_ACTION; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import org.pixmob.freemobile.netstat.ui.Netstat; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.provider.Settings; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.util; /** * Application intents. * @author Pixmob */ public final class IntentFactory { private IntentFactory() { } /** * Open network operator settings activity. */ public static Intent networkOperatorSettings(Context context) { // Check if the network operator settings intent is available. Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); if (!networkOperatorSettingsAvailable) { // The previous intent action is not available with some devices: // http://stackoverflow.com/a/6789616/422906 networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", "com.android.phone.NetworkSetting")); networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); } return networkOperatorSettingsIntent; } /** * Open statistics. */ public static Intent statistics(Context context) {
return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/util/IntentFactory.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS = "network_operator_settings"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_STATISTICS = "statistics"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_NOTIF_ACTION = "pref_notif_action"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/ui/Netstat.java // @SuppressLint("CommitPrefEdits") // public class Netstat extends FragmentActivity { // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // requestWindowFeature(Window.FEATURE_NO_TITLE); // } // // if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) { // final StatisticsFragment f = new StatisticsFragment(); // getSupportFragmentManager().beginTransaction().add(android.R.id.content, f).commit(); // } // // final Context c = getApplicationContext(); // final Intent i = new Intent(c, MonitorService.class); // c.startService(i); // // SyncService.schedule(this, true); // // final int applicationVersion; // try { // applicationVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; // } catch (NameNotFoundException e) { // // Unlikely to happen. // throw new RuntimeException("Failed to get application version", e); // } // // final String versionKey = "version"; // final SharedPreferences prefs = getPreferences(MODE_PRIVATE); // final int lastKnownVersion = prefs.getInt(versionKey, 0); // if (lastKnownVersion != applicationVersion) { // // Store the current application version. // final SharedPreferences.Editor prefsEditor = prefs.edit(); // prefsEditor.putInt(versionKey, applicationVersion); // Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); // // // The application was updated: let's show changelog. // startActivity(new Intent(this, DocumentBrowser.class).putExtra(DocumentBrowser.INTENT_EXTRA_URL, // "CHANGELOG.html")); // } // } // // @Override // public void onAttachedToWindow() { // super.onAttachedToWindow(); // // // Enable "better" gradients: // // http://stackoverflow.com/a/2932030/422906 // final Window window = getWindow(); // window.setFormat(PixelFormat.RGBA_8888); // window.getDecorView().getBackground().setDither(true); // } // }
import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS; import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_STATISTICS; import static org.pixmob.freemobile.netstat.Constants.SP_KEY_NOTIF_ACTION; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import org.pixmob.freemobile.netstat.ui.Netstat; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.provider.Settings;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.util; /** * Application intents. * @author Pixmob */ public final class IntentFactory { private IntentFactory() { } /** * Open network operator settings activity. */ public static Intent networkOperatorSettings(Context context) { // Check if the network operator settings intent is available. Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); if (!networkOperatorSettingsAvailable) { // The previous intent action is not available with some devices: // http://stackoverflow.com/a/6789616/422906 networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", "com.android.phone.NetworkSetting")); networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); } return networkOperatorSettingsIntent; } /** * Open statistics. */ public static Intent statistics(Context context) { return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } /** * Get the intent to handle notification action. */ public static Intent notificationAction(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { return statistics(context); }
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS = "network_operator_settings"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_STATISTICS = "statistics"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_NOTIF_ACTION = "pref_notif_action"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/ui/Netstat.java // @SuppressLint("CommitPrefEdits") // public class Netstat extends FragmentActivity { // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // requestWindowFeature(Window.FEATURE_NO_TITLE); // } // // if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) { // final StatisticsFragment f = new StatisticsFragment(); // getSupportFragmentManager().beginTransaction().add(android.R.id.content, f).commit(); // } // // final Context c = getApplicationContext(); // final Intent i = new Intent(c, MonitorService.class); // c.startService(i); // // SyncService.schedule(this, true); // // final int applicationVersion; // try { // applicationVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; // } catch (NameNotFoundException e) { // // Unlikely to happen. // throw new RuntimeException("Failed to get application version", e); // } // // final String versionKey = "version"; // final SharedPreferences prefs = getPreferences(MODE_PRIVATE); // final int lastKnownVersion = prefs.getInt(versionKey, 0); // if (lastKnownVersion != applicationVersion) { // // Store the current application version. // final SharedPreferences.Editor prefsEditor = prefs.edit(); // prefsEditor.putInt(versionKey, applicationVersion); // Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); // // // The application was updated: let's show changelog. // startActivity(new Intent(this, DocumentBrowser.class).putExtra(DocumentBrowser.INTENT_EXTRA_URL, // "CHANGELOG.html")); // } // } // // @Override // public void onAttachedToWindow() { // super.onAttachedToWindow(); // // // Enable "better" gradients: // // http://stackoverflow.com/a/2932030/422906 // final Window window = getWindow(); // window.setFormat(PixelFormat.RGBA_8888); // window.getDecorView().getBackground().setDither(true); // } // } // Path: src/org/pixmob/freemobile/netstat/util/IntentFactory.java import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS; import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_STATISTICS; import static org.pixmob.freemobile.netstat.Constants.SP_KEY_NOTIF_ACTION; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import org.pixmob.freemobile.netstat.ui.Netstat; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.provider.Settings; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.util; /** * Application intents. * @author Pixmob */ public final class IntentFactory { private IntentFactory() { } /** * Open network operator settings activity. */ public static Intent networkOperatorSettings(Context context) { // Check if the network operator settings intent is available. Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); if (!networkOperatorSettingsAvailable) { // The previous intent action is not available with some devices: // http://stackoverflow.com/a/6789616/422906 networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", "com.android.phone.NetworkSetting")); networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); } return networkOperatorSettingsIntent; } /** * Open statistics. */ public static Intent statistics(Context context) { return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } /** * Get the intent to handle notification action. */ public static Intent notificationAction(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { return statistics(context); }
final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/util/IntentFactory.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS = "network_operator_settings"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_STATISTICS = "statistics"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_NOTIF_ACTION = "pref_notif_action"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/ui/Netstat.java // @SuppressLint("CommitPrefEdits") // public class Netstat extends FragmentActivity { // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // requestWindowFeature(Window.FEATURE_NO_TITLE); // } // // if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) { // final StatisticsFragment f = new StatisticsFragment(); // getSupportFragmentManager().beginTransaction().add(android.R.id.content, f).commit(); // } // // final Context c = getApplicationContext(); // final Intent i = new Intent(c, MonitorService.class); // c.startService(i); // // SyncService.schedule(this, true); // // final int applicationVersion; // try { // applicationVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; // } catch (NameNotFoundException e) { // // Unlikely to happen. // throw new RuntimeException("Failed to get application version", e); // } // // final String versionKey = "version"; // final SharedPreferences prefs = getPreferences(MODE_PRIVATE); // final int lastKnownVersion = prefs.getInt(versionKey, 0); // if (lastKnownVersion != applicationVersion) { // // Store the current application version. // final SharedPreferences.Editor prefsEditor = prefs.edit(); // prefsEditor.putInt(versionKey, applicationVersion); // Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); // // // The application was updated: let's show changelog. // startActivity(new Intent(this, DocumentBrowser.class).putExtra(DocumentBrowser.INTENT_EXTRA_URL, // "CHANGELOG.html")); // } // } // // @Override // public void onAttachedToWindow() { // super.onAttachedToWindow(); // // // Enable "better" gradients: // // http://stackoverflow.com/a/2932030/422906 // final Window window = getWindow(); // window.setFormat(PixelFormat.RGBA_8888); // window.getDecorView().getBackground().setDither(true); // } // }
import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS; import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_STATISTICS; import static org.pixmob.freemobile.netstat.Constants.SP_KEY_NOTIF_ACTION; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import org.pixmob.freemobile.netstat.ui.Netstat; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.provider.Settings;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.util; /** * Application intents. * @author Pixmob */ public final class IntentFactory { private IntentFactory() { } /** * Open network operator settings activity. */ public static Intent networkOperatorSettings(Context context) { // Check if the network operator settings intent is available. Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); if (!networkOperatorSettingsAvailable) { // The previous intent action is not available with some devices: // http://stackoverflow.com/a/6789616/422906 networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", "com.android.phone.NetworkSetting")); networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); } return networkOperatorSettingsIntent; } /** * Open statistics. */ public static Intent statistics(Context context) { return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } /** * Get the intent to handle notification action. */ public static Intent notificationAction(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { return statistics(context); } final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS = "network_operator_settings"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_STATISTICS = "statistics"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_NOTIF_ACTION = "pref_notif_action"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/ui/Netstat.java // @SuppressLint("CommitPrefEdits") // public class Netstat extends FragmentActivity { // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // requestWindowFeature(Window.FEATURE_NO_TITLE); // } // // if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) { // final StatisticsFragment f = new StatisticsFragment(); // getSupportFragmentManager().beginTransaction().add(android.R.id.content, f).commit(); // } // // final Context c = getApplicationContext(); // final Intent i = new Intent(c, MonitorService.class); // c.startService(i); // // SyncService.schedule(this, true); // // final int applicationVersion; // try { // applicationVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; // } catch (NameNotFoundException e) { // // Unlikely to happen. // throw new RuntimeException("Failed to get application version", e); // } // // final String versionKey = "version"; // final SharedPreferences prefs = getPreferences(MODE_PRIVATE); // final int lastKnownVersion = prefs.getInt(versionKey, 0); // if (lastKnownVersion != applicationVersion) { // // Store the current application version. // final SharedPreferences.Editor prefsEditor = prefs.edit(); // prefsEditor.putInt(versionKey, applicationVersion); // Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); // // // The application was updated: let's show changelog. // startActivity(new Intent(this, DocumentBrowser.class).putExtra(DocumentBrowser.INTENT_EXTRA_URL, // "CHANGELOG.html")); // } // } // // @Override // public void onAttachedToWindow() { // super.onAttachedToWindow(); // // // Enable "better" gradients: // // http://stackoverflow.com/a/2932030/422906 // final Window window = getWindow(); // window.setFormat(PixelFormat.RGBA_8888); // window.getDecorView().getBackground().setDither(true); // } // } // Path: src/org/pixmob/freemobile/netstat/util/IntentFactory.java import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS; import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_STATISTICS; import static org.pixmob.freemobile.netstat.Constants.SP_KEY_NOTIF_ACTION; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import org.pixmob.freemobile.netstat.ui.Netstat; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.provider.Settings; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.util; /** * Application intents. * @author Pixmob */ public final class IntentFactory { private IntentFactory() { } /** * Open network operator settings activity. */ public static Intent networkOperatorSettings(Context context) { // Check if the network operator settings intent is available. Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); if (!networkOperatorSettingsAvailable) { // The previous intent action is not available with some devices: // http://stackoverflow.com/a/6789616/422906 networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", "com.android.phone.NetworkSetting")); networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); } return networkOperatorSettingsIntent; } /** * Open statistics. */ public static Intent statistics(Context context) { return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } /** * Get the intent to handle notification action. */ public static Intent notificationAction(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { return statistics(context); } final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
final String notifAction = p.getString(SP_KEY_NOTIF_ACTION, NOTIF_ACTION_STATISTICS);
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/util/IntentFactory.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS = "network_operator_settings"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_STATISTICS = "statistics"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_NOTIF_ACTION = "pref_notif_action"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/ui/Netstat.java // @SuppressLint("CommitPrefEdits") // public class Netstat extends FragmentActivity { // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // requestWindowFeature(Window.FEATURE_NO_TITLE); // } // // if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) { // final StatisticsFragment f = new StatisticsFragment(); // getSupportFragmentManager().beginTransaction().add(android.R.id.content, f).commit(); // } // // final Context c = getApplicationContext(); // final Intent i = new Intent(c, MonitorService.class); // c.startService(i); // // SyncService.schedule(this, true); // // final int applicationVersion; // try { // applicationVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; // } catch (NameNotFoundException e) { // // Unlikely to happen. // throw new RuntimeException("Failed to get application version", e); // } // // final String versionKey = "version"; // final SharedPreferences prefs = getPreferences(MODE_PRIVATE); // final int lastKnownVersion = prefs.getInt(versionKey, 0); // if (lastKnownVersion != applicationVersion) { // // Store the current application version. // final SharedPreferences.Editor prefsEditor = prefs.edit(); // prefsEditor.putInt(versionKey, applicationVersion); // Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); // // // The application was updated: let's show changelog. // startActivity(new Intent(this, DocumentBrowser.class).putExtra(DocumentBrowser.INTENT_EXTRA_URL, // "CHANGELOG.html")); // } // } // // @Override // public void onAttachedToWindow() { // super.onAttachedToWindow(); // // // Enable "better" gradients: // // http://stackoverflow.com/a/2932030/422906 // final Window window = getWindow(); // window.setFormat(PixelFormat.RGBA_8888); // window.getDecorView().getBackground().setDither(true); // } // }
import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS; import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_STATISTICS; import static org.pixmob.freemobile.netstat.Constants.SP_KEY_NOTIF_ACTION; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import org.pixmob.freemobile.netstat.ui.Netstat; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.provider.Settings;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.util; /** * Application intents. * @author Pixmob */ public final class IntentFactory { private IntentFactory() { } /** * Open network operator settings activity. */ public static Intent networkOperatorSettings(Context context) { // Check if the network operator settings intent is available. Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); if (!networkOperatorSettingsAvailable) { // The previous intent action is not available with some devices: // http://stackoverflow.com/a/6789616/422906 networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", "com.android.phone.NetworkSetting")); networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); } return networkOperatorSettingsIntent; } /** * Open statistics. */ public static Intent statistics(Context context) { return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } /** * Get the intent to handle notification action. */ public static Intent notificationAction(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { return statistics(context); } final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS = "network_operator_settings"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_STATISTICS = "statistics"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_NOTIF_ACTION = "pref_notif_action"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/ui/Netstat.java // @SuppressLint("CommitPrefEdits") // public class Netstat extends FragmentActivity { // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // requestWindowFeature(Window.FEATURE_NO_TITLE); // } // // if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) { // final StatisticsFragment f = new StatisticsFragment(); // getSupportFragmentManager().beginTransaction().add(android.R.id.content, f).commit(); // } // // final Context c = getApplicationContext(); // final Intent i = new Intent(c, MonitorService.class); // c.startService(i); // // SyncService.schedule(this, true); // // final int applicationVersion; // try { // applicationVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; // } catch (NameNotFoundException e) { // // Unlikely to happen. // throw new RuntimeException("Failed to get application version", e); // } // // final String versionKey = "version"; // final SharedPreferences prefs = getPreferences(MODE_PRIVATE); // final int lastKnownVersion = prefs.getInt(versionKey, 0); // if (lastKnownVersion != applicationVersion) { // // Store the current application version. // final SharedPreferences.Editor prefsEditor = prefs.edit(); // prefsEditor.putInt(versionKey, applicationVersion); // Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); // // // The application was updated: let's show changelog. // startActivity(new Intent(this, DocumentBrowser.class).putExtra(DocumentBrowser.INTENT_EXTRA_URL, // "CHANGELOG.html")); // } // } // // @Override // public void onAttachedToWindow() { // super.onAttachedToWindow(); // // // Enable "better" gradients: // // http://stackoverflow.com/a/2932030/422906 // final Window window = getWindow(); // window.setFormat(PixelFormat.RGBA_8888); // window.getDecorView().getBackground().setDither(true); // } // } // Path: src/org/pixmob/freemobile/netstat/util/IntentFactory.java import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS; import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_STATISTICS; import static org.pixmob.freemobile.netstat.Constants.SP_KEY_NOTIF_ACTION; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import org.pixmob.freemobile.netstat.ui.Netstat; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.provider.Settings; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.util; /** * Application intents. * @author Pixmob */ public final class IntentFactory { private IntentFactory() { } /** * Open network operator settings activity. */ public static Intent networkOperatorSettings(Context context) { // Check if the network operator settings intent is available. Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); if (!networkOperatorSettingsAvailable) { // The previous intent action is not available with some devices: // http://stackoverflow.com/a/6789616/422906 networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", "com.android.phone.NetworkSetting")); networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); } return networkOperatorSettingsIntent; } /** * Open statistics. */ public static Intent statistics(Context context) { return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } /** * Get the intent to handle notification action. */ public static Intent notificationAction(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { return statistics(context); } final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
final String notifAction = p.getString(SP_KEY_NOTIF_ACTION, NOTIF_ACTION_STATISTICS);
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/util/IntentFactory.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS = "network_operator_settings"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_STATISTICS = "statistics"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_NOTIF_ACTION = "pref_notif_action"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/ui/Netstat.java // @SuppressLint("CommitPrefEdits") // public class Netstat extends FragmentActivity { // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // requestWindowFeature(Window.FEATURE_NO_TITLE); // } // // if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) { // final StatisticsFragment f = new StatisticsFragment(); // getSupportFragmentManager().beginTransaction().add(android.R.id.content, f).commit(); // } // // final Context c = getApplicationContext(); // final Intent i = new Intent(c, MonitorService.class); // c.startService(i); // // SyncService.schedule(this, true); // // final int applicationVersion; // try { // applicationVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; // } catch (NameNotFoundException e) { // // Unlikely to happen. // throw new RuntimeException("Failed to get application version", e); // } // // final String versionKey = "version"; // final SharedPreferences prefs = getPreferences(MODE_PRIVATE); // final int lastKnownVersion = prefs.getInt(versionKey, 0); // if (lastKnownVersion != applicationVersion) { // // Store the current application version. // final SharedPreferences.Editor prefsEditor = prefs.edit(); // prefsEditor.putInt(versionKey, applicationVersion); // Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); // // // The application was updated: let's show changelog. // startActivity(new Intent(this, DocumentBrowser.class).putExtra(DocumentBrowser.INTENT_EXTRA_URL, // "CHANGELOG.html")); // } // } // // @Override // public void onAttachedToWindow() { // super.onAttachedToWindow(); // // // Enable "better" gradients: // // http://stackoverflow.com/a/2932030/422906 // final Window window = getWindow(); // window.setFormat(PixelFormat.RGBA_8888); // window.getDecorView().getBackground().setDither(true); // } // }
import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS; import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_STATISTICS; import static org.pixmob.freemobile.netstat.Constants.SP_KEY_NOTIF_ACTION; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import org.pixmob.freemobile.netstat.ui.Netstat; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.provider.Settings;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.util; /** * Application intents. * @author Pixmob */ public final class IntentFactory { private IntentFactory() { } /** * Open network operator settings activity. */ public static Intent networkOperatorSettings(Context context) { // Check if the network operator settings intent is available. Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); if (!networkOperatorSettingsAvailable) { // The previous intent action is not available with some devices: // http://stackoverflow.com/a/6789616/422906 networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", "com.android.phone.NetworkSetting")); networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); } return networkOperatorSettingsIntent; } /** * Open statistics. */ public static Intent statistics(Context context) { return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } /** * Get the intent to handle notification action. */ public static Intent notificationAction(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { return statistics(context); } final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); final String notifAction = p.getString(SP_KEY_NOTIF_ACTION, NOTIF_ACTION_STATISTICS); if (NOTIF_ACTION_STATISTICS.equals(notifAction)) { return statistics(context); }
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS = "network_operator_settings"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String NOTIF_ACTION_STATISTICS = "statistics"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_KEY_NOTIF_ACTION = "pref_notif_action"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String SP_NAME = "netstat"; // // Path: src/org/pixmob/freemobile/netstat/ui/Netstat.java // @SuppressLint("CommitPrefEdits") // public class Netstat extends FragmentActivity { // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // requestWindowFeature(Window.FEATURE_NO_TITLE); // } // // if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) { // final StatisticsFragment f = new StatisticsFragment(); // getSupportFragmentManager().beginTransaction().add(android.R.id.content, f).commit(); // } // // final Context c = getApplicationContext(); // final Intent i = new Intent(c, MonitorService.class); // c.startService(i); // // SyncService.schedule(this, true); // // final int applicationVersion; // try { // applicationVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; // } catch (NameNotFoundException e) { // // Unlikely to happen. // throw new RuntimeException("Failed to get application version", e); // } // // final String versionKey = "version"; // final SharedPreferences prefs = getPreferences(MODE_PRIVATE); // final int lastKnownVersion = prefs.getInt(versionKey, 0); // if (lastKnownVersion != applicationVersion) { // // Store the current application version. // final SharedPreferences.Editor prefsEditor = prefs.edit(); // prefsEditor.putInt(versionKey, applicationVersion); // Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); // // // The application was updated: let's show changelog. // startActivity(new Intent(this, DocumentBrowser.class).putExtra(DocumentBrowser.INTENT_EXTRA_URL, // "CHANGELOG.html")); // } // } // // @Override // public void onAttachedToWindow() { // super.onAttachedToWindow(); // // // Enable "better" gradients: // // http://stackoverflow.com/a/2932030/422906 // final Window window = getWindow(); // window.setFormat(PixelFormat.RGBA_8888); // window.getDecorView().getBackground().setDither(true); // } // } // Path: src/org/pixmob/freemobile/netstat/util/IntentFactory.java import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS; import static org.pixmob.freemobile.netstat.Constants.NOTIF_ACTION_STATISTICS; import static org.pixmob.freemobile.netstat.Constants.SP_KEY_NOTIF_ACTION; import static org.pixmob.freemobile.netstat.Constants.SP_NAME; import org.pixmob.freemobile.netstat.ui.Netstat; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.provider.Settings; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.util; /** * Application intents. * @author Pixmob */ public final class IntentFactory { private IntentFactory() { } /** * Open network operator settings activity. */ public static Intent networkOperatorSettings(Context context) { // Check if the network operator settings intent is available. Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); if (!networkOperatorSettingsAvailable) { // The previous intent action is not available with some devices: // http://stackoverflow.com/a/6789616/422906 networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", "com.android.phone.NetworkSetting")); networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); } return networkOperatorSettingsIntent; } /** * Open statistics. */ public static Intent statistics(Context context) { return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } /** * Get the intent to handle notification action. */ public static Intent notificationAction(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { return statistics(context); } final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); final String notifAction = p.getString(SP_KEY_NOTIF_ACTION, NOTIF_ACTION_STATISTICS); if (NOTIF_ACTION_STATISTICS.equals(notifAction)) { return statistics(context); }
if (NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS.equals(notifAction)) {
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/DatabaseCleanup.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // }
import static org.pixmob.freemobile.netstat.Constants.TAG; import java.util.Calendar; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Process; import android.util.Log;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * This broadcast receiver removes old data from the database. * @author Pixmob */ public class DatabaseCleanup extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // The database cleanup is done in a background thread so that the main // thread is not blocked. new DatabaseCleanupTask(context.getApplicationContext()).start(); } /** * Internal thread for executing database cleanup. * @author Pixmob */ private static class DatabaseCleanupTask extends Thread { private final Context context; public DatabaseCleanupTask(final Context context) { this.context = context; } @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); try { cleanupDatabase(); } catch (Exception e) {
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // Path: src/org/pixmob/freemobile/netstat/DatabaseCleanup.java import static org.pixmob.freemobile.netstat.Constants.TAG; import java.util.Calendar; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Process; import android.util.Log; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * This broadcast receiver removes old data from the database. * @author Pixmob */ public class DatabaseCleanup extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // The database cleanup is done in a background thread so that the main // thread is not blocked. new DatabaseCleanupTask(context.getApplicationContext()).start(); } /** * Internal thread for executing database cleanup. * @author Pixmob */ private static class DatabaseCleanupTask extends Thread { private final Context context; public DatabaseCleanupTask(final Context context) { this.context = context; } @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); try { cleanupDatabase(); } catch (Exception e) {
Log.e(TAG, "Failed to cleanup database", e);
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/DatabaseCleanup.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // }
import static org.pixmob.freemobile.netstat.Constants.TAG; import java.util.Calendar; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Process; import android.util.Log;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * This broadcast receiver removes old data from the database. * @author Pixmob */ public class DatabaseCleanup extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // The database cleanup is done in a background thread so that the main // thread is not blocked. new DatabaseCleanupTask(context.getApplicationContext()).start(); } /** * Internal thread for executing database cleanup. * @author Pixmob */ private static class DatabaseCleanupTask extends Thread { private final Context context; public DatabaseCleanupTask(final Context context) { this.context = context; } @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); try { cleanupDatabase(); } catch (Exception e) { Log.e(TAG, "Failed to cleanup database", e); } } private void cleanupDatabase() throws Exception { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.MONTH, -1); Log.i(TAG, "Deleting events older than " + cal.getTime()); // Delete oldest events. final long timestampLimit = cal.getTimeInMillis(); final int deletedEvents = context.getContentResolver().delete(
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // Path: src/org/pixmob/freemobile/netstat/DatabaseCleanup.java import static org.pixmob.freemobile.netstat.Constants.TAG; import java.util.Calendar; import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Process; import android.util.Log; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * This broadcast receiver removes old data from the database. * @author Pixmob */ public class DatabaseCleanup extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // The database cleanup is done in a background thread so that the main // thread is not blocked. new DatabaseCleanupTask(context.getApplicationContext()).start(); } /** * Internal thread for executing database cleanup. * @author Pixmob */ private static class DatabaseCleanupTask extends Thread { private final Context context; public DatabaseCleanupTask(final Context context) { this.context = context; } @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); try { cleanupDatabase(); } catch (Exception e) { Log.e(TAG, "Failed to cleanup database", e); } } private void cleanupDatabase() throws Exception { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.MONTH, -1); Log.i(TAG, "Deleting events older than " + cal.getTime()); // Delete oldest events. final long timestampLimit = cal.getTimeInMillis(); final int deletedEvents = context.getContentResolver().delete(
Events.CONTENT_URI, Events.TIMESTAMP + "<?",
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/NotificationHandler.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String ACTION_NOTIFICATION = "org.pixmob.freemobile.netstat.notif"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/util/IntentFactory.java // public final class IntentFactory { // private IntentFactory() { // } // // /** // * Open network operator settings activity. // */ // public static Intent networkOperatorSettings(Context context) { // // Check if the network operator settings intent is available. // Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); // boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); // if (!networkOperatorSettingsAvailable) { // // The previous intent action is not available with some devices: // // http://stackoverflow.com/a/6789616/422906 // networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); // networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", // "com.android.phone.NetworkSetting")); // networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); // } // return networkOperatorSettingsIntent; // } // // /** // * Open statistics. // */ // public static Intent statistics(Context context) { // return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // } // // /** // * Get the intent to handle notification action. // */ // public static Intent notificationAction(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return statistics(context); // } // // final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); // final String notifAction = p.getString(SP_KEY_NOTIF_ACTION, NOTIF_ACTION_STATISTICS); // if (NOTIF_ACTION_STATISTICS.equals(notifAction)) { // return statistics(context); // } // if (NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS.equals(notifAction)) { // return networkOperatorSettings(context); // } // return null; // } // // private static boolean isIntentAvailable(Context context, Intent i) { // return !context.getPackageManager().queryIntentActivities(i, 0).isEmpty(); // } // }
import static org.pixmob.freemobile.netstat.Constants.ACTION_NOTIFICATION; import static org.pixmob.freemobile.netstat.Constants.TAG; import org.pixmob.freemobile.netstat.util.IntentFactory; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * Handle notification action. * @author Pixmob */ public class NotificationHandler extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String ACTION_NOTIFICATION = "org.pixmob.freemobile.netstat.notif"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/util/IntentFactory.java // public final class IntentFactory { // private IntentFactory() { // } // // /** // * Open network operator settings activity. // */ // public static Intent networkOperatorSettings(Context context) { // // Check if the network operator settings intent is available. // Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); // boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); // if (!networkOperatorSettingsAvailable) { // // The previous intent action is not available with some devices: // // http://stackoverflow.com/a/6789616/422906 // networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); // networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", // "com.android.phone.NetworkSetting")); // networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); // } // return networkOperatorSettingsIntent; // } // // /** // * Open statistics. // */ // public static Intent statistics(Context context) { // return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // } // // /** // * Get the intent to handle notification action. // */ // public static Intent notificationAction(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return statistics(context); // } // // final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); // final String notifAction = p.getString(SP_KEY_NOTIF_ACTION, NOTIF_ACTION_STATISTICS); // if (NOTIF_ACTION_STATISTICS.equals(notifAction)) { // return statistics(context); // } // if (NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS.equals(notifAction)) { // return networkOperatorSettings(context); // } // return null; // } // // private static boolean isIntentAvailable(Context context, Intent i) { // return !context.getPackageManager().queryIntentActivities(i, 0).isEmpty(); // } // } // Path: src/org/pixmob/freemobile/netstat/NotificationHandler.java import static org.pixmob.freemobile.netstat.Constants.ACTION_NOTIFICATION; import static org.pixmob.freemobile.netstat.Constants.TAG; import org.pixmob.freemobile.netstat.util.IntentFactory; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * Handle notification action. * @author Pixmob */ public class NotificationHandler extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {
if (ACTION_NOTIFICATION.equals(intent.getAction())) {
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/NotificationHandler.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String ACTION_NOTIFICATION = "org.pixmob.freemobile.netstat.notif"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/util/IntentFactory.java // public final class IntentFactory { // private IntentFactory() { // } // // /** // * Open network operator settings activity. // */ // public static Intent networkOperatorSettings(Context context) { // // Check if the network operator settings intent is available. // Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); // boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); // if (!networkOperatorSettingsAvailable) { // // The previous intent action is not available with some devices: // // http://stackoverflow.com/a/6789616/422906 // networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); // networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", // "com.android.phone.NetworkSetting")); // networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); // } // return networkOperatorSettingsIntent; // } // // /** // * Open statistics. // */ // public static Intent statistics(Context context) { // return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // } // // /** // * Get the intent to handle notification action. // */ // public static Intent notificationAction(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return statistics(context); // } // // final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); // final String notifAction = p.getString(SP_KEY_NOTIF_ACTION, NOTIF_ACTION_STATISTICS); // if (NOTIF_ACTION_STATISTICS.equals(notifAction)) { // return statistics(context); // } // if (NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS.equals(notifAction)) { // return networkOperatorSettings(context); // } // return null; // } // // private static boolean isIntentAvailable(Context context, Intent i) { // return !context.getPackageManager().queryIntentActivities(i, 0).isEmpty(); // } // }
import static org.pixmob.freemobile.netstat.Constants.ACTION_NOTIFICATION; import static org.pixmob.freemobile.netstat.Constants.TAG; import org.pixmob.freemobile.netstat.util.IntentFactory; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * Handle notification action. * @author Pixmob */ public class NotificationHandler extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (ACTION_NOTIFICATION.equals(intent.getAction())) {
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String ACTION_NOTIFICATION = "org.pixmob.freemobile.netstat.notif"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/util/IntentFactory.java // public final class IntentFactory { // private IntentFactory() { // } // // /** // * Open network operator settings activity. // */ // public static Intent networkOperatorSettings(Context context) { // // Check if the network operator settings intent is available. // Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); // boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); // if (!networkOperatorSettingsAvailable) { // // The previous intent action is not available with some devices: // // http://stackoverflow.com/a/6789616/422906 // networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); // networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", // "com.android.phone.NetworkSetting")); // networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); // } // return networkOperatorSettingsIntent; // } // // /** // * Open statistics. // */ // public static Intent statistics(Context context) { // return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // } // // /** // * Get the intent to handle notification action. // */ // public static Intent notificationAction(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return statistics(context); // } // // final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); // final String notifAction = p.getString(SP_KEY_NOTIF_ACTION, NOTIF_ACTION_STATISTICS); // if (NOTIF_ACTION_STATISTICS.equals(notifAction)) { // return statistics(context); // } // if (NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS.equals(notifAction)) { // return networkOperatorSettings(context); // } // return null; // } // // private static boolean isIntentAvailable(Context context, Intent i) { // return !context.getPackageManager().queryIntentActivities(i, 0).isEmpty(); // } // } // Path: src/org/pixmob/freemobile/netstat/NotificationHandler.java import static org.pixmob.freemobile.netstat.Constants.ACTION_NOTIFICATION; import static org.pixmob.freemobile.netstat.Constants.TAG; import org.pixmob.freemobile.netstat.util.IntentFactory; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * Handle notification action. * @author Pixmob */ public class NotificationHandler extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (ACTION_NOTIFICATION.equals(intent.getAction())) {
final Intent i = IntentFactory.notificationAction(context);
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/NotificationHandler.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String ACTION_NOTIFICATION = "org.pixmob.freemobile.netstat.notif"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/util/IntentFactory.java // public final class IntentFactory { // private IntentFactory() { // } // // /** // * Open network operator settings activity. // */ // public static Intent networkOperatorSettings(Context context) { // // Check if the network operator settings intent is available. // Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); // boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); // if (!networkOperatorSettingsAvailable) { // // The previous intent action is not available with some devices: // // http://stackoverflow.com/a/6789616/422906 // networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); // networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", // "com.android.phone.NetworkSetting")); // networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); // } // return networkOperatorSettingsIntent; // } // // /** // * Open statistics. // */ // public static Intent statistics(Context context) { // return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // } // // /** // * Get the intent to handle notification action. // */ // public static Intent notificationAction(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return statistics(context); // } // // final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); // final String notifAction = p.getString(SP_KEY_NOTIF_ACTION, NOTIF_ACTION_STATISTICS); // if (NOTIF_ACTION_STATISTICS.equals(notifAction)) { // return statistics(context); // } // if (NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS.equals(notifAction)) { // return networkOperatorSettings(context); // } // return null; // } // // private static boolean isIntentAvailable(Context context, Intent i) { // return !context.getPackageManager().queryIntentActivities(i, 0).isEmpty(); // } // }
import static org.pixmob.freemobile.netstat.Constants.ACTION_NOTIFICATION; import static org.pixmob.freemobile.netstat.Constants.TAG; import org.pixmob.freemobile.netstat.util.IntentFactory; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * Handle notification action. * @author Pixmob */ public class NotificationHandler extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (ACTION_NOTIFICATION.equals(intent.getAction())) { final Intent i = IntentFactory.notificationAction(context); if (i != null) { i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } else {
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String ACTION_NOTIFICATION = "org.pixmob.freemobile.netstat.notif"; // // Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // // Path: src/org/pixmob/freemobile/netstat/util/IntentFactory.java // public final class IntentFactory { // private IntentFactory() { // } // // /** // * Open network operator settings activity. // */ // public static Intent networkOperatorSettings(Context context) { // // Check if the network operator settings intent is available. // Intent networkOperatorSettingsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); // boolean networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); // if (!networkOperatorSettingsAvailable) { // // The previous intent action is not available with some devices: // // http://stackoverflow.com/a/6789616/422906 // networkOperatorSettingsIntent = new Intent(Intent.ACTION_MAIN); // networkOperatorSettingsIntent.setComponent(new ComponentName("com.android.phone", // "com.android.phone.NetworkSetting")); // networkOperatorSettingsAvailable = isIntentAvailable(context, networkOperatorSettingsIntent); // } // return networkOperatorSettingsIntent; // } // // /** // * Open statistics. // */ // public static Intent statistics(Context context) { // return new Intent(context, Netstat.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // } // // /** // * Get the intent to handle notification action. // */ // public static Intent notificationAction(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // return statistics(context); // } // // final SharedPreferences p = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); // final String notifAction = p.getString(SP_KEY_NOTIF_ACTION, NOTIF_ACTION_STATISTICS); // if (NOTIF_ACTION_STATISTICS.equals(notifAction)) { // return statistics(context); // } // if (NOTIF_ACTION_NETWORK_OPERATOR_SETTINGS.equals(notifAction)) { // return networkOperatorSettings(context); // } // return null; // } // // private static boolean isIntentAvailable(Context context, Intent i) { // return !context.getPackageManager().queryIntentActivities(i, 0).isEmpty(); // } // } // Path: src/org/pixmob/freemobile/netstat/NotificationHandler.java import static org.pixmob.freemobile.netstat.Constants.ACTION_NOTIFICATION; import static org.pixmob.freemobile.netstat.Constants.TAG; import org.pixmob.freemobile.netstat.util.IntentFactory; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * Handle notification action. * @author Pixmob */ public class NotificationHandler extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (ACTION_NOTIFICATION.equals(intent.getAction())) { final Intent i = IntentFactory.notificationAction(context); if (i != null) { i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); } else {
Log.e(TAG, "Cannot handle notification action");
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/Event.java
// Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // }
import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import android.content.ContentValues; import android.database.Cursor; import android.text.format.DateFormat;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * Network event. * @author Pixmob */ public class Event { public long timestamp; public boolean screenOn; public boolean wifiConnected; public boolean mobileConnected; public String mobileOperator; public int batteryLevel; public boolean powerOn; /** * Read an {@link Event} instance from a database {@link Cursor}. The cursor * should include every columns defined in {@link Events}. */ public void read(Cursor c) {
// Path: src/org/pixmob/freemobile/netstat/content/NetstatContract.java // public static class Events implements BaseColumns, EventsColumns { // /** // * The content:// style URI for this table. // */ // public static final Uri CONTENT_URI = new Uri.Builder() // .scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY) // .appendPath("events").build(); // /** // * The MIME type of a {@link #CONTENT_URI} subdirectory of a single // * entry. // */ // public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/event"; // /** // * The MIME type of {@link #CONTENT_TYPE} providing a directory of // * entries. // */ // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/event"; // } // Path: src/org/pixmob/freemobile/netstat/Event.java import org.pixmob.freemobile.netstat.content.NetstatContract.Events; import android.content.ContentValues; import android.database.Cursor; import android.text.format.DateFormat; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * Network event. * @author Pixmob */ public class Event { public long timestamp; public boolean screenOn; public boolean wifiConnected; public boolean mobileConnected; public String mobileOperator; public int batteryLevel; public boolean powerOn; /** * Read an {@link Event} instance from a database {@link Cursor}. The cursor * should include every columns defined in {@link Events}. */ public void read(Cursor c) {
timestamp = c.getLong(c.getColumnIndexOrThrow(Events.TIMESTAMP));
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/MobileOperator.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat";
import static org.pixmob.freemobile.netstat.BuildConfig.DEBUG; import static org.pixmob.freemobile.netstat.Constants.TAG; import java.util.HashSet; import java.util.Set; import android.content.Context; import android.database.CharArrayBuffer; import android.util.Log;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * Mobile operator list. * @author Pixmob */ public enum MobileOperator { FREE_MOBILE, ORANGE; private static final Set<String> FREE_MOBILE_IDENTIFIERS = new HashSet<String>(2); private static final Set<String> ORANGE_IDENTIFIERS = new HashSet<String>(3); static { // MCC+MNC identifier list: // http://en.wikipedia.org/wiki/Mobile_Network_Code FREE_MOBILE_IDENTIFIERS.add("20815"); FREE_MOBILE_IDENTIFIERS.add("20816"); ORANGE_IDENTIFIERS.add("20800"); ORANGE_IDENTIFIERS.add("20801"); ORANGE_IDENTIFIERS.add("20802"); } /** * Get a {@link MobileOperator} instance from a MCC+MNC identifier. */ public static MobileOperator fromString(String mccMnc) { if (mccMnc == null) { return null; } if (ORANGE_IDENTIFIERS.contains(mccMnc)) { return ORANGE; } if (FREE_MOBILE_IDENTIFIERS.contains(mccMnc)) { return FREE_MOBILE; } if (DEBUG) {
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // Path: src/org/pixmob/freemobile/netstat/MobileOperator.java import static org.pixmob.freemobile.netstat.BuildConfig.DEBUG; import static org.pixmob.freemobile.netstat.Constants.TAG; import java.util.HashSet; import java.util.Set; import android.content.Context; import android.database.CharArrayBuffer; import android.util.Log; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat; /** * Mobile operator list. * @author Pixmob */ public enum MobileOperator { FREE_MOBILE, ORANGE; private static final Set<String> FREE_MOBILE_IDENTIFIERS = new HashSet<String>(2); private static final Set<String> ORANGE_IDENTIFIERS = new HashSet<String>(3); static { // MCC+MNC identifier list: // http://en.wikipedia.org/wiki/Mobile_Network_Code FREE_MOBILE_IDENTIFIERS.add("20815"); FREE_MOBILE_IDENTIFIERS.add("20816"); ORANGE_IDENTIFIERS.add("20800"); ORANGE_IDENTIFIERS.add("20801"); ORANGE_IDENTIFIERS.add("20802"); } /** * Get a {@link MobileOperator} instance from a MCC+MNC identifier. */ public static MobileOperator fromString(String mccMnc) { if (mccMnc == null) { return null; } if (ORANGE_IDENTIFIERS.contains(mccMnc)) { return ORANGE; } if (FREE_MOBILE_IDENTIFIERS.contains(mccMnc)) { return FREE_MOBILE; } if (DEBUG) {
Log.v(TAG, "Unknown MCC+MNC: " + mccMnc);
pixmob/freemobilenetstat
src/org/pixmob/freemobile/netstat/util/BugSenseUtils.java
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat";
import static org.pixmob.freemobile.netstat.Constants.TAG; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import android.content.Context; import android.util.Log; import com.bugsense.trace.BugSenseHandler;
/* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.util; /** * BugSense (error reporting) utilities. * @author Pixmob */ public final class BugSenseUtils { private BugSenseUtils() { } /** * Setup the BugSense framework for reporting errors in the application. The * API key is loaded from application assets. If the key is not found, a * warning message is logged. */ public static void setup(Context context) { String apiKey = null; try { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(context.getAssets().open("bugsense.txt"))); for (String line; (line = reader.readLine()) != null;) { line = line.trim(); if (!line.startsWith("#") && line.length() != 0) { apiKey = line; break; } } } catch (IOException e) {
// Path: src/org/pixmob/freemobile/netstat/Constants.java // public static final String TAG = "FreeMobileNetstat"; // Path: src/org/pixmob/freemobile/netstat/util/BugSenseUtils.java import static org.pixmob.freemobile.netstat.Constants.TAG; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import android.content.Context; import android.util.Log; import com.bugsense.trace.BugSenseHandler; /* * Copyright (C) 2012 Pixmob (http://github.com/pixmob) * * 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 org.pixmob.freemobile.netstat.util; /** * BugSense (error reporting) utilities. * @author Pixmob */ public final class BugSenseUtils { private BugSenseUtils() { } /** * Setup the BugSense framework for reporting errors in the application. The * API key is loaded from application assets. If the key is not found, a * warning message is logged. */ public static void setup(Context context) { String apiKey = null; try { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(context.getAssets().open("bugsense.txt"))); for (String line; (line = reader.readLine()) != null;) { line = line.trim(); if (!line.startsWith("#") && line.length() != 0) { apiKey = line; break; } } } catch (IOException e) {
Log.w(TAG, "Failed to load BugSense API key", e);
princeofgiri/f-droid
F-Droid/src/org/fdroid/fdroid/SearchResults.java
// Path: F-Droid/src/org/fdroid/fdroid/views/fragments/SearchResultsFragment.java // public class SearchResultsFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { // // private static final String TAG = "org.fdroid.fdroid.views.fragments.SearchResultsFragment"; // // private static final int REQUEST_APPDETAILS = 0; // // private AppListAdapter adapter; // // protected String getQuery() { // Intent intent = getActivity().getIntent(); // String query = null; // if (Intent.ACTION_SEARCH.equals(intent.getAction())) { // query = intent.getStringExtra(SearchManager.QUERY); // } else { // Uri data = intent.getData(); // if (data != null && data.isHierarchical()) { // query = data.getQueryParameter("q"); // if (query != null && query.startsWith("pname:")) // query = query.substring(6); // } else if (data!= null) { // query = data.getEncodedSchemeSpecificPart(); // } // } // return query == null ? "" : query; // } // // @Override // public void onResume() { // super.onResume(); // // //Starts a new or restarts an existing Loader in this manager // getLoaderManager().restartLoader(0, null, this); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle data) { // // adapter = new AvailableAppListAdapter(getActivity(), null); // setListAdapter(adapter); // // View view = inflater.inflate(R.layout.searchresults, null); // updateSummary(view); // // return view; // } // // @Override // public Loader<Cursor> onCreateLoader(int id, Bundle args) { // Uri uri = AppProvider.getSearchUri(getQuery()); // return new CursorLoader( // getActivity(), // uri, // AppListFragment.APP_PROJECTION, // null, // null, // AppListFragment.APP_SORT // ); // } // // private void updateSummary() { // updateSummary(getView()); // } // // private void updateSummary(View view) { // // String query = getQuery(); // // if (query != null) // query = query.trim(); // // if (query == null || query.length() == 0) // getActivity().finish(); // // TextView tv = (TextView) view.findViewById(R.id.description); // String headerText; // int count = adapter.getCount(); // if (count == 0) { // headerText = getString(R.string.searchres_noapps, query); // } else if (count == 1) { // headerText = getString(R.string.searchres_oneapp, query); // } else { // headerText = getString(R.string.searchres_napps, count, query); // } // tv.setText(headerText); // Log.d(TAG, "Search for '" + query + "' returned " + count + " results"); // } // // @Override // public void onListItemClick(ListView l, View v, int position, long id) { // final App app; // app = new App((Cursor) adapter.getItem(position)); // // Intent intent = new Intent(getActivity(), AppDetails.class); // intent.putExtra(AppDetails.EXTRA_APPID, app.id); // startActivityForResult(intent, REQUEST_APPDETAILS); // super.onListItemClick(l, v, position, id); // } // // @Override // public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // adapter.swapCursor(data); // updateSummary(); // } // // @Override // public void onLoaderReset(Loader<Cursor> loader) { // adapter.swapCursor(null); // } // }
import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.NavUtils; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.widget.LinearLayout; import org.fdroid.fdroid.views.fragments.SearchResultsFragment;
/* * Copyright (C) 2011-13 Ciaran Gultnieks, ciaran@ciarang.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.fdroid.fdroid; public class SearchResults extends ActionBarActivity { private static final int SEARCH = Menu.FIRST; @Override public void onCreate(Bundle savedInstanceState) { ((FDroidApp) getApplication()).applyTheme(this); super.onCreate(savedInstanceState); // Start a search by just typing setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentById(android.R.id.content) == null) { // Need to set a dummy view (which will get overridden by the fragment manager // below) so that we can call setContentView(). This is a work around for // a (bug?) thing in 3.0, 3.1 which requires setContentView to be invoked before // the actionbar is played with: // http://blog.perpetumdesign.com/2011/08/strange-case-of-dr-action-and-mr-bar.html setContentView(new LinearLayout(this));
// Path: F-Droid/src/org/fdroid/fdroid/views/fragments/SearchResultsFragment.java // public class SearchResultsFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { // // private static final String TAG = "org.fdroid.fdroid.views.fragments.SearchResultsFragment"; // // private static final int REQUEST_APPDETAILS = 0; // // private AppListAdapter adapter; // // protected String getQuery() { // Intent intent = getActivity().getIntent(); // String query = null; // if (Intent.ACTION_SEARCH.equals(intent.getAction())) { // query = intent.getStringExtra(SearchManager.QUERY); // } else { // Uri data = intent.getData(); // if (data != null && data.isHierarchical()) { // query = data.getQueryParameter("q"); // if (query != null && query.startsWith("pname:")) // query = query.substring(6); // } else if (data!= null) { // query = data.getEncodedSchemeSpecificPart(); // } // } // return query == null ? "" : query; // } // // @Override // public void onResume() { // super.onResume(); // // //Starts a new or restarts an existing Loader in this manager // getLoaderManager().restartLoader(0, null, this); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle data) { // // adapter = new AvailableAppListAdapter(getActivity(), null); // setListAdapter(adapter); // // View view = inflater.inflate(R.layout.searchresults, null); // updateSummary(view); // // return view; // } // // @Override // public Loader<Cursor> onCreateLoader(int id, Bundle args) { // Uri uri = AppProvider.getSearchUri(getQuery()); // return new CursorLoader( // getActivity(), // uri, // AppListFragment.APP_PROJECTION, // null, // null, // AppListFragment.APP_SORT // ); // } // // private void updateSummary() { // updateSummary(getView()); // } // // private void updateSummary(View view) { // // String query = getQuery(); // // if (query != null) // query = query.trim(); // // if (query == null || query.length() == 0) // getActivity().finish(); // // TextView tv = (TextView) view.findViewById(R.id.description); // String headerText; // int count = adapter.getCount(); // if (count == 0) { // headerText = getString(R.string.searchres_noapps, query); // } else if (count == 1) { // headerText = getString(R.string.searchres_oneapp, query); // } else { // headerText = getString(R.string.searchres_napps, count, query); // } // tv.setText(headerText); // Log.d(TAG, "Search for '" + query + "' returned " + count + " results"); // } // // @Override // public void onListItemClick(ListView l, View v, int position, long id) { // final App app; // app = new App((Cursor) adapter.getItem(position)); // // Intent intent = new Intent(getActivity(), AppDetails.class); // intent.putExtra(AppDetails.EXTRA_APPID, app.id); // startActivityForResult(intent, REQUEST_APPDETAILS); // super.onListItemClick(l, v, position, id); // } // // @Override // public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // adapter.swapCursor(data); // updateSummary(); // } // // @Override // public void onLoaderReset(Loader<Cursor> loader) { // adapter.swapCursor(null); // } // } // Path: F-Droid/src/org/fdroid/fdroid/SearchResults.java import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.NavUtils; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.widget.LinearLayout; import org.fdroid.fdroid.views.fragments.SearchResultsFragment; /* * Copyright (C) 2011-13 Ciaran Gultnieks, ciaran@ciarang.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.fdroid.fdroid; public class SearchResults extends ActionBarActivity { private static final int SEARCH = Menu.FIRST; @Override public void onCreate(Bundle savedInstanceState) { ((FDroidApp) getApplication()).applyTheme(this); super.onCreate(savedInstanceState); // Start a search by just typing setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentById(android.R.id.content) == null) { // Need to set a dummy view (which will get overridden by the fragment manager // below) so that we can call setContentView(). This is a work around for // a (bug?) thing in 3.0, 3.1 which requires setContentView to be invoked before // the actionbar is played with: // http://blog.perpetumdesign.com/2011/08/strange-case-of-dr-action-and-mr-bar.html setContentView(new LinearLayout(this));
SearchResultsFragment fragment = new SearchResultsFragment();
princeofgiri/f-droid
F-Droid/src/org/fdroid/fdroid/views/swap/SwapAppListActivity.java
// Path: F-Droid/src/org/fdroid/fdroid/views/fragments/AppListFragment.java // abstract public class AppListFragment extends ThemeableListFragment implements // AdapterView.OnItemClickListener, // Preferences.ChangeListener, // LoaderManager.LoaderCallbacks<Cursor> { // // public static final String[] APP_PROJECTION = { // AppProvider.DataColumns._ID, // Required for cursor loader to work. // AppProvider.DataColumns.APP_ID, // AppProvider.DataColumns.NAME, // AppProvider.DataColumns.SUMMARY, // AppProvider.DataColumns.IS_COMPATIBLE, // AppProvider.DataColumns.LICENSE, // AppProvider.DataColumns.ICON, // AppProvider.DataColumns.ICON_URL, // AppProvider.DataColumns.InstalledApp.VERSION_CODE, // AppProvider.DataColumns.InstalledApp.VERSION_NAME, // AppProvider.DataColumns.SuggestedApk.VERSION, // AppProvider.DataColumns.SUGGESTED_VERSION_CODE, // AppProvider.DataColumns.IGNORE_ALLUPDATES, // AppProvider.DataColumns.IGNORE_THISUPDATE, // AppProvider.DataColumns.REQUIREMENTS, // Needed for filtering apps that require root. // }; // // public static final String APP_SORT = AppProvider.DataColumns.NAME; // // protected AppListAdapter appAdapter; // // protected abstract AppListAdapter getAppListAdapter(); // // protected abstract String getFromTitle(); // // protected abstract Uri getDataUri(); // // @Override // public void onActivityCreated(Bundle savedInstanceState) { // super.onActivityCreated(savedInstanceState); // // // Can't do this in the onCreate view, because "onCreateView" which // // returns the list view is "called between onCreate and // // onActivityCreated" according to the docs. // getListView().setFastScrollEnabled(true); // getListView().setOnItemClickListener(this); // } // // @Override // public void onResume() { // super.onResume(); // // //Starts a new or restarts an existing Loader in this manager // getLoaderManager().restartLoader(0, null, this); // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // Preferences.get().registerCompactLayoutChangeListener(this); // // appAdapter = getAppListAdapter(); // // if (appAdapter.getCount() == 0) { // updateEmptyRepos(); // } // // setListAdapter(appAdapter); // } // // /** // * The first time the app is run, we will have an empty app list. // * If this is the case, we will attempt to update with the default repo. // * However, if we have tried this at least once, then don't try to do // * it automatically again, because the repos or internet connection may // * be bad. // */ // public boolean updateEmptyRepos() { // final String TRIED_EMPTY_UPDATE = "triedEmptyUpdate"; // SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE); // boolean hasTriedEmptyUpdate = prefs.getBoolean(TRIED_EMPTY_UPDATE, false); // if (!hasTriedEmptyUpdate) { // Log.d("FDroid", "Empty app list, and we haven't done an update yet. Forcing repo update."); // prefs.edit().putBoolean(TRIED_EMPTY_UPDATE, true).commit(); // UpdateService.updateNow(getActivity()); // return true; // } else { // Log.d("FDroid", "Empty app list, but it looks like we've had an update previously. Will not force repo update."); // return false; // } // } // // @Override // public void onDestroy() { // super.onDestroy(); // Preferences.get().unregisterCompactLayoutChangeListener(this); // } // // @Override // public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // final App app = new App((Cursor)getListView().getItemAtPosition(position)); // Intent intent = new Intent(getActivity(), AppDetails.class); // intent.putExtra(AppDetails.EXTRA_APPID, app.id); // intent.putExtra(AppDetails.EXTRA_FROM, getFromTitle()); // startActivityForResult(intent, FDroid.REQUEST_APPDETAILS); // } // // @Override // public void onPreferenceChange() { // getAppListAdapter().notifyDataSetChanged(); // } // // @Override // public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // appAdapter.swapCursor(data); // } // // @Override // public void onLoaderReset(Loader<Cursor> loader) { // appAdapter.swapCursor(null); // } // // @Override // public Loader<Cursor> onCreateLoader(int id, Bundle args) { // Uri uri = getDataUri(); // return new CursorLoader( // getActivity(), uri, APP_PROJECTION, null, null, APP_SORT); // } // // }
import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import org.fdroid.fdroid.R; import org.fdroid.fdroid.data.AppProvider; import org.fdroid.fdroid.views.AppListAdapter; import org.fdroid.fdroid.views.AvailableAppListAdapter; import org.fdroid.fdroid.views.fragments.AppListFragment;
package org.fdroid.fdroid.views.swap; public class SwapAppListActivity extends ActionBarActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { getSupportFragmentManager() .beginTransaction() .add(android.R.id.content, new SwapAppListFragment()) .commit(); } }
// Path: F-Droid/src/org/fdroid/fdroid/views/fragments/AppListFragment.java // abstract public class AppListFragment extends ThemeableListFragment implements // AdapterView.OnItemClickListener, // Preferences.ChangeListener, // LoaderManager.LoaderCallbacks<Cursor> { // // public static final String[] APP_PROJECTION = { // AppProvider.DataColumns._ID, // Required for cursor loader to work. // AppProvider.DataColumns.APP_ID, // AppProvider.DataColumns.NAME, // AppProvider.DataColumns.SUMMARY, // AppProvider.DataColumns.IS_COMPATIBLE, // AppProvider.DataColumns.LICENSE, // AppProvider.DataColumns.ICON, // AppProvider.DataColumns.ICON_URL, // AppProvider.DataColumns.InstalledApp.VERSION_CODE, // AppProvider.DataColumns.InstalledApp.VERSION_NAME, // AppProvider.DataColumns.SuggestedApk.VERSION, // AppProvider.DataColumns.SUGGESTED_VERSION_CODE, // AppProvider.DataColumns.IGNORE_ALLUPDATES, // AppProvider.DataColumns.IGNORE_THISUPDATE, // AppProvider.DataColumns.REQUIREMENTS, // Needed for filtering apps that require root. // }; // // public static final String APP_SORT = AppProvider.DataColumns.NAME; // // protected AppListAdapter appAdapter; // // protected abstract AppListAdapter getAppListAdapter(); // // protected abstract String getFromTitle(); // // protected abstract Uri getDataUri(); // // @Override // public void onActivityCreated(Bundle savedInstanceState) { // super.onActivityCreated(savedInstanceState); // // // Can't do this in the onCreate view, because "onCreateView" which // // returns the list view is "called between onCreate and // // onActivityCreated" according to the docs. // getListView().setFastScrollEnabled(true); // getListView().setOnItemClickListener(this); // } // // @Override // public void onResume() { // super.onResume(); // // //Starts a new or restarts an existing Loader in this manager // getLoaderManager().restartLoader(0, null, this); // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // Preferences.get().registerCompactLayoutChangeListener(this); // // appAdapter = getAppListAdapter(); // // if (appAdapter.getCount() == 0) { // updateEmptyRepos(); // } // // setListAdapter(appAdapter); // } // // /** // * The first time the app is run, we will have an empty app list. // * If this is the case, we will attempt to update with the default repo. // * However, if we have tried this at least once, then don't try to do // * it automatically again, because the repos or internet connection may // * be bad. // */ // public boolean updateEmptyRepos() { // final String TRIED_EMPTY_UPDATE = "triedEmptyUpdate"; // SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE); // boolean hasTriedEmptyUpdate = prefs.getBoolean(TRIED_EMPTY_UPDATE, false); // if (!hasTriedEmptyUpdate) { // Log.d("FDroid", "Empty app list, and we haven't done an update yet. Forcing repo update."); // prefs.edit().putBoolean(TRIED_EMPTY_UPDATE, true).commit(); // UpdateService.updateNow(getActivity()); // return true; // } else { // Log.d("FDroid", "Empty app list, but it looks like we've had an update previously. Will not force repo update."); // return false; // } // } // // @Override // public void onDestroy() { // super.onDestroy(); // Preferences.get().unregisterCompactLayoutChangeListener(this); // } // // @Override // public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // final App app = new App((Cursor)getListView().getItemAtPosition(position)); // Intent intent = new Intent(getActivity(), AppDetails.class); // intent.putExtra(AppDetails.EXTRA_APPID, app.id); // intent.putExtra(AppDetails.EXTRA_FROM, getFromTitle()); // startActivityForResult(intent, FDroid.REQUEST_APPDETAILS); // } // // @Override // public void onPreferenceChange() { // getAppListAdapter().notifyDataSetChanged(); // } // // @Override // public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // appAdapter.swapCursor(data); // } // // @Override // public void onLoaderReset(Loader<Cursor> loader) { // appAdapter.swapCursor(null); // } // // @Override // public Loader<Cursor> onCreateLoader(int id, Bundle args) { // Uri uri = getDataUri(); // return new CursorLoader( // getActivity(), uri, APP_PROJECTION, null, null, APP_SORT); // } // // } // Path: F-Droid/src/org/fdroid/fdroid/views/swap/SwapAppListActivity.java import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import org.fdroid.fdroid.R; import org.fdroid.fdroid.data.AppProvider; import org.fdroid.fdroid.views.AppListAdapter; import org.fdroid.fdroid.views.AvailableAppListAdapter; import org.fdroid.fdroid.views.fragments.AppListFragment; package org.fdroid.fdroid.views.swap; public class SwapAppListActivity extends ActionBarActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { getSupportFragmentManager() .beginTransaction() .add(android.R.id.content, new SwapAppListFragment()) .commit(); } }
private static class SwapAppListFragment extends AppListFragment {
princeofgiri/f-droid
F-Droid/src/org/fdroid/fdroid/CompatibilityChecker.java
// Path: F-Droid/src/org/fdroid/fdroid/compat/SupportedArchitectures.java // public class SupportedArchitectures extends Compatibility { // // @SuppressWarnings("deprecation") // private static String[] getAbisDonut() { // return new String[]{Build.CPU_ABI}; // } // // @SuppressWarnings("deprecation") // @TargetApi(8) // private static String[] getAbisFroyo() { // return new String[]{Build.CPU_ABI, Build.CPU_ABI2}; // } // // @TargetApi(21) // private static String[] getAbisLollipop() { // return Build.SUPPORTED_ABIS; // } // // /** // * The most preferred ABI is the first element in the list. // */ // public static String[] getAbis() { // if (hasApi(21)) { // return getAbisLollipop(); // } // if (hasApi(8)) { // return getAbisFroyo(); // } // return getAbisDonut(); // } // // }
import android.content.Context; import android.content.SharedPreferences; import android.content.pm.FeatureInfo; import android.content.pm.PackageManager; import android.preference.PreferenceManager; import android.util.Log; import org.fdroid.fdroid.compat.Compatibility; import org.fdroid.fdroid.compat.SupportedArchitectures; import org.fdroid.fdroid.data.Apk; import java.util.*;
package org.fdroid.fdroid; // Call getIncompatibleReasons(apk) on an instance of this class to // find reasons why an apk may be incompatible with the user's device. public class CompatibilityChecker extends Compatibility { private Context context; private Set<String> features; private String[] cpuAbis; private String cpuAbisDesc; private boolean ignoreTouchscreen; public CompatibilityChecker(Context ctx) { context = ctx.getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); ignoreTouchscreen = prefs.getBoolean(Preferences.PREF_IGN_TOUCH, false); PackageManager pm = ctx.getPackageManager(); StringBuilder logMsg = new StringBuilder(); logMsg.append("Available device features:"); features = new HashSet<String>(); if (pm != null) { final FeatureInfo[] featureArray = pm.getSystemAvailableFeatures(); if (featureArray != null) for (FeatureInfo fi : pm.getSystemAvailableFeatures()) { features.add(fi.name); logMsg.append('\n'); logMsg.append(fi.name); } }
// Path: F-Droid/src/org/fdroid/fdroid/compat/SupportedArchitectures.java // public class SupportedArchitectures extends Compatibility { // // @SuppressWarnings("deprecation") // private static String[] getAbisDonut() { // return new String[]{Build.CPU_ABI}; // } // // @SuppressWarnings("deprecation") // @TargetApi(8) // private static String[] getAbisFroyo() { // return new String[]{Build.CPU_ABI, Build.CPU_ABI2}; // } // // @TargetApi(21) // private static String[] getAbisLollipop() { // return Build.SUPPORTED_ABIS; // } // // /** // * The most preferred ABI is the first element in the list. // */ // public static String[] getAbis() { // if (hasApi(21)) { // return getAbisLollipop(); // } // if (hasApi(8)) { // return getAbisFroyo(); // } // return getAbisDonut(); // } // // } // Path: F-Droid/src/org/fdroid/fdroid/CompatibilityChecker.java import android.content.Context; import android.content.SharedPreferences; import android.content.pm.FeatureInfo; import android.content.pm.PackageManager; import android.preference.PreferenceManager; import android.util.Log; import org.fdroid.fdroid.compat.Compatibility; import org.fdroid.fdroid.compat.SupportedArchitectures; import org.fdroid.fdroid.data.Apk; import java.util.*; package org.fdroid.fdroid; // Call getIncompatibleReasons(apk) on an instance of this class to // find reasons why an apk may be incompatible with the user's device. public class CompatibilityChecker extends Compatibility { private Context context; private Set<String> features; private String[] cpuAbis; private String cpuAbisDesc; private boolean ignoreTouchscreen; public CompatibilityChecker(Context ctx) { context = ctx.getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); ignoreTouchscreen = prefs.getBoolean(Preferences.PREF_IGN_TOUCH, false); PackageManager pm = ctx.getPackageManager(); StringBuilder logMsg = new StringBuilder(); logMsg.append("Available device features:"); features = new HashSet<String>(); if (pm != null) { final FeatureInfo[] featureArray = pm.getSystemAvailableFeatures(); if (featureArray != null) for (FeatureInfo fi : pm.getSystemAvailableFeatures()) { features.add(fi.name); logMsg.append('\n'); logMsg.append(fi.name); } }
cpuAbis = SupportedArchitectures.getAbis();
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/lucene/MusicSearch.java
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/LuceneUtil.java // public enum LuceneUtil { // INSTANCE; // // private Directory directory; // private IndexWriter indexWriter; // private Analyzer analyzer; // public Directory getDirectory() { // return directory; // } // // public Analyzer getAnalyzer() { // return analyzer; // } // // public IndexWriter getIndexWriter() { // // IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_46, analyzer); // // try { // indexWriter = new IndexWriter(directory, indexWriterConfig); // } catch (IOException exception) { // exception.printStackTrace(); // } // return indexWriter; // } // // // { // analyzer = new StandardAnalyzer(Version.LUCENE_46); // directory = new RAMDirectory(); // Directory hd = getDirecotoryHD(); // backup(hd, directory); // // // } // // private Directory getDirecotoryHD() { // File file = new File(System.getProperty("user.home").concat("/lucene/music/")); // if (!file.exists()) { // file.mkdirs(); // } // try { // return FSDirectory.open(file); // } catch (IOException e) { // e.printStackTrace(); // } // // return null; // } // // public void backupToHD() { // Directory hd = getDirecotoryHD(); // backup(directory, hd); // } // // private void backup(Directory deDiretorio, Directory paraDiretoria) { // // try { // for (String file : deDiretorio.listAll()) { // deDiretorio.copy(paraDiretoria, file, file, IOContext.DEFAULT); // } // } catch (IOException ioException) { // ioException.printStackTrace(); // } // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // }
import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.util.Version; import org.javabahia.cassandra.spring.LuceneUtil; import org.javabahia.cassandra.spring.model.Music; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service;
package org.javabahia.cassandra.spring.lucene; @Service @Scope("prototype") public class MusicSearch { private static final String COLUNM_LYRIC = "lyric"; private static final String COLUNM_AUTHOR = "Author"; private static final String COLUMN_NAME = "name"; public List<String> findMusicByLyric(String lyric) throws ParseException, IOException { Query query = new QueryParser(Version.LUCENE_46, COLUNM_LYRIC,
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/LuceneUtil.java // public enum LuceneUtil { // INSTANCE; // // private Directory directory; // private IndexWriter indexWriter; // private Analyzer analyzer; // public Directory getDirectory() { // return directory; // } // // public Analyzer getAnalyzer() { // return analyzer; // } // // public IndexWriter getIndexWriter() { // // IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_46, analyzer); // // try { // indexWriter = new IndexWriter(directory, indexWriterConfig); // } catch (IOException exception) { // exception.printStackTrace(); // } // return indexWriter; // } // // // { // analyzer = new StandardAnalyzer(Version.LUCENE_46); // directory = new RAMDirectory(); // Directory hd = getDirecotoryHD(); // backup(hd, directory); // // // } // // private Directory getDirecotoryHD() { // File file = new File(System.getProperty("user.home").concat("/lucene/music/")); // if (!file.exists()) { // file.mkdirs(); // } // try { // return FSDirectory.open(file); // } catch (IOException e) { // e.printStackTrace(); // } // // return null; // } // // public void backupToHD() { // Directory hd = getDirecotoryHD(); // backup(directory, hd); // } // // private void backup(Directory deDiretorio, Directory paraDiretoria) { // // try { // for (String file : deDiretorio.listAll()) { // deDiretorio.copy(paraDiretoria, file, file, IOContext.DEFAULT); // } // } catch (IOException ioException) { // ioException.printStackTrace(); // } // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/lucene/MusicSearch.java import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.util.Version; import org.javabahia.cassandra.spring.LuceneUtil; import org.javabahia.cassandra.spring.model.Music; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; package org.javabahia.cassandra.spring.lucene; @Service @Scope("prototype") public class MusicSearch { private static final String COLUNM_LYRIC = "lyric"; private static final String COLUNM_AUTHOR = "Author"; private static final String COLUMN_NAME = "name"; public List<String> findMusicByLyric(String lyric) throws ParseException, IOException { Query query = new QueryParser(Version.LUCENE_46, COLUNM_LYRIC,
LuceneUtil.INSTANCE.getAnalyzer()).parse(lyric);
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/lucene/MusicSearch.java
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/LuceneUtil.java // public enum LuceneUtil { // INSTANCE; // // private Directory directory; // private IndexWriter indexWriter; // private Analyzer analyzer; // public Directory getDirectory() { // return directory; // } // // public Analyzer getAnalyzer() { // return analyzer; // } // // public IndexWriter getIndexWriter() { // // IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_46, analyzer); // // try { // indexWriter = new IndexWriter(directory, indexWriterConfig); // } catch (IOException exception) { // exception.printStackTrace(); // } // return indexWriter; // } // // // { // analyzer = new StandardAnalyzer(Version.LUCENE_46); // directory = new RAMDirectory(); // Directory hd = getDirecotoryHD(); // backup(hd, directory); // // // } // // private Directory getDirecotoryHD() { // File file = new File(System.getProperty("user.home").concat("/lucene/music/")); // if (!file.exists()) { // file.mkdirs(); // } // try { // return FSDirectory.open(file); // } catch (IOException e) { // e.printStackTrace(); // } // // return null; // } // // public void backupToHD() { // Directory hd = getDirecotoryHD(); // backup(directory, hd); // } // // private void backup(Directory deDiretorio, Directory paraDiretoria) { // // try { // for (String file : deDiretorio.listAll()) { // deDiretorio.copy(paraDiretoria, file, file, IOContext.DEFAULT); // } // } catch (IOException ioException) { // ioException.printStackTrace(); // } // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // }
import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.util.Version; import org.javabahia.cassandra.spring.LuceneUtil; import org.javabahia.cassandra.spring.model.Music; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service;
LuceneUtil.INSTANCE.getAnalyzer()).parse(lyric); return returnMusics(query); } public List<String> findMusicByAuthor(String author) throws ParseException, IOException { Term term = new Term(COLUNM_AUTHOR, author); Query query = new TermQuery(term); return returnMusics(query); } private List<String> returnMusics(Query query) throws IOException { int hitsPerPage = 10; IndexReader reader = DirectoryReader.open(LuceneUtil.INSTANCE.getDirectory()); IndexSearcher searcher = new IndexSearcher(reader); TopScoreDocCollector collector = TopScoreDocCollector.create( hitsPerPage, true); searcher.search(query, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; List<String> musics = new LinkedList<>(); for(int i=0;i<hits.length;++i) { int docId = hits[i].doc; Document d = searcher.doc(docId); musics.add(d.get(COLUMN_NAME)); } return musics; }
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/LuceneUtil.java // public enum LuceneUtil { // INSTANCE; // // private Directory directory; // private IndexWriter indexWriter; // private Analyzer analyzer; // public Directory getDirectory() { // return directory; // } // // public Analyzer getAnalyzer() { // return analyzer; // } // // public IndexWriter getIndexWriter() { // // IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_46, analyzer); // // try { // indexWriter = new IndexWriter(directory, indexWriterConfig); // } catch (IOException exception) { // exception.printStackTrace(); // } // return indexWriter; // } // // // { // analyzer = new StandardAnalyzer(Version.LUCENE_46); // directory = new RAMDirectory(); // Directory hd = getDirecotoryHD(); // backup(hd, directory); // // // } // // private Directory getDirecotoryHD() { // File file = new File(System.getProperty("user.home").concat("/lucene/music/")); // if (!file.exists()) { // file.mkdirs(); // } // try { // return FSDirectory.open(file); // } catch (IOException e) { // e.printStackTrace(); // } // // return null; // } // // public void backupToHD() { // Directory hd = getDirecotoryHD(); // backup(directory, hd); // } // // private void backup(Directory deDiretorio, Directory paraDiretoria) { // // try { // for (String file : deDiretorio.listAll()) { // deDiretorio.copy(paraDiretoria, file, file, IOContext.DEFAULT); // } // } catch (IOException ioException) { // ioException.printStackTrace(); // } // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/lucene/MusicSearch.java import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.util.Version; import org.javabahia.cassandra.spring.LuceneUtil; import org.javabahia.cassandra.spring.model.Music; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; LuceneUtil.INSTANCE.getAnalyzer()).parse(lyric); return returnMusics(query); } public List<String> findMusicByAuthor(String author) throws ParseException, IOException { Term term = new Term(COLUNM_AUTHOR, author); Query query = new TermQuery(term); return returnMusics(query); } private List<String> returnMusics(Query query) throws IOException { int hitsPerPage = 10; IndexReader reader = DirectoryReader.open(LuceneUtil.INSTANCE.getDirectory()); IndexSearcher searcher = new IndexSearcher(reader); TopScoreDocCollector collector = TopScoreDocCollector.create( hitsPerPage, true); searcher.search(query, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; List<String> musics = new LinkedList<>(); for(int i=0;i<hits.length;++i) { int docId = hits[i].doc; Document d = searcher.doc(docId); musics.add(d.get(COLUMN_NAME)); } return musics; }
public void indexarAll(List<Music> musicas) throws IOException {
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/repository/ResumeRepository.java
// Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/model/Resume.java // @Entity // public class Resume implements Serializable{ // // private static final long serialVersionUID = 1L; // // @Id // private String nickName; // @Column // private String name; // @Column // private String country; // @Column // private String bio; // // public String getNickName() { // return nickName; // } // public void setNickName(String nickName) { // this.nickName = nickName; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getCountry() { // return country; // } // public void setCountry(String country) { // this.country = country; // } // public String getBio() { // return bio; // } // public void setBio(String bio) { // this.bio = bio; // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Resume) { // Resume other = Resume.class.cast(obj); // return new EqualsBuilder().append(other.nickName, nickName) // .isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(nickName).toHashCode(); // } // }
import org.easycassandra.persistence.cassandra.spring.CassandraRepository; import org.easycassandra.persistence.cassandra.spring.CassandraTemplate; import org.javabahia.cassandra.spring.cv.model.Resume; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository;
package org.javabahia.cassandra.spring.cv.repository; @Repository @Scope("prototype")
// Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/model/Resume.java // @Entity // public class Resume implements Serializable{ // // private static final long serialVersionUID = 1L; // // @Id // private String nickName; // @Column // private String name; // @Column // private String country; // @Column // private String bio; // // public String getNickName() { // return nickName; // } // public void setNickName(String nickName) { // this.nickName = nickName; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getCountry() { // return country; // } // public void setCountry(String country) { // this.country = country; // } // public String getBio() { // return bio; // } // public void setBio(String bio) { // this.bio = bio; // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Resume) { // Resume other = Resume.class.cast(obj); // return new EqualsBuilder().append(other.nickName, nickName) // .isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(nickName).toHashCode(); // } // } // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/repository/ResumeRepository.java import org.easycassandra.persistence.cassandra.spring.CassandraRepository; import org.easycassandra.persistence.cassandra.spring.CassandraTemplate; import org.javabahia.cassandra.spring.cv.model.Resume; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; package org.javabahia.cassandra.spring.cv.repository; @Repository @Scope("prototype")
public class ResumeRepository extends CassandraRepository<Resume, String>{
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/service/CurriculoService.java
// Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/lucene/ResumeSearch.java // @Service // @Scope("prototype") // public class ResumeSearch { // // private static final String COLUMN_RESUME = "cv"; // private static final String COLUMN_COUNTRY = "estado"; // private static final String COLUMN_NAME = "name"; // private static final String COLUMN_NICk_NAME = "nickName"; // // public List<String> findByBio(String bio) throws ParseException, IOException { // Query query = new QueryParser(Version.LUCENE_46, COLUMN_RESUME, // LuceneUtil.INSTANCE.getAnalyzer()).parse(bio); // return returnResume(query); // } // // // // private List<String> returnResume(Query query) throws IOException { // int hitsPerPage = 10; // IndexReader reader = DirectoryReader.open(LuceneUtil.INSTANCE.getDirectory()); // IndexSearcher searcher = new IndexSearcher(reader); // TopScoreDocCollector collector = TopScoreDocCollector.create( // hitsPerPage, true); // searcher.search(query, collector); // ScoreDoc[] hits = collector.topDocs().scoreDocs; // // // List<String> resumeIDs = new LinkedList<>(); // for(int i=0;i<hits.length;++i) { // int docId = hits[i].doc; // Document d = searcher.doc(docId); // resumeIDs.add(d.get(COLUMN_NICk_NAME)); // } // return resumeIDs; // } // // public void indexarAll(List<Resume> resumes) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // for (Resume resume : resumes) { // indexWriter.addDocument(indexResume(resume)); // } // indexWriter.close(); // } // public void index(Resume resume) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // indexWriter.addDocument(indexResume(resume)); // indexWriter.close(); // } // // private Document indexResume(Resume resume) { // Document document = new Document(); // document.add(new TextField(COLUMN_NICk_NAME, resume.getNickName(), Field.Store.YES)); // document.add(new StringField(COLUMN_COUNTRY, resume.getCountry(), Field.Store.NO)); // document.add(new StringField(COLUMN_NAME, resume.getName(), Field.Store.NO)); // document.add(new TextField(COLUMN_RESUME, resume.getBio(), Field.Store.NO)); // return document; // } // // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/model/Resume.java // @Entity // public class Resume implements Serializable{ // // private static final long serialVersionUID = 1L; // // @Id // private String nickName; // @Column // private String name; // @Column // private String country; // @Column // private String bio; // // public String getNickName() { // return nickName; // } // public void setNickName(String nickName) { // this.nickName = nickName; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getCountry() { // return country; // } // public void setCountry(String country) { // this.country = country; // } // public String getBio() { // return bio; // } // public void setBio(String bio) { // this.bio = bio; // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Resume) { // Resume other = Resume.class.cast(obj); // return new EqualsBuilder().append(other.nickName, nickName) // .isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(nickName).toHashCode(); // } // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/repository/ResumeRepository.java // @Repository // @Scope("prototype") // public class ResumeRepository extends CassandraRepository<Resume, String>{ // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // }
import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.cv.lucene.ResumeSearch; import org.javabahia.cassandra.spring.cv.model.Resume; import org.javabahia.cassandra.spring.cv.repository.ResumeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service;
package org.javabahia.cassandra.spring.cv.service; @Service @Scope("prototype") public class CurriculoService { @Autowired
// Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/lucene/ResumeSearch.java // @Service // @Scope("prototype") // public class ResumeSearch { // // private static final String COLUMN_RESUME = "cv"; // private static final String COLUMN_COUNTRY = "estado"; // private static final String COLUMN_NAME = "name"; // private static final String COLUMN_NICk_NAME = "nickName"; // // public List<String> findByBio(String bio) throws ParseException, IOException { // Query query = new QueryParser(Version.LUCENE_46, COLUMN_RESUME, // LuceneUtil.INSTANCE.getAnalyzer()).parse(bio); // return returnResume(query); // } // // // // private List<String> returnResume(Query query) throws IOException { // int hitsPerPage = 10; // IndexReader reader = DirectoryReader.open(LuceneUtil.INSTANCE.getDirectory()); // IndexSearcher searcher = new IndexSearcher(reader); // TopScoreDocCollector collector = TopScoreDocCollector.create( // hitsPerPage, true); // searcher.search(query, collector); // ScoreDoc[] hits = collector.topDocs().scoreDocs; // // // List<String> resumeIDs = new LinkedList<>(); // for(int i=0;i<hits.length;++i) { // int docId = hits[i].doc; // Document d = searcher.doc(docId); // resumeIDs.add(d.get(COLUMN_NICk_NAME)); // } // return resumeIDs; // } // // public void indexarAll(List<Resume> resumes) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // for (Resume resume : resumes) { // indexWriter.addDocument(indexResume(resume)); // } // indexWriter.close(); // } // public void index(Resume resume) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // indexWriter.addDocument(indexResume(resume)); // indexWriter.close(); // } // // private Document indexResume(Resume resume) { // Document document = new Document(); // document.add(new TextField(COLUMN_NICk_NAME, resume.getNickName(), Field.Store.YES)); // document.add(new StringField(COLUMN_COUNTRY, resume.getCountry(), Field.Store.NO)); // document.add(new StringField(COLUMN_NAME, resume.getName(), Field.Store.NO)); // document.add(new TextField(COLUMN_RESUME, resume.getBio(), Field.Store.NO)); // return document; // } // // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/model/Resume.java // @Entity // public class Resume implements Serializable{ // // private static final long serialVersionUID = 1L; // // @Id // private String nickName; // @Column // private String name; // @Column // private String country; // @Column // private String bio; // // public String getNickName() { // return nickName; // } // public void setNickName(String nickName) { // this.nickName = nickName; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getCountry() { // return country; // } // public void setCountry(String country) { // this.country = country; // } // public String getBio() { // return bio; // } // public void setBio(String bio) { // this.bio = bio; // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Resume) { // Resume other = Resume.class.cast(obj); // return new EqualsBuilder().append(other.nickName, nickName) // .isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(nickName).toHashCode(); // } // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/repository/ResumeRepository.java // @Repository // @Scope("prototype") // public class ResumeRepository extends CassandraRepository<Resume, String>{ // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // } // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/service/CurriculoService.java import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.cv.lucene.ResumeSearch; import org.javabahia.cassandra.spring.cv.model.Resume; import org.javabahia.cassandra.spring.cv.repository.ResumeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; package org.javabahia.cassandra.spring.cv.service; @Service @Scope("prototype") public class CurriculoService { @Autowired
private ResumeRepository repository;
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/service/CurriculoService.java
// Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/lucene/ResumeSearch.java // @Service // @Scope("prototype") // public class ResumeSearch { // // private static final String COLUMN_RESUME = "cv"; // private static final String COLUMN_COUNTRY = "estado"; // private static final String COLUMN_NAME = "name"; // private static final String COLUMN_NICk_NAME = "nickName"; // // public List<String> findByBio(String bio) throws ParseException, IOException { // Query query = new QueryParser(Version.LUCENE_46, COLUMN_RESUME, // LuceneUtil.INSTANCE.getAnalyzer()).parse(bio); // return returnResume(query); // } // // // // private List<String> returnResume(Query query) throws IOException { // int hitsPerPage = 10; // IndexReader reader = DirectoryReader.open(LuceneUtil.INSTANCE.getDirectory()); // IndexSearcher searcher = new IndexSearcher(reader); // TopScoreDocCollector collector = TopScoreDocCollector.create( // hitsPerPage, true); // searcher.search(query, collector); // ScoreDoc[] hits = collector.topDocs().scoreDocs; // // // List<String> resumeIDs = new LinkedList<>(); // for(int i=0;i<hits.length;++i) { // int docId = hits[i].doc; // Document d = searcher.doc(docId); // resumeIDs.add(d.get(COLUMN_NICk_NAME)); // } // return resumeIDs; // } // // public void indexarAll(List<Resume> resumes) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // for (Resume resume : resumes) { // indexWriter.addDocument(indexResume(resume)); // } // indexWriter.close(); // } // public void index(Resume resume) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // indexWriter.addDocument(indexResume(resume)); // indexWriter.close(); // } // // private Document indexResume(Resume resume) { // Document document = new Document(); // document.add(new TextField(COLUMN_NICk_NAME, resume.getNickName(), Field.Store.YES)); // document.add(new StringField(COLUMN_COUNTRY, resume.getCountry(), Field.Store.NO)); // document.add(new StringField(COLUMN_NAME, resume.getName(), Field.Store.NO)); // document.add(new TextField(COLUMN_RESUME, resume.getBio(), Field.Store.NO)); // return document; // } // // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/model/Resume.java // @Entity // public class Resume implements Serializable{ // // private static final long serialVersionUID = 1L; // // @Id // private String nickName; // @Column // private String name; // @Column // private String country; // @Column // private String bio; // // public String getNickName() { // return nickName; // } // public void setNickName(String nickName) { // this.nickName = nickName; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getCountry() { // return country; // } // public void setCountry(String country) { // this.country = country; // } // public String getBio() { // return bio; // } // public void setBio(String bio) { // this.bio = bio; // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Resume) { // Resume other = Resume.class.cast(obj); // return new EqualsBuilder().append(other.nickName, nickName) // .isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(nickName).toHashCode(); // } // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/repository/ResumeRepository.java // @Repository // @Scope("prototype") // public class ResumeRepository extends CassandraRepository<Resume, String>{ // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // }
import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.cv.lucene.ResumeSearch; import org.javabahia.cassandra.spring.cv.model.Resume; import org.javabahia.cassandra.spring.cv.repository.ResumeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service;
package org.javabahia.cassandra.spring.cv.service; @Service @Scope("prototype") public class CurriculoService { @Autowired private ResumeRepository repository; @Autowired
// Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/lucene/ResumeSearch.java // @Service // @Scope("prototype") // public class ResumeSearch { // // private static final String COLUMN_RESUME = "cv"; // private static final String COLUMN_COUNTRY = "estado"; // private static final String COLUMN_NAME = "name"; // private static final String COLUMN_NICk_NAME = "nickName"; // // public List<String> findByBio(String bio) throws ParseException, IOException { // Query query = new QueryParser(Version.LUCENE_46, COLUMN_RESUME, // LuceneUtil.INSTANCE.getAnalyzer()).parse(bio); // return returnResume(query); // } // // // // private List<String> returnResume(Query query) throws IOException { // int hitsPerPage = 10; // IndexReader reader = DirectoryReader.open(LuceneUtil.INSTANCE.getDirectory()); // IndexSearcher searcher = new IndexSearcher(reader); // TopScoreDocCollector collector = TopScoreDocCollector.create( // hitsPerPage, true); // searcher.search(query, collector); // ScoreDoc[] hits = collector.topDocs().scoreDocs; // // // List<String> resumeIDs = new LinkedList<>(); // for(int i=0;i<hits.length;++i) { // int docId = hits[i].doc; // Document d = searcher.doc(docId); // resumeIDs.add(d.get(COLUMN_NICk_NAME)); // } // return resumeIDs; // } // // public void indexarAll(List<Resume> resumes) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // for (Resume resume : resumes) { // indexWriter.addDocument(indexResume(resume)); // } // indexWriter.close(); // } // public void index(Resume resume) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // indexWriter.addDocument(indexResume(resume)); // indexWriter.close(); // } // // private Document indexResume(Resume resume) { // Document document = new Document(); // document.add(new TextField(COLUMN_NICk_NAME, resume.getNickName(), Field.Store.YES)); // document.add(new StringField(COLUMN_COUNTRY, resume.getCountry(), Field.Store.NO)); // document.add(new StringField(COLUMN_NAME, resume.getName(), Field.Store.NO)); // document.add(new TextField(COLUMN_RESUME, resume.getBio(), Field.Store.NO)); // return document; // } // // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/model/Resume.java // @Entity // public class Resume implements Serializable{ // // private static final long serialVersionUID = 1L; // // @Id // private String nickName; // @Column // private String name; // @Column // private String country; // @Column // private String bio; // // public String getNickName() { // return nickName; // } // public void setNickName(String nickName) { // this.nickName = nickName; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getCountry() { // return country; // } // public void setCountry(String country) { // this.country = country; // } // public String getBio() { // return bio; // } // public void setBio(String bio) { // this.bio = bio; // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Resume) { // Resume other = Resume.class.cast(obj); // return new EqualsBuilder().append(other.nickName, nickName) // .isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(nickName).toHashCode(); // } // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/repository/ResumeRepository.java // @Repository // @Scope("prototype") // public class ResumeRepository extends CassandraRepository<Resume, String>{ // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // } // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/service/CurriculoService.java import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.cv.lucene.ResumeSearch; import org.javabahia.cassandra.spring.cv.model.Resume; import org.javabahia.cassandra.spring.cv.repository.ResumeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; package org.javabahia.cassandra.spring.cv.service; @Service @Scope("prototype") public class CurriculoService { @Autowired private ResumeRepository repository; @Autowired
private ResumeSearch search;
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/service/CurriculoService.java
// Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/lucene/ResumeSearch.java // @Service // @Scope("prototype") // public class ResumeSearch { // // private static final String COLUMN_RESUME = "cv"; // private static final String COLUMN_COUNTRY = "estado"; // private static final String COLUMN_NAME = "name"; // private static final String COLUMN_NICk_NAME = "nickName"; // // public List<String> findByBio(String bio) throws ParseException, IOException { // Query query = new QueryParser(Version.LUCENE_46, COLUMN_RESUME, // LuceneUtil.INSTANCE.getAnalyzer()).parse(bio); // return returnResume(query); // } // // // // private List<String> returnResume(Query query) throws IOException { // int hitsPerPage = 10; // IndexReader reader = DirectoryReader.open(LuceneUtil.INSTANCE.getDirectory()); // IndexSearcher searcher = new IndexSearcher(reader); // TopScoreDocCollector collector = TopScoreDocCollector.create( // hitsPerPage, true); // searcher.search(query, collector); // ScoreDoc[] hits = collector.topDocs().scoreDocs; // // // List<String> resumeIDs = new LinkedList<>(); // for(int i=0;i<hits.length;++i) { // int docId = hits[i].doc; // Document d = searcher.doc(docId); // resumeIDs.add(d.get(COLUMN_NICk_NAME)); // } // return resumeIDs; // } // // public void indexarAll(List<Resume> resumes) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // for (Resume resume : resumes) { // indexWriter.addDocument(indexResume(resume)); // } // indexWriter.close(); // } // public void index(Resume resume) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // indexWriter.addDocument(indexResume(resume)); // indexWriter.close(); // } // // private Document indexResume(Resume resume) { // Document document = new Document(); // document.add(new TextField(COLUMN_NICk_NAME, resume.getNickName(), Field.Store.YES)); // document.add(new StringField(COLUMN_COUNTRY, resume.getCountry(), Field.Store.NO)); // document.add(new StringField(COLUMN_NAME, resume.getName(), Field.Store.NO)); // document.add(new TextField(COLUMN_RESUME, resume.getBio(), Field.Store.NO)); // return document; // } // // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/model/Resume.java // @Entity // public class Resume implements Serializable{ // // private static final long serialVersionUID = 1L; // // @Id // private String nickName; // @Column // private String name; // @Column // private String country; // @Column // private String bio; // // public String getNickName() { // return nickName; // } // public void setNickName(String nickName) { // this.nickName = nickName; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getCountry() { // return country; // } // public void setCountry(String country) { // this.country = country; // } // public String getBio() { // return bio; // } // public void setBio(String bio) { // this.bio = bio; // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Resume) { // Resume other = Resume.class.cast(obj); // return new EqualsBuilder().append(other.nickName, nickName) // .isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(nickName).toHashCode(); // } // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/repository/ResumeRepository.java // @Repository // @Scope("prototype") // public class ResumeRepository extends CassandraRepository<Resume, String>{ // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // }
import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.cv.lucene.ResumeSearch; import org.javabahia.cassandra.spring.cv.model.Resume; import org.javabahia.cassandra.spring.cv.repository.ResumeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service;
package org.javabahia.cassandra.spring.cv.service; @Service @Scope("prototype") public class CurriculoService { @Autowired private ResumeRepository repository; @Autowired private ResumeSearch search;
// Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/lucene/ResumeSearch.java // @Service // @Scope("prototype") // public class ResumeSearch { // // private static final String COLUMN_RESUME = "cv"; // private static final String COLUMN_COUNTRY = "estado"; // private static final String COLUMN_NAME = "name"; // private static final String COLUMN_NICk_NAME = "nickName"; // // public List<String> findByBio(String bio) throws ParseException, IOException { // Query query = new QueryParser(Version.LUCENE_46, COLUMN_RESUME, // LuceneUtil.INSTANCE.getAnalyzer()).parse(bio); // return returnResume(query); // } // // // // private List<String> returnResume(Query query) throws IOException { // int hitsPerPage = 10; // IndexReader reader = DirectoryReader.open(LuceneUtil.INSTANCE.getDirectory()); // IndexSearcher searcher = new IndexSearcher(reader); // TopScoreDocCollector collector = TopScoreDocCollector.create( // hitsPerPage, true); // searcher.search(query, collector); // ScoreDoc[] hits = collector.topDocs().scoreDocs; // // // List<String> resumeIDs = new LinkedList<>(); // for(int i=0;i<hits.length;++i) { // int docId = hits[i].doc; // Document d = searcher.doc(docId); // resumeIDs.add(d.get(COLUMN_NICk_NAME)); // } // return resumeIDs; // } // // public void indexarAll(List<Resume> resumes) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // for (Resume resume : resumes) { // indexWriter.addDocument(indexResume(resume)); // } // indexWriter.close(); // } // public void index(Resume resume) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // indexWriter.addDocument(indexResume(resume)); // indexWriter.close(); // } // // private Document indexResume(Resume resume) { // Document document = new Document(); // document.add(new TextField(COLUMN_NICk_NAME, resume.getNickName(), Field.Store.YES)); // document.add(new StringField(COLUMN_COUNTRY, resume.getCountry(), Field.Store.NO)); // document.add(new StringField(COLUMN_NAME, resume.getName(), Field.Store.NO)); // document.add(new TextField(COLUMN_RESUME, resume.getBio(), Field.Store.NO)); // return document; // } // // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/model/Resume.java // @Entity // public class Resume implements Serializable{ // // private static final long serialVersionUID = 1L; // // @Id // private String nickName; // @Column // private String name; // @Column // private String country; // @Column // private String bio; // // public String getNickName() { // return nickName; // } // public void setNickName(String nickName) { // this.nickName = nickName; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getCountry() { // return country; // } // public void setCountry(String country) { // this.country = country; // } // public String getBio() { // return bio; // } // public void setBio(String bio) { // this.bio = bio; // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Resume) { // Resume other = Resume.class.cast(obj); // return new EqualsBuilder().append(other.nickName, nickName) // .isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(nickName).toHashCode(); // } // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/repository/ResumeRepository.java // @Repository // @Scope("prototype") // public class ResumeRepository extends CassandraRepository<Resume, String>{ // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // } // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/service/CurriculoService.java import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.cv.lucene.ResumeSearch; import org.javabahia.cassandra.spring.cv.model.Resume; import org.javabahia.cassandra.spring.cv.repository.ResumeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; package org.javabahia.cassandra.spring.cv.service; @Service @Scope("prototype") public class CurriculoService { @Autowired private ResumeRepository repository; @Autowired private ResumeSearch search;
public void save(Resume cv){
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/service/MusicService.java
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/lucene/MusicSearch.java // @Service // @Scope("prototype") // public class MusicSearch { // // // // private static final String COLUNM_LYRIC = "lyric"; // private static final String COLUNM_AUTHOR = "Author"; // private static final String COLUMN_NAME = "name"; // // public List<String> findMusicByLyric(String lyric) throws ParseException, IOException { // // Query query = new QueryParser(Version.LUCENE_46, COLUNM_LYRIC, // LuceneUtil.INSTANCE.getAnalyzer()).parse(lyric); // // return returnMusics(query); // } // // public List<String> findMusicByAuthor(String author) throws ParseException, IOException { // Term term = new Term(COLUNM_AUTHOR, author); // Query query = new TermQuery(term); // return returnMusics(query); // } // // private List<String> returnMusics(Query query) throws IOException { // int hitsPerPage = 10; // IndexReader reader = DirectoryReader.open(LuceneUtil.INSTANCE.getDirectory()); // IndexSearcher searcher = new IndexSearcher(reader); // TopScoreDocCollector collector = TopScoreDocCollector.create( // hitsPerPage, true); // searcher.search(query, collector); // ScoreDoc[] hits = collector.topDocs().scoreDocs; // // // List<String> musics = new LinkedList<>(); // for(int i=0;i<hits.length;++i) { // int docId = hits[i].doc; // Document d = searcher.doc(docId); // musics.add(d.get(COLUMN_NAME)); // } // return musics; // } // // public void indexarAll(List<Music> musicas) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // for (Music music : musicas) { // indexWriter.addDocument(indexMusic(music)); // } // indexWriter.close(); // } // public void index(Music music) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // indexWriter.addDocument(indexMusic(music)); // indexWriter.close(); // } // // private Document indexMusic(Music music) { // Document document = new Document(); // document.add(new TextField(COLUMN_NAME, music.getName(), Field.Store.YES)); // document.add(new StringField(COLUNM_AUTHOR, music.getAuthor(), Field.Store.NO)); // document.add(new TextField(COLUNM_LYRIC, music.getLyric(), Field.Store.NO)); // return document; // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/repository/MusicRepository.java // @Repository // @Scope("prototype") // public class MusicRepository extends CassandraRepository<Music, String>{ // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // }
import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.logging.Logger; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.lucene.MusicSearch; import org.javabahia.cassandra.spring.model.Music; import org.javabahia.cassandra.spring.repository.MusicRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service;
package org.javabahia.cassandra.spring.service; @Service @Scope("prototype") public class MusicService { @Autowired
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/lucene/MusicSearch.java // @Service // @Scope("prototype") // public class MusicSearch { // // // // private static final String COLUNM_LYRIC = "lyric"; // private static final String COLUNM_AUTHOR = "Author"; // private static final String COLUMN_NAME = "name"; // // public List<String> findMusicByLyric(String lyric) throws ParseException, IOException { // // Query query = new QueryParser(Version.LUCENE_46, COLUNM_LYRIC, // LuceneUtil.INSTANCE.getAnalyzer()).parse(lyric); // // return returnMusics(query); // } // // public List<String> findMusicByAuthor(String author) throws ParseException, IOException { // Term term = new Term(COLUNM_AUTHOR, author); // Query query = new TermQuery(term); // return returnMusics(query); // } // // private List<String> returnMusics(Query query) throws IOException { // int hitsPerPage = 10; // IndexReader reader = DirectoryReader.open(LuceneUtil.INSTANCE.getDirectory()); // IndexSearcher searcher = new IndexSearcher(reader); // TopScoreDocCollector collector = TopScoreDocCollector.create( // hitsPerPage, true); // searcher.search(query, collector); // ScoreDoc[] hits = collector.topDocs().scoreDocs; // // // List<String> musics = new LinkedList<>(); // for(int i=0;i<hits.length;++i) { // int docId = hits[i].doc; // Document d = searcher.doc(docId); // musics.add(d.get(COLUMN_NAME)); // } // return musics; // } // // public void indexarAll(List<Music> musicas) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // for (Music music : musicas) { // indexWriter.addDocument(indexMusic(music)); // } // indexWriter.close(); // } // public void index(Music music) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // indexWriter.addDocument(indexMusic(music)); // indexWriter.close(); // } // // private Document indexMusic(Music music) { // Document document = new Document(); // document.add(new TextField(COLUMN_NAME, music.getName(), Field.Store.YES)); // document.add(new StringField(COLUNM_AUTHOR, music.getAuthor(), Field.Store.NO)); // document.add(new TextField(COLUNM_LYRIC, music.getLyric(), Field.Store.NO)); // return document; // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/repository/MusicRepository.java // @Repository // @Scope("prototype") // public class MusicRepository extends CassandraRepository<Music, String>{ // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // } // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/service/MusicService.java import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.logging.Logger; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.lucene.MusicSearch; import org.javabahia.cassandra.spring.model.Music; import org.javabahia.cassandra.spring.repository.MusicRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; package org.javabahia.cassandra.spring.service; @Service @Scope("prototype") public class MusicService { @Autowired
private MusicRepository repository;
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/service/MusicService.java
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/lucene/MusicSearch.java // @Service // @Scope("prototype") // public class MusicSearch { // // // // private static final String COLUNM_LYRIC = "lyric"; // private static final String COLUNM_AUTHOR = "Author"; // private static final String COLUMN_NAME = "name"; // // public List<String> findMusicByLyric(String lyric) throws ParseException, IOException { // // Query query = new QueryParser(Version.LUCENE_46, COLUNM_LYRIC, // LuceneUtil.INSTANCE.getAnalyzer()).parse(lyric); // // return returnMusics(query); // } // // public List<String> findMusicByAuthor(String author) throws ParseException, IOException { // Term term = new Term(COLUNM_AUTHOR, author); // Query query = new TermQuery(term); // return returnMusics(query); // } // // private List<String> returnMusics(Query query) throws IOException { // int hitsPerPage = 10; // IndexReader reader = DirectoryReader.open(LuceneUtil.INSTANCE.getDirectory()); // IndexSearcher searcher = new IndexSearcher(reader); // TopScoreDocCollector collector = TopScoreDocCollector.create( // hitsPerPage, true); // searcher.search(query, collector); // ScoreDoc[] hits = collector.topDocs().scoreDocs; // // // List<String> musics = new LinkedList<>(); // for(int i=0;i<hits.length;++i) { // int docId = hits[i].doc; // Document d = searcher.doc(docId); // musics.add(d.get(COLUMN_NAME)); // } // return musics; // } // // public void indexarAll(List<Music> musicas) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // for (Music music : musicas) { // indexWriter.addDocument(indexMusic(music)); // } // indexWriter.close(); // } // public void index(Music music) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // indexWriter.addDocument(indexMusic(music)); // indexWriter.close(); // } // // private Document indexMusic(Music music) { // Document document = new Document(); // document.add(new TextField(COLUMN_NAME, music.getName(), Field.Store.YES)); // document.add(new StringField(COLUNM_AUTHOR, music.getAuthor(), Field.Store.NO)); // document.add(new TextField(COLUNM_LYRIC, music.getLyric(), Field.Store.NO)); // return document; // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/repository/MusicRepository.java // @Repository // @Scope("prototype") // public class MusicRepository extends CassandraRepository<Music, String>{ // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // }
import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.logging.Logger; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.lucene.MusicSearch; import org.javabahia.cassandra.spring.model.Music; import org.javabahia.cassandra.spring.repository.MusicRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service;
package org.javabahia.cassandra.spring.service; @Service @Scope("prototype") public class MusicService { @Autowired private MusicRepository repository; @Autowired
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/lucene/MusicSearch.java // @Service // @Scope("prototype") // public class MusicSearch { // // // // private static final String COLUNM_LYRIC = "lyric"; // private static final String COLUNM_AUTHOR = "Author"; // private static final String COLUMN_NAME = "name"; // // public List<String> findMusicByLyric(String lyric) throws ParseException, IOException { // // Query query = new QueryParser(Version.LUCENE_46, COLUNM_LYRIC, // LuceneUtil.INSTANCE.getAnalyzer()).parse(lyric); // // return returnMusics(query); // } // // public List<String> findMusicByAuthor(String author) throws ParseException, IOException { // Term term = new Term(COLUNM_AUTHOR, author); // Query query = new TermQuery(term); // return returnMusics(query); // } // // private List<String> returnMusics(Query query) throws IOException { // int hitsPerPage = 10; // IndexReader reader = DirectoryReader.open(LuceneUtil.INSTANCE.getDirectory()); // IndexSearcher searcher = new IndexSearcher(reader); // TopScoreDocCollector collector = TopScoreDocCollector.create( // hitsPerPage, true); // searcher.search(query, collector); // ScoreDoc[] hits = collector.topDocs().scoreDocs; // // // List<String> musics = new LinkedList<>(); // for(int i=0;i<hits.length;++i) { // int docId = hits[i].doc; // Document d = searcher.doc(docId); // musics.add(d.get(COLUMN_NAME)); // } // return musics; // } // // public void indexarAll(List<Music> musicas) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // for (Music music : musicas) { // indexWriter.addDocument(indexMusic(music)); // } // indexWriter.close(); // } // public void index(Music music) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // indexWriter.addDocument(indexMusic(music)); // indexWriter.close(); // } // // private Document indexMusic(Music music) { // Document document = new Document(); // document.add(new TextField(COLUMN_NAME, music.getName(), Field.Store.YES)); // document.add(new StringField(COLUNM_AUTHOR, music.getAuthor(), Field.Store.NO)); // document.add(new TextField(COLUNM_LYRIC, music.getLyric(), Field.Store.NO)); // return document; // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/repository/MusicRepository.java // @Repository // @Scope("prototype") // public class MusicRepository extends CassandraRepository<Music, String>{ // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // } // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/service/MusicService.java import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.logging.Logger; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.lucene.MusicSearch; import org.javabahia.cassandra.spring.model.Music; import org.javabahia.cassandra.spring.repository.MusicRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; package org.javabahia.cassandra.spring.service; @Service @Scope("prototype") public class MusicService { @Autowired private MusicRepository repository; @Autowired
private MusicSearch musicaSearch;
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/service/MusicService.java
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/lucene/MusicSearch.java // @Service // @Scope("prototype") // public class MusicSearch { // // // // private static final String COLUNM_LYRIC = "lyric"; // private static final String COLUNM_AUTHOR = "Author"; // private static final String COLUMN_NAME = "name"; // // public List<String> findMusicByLyric(String lyric) throws ParseException, IOException { // // Query query = new QueryParser(Version.LUCENE_46, COLUNM_LYRIC, // LuceneUtil.INSTANCE.getAnalyzer()).parse(lyric); // // return returnMusics(query); // } // // public List<String> findMusicByAuthor(String author) throws ParseException, IOException { // Term term = new Term(COLUNM_AUTHOR, author); // Query query = new TermQuery(term); // return returnMusics(query); // } // // private List<String> returnMusics(Query query) throws IOException { // int hitsPerPage = 10; // IndexReader reader = DirectoryReader.open(LuceneUtil.INSTANCE.getDirectory()); // IndexSearcher searcher = new IndexSearcher(reader); // TopScoreDocCollector collector = TopScoreDocCollector.create( // hitsPerPage, true); // searcher.search(query, collector); // ScoreDoc[] hits = collector.topDocs().scoreDocs; // // // List<String> musics = new LinkedList<>(); // for(int i=0;i<hits.length;++i) { // int docId = hits[i].doc; // Document d = searcher.doc(docId); // musics.add(d.get(COLUMN_NAME)); // } // return musics; // } // // public void indexarAll(List<Music> musicas) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // for (Music music : musicas) { // indexWriter.addDocument(indexMusic(music)); // } // indexWriter.close(); // } // public void index(Music music) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // indexWriter.addDocument(indexMusic(music)); // indexWriter.close(); // } // // private Document indexMusic(Music music) { // Document document = new Document(); // document.add(new TextField(COLUMN_NAME, music.getName(), Field.Store.YES)); // document.add(new StringField(COLUNM_AUTHOR, music.getAuthor(), Field.Store.NO)); // document.add(new TextField(COLUNM_LYRIC, music.getLyric(), Field.Store.NO)); // return document; // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/repository/MusicRepository.java // @Repository // @Scope("prototype") // public class MusicRepository extends CassandraRepository<Music, String>{ // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // }
import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.logging.Logger; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.lucene.MusicSearch; import org.javabahia.cassandra.spring.model.Music; import org.javabahia.cassandra.spring.repository.MusicRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service;
package org.javabahia.cassandra.spring.service; @Service @Scope("prototype") public class MusicService { @Autowired private MusicRepository repository; @Autowired private MusicSearch musicaSearch;
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/lucene/MusicSearch.java // @Service // @Scope("prototype") // public class MusicSearch { // // // // private static final String COLUNM_LYRIC = "lyric"; // private static final String COLUNM_AUTHOR = "Author"; // private static final String COLUMN_NAME = "name"; // // public List<String> findMusicByLyric(String lyric) throws ParseException, IOException { // // Query query = new QueryParser(Version.LUCENE_46, COLUNM_LYRIC, // LuceneUtil.INSTANCE.getAnalyzer()).parse(lyric); // // return returnMusics(query); // } // // public List<String> findMusicByAuthor(String author) throws ParseException, IOException { // Term term = new Term(COLUNM_AUTHOR, author); // Query query = new TermQuery(term); // return returnMusics(query); // } // // private List<String> returnMusics(Query query) throws IOException { // int hitsPerPage = 10; // IndexReader reader = DirectoryReader.open(LuceneUtil.INSTANCE.getDirectory()); // IndexSearcher searcher = new IndexSearcher(reader); // TopScoreDocCollector collector = TopScoreDocCollector.create( // hitsPerPage, true); // searcher.search(query, collector); // ScoreDoc[] hits = collector.topDocs().scoreDocs; // // // List<String> musics = new LinkedList<>(); // for(int i=0;i<hits.length;++i) { // int docId = hits[i].doc; // Document d = searcher.doc(docId); // musics.add(d.get(COLUMN_NAME)); // } // return musics; // } // // public void indexarAll(List<Music> musicas) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // for (Music music : musicas) { // indexWriter.addDocument(indexMusic(music)); // } // indexWriter.close(); // } // public void index(Music music) throws IOException { // IndexWriter indexWriter = LuceneUtil.INSTANCE.getIndexWriter(); // indexWriter.addDocument(indexMusic(music)); // indexWriter.close(); // } // // private Document indexMusic(Music music) { // Document document = new Document(); // document.add(new TextField(COLUMN_NAME, music.getName(), Field.Store.YES)); // document.add(new StringField(COLUNM_AUTHOR, music.getAuthor(), Field.Store.NO)); // document.add(new TextField(COLUNM_LYRIC, music.getLyric(), Field.Store.NO)); // return document; // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/repository/MusicRepository.java // @Repository // @Scope("prototype") // public class MusicRepository extends CassandraRepository<Music, String>{ // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // } // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/service/MusicService.java import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.logging.Logger; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.lucene.MusicSearch; import org.javabahia.cassandra.spring.model.Music; import org.javabahia.cassandra.spring.repository.MusicRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; package org.javabahia.cassandra.spring.service; @Service @Scope("prototype") public class MusicService { @Autowired private MusicRepository repository; @Autowired private MusicSearch musicaSearch;
public void save(Music musica){
otaviojava/Easy-Cassandra-samples
cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/repository/TweetRepository.java
// Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/model/Tweet.java // @Entity(name = "tweet") // public class Tweet implements Serializable { // // private static final long serialVersionUID = 3L; // // @Id // private UUID id; // // @Index // @Column(name = "nickName") // private String nickName; // // @Column(name = "message") // private String message; // // @Column(name = "time") // private Date time; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getNickName() { // return nickName; // } // // public void setNickName(String nickName) { // this.nickName = nickName; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof Tweet) { // Tweet other = Tweet.class.cast(obj); // return new EqualsBuilder().append(id, other.id).isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(id).toHashCode(); // } // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // }
import java.util.List; import java.util.UUID; import org.easycassandra.persistence.cassandra.Persistence; import org.javabahia.cassandra.tweet.model.Tweet;
package org.javabahia.cassandra.tweet.repository; public class TweetRepository { private Persistence persistence;
// Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/model/Tweet.java // @Entity(name = "tweet") // public class Tweet implements Serializable { // // private static final long serialVersionUID = 3L; // // @Id // private UUID id; // // @Index // @Column(name = "nickName") // private String nickName; // // @Column(name = "message") // private String message; // // @Column(name = "time") // private Date time; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getNickName() { // return nickName; // } // // public void setNickName(String nickName) { // this.nickName = nickName; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof Tweet) { // Tweet other = Tweet.class.cast(obj); // return new EqualsBuilder().append(id, other.id).isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(id).toHashCode(); // } // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/repository/TweetRepository.java import java.util.List; import java.util.UUID; import org.easycassandra.persistence.cassandra.Persistence; import org.javabahia.cassandra.tweet.model.Tweet; package org.javabahia.cassandra.tweet.repository; public class TweetRepository { private Persistence persistence;
public List<Tweet> findByIndex(String nickName) {
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/rest/ResumeResource.java
// Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/model/Resume.java // @Entity // public class Resume implements Serializable{ // // private static final long serialVersionUID = 1L; // // @Id // private String nickName; // @Column // private String name; // @Column // private String country; // @Column // private String bio; // // public String getNickName() { // return nickName; // } // public void setNickName(String nickName) { // this.nickName = nickName; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getCountry() { // return country; // } // public void setCountry(String country) { // this.country = country; // } // public String getBio() { // return bio; // } // public void setBio(String bio) { // this.bio = bio; // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Resume) { // Resume other = Resume.class.cast(obj); // return new EqualsBuilder().append(other.nickName, nickName) // .isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(nickName).toHashCode(); // } // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/service/CurriculoService.java // @Service // @Scope("prototype") // public class CurriculoService { // // @Autowired // private ResumeRepository repository; // // @Autowired // private ResumeSearch search; // // public void save(Resume cv){ // repository.save(cv); // try { // search.index(cv); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public List<Resume> procurarCV(String texto) { // try { // List<String> ids = search.findByBio(texto); // return (List<Resume>) repository.findAll(ids); // } catch (ParseException | IOException e) { // e.printStackTrace(); // } // return Collections.emptyList(); // } // // }
import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.javabahia.cassandra.spring.cv.model.Resume; import org.javabahia.cassandra.spring.cv.service.CurriculoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
package org.javabahia.cassandra.spring.cv.rest; @Component @Path("/resume") public class ResumeResource { @Autowired
// Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/model/Resume.java // @Entity // public class Resume implements Serializable{ // // private static final long serialVersionUID = 1L; // // @Id // private String nickName; // @Column // private String name; // @Column // private String country; // @Column // private String bio; // // public String getNickName() { // return nickName; // } // public void setNickName(String nickName) { // this.nickName = nickName; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getCountry() { // return country; // } // public void setCountry(String country) { // this.country = country; // } // public String getBio() { // return bio; // } // public void setBio(String bio) { // this.bio = bio; // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Resume) { // Resume other = Resume.class.cast(obj); // return new EqualsBuilder().append(other.nickName, nickName) // .isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(nickName).toHashCode(); // } // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/service/CurriculoService.java // @Service // @Scope("prototype") // public class CurriculoService { // // @Autowired // private ResumeRepository repository; // // @Autowired // private ResumeSearch search; // // public void save(Resume cv){ // repository.save(cv); // try { // search.index(cv); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public List<Resume> procurarCV(String texto) { // try { // List<String> ids = search.findByBio(texto); // return (List<Resume>) repository.findAll(ids); // } catch (ParseException | IOException e) { // e.printStackTrace(); // } // return Collections.emptyList(); // } // // } // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/rest/ResumeResource.java import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.javabahia.cassandra.spring.cv.model.Resume; import org.javabahia.cassandra.spring.cv.service.CurriculoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; package org.javabahia.cassandra.spring.cv.rest; @Component @Path("/resume") public class ResumeResource { @Autowired
private CurriculoService service;
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/rest/ResumeResource.java
// Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/model/Resume.java // @Entity // public class Resume implements Serializable{ // // private static final long serialVersionUID = 1L; // // @Id // private String nickName; // @Column // private String name; // @Column // private String country; // @Column // private String bio; // // public String getNickName() { // return nickName; // } // public void setNickName(String nickName) { // this.nickName = nickName; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getCountry() { // return country; // } // public void setCountry(String country) { // this.country = country; // } // public String getBio() { // return bio; // } // public void setBio(String bio) { // this.bio = bio; // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Resume) { // Resume other = Resume.class.cast(obj); // return new EqualsBuilder().append(other.nickName, nickName) // .isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(nickName).toHashCode(); // } // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/service/CurriculoService.java // @Service // @Scope("prototype") // public class CurriculoService { // // @Autowired // private ResumeRepository repository; // // @Autowired // private ResumeSearch search; // // public void save(Resume cv){ // repository.save(cv); // try { // search.index(cv); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public List<Resume> procurarCV(String texto) { // try { // List<String> ids = search.findByBio(texto); // return (List<Resume>) repository.findAll(ids); // } catch (ParseException | IOException e) { // e.printStackTrace(); // } // return Collections.emptyList(); // } // // }
import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.javabahia.cassandra.spring.cv.model.Resume; import org.javabahia.cassandra.spring.cv.service.CurriculoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
package org.javabahia.cassandra.spring.cv.rest; @Component @Path("/resume") public class ResumeResource { @Autowired private CurriculoService service; @GET public Response printMessage() { return Response.status(200).entity("It's working").build(); } @GET @Path("/{conteudo}") @Produces("application/json;charset=utf-8")
// Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/model/Resume.java // @Entity // public class Resume implements Serializable{ // // private static final long serialVersionUID = 1L; // // @Id // private String nickName; // @Column // private String name; // @Column // private String country; // @Column // private String bio; // // public String getNickName() { // return nickName; // } // public void setNickName(String nickName) { // this.nickName = nickName; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getCountry() { // return country; // } // public void setCountry(String country) { // this.country = country; // } // public String getBio() { // return bio; // } // public void setBio(String bio) { // this.bio = bio; // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Resume) { // Resume other = Resume.class.cast(obj); // return new EqualsBuilder().append(other.nickName, nickName) // .isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(nickName).toHashCode(); // } // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/service/CurriculoService.java // @Service // @Scope("prototype") // public class CurriculoService { // // @Autowired // private ResumeRepository repository; // // @Autowired // private ResumeSearch search; // // public void save(Resume cv){ // repository.save(cv); // try { // search.index(cv); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public List<Resume> procurarCV(String texto) { // try { // List<String> ids = search.findByBio(texto); // return (List<Resume>) repository.findAll(ids); // } catch (ParseException | IOException e) { // e.printStackTrace(); // } // return Collections.emptyList(); // } // // } // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/rest/ResumeResource.java import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.javabahia.cassandra.spring.cv.model.Resume; import org.javabahia.cassandra.spring.cv.service.CurriculoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; package org.javabahia.cassandra.spring.cv.rest; @Component @Path("/resume") public class ResumeResource { @Autowired private CurriculoService service; @GET public Response printMessage() { return Response.status(200).entity("It's working").build(); } @GET @Path("/{conteudo}") @Produces("application/json;charset=utf-8")
public List<Resume> getCV(@PathParam("conteudo")String text) {
otaviojava/Easy-Cassandra-samples
cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/repository/CassandraManager.java
// Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/model/Tweet.java // @Entity(name = "tweet") // public class Tweet implements Serializable { // // private static final long serialVersionUID = 3L; // // @Id // private UUID id; // // @Index // @Column(name = "nickName") // private String nickName; // // @Column(name = "message") // private String message; // // @Column(name = "time") // private Date time; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getNickName() { // return nickName; // } // // public void setNickName(String nickName) { // this.nickName = nickName; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof Tweet) { // Tweet other = Tweet.class.cast(obj); // return new EqualsBuilder().append(id, other.id).isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(id).toHashCode(); // } // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // }
import org.easycassandra.persistence.cassandra.ClusterInformation; import org.easycassandra.persistence.cassandra.EasyCassandraManager; import org.easycassandra.persistence.cassandra.Persistence; import org.javabahia.cassandra.tweet.model.Tweet;
package org.javabahia.cassandra.tweet.repository; public enum CassandraManager { INSTANCE; private EasyCassandraManager easyCassandraManager; private Persistence persistence; { easyCassandraManager = new EasyCassandraManager(ClusterInformation.create().addHost("localhost").withKeySpace("javabahia"));
// Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/model/Tweet.java // @Entity(name = "tweet") // public class Tweet implements Serializable { // // private static final long serialVersionUID = 3L; // // @Id // private UUID id; // // @Index // @Column(name = "nickName") // private String nickName; // // @Column(name = "message") // private String message; // // @Column(name = "time") // private Date time; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getNickName() { // return nickName; // } // // public void setNickName(String nickName) { // this.nickName = nickName; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof Tweet) { // Tweet other = Tweet.class.cast(obj); // return new EqualsBuilder().append(id, other.id).isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(id).toHashCode(); // } // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/repository/CassandraManager.java import org.easycassandra.persistence.cassandra.ClusterInformation; import org.easycassandra.persistence.cassandra.EasyCassandraManager; import org.easycassandra.persistence.cassandra.Persistence; import org.javabahia.cassandra.tweet.model.Tweet; package org.javabahia.cassandra.tweet.repository; public enum CassandraManager { INSTANCE; private EasyCassandraManager easyCassandraManager; private Persistence persistence; { easyCassandraManager = new EasyCassandraManager(ClusterInformation.create().addHost("localhost").withKeySpace("javabahia"));
easyCassandraManager.addFamilyObject(Tweet.class);
otaviojava/Easy-Cassandra-samples
cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/persistence/PersistenceManager.java
// Path: cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/api/CostUnit.java // @XmlRootElement // @Entity // public class CostUnit implements Serializable{ // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id // private String city; // // @Column // private String address; // // @Column // private String neighborhood; // // @Column // private String state; // // @Column // private Double value; // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getAddress() { // return address; // } // // public void setAddress(String address) { // this.address = address; // } // // public String getNeighborhood() { // return neighborhood; // } // // public void setNeighborhood(String neighborhood) { // this.neighborhood = neighborhood; // } // // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // // public Double getValue() { // return value; // } // // public void setValue(Double value) { // this.value = value; // } // // // @Override // public String toString() { // // return neighborhood+city +" - "+state+" R$ "+value; // } // // public static CostUnit valueof(String[] strings) { // CostUnit controle = new CostUnit(); // controle.setCity(strings[0]); // controle.setAddress(strings[1]); // controle.setNeighborhood(strings[2]); // controle.setState(strings[3]); // controle.setValue(new Double(strings[4])); // // return controle; // } // }
import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import javax.inject.Inject; import org.easycassandra.persistence.cassandra.CassandraFactory; import org.easycassandra.persistence.cassandra.ClusterInformation; import org.easycassandra.persistence.cassandra.EasyCassandraManager; import org.easycassandra.persistence.cassandra.Persistence; import org.easycassandra.samples.javaee.rest.api.CostUnit;
package org.easycassandra.samples.javaee.rest.persistence; @ApplicationScoped public class PersistenceManager { private static final String HOST = "localhost"; private static final String KEY_SPACE = "javaee"; @Produces private CassandraFactory cassandraFactory; @Produces private Persistence persistence; @Inject public void init(){ ClusterInformation clusterInformation = ClusterInformation.create() .withKeySpace(KEY_SPACE).addHost(HOST); EasyCassandraManager easyCassandraManager=new EasyCassandraManager(clusterInformation);
// Path: cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/api/CostUnit.java // @XmlRootElement // @Entity // public class CostUnit implements Serializable{ // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id // private String city; // // @Column // private String address; // // @Column // private String neighborhood; // // @Column // private String state; // // @Column // private Double value; // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getAddress() { // return address; // } // // public void setAddress(String address) { // this.address = address; // } // // public String getNeighborhood() { // return neighborhood; // } // // public void setNeighborhood(String neighborhood) { // this.neighborhood = neighborhood; // } // // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // // public Double getValue() { // return value; // } // // public void setValue(Double value) { // this.value = value; // } // // // @Override // public String toString() { // // return neighborhood+city +" - "+state+" R$ "+value; // } // // public static CostUnit valueof(String[] strings) { // CostUnit controle = new CostUnit(); // controle.setCity(strings[0]); // controle.setAddress(strings[1]); // controle.setNeighborhood(strings[2]); // controle.setState(strings[3]); // controle.setValue(new Double(strings[4])); // // return controle; // } // } // Path: cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/persistence/PersistenceManager.java import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import javax.inject.Inject; import org.easycassandra.persistence.cassandra.CassandraFactory; import org.easycassandra.persistence.cassandra.ClusterInformation; import org.easycassandra.persistence.cassandra.EasyCassandraManager; import org.easycassandra.persistence.cassandra.Persistence; import org.easycassandra.samples.javaee.rest.api.CostUnit; package org.easycassandra.samples.javaee.rest.persistence; @ApplicationScoped public class PersistenceManager { private static final String HOST = "localhost"; private static final String KEY_SPACE = "javaee"; @Produces private CassandraFactory cassandraFactory; @Produces private Persistence persistence; @Inject public void init(){ ClusterInformation clusterInformation = ClusterInformation.create() .withKeySpace(KEY_SPACE).addHost(HOST); EasyCassandraManager easyCassandraManager=new EasyCassandraManager(clusterInformation);
easyCassandraManager.addFamilyObject(CostUnit.class);
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/repository/MusicRepository.java
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // }
import org.easycassandra.persistence.cassandra.spring.CassandraRepository; import org.easycassandra.persistence.cassandra.spring.CassandraTemplate; import org.javabahia.cassandra.spring.model.Music; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository;
package org.javabahia.cassandra.spring.repository; @Repository @Scope("prototype")
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/repository/MusicRepository.java import org.easycassandra.persistence.cassandra.spring.CassandraRepository; import org.easycassandra.persistence.cassandra.spring.CassandraTemplate; import org.javabahia.cassandra.spring.model.Music; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; package org.javabahia.cassandra.spring.repository; @Repository @Scope("prototype")
public class MusicRepository extends CassandraRepository<Music, String>{
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/App.java
// Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempoID.java // public class PrevisaoTempoID implements Serializable { // // private static final long serialVersionUID = -3202328496277683345L; // @Column // private String cidade; // @Column // private Date dia; // // public String getCidade() { // return cidade; // } // // public void setCidade(String cidade) { // this.cidade = cidade; // } // // public Date getDia() { // return dia; // } // // public void setDia(Date dia) { // this.dia = dia; // } // // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempoID) { // PrevisaoTempoID other = PrevisaoTempoID.class.cast(obj); // return new EqualsBuilder().append(cidade, other.cidade) // .append(dia, other.dia).isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(dia).append(cidade).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoMediaService.java // @Service // public class PrevisaoMediaService extends AbstractService{ // // @Autowired // private PrevisaoTempoMediaRepository repository; // // @Autowired // private PrevisaoTempoRepository previsaoTempoRepository; // // public void atualizar(PrevisaoTempoID id) { // PrevisaoTempo previsao = previsaoTempoRepository.findOne(id); // Double temperaturaMedia = 0d; // for (Double temperatura: previsao.getTemperaturas() ){ // temperaturaMedia+=temperatura; // } // temperaturaMedia/=previsao.getTemperaturas().size(); // // PrevisaoTempoMedia previsaoTempoMedia = new PrevisaoTempoMedia(); // previsaoTempoMedia.setId(id); // previsaoTempoMedia.setTemperatura(temperaturaMedia); // // repository.save(previsaoTempoMedia); // } // public PrevisaoTempoMedia findById(PrevisaoTempoID id) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // return repository.findOne(id); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoService.java // @Service // public class PrevisaoService extends AbstractService{ // // @Autowired // private PrevisaoTempoRepository repository; // // @Autowired // private PrevisaoMediaService mediaService; // // public void inserir(PrevisaoTempoID id, double temperatura) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // // UpdateBuilder<PrevisaoTempo> updateBuilder = repository.updateBuilder(id); // updateBuilder.addList("temperaturas", temperatura).value("temperatura", temperatura); // updateBuilder.executeAsync(); // // mediaService.atualizar(id); // } // // public PrevisaoTempo findById(PrevisaoTempoID id) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // return repository.findOne(id); // } // // // }
import java.util.Date; import linguagil.cassandra.temperatura.model.PrevisaoTempoID; import linguagil.cassandra.temperatura.service.PrevisaoMediaService; import linguagil.cassandra.temperatura.service.PrevisaoService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext;
package linguagil.cassandra.temperatura; /** * Hello world! * */ public class App { public static void main( String[] args ) { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
// Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempoID.java // public class PrevisaoTempoID implements Serializable { // // private static final long serialVersionUID = -3202328496277683345L; // @Column // private String cidade; // @Column // private Date dia; // // public String getCidade() { // return cidade; // } // // public void setCidade(String cidade) { // this.cidade = cidade; // } // // public Date getDia() { // return dia; // } // // public void setDia(Date dia) { // this.dia = dia; // } // // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempoID) { // PrevisaoTempoID other = PrevisaoTempoID.class.cast(obj); // return new EqualsBuilder().append(cidade, other.cidade) // .append(dia, other.dia).isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(dia).append(cidade).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoMediaService.java // @Service // public class PrevisaoMediaService extends AbstractService{ // // @Autowired // private PrevisaoTempoMediaRepository repository; // // @Autowired // private PrevisaoTempoRepository previsaoTempoRepository; // // public void atualizar(PrevisaoTempoID id) { // PrevisaoTempo previsao = previsaoTempoRepository.findOne(id); // Double temperaturaMedia = 0d; // for (Double temperatura: previsao.getTemperaturas() ){ // temperaturaMedia+=temperatura; // } // temperaturaMedia/=previsao.getTemperaturas().size(); // // PrevisaoTempoMedia previsaoTempoMedia = new PrevisaoTempoMedia(); // previsaoTempoMedia.setId(id); // previsaoTempoMedia.setTemperatura(temperaturaMedia); // // repository.save(previsaoTempoMedia); // } // public PrevisaoTempoMedia findById(PrevisaoTempoID id) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // return repository.findOne(id); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoService.java // @Service // public class PrevisaoService extends AbstractService{ // // @Autowired // private PrevisaoTempoRepository repository; // // @Autowired // private PrevisaoMediaService mediaService; // // public void inserir(PrevisaoTempoID id, double temperatura) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // // UpdateBuilder<PrevisaoTempo> updateBuilder = repository.updateBuilder(id); // updateBuilder.addList("temperaturas", temperatura).value("temperatura", temperatura); // updateBuilder.executeAsync(); // // mediaService.atualizar(id); // } // // public PrevisaoTempo findById(PrevisaoTempoID id) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // return repository.findOne(id); // } // // // } // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/App.java import java.util.Date; import linguagil.cassandra.temperatura.model.PrevisaoTempoID; import linguagil.cassandra.temperatura.service.PrevisaoMediaService; import linguagil.cassandra.temperatura.service.PrevisaoService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; package linguagil.cassandra.temperatura; /** * Hello world! * */ public class App { public static void main( String[] args ) { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
PrevisaoService service = ctx.getBean(PrevisaoService.class);
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/App.java
// Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempoID.java // public class PrevisaoTempoID implements Serializable { // // private static final long serialVersionUID = -3202328496277683345L; // @Column // private String cidade; // @Column // private Date dia; // // public String getCidade() { // return cidade; // } // // public void setCidade(String cidade) { // this.cidade = cidade; // } // // public Date getDia() { // return dia; // } // // public void setDia(Date dia) { // this.dia = dia; // } // // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempoID) { // PrevisaoTempoID other = PrevisaoTempoID.class.cast(obj); // return new EqualsBuilder().append(cidade, other.cidade) // .append(dia, other.dia).isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(dia).append(cidade).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoMediaService.java // @Service // public class PrevisaoMediaService extends AbstractService{ // // @Autowired // private PrevisaoTempoMediaRepository repository; // // @Autowired // private PrevisaoTempoRepository previsaoTempoRepository; // // public void atualizar(PrevisaoTempoID id) { // PrevisaoTempo previsao = previsaoTempoRepository.findOne(id); // Double temperaturaMedia = 0d; // for (Double temperatura: previsao.getTemperaturas() ){ // temperaturaMedia+=temperatura; // } // temperaturaMedia/=previsao.getTemperaturas().size(); // // PrevisaoTempoMedia previsaoTempoMedia = new PrevisaoTempoMedia(); // previsaoTempoMedia.setId(id); // previsaoTempoMedia.setTemperatura(temperaturaMedia); // // repository.save(previsaoTempoMedia); // } // public PrevisaoTempoMedia findById(PrevisaoTempoID id) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // return repository.findOne(id); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoService.java // @Service // public class PrevisaoService extends AbstractService{ // // @Autowired // private PrevisaoTempoRepository repository; // // @Autowired // private PrevisaoMediaService mediaService; // // public void inserir(PrevisaoTempoID id, double temperatura) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // // UpdateBuilder<PrevisaoTempo> updateBuilder = repository.updateBuilder(id); // updateBuilder.addList("temperaturas", temperatura).value("temperatura", temperatura); // updateBuilder.executeAsync(); // // mediaService.atualizar(id); // } // // public PrevisaoTempo findById(PrevisaoTempoID id) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // return repository.findOne(id); // } // // // }
import java.util.Date; import linguagil.cassandra.temperatura.model.PrevisaoTempoID; import linguagil.cassandra.temperatura.service.PrevisaoMediaService; import linguagil.cassandra.temperatura.service.PrevisaoService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext;
package linguagil.cassandra.temperatura; /** * Hello world! * */ public class App { public static void main( String[] args ) { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml"); PrevisaoService service = ctx.getBean(PrevisaoService.class);
// Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempoID.java // public class PrevisaoTempoID implements Serializable { // // private static final long serialVersionUID = -3202328496277683345L; // @Column // private String cidade; // @Column // private Date dia; // // public String getCidade() { // return cidade; // } // // public void setCidade(String cidade) { // this.cidade = cidade; // } // // public Date getDia() { // return dia; // } // // public void setDia(Date dia) { // this.dia = dia; // } // // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempoID) { // PrevisaoTempoID other = PrevisaoTempoID.class.cast(obj); // return new EqualsBuilder().append(cidade, other.cidade) // .append(dia, other.dia).isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(dia).append(cidade).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoMediaService.java // @Service // public class PrevisaoMediaService extends AbstractService{ // // @Autowired // private PrevisaoTempoMediaRepository repository; // // @Autowired // private PrevisaoTempoRepository previsaoTempoRepository; // // public void atualizar(PrevisaoTempoID id) { // PrevisaoTempo previsao = previsaoTempoRepository.findOne(id); // Double temperaturaMedia = 0d; // for (Double temperatura: previsao.getTemperaturas() ){ // temperaturaMedia+=temperatura; // } // temperaturaMedia/=previsao.getTemperaturas().size(); // // PrevisaoTempoMedia previsaoTempoMedia = new PrevisaoTempoMedia(); // previsaoTempoMedia.setId(id); // previsaoTempoMedia.setTemperatura(temperaturaMedia); // // repository.save(previsaoTempoMedia); // } // public PrevisaoTempoMedia findById(PrevisaoTempoID id) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // return repository.findOne(id); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoService.java // @Service // public class PrevisaoService extends AbstractService{ // // @Autowired // private PrevisaoTempoRepository repository; // // @Autowired // private PrevisaoMediaService mediaService; // // public void inserir(PrevisaoTempoID id, double temperatura) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // // UpdateBuilder<PrevisaoTempo> updateBuilder = repository.updateBuilder(id); // updateBuilder.addList("temperaturas", temperatura).value("temperatura", temperatura); // updateBuilder.executeAsync(); // // mediaService.atualizar(id); // } // // public PrevisaoTempo findById(PrevisaoTempoID id) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // return repository.findOne(id); // } // // // } // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/App.java import java.util.Date; import linguagil.cassandra.temperatura.model.PrevisaoTempoID; import linguagil.cassandra.temperatura.service.PrevisaoMediaService; import linguagil.cassandra.temperatura.service.PrevisaoService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; package linguagil.cassandra.temperatura; /** * Hello world! * */ public class App { public static void main( String[] args ) { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml"); PrevisaoService service = ctx.getBean(PrevisaoService.class);
PrevisaoMediaService mediaService = ctx.getBean(PrevisaoMediaService.class);
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/App.java
// Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempoID.java // public class PrevisaoTempoID implements Serializable { // // private static final long serialVersionUID = -3202328496277683345L; // @Column // private String cidade; // @Column // private Date dia; // // public String getCidade() { // return cidade; // } // // public void setCidade(String cidade) { // this.cidade = cidade; // } // // public Date getDia() { // return dia; // } // // public void setDia(Date dia) { // this.dia = dia; // } // // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempoID) { // PrevisaoTempoID other = PrevisaoTempoID.class.cast(obj); // return new EqualsBuilder().append(cidade, other.cidade) // .append(dia, other.dia).isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(dia).append(cidade).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoMediaService.java // @Service // public class PrevisaoMediaService extends AbstractService{ // // @Autowired // private PrevisaoTempoMediaRepository repository; // // @Autowired // private PrevisaoTempoRepository previsaoTempoRepository; // // public void atualizar(PrevisaoTempoID id) { // PrevisaoTempo previsao = previsaoTempoRepository.findOne(id); // Double temperaturaMedia = 0d; // for (Double temperatura: previsao.getTemperaturas() ){ // temperaturaMedia+=temperatura; // } // temperaturaMedia/=previsao.getTemperaturas().size(); // // PrevisaoTempoMedia previsaoTempoMedia = new PrevisaoTempoMedia(); // previsaoTempoMedia.setId(id); // previsaoTempoMedia.setTemperatura(temperaturaMedia); // // repository.save(previsaoTempoMedia); // } // public PrevisaoTempoMedia findById(PrevisaoTempoID id) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // return repository.findOne(id); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoService.java // @Service // public class PrevisaoService extends AbstractService{ // // @Autowired // private PrevisaoTempoRepository repository; // // @Autowired // private PrevisaoMediaService mediaService; // // public void inserir(PrevisaoTempoID id, double temperatura) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // // UpdateBuilder<PrevisaoTempo> updateBuilder = repository.updateBuilder(id); // updateBuilder.addList("temperaturas", temperatura).value("temperatura", temperatura); // updateBuilder.executeAsync(); // // mediaService.atualizar(id); // } // // public PrevisaoTempo findById(PrevisaoTempoID id) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // return repository.findOne(id); // } // // // }
import java.util.Date; import linguagil.cassandra.temperatura.model.PrevisaoTempoID; import linguagil.cassandra.temperatura.service.PrevisaoMediaService; import linguagil.cassandra.temperatura.service.PrevisaoService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext;
package linguagil.cassandra.temperatura; /** * Hello world! * */ public class App { public static void main( String[] args ) { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml"); PrevisaoService service = ctx.getBean(PrevisaoService.class); PrevisaoMediaService mediaService = ctx.getBean(PrevisaoMediaService.class);
// Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempoID.java // public class PrevisaoTempoID implements Serializable { // // private static final long serialVersionUID = -3202328496277683345L; // @Column // private String cidade; // @Column // private Date dia; // // public String getCidade() { // return cidade; // } // // public void setCidade(String cidade) { // this.cidade = cidade; // } // // public Date getDia() { // return dia; // } // // public void setDia(Date dia) { // this.dia = dia; // } // // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempoID) { // PrevisaoTempoID other = PrevisaoTempoID.class.cast(obj); // return new EqualsBuilder().append(cidade, other.cidade) // .append(dia, other.dia).isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(dia).append(cidade).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoMediaService.java // @Service // public class PrevisaoMediaService extends AbstractService{ // // @Autowired // private PrevisaoTempoMediaRepository repository; // // @Autowired // private PrevisaoTempoRepository previsaoTempoRepository; // // public void atualizar(PrevisaoTempoID id) { // PrevisaoTempo previsao = previsaoTempoRepository.findOne(id); // Double temperaturaMedia = 0d; // for (Double temperatura: previsao.getTemperaturas() ){ // temperaturaMedia+=temperatura; // } // temperaturaMedia/=previsao.getTemperaturas().size(); // // PrevisaoTempoMedia previsaoTempoMedia = new PrevisaoTempoMedia(); // previsaoTempoMedia.setId(id); // previsaoTempoMedia.setTemperatura(temperaturaMedia); // // repository.save(previsaoTempoMedia); // } // public PrevisaoTempoMedia findById(PrevisaoTempoID id) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // return repository.findOne(id); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoService.java // @Service // public class PrevisaoService extends AbstractService{ // // @Autowired // private PrevisaoTempoRepository repository; // // @Autowired // private PrevisaoMediaService mediaService; // // public void inserir(PrevisaoTempoID id, double temperatura) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // // UpdateBuilder<PrevisaoTempo> updateBuilder = repository.updateBuilder(id); // updateBuilder.addList("temperaturas", temperatura).value("temperatura", temperatura); // updateBuilder.executeAsync(); // // mediaService.atualizar(id); // } // // public PrevisaoTempo findById(PrevisaoTempoID id) { // Date dia = limparDia(id.getDia()); // id.setDia(dia); // return repository.findOne(id); // } // // // } // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/App.java import java.util.Date; import linguagil.cassandra.temperatura.model.PrevisaoTempoID; import linguagil.cassandra.temperatura.service.PrevisaoMediaService; import linguagil.cassandra.temperatura.service.PrevisaoService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; package linguagil.cassandra.temperatura; /** * Hello world! * */ public class App { public static void main( String[] args ) { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml"); PrevisaoService service = ctx.getBean(PrevisaoService.class); PrevisaoMediaService mediaService = ctx.getBean(PrevisaoMediaService.class);
PrevisaoTempoID id = new PrevisaoTempoID();
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/App.java
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Musics.java // public class Musics { // // private List<Music> musics; // // public List<Music> getMusics() { // return musics; // } // // public void setMusics(List<Music> musics) { // this.musics = musics; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/service/MusicService.java // @Service // @Scope("prototype") // public class MusicService { // // @Autowired // private MusicRepository repository; // // @Autowired // private MusicSearch musicaSearch; // // // public void save(Music musica){ // repository.save(musica); // try { // musicaSearch.index(musica); // } catch (IOException e) { // e.printStackTrace(); // } // } // // // public List<Music> findMusicByLyric(String lyric) { // try { // List<String> ids = musicaSearch.findMusicByLyric(lyric); // return (List<Music>) repository.findAll(ids); // } catch (ParseException | IOException e) { // Logger.getLogger(MusicService.class.getName()).severe("Error on findMusicByLyric " + e.getMessage()); // } // return Collections.emptyList(); // } // // public List<Music> findMusicByAuthor(String author) { // try { // List<String> ids = musicaSearch.findMusicByAuthor(author); // return (List<Music>) repository.findAll(ids); // } catch (ParseException | IOException e) { // Logger.getLogger(MusicService.class.getName()).severe("Error on findMusicByAuthor " + e.getMessage()); // } // return Collections.emptyList(); // } // // // }
import java.io.IOException; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.model.Music; import org.javabahia.cassandra.spring.model.Musics; import org.javabahia.cassandra.spring.service.MusicService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext;
package org.javabahia.cassandra.spring; public class App { public static void main(String[] args) throws IOException, ParseException { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Musics.java // public class Musics { // // private List<Music> musics; // // public List<Music> getMusics() { // return musics; // } // // public void setMusics(List<Music> musics) { // this.musics = musics; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/service/MusicService.java // @Service // @Scope("prototype") // public class MusicService { // // @Autowired // private MusicRepository repository; // // @Autowired // private MusicSearch musicaSearch; // // // public void save(Music musica){ // repository.save(musica); // try { // musicaSearch.index(musica); // } catch (IOException e) { // e.printStackTrace(); // } // } // // // public List<Music> findMusicByLyric(String lyric) { // try { // List<String> ids = musicaSearch.findMusicByLyric(lyric); // return (List<Music>) repository.findAll(ids); // } catch (ParseException | IOException e) { // Logger.getLogger(MusicService.class.getName()).severe("Error on findMusicByLyric " + e.getMessage()); // } // return Collections.emptyList(); // } // // public List<Music> findMusicByAuthor(String author) { // try { // List<String> ids = musicaSearch.findMusicByAuthor(author); // return (List<Music>) repository.findAll(ids); // } catch (ParseException | IOException e) { // Logger.getLogger(MusicService.class.getName()).severe("Error on findMusicByAuthor " + e.getMessage()); // } // return Collections.emptyList(); // } // // // } // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/App.java import java.io.IOException; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.model.Music; import org.javabahia.cassandra.spring.model.Musics; import org.javabahia.cassandra.spring.service.MusicService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; package org.javabahia.cassandra.spring; public class App { public static void main(String[] args) throws IOException, ParseException { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
Musics musicas = ctx.getBean(Musics.class);
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/App.java
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Musics.java // public class Musics { // // private List<Music> musics; // // public List<Music> getMusics() { // return musics; // } // // public void setMusics(List<Music> musics) { // this.musics = musics; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/service/MusicService.java // @Service // @Scope("prototype") // public class MusicService { // // @Autowired // private MusicRepository repository; // // @Autowired // private MusicSearch musicaSearch; // // // public void save(Music musica){ // repository.save(musica); // try { // musicaSearch.index(musica); // } catch (IOException e) { // e.printStackTrace(); // } // } // // // public List<Music> findMusicByLyric(String lyric) { // try { // List<String> ids = musicaSearch.findMusicByLyric(lyric); // return (List<Music>) repository.findAll(ids); // } catch (ParseException | IOException e) { // Logger.getLogger(MusicService.class.getName()).severe("Error on findMusicByLyric " + e.getMessage()); // } // return Collections.emptyList(); // } // // public List<Music> findMusicByAuthor(String author) { // try { // List<String> ids = musicaSearch.findMusicByAuthor(author); // return (List<Music>) repository.findAll(ids); // } catch (ParseException | IOException e) { // Logger.getLogger(MusicService.class.getName()).severe("Error on findMusicByAuthor " + e.getMessage()); // } // return Collections.emptyList(); // } // // // }
import java.io.IOException; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.model.Music; import org.javabahia.cassandra.spring.model.Musics; import org.javabahia.cassandra.spring.service.MusicService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext;
package org.javabahia.cassandra.spring; public class App { public static void main(String[] args) throws IOException, ParseException { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml"); Musics musicas = ctx.getBean(Musics.class);
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Musics.java // public class Musics { // // private List<Music> musics; // // public List<Music> getMusics() { // return musics; // } // // public void setMusics(List<Music> musics) { // this.musics = musics; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/service/MusicService.java // @Service // @Scope("prototype") // public class MusicService { // // @Autowired // private MusicRepository repository; // // @Autowired // private MusicSearch musicaSearch; // // // public void save(Music musica){ // repository.save(musica); // try { // musicaSearch.index(musica); // } catch (IOException e) { // e.printStackTrace(); // } // } // // // public List<Music> findMusicByLyric(String lyric) { // try { // List<String> ids = musicaSearch.findMusicByLyric(lyric); // return (List<Music>) repository.findAll(ids); // } catch (ParseException | IOException e) { // Logger.getLogger(MusicService.class.getName()).severe("Error on findMusicByLyric " + e.getMessage()); // } // return Collections.emptyList(); // } // // public List<Music> findMusicByAuthor(String author) { // try { // List<String> ids = musicaSearch.findMusicByAuthor(author); // return (List<Music>) repository.findAll(ids); // } catch (ParseException | IOException e) { // Logger.getLogger(MusicService.class.getName()).severe("Error on findMusicByAuthor " + e.getMessage()); // } // return Collections.emptyList(); // } // // // } // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/App.java import java.io.IOException; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.model.Music; import org.javabahia.cassandra.spring.model.Musics; import org.javabahia.cassandra.spring.service.MusicService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; package org.javabahia.cassandra.spring; public class App { public static void main(String[] args) throws IOException, ParseException { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml"); Musics musicas = ctx.getBean(Musics.class);
MusicService service = ctx.getBean(MusicService.class);
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/App.java
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Musics.java // public class Musics { // // private List<Music> musics; // // public List<Music> getMusics() { // return musics; // } // // public void setMusics(List<Music> musics) { // this.musics = musics; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/service/MusicService.java // @Service // @Scope("prototype") // public class MusicService { // // @Autowired // private MusicRepository repository; // // @Autowired // private MusicSearch musicaSearch; // // // public void save(Music musica){ // repository.save(musica); // try { // musicaSearch.index(musica); // } catch (IOException e) { // e.printStackTrace(); // } // } // // // public List<Music> findMusicByLyric(String lyric) { // try { // List<String> ids = musicaSearch.findMusicByLyric(lyric); // return (List<Music>) repository.findAll(ids); // } catch (ParseException | IOException e) { // Logger.getLogger(MusicService.class.getName()).severe("Error on findMusicByLyric " + e.getMessage()); // } // return Collections.emptyList(); // } // // public List<Music> findMusicByAuthor(String author) { // try { // List<String> ids = musicaSearch.findMusicByAuthor(author); // return (List<Music>) repository.findAll(ids); // } catch (ParseException | IOException e) { // Logger.getLogger(MusicService.class.getName()).severe("Error on findMusicByAuthor " + e.getMessage()); // } // return Collections.emptyList(); // } // // // }
import java.io.IOException; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.model.Music; import org.javabahia.cassandra.spring.model.Musics; import org.javabahia.cassandra.spring.service.MusicService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext;
package org.javabahia.cassandra.spring; public class App { public static void main(String[] args) throws IOException, ParseException { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml"); Musics musicas = ctx.getBean(Musics.class); MusicService service = ctx.getBean(MusicService.class);
// Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Music.java // @Entity // public class Music implements Serializable{ // // private static final long serialVersionUID = -8245568483951712497L; // // @Id // private String name; // @Column // private String author; // @Column // private String lyric; // // public String getName() { // return name; // } // // public void setName(String nome) { // this.name = nome; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String autor) { // this.author = autor; // } // // public String getLyric() { // return lyric; // } // // public void setLyric(String lyric) { // this.lyric = lyric; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/model/Musics.java // public class Musics { // // private List<Music> musics; // // public List<Music> getMusics() { // return musics; // } // // public void setMusics(List<Music> musics) { // this.musics = musics; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/service/MusicService.java // @Service // @Scope("prototype") // public class MusicService { // // @Autowired // private MusicRepository repository; // // @Autowired // private MusicSearch musicaSearch; // // // public void save(Music musica){ // repository.save(musica); // try { // musicaSearch.index(musica); // } catch (IOException e) { // e.printStackTrace(); // } // } // // // public List<Music> findMusicByLyric(String lyric) { // try { // List<String> ids = musicaSearch.findMusicByLyric(lyric); // return (List<Music>) repository.findAll(ids); // } catch (ParseException | IOException e) { // Logger.getLogger(MusicService.class.getName()).severe("Error on findMusicByLyric " + e.getMessage()); // } // return Collections.emptyList(); // } // // public List<Music> findMusicByAuthor(String author) { // try { // List<String> ids = musicaSearch.findMusicByAuthor(author); // return (List<Music>) repository.findAll(ids); // } catch (ParseException | IOException e) { // Logger.getLogger(MusicService.class.getName()).severe("Error on findMusicByAuthor " + e.getMessage()); // } // return Collections.emptyList(); // } // // // } // Path: cassandra-spring/cassandra-spring-lucene/src/main/java/org/javabahia/cassandra/spring/App.java import java.io.IOException; import org.apache.lucene.queryparser.classic.ParseException; import org.javabahia.cassandra.spring.model.Music; import org.javabahia.cassandra.spring.model.Musics; import org.javabahia.cassandra.spring.service.MusicService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; package org.javabahia.cassandra.spring; public class App { public static void main(String[] args) throws IOException, ParseException { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml"); Musics musicas = ctx.getBean(Musics.class); MusicService service = ctx.getBean(MusicService.class);
for (Music musica: musicas.getMusics()) {
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoService.java
// Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempo.java // @Entity(name = "previsaotempo") // public class PrevisaoTempo { // // @EmbeddedId // private PrevisaoTempoID id; // // @Column(name = "temperatura") // private Double temperatura; // // @ElementCollection // @Column(name = "temperaturas") // private List<Double> temperaturas; // // public PrevisaoTempoID getId() { // return id; // } // // public void setId(PrevisaoTempoID id) { // this.id = id; // } // // public Double getTemperatura() { // return temperatura; // } // // public void setTemperatura(Double temperatura) { // this.temperatura = temperatura; // } // // public List<Double> getTemperaturas() { // return temperaturas; // } // // public void setTemperaturas(List<Double> temperaturas) { // this.temperaturas = temperaturas; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempo) { // PrevisaoTempo other = PrevisaoTempo.class.cast(obj); // return new EqualsBuilder().append(id, other.id) // .isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(id).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempoID.java // public class PrevisaoTempoID implements Serializable { // // private static final long serialVersionUID = -3202328496277683345L; // @Column // private String cidade; // @Column // private Date dia; // // public String getCidade() { // return cidade; // } // // public void setCidade(String cidade) { // this.cidade = cidade; // } // // public Date getDia() { // return dia; // } // // public void setDia(Date dia) { // this.dia = dia; // } // // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempoID) { // PrevisaoTempoID other = PrevisaoTempoID.class.cast(obj); // return new EqualsBuilder().append(cidade, other.cidade) // .append(dia, other.dia).isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(dia).append(cidade).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/repository/PrevisaoTempoRepository.java // @Repository("previsaoRepository") // public class PrevisaoTempoRepository extends CassandraRepository<PrevisaoTempo, PrevisaoTempoID>{ // // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // public UpdateBuilder<PrevisaoTempo> updateBuilder(PrevisaoTempoID id) { // return cassandraTemplate.updateBuilder(PrevisaoTempo.class, id); // } // // // }
import java.util.Date; import linguagil.cassandra.temperatura.model.PrevisaoTempo; import linguagil.cassandra.temperatura.model.PrevisaoTempoID; import linguagil.cassandra.temperatura.repository.PrevisaoTempoRepository; import org.easycassandra.persistence.cassandra.UpdateBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
package linguagil.cassandra.temperatura.service; @Service public class PrevisaoService extends AbstractService{ @Autowired
// Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempo.java // @Entity(name = "previsaotempo") // public class PrevisaoTempo { // // @EmbeddedId // private PrevisaoTempoID id; // // @Column(name = "temperatura") // private Double temperatura; // // @ElementCollection // @Column(name = "temperaturas") // private List<Double> temperaturas; // // public PrevisaoTempoID getId() { // return id; // } // // public void setId(PrevisaoTempoID id) { // this.id = id; // } // // public Double getTemperatura() { // return temperatura; // } // // public void setTemperatura(Double temperatura) { // this.temperatura = temperatura; // } // // public List<Double> getTemperaturas() { // return temperaturas; // } // // public void setTemperaturas(List<Double> temperaturas) { // this.temperaturas = temperaturas; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempo) { // PrevisaoTempo other = PrevisaoTempo.class.cast(obj); // return new EqualsBuilder().append(id, other.id) // .isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(id).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempoID.java // public class PrevisaoTempoID implements Serializable { // // private static final long serialVersionUID = -3202328496277683345L; // @Column // private String cidade; // @Column // private Date dia; // // public String getCidade() { // return cidade; // } // // public void setCidade(String cidade) { // this.cidade = cidade; // } // // public Date getDia() { // return dia; // } // // public void setDia(Date dia) { // this.dia = dia; // } // // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempoID) { // PrevisaoTempoID other = PrevisaoTempoID.class.cast(obj); // return new EqualsBuilder().append(cidade, other.cidade) // .append(dia, other.dia).isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(dia).append(cidade).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/repository/PrevisaoTempoRepository.java // @Repository("previsaoRepository") // public class PrevisaoTempoRepository extends CassandraRepository<PrevisaoTempo, PrevisaoTempoID>{ // // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // public UpdateBuilder<PrevisaoTempo> updateBuilder(PrevisaoTempoID id) { // return cassandraTemplate.updateBuilder(PrevisaoTempo.class, id); // } // // // } // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoService.java import java.util.Date; import linguagil.cassandra.temperatura.model.PrevisaoTempo; import linguagil.cassandra.temperatura.model.PrevisaoTempoID; import linguagil.cassandra.temperatura.repository.PrevisaoTempoRepository; import org.easycassandra.persistence.cassandra.UpdateBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; package linguagil.cassandra.temperatura.service; @Service public class PrevisaoService extends AbstractService{ @Autowired
private PrevisaoTempoRepository repository;
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoService.java
// Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempo.java // @Entity(name = "previsaotempo") // public class PrevisaoTempo { // // @EmbeddedId // private PrevisaoTempoID id; // // @Column(name = "temperatura") // private Double temperatura; // // @ElementCollection // @Column(name = "temperaturas") // private List<Double> temperaturas; // // public PrevisaoTempoID getId() { // return id; // } // // public void setId(PrevisaoTempoID id) { // this.id = id; // } // // public Double getTemperatura() { // return temperatura; // } // // public void setTemperatura(Double temperatura) { // this.temperatura = temperatura; // } // // public List<Double> getTemperaturas() { // return temperaturas; // } // // public void setTemperaturas(List<Double> temperaturas) { // this.temperaturas = temperaturas; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempo) { // PrevisaoTempo other = PrevisaoTempo.class.cast(obj); // return new EqualsBuilder().append(id, other.id) // .isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(id).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempoID.java // public class PrevisaoTempoID implements Serializable { // // private static final long serialVersionUID = -3202328496277683345L; // @Column // private String cidade; // @Column // private Date dia; // // public String getCidade() { // return cidade; // } // // public void setCidade(String cidade) { // this.cidade = cidade; // } // // public Date getDia() { // return dia; // } // // public void setDia(Date dia) { // this.dia = dia; // } // // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempoID) { // PrevisaoTempoID other = PrevisaoTempoID.class.cast(obj); // return new EqualsBuilder().append(cidade, other.cidade) // .append(dia, other.dia).isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(dia).append(cidade).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/repository/PrevisaoTempoRepository.java // @Repository("previsaoRepository") // public class PrevisaoTempoRepository extends CassandraRepository<PrevisaoTempo, PrevisaoTempoID>{ // // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // public UpdateBuilder<PrevisaoTempo> updateBuilder(PrevisaoTempoID id) { // return cassandraTemplate.updateBuilder(PrevisaoTempo.class, id); // } // // // }
import java.util.Date; import linguagil.cassandra.temperatura.model.PrevisaoTempo; import linguagil.cassandra.temperatura.model.PrevisaoTempoID; import linguagil.cassandra.temperatura.repository.PrevisaoTempoRepository; import org.easycassandra.persistence.cassandra.UpdateBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
package linguagil.cassandra.temperatura.service; @Service public class PrevisaoService extends AbstractService{ @Autowired private PrevisaoTempoRepository repository; @Autowired private PrevisaoMediaService mediaService;
// Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempo.java // @Entity(name = "previsaotempo") // public class PrevisaoTempo { // // @EmbeddedId // private PrevisaoTempoID id; // // @Column(name = "temperatura") // private Double temperatura; // // @ElementCollection // @Column(name = "temperaturas") // private List<Double> temperaturas; // // public PrevisaoTempoID getId() { // return id; // } // // public void setId(PrevisaoTempoID id) { // this.id = id; // } // // public Double getTemperatura() { // return temperatura; // } // // public void setTemperatura(Double temperatura) { // this.temperatura = temperatura; // } // // public List<Double> getTemperaturas() { // return temperaturas; // } // // public void setTemperaturas(List<Double> temperaturas) { // this.temperaturas = temperaturas; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempo) { // PrevisaoTempo other = PrevisaoTempo.class.cast(obj); // return new EqualsBuilder().append(id, other.id) // .isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(id).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempoID.java // public class PrevisaoTempoID implements Serializable { // // private static final long serialVersionUID = -3202328496277683345L; // @Column // private String cidade; // @Column // private Date dia; // // public String getCidade() { // return cidade; // } // // public void setCidade(String cidade) { // this.cidade = cidade; // } // // public Date getDia() { // return dia; // } // // public void setDia(Date dia) { // this.dia = dia; // } // // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempoID) { // PrevisaoTempoID other = PrevisaoTempoID.class.cast(obj); // return new EqualsBuilder().append(cidade, other.cidade) // .append(dia, other.dia).isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(dia).append(cidade).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/repository/PrevisaoTempoRepository.java // @Repository("previsaoRepository") // public class PrevisaoTempoRepository extends CassandraRepository<PrevisaoTempo, PrevisaoTempoID>{ // // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // public UpdateBuilder<PrevisaoTempo> updateBuilder(PrevisaoTempoID id) { // return cassandraTemplate.updateBuilder(PrevisaoTempo.class, id); // } // // // } // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoService.java import java.util.Date; import linguagil.cassandra.temperatura.model.PrevisaoTempo; import linguagil.cassandra.temperatura.model.PrevisaoTempoID; import linguagil.cassandra.temperatura.repository.PrevisaoTempoRepository; import org.easycassandra.persistence.cassandra.UpdateBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; package linguagil.cassandra.temperatura.service; @Service public class PrevisaoService extends AbstractService{ @Autowired private PrevisaoTempoRepository repository; @Autowired private PrevisaoMediaService mediaService;
public void inserir(PrevisaoTempoID id, double temperatura) {
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoService.java
// Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempo.java // @Entity(name = "previsaotempo") // public class PrevisaoTempo { // // @EmbeddedId // private PrevisaoTempoID id; // // @Column(name = "temperatura") // private Double temperatura; // // @ElementCollection // @Column(name = "temperaturas") // private List<Double> temperaturas; // // public PrevisaoTempoID getId() { // return id; // } // // public void setId(PrevisaoTempoID id) { // this.id = id; // } // // public Double getTemperatura() { // return temperatura; // } // // public void setTemperatura(Double temperatura) { // this.temperatura = temperatura; // } // // public List<Double> getTemperaturas() { // return temperaturas; // } // // public void setTemperaturas(List<Double> temperaturas) { // this.temperaturas = temperaturas; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempo) { // PrevisaoTempo other = PrevisaoTempo.class.cast(obj); // return new EqualsBuilder().append(id, other.id) // .isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(id).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempoID.java // public class PrevisaoTempoID implements Serializable { // // private static final long serialVersionUID = -3202328496277683345L; // @Column // private String cidade; // @Column // private Date dia; // // public String getCidade() { // return cidade; // } // // public void setCidade(String cidade) { // this.cidade = cidade; // } // // public Date getDia() { // return dia; // } // // public void setDia(Date dia) { // this.dia = dia; // } // // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempoID) { // PrevisaoTempoID other = PrevisaoTempoID.class.cast(obj); // return new EqualsBuilder().append(cidade, other.cidade) // .append(dia, other.dia).isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(dia).append(cidade).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/repository/PrevisaoTempoRepository.java // @Repository("previsaoRepository") // public class PrevisaoTempoRepository extends CassandraRepository<PrevisaoTempo, PrevisaoTempoID>{ // // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // public UpdateBuilder<PrevisaoTempo> updateBuilder(PrevisaoTempoID id) { // return cassandraTemplate.updateBuilder(PrevisaoTempo.class, id); // } // // // }
import java.util.Date; import linguagil.cassandra.temperatura.model.PrevisaoTempo; import linguagil.cassandra.temperatura.model.PrevisaoTempoID; import linguagil.cassandra.temperatura.repository.PrevisaoTempoRepository; import org.easycassandra.persistence.cassandra.UpdateBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
package linguagil.cassandra.temperatura.service; @Service public class PrevisaoService extends AbstractService{ @Autowired private PrevisaoTempoRepository repository; @Autowired private PrevisaoMediaService mediaService; public void inserir(PrevisaoTempoID id, double temperatura) { Date dia = limparDia(id.getDia()); id.setDia(dia);
// Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempo.java // @Entity(name = "previsaotempo") // public class PrevisaoTempo { // // @EmbeddedId // private PrevisaoTempoID id; // // @Column(name = "temperatura") // private Double temperatura; // // @ElementCollection // @Column(name = "temperaturas") // private List<Double> temperaturas; // // public PrevisaoTempoID getId() { // return id; // } // // public void setId(PrevisaoTempoID id) { // this.id = id; // } // // public Double getTemperatura() { // return temperatura; // } // // public void setTemperatura(Double temperatura) { // this.temperatura = temperatura; // } // // public List<Double> getTemperaturas() { // return temperaturas; // } // // public void setTemperaturas(List<Double> temperaturas) { // this.temperaturas = temperaturas; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempo) { // PrevisaoTempo other = PrevisaoTempo.class.cast(obj); // return new EqualsBuilder().append(id, other.id) // .isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(id).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/model/PrevisaoTempoID.java // public class PrevisaoTempoID implements Serializable { // // private static final long serialVersionUID = -3202328496277683345L; // @Column // private String cidade; // @Column // private Date dia; // // public String getCidade() { // return cidade; // } // // public void setCidade(String cidade) { // this.cidade = cidade; // } // // public Date getDia() { // return dia; // } // // public void setDia(Date dia) { // this.dia = dia; // } // // // @Override // public boolean equals(Object obj) { // if (obj instanceof PrevisaoTempoID) { // PrevisaoTempoID other = PrevisaoTempoID.class.cast(obj); // return new EqualsBuilder().append(cidade, other.cidade) // .append(dia, other.dia).isEquals(); // } // return false; // } // @Override // public int hashCode() { // // return new HashCodeBuilder().append(dia).append(cidade).toHashCode(); // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // } // // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/repository/PrevisaoTempoRepository.java // @Repository("previsaoRepository") // public class PrevisaoTempoRepository extends CassandraRepository<PrevisaoTempo, PrevisaoTempoID>{ // // // // @Value(value="#{cassandraFactory.template}") // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // public UpdateBuilder<PrevisaoTempo> updateBuilder(PrevisaoTempoID id) { // return cassandraTemplate.updateBuilder(PrevisaoTempo.class, id); // } // // // } // Path: cassandra-spring/cassandra-spring-lucene/src/java/linguagil/cassandra/temperatura/service/PrevisaoService.java import java.util.Date; import linguagil.cassandra.temperatura.model.PrevisaoTempo; import linguagil.cassandra.temperatura.model.PrevisaoTempoID; import linguagil.cassandra.temperatura.repository.PrevisaoTempoRepository; import org.easycassandra.persistence.cassandra.UpdateBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; package linguagil.cassandra.temperatura.service; @Service public class PrevisaoService extends AbstractService{ @Autowired private PrevisaoTempoRepository repository; @Autowired private PrevisaoMediaService mediaService; public void inserir(PrevisaoTempoID id, double temperatura) { Date dia = limparDia(id.getDia()); id.setDia(dia);
UpdateBuilder<PrevisaoTempo> updateBuilder = repository.updateBuilder(id);
otaviojava/Easy-Cassandra-samples
cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/resource/CostResource.java
// Path: cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/api/CostOperations.java // public interface CostOperations { // // boolean save(CostUnit bean); // // boolean update(CostUnit bean); // // boolean delete(String cityName); // // List<CostUnit> list(); // // CostUnit retrieve(String city); // // // } // // Path: cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/api/CostUnit.java // @XmlRootElement // @Entity // public class CostUnit implements Serializable{ // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id // private String city; // // @Column // private String address; // // @Column // private String neighborhood; // // @Column // private String state; // // @Column // private Double value; // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getAddress() { // return address; // } // // public void setAddress(String address) { // this.address = address; // } // // public String getNeighborhood() { // return neighborhood; // } // // public void setNeighborhood(String neighborhood) { // this.neighborhood = neighborhood; // } // // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // // public Double getValue() { // return value; // } // // public void setValue(Double value) { // this.value = value; // } // // // @Override // public String toString() { // // return neighborhood+city +" - "+state+" R$ "+value; // } // // public static CostUnit valueof(String[] strings) { // CostUnit controle = new CostUnit(); // controle.setCity(strings[0]); // controle.setAddress(strings[1]); // controle.setNeighborhood(strings[2]); // controle.setState(strings[3]); // controle.setValue(new Double(strings[4])); // // return controle; // } // }
import java.util.List; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.easycassandra.persistence.cassandra.Persistence; import org.easycassandra.samples.javaee.rest.api.CostOperations; import org.easycassandra.samples.javaee.rest.api.CostUnit;
package org.easycassandra.samples.javaee.rest.resource; /** * * @author otaviojava */ @Path("/cost") @RequestScoped
// Path: cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/api/CostOperations.java // public interface CostOperations { // // boolean save(CostUnit bean); // // boolean update(CostUnit bean); // // boolean delete(String cityName); // // List<CostUnit> list(); // // CostUnit retrieve(String city); // // // } // // Path: cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/api/CostUnit.java // @XmlRootElement // @Entity // public class CostUnit implements Serializable{ // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id // private String city; // // @Column // private String address; // // @Column // private String neighborhood; // // @Column // private String state; // // @Column // private Double value; // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getAddress() { // return address; // } // // public void setAddress(String address) { // this.address = address; // } // // public String getNeighborhood() { // return neighborhood; // } // // public void setNeighborhood(String neighborhood) { // this.neighborhood = neighborhood; // } // // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // // public Double getValue() { // return value; // } // // public void setValue(Double value) { // this.value = value; // } // // // @Override // public String toString() { // // return neighborhood+city +" - "+state+" R$ "+value; // } // // public static CostUnit valueof(String[] strings) { // CostUnit controle = new CostUnit(); // controle.setCity(strings[0]); // controle.setAddress(strings[1]); // controle.setNeighborhood(strings[2]); // controle.setState(strings[3]); // controle.setValue(new Double(strings[4])); // // return controle; // } // } // Path: cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/resource/CostResource.java import java.util.List; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.easycassandra.persistence.cassandra.Persistence; import org.easycassandra.samples.javaee.rest.api.CostOperations; import org.easycassandra.samples.javaee.rest.api.CostUnit; package org.easycassandra.samples.javaee.rest.resource; /** * * @author otaviojava */ @Path("/cost") @RequestScoped
public class CostResource implements CostOperations{
otaviojava/Easy-Cassandra-samples
cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/resource/CostResource.java
// Path: cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/api/CostOperations.java // public interface CostOperations { // // boolean save(CostUnit bean); // // boolean update(CostUnit bean); // // boolean delete(String cityName); // // List<CostUnit> list(); // // CostUnit retrieve(String city); // // // } // // Path: cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/api/CostUnit.java // @XmlRootElement // @Entity // public class CostUnit implements Serializable{ // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id // private String city; // // @Column // private String address; // // @Column // private String neighborhood; // // @Column // private String state; // // @Column // private Double value; // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getAddress() { // return address; // } // // public void setAddress(String address) { // this.address = address; // } // // public String getNeighborhood() { // return neighborhood; // } // // public void setNeighborhood(String neighborhood) { // this.neighborhood = neighborhood; // } // // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // // public Double getValue() { // return value; // } // // public void setValue(Double value) { // this.value = value; // } // // // @Override // public String toString() { // // return neighborhood+city +" - "+state+" R$ "+value; // } // // public static CostUnit valueof(String[] strings) { // CostUnit controle = new CostUnit(); // controle.setCity(strings[0]); // controle.setAddress(strings[1]); // controle.setNeighborhood(strings[2]); // controle.setState(strings[3]); // controle.setValue(new Double(strings[4])); // // return controle; // } // }
import java.util.List; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.easycassandra.persistence.cassandra.Persistence; import org.easycassandra.samples.javaee.rest.api.CostOperations; import org.easycassandra.samples.javaee.rest.api.CostUnit;
package org.easycassandra.samples.javaee.rest.resource; /** * * @author otaviojava */ @Path("/cost") @RequestScoped public class CostResource implements CostOperations{ @Inject private Persistence persistence; @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
// Path: cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/api/CostOperations.java // public interface CostOperations { // // boolean save(CostUnit bean); // // boolean update(CostUnit bean); // // boolean delete(String cityName); // // List<CostUnit> list(); // // CostUnit retrieve(String city); // // // } // // Path: cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/api/CostUnit.java // @XmlRootElement // @Entity // public class CostUnit implements Serializable{ // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id // private String city; // // @Column // private String address; // // @Column // private String neighborhood; // // @Column // private String state; // // @Column // private Double value; // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public String getAddress() { // return address; // } // // public void setAddress(String address) { // this.address = address; // } // // public String getNeighborhood() { // return neighborhood; // } // // public void setNeighborhood(String neighborhood) { // this.neighborhood = neighborhood; // } // // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // // public Double getValue() { // return value; // } // // public void setValue(Double value) { // this.value = value; // } // // // @Override // public String toString() { // // return neighborhood+city +" - "+state+" R$ "+value; // } // // public static CostUnit valueof(String[] strings) { // CostUnit controle = new CostUnit(); // controle.setCity(strings[0]); // controle.setAddress(strings[1]); // controle.setNeighborhood(strings[2]); // controle.setState(strings[3]); // controle.setValue(new Double(strings[4])); // // return controle; // } // } // Path: cassandra-javaee-rest-hello-world/src/main/java/org/easycassandra/samples/javaee/rest/resource/CostResource.java import java.util.List; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.easycassandra.persistence.cassandra.Persistence; import org.easycassandra.samples.javaee.rest.api.CostOperations; import org.easycassandra.samples.javaee.rest.api.CostUnit; package org.easycassandra.samples.javaee.rest.resource; /** * * @author otaviojava */ @Path("/cost") @RequestScoped public class CostResource implements CostOperations{ @Inject private Persistence persistence; @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public boolean save(CostUnit bean) {
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-hello-world/src/main/java/org/javabahia/cassandra/spring/App.java
// Path: cassandra-spring/cassandra-spring-hello-world/src/main/java/org/javabahia/cassandra/spring/entity/Person.java // @Entity(name = "person") // public class Person implements Serializable { // // private static final long serialVersionUID = 3L; // // @Id // private UUID id; // // @Index // @Column(name = "name") // private String name; // // @Column(name = "born") // private Integer year; // // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public Integer getYear() { // return year; // } // // public void setYear(Integer year) { // this.year = year; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((id == null) ? 0 : id.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Person other = (Person) obj; // if (id == null) { // if (other.id != null) // return false; // } else if (!id.equals(other.id)) // return false; // return true; // } // // // // } // // Path: cassandra-spring/cassandra-spring-hello-world/src/main/java/org/javabahia/cassandra/spring/repository/PersonRepository.java // @Repository("personRepository") // public class PersonRepository extends CassandraRepository<Person, UUID>{ // // // @Autowired // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // }
import java.util.UUID; import org.javabahia.cassandra.spring.entity.Person; import org.javabahia.cassandra.spring.repository.PersonRepository; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext;
package org.javabahia.cassandra.spring; /** * Hello world! * */ public class App { public static void main( String[] args ) { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
// Path: cassandra-spring/cassandra-spring-hello-world/src/main/java/org/javabahia/cassandra/spring/entity/Person.java // @Entity(name = "person") // public class Person implements Serializable { // // private static final long serialVersionUID = 3L; // // @Id // private UUID id; // // @Index // @Column(name = "name") // private String name; // // @Column(name = "born") // private Integer year; // // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public Integer getYear() { // return year; // } // // public void setYear(Integer year) { // this.year = year; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((id == null) ? 0 : id.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Person other = (Person) obj; // if (id == null) { // if (other.id != null) // return false; // } else if (!id.equals(other.id)) // return false; // return true; // } // // // // } // // Path: cassandra-spring/cassandra-spring-hello-world/src/main/java/org/javabahia/cassandra/spring/repository/PersonRepository.java // @Repository("personRepository") // public class PersonRepository extends CassandraRepository<Person, UUID>{ // // // @Autowired // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // } // Path: cassandra-spring/cassandra-spring-hello-world/src/main/java/org/javabahia/cassandra/spring/App.java import java.util.UUID; import org.javabahia.cassandra.spring.entity.Person; import org.javabahia.cassandra.spring.repository.PersonRepository; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; package org.javabahia.cassandra.spring; /** * Hello world! * */ public class App { public static void main( String[] args ) { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
PersonRepository personService=ctx.getBean(PersonRepository.class);
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-hello-world/src/main/java/org/javabahia/cassandra/spring/App.java
// Path: cassandra-spring/cassandra-spring-hello-world/src/main/java/org/javabahia/cassandra/spring/entity/Person.java // @Entity(name = "person") // public class Person implements Serializable { // // private static final long serialVersionUID = 3L; // // @Id // private UUID id; // // @Index // @Column(name = "name") // private String name; // // @Column(name = "born") // private Integer year; // // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public Integer getYear() { // return year; // } // // public void setYear(Integer year) { // this.year = year; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((id == null) ? 0 : id.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Person other = (Person) obj; // if (id == null) { // if (other.id != null) // return false; // } else if (!id.equals(other.id)) // return false; // return true; // } // // // // } // // Path: cassandra-spring/cassandra-spring-hello-world/src/main/java/org/javabahia/cassandra/spring/repository/PersonRepository.java // @Repository("personRepository") // public class PersonRepository extends CassandraRepository<Person, UUID>{ // // // @Autowired // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // }
import java.util.UUID; import org.javabahia.cassandra.spring.entity.Person; import org.javabahia.cassandra.spring.repository.PersonRepository; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext;
package org.javabahia.cassandra.spring; /** * Hello world! * */ public class App { public static void main( String[] args ) { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml"); PersonRepository personService=ctx.getBean(PersonRepository.class); UUID uuid=UUID.randomUUID();
// Path: cassandra-spring/cassandra-spring-hello-world/src/main/java/org/javabahia/cassandra/spring/entity/Person.java // @Entity(name = "person") // public class Person implements Serializable { // // private static final long serialVersionUID = 3L; // // @Id // private UUID id; // // @Index // @Column(name = "name") // private String name; // // @Column(name = "born") // private Integer year; // // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public Integer getYear() { // return year; // } // // public void setYear(Integer year) { // this.year = year; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((id == null) ? 0 : id.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Person other = (Person) obj; // if (id == null) { // if (other.id != null) // return false; // } else if (!id.equals(other.id)) // return false; // return true; // } // // // // } // // Path: cassandra-spring/cassandra-spring-hello-world/src/main/java/org/javabahia/cassandra/spring/repository/PersonRepository.java // @Repository("personRepository") // public class PersonRepository extends CassandraRepository<Person, UUID>{ // // // @Autowired // private CassandraTemplate cassandraTemplate; // // @Override // protected CassandraTemplate getCassandraTemplate() { // return cassandraTemplate; // } // // } // Path: cassandra-spring/cassandra-spring-hello-world/src/main/java/org/javabahia/cassandra/spring/App.java import java.util.UUID; import org.javabahia.cassandra.spring.entity.Person; import org.javabahia.cassandra.spring.repository.PersonRepository; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; package org.javabahia.cassandra.spring; /** * Hello world! * */ public class App { public static void main( String[] args ) { @SuppressWarnings("resource") ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml"); PersonRepository personService=ctx.getBean(PersonRepository.class); UUID uuid=UUID.randomUUID();
Person person=new Person();
otaviojava/Easy-Cassandra-samples
cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/lucene/ResumeSearch.java
// Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/model/Resume.java // @Entity // public class Resume implements Serializable{ // // private static final long serialVersionUID = 1L; // // @Id // private String nickName; // @Column // private String name; // @Column // private String country; // @Column // private String bio; // // public String getNickName() { // return nickName; // } // public void setNickName(String nickName) { // this.nickName = nickName; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getCountry() { // return country; // } // public void setCountry(String country) { // this.country = country; // } // public String getBio() { // return bio; // } // public void setBio(String bio) { // this.bio = bio; // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Resume) { // Resume other = Resume.class.cast(obj); // return new EqualsBuilder().append(other.nickName, nickName) // .isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(nickName).toHashCode(); // } // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/util/LuceneUtil.java // public enum LuceneUtil { // INSTANCE; // // private Directory directory; // private IndexWriter indexWriter; // private Analyzer analyzer; // public Directory getDirectory() { // return directory; // } // // public Analyzer getAnalyzer() { // return analyzer; // } // // public IndexWriter getIndexWriter() { // // IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_46, analyzer); // // try { // indexWriter = new IndexWriter(directory, indexWriterConfig); // } catch (IOException exception) { // exception.printStackTrace(); // } // return indexWriter; // } // // // { // analyzer = new StandardAnalyzer(Version.LUCENE_46); // directory = new RAMDirectory(); // Directory hd = getDirecotoryHD(); // backup(hd, directory); // // // } // // private Directory getDirecotoryHD() { // File file = new File(System.getProperty("user.home").concat("/lucene/resume/")); // if (!file.exists()) { // file.mkdir(); // } // try { // return FSDirectory.open(file); // } catch (IOException e) { // e.printStackTrace(); // } // // return null; // } // // public void getMemoryToHD() { // Directory hd = getDirecotoryHD(); // backup(directory, hd); // } // // private void backup(Directory deDiretorio, Directory paraDiretoria) { // // try { // for (String file : deDiretorio.listAll()) { // deDiretorio.copy(paraDiretoria, file, file, IOContext.DEFAULT); // } // } catch (IOException ioException) { // ioException.printStackTrace(); // } // } // }
import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.util.Version; import org.javabahia.cassandra.spring.cv.model.Resume; import org.javabahia.cassandra.spring.cv.util.LuceneUtil; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service;
package org.javabahia.cassandra.spring.cv.lucene; @Service @Scope("prototype") public class ResumeSearch { private static final String COLUMN_RESUME = "cv"; private static final String COLUMN_COUNTRY = "estado"; private static final String COLUMN_NAME = "name"; private static final String COLUMN_NICk_NAME = "nickName"; public List<String> findByBio(String bio) throws ParseException, IOException { Query query = new QueryParser(Version.LUCENE_46, COLUMN_RESUME,
// Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/model/Resume.java // @Entity // public class Resume implements Serializable{ // // private static final long serialVersionUID = 1L; // // @Id // private String nickName; // @Column // private String name; // @Column // private String country; // @Column // private String bio; // // public String getNickName() { // return nickName; // } // public void setNickName(String nickName) { // this.nickName = nickName; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getCountry() { // return country; // } // public void setCountry(String country) { // this.country = country; // } // public String getBio() { // return bio; // } // public void setBio(String bio) { // this.bio = bio; // } // // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Resume) { // Resume other = Resume.class.cast(obj); // return new EqualsBuilder().append(other.nickName, nickName) // .isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(nickName).toHashCode(); // } // } // // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/util/LuceneUtil.java // public enum LuceneUtil { // INSTANCE; // // private Directory directory; // private IndexWriter indexWriter; // private Analyzer analyzer; // public Directory getDirectory() { // return directory; // } // // public Analyzer getAnalyzer() { // return analyzer; // } // // public IndexWriter getIndexWriter() { // // IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_46, analyzer); // // try { // indexWriter = new IndexWriter(directory, indexWriterConfig); // } catch (IOException exception) { // exception.printStackTrace(); // } // return indexWriter; // } // // // { // analyzer = new StandardAnalyzer(Version.LUCENE_46); // directory = new RAMDirectory(); // Directory hd = getDirecotoryHD(); // backup(hd, directory); // // // } // // private Directory getDirecotoryHD() { // File file = new File(System.getProperty("user.home").concat("/lucene/resume/")); // if (!file.exists()) { // file.mkdir(); // } // try { // return FSDirectory.open(file); // } catch (IOException e) { // e.printStackTrace(); // } // // return null; // } // // public void getMemoryToHD() { // Directory hd = getDirecotoryHD(); // backup(directory, hd); // } // // private void backup(Directory deDiretorio, Directory paraDiretoria) { // // try { // for (String file : deDiretorio.listAll()) { // deDiretorio.copy(paraDiretoria, file, file, IOContext.DEFAULT); // } // } catch (IOException ioException) { // ioException.printStackTrace(); // } // } // } // Path: cassandra-spring/cassandra-spring-rest/src/main/java/org/javabahia/cassandra/spring/cv/lucene/ResumeSearch.java import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.util.Version; import org.javabahia.cassandra.spring.cv.model.Resume; import org.javabahia.cassandra.spring.cv.util.LuceneUtil; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; package org.javabahia.cassandra.spring.cv.lucene; @Service @Scope("prototype") public class ResumeSearch { private static final String COLUMN_RESUME = "cv"; private static final String COLUMN_COUNTRY = "estado"; private static final String COLUMN_NAME = "name"; private static final String COLUMN_NICk_NAME = "nickName"; public List<String> findByBio(String bio) throws ParseException, IOException { Query query = new QueryParser(Version.LUCENE_46, COLUMN_RESUME,
LuceneUtil.INSTANCE.getAnalyzer()).parse(bio);
otaviojava/Easy-Cassandra-samples
cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/App.java
// Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/model/Tweet.java // @Entity(name = "tweet") // public class Tweet implements Serializable { // // private static final long serialVersionUID = 3L; // // @Id // private UUID id; // // @Index // @Column(name = "nickName") // private String nickName; // // @Column(name = "message") // private String message; // // @Column(name = "time") // private Date time; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getNickName() { // return nickName; // } // // public void setNickName(String nickName) { // this.nickName = nickName; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof Tweet) { // Tweet other = Tweet.class.cast(obj); // return new EqualsBuilder().append(id, other.id).isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(id).toHashCode(); // } // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/repository/TweetRepository.java // public class TweetRepository { // // private Persistence persistence; // // public List<Tweet> findByIndex(String nickName) { // return persistence.findByIndex("nickName", nickName, Tweet.class); // } // // // { // this.persistence = CassandraManager.INSTANCE.getPersistence(); // } // // // public void save(Tweet tweet) { // persistence.insert(tweet); // } // // // public Tweet findOne(UUID uuid) { // return persistence.findByKey(uuid, Tweet.class); // } // // }
import java.util.Date; import java.util.UUID; import org.javabahia.cassandra.tweet.model.Tweet; import org.javabahia.cassandra.tweet.repository.TweetRepository;
package org.javabahia.cassandra.tweet; /** * Hello world! * */ public class App { public static void main( String[] args ) {
// Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/model/Tweet.java // @Entity(name = "tweet") // public class Tweet implements Serializable { // // private static final long serialVersionUID = 3L; // // @Id // private UUID id; // // @Index // @Column(name = "nickName") // private String nickName; // // @Column(name = "message") // private String message; // // @Column(name = "time") // private Date time; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getNickName() { // return nickName; // } // // public void setNickName(String nickName) { // this.nickName = nickName; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof Tweet) { // Tweet other = Tweet.class.cast(obj); // return new EqualsBuilder().append(id, other.id).isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(id).toHashCode(); // } // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/repository/TweetRepository.java // public class TweetRepository { // // private Persistence persistence; // // public List<Tweet> findByIndex(String nickName) { // return persistence.findByIndex("nickName", nickName, Tweet.class); // } // // // { // this.persistence = CassandraManager.INSTANCE.getPersistence(); // } // // // public void save(Tweet tweet) { // persistence.insert(tweet); // } // // // public Tweet findOne(UUID uuid) { // return persistence.findByKey(uuid, Tweet.class); // } // // } // Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/App.java import java.util.Date; import java.util.UUID; import org.javabahia.cassandra.tweet.model.Tweet; import org.javabahia.cassandra.tweet.repository.TweetRepository; package org.javabahia.cassandra.tweet; /** * Hello world! * */ public class App { public static void main( String[] args ) {
TweetRepository personService = new TweetRepository();
otaviojava/Easy-Cassandra-samples
cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/App.java
// Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/model/Tweet.java // @Entity(name = "tweet") // public class Tweet implements Serializable { // // private static final long serialVersionUID = 3L; // // @Id // private UUID id; // // @Index // @Column(name = "nickName") // private String nickName; // // @Column(name = "message") // private String message; // // @Column(name = "time") // private Date time; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getNickName() { // return nickName; // } // // public void setNickName(String nickName) { // this.nickName = nickName; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof Tweet) { // Tweet other = Tweet.class.cast(obj); // return new EqualsBuilder().append(id, other.id).isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(id).toHashCode(); // } // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/repository/TweetRepository.java // public class TweetRepository { // // private Persistence persistence; // // public List<Tweet> findByIndex(String nickName) { // return persistence.findByIndex("nickName", nickName, Tweet.class); // } // // // { // this.persistence = CassandraManager.INSTANCE.getPersistence(); // } // // // public void save(Tweet tweet) { // persistence.insert(tweet); // } // // // public Tweet findOne(UUID uuid) { // return persistence.findByKey(uuid, Tweet.class); // } // // }
import java.util.Date; import java.util.UUID; import org.javabahia.cassandra.tweet.model.Tweet; import org.javabahia.cassandra.tweet.repository.TweetRepository;
package org.javabahia.cassandra.tweet; /** * Hello world! * */ public class App { public static void main( String[] args ) { TweetRepository personService = new TweetRepository(); UUID uuid = UUID.randomUUID();
// Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/model/Tweet.java // @Entity(name = "tweet") // public class Tweet implements Serializable { // // private static final long serialVersionUID = 3L; // // @Id // private UUID id; // // @Index // @Column(name = "nickName") // private String nickName; // // @Column(name = "message") // private String message; // // @Column(name = "time") // private Date time; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getNickName() { // return nickName; // } // // public void setNickName(String nickName) { // this.nickName = nickName; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof Tweet) { // Tweet other = Tweet.class.cast(obj); // return new EqualsBuilder().append(id, other.id).isEquals(); // } // return false; // } // // @Override // public int hashCode() { // // return new HashCodeBuilder().append(id).toHashCode(); // } // @Override // public String toString() { // // return ToStringBuilder.reflectionToString(this, // ToStringStyle.SHORT_PREFIX_STYLE); // } // // } // // Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/repository/TweetRepository.java // public class TweetRepository { // // private Persistence persistence; // // public List<Tweet> findByIndex(String nickName) { // return persistence.findByIndex("nickName", nickName, Tweet.class); // } // // // { // this.persistence = CassandraManager.INSTANCE.getPersistence(); // } // // // public void save(Tweet tweet) { // persistence.insert(tweet); // } // // // public Tweet findOne(UUID uuid) { // return persistence.findByKey(uuid, Tweet.class); // } // // } // Path: cassandra-hello-world/src/main/java/org/javabahia/cassandra/tweet/App.java import java.util.Date; import java.util.UUID; import org.javabahia.cassandra.tweet.model.Tweet; import org.javabahia.cassandra.tweet.repository.TweetRepository; package org.javabahia.cassandra.tweet; /** * Hello world! * */ public class App { public static void main( String[] args ) { TweetRepository personService = new TweetRepository(); UUID uuid = UUID.randomUUID();
Tweet tweet = new Tweet();
CloudCoders/GestAca
src/main/java/com/cloudcoders/gestaca/persistance/StudentDAOImpl.java
// Path: src/main/java/com/cloudcoders/gestaca/logic/IStudentDAO.java // public interface IStudentDAO { // // Student get(String id); // // void add(Student student); // // Student remove(Student student); // // List<Student> getAll(); // } // // Path: src/main/java/com/cloudcoders/gestaca/model/Student.java // public class Student extends Person { // private String iban; // private List<Enrollment> enrollments; // // public Student(int zip, String address, String id, String name, String iban) { // super(zip, address, id, name); // this.iban = iban; // this.enrollments = new ArrayList<Enrollment>(); // } // // public Student(int zip, String address, String id, String name, String iban, List<Enrollment> enrollments) { // super(zip, address, id, name); // this.iban = iban; // this.enrollments = enrollments; // } // // // public void addEnrollment(Enrollment enrollment) { // this.enrollments.add(enrollment); // } // // public void removeEnrollment(Enrollment enrollment) { // this.enrollments.remove(enrollment); // } // // public String getIban() { // return iban; // } // // public List<Enrollment> getEnrollments() { // return enrollments; // } // // }
import com.cloudcoders.gestaca.logic.IStudentDAO; import com.cloudcoders.gestaca.model.Student; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List;
package com.cloudcoders.gestaca.persistance; public class StudentDAOImpl implements IStudentDAO { private JsonParser parser = new JsonParser(); @Override
// Path: src/main/java/com/cloudcoders/gestaca/logic/IStudentDAO.java // public interface IStudentDAO { // // Student get(String id); // // void add(Student student); // // Student remove(Student student); // // List<Student> getAll(); // } // // Path: src/main/java/com/cloudcoders/gestaca/model/Student.java // public class Student extends Person { // private String iban; // private List<Enrollment> enrollments; // // public Student(int zip, String address, String id, String name, String iban) { // super(zip, address, id, name); // this.iban = iban; // this.enrollments = new ArrayList<Enrollment>(); // } // // public Student(int zip, String address, String id, String name, String iban, List<Enrollment> enrollments) { // super(zip, address, id, name); // this.iban = iban; // this.enrollments = enrollments; // } // // // public void addEnrollment(Enrollment enrollment) { // this.enrollments.add(enrollment); // } // // public void removeEnrollment(Enrollment enrollment) { // this.enrollments.remove(enrollment); // } // // public String getIban() { // return iban; // } // // public List<Enrollment> getEnrollments() { // return enrollments; // } // // } // Path: src/main/java/com/cloudcoders/gestaca/persistance/StudentDAOImpl.java import com.cloudcoders.gestaca.logic.IStudentDAO; import com.cloudcoders.gestaca.model.Student; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; package com.cloudcoders.gestaca.persistance; public class StudentDAOImpl implements IStudentDAO { private JsonParser parser = new JsonParser(); @Override
public Student get(String dni) {
CloudCoders/GestAca
src/main/java/com/cloudcoders/gestaca/ui/controller/CreateCourseCommand.java
// Path: src/main/java/com/cloudcoders/gestaca/logic/course/AddCourse.java // public class AddCourse { // ICourseDAO iCourseDAO; // // public AddCourse(ICourseDAO iCourseDAO) { // this.iCourseDAO = iCourseDAO; // } // // public void add(Course course) { // iCourseDAO.add(course); // } // } // // Path: src/main/java/com/cloudcoders/gestaca/model/Course.java // public class Course { // private String description; // private String name; // private int id; // private List<TaughtCourse> taughtCourses; // // public Course(String description, String name, int id, List<TaughtCourse> taughtCourses) { // this.description = description; // this.name = name; // this.id = id; // this.taughtCourses = taughtCourses; // } // // public Course(String description, String name, int id) { // this.description = description; // this.name = name; // this.id = id; // this.taughtCourses = new ArrayList<TaughtCourse>(); // } // // public void addTaughtCourse(TaughtCourse taughtCourse) { // this.taughtCourses.add(taughtCourse); // } // // public void removeTaughtCourse(TaughtCourse taughtCourse) { // this.taughtCourses.remove(taughtCourse); // } // // public String getDescription() { // return description; // } // // public String getName() { // return name; // } // // public int getId() { // return id; // } // // public List<TaughtCourse> getTaughtCourses() { // return taughtCourses; // } // // } // // Path: src/main/java/com/cloudcoders/gestaca/ui/View.java // public interface View { // void showCourses(List<Course> courseList); // // void showEmptyCourses(); // // Course askCourse(); // // String askDNI(); // // void showStudentNotFound(); // // void showStudentFoundAndEnrolled(); // // void showStudentEnrolled(); // // void showStudentFoundAndNotEnrolled(); // // Student askStudent(); // // void showStudent(Student student); // // Course askCreateCourse(); // // void showCurseCreated(); // // void showCurseAlreadyExists(); // }
import com.cloudcoders.gestaca.logic.course.AddCourse; import com.cloudcoders.gestaca.model.Course; import com.cloudcoders.gestaca.ui.View;
package com.cloudcoders.gestaca.ui.controller; public class CreateCourseCommand implements Command { public static final String CREATE_CURSE = "crear curso";
// Path: src/main/java/com/cloudcoders/gestaca/logic/course/AddCourse.java // public class AddCourse { // ICourseDAO iCourseDAO; // // public AddCourse(ICourseDAO iCourseDAO) { // this.iCourseDAO = iCourseDAO; // } // // public void add(Course course) { // iCourseDAO.add(course); // } // } // // Path: src/main/java/com/cloudcoders/gestaca/model/Course.java // public class Course { // private String description; // private String name; // private int id; // private List<TaughtCourse> taughtCourses; // // public Course(String description, String name, int id, List<TaughtCourse> taughtCourses) { // this.description = description; // this.name = name; // this.id = id; // this.taughtCourses = taughtCourses; // } // // public Course(String description, String name, int id) { // this.description = description; // this.name = name; // this.id = id; // this.taughtCourses = new ArrayList<TaughtCourse>(); // } // // public void addTaughtCourse(TaughtCourse taughtCourse) { // this.taughtCourses.add(taughtCourse); // } // // public void removeTaughtCourse(TaughtCourse taughtCourse) { // this.taughtCourses.remove(taughtCourse); // } // // public String getDescription() { // return description; // } // // public String getName() { // return name; // } // // public int getId() { // return id; // } // // public List<TaughtCourse> getTaughtCourses() { // return taughtCourses; // } // // } // // Path: src/main/java/com/cloudcoders/gestaca/ui/View.java // public interface View { // void showCourses(List<Course> courseList); // // void showEmptyCourses(); // // Course askCourse(); // // String askDNI(); // // void showStudentNotFound(); // // void showStudentFoundAndEnrolled(); // // void showStudentEnrolled(); // // void showStudentFoundAndNotEnrolled(); // // Student askStudent(); // // void showStudent(Student student); // // Course askCreateCourse(); // // void showCurseCreated(); // // void showCurseAlreadyExists(); // } // Path: src/main/java/com/cloudcoders/gestaca/ui/controller/CreateCourseCommand.java import com.cloudcoders.gestaca.logic.course.AddCourse; import com.cloudcoders.gestaca.model.Course; import com.cloudcoders.gestaca.ui.View; package com.cloudcoders.gestaca.ui.controller; public class CreateCourseCommand implements Command { public static final String CREATE_CURSE = "crear curso";
private View view;
CloudCoders/GestAca
src/main/java/com/cloudcoders/gestaca/ui/controller/CreateCourseCommand.java
// Path: src/main/java/com/cloudcoders/gestaca/logic/course/AddCourse.java // public class AddCourse { // ICourseDAO iCourseDAO; // // public AddCourse(ICourseDAO iCourseDAO) { // this.iCourseDAO = iCourseDAO; // } // // public void add(Course course) { // iCourseDAO.add(course); // } // } // // Path: src/main/java/com/cloudcoders/gestaca/model/Course.java // public class Course { // private String description; // private String name; // private int id; // private List<TaughtCourse> taughtCourses; // // public Course(String description, String name, int id, List<TaughtCourse> taughtCourses) { // this.description = description; // this.name = name; // this.id = id; // this.taughtCourses = taughtCourses; // } // // public Course(String description, String name, int id) { // this.description = description; // this.name = name; // this.id = id; // this.taughtCourses = new ArrayList<TaughtCourse>(); // } // // public void addTaughtCourse(TaughtCourse taughtCourse) { // this.taughtCourses.add(taughtCourse); // } // // public void removeTaughtCourse(TaughtCourse taughtCourse) { // this.taughtCourses.remove(taughtCourse); // } // // public String getDescription() { // return description; // } // // public String getName() { // return name; // } // // public int getId() { // return id; // } // // public List<TaughtCourse> getTaughtCourses() { // return taughtCourses; // } // // } // // Path: src/main/java/com/cloudcoders/gestaca/ui/View.java // public interface View { // void showCourses(List<Course> courseList); // // void showEmptyCourses(); // // Course askCourse(); // // String askDNI(); // // void showStudentNotFound(); // // void showStudentFoundAndEnrolled(); // // void showStudentEnrolled(); // // void showStudentFoundAndNotEnrolled(); // // Student askStudent(); // // void showStudent(Student student); // // Course askCreateCourse(); // // void showCurseCreated(); // // void showCurseAlreadyExists(); // }
import com.cloudcoders.gestaca.logic.course.AddCourse; import com.cloudcoders.gestaca.model.Course; import com.cloudcoders.gestaca.ui.View;
package com.cloudcoders.gestaca.ui.controller; public class CreateCourseCommand implements Command { public static final String CREATE_CURSE = "crear curso"; private View view;
// Path: src/main/java/com/cloudcoders/gestaca/logic/course/AddCourse.java // public class AddCourse { // ICourseDAO iCourseDAO; // // public AddCourse(ICourseDAO iCourseDAO) { // this.iCourseDAO = iCourseDAO; // } // // public void add(Course course) { // iCourseDAO.add(course); // } // } // // Path: src/main/java/com/cloudcoders/gestaca/model/Course.java // public class Course { // private String description; // private String name; // private int id; // private List<TaughtCourse> taughtCourses; // // public Course(String description, String name, int id, List<TaughtCourse> taughtCourses) { // this.description = description; // this.name = name; // this.id = id; // this.taughtCourses = taughtCourses; // } // // public Course(String description, String name, int id) { // this.description = description; // this.name = name; // this.id = id; // this.taughtCourses = new ArrayList<TaughtCourse>(); // } // // public void addTaughtCourse(TaughtCourse taughtCourse) { // this.taughtCourses.add(taughtCourse); // } // // public void removeTaughtCourse(TaughtCourse taughtCourse) { // this.taughtCourses.remove(taughtCourse); // } // // public String getDescription() { // return description; // } // // public String getName() { // return name; // } // // public int getId() { // return id; // } // // public List<TaughtCourse> getTaughtCourses() { // return taughtCourses; // } // // } // // Path: src/main/java/com/cloudcoders/gestaca/ui/View.java // public interface View { // void showCourses(List<Course> courseList); // // void showEmptyCourses(); // // Course askCourse(); // // String askDNI(); // // void showStudentNotFound(); // // void showStudentFoundAndEnrolled(); // // void showStudentEnrolled(); // // void showStudentFoundAndNotEnrolled(); // // Student askStudent(); // // void showStudent(Student student); // // Course askCreateCourse(); // // void showCurseCreated(); // // void showCurseAlreadyExists(); // } // Path: src/main/java/com/cloudcoders/gestaca/ui/controller/CreateCourseCommand.java import com.cloudcoders.gestaca.logic.course.AddCourse; import com.cloudcoders.gestaca.model.Course; import com.cloudcoders.gestaca.ui.View; package com.cloudcoders.gestaca.ui.controller; public class CreateCourseCommand implements Command { public static final String CREATE_CURSE = "crear curso"; private View view;
private AddCourse addCourse;
CloudCoders/GestAca
src/main/java/com/cloudcoders/gestaca/ui/controller/CreateCourseCommand.java
// Path: src/main/java/com/cloudcoders/gestaca/logic/course/AddCourse.java // public class AddCourse { // ICourseDAO iCourseDAO; // // public AddCourse(ICourseDAO iCourseDAO) { // this.iCourseDAO = iCourseDAO; // } // // public void add(Course course) { // iCourseDAO.add(course); // } // } // // Path: src/main/java/com/cloudcoders/gestaca/model/Course.java // public class Course { // private String description; // private String name; // private int id; // private List<TaughtCourse> taughtCourses; // // public Course(String description, String name, int id, List<TaughtCourse> taughtCourses) { // this.description = description; // this.name = name; // this.id = id; // this.taughtCourses = taughtCourses; // } // // public Course(String description, String name, int id) { // this.description = description; // this.name = name; // this.id = id; // this.taughtCourses = new ArrayList<TaughtCourse>(); // } // // public void addTaughtCourse(TaughtCourse taughtCourse) { // this.taughtCourses.add(taughtCourse); // } // // public void removeTaughtCourse(TaughtCourse taughtCourse) { // this.taughtCourses.remove(taughtCourse); // } // // public String getDescription() { // return description; // } // // public String getName() { // return name; // } // // public int getId() { // return id; // } // // public List<TaughtCourse> getTaughtCourses() { // return taughtCourses; // } // // } // // Path: src/main/java/com/cloudcoders/gestaca/ui/View.java // public interface View { // void showCourses(List<Course> courseList); // // void showEmptyCourses(); // // Course askCourse(); // // String askDNI(); // // void showStudentNotFound(); // // void showStudentFoundAndEnrolled(); // // void showStudentEnrolled(); // // void showStudentFoundAndNotEnrolled(); // // Student askStudent(); // // void showStudent(Student student); // // Course askCreateCourse(); // // void showCurseCreated(); // // void showCurseAlreadyExists(); // }
import com.cloudcoders.gestaca.logic.course.AddCourse; import com.cloudcoders.gestaca.model.Course; import com.cloudcoders.gestaca.ui.View;
package com.cloudcoders.gestaca.ui.controller; public class CreateCourseCommand implements Command { public static final String CREATE_CURSE = "crear curso"; private View view; private AddCourse addCourse; public CreateCourseCommand(View view, AddCourse addCourse) { this.view = view; this.addCourse = addCourse; } @Override public boolean matches(String cmd) { return cmd.equals(CREATE_CURSE); } @Override public void execute() {
// Path: src/main/java/com/cloudcoders/gestaca/logic/course/AddCourse.java // public class AddCourse { // ICourseDAO iCourseDAO; // // public AddCourse(ICourseDAO iCourseDAO) { // this.iCourseDAO = iCourseDAO; // } // // public void add(Course course) { // iCourseDAO.add(course); // } // } // // Path: src/main/java/com/cloudcoders/gestaca/model/Course.java // public class Course { // private String description; // private String name; // private int id; // private List<TaughtCourse> taughtCourses; // // public Course(String description, String name, int id, List<TaughtCourse> taughtCourses) { // this.description = description; // this.name = name; // this.id = id; // this.taughtCourses = taughtCourses; // } // // public Course(String description, String name, int id) { // this.description = description; // this.name = name; // this.id = id; // this.taughtCourses = new ArrayList<TaughtCourse>(); // } // // public void addTaughtCourse(TaughtCourse taughtCourse) { // this.taughtCourses.add(taughtCourse); // } // // public void removeTaughtCourse(TaughtCourse taughtCourse) { // this.taughtCourses.remove(taughtCourse); // } // // public String getDescription() { // return description; // } // // public String getName() { // return name; // } // // public int getId() { // return id; // } // // public List<TaughtCourse> getTaughtCourses() { // return taughtCourses; // } // // } // // Path: src/main/java/com/cloudcoders/gestaca/ui/View.java // public interface View { // void showCourses(List<Course> courseList); // // void showEmptyCourses(); // // Course askCourse(); // // String askDNI(); // // void showStudentNotFound(); // // void showStudentFoundAndEnrolled(); // // void showStudentEnrolled(); // // void showStudentFoundAndNotEnrolled(); // // Student askStudent(); // // void showStudent(Student student); // // Course askCreateCourse(); // // void showCurseCreated(); // // void showCurseAlreadyExists(); // } // Path: src/main/java/com/cloudcoders/gestaca/ui/controller/CreateCourseCommand.java import com.cloudcoders.gestaca.logic.course.AddCourse; import com.cloudcoders.gestaca.model.Course; import com.cloudcoders.gestaca.ui.View; package com.cloudcoders.gestaca.ui.controller; public class CreateCourseCommand implements Command { public static final String CREATE_CURSE = "crear curso"; private View view; private AddCourse addCourse; public CreateCourseCommand(View view, AddCourse addCourse) { this.view = view; this.addCourse = addCourse; } @Override public boolean matches(String cmd) { return cmd.equals(CREATE_CURSE); } @Override public void execute() {
Course course = view.askCreateCourse();