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
upwork/java-upwork
test/com/Upwork/api/Routers/Freelancers/SearchTest.java
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Freelancers/Search.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Search { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Search(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Search freelancers // * // * @param params (Optional) Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject find(HashMap<String, String> params) throws JSONException { // return oClient.get("/profiles/v2/search/providers", params); // } // // }
import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Freelancers.Search;
package com.Upwork.api.Routers.Freelancers; @RunWith(PowerMockRunner.class) @PrepareForTest({
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Freelancers/Search.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Search { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Search(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Search freelancers // * // * @param params (Optional) Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject find(HashMap<String, String> params) throws JSONException { // return oClient.get("/profiles/v2/search/providers", params); // } // // } // Path: test/com/Upwork/api/Routers/Freelancers/SearchTest.java import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Freelancers.Search; package com.Upwork.api.Routers.Freelancers; @RunWith(PowerMockRunner.class) @PrepareForTest({
Search.class
upwork/java-upwork
test/com/Upwork/api/Routers/Freelancers/SearchTest.java
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Freelancers/Search.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Search { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Search(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Search freelancers // * // * @param params (Optional) Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject find(HashMap<String, String> params) throws JSONException { // return oClient.get("/profiles/v2/search/providers", params); // } // // }
import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Freelancers.Search;
package com.Upwork.api.Routers.Freelancers; @RunWith(PowerMockRunner.class) @PrepareForTest({ Search.class })
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Freelancers/Search.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Search { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Search(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Search freelancers // * // * @param params (Optional) Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject find(HashMap<String, String> params) throws JSONException { // return oClient.get("/profiles/v2/search/providers", params); // } // // } // Path: test/com/Upwork/api/Routers/Freelancers/SearchTest.java import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Freelancers.Search; package com.Upwork.api.Routers.Freelancers; @RunWith(PowerMockRunner.class) @PrepareForTest({ Search.class })
public class SearchTest extends Helper {
upwork/java-upwork
test/com/Upwork/api/Routers/Jobs/ProfileTest.java
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Jobs/Profile.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Profile { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Profile(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get specific Job's Profile // * // * @param key Profile key // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecific(String key) throws JSONException { // return oClient.get("/profiles/v1/jobs/" + key); // } // // }
import static org.junit.Assert.*; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Jobs.Profile;
package com.Upwork.api.Routers.Jobs; @RunWith(PowerMockRunner.class) @PrepareForTest({
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Jobs/Profile.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Profile { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Profile(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get specific Job's Profile // * // * @param key Profile key // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecific(String key) throws JSONException { // return oClient.get("/profiles/v1/jobs/" + key); // } // // } // Path: test/com/Upwork/api/Routers/Jobs/ProfileTest.java import static org.junit.Assert.*; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Jobs.Profile; package com.Upwork.api.Routers.Jobs; @RunWith(PowerMockRunner.class) @PrepareForTest({
Profile.class
upwork/java-upwork
test/com/Upwork/api/Routers/Jobs/ProfileTest.java
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Jobs/Profile.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Profile { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Profile(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get specific Job's Profile // * // * @param key Profile key // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecific(String key) throws JSONException { // return oClient.get("/profiles/v1/jobs/" + key); // } // // }
import static org.junit.Assert.*; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Jobs.Profile;
package com.Upwork.api.Routers.Jobs; @RunWith(PowerMockRunner.class) @PrepareForTest({ Profile.class })
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Jobs/Profile.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Profile { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Profile(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get specific Job's Profile // * // * @param key Profile key // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecific(String key) throws JSONException { // return oClient.get("/profiles/v1/jobs/" + key); // } // // } // Path: test/com/Upwork/api/Routers/Jobs/ProfileTest.java import static org.junit.Assert.*; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Jobs.Profile; package com.Upwork.api.Routers.Jobs; @RunWith(PowerMockRunner.class) @PrepareForTest({ Profile.class })
public class ProfileTest extends Helper {
upwork/java-upwork
example-android/app/src/main/java/com/upwork/example_upworkapi/MyActivity.java
// Path: src/com/Upwork/api/Routers/Organization/Users.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "10/13/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Users { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Users(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get Auth User Info // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getMyInfo() throws JSONException { // return oClient.get("/hr/v2/users/me"); // } // // /** // * Get Specific User Info // * // * @param userReference User reference // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecific(String userReference) throws JSONException { // return oClient.get("/hr/v2/users/" + userReference); // } // // }
import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.os.Build; import android.widget.Button; import android.widget.Toast; import java.util.HashMap; import java.util.Properties; import com.Upwork.api.*; import com.Upwork.api.Routers.Organization.Users; import org.json.JSONException; import org.json.JSONObject; import oauth.signpost.OAuth;
class UpworkRetrieveAccessTokenTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String verifier = params[0]; HashMap<String, String> token = client.getAccessTokenSet(verifier); client.setTokenWithSecret(token.get("token"), token.get("secret")); // Save token/secret in preferences prefs.edit().putString("token", token.get("token")) .putString("secret", token.get("secret")) .commit(); return "ok - token is: " + prefs.getString("token", null); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (result != null) { Toast.makeText(MyActivity.this, result, Toast.LENGTH_LONG).show(); } } } class GetMyUIdTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { JSONObject json = null; String token = prefs.getString("token", null);
// Path: src/com/Upwork/api/Routers/Organization/Users.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "10/13/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Users { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Users(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get Auth User Info // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getMyInfo() throws JSONException { // return oClient.get("/hr/v2/users/me"); // } // // /** // * Get Specific User Info // * // * @param userReference User reference // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecific(String userReference) throws JSONException { // return oClient.get("/hr/v2/users/" + userReference); // } // // } // Path: example-android/app/src/main/java/com/upwork/example_upworkapi/MyActivity.java import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.os.Build; import android.widget.Button; import android.widget.Toast; import java.util.HashMap; import java.util.Properties; import com.Upwork.api.*; import com.Upwork.api.Routers.Organization.Users; import org.json.JSONException; import org.json.JSONObject; import oauth.signpost.OAuth; class UpworkRetrieveAccessTokenTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String verifier = params[0]; HashMap<String, String> token = client.getAccessTokenSet(verifier); client.setTokenWithSecret(token.get("token"), token.get("secret")); // Save token/secret in preferences prefs.edit().putString("token", token.get("token")) .putString("secret", token.get("secret")) .commit(); return "ok - token is: " + prefs.getString("token", null); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (result != null) { Toast.makeText(MyActivity.this, result, Toast.LENGTH_LONG).show(); } } } class GetMyUIdTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { JSONObject json = null; String token = prefs.getString("token", null);
Users users = new Users(client);
upwork/java-upwork
test/com/Upwork/api/Routers/Activities/EngagementTest.java
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Activities/Engagement.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "24/09/2015", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Engagement { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Engagement(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * List activities for specific engagement // * // * @param engagement_ref Engagement reference // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecific(String engagement_ref) throws JSONException { // return oClient.get("/tasks/v2/tasks/contracts/" + engagement_ref); // } // // /** // * Assign engagements to the list of activities // * // * @param company Company ID // * @param team Team ID // * @param engagement Engagement // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject assign(String company, String team, String engagement, HashMap<String, String> params) throws JSONException { // return oClient.put("/otask/v1/tasks/companies/" + company + "/teams/" + team + "/engagements/" + engagement + "/tasks", params); // } // // /** // * Assign engagements to the list of activities // * // * @param engagement_ref Engagement reference // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject assignToEngagement(String engagement_ref, HashMap<String, String> params) throws JSONException { // return oClient.put("/tasks/v2/tasks/contracts/" + engagement_ref, params); // } // // }
import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Activities.Engagement;
package com.Upwork.api.Routers.Activities; @RunWith(PowerMockRunner.class) @PrepareForTest({
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Activities/Engagement.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "24/09/2015", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Engagement { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Engagement(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * List activities for specific engagement // * // * @param engagement_ref Engagement reference // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecific(String engagement_ref) throws JSONException { // return oClient.get("/tasks/v2/tasks/contracts/" + engagement_ref); // } // // /** // * Assign engagements to the list of activities // * // * @param company Company ID // * @param team Team ID // * @param engagement Engagement // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject assign(String company, String team, String engagement, HashMap<String, String> params) throws JSONException { // return oClient.put("/otask/v1/tasks/companies/" + company + "/teams/" + team + "/engagements/" + engagement + "/tasks", params); // } // // /** // * Assign engagements to the list of activities // * // * @param engagement_ref Engagement reference // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject assignToEngagement(String engagement_ref, HashMap<String, String> params) throws JSONException { // return oClient.put("/tasks/v2/tasks/contracts/" + engagement_ref, params); // } // // } // Path: test/com/Upwork/api/Routers/Activities/EngagementTest.java import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Activities.Engagement; package com.Upwork.api.Routers.Activities; @RunWith(PowerMockRunner.class) @PrepareForTest({
Engagement.class
upwork/java-upwork
test/com/Upwork/api/Routers/Activities/EngagementTest.java
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Activities/Engagement.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "24/09/2015", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Engagement { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Engagement(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * List activities for specific engagement // * // * @param engagement_ref Engagement reference // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecific(String engagement_ref) throws JSONException { // return oClient.get("/tasks/v2/tasks/contracts/" + engagement_ref); // } // // /** // * Assign engagements to the list of activities // * // * @param company Company ID // * @param team Team ID // * @param engagement Engagement // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject assign(String company, String team, String engagement, HashMap<String, String> params) throws JSONException { // return oClient.put("/otask/v1/tasks/companies/" + company + "/teams/" + team + "/engagements/" + engagement + "/tasks", params); // } // // /** // * Assign engagements to the list of activities // * // * @param engagement_ref Engagement reference // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject assignToEngagement(String engagement_ref, HashMap<String, String> params) throws JSONException { // return oClient.put("/tasks/v2/tasks/contracts/" + engagement_ref, params); // } // // }
import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Activities.Engagement;
package com.Upwork.api.Routers.Activities; @RunWith(PowerMockRunner.class) @PrepareForTest({ Engagement.class })
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Activities/Engagement.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "24/09/2015", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Engagement { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Engagement(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * List activities for specific engagement // * // * @param engagement_ref Engagement reference // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecific(String engagement_ref) throws JSONException { // return oClient.get("/tasks/v2/tasks/contracts/" + engagement_ref); // } // // /** // * Assign engagements to the list of activities // * // * @param company Company ID // * @param team Team ID // * @param engagement Engagement // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject assign(String company, String team, String engagement, HashMap<String, String> params) throws JSONException { // return oClient.put("/otask/v1/tasks/companies/" + company + "/teams/" + team + "/engagements/" + engagement + "/tasks", params); // } // // /** // * Assign engagements to the list of activities // * // * @param engagement_ref Engagement reference // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject assignToEngagement(String engagement_ref, HashMap<String, String> params) throws JSONException { // return oClient.put("/tasks/v2/tasks/contracts/" + engagement_ref, params); // } // // } // Path: test/com/Upwork/api/Routers/Activities/EngagementTest.java import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Activities.Engagement; package com.Upwork.api.Routers.Activities; @RunWith(PowerMockRunner.class) @PrepareForTest({ Engagement.class })
public class EngagementTest extends Helper {
upwork/java-upwork
test/com/Upwork/api/Routers/SnapshotTest.java
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Snapshot.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "24/5/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Snapshot { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Snapshot(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get snapshot info by specific contract // * // * @param contractId Contract ID // * @param ts Timestamp // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getByContract(String contractId, String ts) throws JSONException { // return oClient.get("/team/v3/snapshots/contracts/" + contractId + "/" + ts); // } // // /** // * Update snapshot by specific contract // * // * @param contractId Contract ID // * @param ts Timestamp // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject updateByContract(String contractId, String ts, HashMap<String, String> params) throws JSONException { // return oClient.put("/team/v3/snapshots/contracts/" + contractId + "/" + ts, params); // } // // /** // * Delete snapshot by specific contract // * // * @param contractId Contract ID // * @param ts Timestamp // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject deleteByContract(String contractId, String ts) throws JSONException { // return oClient.delete("/team/v3/snapshots/contracts/" + contractId + "/" + ts); // } // // }
import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Snapshot;
package com.Upwork.api.Routers; @RunWith(PowerMockRunner.class) @PrepareForTest({
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Snapshot.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "24/5/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Snapshot { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Snapshot(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get snapshot info by specific contract // * // * @param contractId Contract ID // * @param ts Timestamp // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getByContract(String contractId, String ts) throws JSONException { // return oClient.get("/team/v3/snapshots/contracts/" + contractId + "/" + ts); // } // // /** // * Update snapshot by specific contract // * // * @param contractId Contract ID // * @param ts Timestamp // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject updateByContract(String contractId, String ts, HashMap<String, String> params) throws JSONException { // return oClient.put("/team/v3/snapshots/contracts/" + contractId + "/" + ts, params); // } // // /** // * Delete snapshot by specific contract // * // * @param contractId Contract ID // * @param ts Timestamp // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject deleteByContract(String contractId, String ts) throws JSONException { // return oClient.delete("/team/v3/snapshots/contracts/" + contractId + "/" + ts); // } // // } // Path: test/com/Upwork/api/Routers/SnapshotTest.java import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Snapshot; package com.Upwork.api.Routers; @RunWith(PowerMockRunner.class) @PrepareForTest({
Snapshot.class
upwork/java-upwork
test/com/Upwork/api/Routers/SnapshotTest.java
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Snapshot.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "24/5/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Snapshot { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Snapshot(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get snapshot info by specific contract // * // * @param contractId Contract ID // * @param ts Timestamp // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getByContract(String contractId, String ts) throws JSONException { // return oClient.get("/team/v3/snapshots/contracts/" + contractId + "/" + ts); // } // // /** // * Update snapshot by specific contract // * // * @param contractId Contract ID // * @param ts Timestamp // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject updateByContract(String contractId, String ts, HashMap<String, String> params) throws JSONException { // return oClient.put("/team/v3/snapshots/contracts/" + contractId + "/" + ts, params); // } // // /** // * Delete snapshot by specific contract // * // * @param contractId Contract ID // * @param ts Timestamp // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject deleteByContract(String contractId, String ts) throws JSONException { // return oClient.delete("/team/v3/snapshots/contracts/" + contractId + "/" + ts); // } // // }
import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Snapshot;
package com.Upwork.api.Routers; @RunWith(PowerMockRunner.class) @PrepareForTest({ Snapshot.class })
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Snapshot.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "24/5/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Snapshot { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Snapshot(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get snapshot info by specific contract // * // * @param contractId Contract ID // * @param ts Timestamp // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getByContract(String contractId, String ts) throws JSONException { // return oClient.get("/team/v3/snapshots/contracts/" + contractId + "/" + ts); // } // // /** // * Update snapshot by specific contract // * // * @param contractId Contract ID // * @param ts Timestamp // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject updateByContract(String contractId, String ts, HashMap<String, String> params) throws JSONException { // return oClient.put("/team/v3/snapshots/contracts/" + contractId + "/" + ts, params); // } // // /** // * Delete snapshot by specific contract // * // * @param contractId Contract ID // * @param ts Timestamp // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject deleteByContract(String contractId, String ts) throws JSONException { // return oClient.delete("/team/v3/snapshots/contracts/" + contractId + "/" + ts); // } // // } // Path: test/com/Upwork/api/Routers/SnapshotTest.java import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Snapshot; package com.Upwork.api.Routers; @RunWith(PowerMockRunner.class) @PrepareForTest({ Snapshot.class })
public class SnapshotTest extends Helper {
upwork/java-upwork
test/com/Upwork/api/Routers/AuthTest.java
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Auth.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/3/2014", // currentRevision = 1, // lastModified = "6/3/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Auth { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Auth(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get My Info // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // * */ // public JSONObject getUserInfo() throws JSONException { // return oClient.get("/auth/v1/info"); // } // // }
import static org.junit.Assert.*; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Auth;
package com.Upwork.api.Routers; @RunWith(PowerMockRunner.class) @PrepareForTest({
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Auth.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/3/2014", // currentRevision = 1, // lastModified = "6/3/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Auth { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Auth(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get My Info // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // * */ // public JSONObject getUserInfo() throws JSONException { // return oClient.get("/auth/v1/info"); // } // // } // Path: test/com/Upwork/api/Routers/AuthTest.java import static org.junit.Assert.*; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Auth; package com.Upwork.api.Routers; @RunWith(PowerMockRunner.class) @PrepareForTest({
Auth.class
upwork/java-upwork
test/com/Upwork/api/Routers/AuthTest.java
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Auth.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/3/2014", // currentRevision = 1, // lastModified = "6/3/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Auth { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Auth(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get My Info // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // * */ // public JSONObject getUserInfo() throws JSONException { // return oClient.get("/auth/v1/info"); // } // // }
import static org.junit.Assert.*; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Auth;
package com.Upwork.api.Routers; @RunWith(PowerMockRunner.class) @PrepareForTest({ Auth.class })
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Auth.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/3/2014", // currentRevision = 1, // lastModified = "6/3/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Auth { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Auth(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get My Info // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // * */ // public JSONObject getUserInfo() throws JSONException { // return oClient.get("/auth/v1/info"); // } // // } // Path: test/com/Upwork/api/Routers/AuthTest.java import static org.junit.Assert.*; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Auth; package com.Upwork.api.Routers; @RunWith(PowerMockRunner.class) @PrepareForTest({ Auth.class })
public class AuthTest extends Helper {
upwork/java-upwork
test/com/Upwork/api/Routers/MetadataTest.java
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Metadata.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Metadata { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Metadata(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get Categories // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getCategories() throws JSONException { // return oClient.get("/profiles/v1/metadata/categories"); // } // // /** // * Get Categories (v2) // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getCategoriesV2() throws JSONException { // return oClient.get("/profiles/v2/metadata/categories"); // } // // /** // * Get Skills // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSkills() throws JSONException { // return oClient.get("/profiles/v1/metadata/skills"); // } // // /** // * Get Skills V2 // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSkillsV2() throws JSONException { // return oClient.get("/profiles/v2/metadata/skills"); // } // // /** // * Get Specialties // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecialties() throws JSONException { // return oClient.get("/profiles/v1/metadata/specialties"); // } // // /** // * Get regions // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getRegions() throws JSONException { // return oClient.get("/profiles/v1/metadata/regions"); // } // // /** // * Get tests // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getTests() throws JSONException { // return oClient.get("/profiles/v1/metadata/tests"); // } // // /** // * Get reasons // * // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getReasons(HashMap<String, String> params) throws JSONException { // return oClient.get("/profiles/v1/metadata/reasons", params); // } // // }
import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Metadata;
package com.Upwork.api.Routers; @RunWith(PowerMockRunner.class) @PrepareForTest({
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Metadata.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Metadata { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Metadata(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get Categories // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getCategories() throws JSONException { // return oClient.get("/profiles/v1/metadata/categories"); // } // // /** // * Get Categories (v2) // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getCategoriesV2() throws JSONException { // return oClient.get("/profiles/v2/metadata/categories"); // } // // /** // * Get Skills // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSkills() throws JSONException { // return oClient.get("/profiles/v1/metadata/skills"); // } // // /** // * Get Skills V2 // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSkillsV2() throws JSONException { // return oClient.get("/profiles/v2/metadata/skills"); // } // // /** // * Get Specialties // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecialties() throws JSONException { // return oClient.get("/profiles/v1/metadata/specialties"); // } // // /** // * Get regions // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getRegions() throws JSONException { // return oClient.get("/profiles/v1/metadata/regions"); // } // // /** // * Get tests // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getTests() throws JSONException { // return oClient.get("/profiles/v1/metadata/tests"); // } // // /** // * Get reasons // * // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getReasons(HashMap<String, String> params) throws JSONException { // return oClient.get("/profiles/v1/metadata/reasons", params); // } // // } // Path: test/com/Upwork/api/Routers/MetadataTest.java import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Metadata; package com.Upwork.api.Routers; @RunWith(PowerMockRunner.class) @PrepareForTest({
Metadata.class
upwork/java-upwork
test/com/Upwork/api/Routers/MetadataTest.java
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Metadata.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Metadata { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Metadata(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get Categories // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getCategories() throws JSONException { // return oClient.get("/profiles/v1/metadata/categories"); // } // // /** // * Get Categories (v2) // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getCategoriesV2() throws JSONException { // return oClient.get("/profiles/v2/metadata/categories"); // } // // /** // * Get Skills // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSkills() throws JSONException { // return oClient.get("/profiles/v1/metadata/skills"); // } // // /** // * Get Skills V2 // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSkillsV2() throws JSONException { // return oClient.get("/profiles/v2/metadata/skills"); // } // // /** // * Get Specialties // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecialties() throws JSONException { // return oClient.get("/profiles/v1/metadata/specialties"); // } // // /** // * Get regions // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getRegions() throws JSONException { // return oClient.get("/profiles/v1/metadata/regions"); // } // // /** // * Get tests // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getTests() throws JSONException { // return oClient.get("/profiles/v1/metadata/tests"); // } // // /** // * Get reasons // * // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getReasons(HashMap<String, String> params) throws JSONException { // return oClient.get("/profiles/v1/metadata/reasons", params); // } // // }
import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Metadata;
package com.Upwork.api.Routers; @RunWith(PowerMockRunner.class) @PrepareForTest({ Metadata.class })
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Metadata.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Metadata { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Metadata(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get Categories // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getCategories() throws JSONException { // return oClient.get("/profiles/v1/metadata/categories"); // } // // /** // * Get Categories (v2) // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getCategoriesV2() throws JSONException { // return oClient.get("/profiles/v2/metadata/categories"); // } // // /** // * Get Skills // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSkills() throws JSONException { // return oClient.get("/profiles/v1/metadata/skills"); // } // // /** // * Get Skills V2 // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSkillsV2() throws JSONException { // return oClient.get("/profiles/v2/metadata/skills"); // } // // /** // * Get Specialties // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecialties() throws JSONException { // return oClient.get("/profiles/v1/metadata/specialties"); // } // // /** // * Get regions // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getRegions() throws JSONException { // return oClient.get("/profiles/v1/metadata/regions"); // } // // /** // * Get tests // * // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getTests() throws JSONException { // return oClient.get("/profiles/v1/metadata/tests"); // } // // /** // * Get reasons // * // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getReasons(HashMap<String, String> params) throws JSONException { // return oClient.get("/profiles/v1/metadata/reasons", params); // } // // } // Path: test/com/Upwork/api/Routers/MetadataTest.java import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Metadata; package com.Upwork.api.Routers; @RunWith(PowerMockRunner.class) @PrepareForTest({ Metadata.class })
public class MetadataTest extends Helper {
upwork/java-upwork
test/com/Upwork/api/Routers/Hr/EngagementsTest.java
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Hr/Engagements.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Engagements { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Engagements(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get list of engagements // * // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getList(HashMap<String, String> params) throws JSONException { // return oClient.get("/hr/v2/engagements", params); // } // // /** // * Get specific engagement // * // * @param reference Engagement's reference // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecific(String reference) throws JSONException { // return oClient.get("/hr/v2/engagements/" + reference); // } // // }
import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Hr.Engagements;
package com.Upwork.api.Routers.Hr; @RunWith(PowerMockRunner.class) @PrepareForTest({
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Hr/Engagements.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Engagements { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Engagements(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get list of engagements // * // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getList(HashMap<String, String> params) throws JSONException { // return oClient.get("/hr/v2/engagements", params); // } // // /** // * Get specific engagement // * // * @param reference Engagement's reference // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecific(String reference) throws JSONException { // return oClient.get("/hr/v2/engagements/" + reference); // } // // } // Path: test/com/Upwork/api/Routers/Hr/EngagementsTest.java import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Hr.Engagements; package com.Upwork.api.Routers.Hr; @RunWith(PowerMockRunner.class) @PrepareForTest({
Engagements.class
upwork/java-upwork
test/com/Upwork/api/Routers/Hr/EngagementsTest.java
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Hr/Engagements.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Engagements { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Engagements(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get list of engagements // * // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getList(HashMap<String, String> params) throws JSONException { // return oClient.get("/hr/v2/engagements", params); // } // // /** // * Get specific engagement // * // * @param reference Engagement's reference // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecific(String reference) throws JSONException { // return oClient.get("/hr/v2/engagements/" + reference); // } // // }
import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Hr.Engagements;
package com.Upwork.api.Routers.Hr; @RunWith(PowerMockRunner.class) @PrepareForTest({ Engagements.class })
// Path: test/com/Upwork/api/Routers/Helper.java // @RunWith(PowerMockRunner.class) // public class Helper { // @Mock // protected OAuthClient client; // // @Before // public void setUp() throws JSONException { // MockitoAnnotations.initMocks(this); // when(client.get(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.get(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.post(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.put(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString())).thenReturn(new JSONObject("{'key': 'value'}")); // when(client.delete(Matchers.anyString(), (HashMap<String, String>) Matchers.anyObject())).thenReturn(new JSONObject("{'key': 'value'}")); // } // } // // Path: src/com/Upwork/api/Routers/Hr/Engagements.java // @ClassPreamble ( // author = "Maksym Novozhylov <mnovozhilov@upwork.com>", // date = "6/4/2014", // currentRevision = 1, // lastModified = "6/4/2014", // lastModifiedBy = "Maksym Novozhylov", // reviewers = {"Yiota Tsakiri"} // ) // public final class Engagements { // // final static String ENTRY_POINT = "api"; // // private OAuthClient oClient = null; // // public Engagements(OAuthClient client) { // oClient = client; // oClient.setEntryPoint(ENTRY_POINT); // } // // /** // * Get list of engagements // * // * @param params Parameters // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getList(HashMap<String, String> params) throws JSONException { // return oClient.get("/hr/v2/engagements", params); // } // // /** // * Get specific engagement // * // * @param reference Engagement's reference // * @throws JSONException If error occurred // * @return {@link JSONObject} // */ // public JSONObject getSpecific(String reference) throws JSONException { // return oClient.get("/hr/v2/engagements/" + reference); // } // // } // Path: test/com/Upwork/api/Routers/Hr/EngagementsTest.java import static org.junit.Assert.*; import java.util.HashMap; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.Upwork.api.Routers.Helper; import com.Upwork.api.Routers.Hr.Engagements; package com.Upwork.api.Routers.Hr; @RunWith(PowerMockRunner.class) @PrepareForTest({ Engagements.class })
public class EngagementsTest extends Helper {
silkimen/cordova-plugin-advanced-http
src/android/com/silkimen/http/TLSConfiguration.java
// Path: src/android/com/silkimen/http/TLSSocketFactory.java // public class TLSSocketFactory extends SSLSocketFactory { // // private SSLSocketFactory delegate; // private List<String> blacklistedProtocols; // // public TLSSocketFactory(SSLContext context, String[] blacklistedProtocols) { // this.delegate = context.getSocketFactory(); // this.blacklistedProtocols = new ArrayList(); // // for (int i = 0; i < blacklistedProtocols.length; ++i) { // this.blacklistedProtocols.add(blacklistedProtocols[i].trim()); // } // } // // @Override // public String[] getDefaultCipherSuites() { // return delegate.getDefaultCipherSuites(); // } // // @Override // public String[] getSupportedCipherSuites() { // return delegate.getSupportedCipherSuites(); // } // // @Override // public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { // return enableTLSOnSocket(delegate.createSocket(socket, host, port, autoClose)); // } // // @Override // public Socket createSocket(String host, int port) throws IOException, UnknownHostException { // return enableTLSOnSocket(delegate.createSocket(host, port)); // } // // @Override // public Socket createSocket(String host, int port, InetAddress localHost, int localPort) // throws IOException, UnknownHostException { // return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort)); // } // // @Override // public Socket createSocket(InetAddress host, int port) throws IOException { // return enableTLSOnSocket(delegate.createSocket(host, port)); // } // // @Override // public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) // throws IOException { // return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort)); // } // // private Socket enableTLSOnSocket(Socket socket) { // if (socket == null || !(socket instanceof SSLSocket)) { // return socket; // } // // String[] supported = ((SSLSocket) socket).getSupportedProtocols(); // List<String> filtered = new ArrayList(); // // for (int i = 0; i < supported.length; ++i) { // if (!this.blacklistedProtocols.contains(supported[i])) { // filtered.add(supported[i]); // } // } // // ((SSLSocket) socket).setEnabledProtocols(filtered.toArray(new String[0])); // // return socket; // } // }
import java.io.IOException; import java.security.GeneralSecurityException; import java.security.SecureRandom; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import com.silkimen.http.TLSSocketFactory;
} public void setKeyManagers(KeyManager[] keyManagers) { this.keyManagers = keyManagers; this.socketFactory = null; } public void setTrustManagers(TrustManager[] trustManagers) { this.trustManagers = trustManagers; this.socketFactory = null; } public void setBlacklistedProtocols(String[] protocols) { this.blacklistedProtocols = protocols; this.socketFactory = null; } public HostnameVerifier getHostnameVerifier() { return this.hostnameVerifier; } public SSLSocketFactory getTLSSocketFactory() throws IOException { if (this.socketFactory != null) { return this.socketFactory; } try { SSLContext context = SSLContext.getInstance("TLS"); context.init(this.keyManagers, this.trustManagers, new SecureRandom());
// Path: src/android/com/silkimen/http/TLSSocketFactory.java // public class TLSSocketFactory extends SSLSocketFactory { // // private SSLSocketFactory delegate; // private List<String> blacklistedProtocols; // // public TLSSocketFactory(SSLContext context, String[] blacklistedProtocols) { // this.delegate = context.getSocketFactory(); // this.blacklistedProtocols = new ArrayList(); // // for (int i = 0; i < blacklistedProtocols.length; ++i) { // this.blacklistedProtocols.add(blacklistedProtocols[i].trim()); // } // } // // @Override // public String[] getDefaultCipherSuites() { // return delegate.getDefaultCipherSuites(); // } // // @Override // public String[] getSupportedCipherSuites() { // return delegate.getSupportedCipherSuites(); // } // // @Override // public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { // return enableTLSOnSocket(delegate.createSocket(socket, host, port, autoClose)); // } // // @Override // public Socket createSocket(String host, int port) throws IOException, UnknownHostException { // return enableTLSOnSocket(delegate.createSocket(host, port)); // } // // @Override // public Socket createSocket(String host, int port, InetAddress localHost, int localPort) // throws IOException, UnknownHostException { // return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort)); // } // // @Override // public Socket createSocket(InetAddress host, int port) throws IOException { // return enableTLSOnSocket(delegate.createSocket(host, port)); // } // // @Override // public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) // throws IOException { // return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort)); // } // // private Socket enableTLSOnSocket(Socket socket) { // if (socket == null || !(socket instanceof SSLSocket)) { // return socket; // } // // String[] supported = ((SSLSocket) socket).getSupportedProtocols(); // List<String> filtered = new ArrayList(); // // for (int i = 0; i < supported.length; ++i) { // if (!this.blacklistedProtocols.contains(supported[i])) { // filtered.add(supported[i]); // } // } // // ((SSLSocket) socket).setEnabledProtocols(filtered.toArray(new String[0])); // // return socket; // } // } // Path: src/android/com/silkimen/http/TLSConfiguration.java import java.io.IOException; import java.security.GeneralSecurityException; import java.security.SecureRandom; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import com.silkimen.http.TLSSocketFactory; } public void setKeyManagers(KeyManager[] keyManagers) { this.keyManagers = keyManagers; this.socketFactory = null; } public void setTrustManagers(TrustManager[] trustManagers) { this.trustManagers = trustManagers; this.socketFactory = null; } public void setBlacklistedProtocols(String[] protocols) { this.blacklistedProtocols = protocols; this.socketFactory = null; } public HostnameVerifier getHostnameVerifier() { return this.hostnameVerifier; } public SSLSocketFactory getTLSSocketFactory() throws IOException { if (this.socketFactory != null) { return this.socketFactory; } try { SSLContext context = SSLContext.getInstance("TLS"); context.init(this.keyManagers, this.trustManagers, new SecureRandom());
this.socketFactory = new TLSSocketFactory(context, this.blacklistedProtocols);
silkimen/cordova-plugin-advanced-http
src/android/com/silkimen/cordovahttp/CordovaHttpOperation.java
// Path: src/android/com/silkimen/http/TLSConfiguration.java // public class TLSConfiguration { // private TrustManager[] trustManagers = null; // private KeyManager[] keyManagers = null; // private HostnameVerifier hostnameVerifier = null; // private String[] blacklistedProtocols = {}; // // private SSLSocketFactory socketFactory; // // public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { // this.hostnameVerifier = hostnameVerifier; // } // // public void setKeyManagers(KeyManager[] keyManagers) { // this.keyManagers = keyManagers; // this.socketFactory = null; // } // // public void setTrustManagers(TrustManager[] trustManagers) { // this.trustManagers = trustManagers; // this.socketFactory = null; // } // // public void setBlacklistedProtocols(String[] protocols) { // this.blacklistedProtocols = protocols; // this.socketFactory = null; // } // // public HostnameVerifier getHostnameVerifier() { // return this.hostnameVerifier; // } // // public SSLSocketFactory getTLSSocketFactory() throws IOException { // if (this.socketFactory != null) { // return this.socketFactory; // } // // try { // SSLContext context = SSLContext.getInstance("TLS"); // // context.init(this.keyManagers, this.trustManagers, new SecureRandom()); // this.socketFactory = new TLSSocketFactory(context, this.blacklistedProtocols); // // return this.socketFactory; // } catch (GeneralSecurityException e) { // IOException ioException = new IOException("Security exception occured while configuring TLS context"); // ioException.initCause(e); // throw ioException; // } // } // }
import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSocketFactory; import com.silkimen.http.TLSConfiguration; import org.json.JSONObject;
package com.silkimen.cordovahttp; class CordovaHttpOperation extends CordovaHttpBase { public CordovaHttpOperation(String method, String url, String serializer, Object data, JSONObject headers,
// Path: src/android/com/silkimen/http/TLSConfiguration.java // public class TLSConfiguration { // private TrustManager[] trustManagers = null; // private KeyManager[] keyManagers = null; // private HostnameVerifier hostnameVerifier = null; // private String[] blacklistedProtocols = {}; // // private SSLSocketFactory socketFactory; // // public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { // this.hostnameVerifier = hostnameVerifier; // } // // public void setKeyManagers(KeyManager[] keyManagers) { // this.keyManagers = keyManagers; // this.socketFactory = null; // } // // public void setTrustManagers(TrustManager[] trustManagers) { // this.trustManagers = trustManagers; // this.socketFactory = null; // } // // public void setBlacklistedProtocols(String[] protocols) { // this.blacklistedProtocols = protocols; // this.socketFactory = null; // } // // public HostnameVerifier getHostnameVerifier() { // return this.hostnameVerifier; // } // // public SSLSocketFactory getTLSSocketFactory() throws IOException { // if (this.socketFactory != null) { // return this.socketFactory; // } // // try { // SSLContext context = SSLContext.getInstance("TLS"); // // context.init(this.keyManagers, this.trustManagers, new SecureRandom()); // this.socketFactory = new TLSSocketFactory(context, this.blacklistedProtocols); // // return this.socketFactory; // } catch (GeneralSecurityException e) { // IOException ioException = new IOException("Security exception occured while configuring TLS context"); // ioException.initCause(e); // throw ioException; // } // } // } // Path: src/android/com/silkimen/cordovahttp/CordovaHttpOperation.java import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSocketFactory; import com.silkimen.http.TLSConfiguration; import org.json.JSONObject; package com.silkimen.cordovahttp; class CordovaHttpOperation extends CordovaHttpBase { public CordovaHttpOperation(String method, String url, String serializer, Object data, JSONObject headers,
int connectTimeout, int readTimeout, boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration,
silkimen/cordova-plugin-advanced-http
src/android/com/silkimen/cordovahttp/CordovaServerTrust.java
// Path: src/android/com/silkimen/http/TLSConfiguration.java // public class TLSConfiguration { // private TrustManager[] trustManagers = null; // private KeyManager[] keyManagers = null; // private HostnameVerifier hostnameVerifier = null; // private String[] blacklistedProtocols = {}; // // private SSLSocketFactory socketFactory; // // public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { // this.hostnameVerifier = hostnameVerifier; // } // // public void setKeyManagers(KeyManager[] keyManagers) { // this.keyManagers = keyManagers; // this.socketFactory = null; // } // // public void setTrustManagers(TrustManager[] trustManagers) { // this.trustManagers = trustManagers; // this.socketFactory = null; // } // // public void setBlacklistedProtocols(String[] protocols) { // this.blacklistedProtocols = protocols; // this.socketFactory = null; // } // // public HostnameVerifier getHostnameVerifier() { // return this.hostnameVerifier; // } // // public SSLSocketFactory getTLSSocketFactory() throws IOException { // if (this.socketFactory != null) { // return this.socketFactory; // } // // try { // SSLContext context = SSLContext.getInstance("TLS"); // // context.init(this.keyManagers, this.trustManagers, new SecureRandom()); // this.socketFactory = new TLSSocketFactory(context, this.blacklistedProtocols); // // return this.socketFactory; // } catch (GeneralSecurityException e) { // IOException ioException = new IOException("Security exception occured while configuring TLS context"); // ioException.initCause(e); // throw ioException; // } // } // }
import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import com.silkimen.http.TLSConfiguration; import org.apache.cordova.CallbackContext; import android.app.Activity; import android.util.Log; import android.content.res.AssetManager; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager;
package com.silkimen.cordovahttp; class CordovaServerTrust implements Runnable { private static final String TAG = "Cordova-Plugin-HTTP"; private final TrustManager[] noOpTrustManagers; private final HostnameVerifier noOpVerifier; private String mode; private Activity activity;
// Path: src/android/com/silkimen/http/TLSConfiguration.java // public class TLSConfiguration { // private TrustManager[] trustManagers = null; // private KeyManager[] keyManagers = null; // private HostnameVerifier hostnameVerifier = null; // private String[] blacklistedProtocols = {}; // // private SSLSocketFactory socketFactory; // // public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { // this.hostnameVerifier = hostnameVerifier; // } // // public void setKeyManagers(KeyManager[] keyManagers) { // this.keyManagers = keyManagers; // this.socketFactory = null; // } // // public void setTrustManagers(TrustManager[] trustManagers) { // this.trustManagers = trustManagers; // this.socketFactory = null; // } // // public void setBlacklistedProtocols(String[] protocols) { // this.blacklistedProtocols = protocols; // this.socketFactory = null; // } // // public HostnameVerifier getHostnameVerifier() { // return this.hostnameVerifier; // } // // public SSLSocketFactory getTLSSocketFactory() throws IOException { // if (this.socketFactory != null) { // return this.socketFactory; // } // // try { // SSLContext context = SSLContext.getInstance("TLS"); // // context.init(this.keyManagers, this.trustManagers, new SecureRandom()); // this.socketFactory = new TLSSocketFactory(context, this.blacklistedProtocols); // // return this.socketFactory; // } catch (GeneralSecurityException e) { // IOException ioException = new IOException("Security exception occured while configuring TLS context"); // ioException.initCause(e); // throw ioException; // } // } // } // Path: src/android/com/silkimen/cordovahttp/CordovaServerTrust.java import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import com.silkimen.http.TLSConfiguration; import org.apache.cordova.CallbackContext; import android.app.Activity; import android.util.Log; import android.content.res.AssetManager; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; package com.silkimen.cordovahttp; class CordovaServerTrust implements Runnable { private static final String TAG = "Cordova-Plugin-HTTP"; private final TrustManager[] noOpTrustManagers; private final HostnameVerifier noOpVerifier; private String mode; private Activity activity;
private TLSConfiguration tlsConfiguration;
silkimen/cordova-plugin-advanced-http
src/android/com/silkimen/cordovahttp/CordovaHttpPlugin.java
// Path: src/android/com/silkimen/http/TLSConfiguration.java // public class TLSConfiguration { // private TrustManager[] trustManagers = null; // private KeyManager[] keyManagers = null; // private HostnameVerifier hostnameVerifier = null; // private String[] blacklistedProtocols = {}; // // private SSLSocketFactory socketFactory; // // public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { // this.hostnameVerifier = hostnameVerifier; // } // // public void setKeyManagers(KeyManager[] keyManagers) { // this.keyManagers = keyManagers; // this.socketFactory = null; // } // // public void setTrustManagers(TrustManager[] trustManagers) { // this.trustManagers = trustManagers; // this.socketFactory = null; // } // // public void setBlacklistedProtocols(String[] protocols) { // this.blacklistedProtocols = protocols; // this.socketFactory = null; // } // // public HostnameVerifier getHostnameVerifier() { // return this.hostnameVerifier; // } // // public SSLSocketFactory getTLSSocketFactory() throws IOException { // if (this.socketFactory != null) { // return this.socketFactory; // } // // try { // SSLContext context = SSLContext.getInstance("TLS"); // // context.init(this.keyManagers, this.trustManagers, new SecureRandom()); // this.socketFactory = new TLSSocketFactory(context, this.blacklistedProtocols); // // return this.socketFactory; // } catch (GeneralSecurityException e) { // IOException ioException = new IOException("Security exception occured while configuring TLS context"); // ioException.initCause(e); // throw ioException; // } // } // }
import java.security.KeyStore; import java.util.HashMap; import java.util.Observable; import java.util.Observer; import java.util.concurrent.Future; import com.silkimen.http.TLSConfiguration; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import android.util.Base64; import javax.net.ssl.TrustManagerFactory;
package com.silkimen.cordovahttp; public class CordovaHttpPlugin extends CordovaPlugin implements Observer { private static final String TAG = "Cordova-Plugin-HTTP";
// Path: src/android/com/silkimen/http/TLSConfiguration.java // public class TLSConfiguration { // private TrustManager[] trustManagers = null; // private KeyManager[] keyManagers = null; // private HostnameVerifier hostnameVerifier = null; // private String[] blacklistedProtocols = {}; // // private SSLSocketFactory socketFactory; // // public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { // this.hostnameVerifier = hostnameVerifier; // } // // public void setKeyManagers(KeyManager[] keyManagers) { // this.keyManagers = keyManagers; // this.socketFactory = null; // } // // public void setTrustManagers(TrustManager[] trustManagers) { // this.trustManagers = trustManagers; // this.socketFactory = null; // } // // public void setBlacklistedProtocols(String[] protocols) { // this.blacklistedProtocols = protocols; // this.socketFactory = null; // } // // public HostnameVerifier getHostnameVerifier() { // return this.hostnameVerifier; // } // // public SSLSocketFactory getTLSSocketFactory() throws IOException { // if (this.socketFactory != null) { // return this.socketFactory; // } // // try { // SSLContext context = SSLContext.getInstance("TLS"); // // context.init(this.keyManagers, this.trustManagers, new SecureRandom()); // this.socketFactory = new TLSSocketFactory(context, this.blacklistedProtocols); // // return this.socketFactory; // } catch (GeneralSecurityException e) { // IOException ioException = new IOException("Security exception occured while configuring TLS context"); // ioException.initCause(e); // throw ioException; // } // } // } // Path: src/android/com/silkimen/cordovahttp/CordovaHttpPlugin.java import java.security.KeyStore; import java.util.HashMap; import java.util.Observable; import java.util.Observer; import java.util.concurrent.Future; import com.silkimen.http.TLSConfiguration; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import android.util.Base64; import javax.net.ssl.TrustManagerFactory; package com.silkimen.cordovahttp; public class CordovaHttpPlugin extends CordovaPlugin implements Observer { private static final String TAG = "Cordova-Plugin-HTTP";
private TLSConfiguration tlsConfiguration;
silkimen/cordova-plugin-advanced-http
src/android/com/silkimen/cordovahttp/CordovaClientAuth.java
// Path: src/android/com/silkimen/http/KeyChainKeyManager.java // public class KeyChainKeyManager extends X509ExtendedKeyManager { // private final String alias; // private final X509Certificate[] chain; // private final PrivateKey key; // // public KeyChainKeyManager(String alias, PrivateKey key, X509Certificate[] chain) { // this.alias = alias; // this.key = key; // this.chain = chain; // } // // @Override // public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) { // return this.alias; // } // // @Override // public X509Certificate[] getCertificateChain(String alias) { // return chain; // } // // @Override // public PrivateKey getPrivateKey(String alias) { // return key; // } // // @Override // public final String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { // // not a client SSLSocket callback // throw new UnsupportedOperationException(); // } // // @Override // public final String[] getClientAliases(String keyType, Principal[] issuers) { // // not a client SSLSocket callback // throw new UnsupportedOperationException(); // } // // @Override // public final String[] getServerAliases(String keyType, Principal[] issuers) { // // not a client SSLSocket callback // throw new UnsupportedOperationException(); // } // } // // Path: src/android/com/silkimen/http/TLSConfiguration.java // public class TLSConfiguration { // private TrustManager[] trustManagers = null; // private KeyManager[] keyManagers = null; // private HostnameVerifier hostnameVerifier = null; // private String[] blacklistedProtocols = {}; // // private SSLSocketFactory socketFactory; // // public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { // this.hostnameVerifier = hostnameVerifier; // } // // public void setKeyManagers(KeyManager[] keyManagers) { // this.keyManagers = keyManagers; // this.socketFactory = null; // } // // public void setTrustManagers(TrustManager[] trustManagers) { // this.trustManagers = trustManagers; // this.socketFactory = null; // } // // public void setBlacklistedProtocols(String[] protocols) { // this.blacklistedProtocols = protocols; // this.socketFactory = null; // } // // public HostnameVerifier getHostnameVerifier() { // return this.hostnameVerifier; // } // // public SSLSocketFactory getTLSSocketFactory() throws IOException { // if (this.socketFactory != null) { // return this.socketFactory; // } // // try { // SSLContext context = SSLContext.getInstance("TLS"); // // context.init(this.keyManagers, this.trustManagers, new SecureRandom()); // this.socketFactory = new TLSSocketFactory(context, this.blacklistedProtocols); // // return this.socketFactory; // } catch (GeneralSecurityException e) { // IOException ioException = new IOException("Security exception occured while configuring TLS context"); // ioException.initCause(e); // throw ioException; // } // } // }
import android.app.Activity; import android.content.Context; import android.security.KeyChain; import android.security.KeyChainAliasCallback; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URI; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.X509Certificate; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import org.apache.cordova.CallbackContext; import com.silkimen.http.KeyChainKeyManager; import com.silkimen.http.TLSConfiguration;
package com.silkimen.cordovahttp; class CordovaClientAuth implements Runnable, KeyChainAliasCallback { private static final String TAG = "Cordova-Plugin-HTTP"; private String mode; private String aliasString; private byte[] rawPkcs; private String pkcsPassword; private Activity activity; private Context context;
// Path: src/android/com/silkimen/http/KeyChainKeyManager.java // public class KeyChainKeyManager extends X509ExtendedKeyManager { // private final String alias; // private final X509Certificate[] chain; // private final PrivateKey key; // // public KeyChainKeyManager(String alias, PrivateKey key, X509Certificate[] chain) { // this.alias = alias; // this.key = key; // this.chain = chain; // } // // @Override // public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) { // return this.alias; // } // // @Override // public X509Certificate[] getCertificateChain(String alias) { // return chain; // } // // @Override // public PrivateKey getPrivateKey(String alias) { // return key; // } // // @Override // public final String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { // // not a client SSLSocket callback // throw new UnsupportedOperationException(); // } // // @Override // public final String[] getClientAliases(String keyType, Principal[] issuers) { // // not a client SSLSocket callback // throw new UnsupportedOperationException(); // } // // @Override // public final String[] getServerAliases(String keyType, Principal[] issuers) { // // not a client SSLSocket callback // throw new UnsupportedOperationException(); // } // } // // Path: src/android/com/silkimen/http/TLSConfiguration.java // public class TLSConfiguration { // private TrustManager[] trustManagers = null; // private KeyManager[] keyManagers = null; // private HostnameVerifier hostnameVerifier = null; // private String[] blacklistedProtocols = {}; // // private SSLSocketFactory socketFactory; // // public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { // this.hostnameVerifier = hostnameVerifier; // } // // public void setKeyManagers(KeyManager[] keyManagers) { // this.keyManagers = keyManagers; // this.socketFactory = null; // } // // public void setTrustManagers(TrustManager[] trustManagers) { // this.trustManagers = trustManagers; // this.socketFactory = null; // } // // public void setBlacklistedProtocols(String[] protocols) { // this.blacklistedProtocols = protocols; // this.socketFactory = null; // } // // public HostnameVerifier getHostnameVerifier() { // return this.hostnameVerifier; // } // // public SSLSocketFactory getTLSSocketFactory() throws IOException { // if (this.socketFactory != null) { // return this.socketFactory; // } // // try { // SSLContext context = SSLContext.getInstance("TLS"); // // context.init(this.keyManagers, this.trustManagers, new SecureRandom()); // this.socketFactory = new TLSSocketFactory(context, this.blacklistedProtocols); // // return this.socketFactory; // } catch (GeneralSecurityException e) { // IOException ioException = new IOException("Security exception occured while configuring TLS context"); // ioException.initCause(e); // throw ioException; // } // } // } // Path: src/android/com/silkimen/cordovahttp/CordovaClientAuth.java import android.app.Activity; import android.content.Context; import android.security.KeyChain; import android.security.KeyChainAliasCallback; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URI; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.X509Certificate; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import org.apache.cordova.CallbackContext; import com.silkimen.http.KeyChainKeyManager; import com.silkimen.http.TLSConfiguration; package com.silkimen.cordovahttp; class CordovaClientAuth implements Runnable, KeyChainAliasCallback { private static final String TAG = "Cordova-Plugin-HTTP"; private String mode; private String aliasString; private byte[] rawPkcs; private String pkcsPassword; private Activity activity; private Context context;
private TLSConfiguration tlsConfiguration;
silkimen/cordova-plugin-advanced-http
src/android/com/silkimen/cordovahttp/CordovaClientAuth.java
// Path: src/android/com/silkimen/http/KeyChainKeyManager.java // public class KeyChainKeyManager extends X509ExtendedKeyManager { // private final String alias; // private final X509Certificate[] chain; // private final PrivateKey key; // // public KeyChainKeyManager(String alias, PrivateKey key, X509Certificate[] chain) { // this.alias = alias; // this.key = key; // this.chain = chain; // } // // @Override // public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) { // return this.alias; // } // // @Override // public X509Certificate[] getCertificateChain(String alias) { // return chain; // } // // @Override // public PrivateKey getPrivateKey(String alias) { // return key; // } // // @Override // public final String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { // // not a client SSLSocket callback // throw new UnsupportedOperationException(); // } // // @Override // public final String[] getClientAliases(String keyType, Principal[] issuers) { // // not a client SSLSocket callback // throw new UnsupportedOperationException(); // } // // @Override // public final String[] getServerAliases(String keyType, Principal[] issuers) { // // not a client SSLSocket callback // throw new UnsupportedOperationException(); // } // } // // Path: src/android/com/silkimen/http/TLSConfiguration.java // public class TLSConfiguration { // private TrustManager[] trustManagers = null; // private KeyManager[] keyManagers = null; // private HostnameVerifier hostnameVerifier = null; // private String[] blacklistedProtocols = {}; // // private SSLSocketFactory socketFactory; // // public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { // this.hostnameVerifier = hostnameVerifier; // } // // public void setKeyManagers(KeyManager[] keyManagers) { // this.keyManagers = keyManagers; // this.socketFactory = null; // } // // public void setTrustManagers(TrustManager[] trustManagers) { // this.trustManagers = trustManagers; // this.socketFactory = null; // } // // public void setBlacklistedProtocols(String[] protocols) { // this.blacklistedProtocols = protocols; // this.socketFactory = null; // } // // public HostnameVerifier getHostnameVerifier() { // return this.hostnameVerifier; // } // // public SSLSocketFactory getTLSSocketFactory() throws IOException { // if (this.socketFactory != null) { // return this.socketFactory; // } // // try { // SSLContext context = SSLContext.getInstance("TLS"); // // context.init(this.keyManagers, this.trustManagers, new SecureRandom()); // this.socketFactory = new TLSSocketFactory(context, this.blacklistedProtocols); // // return this.socketFactory; // } catch (GeneralSecurityException e) { // IOException ioException = new IOException("Security exception occured while configuring TLS context"); // ioException.initCause(e); // throw ioException; // } // } // }
import android.app.Activity; import android.content.Context; import android.security.KeyChain; import android.security.KeyChainAliasCallback; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URI; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.X509Certificate; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import org.apache.cordova.CallbackContext; import com.silkimen.http.KeyChainKeyManager; import com.silkimen.http.TLSConfiguration;
KeyStore keyStore = KeyStore.getInstance("PKCS12"); String keyManagerFactoryAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm); ByteArrayInputStream stream = new ByteArrayInputStream(this.rawPkcs); keyStore.load(stream, this.pkcsPassword.toCharArray()); keyManagerFactory.init(keyStore, this.pkcsPassword.toCharArray()); this.tlsConfiguration.setKeyManagers(keyManagerFactory.getKeyManagers()); this.callbackContext.success(); } catch (Exception e) { Log.e(TAG, "Couldn't load given PKCS12 container for authentication", e); this.callbackContext.error("Couldn't load given PKCS12 container for authentication"); } } private void disableClientAuth() { this.tlsConfiguration.setKeyManagers(null); this.callbackContext.success(); } @Override public void alias(final String alias) { try { if (alias == null) { throw new Exception("Couldn't get a consent for private key access"); } PrivateKey key = KeyChain.getPrivateKey(this.context, alias); X509Certificate[] chain = KeyChain.getCertificateChain(this.context, alias);
// Path: src/android/com/silkimen/http/KeyChainKeyManager.java // public class KeyChainKeyManager extends X509ExtendedKeyManager { // private final String alias; // private final X509Certificate[] chain; // private final PrivateKey key; // // public KeyChainKeyManager(String alias, PrivateKey key, X509Certificate[] chain) { // this.alias = alias; // this.key = key; // this.chain = chain; // } // // @Override // public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) { // return this.alias; // } // // @Override // public X509Certificate[] getCertificateChain(String alias) { // return chain; // } // // @Override // public PrivateKey getPrivateKey(String alias) { // return key; // } // // @Override // public final String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { // // not a client SSLSocket callback // throw new UnsupportedOperationException(); // } // // @Override // public final String[] getClientAliases(String keyType, Principal[] issuers) { // // not a client SSLSocket callback // throw new UnsupportedOperationException(); // } // // @Override // public final String[] getServerAliases(String keyType, Principal[] issuers) { // // not a client SSLSocket callback // throw new UnsupportedOperationException(); // } // } // // Path: src/android/com/silkimen/http/TLSConfiguration.java // public class TLSConfiguration { // private TrustManager[] trustManagers = null; // private KeyManager[] keyManagers = null; // private HostnameVerifier hostnameVerifier = null; // private String[] blacklistedProtocols = {}; // // private SSLSocketFactory socketFactory; // // public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { // this.hostnameVerifier = hostnameVerifier; // } // // public void setKeyManagers(KeyManager[] keyManagers) { // this.keyManagers = keyManagers; // this.socketFactory = null; // } // // public void setTrustManagers(TrustManager[] trustManagers) { // this.trustManagers = trustManagers; // this.socketFactory = null; // } // // public void setBlacklistedProtocols(String[] protocols) { // this.blacklistedProtocols = protocols; // this.socketFactory = null; // } // // public HostnameVerifier getHostnameVerifier() { // return this.hostnameVerifier; // } // // public SSLSocketFactory getTLSSocketFactory() throws IOException { // if (this.socketFactory != null) { // return this.socketFactory; // } // // try { // SSLContext context = SSLContext.getInstance("TLS"); // // context.init(this.keyManagers, this.trustManagers, new SecureRandom()); // this.socketFactory = new TLSSocketFactory(context, this.blacklistedProtocols); // // return this.socketFactory; // } catch (GeneralSecurityException e) { // IOException ioException = new IOException("Security exception occured while configuring TLS context"); // ioException.initCause(e); // throw ioException; // } // } // } // Path: src/android/com/silkimen/cordovahttp/CordovaClientAuth.java import android.app.Activity; import android.content.Context; import android.security.KeyChain; import android.security.KeyChainAliasCallback; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URI; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.X509Certificate; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import org.apache.cordova.CallbackContext; import com.silkimen.http.KeyChainKeyManager; import com.silkimen.http.TLSConfiguration; KeyStore keyStore = KeyStore.getInstance("PKCS12"); String keyManagerFactoryAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm); ByteArrayInputStream stream = new ByteArrayInputStream(this.rawPkcs); keyStore.load(stream, this.pkcsPassword.toCharArray()); keyManagerFactory.init(keyStore, this.pkcsPassword.toCharArray()); this.tlsConfiguration.setKeyManagers(keyManagerFactory.getKeyManagers()); this.callbackContext.success(); } catch (Exception e) { Log.e(TAG, "Couldn't load given PKCS12 container for authentication", e); this.callbackContext.error("Couldn't load given PKCS12 container for authentication"); } } private void disableClientAuth() { this.tlsConfiguration.setKeyManagers(null); this.callbackContext.success(); } @Override public void alias(final String alias) { try { if (alias == null) { throw new Exception("Couldn't get a consent for private key access"); } PrivateKey key = KeyChain.getPrivateKey(this.context, alias); X509Certificate[] chain = KeyChain.getCertificateChain(this.context, alias);
KeyManager keyManager = new KeyChainKeyManager(alias, key, chain);
eponvert/upparse
java/upparse/corpus/BnInOEncoder.java
// Path: java/upparse/util/Ipredicate.java // public interface Ipredicate { // public boolean pred(int t); // }
import java.util.Arrays; import upparse.util.Ipredicate;
} private boolean isIState(int j) { if (j < 2) return false; final int r = reducedTagVal(j); return r == I; } private boolean isBState(int j) { if (j < 2) return false; final int r = reducedTagVal(j); return r == B; } private int reducedTagVal(int tag) { final int val = (tag - 2) % 2; return val + 2; } private boolean isOState(int j) { return j == O; } private boolean isStopState(int j) { return j == STOP; } @Override
// Path: java/upparse/util/Ipredicate.java // public interface Ipredicate { // public boolean pred(int t); // } // Path: java/upparse/corpus/BnInOEncoder.java import java.util.Arrays; import upparse.util.Ipredicate; } private boolean isIState(int j) { if (j < 2) return false; final int r = reducedTagVal(j); return r == I; } private boolean isBState(int j) { if (j < 2) return false; final int r = reducedTagVal(j); return r == B; } private int reducedTagVal(int tag) { final int val = (tag - 2) % 2; return val + 2; } private boolean isOState(int j) { return j == O; } private boolean isStopState(int j) { return j == STOP; } @Override
public Ipredicate isStopPred() {
eponvert/upparse
java/upparse/corpus/BnInLnOEncoder.java
// Path: java/upparse/util/Ipredicate.java // public interface Ipredicate { // public boolean pred(int t); // }
import java.util.Arrays; import upparse.util.Ipredicate;
} private boolean isBState(int j) { if (j < 2) return false; final int r = reducedTagVal(j); return r == B; } private boolean isLState(int j) { if (j < 2) return false; final int r = reducedTagVal(j); return r == L; } private int reducedTagVal(int tag) { final int val = (tag - 2) % 3; return val + 2; } private boolean isOState(int j) { return j == O; } private boolean isStopState(int j) { return j == STOP; } @Override
// Path: java/upparse/util/Ipredicate.java // public interface Ipredicate { // public boolean pred(int t); // } // Path: java/upparse/corpus/BnInLnOEncoder.java import java.util.Arrays; import upparse.util.Ipredicate; } private boolean isBState(int j) { if (j < 2) return false; final int r = reducedTagVal(j); return r == B; } private boolean isLState(int j) { if (j < 2) return false; final int r = reducedTagVal(j); return r == L; } private int reducedTagVal(int tag) { final int val = (tag - 2) % 3; return val + 2; } private boolean isOState(int j) { return j == O; } private boolean isStopState(int j) { return j == STOP; } @Override
public Ipredicate isStopPred() {
eponvert/upparse
java/upparse/eval/EvalManager.java
// Path: java/upparse/util/Util.java // public class Util { // // public static double sum(final double[] ds) { // double s = 0; // for (double d: ds) // s += d; // return s; // } // // public static double logadd(final double x, final double y) { // assert !Double.isNaN(y); // assert !Double.isNaN(x); // if (x <= Util.LOGEPS) // return y; // else if (y <= Util.LOGEPS) // return x; // else if (y <= x) // return x + log(1 + exp(y-x)); // else // return y + log(1 + exp(x-y)); // } // // static final double LOGEPS = -1e+16; // // public static double sum(double[][] ds) { // double s = 0; // for (double[] a: ds) // for (double b: a) // s += b; // return s; // } // // public static double countNonzero(double[] ds) { // int c = 0; // for (double d: ds) if (d != 0) c++; // return (double) c; // } // // public static int[][][] reverse(int[][][] corpus) { // int n = corpus.length; // int[][][] newCorpus = new int[n][][]; // for (int i = 0; i < n; i++) // newCorpus[i] = reverse(corpus[n - i - 1]); // return newCorpus; // } // // private static int[][] reverse(int[][] sent) { // int n = sent.length; // int[][] newSent = new int[n][]; // for (int i = 0; i < n; i++) // newSent[i] = reverse(sent[n - i - 1]); // return newSent; // } // // private static int[] reverse(int[] seg) { // int n = seg.length; // int[] newSeg = new int[n]; // for (int i = 0; i < n; i++) // newSeg[i] = seg[n - i - 1]; // return newSeg; // } // // public static int[][][][] reverse(int[][][][] corpus) { // int n = corpus.length; // int[][][][] newCorpus = new int[n][][][]; // for (int i = 0; i < n; i++) // newCorpus[i] = reverse(corpus[n-i-1]); // return newCorpus; // } // // public static BufferedWriter bufferedWriter(String filename) // throws IOException { // return new BufferedWriter(new OutputStreamWriter( // new FileOutputStream(new File(filename)), "UTF-8")); // } // }
import java.io.*; import java.util.*; import upparse.cli.*; import upparse.corpus.*; import upparse.util.Util;
ubsFromNPsEval = new TreebankEval("NPs Recall", npsGoldStandard.toUnlabeledBracketSetCorpus()); ubsFromPPsEval = new TreebankEval("PPs Recall", ppsGoldStandard.toUnlabeledBracketSetCorpus()); } public void evalParserOutput(final UnlabeledBracketSetCorpus output, final OutputManager man) throws CorpusError, EvalError, IOException { final ChunkedCorpus chunked = CorpusUtil.getChunkedCorpusClumps(alpha, output); treebankEval.getExperiment("asTrees", output.getTrees()).writeSummary( man.getResultsStream()); clumpsEval.addExperiment(clumpsEval .newChunkingExperiment("clumps", chunked)); clumpsEval.writeSummary(evalReportType, man.getResultsStream(), false); ubsFromClumpsEval.getExperiment("", output.getTrees()).writeSummary( man.getResultsStream()); npsEval.addExperiment(npsEval.newChunkingExperiment("NPs", chunked)); npsEval.writeSummary(evalReportType, man.getResultsStream(), false); ubsFromNPsEval.getExperiment("", output.getTrees()).writeSummary( man.getResultsStream()); ubsFromPPsEval.getExperiment("", output.getTrees()).writeSummary( man.getResultsStream()); if (!man.isNull()) {
// Path: java/upparse/util/Util.java // public class Util { // // public static double sum(final double[] ds) { // double s = 0; // for (double d: ds) // s += d; // return s; // } // // public static double logadd(final double x, final double y) { // assert !Double.isNaN(y); // assert !Double.isNaN(x); // if (x <= Util.LOGEPS) // return y; // else if (y <= Util.LOGEPS) // return x; // else if (y <= x) // return x + log(1 + exp(y-x)); // else // return y + log(1 + exp(x-y)); // } // // static final double LOGEPS = -1e+16; // // public static double sum(double[][] ds) { // double s = 0; // for (double[] a: ds) // for (double b: a) // s += b; // return s; // } // // public static double countNonzero(double[] ds) { // int c = 0; // for (double d: ds) if (d != 0) c++; // return (double) c; // } // // public static int[][][] reverse(int[][][] corpus) { // int n = corpus.length; // int[][][] newCorpus = new int[n][][]; // for (int i = 0; i < n; i++) // newCorpus[i] = reverse(corpus[n - i - 1]); // return newCorpus; // } // // private static int[][] reverse(int[][] sent) { // int n = sent.length; // int[][] newSent = new int[n][]; // for (int i = 0; i < n; i++) // newSent[i] = reverse(sent[n - i - 1]); // return newSent; // } // // private static int[] reverse(int[] seg) { // int n = seg.length; // int[] newSeg = new int[n]; // for (int i = 0; i < n; i++) // newSeg[i] = seg[n - i - 1]; // return newSeg; // } // // public static int[][][][] reverse(int[][][][] corpus) { // int n = corpus.length; // int[][][][] newCorpus = new int[n][][][]; // for (int i = 0; i < n; i++) // newCorpus[i] = reverse(corpus[n-i-1]); // return newCorpus; // } // // public static BufferedWriter bufferedWriter(String filename) // throws IOException { // return new BufferedWriter(new OutputStreamWriter( // new FileOutputStream(new File(filename)), "UTF-8")); // } // } // Path: java/upparse/eval/EvalManager.java import java.io.*; import java.util.*; import upparse.cli.*; import upparse.corpus.*; import upparse.util.Util; ubsFromNPsEval = new TreebankEval("NPs Recall", npsGoldStandard.toUnlabeledBracketSetCorpus()); ubsFromPPsEval = new TreebankEval("PPs Recall", ppsGoldStandard.toUnlabeledBracketSetCorpus()); } public void evalParserOutput(final UnlabeledBracketSetCorpus output, final OutputManager man) throws CorpusError, EvalError, IOException { final ChunkedCorpus chunked = CorpusUtil.getChunkedCorpusClumps(alpha, output); treebankEval.getExperiment("asTrees", output.getTrees()).writeSummary( man.getResultsStream()); clumpsEval.addExperiment(clumpsEval .newChunkingExperiment("clumps", chunked)); clumpsEval.writeSummary(evalReportType, man.getResultsStream(), false); ubsFromClumpsEval.getExperiment("", output.getTrees()).writeSummary( man.getResultsStream()); npsEval.addExperiment(npsEval.newChunkingExperiment("NPs", chunked)); npsEval.writeSummary(evalReportType, man.getResultsStream(), false); ubsFromNPsEval.getExperiment("", output.getTrees()).writeSummary( man.getResultsStream()); ubsFromPPsEval.getExperiment("", output.getTrees()).writeSummary( man.getResultsStream()); if (!man.isNull()) {
BufferedWriter bw = Util.bufferedWriter(man.treeOutputFilename());
spotify/spydra
spydra/src/test/java/com/spotify/spydra/historytools/DumpLogsCliParserTest.java
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpLogsCommand.java // @AutoValue // public abstract class DumpLogsCommand { // // DumpLogsCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String username(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpLogsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder username(String username); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpLogsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpLogsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test;
/*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpLogsCliParserTest { private static final DumpLogsCliParser PARSER = new DumpLogsCliParser(); private static final String DUMMY_APP_ID = "application_1345678910111_123456"; private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_USER = "rewt"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParse() {
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpLogsCommand.java // @AutoValue // public abstract class DumpLogsCommand { // // DumpLogsCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String username(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpLogsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder username(String username); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpLogsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/test/java/com/spotify/spydra/historytools/DumpLogsCliParserTest.java import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpLogsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test; /*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpLogsCliParserTest { private static final DumpLogsCliParser PARSER = new DumpLogsCliParser(); private static final String DUMMY_APP_ID = "application_1345678910111_123456"; private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_USER = "rewt"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParse() {
DumpLogsCommand dumpCmd = PARSER.parse(new String[]{
spotify/spydra
spydra/src/test/java/com/spotify/spydra/historytools/DumpLogsCliParserTest.java
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpLogsCommand.java // @AutoValue // public abstract class DumpLogsCommand { // // DumpLogsCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String username(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpLogsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder username(String username); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpLogsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpLogsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test;
/*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpLogsCliParserTest { private static final DumpLogsCliParser PARSER = new DumpLogsCliParser(); private static final String DUMMY_APP_ID = "application_1345678910111_123456"; private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_USER = "rewt"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParse() { DumpLogsCommand dumpCmd = PARSER.parse(new String[]{
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpLogsCommand.java // @AutoValue // public abstract class DumpLogsCommand { // // DumpLogsCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String username(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpLogsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder username(String username); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpLogsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/test/java/com/spotify/spydra/historytools/DumpLogsCliParserTest.java import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpLogsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test; /*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpLogsCliParserTest { private static final DumpLogsCliParser PARSER = new DumpLogsCliParser(); private static final String DUMMY_APP_ID = "application_1345678910111_123456"; private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_USER = "rewt"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParse() { DumpLogsCommand dumpCmd = PARSER.parse(new String[]{
CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID),
spotify/spydra
spydra/src/test/java/com/spotify/spydra/historytools/DumpLogsCliParserTest.java
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpLogsCommand.java // @AutoValue // public abstract class DumpLogsCommand { // // DumpLogsCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String username(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpLogsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder username(String username); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpLogsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpLogsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test;
/*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpLogsCliParserTest { private static final DumpLogsCliParser PARSER = new DumpLogsCliParser(); private static final String DUMMY_APP_ID = "application_1345678910111_123456"; private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_USER = "rewt"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParse() { DumpLogsCommand dumpCmd = PARSER.parse(new String[]{
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpLogsCommand.java // @AutoValue // public abstract class DumpLogsCommand { // // DumpLogsCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String username(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpLogsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder username(String username); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpLogsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/test/java/com/spotify/spydra/historytools/DumpLogsCliParserTest.java import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpLogsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test; /*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpLogsCliParserTest { private static final DumpLogsCliParser PARSER = new DumpLogsCliParser(); private static final String DUMMY_APP_ID = "application_1345678910111_123456"; private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_USER = "rewt"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParse() { DumpLogsCommand dumpCmd = PARSER.parse(new String[]{
CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID),
spotify/spydra
spydra/src/test/java/com/spotify/spydra/historytools/DumpLogsCliParserTest.java
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpLogsCommand.java // @AutoValue // public abstract class DumpLogsCommand { // // DumpLogsCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String username(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpLogsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder username(String username); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpLogsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpLogsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test;
CliTestHelpers.toStrOpt(CliConsts.USERNAME_OPTION_NAME, DUMMY_USER), CliTestHelpers.toStrOpt(CliConsts.LOG_BUCKET_OPTION_NAME, DUMMY_BUCKET) }); assertEquals(dumpCmd.applicationId().toString(), DUMMY_APP_ID); assertEquals(dumpCmd.clientId(), DUMMY_CLIENT_ID); assertEquals(dumpCmd.username(), DUMMY_USER); assertEquals(dumpCmd.logBucket(), DUMMY_BUCKET); } @Test public void testMissingArgs() { // Ensure options are mandatory List<String[]> failingLines = Arrays.asList( new String[]{ CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID) }, new String[]{ CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID) }, new String[]{ CliTestHelpers.toStrOpt(CliConsts.USERNAME_OPTION_NAME, DUMMY_USER) }, new String[]{ CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID), CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID), CliTestHelpers.toStrOpt(CliConsts.USERNAME_OPTION_NAME, DUMMY_USER) } );
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpLogsCommand.java // @AutoValue // public abstract class DumpLogsCommand { // // DumpLogsCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String username(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpLogsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder username(String username); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpLogsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/test/java/com/spotify/spydra/historytools/DumpLogsCliParserTest.java import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpLogsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test; CliTestHelpers.toStrOpt(CliConsts.USERNAME_OPTION_NAME, DUMMY_USER), CliTestHelpers.toStrOpt(CliConsts.LOG_BUCKET_OPTION_NAME, DUMMY_BUCKET) }); assertEquals(dumpCmd.applicationId().toString(), DUMMY_APP_ID); assertEquals(dumpCmd.clientId(), DUMMY_CLIENT_ID); assertEquals(dumpCmd.username(), DUMMY_USER); assertEquals(dumpCmd.logBucket(), DUMMY_BUCKET); } @Test public void testMissingArgs() { // Ensure options are mandatory List<String[]> failingLines = Arrays.asList( new String[]{ CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID) }, new String[]{ CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID) }, new String[]{ CliTestHelpers.toStrOpt(CliConsts.USERNAME_OPTION_NAME, DUMMY_USER) }, new String[]{ CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID), CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID), CliTestHelpers.toStrOpt(CliConsts.USERNAME_OPTION_NAME, DUMMY_USER) } );
CliTestHelpers.ensureAllThrow(PARSER, failingLines, CliParser.ParsingException.class);
spotify/spydra
spydra/src/test/java/com/spotify/spydra/historytools/RunJhsCliParserTest.java
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/RunJhsCommand.java // @AutoValue // public abstract class RunJhsCommand { // // RunJhsCommand() { // } // // public abstract String clientId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_RunJhsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder logBucket(String logBucket); // // public abstract RunJhsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.RunJhsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import org.junit.Test;
/*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class RunJhsCliParserTest { private static final RunJhsCliParser PARSER = new RunJhsCliParser(); private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParseWithUser() {
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/RunJhsCommand.java // @AutoValue // public abstract class RunJhsCommand { // // RunJhsCommand() { // } // // public abstract String clientId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_RunJhsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder logBucket(String logBucket); // // public abstract RunJhsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/test/java/com/spotify/spydra/historytools/RunJhsCliParserTest.java import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.RunJhsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import org.junit.Test; /*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class RunJhsCliParserTest { private static final RunJhsCliParser PARSER = new RunJhsCliParser(); private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParseWithUser() {
RunJhsCommand jhsCmd = PARSER.parse(new String[]{
spotify/spydra
spydra/src/test/java/com/spotify/spydra/historytools/RunJhsCliParserTest.java
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/RunJhsCommand.java // @AutoValue // public abstract class RunJhsCommand { // // RunJhsCommand() { // } // // public abstract String clientId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_RunJhsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder logBucket(String logBucket); // // public abstract RunJhsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.RunJhsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import org.junit.Test;
/*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class RunJhsCliParserTest { private static final RunJhsCliParser PARSER = new RunJhsCliParser(); private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParseWithUser() { RunJhsCommand jhsCmd = PARSER.parse(new String[]{
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/RunJhsCommand.java // @AutoValue // public abstract class RunJhsCommand { // // RunJhsCommand() { // } // // public abstract String clientId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_RunJhsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder logBucket(String logBucket); // // public abstract RunJhsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/test/java/com/spotify/spydra/historytools/RunJhsCliParserTest.java import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.RunJhsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import org.junit.Test; /*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class RunJhsCliParserTest { private static final RunJhsCliParser PARSER = new RunJhsCliParser(); private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParseWithUser() { RunJhsCommand jhsCmd = PARSER.parse(new String[]{
CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID),
spotify/spydra
spydra/src/test/java/com/spotify/spydra/historytools/RunJhsCliParserTest.java
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/RunJhsCommand.java // @AutoValue // public abstract class RunJhsCommand { // // RunJhsCommand() { // } // // public abstract String clientId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_RunJhsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder logBucket(String logBucket); // // public abstract RunJhsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.RunJhsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import org.junit.Test;
/*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class RunJhsCliParserTest { private static final RunJhsCliParser PARSER = new RunJhsCliParser(); private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParseWithUser() { RunJhsCommand jhsCmd = PARSER.parse(new String[]{
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/RunJhsCommand.java // @AutoValue // public abstract class RunJhsCommand { // // RunJhsCommand() { // } // // public abstract String clientId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_RunJhsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder logBucket(String logBucket); // // public abstract RunJhsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/test/java/com/spotify/spydra/historytools/RunJhsCliParserTest.java import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.RunJhsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import org.junit.Test; /*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class RunJhsCliParserTest { private static final RunJhsCliParser PARSER = new RunJhsCliParser(); private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParseWithUser() { RunJhsCommand jhsCmd = PARSER.parse(new String[]{
CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID),
spotify/spydra
spydra/src/test/java/com/spotify/spydra/historytools/RunJhsCliParserTest.java
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/RunJhsCommand.java // @AutoValue // public abstract class RunJhsCommand { // // RunJhsCommand() { // } // // public abstract String clientId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_RunJhsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder logBucket(String logBucket); // // public abstract RunJhsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.RunJhsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import org.junit.Test;
/*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class RunJhsCliParserTest { private static final RunJhsCliParser PARSER = new RunJhsCliParser(); private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParseWithUser() { RunJhsCommand jhsCmd = PARSER.parse(new String[]{ CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID), CliTestHelpers.toStrOpt(CliConsts.LOG_BUCKET_OPTION_NAME, DUMMY_BUCKET) }); assertEquals(jhsCmd.clientId(), DUMMY_CLIENT_ID); } @Test public void testParseWithoutUser() { RunJhsCommand jhsCmd = PARSER.parse(new String[]{ CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID), CliTestHelpers.toStrOpt(CliConsts.LOG_BUCKET_OPTION_NAME, DUMMY_BUCKET) }); assertEquals(jhsCmd.clientId(), DUMMY_CLIENT_ID); } @Test public void testMissingArgs() { CliTestHelpers.ensureAllThrow( PARSER, Arrays.asList(new String[]{}, new String[]{"--noSuchThing=FOO"}),
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/RunJhsCommand.java // @AutoValue // public abstract class RunJhsCommand { // // RunJhsCommand() { // } // // public abstract String clientId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_RunJhsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder logBucket(String logBucket); // // public abstract RunJhsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/test/java/com/spotify/spydra/historytools/RunJhsCliParserTest.java import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.RunJhsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import org.junit.Test; /*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class RunJhsCliParserTest { private static final RunJhsCliParser PARSER = new RunJhsCliParser(); private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParseWithUser() { RunJhsCommand jhsCmd = PARSER.parse(new String[]{ CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID), CliTestHelpers.toStrOpt(CliConsts.LOG_BUCKET_OPTION_NAME, DUMMY_BUCKET) }); assertEquals(jhsCmd.clientId(), DUMMY_CLIENT_ID); } @Test public void testParseWithoutUser() { RunJhsCommand jhsCmd = PARSER.parse(new String[]{ CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID), CliTestHelpers.toStrOpt(CliConsts.LOG_BUCKET_OPTION_NAME, DUMMY_BUCKET) }); assertEquals(jhsCmd.clientId(), DUMMY_CLIENT_ID); } @Test public void testMissingArgs() { CliTestHelpers.ensureAllThrow( PARSER, Arrays.asList(new String[]{}, new String[]{"--noSuchThing=FOO"}),
CliParser.ParsingException.class);
spotify/spydra
spydra/src/main/java/com/spotify/spydra/historytools/DumpLogsCliParser.java
// Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpLogsCommand.java // @AutoValue // public abstract class DumpLogsCommand { // // DumpLogsCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String username(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpLogsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder username(String username); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpLogsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliHelper.java // public class CliHelper { // // private static final Logger logger = LoggerFactory.getLogger(CliHelper.class); // // /** // * Creates an optional long parameter with a single argument. // */ // public static Option createSingleOption(String optName, String description) { // return createOption(optName, description, false, false); // } // // /** // * Creates a required long parameter with a single argument. // */ // public static Option createRequiredSingleOption(String optName, String description) { // return createOption(optName, description, true, false); // } // // /** // * Creates an optional long parameter with multiple arguments. // */ // public static Option createMultiOption(String optName, String description) { // return createOption(optName, description, false, true); // } // // /** // * Small helper for creating some of the long parameter settings we frequently // * use here. // * // * @param optName name of the parameter/option // * @param description description for the help text // * @param isRequired whether this parameter is strictly required // * @param unlimitedArgs whether it supports multiple arguments, default is on argument // */ // public static Option createOption( // String optName, String description, // boolean isRequired, boolean unlimitedArgs) { // // Option.Builder builder = Option.builder() // .longOpt(optName) // .hasArg() // .valueSeparator(',') // .required(isRequired) // .desc(description); // // if (unlimitedArgs) { // builder.hasArgs(); // } // // return builder.build(); // } // // public static CommandLine tryParse( // CommandLineParser parser, // Options options, // String[] args) { // try { // return parser.parse(options, args); // } catch (MissingOptionException moe) { // logger.error(moe.getMessage()); // throw new CliParser.ParsingException(moe); // } catch (ParseException e) { // logger.error("Failed parsing options", e); // throw new CliParser.ParsingException(e); // } // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import com.spotify.spydra.historytools.commands.DumpLogsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliHelper; import com.spotify.spydra.submitter.runner.CliParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.hadoop.yarn.util.ConverterUtils;
/*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpLogsCliParser implements CliParser<DumpLogsCommand> { private static final String CMD_NAME = CliConsts.DUMP_HISTORY_CMD_NAME; private static final Options options; static { options = buildCliOptions(); } @Override public DumpLogsCommand parse(String[] args) { DefaultParser parser = new DefaultParser(); CommandLine cmdLine;
// Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpLogsCommand.java // @AutoValue // public abstract class DumpLogsCommand { // // DumpLogsCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String username(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpLogsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder username(String username); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpLogsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliHelper.java // public class CliHelper { // // private static final Logger logger = LoggerFactory.getLogger(CliHelper.class); // // /** // * Creates an optional long parameter with a single argument. // */ // public static Option createSingleOption(String optName, String description) { // return createOption(optName, description, false, false); // } // // /** // * Creates a required long parameter with a single argument. // */ // public static Option createRequiredSingleOption(String optName, String description) { // return createOption(optName, description, true, false); // } // // /** // * Creates an optional long parameter with multiple arguments. // */ // public static Option createMultiOption(String optName, String description) { // return createOption(optName, description, false, true); // } // // /** // * Small helper for creating some of the long parameter settings we frequently // * use here. // * // * @param optName name of the parameter/option // * @param description description for the help text // * @param isRequired whether this parameter is strictly required // * @param unlimitedArgs whether it supports multiple arguments, default is on argument // */ // public static Option createOption( // String optName, String description, // boolean isRequired, boolean unlimitedArgs) { // // Option.Builder builder = Option.builder() // .longOpt(optName) // .hasArg() // .valueSeparator(',') // .required(isRequired) // .desc(description); // // if (unlimitedArgs) { // builder.hasArgs(); // } // // return builder.build(); // } // // public static CommandLine tryParse( // CommandLineParser parser, // Options options, // String[] args) { // try { // return parser.parse(options, args); // } catch (MissingOptionException moe) { // logger.error(moe.getMessage()); // throw new CliParser.ParsingException(moe); // } catch (ParseException e) { // logger.error("Failed parsing options", e); // throw new CliParser.ParsingException(e); // } // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/main/java/com/spotify/spydra/historytools/DumpLogsCliParser.java import com.spotify.spydra.historytools.commands.DumpLogsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliHelper; import com.spotify.spydra.submitter.runner.CliParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.hadoop.yarn.util.ConverterUtils; /*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpLogsCliParser implements CliParser<DumpLogsCommand> { private static final String CMD_NAME = CliConsts.DUMP_HISTORY_CMD_NAME; private static final Options options; static { options = buildCliOptions(); } @Override public DumpLogsCommand parse(String[] args) { DefaultParser parser = new DefaultParser(); CommandLine cmdLine;
cmdLine = CliHelper.tryParse(parser, options, args);
spotify/spydra
spydra/src/main/java/com/spotify/spydra/historytools/DumpHistoryCliParser.java
// Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpHistoryCommand.java // @AutoValue // public abstract class DumpHistoryCommand { // // DumpHistoryCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpHistoryCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpHistoryCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliHelper.java // public class CliHelper { // // private static final Logger logger = LoggerFactory.getLogger(CliHelper.class); // // /** // * Creates an optional long parameter with a single argument. // */ // public static Option createSingleOption(String optName, String description) { // return createOption(optName, description, false, false); // } // // /** // * Creates a required long parameter with a single argument. // */ // public static Option createRequiredSingleOption(String optName, String description) { // return createOption(optName, description, true, false); // } // // /** // * Creates an optional long parameter with multiple arguments. // */ // public static Option createMultiOption(String optName, String description) { // return createOption(optName, description, false, true); // } // // /** // * Small helper for creating some of the long parameter settings we frequently // * use here. // * // * @param optName name of the parameter/option // * @param description description for the help text // * @param isRequired whether this parameter is strictly required // * @param unlimitedArgs whether it supports multiple arguments, default is on argument // */ // public static Option createOption( // String optName, String description, // boolean isRequired, boolean unlimitedArgs) { // // Option.Builder builder = Option.builder() // .longOpt(optName) // .hasArg() // .valueSeparator(',') // .required(isRequired) // .desc(description); // // if (unlimitedArgs) { // builder.hasArgs(); // } // // return builder.build(); // } // // public static CommandLine tryParse( // CommandLineParser parser, // Options options, // String[] args) { // try { // return parser.parse(options, args); // } catch (MissingOptionException moe) { // logger.error(moe.getMessage()); // throw new CliParser.ParsingException(moe); // } catch (ParseException e) { // logger.error("Failed parsing options", e); // throw new CliParser.ParsingException(e); // } // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import com.spotify.spydra.historytools.commands.DumpHistoryCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliHelper; import com.spotify.spydra.submitter.runner.CliParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.hadoop.yarn.util.ConverterUtils;
/*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpHistoryCliParser implements CliParser<DumpHistoryCommand> { public static final String CMD_NAME = CliConsts.DUMP_HISTORY_CMD_NAME; private static final Options options; static { options = buildCliOptions(); } @Override public DumpHistoryCommand parse(String[] args) { DefaultParser parser = new DefaultParser(); CommandLine cmdLine;
// Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpHistoryCommand.java // @AutoValue // public abstract class DumpHistoryCommand { // // DumpHistoryCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpHistoryCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpHistoryCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliHelper.java // public class CliHelper { // // private static final Logger logger = LoggerFactory.getLogger(CliHelper.class); // // /** // * Creates an optional long parameter with a single argument. // */ // public static Option createSingleOption(String optName, String description) { // return createOption(optName, description, false, false); // } // // /** // * Creates a required long parameter with a single argument. // */ // public static Option createRequiredSingleOption(String optName, String description) { // return createOption(optName, description, true, false); // } // // /** // * Creates an optional long parameter with multiple arguments. // */ // public static Option createMultiOption(String optName, String description) { // return createOption(optName, description, false, true); // } // // /** // * Small helper for creating some of the long parameter settings we frequently // * use here. // * // * @param optName name of the parameter/option // * @param description description for the help text // * @param isRequired whether this parameter is strictly required // * @param unlimitedArgs whether it supports multiple arguments, default is on argument // */ // public static Option createOption( // String optName, String description, // boolean isRequired, boolean unlimitedArgs) { // // Option.Builder builder = Option.builder() // .longOpt(optName) // .hasArg() // .valueSeparator(',') // .required(isRequired) // .desc(description); // // if (unlimitedArgs) { // builder.hasArgs(); // } // // return builder.build(); // } // // public static CommandLine tryParse( // CommandLineParser parser, // Options options, // String[] args) { // try { // return parser.parse(options, args); // } catch (MissingOptionException moe) { // logger.error(moe.getMessage()); // throw new CliParser.ParsingException(moe); // } catch (ParseException e) { // logger.error("Failed parsing options", e); // throw new CliParser.ParsingException(e); // } // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/main/java/com/spotify/spydra/historytools/DumpHistoryCliParser.java import com.spotify.spydra.historytools.commands.DumpHistoryCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliHelper; import com.spotify.spydra.submitter.runner.CliParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.hadoop.yarn.util.ConverterUtils; /*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpHistoryCliParser implements CliParser<DumpHistoryCommand> { public static final String CMD_NAME = CliConsts.DUMP_HISTORY_CMD_NAME; private static final Options options; static { options = buildCliOptions(); } @Override public DumpHistoryCommand parse(String[] args) { DefaultParser parser = new DefaultParser(); CommandLine cmdLine;
cmdLine = CliHelper.tryParse(parser, options, args);
spotify/spydra
spydra/src/main/java/com/spotify/spydra/historytools/RunJhsCliParser.java
// Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/RunJhsCommand.java // @AutoValue // public abstract class RunJhsCommand { // // RunJhsCommand() { // } // // public abstract String clientId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_RunJhsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder logBucket(String logBucket); // // public abstract RunJhsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliHelper.java // public class CliHelper { // // private static final Logger logger = LoggerFactory.getLogger(CliHelper.class); // // /** // * Creates an optional long parameter with a single argument. // */ // public static Option createSingleOption(String optName, String description) { // return createOption(optName, description, false, false); // } // // /** // * Creates a required long parameter with a single argument. // */ // public static Option createRequiredSingleOption(String optName, String description) { // return createOption(optName, description, true, false); // } // // /** // * Creates an optional long parameter with multiple arguments. // */ // public static Option createMultiOption(String optName, String description) { // return createOption(optName, description, false, true); // } // // /** // * Small helper for creating some of the long parameter settings we frequently // * use here. // * // * @param optName name of the parameter/option // * @param description description for the help text // * @param isRequired whether this parameter is strictly required // * @param unlimitedArgs whether it supports multiple arguments, default is on argument // */ // public static Option createOption( // String optName, String description, // boolean isRequired, boolean unlimitedArgs) { // // Option.Builder builder = Option.builder() // .longOpt(optName) // .hasArg() // .valueSeparator(',') // .required(isRequired) // .desc(description); // // if (unlimitedArgs) { // builder.hasArgs(); // } // // return builder.build(); // } // // public static CommandLine tryParse( // CommandLineParser parser, // Options options, // String[] args) { // try { // return parser.parse(options, args); // } catch (MissingOptionException moe) { // logger.error(moe.getMessage()); // throw new CliParser.ParsingException(moe); // } catch (ParseException e) { // logger.error("Failed parsing options", e); // throw new CliParser.ParsingException(e); // } // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import com.spotify.spydra.historytools.commands.RunJhsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliHelper; import com.spotify.spydra.submitter.runner.CliParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options;
/*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class RunJhsCliParser implements CliParser<RunJhsCommand> { public static final String CMD_NAME = CliConsts.RUN_JHS_CMD_NAME; private static final Options options = buildCliOptions(); @Override public RunJhsCommand parse(String[] args) { DefaultParser parser = new DefaultParser(); CommandLine cmdLine;
// Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/RunJhsCommand.java // @AutoValue // public abstract class RunJhsCommand { // // RunJhsCommand() { // } // // public abstract String clientId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_RunJhsCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder logBucket(String logBucket); // // public abstract RunJhsCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliHelper.java // public class CliHelper { // // private static final Logger logger = LoggerFactory.getLogger(CliHelper.class); // // /** // * Creates an optional long parameter with a single argument. // */ // public static Option createSingleOption(String optName, String description) { // return createOption(optName, description, false, false); // } // // /** // * Creates a required long parameter with a single argument. // */ // public static Option createRequiredSingleOption(String optName, String description) { // return createOption(optName, description, true, false); // } // // /** // * Creates an optional long parameter with multiple arguments. // */ // public static Option createMultiOption(String optName, String description) { // return createOption(optName, description, false, true); // } // // /** // * Small helper for creating some of the long parameter settings we frequently // * use here. // * // * @param optName name of the parameter/option // * @param description description for the help text // * @param isRequired whether this parameter is strictly required // * @param unlimitedArgs whether it supports multiple arguments, default is on argument // */ // public static Option createOption( // String optName, String description, // boolean isRequired, boolean unlimitedArgs) { // // Option.Builder builder = Option.builder() // .longOpt(optName) // .hasArg() // .valueSeparator(',') // .required(isRequired) // .desc(description); // // if (unlimitedArgs) { // builder.hasArgs(); // } // // return builder.build(); // } // // public static CommandLine tryParse( // CommandLineParser parser, // Options options, // String[] args) { // try { // return parser.parse(options, args); // } catch (MissingOptionException moe) { // logger.error(moe.getMessage()); // throw new CliParser.ParsingException(moe); // } catch (ParseException e) { // logger.error("Failed parsing options", e); // throw new CliParser.ParsingException(e); // } // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/main/java/com/spotify/spydra/historytools/RunJhsCliParser.java import com.spotify.spydra.historytools.commands.RunJhsCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliHelper; import com.spotify.spydra.submitter.runner.CliParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; /*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class RunJhsCliParser implements CliParser<RunJhsCommand> { public static final String CMD_NAME = CliConsts.RUN_JHS_CMD_NAME; private static final Options options = buildCliOptions(); @Override public RunJhsCommand parse(String[] args) { DefaultParser parser = new DefaultParser(); CommandLine cmdLine;
cmdLine = CliHelper.tryParse(parser, options, args);
spotify/spydra
spydra/src/test/java/com/spotify/spydra/historytools/DumpHistoryCliParserTest.java
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpHistoryCommand.java // @AutoValue // public abstract class DumpHistoryCommand { // // DumpHistoryCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpHistoryCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpHistoryCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpHistoryCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test;
/*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpHistoryCliParserTest { private static final DumpHistoryCliParser PARSER = new DumpHistoryCliParser(); private static final String DUMMY_APP_ID = "application_1345678910111_123456"; private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParse() {
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpHistoryCommand.java // @AutoValue // public abstract class DumpHistoryCommand { // // DumpHistoryCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpHistoryCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpHistoryCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/test/java/com/spotify/spydra/historytools/DumpHistoryCliParserTest.java import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpHistoryCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test; /*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpHistoryCliParserTest { private static final DumpHistoryCliParser PARSER = new DumpHistoryCliParser(); private static final String DUMMY_APP_ID = "application_1345678910111_123456"; private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParse() {
DumpHistoryCommand dumpCmd = PARSER.parse(new String[]{
spotify/spydra
spydra/src/test/java/com/spotify/spydra/historytools/DumpHistoryCliParserTest.java
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpHistoryCommand.java // @AutoValue // public abstract class DumpHistoryCommand { // // DumpHistoryCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpHistoryCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpHistoryCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpHistoryCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test;
/*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpHistoryCliParserTest { private static final DumpHistoryCliParser PARSER = new DumpHistoryCliParser(); private static final String DUMMY_APP_ID = "application_1345678910111_123456"; private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParse() { DumpHistoryCommand dumpCmd = PARSER.parse(new String[]{
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpHistoryCommand.java // @AutoValue // public abstract class DumpHistoryCommand { // // DumpHistoryCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpHistoryCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpHistoryCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/test/java/com/spotify/spydra/historytools/DumpHistoryCliParserTest.java import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpHistoryCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test; /*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpHistoryCliParserTest { private static final DumpHistoryCliParser PARSER = new DumpHistoryCliParser(); private static final String DUMMY_APP_ID = "application_1345678910111_123456"; private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParse() { DumpHistoryCommand dumpCmd = PARSER.parse(new String[]{
CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID),
spotify/spydra
spydra/src/test/java/com/spotify/spydra/historytools/DumpHistoryCliParserTest.java
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpHistoryCommand.java // @AutoValue // public abstract class DumpHistoryCommand { // // DumpHistoryCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpHistoryCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpHistoryCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpHistoryCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test;
/*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpHistoryCliParserTest { private static final DumpHistoryCliParser PARSER = new DumpHistoryCliParser(); private static final String DUMMY_APP_ID = "application_1345678910111_123456"; private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParse() { DumpHistoryCommand dumpCmd = PARSER.parse(new String[]{
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpHistoryCommand.java // @AutoValue // public abstract class DumpHistoryCommand { // // DumpHistoryCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpHistoryCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpHistoryCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/test/java/com/spotify/spydra/historytools/DumpHistoryCliParserTest.java import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpHistoryCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test; /*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.historytools; public class DumpHistoryCliParserTest { private static final DumpHistoryCliParser PARSER = new DumpHistoryCliParser(); private static final String DUMMY_APP_ID = "application_1345678910111_123456"; private static final String DUMMY_CLIENT_ID = "pretty-client-2342"; private static final String DUMMY_BUCKET = "bucket"; @Test public void testParse() { DumpHistoryCommand dumpCmd = PARSER.parse(new String[]{
CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID),
spotify/spydra
spydra/src/test/java/com/spotify/spydra/historytools/DumpHistoryCliParserTest.java
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpHistoryCommand.java // @AutoValue // public abstract class DumpHistoryCommand { // // DumpHistoryCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpHistoryCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpHistoryCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // }
import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpHistoryCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test;
@Test public void testParse() { DumpHistoryCommand dumpCmd = PARSER.parse(new String[]{ CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID), CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID), CliTestHelpers.toStrOpt(CliConsts.LOG_BUCKET_OPTION_NAME, DUMMY_BUCKET) }); assertEquals(dumpCmd.applicationId().toString(), DUMMY_APP_ID); assertEquals(dumpCmd.clientId(), DUMMY_CLIENT_ID); assertEquals(dumpCmd.logBucket(), DUMMY_BUCKET); } @Test public void testMissingArgs() { // Ensure both options are mandatory List<String[]> failingLines = Arrays.asList( new String[]{ CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID) }, new String[]{ CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID) }, new String[]{ CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID), CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID) } );
// Path: spydra/src/test/java/com/spotify/spydra/CliTestHelpers.java // public class CliTestHelpers { // public static <T> void ensureAllThrow(CliParser<T> parser, List<String[]> argsList, Class exceptionCls) { // for (String[] args : argsList) { // String errorMsg = "Should throw for: " + String.join(";", args); // assertTrue(errorMsg, checkThrows(parser, args, exceptionCls)); // } // } // // public static <T> boolean checkThrows(CliParser<T> parser, String[] args, Class exceptionCls) { // boolean threw = false; // // try { // parser.parse(args); // } catch (Exception e) { // if (exceptionCls.isInstance(e)) { // threw = true; // } // } // return threw; // } // // public static String toStrOpt(String optionName, String optionValue) { // return String.format("--%s=%s", optionName, optionValue); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/historytools/commands/DumpHistoryCommand.java // @AutoValue // public abstract class DumpHistoryCommand { // // DumpHistoryCommand() { // } // // public abstract String clientId(); // // public abstract ApplicationId applicationId(); // // public abstract String logBucket(); // // public static Builder builder() { // return new AutoValue_DumpHistoryCommand.Builder(); // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder clientId(String clientId); // // public abstract Builder applicationId(ApplicationId jobId); // // public abstract Builder logBucket(String logBucket); // // public abstract DumpHistoryCommand build(); // } // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliConsts.java // public class CliConsts { // public static final String SUBMIT_CMD_NAME = "submit"; // public static final String LOGS_CMD_NAME = "dump-logs"; // public static final String DUMP_HISTORY_CMD_NAME = "dump-history"; // public static final String RUN_JHS_CMD_NAME = "run-jhs"; // public static final String JOB_ID_OPTION_NAME = "application"; // public static final String CLIENT_ID_OPTION_NAME = "clientid"; // public static final String JAR_OPTION_NAME = "jar"; // public static final String JARS_OPTION_NAME = "jars"; // public static final String SPYDRA_JSON_OPTION_NAME = "spydra-json"; // public static final String USERNAME_OPTION_NAME = "username"; // public static final String LOG_BUCKET_OPTION_NAME = "log-bucket"; // public static final String JOBNAME_OPTION_NAME = "job-name"; // } // // Path: spydra/src/main/java/com/spotify/spydra/submitter/runner/CliParser.java // public interface CliParser<T> { // // T parse(String[] args) throws IOException; // // /** // * Prints help for the subcommand this parser is responsible for. // */ // void printHelp(); // // boolean enoughArgs(String[] args); // // class ParsingException extends RuntimeException { // public ParsingException(Throwable cause) { // super(cause); // } // } // } // Path: spydra/src/test/java/com/spotify/spydra/historytools/DumpHistoryCliParserTest.java import static org.junit.Assert.assertEquals; import com.spotify.spydra.CliTestHelpers; import com.spotify.spydra.historytools.commands.DumpHistoryCommand; import com.spotify.spydra.submitter.runner.CliConsts; import com.spotify.spydra.submitter.runner.CliParser; import java.util.Arrays; import java.util.List; import org.junit.Test; @Test public void testParse() { DumpHistoryCommand dumpCmd = PARSER.parse(new String[]{ CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID), CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID), CliTestHelpers.toStrOpt(CliConsts.LOG_BUCKET_OPTION_NAME, DUMMY_BUCKET) }); assertEquals(dumpCmd.applicationId().toString(), DUMMY_APP_ID); assertEquals(dumpCmd.clientId(), DUMMY_CLIENT_ID); assertEquals(dumpCmd.logBucket(), DUMMY_BUCKET); } @Test public void testMissingArgs() { // Ensure both options are mandatory List<String[]> failingLines = Arrays.asList( new String[]{ CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID) }, new String[]{ CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID) }, new String[]{ CliTestHelpers.toStrOpt(CliConsts.CLIENT_ID_OPTION_NAME, DUMMY_CLIENT_ID), CliTestHelpers.toStrOpt(CliConsts.JOB_ID_OPTION_NAME, DUMMY_APP_ID) } );
CliTestHelpers.ensureAllThrow(PARSER, failingLines, CliParser.ParsingException.class);
spotify/spydra
spydra/src/test/java/com/spotify/spydra/submitter/api/ClusterPlacementTest.java
// Path: spydra/src/main/java/com/spotify/spydra/submitter/api/PoolingSubmitter.java // public static final String SPYDRA_PLACEMENT_TOKEN_LABEL = "spydra-placement-token"; // // Path: api/src/main/java/com/spotify/spydra/api/model/Cluster.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Cluster { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Status { // // public static final String ERROR = "ERROR"; // public static final String CREATING = "CREATING"; // public static final String RUNNING = "RUNNING"; // public String state; // public ZonedDateTime stateStartTime; // } // // public Status status; // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Config { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class GceClusterConfig { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Metadata { // // // This is the initial heartbeat of the cluster. It is not updated. // // Look at the MasterConfig.instanceNames[0] for updated heartbeats // public Optional<ZonedDateTime> heartbeat = Optional.empty(); // } // // public Metadata metadata = new Metadata(); // public String zoneUri; // Even though this is an Uri-string, --zone takes it just fine // } // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class MasterConfig { // // public List<String> instanceNames = Collections.emptyList(); // } // // public MasterConfig masterConfig = new MasterConfig(); // public GceClusterConfig gceClusterConfig = new GceClusterConfig(); // } // // public Config config = new Config(); // // public String clusterName; // // public Map<String, String> labels; // // //TODO: TW Look at the `metrics` for the cluster // //TODO: TW look at labels to see if it is a spydra created cluster? // } // // Path: common/src/main/java/com/spotify/spydra/model/SpydraArgument.java // public static class Pooling { // public Optional<Integer> limit; // public Optional<Duration> maxAge; // // public Integer getLimit() { // return limit.get(); // } // // public void setLimit(Integer limit) { // this.limit = Optional.of(limit); // } // // public Duration getMaxAge() { // return maxAge.get(); // } // // public void setMaxAge(Duration maxAge) { // this.maxAge = Optional.of(maxAge); // } // // }
import com.spotify.spydra.model.SpydraArgument.Pooling; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import static com.spotify.spydra.submitter.api.PoolingSubmitter.SPYDRA_PLACEMENT_TOKEN_LABEL; import static junit.framework.TestCase.assertTrue; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import com.spotify.spydra.api.model.Cluster;
/*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.submitter.api; public class ClusterPlacementTest { @Test public void testClustereneration() { // Random offset is 20 and 6 for clusterNumber 0 and 1 and age 30
// Path: spydra/src/main/java/com/spotify/spydra/submitter/api/PoolingSubmitter.java // public static final String SPYDRA_PLACEMENT_TOKEN_LABEL = "spydra-placement-token"; // // Path: api/src/main/java/com/spotify/spydra/api/model/Cluster.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Cluster { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Status { // // public static final String ERROR = "ERROR"; // public static final String CREATING = "CREATING"; // public static final String RUNNING = "RUNNING"; // public String state; // public ZonedDateTime stateStartTime; // } // // public Status status; // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Config { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class GceClusterConfig { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Metadata { // // // This is the initial heartbeat of the cluster. It is not updated. // // Look at the MasterConfig.instanceNames[0] for updated heartbeats // public Optional<ZonedDateTime> heartbeat = Optional.empty(); // } // // public Metadata metadata = new Metadata(); // public String zoneUri; // Even though this is an Uri-string, --zone takes it just fine // } // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class MasterConfig { // // public List<String> instanceNames = Collections.emptyList(); // } // // public MasterConfig masterConfig = new MasterConfig(); // public GceClusterConfig gceClusterConfig = new GceClusterConfig(); // } // // public Config config = new Config(); // // public String clusterName; // // public Map<String, String> labels; // // //TODO: TW Look at the `metrics` for the cluster // //TODO: TW look at labels to see if it is a spydra created cluster? // } // // Path: common/src/main/java/com/spotify/spydra/model/SpydraArgument.java // public static class Pooling { // public Optional<Integer> limit; // public Optional<Duration> maxAge; // // public Integer getLimit() { // return limit.get(); // } // // public void setLimit(Integer limit) { // this.limit = Optional.of(limit); // } // // public Duration getMaxAge() { // return maxAge.get(); // } // // public void setMaxAge(Duration maxAge) { // this.maxAge = Optional.of(maxAge); // } // // } // Path: spydra/src/test/java/com/spotify/spydra/submitter/api/ClusterPlacementTest.java import com.spotify.spydra.model.SpydraArgument.Pooling; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import static com.spotify.spydra.submitter.api.PoolingSubmitter.SPYDRA_PLACEMENT_TOKEN_LABEL; import static junit.framework.TestCase.assertTrue; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import com.spotify.spydra.api.model.Cluster; /*- * -\-\- * Spydra * -- * Copyright (C) 2016 - 2018 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.spydra.submitter.api; public class ClusterPlacementTest { @Test public void testClustereneration() { // Random offset is 20 and 6 for clusterNumber 0 and 1 and age 30
final Pooling pooling = new Pooling();
spotify/spydra
spydra/src/test/java/com/spotify/spydra/submitter/api/ClusterPlacementTest.java
// Path: spydra/src/main/java/com/spotify/spydra/submitter/api/PoolingSubmitter.java // public static final String SPYDRA_PLACEMENT_TOKEN_LABEL = "spydra-placement-token"; // // Path: api/src/main/java/com/spotify/spydra/api/model/Cluster.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Cluster { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Status { // // public static final String ERROR = "ERROR"; // public static final String CREATING = "CREATING"; // public static final String RUNNING = "RUNNING"; // public String state; // public ZonedDateTime stateStartTime; // } // // public Status status; // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Config { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class GceClusterConfig { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Metadata { // // // This is the initial heartbeat of the cluster. It is not updated. // // Look at the MasterConfig.instanceNames[0] for updated heartbeats // public Optional<ZonedDateTime> heartbeat = Optional.empty(); // } // // public Metadata metadata = new Metadata(); // public String zoneUri; // Even though this is an Uri-string, --zone takes it just fine // } // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class MasterConfig { // // public List<String> instanceNames = Collections.emptyList(); // } // // public MasterConfig masterConfig = new MasterConfig(); // public GceClusterConfig gceClusterConfig = new GceClusterConfig(); // } // // public Config config = new Config(); // // public String clusterName; // // public Map<String, String> labels; // // //TODO: TW Look at the `metrics` for the cluster // //TODO: TW look at labels to see if it is a spydra created cluster? // } // // Path: common/src/main/java/com/spotify/spydra/model/SpydraArgument.java // public static class Pooling { // public Optional<Integer> limit; // public Optional<Duration> maxAge; // // public Integer getLimit() { // return limit.get(); // } // // public void setLimit(Integer limit) { // this.limit = Optional.of(limit); // } // // public Duration getMaxAge() { // return maxAge.get(); // } // // public void setMaxAge(Duration maxAge) { // this.maxAge = Optional.of(maxAge); // } // // }
import com.spotify.spydra.model.SpydraArgument.Pooling; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import static com.spotify.spydra.submitter.api.PoolingSubmitter.SPYDRA_PLACEMENT_TOKEN_LABEL; import static junit.framework.TestCase.assertTrue; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import com.spotify.spydra.api.model.Cluster;
assertThat(all, hasSize(3)); assertThat(all, hasItems( new ClusterPlacementBuilder().clusterNumber(0).clusterGeneration(2).build(), new ClusterPlacementBuilder().clusterNumber(1).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(2).clusterGeneration(1).build())); } @Test public void testFrom() { ClusterPlacement clusterPlacement = ClusterPlacement.from("10-15"); assertThat(clusterPlacement.clusterNumber(), is(10)); assertThat(clusterPlacement.clusterGeneration(), is(15L)); } @Test public void testToken() { final ClusterPlacement clusterPlacement = new ClusterPlacementBuilder().clusterNumber(10).clusterGeneration(15L).build(); assertThat(clusterPlacement.token(), is("10-15")); } @Test public void testFilterClusters() { final List<ClusterPlacement> clusterPlacements = Arrays.asList(new ClusterPlacementBuilder().clusterNumber(0).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(1).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(2).clusterGeneration(0).build());
// Path: spydra/src/main/java/com/spotify/spydra/submitter/api/PoolingSubmitter.java // public static final String SPYDRA_PLACEMENT_TOKEN_LABEL = "spydra-placement-token"; // // Path: api/src/main/java/com/spotify/spydra/api/model/Cluster.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Cluster { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Status { // // public static final String ERROR = "ERROR"; // public static final String CREATING = "CREATING"; // public static final String RUNNING = "RUNNING"; // public String state; // public ZonedDateTime stateStartTime; // } // // public Status status; // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Config { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class GceClusterConfig { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Metadata { // // // This is the initial heartbeat of the cluster. It is not updated. // // Look at the MasterConfig.instanceNames[0] for updated heartbeats // public Optional<ZonedDateTime> heartbeat = Optional.empty(); // } // // public Metadata metadata = new Metadata(); // public String zoneUri; // Even though this is an Uri-string, --zone takes it just fine // } // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class MasterConfig { // // public List<String> instanceNames = Collections.emptyList(); // } // // public MasterConfig masterConfig = new MasterConfig(); // public GceClusterConfig gceClusterConfig = new GceClusterConfig(); // } // // public Config config = new Config(); // // public String clusterName; // // public Map<String, String> labels; // // //TODO: TW Look at the `metrics` for the cluster // //TODO: TW look at labels to see if it is a spydra created cluster? // } // // Path: common/src/main/java/com/spotify/spydra/model/SpydraArgument.java // public static class Pooling { // public Optional<Integer> limit; // public Optional<Duration> maxAge; // // public Integer getLimit() { // return limit.get(); // } // // public void setLimit(Integer limit) { // this.limit = Optional.of(limit); // } // // public Duration getMaxAge() { // return maxAge.get(); // } // // public void setMaxAge(Duration maxAge) { // this.maxAge = Optional.of(maxAge); // } // // } // Path: spydra/src/test/java/com/spotify/spydra/submitter/api/ClusterPlacementTest.java import com.spotify.spydra.model.SpydraArgument.Pooling; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import static com.spotify.spydra.submitter.api.PoolingSubmitter.SPYDRA_PLACEMENT_TOKEN_LABEL; import static junit.framework.TestCase.assertTrue; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import com.spotify.spydra.api.model.Cluster; assertThat(all, hasSize(3)); assertThat(all, hasItems( new ClusterPlacementBuilder().clusterNumber(0).clusterGeneration(2).build(), new ClusterPlacementBuilder().clusterNumber(1).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(2).clusterGeneration(1).build())); } @Test public void testFrom() { ClusterPlacement clusterPlacement = ClusterPlacement.from("10-15"); assertThat(clusterPlacement.clusterNumber(), is(10)); assertThat(clusterPlacement.clusterGeneration(), is(15L)); } @Test public void testToken() { final ClusterPlacement clusterPlacement = new ClusterPlacementBuilder().clusterNumber(10).clusterGeneration(15L).build(); assertThat(clusterPlacement.token(), is("10-15")); } @Test public void testFilterClusters() { final List<ClusterPlacement> clusterPlacements = Arrays.asList(new ClusterPlacementBuilder().clusterNumber(0).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(1).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(2).clusterGeneration(0).build());
final Cluster cluster1 = new Cluster();
spotify/spydra
spydra/src/test/java/com/spotify/spydra/submitter/api/ClusterPlacementTest.java
// Path: spydra/src/main/java/com/spotify/spydra/submitter/api/PoolingSubmitter.java // public static final String SPYDRA_PLACEMENT_TOKEN_LABEL = "spydra-placement-token"; // // Path: api/src/main/java/com/spotify/spydra/api/model/Cluster.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Cluster { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Status { // // public static final String ERROR = "ERROR"; // public static final String CREATING = "CREATING"; // public static final String RUNNING = "RUNNING"; // public String state; // public ZonedDateTime stateStartTime; // } // // public Status status; // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Config { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class GceClusterConfig { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Metadata { // // // This is the initial heartbeat of the cluster. It is not updated. // // Look at the MasterConfig.instanceNames[0] for updated heartbeats // public Optional<ZonedDateTime> heartbeat = Optional.empty(); // } // // public Metadata metadata = new Metadata(); // public String zoneUri; // Even though this is an Uri-string, --zone takes it just fine // } // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class MasterConfig { // // public List<String> instanceNames = Collections.emptyList(); // } // // public MasterConfig masterConfig = new MasterConfig(); // public GceClusterConfig gceClusterConfig = new GceClusterConfig(); // } // // public Config config = new Config(); // // public String clusterName; // // public Map<String, String> labels; // // //TODO: TW Look at the `metrics` for the cluster // //TODO: TW look at labels to see if it is a spydra created cluster? // } // // Path: common/src/main/java/com/spotify/spydra/model/SpydraArgument.java // public static class Pooling { // public Optional<Integer> limit; // public Optional<Duration> maxAge; // // public Integer getLimit() { // return limit.get(); // } // // public void setLimit(Integer limit) { // this.limit = Optional.of(limit); // } // // public Duration getMaxAge() { // return maxAge.get(); // } // // public void setMaxAge(Duration maxAge) { // this.maxAge = Optional.of(maxAge); // } // // }
import com.spotify.spydra.model.SpydraArgument.Pooling; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import static com.spotify.spydra.submitter.api.PoolingSubmitter.SPYDRA_PLACEMENT_TOKEN_LABEL; import static junit.framework.TestCase.assertTrue; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import com.spotify.spydra.api.model.Cluster;
assertThat(all, hasSize(3)); assertThat(all, hasItems( new ClusterPlacementBuilder().clusterNumber(0).clusterGeneration(2).build(), new ClusterPlacementBuilder().clusterNumber(1).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(2).clusterGeneration(1).build())); } @Test public void testFrom() { ClusterPlacement clusterPlacement = ClusterPlacement.from("10-15"); assertThat(clusterPlacement.clusterNumber(), is(10)); assertThat(clusterPlacement.clusterGeneration(), is(15L)); } @Test public void testToken() { final ClusterPlacement clusterPlacement = new ClusterPlacementBuilder().clusterNumber(10).clusterGeneration(15L).build(); assertThat(clusterPlacement.token(), is("10-15")); } @Test public void testFilterClusters() { final List<ClusterPlacement> clusterPlacements = Arrays.asList(new ClusterPlacementBuilder().clusterNumber(0).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(1).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(2).clusterGeneration(0).build()); final Cluster cluster1 = new Cluster();
// Path: spydra/src/main/java/com/spotify/spydra/submitter/api/PoolingSubmitter.java // public static final String SPYDRA_PLACEMENT_TOKEN_LABEL = "spydra-placement-token"; // // Path: api/src/main/java/com/spotify/spydra/api/model/Cluster.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Cluster { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Status { // // public static final String ERROR = "ERROR"; // public static final String CREATING = "CREATING"; // public static final String RUNNING = "RUNNING"; // public String state; // public ZonedDateTime stateStartTime; // } // // public Status status; // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Config { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class GceClusterConfig { // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class Metadata { // // // This is the initial heartbeat of the cluster. It is not updated. // // Look at the MasterConfig.instanceNames[0] for updated heartbeats // public Optional<ZonedDateTime> heartbeat = Optional.empty(); // } // // public Metadata metadata = new Metadata(); // public String zoneUri; // Even though this is an Uri-string, --zone takes it just fine // } // // @JsonIgnoreProperties(ignoreUnknown = true) // public static class MasterConfig { // // public List<String> instanceNames = Collections.emptyList(); // } // // public MasterConfig masterConfig = new MasterConfig(); // public GceClusterConfig gceClusterConfig = new GceClusterConfig(); // } // // public Config config = new Config(); // // public String clusterName; // // public Map<String, String> labels; // // //TODO: TW Look at the `metrics` for the cluster // //TODO: TW look at labels to see if it is a spydra created cluster? // } // // Path: common/src/main/java/com/spotify/spydra/model/SpydraArgument.java // public static class Pooling { // public Optional<Integer> limit; // public Optional<Duration> maxAge; // // public Integer getLimit() { // return limit.get(); // } // // public void setLimit(Integer limit) { // this.limit = Optional.of(limit); // } // // public Duration getMaxAge() { // return maxAge.get(); // } // // public void setMaxAge(Duration maxAge) { // this.maxAge = Optional.of(maxAge); // } // // } // Path: spydra/src/test/java/com/spotify/spydra/submitter/api/ClusterPlacementTest.java import com.spotify.spydra.model.SpydraArgument.Pooling; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import static com.spotify.spydra.submitter.api.PoolingSubmitter.SPYDRA_PLACEMENT_TOKEN_LABEL; import static junit.framework.TestCase.assertTrue; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import com.spotify.spydra.api.model.Cluster; assertThat(all, hasSize(3)); assertThat(all, hasItems( new ClusterPlacementBuilder().clusterNumber(0).clusterGeneration(2).build(), new ClusterPlacementBuilder().clusterNumber(1).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(2).clusterGeneration(1).build())); } @Test public void testFrom() { ClusterPlacement clusterPlacement = ClusterPlacement.from("10-15"); assertThat(clusterPlacement.clusterNumber(), is(10)); assertThat(clusterPlacement.clusterGeneration(), is(15L)); } @Test public void testToken() { final ClusterPlacement clusterPlacement = new ClusterPlacementBuilder().clusterNumber(10).clusterGeneration(15L).build(); assertThat(clusterPlacement.token(), is("10-15")); } @Test public void testFilterClusters() { final List<ClusterPlacement> clusterPlacements = Arrays.asList(new ClusterPlacementBuilder().clusterNumber(0).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(1).clusterGeneration(1).build(), new ClusterPlacementBuilder().clusterNumber(2).clusterGeneration(0).build()); final Cluster cluster1 = new Cluster();
cluster1.labels = Collections.singletonMap(SPYDRA_PLACEMENT_TOKEN_LABEL, "0-1");
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContent.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // }
import static org.rr.mobi4java.ByteUtils.write; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class MobiContent { public enum CONTENT_TYPE { HEADER, CONTENT, INDEX, TAGX, TAG, IDXT, FLIS, FCIS, FDST, DATP, SRCS, CMET, AUDI, VIDE, END_OF_TEXT, COVER, THUMBNAIL, IMAGE, UNKNOWN }; protected byte[] content; private CONTENT_TYPE type; MobiContent(byte[] content, CONTENT_TYPE type) { this.content = content; this.type = type; } byte[] writeContent(OutputStream out) throws IOException {
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // Path: src/main/java/org/rr/mobi4java/MobiContent.java import static org.rr.mobi4java.ByteUtils.write; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class MobiContent { public enum CONTENT_TYPE { HEADER, CONTENT, INDEX, TAGX, TAG, IDXT, FLIS, FCIS, FDST, DATP, SRCS, CMET, AUDI, VIDE, END_OF_TEXT, COVER, THUMBNAIL, IMAGE, UNKNOWN }; protected byte[] content; private CONTENT_TYPE type; MobiContent(byte[] content, CONTENT_TYPE type) { this.content = content; this.type = type; } byte[] writeContent(OutputStream out) throws IOException {
write(content, out);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentTagEntry.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // }
import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.writeInt; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.builder.ToStringBuilder;
} } private TAG_ENTRY_TYPE(final int type) { this.type = type; } public static TAG_ENTRY_TYPE valueOf(int type) { return map.get(type); } public int getType() { return type; } } private int tag; private int valuesCount; private int bitmask; private int controlByte; MobiContentTagEntry(byte[] content) throws IOException { super(content, CONTENT_TYPE.TAG); readMobiTag(); } private void readMobiTag() throws IOException {
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentTagEntry.java import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.writeInt; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.builder.ToStringBuilder; } } private TAG_ENTRY_TYPE(final int type) { this.type = type; } public static TAG_ENTRY_TYPE valueOf(int type) { return map.get(type); } public int getType() { return type; } } private int tag; private int valuesCount; private int bitmask; private int controlByte; MobiContentTagEntry(byte[] content) throws IOException { super(content, CONTENT_TYPE.TAG); readMobiTag(); } private void readMobiTag() throws IOException {
tag = getInt(content, 0, 1);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentTagEntry.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // }
import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.writeInt; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.builder.ToStringBuilder;
public int getType() { return type; } } private int tag; private int valuesCount; private int bitmask; private int controlByte; MobiContentTagEntry(byte[] content) throws IOException { super(content, CONTENT_TYPE.TAG); readMobiTag(); } private void readMobiTag() throws IOException { tag = getInt(content, 0, 1); valuesCount = getInt(content, 1, 1); bitmask = getInt(content, 2, 1); controlByte = getInt(content, 3, 1); } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch);
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentTagEntry.java import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.writeInt; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.builder.ToStringBuilder; public int getType() { return type; } } private int tag; private int valuesCount; private int bitmask; private int controlByte; MobiContentTagEntry(byte[] content) throws IOException { super(content, CONTENT_TYPE.TAG); readMobiTag(); } private void readMobiTag() throws IOException { tag = getInt(content, 0, 1); valuesCount = getInt(content, 1, 1); bitmask = getInt(content, 2, 1); controlByte = getInt(content, 3, 1); } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch);
writeInt(tag, 1, tee);
rrauschenbach/mobi-api4java
src/test/java/org/rr/mobi4java/exth/ASINRecordDelegateTest.java
// Path: src/main/java/org/rr/mobi4java/EXTHRecordFactory.java // public class EXTHRecordFactory { // // public static EXTHRecord createEXTHRecord(RECORD_TYPE recordType, byte[] recordData) { // EXTHRecord record = createEXTHRecord(recordType); // record.setRecordType(recordType); // record.setData(recordData); // return record; // } // // public static EXTHRecord createEXTHRecord(RECORD_TYPE recordType) { // return new EXTHRecord(recordType.getType()); // } // // /** // * Create a new asin record with the given asin as value. // * // * @param asinCode The asin code which must be a member of the list returned with // * {@link EXTHasinRecordDelegate#getasinCodes()}. // * @return A new asin record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static ASINRecordDelegate createASINRecord(String asin) { // assertNotNull(RECORD_TYPE.ASIN, asin); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.ASIN); // ASINRecordDelegate recordDelegate = new ASINRecordDelegate(record); // recordDelegate.setASIN(asin); // return recordDelegate; // } // // /** // * Create a new isbn record with the given isbn as value. // * // * @param isbnCode The isbn code which must be a member of the list returned with // * {@link EXTHisbnRecordDelegate#getisbnCodes()}. // * @return A new isbn record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static ISBNRecordDelegate createISBNRecord(String isbn) { // assertNotNull(RECORD_TYPE.ISBN, isbn); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.ISBN); // ISBNRecordDelegate recordDelegate = new ISBNRecordDelegate(record); // recordDelegate.setISBN(isbn); // return recordDelegate; // } // // /** // * Create a new language record with the given language as value. // * // * @param languageCode The language code which must be a member of the list returned with // * {@link LanguageRecordDelegate#getLanguageCodes()}. // * @return A new language record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static LanguageRecordDelegate createLanguageRecord(String languageCode) { // assertNotNull(RECORD_TYPE.LANGUAGE, languageCode); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.LANGUAGE); // LanguageRecordDelegate recordDelegate = new LanguageRecordDelegate(record); // recordDelegate.setLanguageCode(languageCode); // return recordDelegate; // } // // /** // * Create a new string record for the given record type and the given string as value. Please note that only some record types fits to a string type. // * // * @param recordType The record type for the result {@link StringRecordDelegate}. // * @param str The string value of the new record. // * @param encoding The encoding. Use {@link MobiDocument#getCharacterEncoding()} for the right document encoding. // * @return A new string record instance. // * @throws UnsupportedEncodingException if the given encoding is not supported by the java virtual machine. // */ // public static StringRecordDelegate createStringRecord(RECORD_TYPE recordType, String str, String encoding) throws UnsupportedEncodingException { // assertNotNull(recordType, str); // // EXTHRecord record = createEXTHRecord(recordType); // StringRecordDelegate recordDelegate = new StringRecordDelegate(record); // recordDelegate.setStringData(str, encoding); // return recordDelegate; // } // // /** // * Create a new date record for the given record type. Please note that only some record types fits to a date type. // * // * @param recordType The record type for the result {@link DateRecordDelegate}. // * @param date The date value of the new record. // * @return A new date record instance. // */ // public static DateRecordDelegate createDateRecord(RECORD_TYPE recordType, Date date) { // assertNotNull(recordType, date); // // EXTHRecord record = createEXTHRecord(recordType); // DateRecordDelegate recordDelegate = new DateRecordDelegate(record); // recordDelegate.setDateData(date); // return recordDelegate; // } // // static EXTHRecord readEXTHRecord(byte[] mobiHeader, int offset) throws IOException { // EXTHRecord record = createEXTHRecord(RECORD_TYPE.valueOf(getInt(mobiHeader, offset + 0, 4))); // return record.readEXTHRecord(mobiHeader, offset); // } // // private static void assertNotNull(RECORD_TYPE type, Object value) { // if(value == null) { // throw new IllegalArgumentException("The record type " + type + " must not be null."); // } // } // }
import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; import org.rr.mobi4java.EXTHRecordFactory;
package org.rr.mobi4java.exth; public class ASINRecordDelegateTest { private static final String VALID_ASIN = "548445857X"; @Test public void testFormattedASINInput() throws IOException {
// Path: src/main/java/org/rr/mobi4java/EXTHRecordFactory.java // public class EXTHRecordFactory { // // public static EXTHRecord createEXTHRecord(RECORD_TYPE recordType, byte[] recordData) { // EXTHRecord record = createEXTHRecord(recordType); // record.setRecordType(recordType); // record.setData(recordData); // return record; // } // // public static EXTHRecord createEXTHRecord(RECORD_TYPE recordType) { // return new EXTHRecord(recordType.getType()); // } // // /** // * Create a new asin record with the given asin as value. // * // * @param asinCode The asin code which must be a member of the list returned with // * {@link EXTHasinRecordDelegate#getasinCodes()}. // * @return A new asin record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static ASINRecordDelegate createASINRecord(String asin) { // assertNotNull(RECORD_TYPE.ASIN, asin); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.ASIN); // ASINRecordDelegate recordDelegate = new ASINRecordDelegate(record); // recordDelegate.setASIN(asin); // return recordDelegate; // } // // /** // * Create a new isbn record with the given isbn as value. // * // * @param isbnCode The isbn code which must be a member of the list returned with // * {@link EXTHisbnRecordDelegate#getisbnCodes()}. // * @return A new isbn record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static ISBNRecordDelegate createISBNRecord(String isbn) { // assertNotNull(RECORD_TYPE.ISBN, isbn); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.ISBN); // ISBNRecordDelegate recordDelegate = new ISBNRecordDelegate(record); // recordDelegate.setISBN(isbn); // return recordDelegate; // } // // /** // * Create a new language record with the given language as value. // * // * @param languageCode The language code which must be a member of the list returned with // * {@link LanguageRecordDelegate#getLanguageCodes()}. // * @return A new language record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static LanguageRecordDelegate createLanguageRecord(String languageCode) { // assertNotNull(RECORD_TYPE.LANGUAGE, languageCode); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.LANGUAGE); // LanguageRecordDelegate recordDelegate = new LanguageRecordDelegate(record); // recordDelegate.setLanguageCode(languageCode); // return recordDelegate; // } // // /** // * Create a new string record for the given record type and the given string as value. Please note that only some record types fits to a string type. // * // * @param recordType The record type for the result {@link StringRecordDelegate}. // * @param str The string value of the new record. // * @param encoding The encoding. Use {@link MobiDocument#getCharacterEncoding()} for the right document encoding. // * @return A new string record instance. // * @throws UnsupportedEncodingException if the given encoding is not supported by the java virtual machine. // */ // public static StringRecordDelegate createStringRecord(RECORD_TYPE recordType, String str, String encoding) throws UnsupportedEncodingException { // assertNotNull(recordType, str); // // EXTHRecord record = createEXTHRecord(recordType); // StringRecordDelegate recordDelegate = new StringRecordDelegate(record); // recordDelegate.setStringData(str, encoding); // return recordDelegate; // } // // /** // * Create a new date record for the given record type. Please note that only some record types fits to a date type. // * // * @param recordType The record type for the result {@link DateRecordDelegate}. // * @param date The date value of the new record. // * @return A new date record instance. // */ // public static DateRecordDelegate createDateRecord(RECORD_TYPE recordType, Date date) { // assertNotNull(recordType, date); // // EXTHRecord record = createEXTHRecord(recordType); // DateRecordDelegate recordDelegate = new DateRecordDelegate(record); // recordDelegate.setDateData(date); // return recordDelegate; // } // // static EXTHRecord readEXTHRecord(byte[] mobiHeader, int offset) throws IOException { // EXTHRecord record = createEXTHRecord(RECORD_TYPE.valueOf(getInt(mobiHeader, offset + 0, 4))); // return record.readEXTHRecord(mobiHeader, offset); // } // // private static void assertNotNull(RECORD_TYPE type, Object value) { // if(value == null) { // throw new IllegalArgumentException("The record type " + type + " must not be null."); // } // } // } // Path: src/test/java/org/rr/mobi4java/exth/ASINRecordDelegateTest.java import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; import org.rr.mobi4java.EXTHRecordFactory; package org.rr.mobi4java.exth; public class ASINRecordDelegateTest { private static final String VALID_ASIN = "548445857X"; @Test public void testFormattedASINInput() throws IOException {
ASINRecordDelegate record = EXTHRecordFactory.createASINRecord(VALID_ASIN);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/EXTHHeader.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class EXTHHeader { private final int exthHeaderOffset; private List<EXTHRecord> recordList; public EXTHHeader(int exthHeaderOffset) { this.exthHeaderOffset = exthHeaderOffset; this.recordList = new ArrayList<>(); } EXTHHeader readEXTHHeader(byte[] mobiHeader) throws IOException {
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/EXTHHeader.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class EXTHHeader { private final int exthHeaderOffset; private List<EXTHRecord> recordList; public EXTHHeader(int exthHeaderOffset) { this.exthHeaderOffset = exthHeaderOffset; this.recordList = new ArrayList<>(); } EXTHHeader readEXTHHeader(byte[] mobiHeader) throws IOException {
String identifier = getString(getBytes(mobiHeader, getOffset(0), 4));
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/EXTHHeader.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class EXTHHeader { private final int exthHeaderOffset; private List<EXTHRecord> recordList; public EXTHHeader(int exthHeaderOffset) { this.exthHeaderOffset = exthHeaderOffset; this.recordList = new ArrayList<>(); } EXTHHeader readEXTHHeader(byte[] mobiHeader) throws IOException {
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/EXTHHeader.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class EXTHHeader { private final int exthHeaderOffset; private List<EXTHRecord> recordList; public EXTHHeader(int exthHeaderOffset) { this.exthHeaderOffset = exthHeaderOffset; this.recordList = new ArrayList<>(); } EXTHHeader readEXTHHeader(byte[] mobiHeader) throws IOException {
String identifier = getString(getBytes(mobiHeader, getOffset(0), 4));
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/EXTHHeader.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class EXTHHeader { private final int exthHeaderOffset; private List<EXTHRecord> recordList; public EXTHHeader(int exthHeaderOffset) { this.exthHeaderOffset = exthHeaderOffset; this.recordList = new ArrayList<>(); } EXTHHeader readEXTHHeader(byte[] mobiHeader) throws IOException { String identifier = getString(getBytes(mobiHeader, getOffset(0), 4));
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/EXTHHeader.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class EXTHHeader { private final int exthHeaderOffset; private List<EXTHRecord> recordList; public EXTHHeader(int exthHeaderOffset) { this.exthHeaderOffset = exthHeaderOffset; this.recordList = new ArrayList<>(); } EXTHHeader readEXTHHeader(byte[] mobiHeader) throws IOException { String identifier = getString(getBytes(mobiHeader, getOffset(0), 4));
int recordCount = getInt(getBytes(mobiHeader, getOffset(8), 4));
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/EXTHHeader.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class EXTHHeader { private final int exthHeaderOffset; private List<EXTHRecord> recordList; public EXTHHeader(int exthHeaderOffset) { this.exthHeaderOffset = exthHeaderOffset; this.recordList = new ArrayList<>(); } EXTHHeader readEXTHHeader(byte[] mobiHeader) throws IOException { String identifier = getString(getBytes(mobiHeader, getOffset(0), 4)); int recordCount = getInt(getBytes(mobiHeader, getOffset(8), 4)); if (negate(StringUtils.equals(identifier, "EXTH"))) { throw new IOException("Expected to find EXTH header identifier EXTH but got '" + identifier + "' instead"); } recordList = new ArrayList<>(recordCount); for (int i = 0; i < recordCount; i++) { EXTHRecord exthRecord = EXTHRecordFactory.readEXTHRecord(mobiHeader, getRecordOffset(i)); recordList.add(exthRecord); } return this; } void writeEXTHHeader(OutputStream out) throws IOException {
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/EXTHHeader.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class EXTHHeader { private final int exthHeaderOffset; private List<EXTHRecord> recordList; public EXTHHeader(int exthHeaderOffset) { this.exthHeaderOffset = exthHeaderOffset; this.recordList = new ArrayList<>(); } EXTHHeader readEXTHHeader(byte[] mobiHeader) throws IOException { String identifier = getString(getBytes(mobiHeader, getOffset(0), 4)); int recordCount = getInt(getBytes(mobiHeader, getOffset(8), 4)); if (negate(StringUtils.equals(identifier, "EXTH"))) { throw new IOException("Expected to find EXTH header identifier EXTH but got '" + identifier + "' instead"); } recordList = new ArrayList<>(recordCount); for (int i = 0; i < recordCount; i++) { EXTHRecord exthRecord = EXTHRecordFactory.readEXTHRecord(mobiHeader, getRecordOffset(i)); recordList.add(exthRecord); } return this; } void writeEXTHHeader(OutputStream out) throws IOException {
writeString("EXTH", 4, out);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/EXTHHeader.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class EXTHHeader { private final int exthHeaderOffset; private List<EXTHRecord> recordList; public EXTHHeader(int exthHeaderOffset) { this.exthHeaderOffset = exthHeaderOffset; this.recordList = new ArrayList<>(); } EXTHHeader readEXTHHeader(byte[] mobiHeader) throws IOException { String identifier = getString(getBytes(mobiHeader, getOffset(0), 4)); int recordCount = getInt(getBytes(mobiHeader, getOffset(8), 4)); if (negate(StringUtils.equals(identifier, "EXTH"))) { throw new IOException("Expected to find EXTH header identifier EXTH but got '" + identifier + "' instead"); } recordList = new ArrayList<>(recordCount); for (int i = 0; i < recordCount; i++) { EXTHRecord exthRecord = EXTHRecordFactory.readEXTHRecord(mobiHeader, getRecordOffset(i)); recordList.add(exthRecord); } return this; } void writeEXTHHeader(OutputStream out) throws IOException { writeString("EXTH", 4, out);
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/EXTHHeader.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class EXTHHeader { private final int exthHeaderOffset; private List<EXTHRecord> recordList; public EXTHHeader(int exthHeaderOffset) { this.exthHeaderOffset = exthHeaderOffset; this.recordList = new ArrayList<>(); } EXTHHeader readEXTHHeader(byte[] mobiHeader) throws IOException { String identifier = getString(getBytes(mobiHeader, getOffset(0), 4)); int recordCount = getInt(getBytes(mobiHeader, getOffset(8), 4)); if (negate(StringUtils.equals(identifier, "EXTH"))) { throw new IOException("Expected to find EXTH header identifier EXTH but got '" + identifier + "' instead"); } recordList = new ArrayList<>(recordCount); for (int i = 0; i < recordCount; i++) { EXTHRecord exthRecord = EXTHRecordFactory.readEXTHRecord(mobiHeader, getRecordOffset(i)); recordList.add(exthRecord); } return this; } void writeEXTHHeader(OutputStream out) throws IOException { writeString("EXTH", 4, out);
writeInt(size(), 4, out);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentHeader.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class MobiContentHeader extends MobiContent { private static final int DEFAULT_HEADER_LENGTH = 264; /** Size of the extra bytes for the rest of mobi header*/ private static final int MOBI_HEADER_REST = 16; public static enum COMPRESSION_CODE { NONE(1), PALM_DOC(2), HUFF_CDIC(17480); private final int type; private static Map<Integer, COMPRESSION_CODE> map = new HashMap<Integer, COMPRESSION_CODE>(); static { for (COMPRESSION_CODE typeEnum : COMPRESSION_CODE.values()) { if(map.put(typeEnum.type, typeEnum) != null) { throw new IllegalArgumentException("Duplicate type " + typeEnum.type); } } } private COMPRESSION_CODE(final int type) { this.type = type; } public static COMPRESSION_CODE valueOf(int type) { return map.get(type); } public int getType() { return type; } } private int recordDataOffset; private int recordDataLength; private int compression; private int unused0; private int textLength; private int recordCount; private int recordSize; private int encryptionType; private int unused1; private int mobiType; private int textEncoding; private int uniqueID; private int fileVersion; private int orthographicIndex; private int inflectionIndex; private int indexNames; private int indexKeys; private int extraIndex0; private int extraIndex1; private int extraIndex2; private int extraIndex3; private int extraIndex4; private int extraIndex5; private int firstNonBookIndex; private int fullNameOffset; private int fullNameLength; private int locale; private int inputLanguage; private int outputLanguage; private int minVersion; private int firstImageIndex; private int huffmanRecordOffset; private int huffmanRecordCount; private int huffmanTableOffset; private int huffmanTableLength; private int exthFlags; private int firstContentRecordIndex = 1; private int lastContentRecordIndex = -1; private int fcisRecordIndex; private int fcisRecordCount; private int flisRecordIndex; private int srcsRecordIndex = -1; private int srcsRecordCount; private int flisRecordCount; private int extraRecordDataFlags; private int indxRecordIndex = -1; private int fragmentRecordIndex = -1; private int skeletonRecordIndex = -1; private int datpRecordIndex = -1; private int guideIndex = -1; private EXTHHeader exthHeader; private byte[] remainder; // end of useful data private MobiContentHeader(byte[] content, long recordDataOffset, long recordDataLength) {
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentHeader.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class MobiContentHeader extends MobiContent { private static final int DEFAULT_HEADER_LENGTH = 264; /** Size of the extra bytes for the rest of mobi header*/ private static final int MOBI_HEADER_REST = 16; public static enum COMPRESSION_CODE { NONE(1), PALM_DOC(2), HUFF_CDIC(17480); private final int type; private static Map<Integer, COMPRESSION_CODE> map = new HashMap<Integer, COMPRESSION_CODE>(); static { for (COMPRESSION_CODE typeEnum : COMPRESSION_CODE.values()) { if(map.put(typeEnum.type, typeEnum) != null) { throw new IllegalArgumentException("Duplicate type " + typeEnum.type); } } } private COMPRESSION_CODE(final int type) { this.type = type; } public static COMPRESSION_CODE valueOf(int type) { return map.get(type); } public int getType() { return type; } } private int recordDataOffset; private int recordDataLength; private int compression; private int unused0; private int textLength; private int recordCount; private int recordSize; private int encryptionType; private int unused1; private int mobiType; private int textEncoding; private int uniqueID; private int fileVersion; private int orthographicIndex; private int inflectionIndex; private int indexNames; private int indexKeys; private int extraIndex0; private int extraIndex1; private int extraIndex2; private int extraIndex3; private int extraIndex4; private int extraIndex5; private int firstNonBookIndex; private int fullNameOffset; private int fullNameLength; private int locale; private int inputLanguage; private int outputLanguage; private int minVersion; private int firstImageIndex; private int huffmanRecordOffset; private int huffmanRecordCount; private int huffmanTableOffset; private int huffmanTableLength; private int exthFlags; private int firstContentRecordIndex = 1; private int lastContentRecordIndex = -1; private int fcisRecordIndex; private int fcisRecordCount; private int flisRecordIndex; private int srcsRecordIndex = -1; private int srcsRecordCount; private int flisRecordCount; private int extraRecordDataFlags; private int indxRecordIndex = -1; private int fragmentRecordIndex = -1; private int skeletonRecordIndex = -1; private int datpRecordIndex = -1; private int guideIndex = -1; private EXTHHeader exthHeader; private byte[] remainder; // end of useful data private MobiContentHeader(byte[] content, long recordDataOffset, long recordDataLength) {
super(getBytes(content, (int) recordDataOffset, (int) recordDataLength), CONTENT_TYPE.HEADER);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentHeader.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class MobiContentHeader extends MobiContent { private static final int DEFAULT_HEADER_LENGTH = 264; /** Size of the extra bytes for the rest of mobi header*/ private static final int MOBI_HEADER_REST = 16; public static enum COMPRESSION_CODE { NONE(1), PALM_DOC(2), HUFF_CDIC(17480); private final int type; private static Map<Integer, COMPRESSION_CODE> map = new HashMap<Integer, COMPRESSION_CODE>(); static { for (COMPRESSION_CODE typeEnum : COMPRESSION_CODE.values()) { if(map.put(typeEnum.type, typeEnum) != null) { throw new IllegalArgumentException("Duplicate type " + typeEnum.type); } } } private COMPRESSION_CODE(final int type) { this.type = type; } public static COMPRESSION_CODE valueOf(int type) { return map.get(type); } public int getType() { return type; } } private int recordDataOffset; private int recordDataLength; private int compression; private int unused0; private int textLength; private int recordCount; private int recordSize; private int encryptionType; private int unused1; private int mobiType; private int textEncoding; private int uniqueID; private int fileVersion; private int orthographicIndex; private int inflectionIndex; private int indexNames; private int indexKeys; private int extraIndex0; private int extraIndex1; private int extraIndex2; private int extraIndex3; private int extraIndex4; private int extraIndex5; private int firstNonBookIndex; private int fullNameOffset; private int fullNameLength; private int locale; private int inputLanguage; private int outputLanguage; private int minVersion; private int firstImageIndex; private int huffmanRecordOffset; private int huffmanRecordCount; private int huffmanTableOffset; private int huffmanTableLength; private int exthFlags; private int firstContentRecordIndex = 1; private int lastContentRecordIndex = -1; private int fcisRecordIndex; private int fcisRecordCount; private int flisRecordIndex; private int srcsRecordIndex = -1; private int srcsRecordCount; private int flisRecordCount; private int extraRecordDataFlags; private int indxRecordIndex = -1; private int fragmentRecordIndex = -1; private int skeletonRecordIndex = -1; private int datpRecordIndex = -1; private int guideIndex = -1; private EXTHHeader exthHeader; private byte[] remainder; // end of useful data private MobiContentHeader(byte[] content, long recordDataOffset, long recordDataLength) { super(getBytes(content, (int) recordDataOffset, (int) recordDataLength), CONTENT_TYPE.HEADER); this.recordDataOffset = (int) recordDataOffset; this.recordDataLength = (int) recordDataLength; } static MobiContentHeader readMobiHeader(byte[] content, long recordDataOffset, long recordDataLength) throws IOException { return new MobiContentHeader(content, recordDataOffset, recordDataLength).readMobiHeader(); } private MobiContentHeader readMobiHeader() throws IOException { // first 16 bytes of the PalmDOC Header followed by the MOBI header
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentHeader.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class MobiContentHeader extends MobiContent { private static final int DEFAULT_HEADER_LENGTH = 264; /** Size of the extra bytes for the rest of mobi header*/ private static final int MOBI_HEADER_REST = 16; public static enum COMPRESSION_CODE { NONE(1), PALM_DOC(2), HUFF_CDIC(17480); private final int type; private static Map<Integer, COMPRESSION_CODE> map = new HashMap<Integer, COMPRESSION_CODE>(); static { for (COMPRESSION_CODE typeEnum : COMPRESSION_CODE.values()) { if(map.put(typeEnum.type, typeEnum) != null) { throw new IllegalArgumentException("Duplicate type " + typeEnum.type); } } } private COMPRESSION_CODE(final int type) { this.type = type; } public static COMPRESSION_CODE valueOf(int type) { return map.get(type); } public int getType() { return type; } } private int recordDataOffset; private int recordDataLength; private int compression; private int unused0; private int textLength; private int recordCount; private int recordSize; private int encryptionType; private int unused1; private int mobiType; private int textEncoding; private int uniqueID; private int fileVersion; private int orthographicIndex; private int inflectionIndex; private int indexNames; private int indexKeys; private int extraIndex0; private int extraIndex1; private int extraIndex2; private int extraIndex3; private int extraIndex4; private int extraIndex5; private int firstNonBookIndex; private int fullNameOffset; private int fullNameLength; private int locale; private int inputLanguage; private int outputLanguage; private int minVersion; private int firstImageIndex; private int huffmanRecordOffset; private int huffmanRecordCount; private int huffmanTableOffset; private int huffmanTableLength; private int exthFlags; private int firstContentRecordIndex = 1; private int lastContentRecordIndex = -1; private int fcisRecordIndex; private int fcisRecordCount; private int flisRecordIndex; private int srcsRecordIndex = -1; private int srcsRecordCount; private int flisRecordCount; private int extraRecordDataFlags; private int indxRecordIndex = -1; private int fragmentRecordIndex = -1; private int skeletonRecordIndex = -1; private int datpRecordIndex = -1; private int guideIndex = -1; private EXTHHeader exthHeader; private byte[] remainder; // end of useful data private MobiContentHeader(byte[] content, long recordDataOffset, long recordDataLength) { super(getBytes(content, (int) recordDataOffset, (int) recordDataLength), CONTENT_TYPE.HEADER); this.recordDataOffset = (int) recordDataOffset; this.recordDataLength = (int) recordDataLength; } static MobiContentHeader readMobiHeader(byte[] content, long recordDataOffset, long recordDataLength) throws IOException { return new MobiContentHeader(content, recordDataOffset, recordDataLength).readMobiHeader(); } private MobiContentHeader readMobiHeader() throws IOException { // first 16 bytes of the PalmDOC Header followed by the MOBI header
compression = getInt(content, 0, 2);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentHeader.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class MobiContentHeader extends MobiContent { private static final int DEFAULT_HEADER_LENGTH = 264; /** Size of the extra bytes for the rest of mobi header*/ private static final int MOBI_HEADER_REST = 16; public static enum COMPRESSION_CODE { NONE(1), PALM_DOC(2), HUFF_CDIC(17480); private final int type; private static Map<Integer, COMPRESSION_CODE> map = new HashMap<Integer, COMPRESSION_CODE>(); static { for (COMPRESSION_CODE typeEnum : COMPRESSION_CODE.values()) { if(map.put(typeEnum.type, typeEnum) != null) { throw new IllegalArgumentException("Duplicate type " + typeEnum.type); } } } private COMPRESSION_CODE(final int type) { this.type = type; } public static COMPRESSION_CODE valueOf(int type) { return map.get(type); } public int getType() { return type; } } private int recordDataOffset; private int recordDataLength; private int compression; private int unused0; private int textLength; private int recordCount; private int recordSize; private int encryptionType; private int unused1; private int mobiType; private int textEncoding; private int uniqueID; private int fileVersion; private int orthographicIndex; private int inflectionIndex; private int indexNames; private int indexKeys; private int extraIndex0; private int extraIndex1; private int extraIndex2; private int extraIndex3; private int extraIndex4; private int extraIndex5; private int firstNonBookIndex; private int fullNameOffset; private int fullNameLength; private int locale; private int inputLanguage; private int outputLanguage; private int minVersion; private int firstImageIndex; private int huffmanRecordOffset; private int huffmanRecordCount; private int huffmanTableOffset; private int huffmanTableLength; private int exthFlags; private int firstContentRecordIndex = 1; private int lastContentRecordIndex = -1; private int fcisRecordIndex; private int fcisRecordCount; private int flisRecordIndex; private int srcsRecordIndex = -1; private int srcsRecordCount; private int flisRecordCount; private int extraRecordDataFlags; private int indxRecordIndex = -1; private int fragmentRecordIndex = -1; private int skeletonRecordIndex = -1; private int datpRecordIndex = -1; private int guideIndex = -1; private EXTHHeader exthHeader; private byte[] remainder; // end of useful data private MobiContentHeader(byte[] content, long recordDataOffset, long recordDataLength) { super(getBytes(content, (int) recordDataOffset, (int) recordDataLength), CONTENT_TYPE.HEADER); this.recordDataOffset = (int) recordDataOffset; this.recordDataLength = (int) recordDataLength; } static MobiContentHeader readMobiHeader(byte[] content, long recordDataOffset, long recordDataLength) throws IOException { return new MobiContentHeader(content, recordDataOffset, recordDataLength).readMobiHeader(); } private MobiContentHeader readMobiHeader() throws IOException { // first 16 bytes of the PalmDOC Header followed by the MOBI header compression = getInt(content, 0, 2); unused0 = getInt(content, 2, 2); textLength = getInt(content, 4, 4); recordCount = getInt(content, 8, 2); recordSize = getInt(content, 10, 2); encryptionType = getInt(content, 12, 2); unused1 = getInt(content, 14, 2);
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentHeader.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class MobiContentHeader extends MobiContent { private static final int DEFAULT_HEADER_LENGTH = 264; /** Size of the extra bytes for the rest of mobi header*/ private static final int MOBI_HEADER_REST = 16; public static enum COMPRESSION_CODE { NONE(1), PALM_DOC(2), HUFF_CDIC(17480); private final int type; private static Map<Integer, COMPRESSION_CODE> map = new HashMap<Integer, COMPRESSION_CODE>(); static { for (COMPRESSION_CODE typeEnum : COMPRESSION_CODE.values()) { if(map.put(typeEnum.type, typeEnum) != null) { throw new IllegalArgumentException("Duplicate type " + typeEnum.type); } } } private COMPRESSION_CODE(final int type) { this.type = type; } public static COMPRESSION_CODE valueOf(int type) { return map.get(type); } public int getType() { return type; } } private int recordDataOffset; private int recordDataLength; private int compression; private int unused0; private int textLength; private int recordCount; private int recordSize; private int encryptionType; private int unused1; private int mobiType; private int textEncoding; private int uniqueID; private int fileVersion; private int orthographicIndex; private int inflectionIndex; private int indexNames; private int indexKeys; private int extraIndex0; private int extraIndex1; private int extraIndex2; private int extraIndex3; private int extraIndex4; private int extraIndex5; private int firstNonBookIndex; private int fullNameOffset; private int fullNameLength; private int locale; private int inputLanguage; private int outputLanguage; private int minVersion; private int firstImageIndex; private int huffmanRecordOffset; private int huffmanRecordCount; private int huffmanTableOffset; private int huffmanTableLength; private int exthFlags; private int firstContentRecordIndex = 1; private int lastContentRecordIndex = -1; private int fcisRecordIndex; private int fcisRecordCount; private int flisRecordIndex; private int srcsRecordIndex = -1; private int srcsRecordCount; private int flisRecordCount; private int extraRecordDataFlags; private int indxRecordIndex = -1; private int fragmentRecordIndex = -1; private int skeletonRecordIndex = -1; private int datpRecordIndex = -1; private int guideIndex = -1; private EXTHHeader exthHeader; private byte[] remainder; // end of useful data private MobiContentHeader(byte[] content, long recordDataOffset, long recordDataLength) { super(getBytes(content, (int) recordDataOffset, (int) recordDataLength), CONTENT_TYPE.HEADER); this.recordDataOffset = (int) recordDataOffset; this.recordDataLength = (int) recordDataLength; } static MobiContentHeader readMobiHeader(byte[] content, long recordDataOffset, long recordDataLength) throws IOException { return new MobiContentHeader(content, recordDataOffset, recordDataLength).readMobiHeader(); } private MobiContentHeader readMobiHeader() throws IOException { // first 16 bytes of the PalmDOC Header followed by the MOBI header compression = getInt(content, 0, 2); unused0 = getInt(content, 2, 2); textLength = getInt(content, 4, 4); recordCount = getInt(content, 8, 2); recordSize = getInt(content, 10, 2); encryptionType = getInt(content, 12, 2); unused1 = getInt(content, 14, 2);
String identifier = getString(content, 16, 4);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentIndex.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
private int idxtIndex; private int indexCount; private int indexEncoding; private int indexLanguage; private int totalIndexCount; private int ordtIndex; private int ligtIndex; private int ordtLigtEntriesCount; private int cncxRecordCount; private byte[] unknownIndxHeaderPart; private byte[] rest; private MobiContentTagx tagx; MobiContentIndex(byte[] content) throws IOException { super(content, CONTENT_TYPE.INDEX); readMobiIndex(); } private void readMobiIndex() throws IOException {
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentIndex.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; private int idxtIndex; private int indexCount; private int indexEncoding; private int indexLanguage; private int totalIndexCount; private int ordtIndex; private int ligtIndex; private int ordtLigtEntriesCount; private int cncxRecordCount; private byte[] unknownIndxHeaderPart; private byte[] rest; private MobiContentTagx tagx; MobiContentIndex(byte[] content) throws IOException { super(content, CONTENT_TYPE.INDEX); readMobiIndex(); } private void readMobiIndex() throws IOException {
String identifier = getString(content, 0, 4);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentIndex.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
private int indexEncoding; private int indexLanguage; private int totalIndexCount; private int ordtIndex; private int ligtIndex; private int ordtLigtEntriesCount; private int cncxRecordCount; private byte[] unknownIndxHeaderPart; private byte[] rest; private MobiContentTagx tagx; MobiContentIndex(byte[] content) throws IOException { super(content, CONTENT_TYPE.INDEX); readMobiIndex(); } private void readMobiIndex() throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find index header identifier INDX but got '" + identifier + "' instead"); }
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentIndex.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; private int indexEncoding; private int indexLanguage; private int totalIndexCount; private int ordtIndex; private int ligtIndex; private int ordtLigtEntriesCount; private int cncxRecordCount; private byte[] unknownIndxHeaderPart; private byte[] rest; private MobiContentTagx tagx; MobiContentIndex(byte[] content) throws IOException { super(content, CONTENT_TYPE.INDEX); readMobiIndex(); } private void readMobiIndex() throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find index header identifier INDX but got '" + identifier + "' instead"); }
headerLength = getInt(content, 4, 4);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentIndex.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
private byte[] unknownIndxHeaderPart; private byte[] rest; private MobiContentTagx tagx; MobiContentIndex(byte[] content) throws IOException { super(content, CONTENT_TYPE.INDEX); readMobiIndex(); } private void readMobiIndex() throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find index header identifier INDX but got '" + identifier + "' instead"); } headerLength = getInt(content, 4, 4); indexType = getInt(content, 8, 4); unknown1 = getInt(content, 12, 4); unknown2 = getInt(content, 16, 4); idxtIndex = getInt(content, 20, 4); indexCount = getInt(content, 24, 4); // entries count indexEncoding = getInt(content, 28, 4); indexLanguage = getInt(content, 32, 4); totalIndexCount = getInt(content, 36, 4); // total entries count ordtIndex = getInt(content, 40, 4); ligtIndex = getInt(content, 44, 4); ordtLigtEntriesCount = getInt(content, 48, 4); cncxRecordCount = getInt(content, 52, 4); /* 60-148: phonetizer */
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentIndex.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; private byte[] unknownIndxHeaderPart; private byte[] rest; private MobiContentTagx tagx; MobiContentIndex(byte[] content) throws IOException { super(content, CONTENT_TYPE.INDEX); readMobiIndex(); } private void readMobiIndex() throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find index header identifier INDX but got '" + identifier + "' instead"); } headerLength = getInt(content, 4, 4); indexType = getInt(content, 8, 4); unknown1 = getInt(content, 12, 4); unknown2 = getInt(content, 16, 4); idxtIndex = getInt(content, 20, 4); indexCount = getInt(content, 24, 4); // entries count indexEncoding = getInt(content, 28, 4); indexLanguage = getInt(content, 32, 4); totalIndexCount = getInt(content, 36, 4); // total entries count ordtIndex = getInt(content, 40, 4); ligtIndex = getInt(content, 44, 4); ordtLigtEntriesCount = getInt(content, 48, 4); cncxRecordCount = getInt(content, 52, 4); /* 60-148: phonetizer */
unknownIndxHeaderPart = getBytes(content, 56, headerLength - 56);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentIndex.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
unknownIndxHeaderPart = getBytes(content, 56, headerLength - 56); int ordtType = getInt(content, 164, 4); int ordtEntriesCount = getInt(content, 168, 4); int ordt1Offset = getInt(content, 172, 4); int ordt2Offset = getInt(content, 176, 4); int entrySize = ordtType == 0 ? 1 : 2; int tagxIndex = getInt(content, 180, 4); int tagxNameLength = getInt(content, 184, 4); if(tagxIndex > 0) { tagx = new MobiContentTagx(getBytes(content, tagxIndex)); List<MobiContentTagEntry> tags = tagx.getTags(); for (MobiContentTagEntry tag : tags) { int value = tag.getControlByte() & tag.getBitmask(); } MobiContentIdxt idxt = new MobiContentIdxt(getBytes(content, idxtIndex), indexCount); rest = getBytes(content, tagxIndex + tagx.getSize()); } else { rest = getBytes(content, headerLength); } } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch);
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentIndex.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; unknownIndxHeaderPart = getBytes(content, 56, headerLength - 56); int ordtType = getInt(content, 164, 4); int ordtEntriesCount = getInt(content, 168, 4); int ordt1Offset = getInt(content, 172, 4); int ordt2Offset = getInt(content, 176, 4); int entrySize = ordtType == 0 ? 1 : 2; int tagxIndex = getInt(content, 180, 4); int tagxNameLength = getInt(content, 184, 4); if(tagxIndex > 0) { tagx = new MobiContentTagx(getBytes(content, tagxIndex)); List<MobiContentTagEntry> tags = tagx.getTags(); for (MobiContentTagEntry tag : tags) { int value = tag.getControlByte() & tag.getBitmask(); } MobiContentIdxt idxt = new MobiContentIdxt(getBytes(content, idxtIndex), indexCount); rest = getBytes(content, tagxIndex + tagx.getSize()); } else { rest = getBytes(content, headerLength); } } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch);
writeString(IDENTIFIER, 4, tee);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentIndex.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
int ordtType = getInt(content, 164, 4); int ordtEntriesCount = getInt(content, 168, 4); int ordt1Offset = getInt(content, 172, 4); int ordt2Offset = getInt(content, 176, 4); int entrySize = ordtType == 0 ? 1 : 2; int tagxIndex = getInt(content, 180, 4); int tagxNameLength = getInt(content, 184, 4); if(tagxIndex > 0) { tagx = new MobiContentTagx(getBytes(content, tagxIndex)); List<MobiContentTagEntry> tags = tagx.getTags(); for (MobiContentTagEntry tag : tags) { int value = tag.getControlByte() & tag.getBitmask(); } MobiContentIdxt idxt = new MobiContentIdxt(getBytes(content, idxtIndex), indexCount); rest = getBytes(content, tagxIndex + tagx.getSize()); } else { rest = getBytes(content, headerLength); } } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch); writeString(IDENTIFIER, 4, tee);
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentIndex.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; int ordtType = getInt(content, 164, 4); int ordtEntriesCount = getInt(content, 168, 4); int ordt1Offset = getInt(content, 172, 4); int ordt2Offset = getInt(content, 176, 4); int entrySize = ordtType == 0 ? 1 : 2; int tagxIndex = getInt(content, 180, 4); int tagxNameLength = getInt(content, 184, 4); if(tagxIndex > 0) { tagx = new MobiContentTagx(getBytes(content, tagxIndex)); List<MobiContentTagEntry> tags = tagx.getTags(); for (MobiContentTagEntry tag : tags) { int value = tag.getControlByte() & tag.getBitmask(); } MobiContentIdxt idxt = new MobiContentIdxt(getBytes(content, idxtIndex), indexCount); rest = getBytes(content, tagxIndex + tagx.getSize()); } else { rest = getBytes(content, headerLength); } } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch); writeString(IDENTIFIER, 4, tee);
writeInt(headerLength, 4, tee);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentIndex.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
int value = tag.getControlByte() & tag.getBitmask(); } MobiContentIdxt idxt = new MobiContentIdxt(getBytes(content, idxtIndex), indexCount); rest = getBytes(content, tagxIndex + tagx.getSize()); } else { rest = getBytes(content, headerLength); } } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch); writeString(IDENTIFIER, 4, tee); writeInt(headerLength, 4, tee); writeInt(indexType, 4, tee); writeInt(unknown1, 4, tee); writeInt(unknown2, 4, tee); writeInt(idxtIndex, 4, tee); writeInt(indexCount, 4, tee); writeInt(indexEncoding, 4, tee); writeInt(indexLanguage, 4, tee); writeInt(totalIndexCount, 4, tee); writeInt(ordtIndex, 4, tee); writeInt(ligtIndex, 4, tee); writeInt(ordtLigtEntriesCount, 4, tee); writeInt(cncxRecordCount, 4, tee);
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void write(byte[] data, OutputStream out) throws IOException { // write(data, data.length, out); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentIndex.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.write; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; int value = tag.getControlByte() & tag.getBitmask(); } MobiContentIdxt idxt = new MobiContentIdxt(getBytes(content, idxtIndex), indexCount); rest = getBytes(content, tagxIndex + tagx.getSize()); } else { rest = getBytes(content, headerLength); } } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch); writeString(IDENTIFIER, 4, tee); writeInt(headerLength, 4, tee); writeInt(indexType, 4, tee); writeInt(unknown1, 4, tee); writeInt(unknown2, 4, tee); writeInt(idxtIndex, 4, tee); writeInt(indexCount, 4, tee); writeInt(indexEncoding, 4, tee); writeInt(indexLanguage, 4, tee); writeInt(totalIndexCount, 4, tee); writeInt(ordtIndex, 4, tee); writeInt(ligtIndex, 4, tee); writeInt(ordtLigtEntriesCount, 4, tee); writeInt(cncxRecordCount, 4, tee);
write(unknownIndxHeaderPart, out);
rrauschenbach/mobi-api4java
src/test/java/org/rr/mobi4java/exth/ISBNRecordDelegateTest.java
// Path: src/main/java/org/rr/mobi4java/EXTHRecordFactory.java // public class EXTHRecordFactory { // // public static EXTHRecord createEXTHRecord(RECORD_TYPE recordType, byte[] recordData) { // EXTHRecord record = createEXTHRecord(recordType); // record.setRecordType(recordType); // record.setData(recordData); // return record; // } // // public static EXTHRecord createEXTHRecord(RECORD_TYPE recordType) { // return new EXTHRecord(recordType.getType()); // } // // /** // * Create a new asin record with the given asin as value. // * // * @param asinCode The asin code which must be a member of the list returned with // * {@link EXTHasinRecordDelegate#getasinCodes()}. // * @return A new asin record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static ASINRecordDelegate createASINRecord(String asin) { // assertNotNull(RECORD_TYPE.ASIN, asin); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.ASIN); // ASINRecordDelegate recordDelegate = new ASINRecordDelegate(record); // recordDelegate.setASIN(asin); // return recordDelegate; // } // // /** // * Create a new isbn record with the given isbn as value. // * // * @param isbnCode The isbn code which must be a member of the list returned with // * {@link EXTHisbnRecordDelegate#getisbnCodes()}. // * @return A new isbn record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static ISBNRecordDelegate createISBNRecord(String isbn) { // assertNotNull(RECORD_TYPE.ISBN, isbn); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.ISBN); // ISBNRecordDelegate recordDelegate = new ISBNRecordDelegate(record); // recordDelegate.setISBN(isbn); // return recordDelegate; // } // // /** // * Create a new language record with the given language as value. // * // * @param languageCode The language code which must be a member of the list returned with // * {@link LanguageRecordDelegate#getLanguageCodes()}. // * @return A new language record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static LanguageRecordDelegate createLanguageRecord(String languageCode) { // assertNotNull(RECORD_TYPE.LANGUAGE, languageCode); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.LANGUAGE); // LanguageRecordDelegate recordDelegate = new LanguageRecordDelegate(record); // recordDelegate.setLanguageCode(languageCode); // return recordDelegate; // } // // /** // * Create a new string record for the given record type and the given string as value. Please note that only some record types fits to a string type. // * // * @param recordType The record type for the result {@link StringRecordDelegate}. // * @param str The string value of the new record. // * @param encoding The encoding. Use {@link MobiDocument#getCharacterEncoding()} for the right document encoding. // * @return A new string record instance. // * @throws UnsupportedEncodingException if the given encoding is not supported by the java virtual machine. // */ // public static StringRecordDelegate createStringRecord(RECORD_TYPE recordType, String str, String encoding) throws UnsupportedEncodingException { // assertNotNull(recordType, str); // // EXTHRecord record = createEXTHRecord(recordType); // StringRecordDelegate recordDelegate = new StringRecordDelegate(record); // recordDelegate.setStringData(str, encoding); // return recordDelegate; // } // // /** // * Create a new date record for the given record type. Please note that only some record types fits to a date type. // * // * @param recordType The record type for the result {@link DateRecordDelegate}. // * @param date The date value of the new record. // * @return A new date record instance. // */ // public static DateRecordDelegate createDateRecord(RECORD_TYPE recordType, Date date) { // assertNotNull(recordType, date); // // EXTHRecord record = createEXTHRecord(recordType); // DateRecordDelegate recordDelegate = new DateRecordDelegate(record); // recordDelegate.setDateData(date); // return recordDelegate; // } // // static EXTHRecord readEXTHRecord(byte[] mobiHeader, int offset) throws IOException { // EXTHRecord record = createEXTHRecord(RECORD_TYPE.valueOf(getInt(mobiHeader, offset + 0, 4))); // return record.readEXTHRecord(mobiHeader, offset); // } // // private static void assertNotNull(RECORD_TYPE type, Object value) { // if(value == null) { // throw new IllegalArgumentException("The record type " + type + " must not be null."); // } // } // }
import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; import org.rr.mobi4java.EXTHRecordFactory;
package org.rr.mobi4java.exth; public class ISBNRecordDelegateTest { private static final String ISBN13_WITH_HYPHEN = "978-3-12-004811-4"; private static final String ISBN10_WITH_HYPEN = "3-12-004811-9"; private static final String ISBN13_RAW = "9783120048114"; private static final String ISBN10_RAW = "3120048119"; @Test public void testFormattedISBN13Input() throws IOException {
// Path: src/main/java/org/rr/mobi4java/EXTHRecordFactory.java // public class EXTHRecordFactory { // // public static EXTHRecord createEXTHRecord(RECORD_TYPE recordType, byte[] recordData) { // EXTHRecord record = createEXTHRecord(recordType); // record.setRecordType(recordType); // record.setData(recordData); // return record; // } // // public static EXTHRecord createEXTHRecord(RECORD_TYPE recordType) { // return new EXTHRecord(recordType.getType()); // } // // /** // * Create a new asin record with the given asin as value. // * // * @param asinCode The asin code which must be a member of the list returned with // * {@link EXTHasinRecordDelegate#getasinCodes()}. // * @return A new asin record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static ASINRecordDelegate createASINRecord(String asin) { // assertNotNull(RECORD_TYPE.ASIN, asin); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.ASIN); // ASINRecordDelegate recordDelegate = new ASINRecordDelegate(record); // recordDelegate.setASIN(asin); // return recordDelegate; // } // // /** // * Create a new isbn record with the given isbn as value. // * // * @param isbnCode The isbn code which must be a member of the list returned with // * {@link EXTHisbnRecordDelegate#getisbnCodes()}. // * @return A new isbn record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static ISBNRecordDelegate createISBNRecord(String isbn) { // assertNotNull(RECORD_TYPE.ISBN, isbn); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.ISBN); // ISBNRecordDelegate recordDelegate = new ISBNRecordDelegate(record); // recordDelegate.setISBN(isbn); // return recordDelegate; // } // // /** // * Create a new language record with the given language as value. // * // * @param languageCode The language code which must be a member of the list returned with // * {@link LanguageRecordDelegate#getLanguageCodes()}. // * @return A new language record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static LanguageRecordDelegate createLanguageRecord(String languageCode) { // assertNotNull(RECORD_TYPE.LANGUAGE, languageCode); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.LANGUAGE); // LanguageRecordDelegate recordDelegate = new LanguageRecordDelegate(record); // recordDelegate.setLanguageCode(languageCode); // return recordDelegate; // } // // /** // * Create a new string record for the given record type and the given string as value. Please note that only some record types fits to a string type. // * // * @param recordType The record type for the result {@link StringRecordDelegate}. // * @param str The string value of the new record. // * @param encoding The encoding. Use {@link MobiDocument#getCharacterEncoding()} for the right document encoding. // * @return A new string record instance. // * @throws UnsupportedEncodingException if the given encoding is not supported by the java virtual machine. // */ // public static StringRecordDelegate createStringRecord(RECORD_TYPE recordType, String str, String encoding) throws UnsupportedEncodingException { // assertNotNull(recordType, str); // // EXTHRecord record = createEXTHRecord(recordType); // StringRecordDelegate recordDelegate = new StringRecordDelegate(record); // recordDelegate.setStringData(str, encoding); // return recordDelegate; // } // // /** // * Create a new date record for the given record type. Please note that only some record types fits to a date type. // * // * @param recordType The record type for the result {@link DateRecordDelegate}. // * @param date The date value of the new record. // * @return A new date record instance. // */ // public static DateRecordDelegate createDateRecord(RECORD_TYPE recordType, Date date) { // assertNotNull(recordType, date); // // EXTHRecord record = createEXTHRecord(recordType); // DateRecordDelegate recordDelegate = new DateRecordDelegate(record); // recordDelegate.setDateData(date); // return recordDelegate; // } // // static EXTHRecord readEXTHRecord(byte[] mobiHeader, int offset) throws IOException { // EXTHRecord record = createEXTHRecord(RECORD_TYPE.valueOf(getInt(mobiHeader, offset + 0, 4))); // return record.readEXTHRecord(mobiHeader, offset); // } // // private static void assertNotNull(RECORD_TYPE type, Object value) { // if(value == null) { // throw new IllegalArgumentException("The record type " + type + " must not be null."); // } // } // } // Path: src/test/java/org/rr/mobi4java/exth/ISBNRecordDelegateTest.java import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; import org.rr.mobi4java.EXTHRecordFactory; package org.rr.mobi4java.exth; public class ISBNRecordDelegateTest { private static final String ISBN13_WITH_HYPHEN = "978-3-12-004811-4"; private static final String ISBN10_WITH_HYPEN = "3-12-004811-9"; private static final String ISBN13_RAW = "9783120048114"; private static final String ISBN10_RAW = "3120048119"; @Test public void testFormattedISBN13Input() throws IOException {
ISBNRecordDelegate record = EXTHRecordFactory.createISBNRecord(ISBN13_WITH_HYPHEN);
rrauschenbach/mobi-api4java
src/test/java/org/rr/mobi4java/TestEmptyTemplate.java
// Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static byte[] createJpegCover(int width, int height) throws IOException { // BufferedImage bufferedImage = new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB); // Graphics2D g = bufferedImage.createGraphics(); // g.drawLine(0, 0, width, height); // g.drawLine(width, 0, 0, height); // g.dispose(); // // return getImageBytes(bufferedImage, "image/jpeg"); // } // // Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static MobiDocument reReadDocument(MobiDocument doc) throws IOException { // byte[] newMobiData = writeDoc(doc); // MobiDocument newDoc = readDoc(newMobiData); // return newDoc; // } // // Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static void verifyRecordIndices(MobiContentHeader mobiHeader, List<MobiContent> mobiContents) { // assertEquals(MobiContent.CONTENT_TYPE.FCIS, mobiContents.get(mobiHeader.getFcisRecordIndex()).getType()); // assertEquals(MobiContent.CONTENT_TYPE.FLIS, mobiContents.get(mobiHeader.getFlisRecordIndex()).getType()); // // if (mobiHeader.getSrcsRecordIndex() != -1) { // assertEquals(MobiContent.CONTENT_TYPE.SRCS, mobiContents.get(mobiHeader.getSrcsRecordIndex()).getType()); // } // }
import static org.apache.commons.lang3.CharEncoding.UTF_8; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.rr.mobi4java.MobiTestUtils.createJpegCover; import static org.rr.mobi4java.MobiTestUtils.reReadDocument; import static org.rr.mobi4java.MobiTestUtils.verifyRecordIndices; import java.io.IOException; import java.util.Arrays; import java.util.Random; import org.junit.Test;
package org.rr.mobi4java; public class TestEmptyTemplate { @Test public void testCreateNewMobiDocument() throws IOException { MobiDocument doc = new MobiReader().empty(); assertNotNull(doc); assertEquals("<html><head><guide></guide></head><body><p></p></body></html>", doc.getTextContent()); assertEquals(EMPTY, doc.getFullName()); assertTrue(doc.getImageContents().isEmpty()); assertEquals(UTF_8, doc.getCharacterEncoding()); assertTrue(doc.getImages().isEmpty()); assertNull(doc.getThumbnail());
// Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static byte[] createJpegCover(int width, int height) throws IOException { // BufferedImage bufferedImage = new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB); // Graphics2D g = bufferedImage.createGraphics(); // g.drawLine(0, 0, width, height); // g.drawLine(width, 0, 0, height); // g.dispose(); // // return getImageBytes(bufferedImage, "image/jpeg"); // } // // Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static MobiDocument reReadDocument(MobiDocument doc) throws IOException { // byte[] newMobiData = writeDoc(doc); // MobiDocument newDoc = readDoc(newMobiData); // return newDoc; // } // // Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static void verifyRecordIndices(MobiContentHeader mobiHeader, List<MobiContent> mobiContents) { // assertEquals(MobiContent.CONTENT_TYPE.FCIS, mobiContents.get(mobiHeader.getFcisRecordIndex()).getType()); // assertEquals(MobiContent.CONTENT_TYPE.FLIS, mobiContents.get(mobiHeader.getFlisRecordIndex()).getType()); // // if (mobiHeader.getSrcsRecordIndex() != -1) { // assertEquals(MobiContent.CONTENT_TYPE.SRCS, mobiContents.get(mobiHeader.getSrcsRecordIndex()).getType()); // } // } // Path: src/test/java/org/rr/mobi4java/TestEmptyTemplate.java import static org.apache.commons.lang3.CharEncoding.UTF_8; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.rr.mobi4java.MobiTestUtils.createJpegCover; import static org.rr.mobi4java.MobiTestUtils.reReadDocument; import static org.rr.mobi4java.MobiTestUtils.verifyRecordIndices; import java.io.IOException; import java.util.Arrays; import java.util.Random; import org.junit.Test; package org.rr.mobi4java; public class TestEmptyTemplate { @Test public void testCreateNewMobiDocument() throws IOException { MobiDocument doc = new MobiReader().empty(); assertNotNull(doc); assertEquals("<html><head><guide></guide></head><body><p></p></body></html>", doc.getTextContent()); assertEquals(EMPTY, doc.getFullName()); assertTrue(doc.getImageContents().isEmpty()); assertEquals(UTF_8, doc.getCharacterEncoding()); assertTrue(doc.getImages().isEmpty()); assertNull(doc.getThumbnail());
verifyRecordIndices(doc.getMobiHeader(), doc.getMobiContents());
rrauschenbach/mobi-api4java
src/test/java/org/rr/mobi4java/TestEmptyTemplate.java
// Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static byte[] createJpegCover(int width, int height) throws IOException { // BufferedImage bufferedImage = new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB); // Graphics2D g = bufferedImage.createGraphics(); // g.drawLine(0, 0, width, height); // g.drawLine(width, 0, 0, height); // g.dispose(); // // return getImageBytes(bufferedImage, "image/jpeg"); // } // // Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static MobiDocument reReadDocument(MobiDocument doc) throws IOException { // byte[] newMobiData = writeDoc(doc); // MobiDocument newDoc = readDoc(newMobiData); // return newDoc; // } // // Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static void verifyRecordIndices(MobiContentHeader mobiHeader, List<MobiContent> mobiContents) { // assertEquals(MobiContent.CONTENT_TYPE.FCIS, mobiContents.get(mobiHeader.getFcisRecordIndex()).getType()); // assertEquals(MobiContent.CONTENT_TYPE.FLIS, mobiContents.get(mobiHeader.getFlisRecordIndex()).getType()); // // if (mobiHeader.getSrcsRecordIndex() != -1) { // assertEquals(MobiContent.CONTENT_TYPE.SRCS, mobiContents.get(mobiHeader.getSrcsRecordIndex()).getType()); // } // }
import static org.apache.commons.lang3.CharEncoding.UTF_8; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.rr.mobi4java.MobiTestUtils.createJpegCover; import static org.rr.mobi4java.MobiTestUtils.reReadDocument; import static org.rr.mobi4java.MobiTestUtils.verifyRecordIndices; import java.io.IOException; import java.util.Arrays; import java.util.Random; import org.junit.Test;
package org.rr.mobi4java; public class TestEmptyTemplate { @Test public void testCreateNewMobiDocument() throws IOException { MobiDocument doc = new MobiReader().empty(); assertNotNull(doc); assertEquals("<html><head><guide></guide></head><body><p></p></body></html>", doc.getTextContent()); assertEquals(EMPTY, doc.getFullName()); assertTrue(doc.getImageContents().isEmpty()); assertEquals(UTF_8, doc.getCharacterEncoding()); assertTrue(doc.getImages().isEmpty()); assertNull(doc.getThumbnail()); verifyRecordIndices(doc.getMobiHeader(), doc.getMobiContents());
// Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static byte[] createJpegCover(int width, int height) throws IOException { // BufferedImage bufferedImage = new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB); // Graphics2D g = bufferedImage.createGraphics(); // g.drawLine(0, 0, width, height); // g.drawLine(width, 0, 0, height); // g.dispose(); // // return getImageBytes(bufferedImage, "image/jpeg"); // } // // Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static MobiDocument reReadDocument(MobiDocument doc) throws IOException { // byte[] newMobiData = writeDoc(doc); // MobiDocument newDoc = readDoc(newMobiData); // return newDoc; // } // // Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static void verifyRecordIndices(MobiContentHeader mobiHeader, List<MobiContent> mobiContents) { // assertEquals(MobiContent.CONTENT_TYPE.FCIS, mobiContents.get(mobiHeader.getFcisRecordIndex()).getType()); // assertEquals(MobiContent.CONTENT_TYPE.FLIS, mobiContents.get(mobiHeader.getFlisRecordIndex()).getType()); // // if (mobiHeader.getSrcsRecordIndex() != -1) { // assertEquals(MobiContent.CONTENT_TYPE.SRCS, mobiContents.get(mobiHeader.getSrcsRecordIndex()).getType()); // } // } // Path: src/test/java/org/rr/mobi4java/TestEmptyTemplate.java import static org.apache.commons.lang3.CharEncoding.UTF_8; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.rr.mobi4java.MobiTestUtils.createJpegCover; import static org.rr.mobi4java.MobiTestUtils.reReadDocument; import static org.rr.mobi4java.MobiTestUtils.verifyRecordIndices; import java.io.IOException; import java.util.Arrays; import java.util.Random; import org.junit.Test; package org.rr.mobi4java; public class TestEmptyTemplate { @Test public void testCreateNewMobiDocument() throws IOException { MobiDocument doc = new MobiReader().empty(); assertNotNull(doc); assertEquals("<html><head><guide></guide></head><body><p></p></body></html>", doc.getTextContent()); assertEquals(EMPTY, doc.getFullName()); assertTrue(doc.getImageContents().isEmpty()); assertEquals(UTF_8, doc.getCharacterEncoding()); assertTrue(doc.getImages().isEmpty()); assertNull(doc.getThumbnail()); verifyRecordIndices(doc.getMobiHeader(), doc.getMobiContents());
MobiDocument newDoc = reReadDocument(doc);
rrauschenbach/mobi-api4java
src/test/java/org/rr/mobi4java/TestEmptyTemplate.java
// Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static byte[] createJpegCover(int width, int height) throws IOException { // BufferedImage bufferedImage = new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB); // Graphics2D g = bufferedImage.createGraphics(); // g.drawLine(0, 0, width, height); // g.drawLine(width, 0, 0, height); // g.dispose(); // // return getImageBytes(bufferedImage, "image/jpeg"); // } // // Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static MobiDocument reReadDocument(MobiDocument doc) throws IOException { // byte[] newMobiData = writeDoc(doc); // MobiDocument newDoc = readDoc(newMobiData); // return newDoc; // } // // Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static void verifyRecordIndices(MobiContentHeader mobiHeader, List<MobiContent> mobiContents) { // assertEquals(MobiContent.CONTENT_TYPE.FCIS, mobiContents.get(mobiHeader.getFcisRecordIndex()).getType()); // assertEquals(MobiContent.CONTENT_TYPE.FLIS, mobiContents.get(mobiHeader.getFlisRecordIndex()).getType()); // // if (mobiHeader.getSrcsRecordIndex() != -1) { // assertEquals(MobiContent.CONTENT_TYPE.SRCS, mobiContents.get(mobiHeader.getSrcsRecordIndex()).getType()); // } // }
import static org.apache.commons.lang3.CharEncoding.UTF_8; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.rr.mobi4java.MobiTestUtils.createJpegCover; import static org.rr.mobi4java.MobiTestUtils.reReadDocument; import static org.rr.mobi4java.MobiTestUtils.verifyRecordIndices; import java.io.IOException; import java.util.Arrays; import java.util.Random; import org.junit.Test;
package org.rr.mobi4java; public class TestEmptyTemplate { @Test public void testCreateNewMobiDocument() throws IOException { MobiDocument doc = new MobiReader().empty(); assertNotNull(doc); assertEquals("<html><head><guide></guide></head><body><p></p></body></html>", doc.getTextContent()); assertEquals(EMPTY, doc.getFullName()); assertTrue(doc.getImageContents().isEmpty()); assertEquals(UTF_8, doc.getCharacterEncoding()); assertTrue(doc.getImages().isEmpty()); assertNull(doc.getThumbnail()); verifyRecordIndices(doc.getMobiHeader(), doc.getMobiContents()); MobiDocument newDoc = reReadDocument(doc); verifyRecordIndices(newDoc.getMobiHeader(), newDoc.getMobiContents()); } @Test public void testCreateNewMobiDocumentAndAddThumbnailAndCover() throws IOException { MobiDocument doc = new MobiReader().empty();
// Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static byte[] createJpegCover(int width, int height) throws IOException { // BufferedImage bufferedImage = new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB); // Graphics2D g = bufferedImage.createGraphics(); // g.drawLine(0, 0, width, height); // g.drawLine(width, 0, 0, height); // g.dispose(); // // return getImageBytes(bufferedImage, "image/jpeg"); // } // // Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static MobiDocument reReadDocument(MobiDocument doc) throws IOException { // byte[] newMobiData = writeDoc(doc); // MobiDocument newDoc = readDoc(newMobiData); // return newDoc; // } // // Path: src/test/java/org/rr/mobi4java/MobiTestUtils.java // static void verifyRecordIndices(MobiContentHeader mobiHeader, List<MobiContent> mobiContents) { // assertEquals(MobiContent.CONTENT_TYPE.FCIS, mobiContents.get(mobiHeader.getFcisRecordIndex()).getType()); // assertEquals(MobiContent.CONTENT_TYPE.FLIS, mobiContents.get(mobiHeader.getFlisRecordIndex()).getType()); // // if (mobiHeader.getSrcsRecordIndex() != -1) { // assertEquals(MobiContent.CONTENT_TYPE.SRCS, mobiContents.get(mobiHeader.getSrcsRecordIndex()).getType()); // } // } // Path: src/test/java/org/rr/mobi4java/TestEmptyTemplate.java import static org.apache.commons.lang3.CharEncoding.UTF_8; import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.rr.mobi4java.MobiTestUtils.createJpegCover; import static org.rr.mobi4java.MobiTestUtils.reReadDocument; import static org.rr.mobi4java.MobiTestUtils.verifyRecordIndices; import java.io.IOException; import java.util.Arrays; import java.util.Random; import org.junit.Test; package org.rr.mobi4java; public class TestEmptyTemplate { @Test public void testCreateNewMobiDocument() throws IOException { MobiDocument doc = new MobiReader().empty(); assertNotNull(doc); assertEquals("<html><head><guide></guide></head><body><p></p></body></html>", doc.getTextContent()); assertEquals(EMPTY, doc.getFullName()); assertTrue(doc.getImageContents().isEmpty()); assertEquals(UTF_8, doc.getCharacterEncoding()); assertTrue(doc.getImages().isEmpty()); assertNull(doc.getThumbnail()); verifyRecordIndices(doc.getMobiHeader(), doc.getMobiContents()); MobiDocument newDoc = reReadDocument(doc); verifyRecordIndices(newDoc.getMobiHeader(), newDoc.getMobiContents()); } @Test public void testCreateNewMobiDocumentAndAddThumbnailAndCover() throws IOException { MobiDocument doc = new MobiReader().empty();
byte[] newCover = createJpegCover(100, 200);
rrauschenbach/mobi-api4java
src/test/java/org/rr/mobi4java/exth/LanguageRecordDelegateTest.java
// Path: src/main/java/org/rr/mobi4java/EXTHRecordFactory.java // public class EXTHRecordFactory { // // public static EXTHRecord createEXTHRecord(RECORD_TYPE recordType, byte[] recordData) { // EXTHRecord record = createEXTHRecord(recordType); // record.setRecordType(recordType); // record.setData(recordData); // return record; // } // // public static EXTHRecord createEXTHRecord(RECORD_TYPE recordType) { // return new EXTHRecord(recordType.getType()); // } // // /** // * Create a new asin record with the given asin as value. // * // * @param asinCode The asin code which must be a member of the list returned with // * {@link EXTHasinRecordDelegate#getasinCodes()}. // * @return A new asin record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static ASINRecordDelegate createASINRecord(String asin) { // assertNotNull(RECORD_TYPE.ASIN, asin); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.ASIN); // ASINRecordDelegate recordDelegate = new ASINRecordDelegate(record); // recordDelegate.setASIN(asin); // return recordDelegate; // } // // /** // * Create a new isbn record with the given isbn as value. // * // * @param isbnCode The isbn code which must be a member of the list returned with // * {@link EXTHisbnRecordDelegate#getisbnCodes()}. // * @return A new isbn record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static ISBNRecordDelegate createISBNRecord(String isbn) { // assertNotNull(RECORD_TYPE.ISBN, isbn); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.ISBN); // ISBNRecordDelegate recordDelegate = new ISBNRecordDelegate(record); // recordDelegate.setISBN(isbn); // return recordDelegate; // } // // /** // * Create a new language record with the given language as value. // * // * @param languageCode The language code which must be a member of the list returned with // * {@link LanguageRecordDelegate#getLanguageCodes()}. // * @return A new language record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static LanguageRecordDelegate createLanguageRecord(String languageCode) { // assertNotNull(RECORD_TYPE.LANGUAGE, languageCode); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.LANGUAGE); // LanguageRecordDelegate recordDelegate = new LanguageRecordDelegate(record); // recordDelegate.setLanguageCode(languageCode); // return recordDelegate; // } // // /** // * Create a new string record for the given record type and the given string as value. Please note that only some record types fits to a string type. // * // * @param recordType The record type for the result {@link StringRecordDelegate}. // * @param str The string value of the new record. // * @param encoding The encoding. Use {@link MobiDocument#getCharacterEncoding()} for the right document encoding. // * @return A new string record instance. // * @throws UnsupportedEncodingException if the given encoding is not supported by the java virtual machine. // */ // public static StringRecordDelegate createStringRecord(RECORD_TYPE recordType, String str, String encoding) throws UnsupportedEncodingException { // assertNotNull(recordType, str); // // EXTHRecord record = createEXTHRecord(recordType); // StringRecordDelegate recordDelegate = new StringRecordDelegate(record); // recordDelegate.setStringData(str, encoding); // return recordDelegate; // } // // /** // * Create a new date record for the given record type. Please note that only some record types fits to a date type. // * // * @param recordType The record type for the result {@link DateRecordDelegate}. // * @param date The date value of the new record. // * @return A new date record instance. // */ // public static DateRecordDelegate createDateRecord(RECORD_TYPE recordType, Date date) { // assertNotNull(recordType, date); // // EXTHRecord record = createEXTHRecord(recordType); // DateRecordDelegate recordDelegate = new DateRecordDelegate(record); // recordDelegate.setDateData(date); // return recordDelegate; // } // // static EXTHRecord readEXTHRecord(byte[] mobiHeader, int offset) throws IOException { // EXTHRecord record = createEXTHRecord(RECORD_TYPE.valueOf(getInt(mobiHeader, offset + 0, 4))); // return record.readEXTHRecord(mobiHeader, offset); // } // // private static void assertNotNull(RECORD_TYPE type, Object value) { // if(value == null) { // throw new IllegalArgumentException("The record type " + type + " must not be null."); // } // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import org.rr.mobi4java.EXTHRecordFactory;
package org.rr.mobi4java.exth; public class LanguageRecordDelegateTest { private static final String VALID_LANGUAGE_CODE = "de"; private static final String INVALID_LANGUAGE_CODE = "abc"; @Test public void testListLanguageCodes() { List<String> languageCodes = LanguageRecordDelegate.getLanguageCodes(); assertTrue(!languageCodes.isEmpty()); } @Test public void testCreateValidLanguageCode() {
// Path: src/main/java/org/rr/mobi4java/EXTHRecordFactory.java // public class EXTHRecordFactory { // // public static EXTHRecord createEXTHRecord(RECORD_TYPE recordType, byte[] recordData) { // EXTHRecord record = createEXTHRecord(recordType); // record.setRecordType(recordType); // record.setData(recordData); // return record; // } // // public static EXTHRecord createEXTHRecord(RECORD_TYPE recordType) { // return new EXTHRecord(recordType.getType()); // } // // /** // * Create a new asin record with the given asin as value. // * // * @param asinCode The asin code which must be a member of the list returned with // * {@link EXTHasinRecordDelegate#getasinCodes()}. // * @return A new asin record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static ASINRecordDelegate createASINRecord(String asin) { // assertNotNull(RECORD_TYPE.ASIN, asin); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.ASIN); // ASINRecordDelegate recordDelegate = new ASINRecordDelegate(record); // recordDelegate.setASIN(asin); // return recordDelegate; // } // // /** // * Create a new isbn record with the given isbn as value. // * // * @param isbnCode The isbn code which must be a member of the list returned with // * {@link EXTHisbnRecordDelegate#getisbnCodes()}. // * @return A new isbn record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static ISBNRecordDelegate createISBNRecord(String isbn) { // assertNotNull(RECORD_TYPE.ISBN, isbn); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.ISBN); // ISBNRecordDelegate recordDelegate = new ISBNRecordDelegate(record); // recordDelegate.setISBN(isbn); // return recordDelegate; // } // // /** // * Create a new language record with the given language as value. // * // * @param languageCode The language code which must be a member of the list returned with // * {@link LanguageRecordDelegate#getLanguageCodes()}. // * @return A new language record instance. // * @throws IllegalArgumentException if the given code is not valid. // */ // public static LanguageRecordDelegate createLanguageRecord(String languageCode) { // assertNotNull(RECORD_TYPE.LANGUAGE, languageCode); // // EXTHRecord record = createEXTHRecord(RECORD_TYPE.LANGUAGE); // LanguageRecordDelegate recordDelegate = new LanguageRecordDelegate(record); // recordDelegate.setLanguageCode(languageCode); // return recordDelegate; // } // // /** // * Create a new string record for the given record type and the given string as value. Please note that only some record types fits to a string type. // * // * @param recordType The record type for the result {@link StringRecordDelegate}. // * @param str The string value of the new record. // * @param encoding The encoding. Use {@link MobiDocument#getCharacterEncoding()} for the right document encoding. // * @return A new string record instance. // * @throws UnsupportedEncodingException if the given encoding is not supported by the java virtual machine. // */ // public static StringRecordDelegate createStringRecord(RECORD_TYPE recordType, String str, String encoding) throws UnsupportedEncodingException { // assertNotNull(recordType, str); // // EXTHRecord record = createEXTHRecord(recordType); // StringRecordDelegate recordDelegate = new StringRecordDelegate(record); // recordDelegate.setStringData(str, encoding); // return recordDelegate; // } // // /** // * Create a new date record for the given record type. Please note that only some record types fits to a date type. // * // * @param recordType The record type for the result {@link DateRecordDelegate}. // * @param date The date value of the new record. // * @return A new date record instance. // */ // public static DateRecordDelegate createDateRecord(RECORD_TYPE recordType, Date date) { // assertNotNull(recordType, date); // // EXTHRecord record = createEXTHRecord(recordType); // DateRecordDelegate recordDelegate = new DateRecordDelegate(record); // recordDelegate.setDateData(date); // return recordDelegate; // } // // static EXTHRecord readEXTHRecord(byte[] mobiHeader, int offset) throws IOException { // EXTHRecord record = createEXTHRecord(RECORD_TYPE.valueOf(getInt(mobiHeader, offset + 0, 4))); // return record.readEXTHRecord(mobiHeader, offset); // } // // private static void assertNotNull(RECORD_TYPE type, Object value) { // if(value == null) { // throw new IllegalArgumentException("The record type " + type + " must not be null."); // } // } // } // Path: src/test/java/org/rr/mobi4java/exth/LanguageRecordDelegateTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import org.rr.mobi4java.EXTHRecordFactory; package org.rr.mobi4java.exth; public class LanguageRecordDelegateTest { private static final String VALID_LANGUAGE_CODE = "de"; private static final String INVALID_LANGUAGE_CODE = "abc"; @Test public void testListLanguageCodes() { List<String> languageCodes = LanguageRecordDelegate.getLanguageCodes(); assertTrue(!languageCodes.isEmpty()); } @Test public void testCreateValidLanguageCode() {
LanguageRecordDelegate deLanguageRecord = EXTHRecordFactory.createLanguageRecord(VALID_LANGUAGE_CODE);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentTagx.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class MobiContentTagx extends MobiContent { private static final String IDENTIFIER = "TAGX"; private int headerLength; private int controlByteCount; private byte[] tagTable; private List<MobiContentTagEntry> tags; MobiContentTagx(byte[] content) throws IOException { super(content, CONTENT_TYPE.TAGX); readMobiTagx(); } private void readMobiTagx() throws IOException {
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentTagx.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class MobiContentTagx extends MobiContent { private static final String IDENTIFIER = "TAGX"; private int headerLength; private int controlByteCount; private byte[] tagTable; private List<MobiContentTagEntry> tags; MobiContentTagx(byte[] content) throws IOException { super(content, CONTENT_TYPE.TAGX); readMobiTagx(); } private void readMobiTagx() throws IOException {
String identifier = getString(content, 0, 4);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentTagx.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class MobiContentTagx extends MobiContent { private static final String IDENTIFIER = "TAGX"; private int headerLength; private int controlByteCount; private byte[] tagTable; private List<MobiContentTagEntry> tags; MobiContentTagx(byte[] content) throws IOException { super(content, CONTENT_TYPE.TAGX); readMobiTagx(); } private void readMobiTagx() throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find TAGX header identifier TAGX but got '" + identifier + "' instead"); }
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentTagx.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class MobiContentTagx extends MobiContent { private static final String IDENTIFIER = "TAGX"; private int headerLength; private int controlByteCount; private byte[] tagTable; private List<MobiContentTagEntry> tags; MobiContentTagx(byte[] content) throws IOException { super(content, CONTENT_TYPE.TAGX); readMobiTagx(); } private void readMobiTagx() throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find TAGX header identifier TAGX but got '" + identifier + "' instead"); }
headerLength = getInt(content, 4, 4);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentTagx.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class MobiContentTagx extends MobiContent { private static final String IDENTIFIER = "TAGX"; private int headerLength; private int controlByteCount; private byte[] tagTable; private List<MobiContentTagEntry> tags; MobiContentTagx(byte[] content) throws IOException { super(content, CONTENT_TYPE.TAGX); readMobiTagx(); } private void readMobiTagx() throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find TAGX header identifier TAGX but got '" + identifier + "' instead"); } headerLength = getInt(content, 4, 4); controlByteCount = getInt(content, 8, 4); int tagCount = (headerLength - 12) / 4;
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentTagx.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class MobiContentTagx extends MobiContent { private static final String IDENTIFIER = "TAGX"; private int headerLength; private int controlByteCount; private byte[] tagTable; private List<MobiContentTagEntry> tags; MobiContentTagx(byte[] content) throws IOException { super(content, CONTENT_TYPE.TAGX); readMobiTagx(); } private void readMobiTagx() throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find TAGX header identifier TAGX but got '" + identifier + "' instead"); } headerLength = getInt(content, 4, 4); controlByteCount = getInt(content, 8, 4); int tagCount = (headerLength - 12) / 4;
tagTable = getBytes(content, 12, headerLength - 12);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentTagx.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class MobiContentTagx extends MobiContent { private static final String IDENTIFIER = "TAGX"; private int headerLength; private int controlByteCount; private byte[] tagTable; private List<MobiContentTagEntry> tags; MobiContentTagx(byte[] content) throws IOException { super(content, CONTENT_TYPE.TAGX); readMobiTagx(); } private void readMobiTagx() throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find TAGX header identifier TAGX but got '" + identifier + "' instead"); } headerLength = getInt(content, 4, 4); controlByteCount = getInt(content, 8, 4); int tagCount = (headerLength - 12) / 4; tagTable = getBytes(content, 12, headerLength - 12); tags = new ArrayList<>(tagCount); for (int i = 0; i < tagCount; i++) { MobiContentTagEntry mobiContentTag = new MobiContentTagEntry(getBytes(content, 12 + (4 * i), 4)); tags.add(mobiContentTag); } } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch);
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentTagx.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class MobiContentTagx extends MobiContent { private static final String IDENTIFIER = "TAGX"; private int headerLength; private int controlByteCount; private byte[] tagTable; private List<MobiContentTagEntry> tags; MobiContentTagx(byte[] content) throws IOException { super(content, CONTENT_TYPE.TAGX); readMobiTagx(); } private void readMobiTagx() throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find TAGX header identifier TAGX but got '" + identifier + "' instead"); } headerLength = getInt(content, 4, 4); controlByteCount = getInt(content, 8, 4); int tagCount = (headerLength - 12) / 4; tagTable = getBytes(content, 12, headerLength - 12); tags = new ArrayList<>(tagCount); for (int i = 0; i < tagCount; i++) { MobiContentTagEntry mobiContentTag = new MobiContentTagEntry(getBytes(content, 12 + (4 * i), 4)); tags.add(mobiContentTag); } } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch);
writeString(IDENTIFIER, 4, tee);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentTagx.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
private List<MobiContentTagEntry> tags; MobiContentTagx(byte[] content) throws IOException { super(content, CONTENT_TYPE.TAGX); readMobiTagx(); } private void readMobiTagx() throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find TAGX header identifier TAGX but got '" + identifier + "' instead"); } headerLength = getInt(content, 4, 4); controlByteCount = getInt(content, 8, 4); int tagCount = (headerLength - 12) / 4; tagTable = getBytes(content, 12, headerLength - 12); tags = new ArrayList<>(tagCount); for (int i = 0; i < tagCount; i++) { MobiContentTagEntry mobiContentTag = new MobiContentTagEntry(getBytes(content, 12 + (4 * i), 4)); tags.add(mobiContentTag); } } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch); writeString(IDENTIFIER, 4, tee);
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static byte[] getBytes(byte[] buffer, int offset) { // byte[] b = new byte[buffer.length - offset]; // System.arraycopy(buffer, offset, b, 0, buffer.length - offset); // return b; // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentTagx.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getBytes; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; private List<MobiContentTagEntry> tags; MobiContentTagx(byte[] content) throws IOException { super(content, CONTENT_TYPE.TAGX); readMobiTagx(); } private void readMobiTagx() throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find TAGX header identifier TAGX but got '" + identifier + "' instead"); } headerLength = getInt(content, 4, 4); controlByteCount = getInt(content, 8, 4); int tagCount = (headerLength - 12) / 4; tagTable = getBytes(content, 12, headerLength - 12); tags = new ArrayList<>(tagCount); for (int i = 0; i < tagCount; i++) { MobiContentTagEntry mobiContentTag = new MobiContentTagEntry(getBytes(content, 12 + (4 * i), 4)); tags.add(mobiContentTag); } } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch); writeString(IDENTIFIER, 4, tee);
writeInt(headerLength, 4, tee);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentIdxt.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class MobiContentIdxt extends MobiContent { private static final String IDENTIFIER = "IDXT"; private int[] indexEntriesIndices; private int indexEntriesCount; MobiContentIdxt(byte[] content, int entriesCount) throws IOException { super(content, CONTENT_TYPE.IDXT); readMobiIdxt(entriesCount); } private void readMobiIdxt(int entriesCount) throws IOException {
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentIdxt.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class MobiContentIdxt extends MobiContent { private static final String IDENTIFIER = "IDXT"; private int[] indexEntriesIndices; private int indexEntriesCount; MobiContentIdxt(byte[] content, int entriesCount) throws IOException { super(content, CONTENT_TYPE.IDXT); readMobiIdxt(entriesCount); } private void readMobiIdxt(int entriesCount) throws IOException {
String identifier = getString(content, 0, 4);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentIdxt.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class MobiContentIdxt extends MobiContent { private static final String IDENTIFIER = "IDXT"; private int[] indexEntriesIndices; private int indexEntriesCount; MobiContentIdxt(byte[] content, int entriesCount) throws IOException { super(content, CONTENT_TYPE.IDXT); readMobiIdxt(entriesCount); } private void readMobiIdxt(int entriesCount) throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find IDXT header identifier IDXT but got '" + identifier + "' instead"); } indexEntriesIndices = new int[entriesCount]; for (int i = 0; i < entriesCount; i++) {
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentIdxt.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class MobiContentIdxt extends MobiContent { private static final String IDENTIFIER = "IDXT"; private int[] indexEntriesIndices; private int indexEntriesCount; MobiContentIdxt(byte[] content, int entriesCount) throws IOException { super(content, CONTENT_TYPE.IDXT); readMobiIdxt(entriesCount); } private void readMobiIdxt(int entriesCount) throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find IDXT header identifier IDXT but got '" + identifier + "' instead"); } indexEntriesIndices = new int[entriesCount]; for (int i = 0; i < entriesCount; i++) {
indexEntriesIndices[i] = getInt(content, 4 + (i * 2), 2);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentIdxt.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class MobiContentIdxt extends MobiContent { private static final String IDENTIFIER = "IDXT"; private int[] indexEntriesIndices; private int indexEntriesCount; MobiContentIdxt(byte[] content, int entriesCount) throws IOException { super(content, CONTENT_TYPE.IDXT); readMobiIdxt(entriesCount); } private void readMobiIdxt(int entriesCount) throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find IDXT header identifier IDXT but got '" + identifier + "' instead"); } indexEntriesIndices = new int[entriesCount]; for (int i = 0; i < entriesCount; i++) { indexEntriesIndices[i] = getInt(content, 4 + (i * 2), 2); } indexEntriesCount = getInt(content, 4 + (indexEntriesIndices.length * 2), 2); } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch);
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentIdxt.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class MobiContentIdxt extends MobiContent { private static final String IDENTIFIER = "IDXT"; private int[] indexEntriesIndices; private int indexEntriesCount; MobiContentIdxt(byte[] content, int entriesCount) throws IOException { super(content, CONTENT_TYPE.IDXT); readMobiIdxt(entriesCount); } private void readMobiIdxt(int entriesCount) throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find IDXT header identifier IDXT but got '" + identifier + "' instead"); } indexEntriesIndices = new int[entriesCount]; for (int i = 0; i < entriesCount; i++) { indexEntriesIndices[i] = getInt(content, 4 + (i * 2), 2); } indexEntriesCount = getInt(content, 4 + (indexEntriesIndices.length * 2), 2); } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch);
writeString(IDENTIFIER, 4, tee);
rrauschenbach/mobi-api4java
src/main/java/org/rr/mobi4java/MobiContentIdxt.java
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // }
import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder;
package org.rr.mobi4java; public class MobiContentIdxt extends MobiContent { private static final String IDENTIFIER = "IDXT"; private int[] indexEntriesIndices; private int indexEntriesCount; MobiContentIdxt(byte[] content, int entriesCount) throws IOException { super(content, CONTENT_TYPE.IDXT); readMobiIdxt(entriesCount); } private void readMobiIdxt(int entriesCount) throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find IDXT header identifier IDXT but got '" + identifier + "' instead"); } indexEntriesIndices = new int[entriesCount]; for (int i = 0; i < entriesCount; i++) { indexEntriesIndices[i] = getInt(content, 4 + (i * 2), 2); } indexEntriesCount = getInt(content, 4 + (indexEntriesIndices.length * 2), 2); } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch); writeString(IDENTIFIER, 4, tee); for (int indexEntriesIndex : indexEntriesIndices) {
// Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static int getInt(byte[] buffer, int offset, int length) { // return getInt(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static String getString(byte[] buffer, int offset, int length) { // return getString(getBytes(buffer, offset, length)); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeInt(int data, int length, OutputStream out) throws IOException { // out.write(getBytes(data, new byte[length]), 0, length); // } // // Path: src/main/java/org/rr/mobi4java/ByteUtils.java // public static void writeString(String data, int length, OutputStream out) throws IOException { // byte[] s = getBytes(data); // byte[] b = new byte[length]; // System.arraycopy(s, 0, b, 0, s.length); // out.write(b, 0, length); // } // Path: src/main/java/org/rr/mobi4java/MobiContentIdxt.java import static org.apache.commons.lang3.BooleanUtils.negate; import static org.rr.mobi4java.ByteUtils.getInt; import static org.rr.mobi4java.ByteUtils.getString; import static org.rr.mobi4java.ByteUtils.writeInt; import static org.rr.mobi4java.ByteUtils.writeString; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.io.output.TeeOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; package org.rr.mobi4java; public class MobiContentIdxt extends MobiContent { private static final String IDENTIFIER = "IDXT"; private int[] indexEntriesIndices; private int indexEntriesCount; MobiContentIdxt(byte[] content, int entriesCount) throws IOException { super(content, CONTENT_TYPE.IDXT); readMobiIdxt(entriesCount); } private void readMobiIdxt(int entriesCount) throws IOException { String identifier = getString(content, 0, 4); if (negate(StringUtils.equals(identifier, IDENTIFIER))) { throw new IOException("Expected to find IDXT header identifier IDXT but got '" + identifier + "' instead"); } indexEntriesIndices = new int[entriesCount]; for (int i = 0; i < entriesCount; i++) { indexEntriesIndices[i] = getInt(content, 4 + (i * 2), 2); } indexEntriesCount = getInt(content, 4 + (indexEntriesIndices.length * 2), 2); } @Override byte[] writeContent(OutputStream out) throws IOException { ByteArrayOutputStream branch = new ByteArrayOutputStream(); TeeOutputStream tee = new TeeOutputStream(out, branch); writeString(IDENTIFIER, 4, tee); for (int indexEntriesIndex : indexEntriesIndices) {
writeInt(indexEntriesIndex, 2, tee);
Jigsaw-Code/Intra
Android/app/src/main/java/app/intra/sys/NetworkManager.java
// Path: Android/app/src/main/java/app/intra/sys/firebase/LogWrapper.java // public class LogWrapper { // public static void logException(Throwable t) { // Log.e("LogWrapper", "Error", t); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().recordException(t); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // // public static void log(int severity, String tag, String message) { // Log.println(severity, tag, message); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().log(tag + ": " + message); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.util.Log; import app.intra.sys.firebase.LogWrapper; import java.lang.reflect.Method; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collection; import java.util.List;
return false; } return networkInfo.isConnectedOrConnecting() && networkInfo.isAvailable(); } /** * Post-Lollipop, we can use VpnService.Builder.addDisallowedApplication to exclude Intra from its * own VPN. If for some reason we needed to get the IP address of the non-VPN resolvers, we could * use ConnectivityManager.getActiveNetwork().getLinkProperties().getDnsServers(). * * Pre-Lollipop, there is no official way to get the non-VPN DNS servers, but we need them in * order to do DNS lookups on protected sockets in Go, in order to resolve DNS server names when * the current server connection is broken, without disabling the VPN. This implementation * exposes the hidden version of LinkProperties that was present prior to Lollipop, in order to * extract the DNS server IPs. * * @return The (unencrypted) DNS servers used by the underlying networks. */ List<InetAddress> getSystemResolvers() { // This list of network types is in roughly descending priority order, so that the first // entries in the returned list are most likely to be the appropriate resolvers. int[] networkTypes = new int[]{ ConnectivityManager.TYPE_ETHERNET, ConnectivityManager.TYPE_WIFI, ConnectivityManager.TYPE_MOBILE, ConnectivityManager.TYPE_WIMAX, }; List<InetAddress> resolvers = new ArrayList<>(); if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
// Path: Android/app/src/main/java/app/intra/sys/firebase/LogWrapper.java // public class LogWrapper { // public static void logException(Throwable t) { // Log.e("LogWrapper", "Error", t); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().recordException(t); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // // public static void log(int severity, String tag, String message) { // Log.println(severity, tag, message); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().log(tag + ": " + message); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // } // Path: Android/app/src/main/java/app/intra/sys/NetworkManager.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.util.Log; import app.intra.sys.firebase.LogWrapper; import java.lang.reflect.Method; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collection; import java.util.List; return false; } return networkInfo.isConnectedOrConnecting() && networkInfo.isAvailable(); } /** * Post-Lollipop, we can use VpnService.Builder.addDisallowedApplication to exclude Intra from its * own VPN. If for some reason we needed to get the IP address of the non-VPN resolvers, we could * use ConnectivityManager.getActiveNetwork().getLinkProperties().getDnsServers(). * * Pre-Lollipop, there is no official way to get the non-VPN DNS servers, but we need them in * order to do DNS lookups on protected sockets in Go, in order to resolve DNS server names when * the current server connection is broken, without disabling the VPN. This implementation * exposes the hidden version of LinkProperties that was present prior to Lollipop, in order to * extract the DNS server IPs. * * @return The (unencrypted) DNS servers used by the underlying networks. */ List<InetAddress> getSystemResolvers() { // This list of network types is in roughly descending priority order, so that the first // entries in the returned list are most likely to be the appropriate resolvers. int[] networkTypes = new int[]{ ConnectivityManager.TYPE_ETHERNET, ConnectivityManager.TYPE_WIFI, ConnectivityManager.TYPE_MOBILE, ConnectivityManager.TYPE_WIMAX, }; List<InetAddress> resolvers = new ArrayList<>(); if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
LogWrapper.log(Log.ASSERT, LOG_TAG, "This function should never be called in L+.");
Jigsaw-Code/Intra
Android/app/src/main/java/app/intra/net/go/GoProber.java
// Path: Android/app/src/main/java/app/intra/net/doh/Prober.java // public abstract class Prober { // // protected static final byte[] QUERY_DATA = { // 0, 0, // [0-1] query ID // 1, 0, // [2-3] flags, RD=1 // 0, 1, // [4-5] QDCOUNT (number of queries) = 1 // 0, 0, // [6-7] ANCOUNT (number of answers) = 0 // 0, 0, // [8-9] NSCOUNT (number of authoritative answers) = 0 // 0, 0, // [10-11] ARCOUNT (number of additional records) = 0 // // Start of first query // 7, 'y', 'o', 'u', 't', 'u', 'b', 'e', // 3, 'c', 'o', 'm', // 0, // null terminator of FQDN (DNS root) // 0, 1, // QTYPE = A // 0, 1 // QCLASS = IN (Internet) // }; // // public interface Callback { // void onCompleted(boolean succeeded); // } // // /** // * Called to execute the probe on a new thread. // * @param url The DOH server URL to probe. // * @param callback How to report the probe results // */ // public abstract void probe(String url, Callback callback); // } // // Path: Android/app/src/main/java/app/intra/sys/VpnController.java // public class VpnController { // // private static VpnController dnsVpnServiceState; // // public Object clone() throws CloneNotSupportedException { // throw new CloneNotSupportedException(); // } // // public static synchronized VpnController getInstance() { // if (dnsVpnServiceState == null) { // dnsVpnServiceState = new VpnController(); // } // return dnsVpnServiceState; // } // // private IntraVpnService intraVpnService = null; // private IntraVpnService.State connectionState = null; // private QueryTracker tracker = null; // // private VpnController() {} // // void setIntraVpnService(IntraVpnService intraVpnService) { // this.intraVpnService = intraVpnService; // } // // public @Nullable IntraVpnService getIntraVpnService() { // return this.intraVpnService; // } // // public synchronized void onConnectionStateChanged(Context context, IntraVpnService.State state) { // if (intraVpnService == null) { // // User clicked disable while the connection state was changing. // return; // } // connectionState = state; // stateChanged(context); // } // // private void stateChanged(Context context) { // Intent broadcast = new Intent(InternalNames.DNS_STATUS.name()); // LocalBroadcastManager.getInstance(context).sendBroadcast(broadcast); // } // // public synchronized QueryTracker getTracker(Context context) { // if (tracker == null) { // tracker = new QueryTracker(context); // } // return tracker; // } // // public synchronized void start(Context context) { // if (intraVpnService != null) { // return; // } // PersistentState.setVpnEnabled(context, true); // stateChanged(context); // Intent startServiceIntent = new Intent(context, IntraVpnService.class); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // context.startForegroundService(startServiceIntent); // } else { // context.startService(startServiceIntent); // } // } // // synchronized void onStartComplete(Context context, boolean succeeded) { // if (!succeeded) { // // VPN setup only fails if VPN permission has been revoked. If this happens, clear the // // user intent state and reset to the default state. // stop(context); // } else { // stateChanged(context); // } // } // // public synchronized void stop(Context context) { // PersistentState.setVpnEnabled(context, false); // connectionState = null; // if (intraVpnService != null) { // intraVpnService.signalStopService(true); // } // intraVpnService = null; // stateChanged(context); // } // // public synchronized VpnState getState(Context context) { // boolean requested = PersistentState.getVpnEnabled(context); // boolean on = intraVpnService != null && intraVpnService.isOn(); // return new VpnState(requested, on, connectionState); // } // // }
import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import app.intra.net.doh.Prober; import app.intra.sys.VpnController; import doh.Transport; import protect.Protector; import tun2socks.Tun2socks;
/* Copyright 2019 Jigsaw Operations LLC 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 https://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 app.intra.net.go; /** * Implements a Probe using the Go-based DoH client. */ public class GoProber extends Prober { private final Context context; public GoProber(Context context) { this.context = context; } @Override public void probe(String url, Callback callback) { new Thread(() -> { String dohIPs = GoVpnAdapter.getIpString(context, url); try { // Protection isn't needed for Lollipop+, or if the VPN is not active. Protector protector = VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP ? null :
// Path: Android/app/src/main/java/app/intra/net/doh/Prober.java // public abstract class Prober { // // protected static final byte[] QUERY_DATA = { // 0, 0, // [0-1] query ID // 1, 0, // [2-3] flags, RD=1 // 0, 1, // [4-5] QDCOUNT (number of queries) = 1 // 0, 0, // [6-7] ANCOUNT (number of answers) = 0 // 0, 0, // [8-9] NSCOUNT (number of authoritative answers) = 0 // 0, 0, // [10-11] ARCOUNT (number of additional records) = 0 // // Start of first query // 7, 'y', 'o', 'u', 't', 'u', 'b', 'e', // 3, 'c', 'o', 'm', // 0, // null terminator of FQDN (DNS root) // 0, 1, // QTYPE = A // 0, 1 // QCLASS = IN (Internet) // }; // // public interface Callback { // void onCompleted(boolean succeeded); // } // // /** // * Called to execute the probe on a new thread. // * @param url The DOH server URL to probe. // * @param callback How to report the probe results // */ // public abstract void probe(String url, Callback callback); // } // // Path: Android/app/src/main/java/app/intra/sys/VpnController.java // public class VpnController { // // private static VpnController dnsVpnServiceState; // // public Object clone() throws CloneNotSupportedException { // throw new CloneNotSupportedException(); // } // // public static synchronized VpnController getInstance() { // if (dnsVpnServiceState == null) { // dnsVpnServiceState = new VpnController(); // } // return dnsVpnServiceState; // } // // private IntraVpnService intraVpnService = null; // private IntraVpnService.State connectionState = null; // private QueryTracker tracker = null; // // private VpnController() {} // // void setIntraVpnService(IntraVpnService intraVpnService) { // this.intraVpnService = intraVpnService; // } // // public @Nullable IntraVpnService getIntraVpnService() { // return this.intraVpnService; // } // // public synchronized void onConnectionStateChanged(Context context, IntraVpnService.State state) { // if (intraVpnService == null) { // // User clicked disable while the connection state was changing. // return; // } // connectionState = state; // stateChanged(context); // } // // private void stateChanged(Context context) { // Intent broadcast = new Intent(InternalNames.DNS_STATUS.name()); // LocalBroadcastManager.getInstance(context).sendBroadcast(broadcast); // } // // public synchronized QueryTracker getTracker(Context context) { // if (tracker == null) { // tracker = new QueryTracker(context); // } // return tracker; // } // // public synchronized void start(Context context) { // if (intraVpnService != null) { // return; // } // PersistentState.setVpnEnabled(context, true); // stateChanged(context); // Intent startServiceIntent = new Intent(context, IntraVpnService.class); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // context.startForegroundService(startServiceIntent); // } else { // context.startService(startServiceIntent); // } // } // // synchronized void onStartComplete(Context context, boolean succeeded) { // if (!succeeded) { // // VPN setup only fails if VPN permission has been revoked. If this happens, clear the // // user intent state and reset to the default state. // stop(context); // } else { // stateChanged(context); // } // } // // public synchronized void stop(Context context) { // PersistentState.setVpnEnabled(context, false); // connectionState = null; // if (intraVpnService != null) { // intraVpnService.signalStopService(true); // } // intraVpnService = null; // stateChanged(context); // } // // public synchronized VpnState getState(Context context) { // boolean requested = PersistentState.getVpnEnabled(context); // boolean on = intraVpnService != null && intraVpnService.isOn(); // return new VpnState(requested, on, connectionState); // } // // } // Path: Android/app/src/main/java/app/intra/net/go/GoProber.java import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import app.intra.net.doh.Prober; import app.intra.sys.VpnController; import doh.Transport; import protect.Protector; import tun2socks.Tun2socks; /* Copyright 2019 Jigsaw Operations LLC 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 https://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 app.intra.net.go; /** * Implements a Probe using the Go-based DoH client. */ public class GoProber extends Prober { private final Context context; public GoProber(Context context) { this.context = context; } @Override public void probe(String url, Callback callback) { new Thread(() -> { String dohIPs = GoVpnAdapter.getIpString(context, url); try { // Protection isn't needed for Lollipop+, or if the VPN is not active. Protector protector = VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP ? null :
VpnController.getInstance().getIntraVpnService();
Jigsaw-Code/Intra
Android/app/src/main/java/app/intra/net/doh/Race.java
// Path: Android/app/src/main/java/app/intra/net/go/GoProber.java // public class GoProber extends Prober { // // private final Context context; // // public GoProber(Context context) { // this.context = context; // } // // @Override // public void probe(String url, Callback callback) { // new Thread(() -> { // String dohIPs = GoVpnAdapter.getIpString(context, url); // try { // // Protection isn't needed for Lollipop+, or if the VPN is not active. // Protector protector = VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP ? null : // VpnController.getInstance().getIntraVpnService(); // Transport transport = Tun2socks.newDoHTransport(url, dohIPs, protector, null, null); // if (transport == null) { // callback.onCompleted(false); // return; // } // byte[] response = transport.query(QUERY_DATA); // if (response != null && response.length > 0) { // callback.onCompleted(true); // return; // } // callback.onCompleted(false); // } catch (Exception e) { // callback.onCompleted(false); // } // }).start(); // } // }
import android.content.Context; import app.intra.net.go.GoProber;
/* Copyright 2019 Jigsaw Operations LLC 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 https://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 app.intra.net.doh; /** * This class performs parallel probes to all of the specified servers and calls the listener when * the fastest probe succeeds or all probes have failed. Each instance can only be used once. */ public class Race { public interface Listener { /** * This method is called once, when the race has concluded. * @param index The index in urls of the fastest server, or -1 if all probes failed. */ void onResult(int index); } /** * Starts a race between different servers. * @param context Used to read the IP addresses of the servers from storage. * @param urls The URLs for all the DOH servers to compare. * @param listener Called once on an arbitrary thread with the result of the race. */ public static void start(Context context, String[] urls, Listener listener) {
// Path: Android/app/src/main/java/app/intra/net/go/GoProber.java // public class GoProber extends Prober { // // private final Context context; // // public GoProber(Context context) { // this.context = context; // } // // @Override // public void probe(String url, Callback callback) { // new Thread(() -> { // String dohIPs = GoVpnAdapter.getIpString(context, url); // try { // // Protection isn't needed for Lollipop+, or if the VPN is not active. // Protector protector = VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP ? null : // VpnController.getInstance().getIntraVpnService(); // Transport transport = Tun2socks.newDoHTransport(url, dohIPs, protector, null, null); // if (transport == null) { // callback.onCompleted(false); // return; // } // byte[] response = transport.query(QUERY_DATA); // if (response != null && response.length > 0) { // callback.onCompleted(true); // return; // } // callback.onCompleted(false); // } catch (Exception e) { // callback.onCompleted(false); // } // }).start(); // } // } // Path: Android/app/src/main/java/app/intra/net/doh/Race.java import android.content.Context; import app.intra.net.go.GoProber; /* Copyright 2019 Jigsaw Operations LLC 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 https://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 app.intra.net.doh; /** * This class performs parallel probes to all of the specified servers and calls the listener when * the fastest probe succeeds or all probes have failed. Each instance can only be used once. */ public class Race { public interface Listener { /** * This method is called once, when the race has concluded. * @param index The index in urls of the fastest server, or -1 if all probes failed. */ void onResult(int index); } /** * Starts a race between different servers. * @param context Used to read the IP addresses of the servers from storage. * @param urls The URLs for all the DOH servers to compare. * @param listener Called once on an arbitrary thread with the result of the race. */ public static void start(Context context, String[] urls, Listener listener) {
Prober prober = new GoProber(context);
Jigsaw-Code/Intra
Android/app/src/test/java/app/intra/ui/settings/UntemplateTest.java
// Path: Android/app/src/main/java/app/intra/ui/settings/Untemplate.java // public class Untemplate { // /** // * Performs variable expansion on a URI Template (RFC 6570) in the special case where all // * variables are undefined. This is the only case of URI templates that is needed for DOH in POST // * mode. // * @param template A URI template (or just a URI) // * @return A URI produced by this template when all variables are undefined // */ // public static String strip(String template) { // return template.replaceAll("\\{[^}]*\\}", ""); // } // }
import app.intra.ui.settings.Untemplate; import org.junit.Test; import static org.junit.Assert.*;
/* Copyright 2018 Jigsaw Operations LLC 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 https://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 app.intra.ui.settings; public class UntemplateTest { private void assertUnmodified(String input) {
// Path: Android/app/src/main/java/app/intra/ui/settings/Untemplate.java // public class Untemplate { // /** // * Performs variable expansion on a URI Template (RFC 6570) in the special case where all // * variables are undefined. This is the only case of URI templates that is needed for DOH in POST // * mode. // * @param template A URI template (or just a URI) // * @return A URI produced by this template when all variables are undefined // */ // public static String strip(String template) { // return template.replaceAll("\\{[^}]*\\}", ""); // } // } // Path: Android/app/src/test/java/app/intra/ui/settings/UntemplateTest.java import app.intra.ui.settings.Untemplate; import org.junit.Test; import static org.junit.Assert.*; /* Copyright 2018 Jigsaw Operations LLC 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 https://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 app.intra.ui.settings; public class UntemplateTest { private void assertUnmodified(String input) {
assertEquals(input, Untemplate.strip(input));
Jigsaw-Code/Intra
Android/app/src/main/java/app/intra/sys/QueryTracker.java
// Path: Android/app/src/main/java/app/intra/net/doh/Transaction.java // public class Transaction implements Serializable { // // public enum Status { // COMPLETE, // SEND_FAIL, // HTTP_ERROR, // BAD_RESPONSE, // INTERNAL_ERROR, // CANCELED // } // // public Transaction(DnsPacket query, long timestamp) { // this.name = query.getQueryName(); // this.type = query.getQueryType(); // this.queryTime = timestamp; // } // // public final long queryTime; // public final String name; // public final short type; // public long responseTime; // public Status status; // public byte[] response; // public Calendar responseCalendar; // public String serverIp; // }
import static android.content.Context.MODE_PRIVATE; import android.content.Context; import android.content.SharedPreferences; import app.intra.net.doh.Transaction; import java.util.Collections; import java.util.LinkedList; import java.util.Queue;
/* Copyright 2018 Jigsaw Operations LLC 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 https://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 app.intra.sys; /** * A class for tracking DNS transactions. This class counts the number of successful transactions, * records the last minute of query timestamps, and optionally maintains a history of recent * transactions. * Thread-safe. */ public class QueryTracker { private static final String NUM_REQUESTS = "numRequests"; private static final int HISTORY_SIZE = 100; private static final int ACTIVITY_MEMORY_MS = 60 * 1000; // One minute private long numRequests = 0;
// Path: Android/app/src/main/java/app/intra/net/doh/Transaction.java // public class Transaction implements Serializable { // // public enum Status { // COMPLETE, // SEND_FAIL, // HTTP_ERROR, // BAD_RESPONSE, // INTERNAL_ERROR, // CANCELED // } // // public Transaction(DnsPacket query, long timestamp) { // this.name = query.getQueryName(); // this.type = query.getQueryType(); // this.queryTime = timestamp; // } // // public final long queryTime; // public final String name; // public final short type; // public long responseTime; // public Status status; // public byte[] response; // public Calendar responseCalendar; // public String serverIp; // } // Path: Android/app/src/main/java/app/intra/sys/QueryTracker.java import static android.content.Context.MODE_PRIVATE; import android.content.Context; import android.content.SharedPreferences; import app.intra.net.doh.Transaction; import java.util.Collections; import java.util.LinkedList; import java.util.Queue; /* Copyright 2018 Jigsaw Operations LLC 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 https://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 app.intra.sys; /** * A class for tracking DNS transactions. This class counts the number of successful transactions, * records the last minute of query timestamps, and optionally maintains a history of recent * transactions. * Thread-safe. */ public class QueryTracker { private static final String NUM_REQUESTS = "numRequests"; private static final int HISTORY_SIZE = 100; private static final int ACTIVITY_MEMORY_MS = 60 * 1000; // One minute private long numRequests = 0;
private Queue<Transaction> recentTransactions = new LinkedList<>();
Jigsaw-Code/Intra
Android/app/src/main/java/app/intra/sys/CountryCode.java
// Path: Android/app/src/main/java/app/intra/sys/firebase/LogWrapper.java // public class LogWrapper { // public static void logException(Throwable t) { // Log.e("LogWrapper", "Error", t); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().recordException(t); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // // public static void log(int severity, String tag, String message) { // Log.println(severity, tag, message); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().log(tag + ": " + message); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // }
import android.annotation.SuppressLint; import android.content.Context; import android.telephony.TelephonyManager; import androidx.annotation.NonNull; import app.intra.sys.firebase.LogWrapper; import java.lang.reflect.Method;
return deviceCountry; } public @NonNull String getNetworkCountry() { return networkCountry; } private static @NonNull String countryFromSim(TelephonyManager telephonyManager) { String simCountry = telephonyManager.getSimCountryIso(); if (!simCountry.isEmpty()) { return simCountry; } // User appears to be non-GSM. Try CDMA. try { // Get the system properties by reflection. @SuppressLint("PrivateApi") Class<?> systemPropertiesClass = Class.forName("android.os.SystemProperties"); Method get = systemPropertiesClass.getMethod("get", String.class); String cdmaOperator = (String)get.invoke(systemPropertiesClass, "ro.cdma.home.operator.numeric"); if (cdmaOperator == null || cdmaOperator.isEmpty()) { // System is neither GSM nor CDMA. return ""; } String mcc = cdmaOperator.substring(0, 3); @SuppressLint("PrivateApi") Class<?> mccTableClass = Class.forName("com.android.internal.telephony.MccTable"); Method countryCodeForMcc = mccTableClass.getMethod("countryCodeForMcc", String.class); return (String)countryCodeForMcc.invoke(mccTableClass, mcc); } catch (Exception e) {
// Path: Android/app/src/main/java/app/intra/sys/firebase/LogWrapper.java // public class LogWrapper { // public static void logException(Throwable t) { // Log.e("LogWrapper", "Error", t); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().recordException(t); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // // public static void log(int severity, String tag, String message) { // Log.println(severity, tag, message); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().log(tag + ": " + message); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // } // Path: Android/app/src/main/java/app/intra/sys/CountryCode.java import android.annotation.SuppressLint; import android.content.Context; import android.telephony.TelephonyManager; import androidx.annotation.NonNull; import app.intra.sys.firebase.LogWrapper; import java.lang.reflect.Method; return deviceCountry; } public @NonNull String getNetworkCountry() { return networkCountry; } private static @NonNull String countryFromSim(TelephonyManager telephonyManager) { String simCountry = telephonyManager.getSimCountryIso(); if (!simCountry.isEmpty()) { return simCountry; } // User appears to be non-GSM. Try CDMA. try { // Get the system properties by reflection. @SuppressLint("PrivateApi") Class<?> systemPropertiesClass = Class.forName("android.os.SystemProperties"); Method get = systemPropertiesClass.getMethod("get", String.class); String cdmaOperator = (String)get.invoke(systemPropertiesClass, "ro.cdma.home.operator.numeric"); if (cdmaOperator == null || cdmaOperator.isEmpty()) { // System is neither GSM nor CDMA. return ""; } String mcc = cdmaOperator.substring(0, 3); @SuppressLint("PrivateApi") Class<?> mccTableClass = Class.forName("com.android.internal.telephony.MccTable"); Method countryCodeForMcc = mccTableClass.getMethod("countryCodeForMcc", String.class); return (String)countryCodeForMcc.invoke(mccTableClass, mcc); } catch (Exception e) {
LogWrapper.logException(e);
Jigsaw-Code/Intra
Android/app/src/main/java/app/intra/sys/PersistentState.java
// Path: Android/app/src/main/java/app/intra/sys/firebase/LogWrapper.java // public class LogWrapper { // public static void logException(Throwable t) { // Log.e("LogWrapper", "Error", t); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().recordException(t); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // // public static void log(int severity, String tag, String message) { // Log.println(severity, tag, message); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().log(tag + ": " + message); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // } // // Path: Android/app/src/main/java/app/intra/ui/settings/Untemplate.java // public class Untemplate { // /** // * Performs variable expansion on a URI Template (RFC 6570) in the special case where all // * variables are undefined. This is the only case of URI templates that is needed for DOH in POST // * mode. // * @param template A URI template (or just a URI) // * @return A URI produced by this template when all variables are undefined // */ // public static String strip(String template) { // return template.replaceAll("\\{[^}]*\\}", ""); // } // }
import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import app.intra.R; import app.intra.sys.firebase.LogWrapper; import app.intra.ui.settings.Untemplate; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.Set;
// There is no URL setting, so read the legacy server name. SharedPreferences settings = getInternalState(context); String domain = settings.getString(SERVER_KEY, null); if (domain == null) { // Legacy setting is in the default state, so we can leave the new URL setting in the default // state as well. return; } String[] urls = context.getResources().getStringArray(R.array.urls); String defaultDomain = context.getResources().getString(R.string.legacy_domain0); String url = null; if (domain.equals(defaultDomain)) { // Common case: the domain is dns.google.com, which now corresponds to dns.google (url 0). url = urls[0]; } else { // In practice, we expect that domain will always be cloudflare-dns.com at this point, because // that was the only other option in the relevant legacy versions of Intra. // Look for the corresponding URL among the builtin servers. for (String u : urls) { Uri parsed = Uri.parse(u); if (domain.equals(parsed.getHost())) { url = u; break; } } } if (url == null) {
// Path: Android/app/src/main/java/app/intra/sys/firebase/LogWrapper.java // public class LogWrapper { // public static void logException(Throwable t) { // Log.e("LogWrapper", "Error", t); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().recordException(t); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // // public static void log(int severity, String tag, String message) { // Log.println(severity, tag, message); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().log(tag + ": " + message); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // } // // Path: Android/app/src/main/java/app/intra/ui/settings/Untemplate.java // public class Untemplate { // /** // * Performs variable expansion on a URI Template (RFC 6570) in the special case where all // * variables are undefined. This is the only case of URI templates that is needed for DOH in POST // * mode. // * @param template A URI template (or just a URI) // * @return A URI produced by this template when all variables are undefined // */ // public static String strip(String template) { // return template.replaceAll("\\{[^}]*\\}", ""); // } // } // Path: Android/app/src/main/java/app/intra/sys/PersistentState.java import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import app.intra.R; import app.intra.sys.firebase.LogWrapper; import app.intra.ui.settings.Untemplate; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.Set; // There is no URL setting, so read the legacy server name. SharedPreferences settings = getInternalState(context); String domain = settings.getString(SERVER_KEY, null); if (domain == null) { // Legacy setting is in the default state, so we can leave the new URL setting in the default // state as well. return; } String[] urls = context.getResources().getStringArray(R.array.urls); String defaultDomain = context.getResources().getString(R.string.legacy_domain0); String url = null; if (domain.equals(defaultDomain)) { // Common case: the domain is dns.google.com, which now corresponds to dns.google (url 0). url = urls[0]; } else { // In practice, we expect that domain will always be cloudflare-dns.com at this point, because // that was the only other option in the relevant legacy versions of Intra. // Look for the corresponding URL among the builtin servers. for (String u : urls) { Uri parsed = Uri.parse(u); if (domain.equals(parsed.getHost())) { url = u; break; } } } if (url == null) {
LogWrapper.log(Log.WARN, LOG_TAG, "Legacy domain is unrecognized");
Jigsaw-Code/Intra
Android/app/src/main/java/app/intra/sys/PersistentState.java
// Path: Android/app/src/main/java/app/intra/sys/firebase/LogWrapper.java // public class LogWrapper { // public static void logException(Throwable t) { // Log.e("LogWrapper", "Error", t); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().recordException(t); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // // public static void log(int severity, String tag, String message) { // Log.println(severity, tag, message); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().log(tag + ": " + message); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // } // // Path: Android/app/src/main/java/app/intra/ui/settings/Untemplate.java // public class Untemplate { // /** // * Performs variable expansion on a URI Template (RFC 6570) in the special case where all // * variables are undefined. This is the only case of URI templates that is needed for DOH in POST // * mode. // * @param template A URI template (or just a URI) // * @return A URI produced by this template when all variables are undefined // */ // public static String strip(String template) { // return template.replaceAll("\\{[^}]*\\}", ""); // } // }
import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import app.intra.R; import app.intra.sys.firebase.LogWrapper; import app.intra.ui.settings.Untemplate; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.Set;
// In practice, we expect that domain will always be cloudflare-dns.com at this point, because // that was the only other option in the relevant legacy versions of Intra. // Look for the corresponding URL among the builtin servers. for (String u : urls) { Uri parsed = Uri.parse(u); if (domain.equals(parsed.getHost())) { url = u; break; } } } if (url == null) { LogWrapper.log(Log.WARN, LOG_TAG, "Legacy domain is unrecognized"); return; } setServerUrl(context, url); } public static void setServerUrl(Context context, String url) { SharedPreferences.Editor editor = getUserPreferences(context).edit(); editor.putString(URL_KEY, url); editor.apply(); } public static String getServerUrl(Context context) { String urlTemplate = getUserPreferences(context).getString(URL_KEY, null); if (urlTemplate == null) { return null; }
// Path: Android/app/src/main/java/app/intra/sys/firebase/LogWrapper.java // public class LogWrapper { // public static void logException(Throwable t) { // Log.e("LogWrapper", "Error", t); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().recordException(t); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // // public static void log(int severity, String tag, String message) { // Log.println(severity, tag, message); // if (BuildConfig.DEBUG) { // return; // } // try { // FirebaseCrashlytics.getInstance().log(tag + ": " + message); // } catch (IllegalStateException e) { // // This only occurs during unit tests. // } // } // } // // Path: Android/app/src/main/java/app/intra/ui/settings/Untemplate.java // public class Untemplate { // /** // * Performs variable expansion on a URI Template (RFC 6570) in the special case where all // * variables are undefined. This is the only case of URI templates that is needed for DOH in POST // * mode. // * @param template A URI template (or just a URI) // * @return A URI produced by this template when all variables are undefined // */ // public static String strip(String template) { // return template.replaceAll("\\{[^}]*\\}", ""); // } // } // Path: Android/app/src/main/java/app/intra/sys/PersistentState.java import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import app.intra.R; import app.intra.sys.firebase.LogWrapper; import app.intra.ui.settings.Untemplate; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.Set; // In practice, we expect that domain will always be cloudflare-dns.com at this point, because // that was the only other option in the relevant legacy versions of Intra. // Look for the corresponding URL among the builtin servers. for (String u : urls) { Uri parsed = Uri.parse(u); if (domain.equals(parsed.getHost())) { url = u; break; } } } if (url == null) { LogWrapper.log(Log.WARN, LOG_TAG, "Legacy domain is unrecognized"); return; } setServerUrl(context, url); } public static void setServerUrl(Context context, String url) { SharedPreferences.Editor editor = getUserPreferences(context).edit(); editor.putString(URL_KEY, url); editor.apply(); } public static String getServerUrl(Context context) { String urlTemplate = getUserPreferences(context).getString(URL_KEY, null); if (urlTemplate == null) { return null; }
return Untemplate.strip(urlTemplate);
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/service/MycatMysqlsService.java
// Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // }
import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.MySqlServer; import org.mycat.web.util.Constant; import org.springframework.stereotype.Service;
package org.mycat.web.service; @Service("mycatMysqlsService") public class MycatMysqlsService extends AbstractConfigSevice{ private Class<MySqlServer> clazz = MySqlServer.class;
// Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // } // Path: src/main/java/org/mycat/web/service/MycatMysqlsService.java import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.MySqlServer; import org.mycat.web.util.Constant; import org.springframework.stereotype.Service; package org.mycat.web.service; @Service("mycatMysqlsService") public class MycatMysqlsService extends AbstractConfigSevice{ private Class<MySqlServer> clazz = MySqlServer.class;
private String menuPath = Constant.MYCAT_MYSQLS_KEY;
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/task/common/TaskManger.java
// Path: src/main/java/org/mycat/web/task/server/CheckMycatSuspend.java // @Service // public class CheckMycatSuspend extends BaseService implements ITask { // private String dbName; // // private static final String NAMESPACE = "MYCATSHOWPROCESSOR"; // // private static final int timeout = 10; //ๅฎ•ๆœบtimeout๏ผš10S // // @Override // public void excute(String dbName, Date nowDate) { // // DataSource dbSource = (DataSource)SpringApplicationContext.getBean(dbName + MycatPortType.MYCAT_MANGER + "dataSource"); // Connection conn = null; // try { // conn = dbSource.getConnection(); // if(!conn.isValid(timeout)){ // MailUtil.send("Mycatๆญปๆœบ", dbName+"ๆญปๆœบ"); // return; // } // } catch (Exception e) { // e.printStackTrace(); // try { // MailUtil.send("Mycatๆญปๆœบ", dbName+"ๆญปๆœบ"); // } catch (MessagingException e1) { // e1.printStackTrace(); // } // return; // }finally{ // if(conn != null){ // try { // conn.close(); // } catch (SQLException e) { // e.printStackTrace(); // } // } // } // // this.dbName = dbName; // // ShowService showService = (ShowService)SpringApplicationContext.getBean("showService"); // showService.getDao().query(dbName + MycatPortType.MYCAT_MANGER, NAMESPACE, "testMycat"); // } // // public String getDbName(){ // return this.dbName; // } // // }
import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.mycat.web.task.server.CheckMycatSuspend; import org.slf4j.LoggerFactory; import org.slf4j.Logger;
} } public void addDBName(String dbName){ if(dbName != null){ if(!dbNames.contains(dbName)){ dbNames.add(dbName); } } } public void addTask(final ITask task,final long period, String taskName,final int timeout){ //้—ด้š”ไธ€ๅฎšๆ—ถ้—ด๏ผŒ่งฆๅ‘ไธ€ๆฌก็›‘ๆต‹ไบ‹ไปถ ScheduledFuture<?> sf = scheduler.scheduleAtFixedRate(new Runnable() { public void run() { //ไธ€ๆฌก็›‘ๆต‹ไบ‹ไปถ๏ผŒๆ นๆฎDBๆ•ฐ้‡๏ผŒไธ€ไธชDB๏ผŒๅผ€ไธ€ไธช็บฟ็จ‹็›‘ๆต‹ final Date nowDate = new Date(); for(final String dbName : dbNames){ try{ ScheduledFuture<?> sf = scheduler.schedule(new Runnable() { public void run() { task.excute(dbName, nowDate); } }, 0, TimeUnit.MILLISECONDS); try { if (timeout != -1) sf.get(timeout, TimeUnit.SECONDS); } catch (TimeoutException e) { //ไธป็บฟ็จ‹็ญ‰ๅพ…่ฎก็ฎ—็ป“ๆžœ่ถ…ๆ—ถ๏ผŒๅ› ๆญคไธญๆ–ญไปปๅŠก็บฟ็จ‹๏ผ e.printStackTrace();
// Path: src/main/java/org/mycat/web/task/server/CheckMycatSuspend.java // @Service // public class CheckMycatSuspend extends BaseService implements ITask { // private String dbName; // // private static final String NAMESPACE = "MYCATSHOWPROCESSOR"; // // private static final int timeout = 10; //ๅฎ•ๆœบtimeout๏ผš10S // // @Override // public void excute(String dbName, Date nowDate) { // // DataSource dbSource = (DataSource)SpringApplicationContext.getBean(dbName + MycatPortType.MYCAT_MANGER + "dataSource"); // Connection conn = null; // try { // conn = dbSource.getConnection(); // if(!conn.isValid(timeout)){ // MailUtil.send("Mycatๆญปๆœบ", dbName+"ๆญปๆœบ"); // return; // } // } catch (Exception e) { // e.printStackTrace(); // try { // MailUtil.send("Mycatๆญปๆœบ", dbName+"ๆญปๆœบ"); // } catch (MessagingException e1) { // e1.printStackTrace(); // } // return; // }finally{ // if(conn != null){ // try { // conn.close(); // } catch (SQLException e) { // e.printStackTrace(); // } // } // } // // this.dbName = dbName; // // ShowService showService = (ShowService)SpringApplicationContext.getBean("showService"); // showService.getDao().query(dbName + MycatPortType.MYCAT_MANGER, NAMESPACE, "testMycat"); // } // // public String getDbName(){ // return this.dbName; // } // // } // Path: src/main/java/org/mycat/web/task/common/TaskManger.java import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.mycat.web.task.server.CheckMycatSuspend; import org.slf4j.LoggerFactory; import org.slf4j.Logger; } } public void addDBName(String dbName){ if(dbName != null){ if(!dbNames.contains(dbName)){ dbNames.add(dbName); } } } public void addTask(final ITask task,final long period, String taskName,final int timeout){ //้—ด้š”ไธ€ๅฎšๆ—ถ้—ด๏ผŒ่งฆๅ‘ไธ€ๆฌก็›‘ๆต‹ไบ‹ไปถ ScheduledFuture<?> sf = scheduler.scheduleAtFixedRate(new Runnable() { public void run() { //ไธ€ๆฌก็›‘ๆต‹ไบ‹ไปถ๏ผŒๆ นๆฎDBๆ•ฐ้‡๏ผŒไธ€ไธชDB๏ผŒๅผ€ไธ€ไธช็บฟ็จ‹็›‘ๆต‹ final Date nowDate = new Date(); for(final String dbName : dbNames){ try{ ScheduledFuture<?> sf = scheduler.schedule(new Runnable() { public void run() { task.excute(dbName, nowDate); } }, 0, TimeUnit.MILLISECONDS); try { if (timeout != -1) sf.get(timeout, TimeUnit.SECONDS); } catch (TimeoutException e) { //ไธป็บฟ็จ‹็ญ‰ๅพ…่ฎก็ฎ—็ป“ๆžœ่ถ…ๆ—ถ๏ผŒๅ› ๆญคไธญๆ–ญไปปๅŠก็บฟ็จ‹๏ผ e.printStackTrace();
if (task instanceof CheckMycatSuspend){
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/task/server/ShowMycatProcessor.java
// Path: src/main/java/org/mycat/web/task/common/ITask.java // public interface ITask{ // public static final String STATEMENT = "queryMycat"; // public static final long UPDATE_PERIOD = 5000*60; // // public void excute(String dbName, Date nowDate); // } // // Path: src/main/java/org/mycat/web/util/DataSourceUtils.java // public enum MycatPortType{ // MYCAT_MANGER, // MYCAT_SERVER // }
import java.util.Date; import java.util.List; import java.util.Map; import org.hx.rainbow.common.context.RainbowProperties; import org.hx.rainbow.common.core.service.BaseService; import org.mycat.web.task.common.ITask; import org.mycat.web.task.common.SqliteStore; import org.mycat.web.util.DataSourceUtils.MycatPortType; import org.springframework.stereotype.Service;
package org.mycat.web.task.server; @Service public class ShowMycatProcessor extends BaseService implements ITask { private static final String NAMESPACE = "MYCATSHOWPROCESSOR"; // public ShowMycatProcessor(){ // Long period = Long.parseLong((String)RainbowProperties.getProperties("show.period")); // if(period == null || period < 30000){ // period = UPDATE_PERIOD; // } // TaskManger.getInstance().addTask(this, period); // } @Override public void excute(String dbName, Date nowDate) {
// Path: src/main/java/org/mycat/web/task/common/ITask.java // public interface ITask{ // public static final String STATEMENT = "queryMycat"; // public static final long UPDATE_PERIOD = 5000*60; // // public void excute(String dbName, Date nowDate); // } // // Path: src/main/java/org/mycat/web/util/DataSourceUtils.java // public enum MycatPortType{ // MYCAT_MANGER, // MYCAT_SERVER // } // Path: src/main/java/org/mycat/web/task/server/ShowMycatProcessor.java import java.util.Date; import java.util.List; import java.util.Map; import org.hx.rainbow.common.context.RainbowProperties; import org.hx.rainbow.common.core.service.BaseService; import org.mycat.web.task.common.ITask; import org.mycat.web.task.common.SqliteStore; import org.mycat.web.util.DataSourceUtils.MycatPortType; import org.springframework.stereotype.Service; package org.mycat.web.task.server; @Service public class ShowMycatProcessor extends BaseService implements ITask { private static final String NAMESPACE = "MYCATSHOWPROCESSOR"; // public ShowMycatProcessor(){ // Long period = Long.parseLong((String)RainbowProperties.getProperties("show.period")); // if(period == null || period < 30000){ // period = UPDATE_PERIOD; // } // TaskManger.getInstance().addTask(this, period); // } @Override public void excute(String dbName, Date nowDate) {
List<Map<String, Object>> datas = super.getDao().query(dbName + MycatPortType.MYCAT_MANGER, NAMESPACE, STATEMENT);
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/service/MycatNodeService.java
// Path: src/main/java/org/mycat/web/model/MyCatNode.java // public class MyCatNode { // // private String name; // // private String zone; // // private String cluster; // // private String hostname; // // private int weigth; // // private int leader; // // private String state; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getZone() { // return zone; // } // // public void setZone(String zone) { // this.zone = zone; // } // // public String getCluster() { // return cluster; // } // // public void setCluster(String cluster) { // this.cluster = cluster; // } // // public String getHostname() { // return hostname; // } // // public void setHostname(String hostname) { // this.hostname = hostname; // } // // public int getWeigth() { // return weigth; // } // // public void setWeigth(int weigth) { // this.weigth = weigth; // } // // public int getLeader() { // return leader; // } // // public void setLeader(int leader) { // this.leader = leader; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // } // // Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // }
import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.MyCatNode; import org.mycat.web.util.Constant; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service;
package org.mycat.web.service; @Lazy @Service("mycatNodeService") public class MycatNodeService extends AbstractConfigSevice {
// Path: src/main/java/org/mycat/web/model/MyCatNode.java // public class MyCatNode { // // private String name; // // private String zone; // // private String cluster; // // private String hostname; // // private int weigth; // // private int leader; // // private String state; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getZone() { // return zone; // } // // public void setZone(String zone) { // this.zone = zone; // } // // public String getCluster() { // return cluster; // } // // public void setCluster(String cluster) { // this.cluster = cluster; // } // // public String getHostname() { // return hostname; // } // // public void setHostname(String hostname) { // this.hostname = hostname; // } // // public int getWeigth() { // return weigth; // } // // public void setWeigth(int weigth) { // this.weigth = weigth; // } // // public int getLeader() { // return leader; // } // // public void setLeader(int leader) { // this.leader = leader; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // } // // Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // } // Path: src/main/java/org/mycat/web/service/MycatNodeService.java import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.MyCatNode; import org.mycat.web.util.Constant; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; package org.mycat.web.service; @Lazy @Service("mycatNodeService") public class MycatNodeService extends AbstractConfigSevice {
private Class<MyCatNode> clazz = MyCatNode.class;
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/service/MycatNodeService.java
// Path: src/main/java/org/mycat/web/model/MyCatNode.java // public class MyCatNode { // // private String name; // // private String zone; // // private String cluster; // // private String hostname; // // private int weigth; // // private int leader; // // private String state; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getZone() { // return zone; // } // // public void setZone(String zone) { // this.zone = zone; // } // // public String getCluster() { // return cluster; // } // // public void setCluster(String cluster) { // this.cluster = cluster; // } // // public String getHostname() { // return hostname; // } // // public void setHostname(String hostname) { // this.hostname = hostname; // } // // public int getWeigth() { // return weigth; // } // // public void setWeigth(int weigth) { // this.weigth = weigth; // } // // public int getLeader() { // return leader; // } // // public void setLeader(int leader) { // this.leader = leader; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // } // // Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // }
import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.MyCatNode; import org.mycat.web.util.Constant; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service;
package org.mycat.web.service; @Lazy @Service("mycatNodeService") public class MycatNodeService extends AbstractConfigSevice { private Class<MyCatNode> clazz = MyCatNode.class;
// Path: src/main/java/org/mycat/web/model/MyCatNode.java // public class MyCatNode { // // private String name; // // private String zone; // // private String cluster; // // private String hostname; // // private int weigth; // // private int leader; // // private String state; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getZone() { // return zone; // } // // public void setZone(String zone) { // this.zone = zone; // } // // public String getCluster() { // return cluster; // } // // public void setCluster(String cluster) { // this.cluster = cluster; // } // // public String getHostname() { // return hostname; // } // // public void setHostname(String hostname) { // this.hostname = hostname; // } // // public int getWeigth() { // return weigth; // } // // public void setWeigth(int weigth) { // this.weigth = weigth; // } // // public int getLeader() { // return leader; // } // // public void setLeader(int leader) { // this.leader = leader; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // } // // Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // } // Path: src/main/java/org/mycat/web/service/MycatNodeService.java import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.MyCatNode; import org.mycat.web.util.Constant; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; package org.mycat.web.service; @Lazy @Service("mycatNodeService") public class MycatNodeService extends AbstractConfigSevice { private Class<MyCatNode> clazz = MyCatNode.class;
private String menuPath = Constant.MYCAT_NODES_KEY;
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/service/cluster/ChildrenTableService.java
// Path: src/main/java/org/mycat/web/model/cluster/ChildrenTable.java // public class ChildrenTable { // private String name; // private String primaryKey; // private String joinKey; // private String parentKey; // // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getPrimaryKey() { // return primaryKey; // } // public void setPrimaryKey(String primaryKey) { // this.primaryKey = primaryKey; // } // public String getJoinKey() { // return joinKey; // } // public void setJoinKey(String joinKey) { // this.joinKey = joinKey; // } // public String getParentKey() { // return parentKey; // } // public void setParentKey(String parentKey) { // this.parentKey = parentKey; // } // // // } // // Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // }
import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.cluster.ChildrenTable; import org.mycat.web.service.AbstractConfigSevice; import org.mycat.web.util.Constant; import org.springframework.stereotype.Service;
package org.mycat.web.service.cluster; @Service("childrenTableService") public class ChildrenTableService extends AbstractConfigSevice {
// Path: src/main/java/org/mycat/web/model/cluster/ChildrenTable.java // public class ChildrenTable { // private String name; // private String primaryKey; // private String joinKey; // private String parentKey; // // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getPrimaryKey() { // return primaryKey; // } // public void setPrimaryKey(String primaryKey) { // this.primaryKey = primaryKey; // } // public String getJoinKey() { // return joinKey; // } // public void setJoinKey(String joinKey) { // this.joinKey = joinKey; // } // public String getParentKey() { // return parentKey; // } // public void setParentKey(String parentKey) { // this.parentKey = parentKey; // } // // // } // // Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // } // Path: src/main/java/org/mycat/web/service/cluster/ChildrenTableService.java import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.cluster.ChildrenTable; import org.mycat.web.service.AbstractConfigSevice; import org.mycat.web.util.Constant; import org.springframework.stereotype.Service; package org.mycat.web.service.cluster; @Service("childrenTableService") public class ChildrenTableService extends AbstractConfigSevice {
private Class<ChildrenTable> clazz = ChildrenTable.class;
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/service/cluster/ChildrenTableService.java
// Path: src/main/java/org/mycat/web/model/cluster/ChildrenTable.java // public class ChildrenTable { // private String name; // private String primaryKey; // private String joinKey; // private String parentKey; // // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getPrimaryKey() { // return primaryKey; // } // public void setPrimaryKey(String primaryKey) { // this.primaryKey = primaryKey; // } // public String getJoinKey() { // return joinKey; // } // public void setJoinKey(String joinKey) { // this.joinKey = joinKey; // } // public String getParentKey() { // return parentKey; // } // public void setParentKey(String parentKey) { // this.parentKey = parentKey; // } // // // } // // Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // }
import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.cluster.ChildrenTable; import org.mycat.web.service.AbstractConfigSevice; import org.mycat.web.util.Constant; import org.springframework.stereotype.Service;
package org.mycat.web.service.cluster; @Service("childrenTableService") public class ChildrenTableService extends AbstractConfigSevice { private Class<ChildrenTable> clazz = ChildrenTable.class;
// Path: src/main/java/org/mycat/web/model/cluster/ChildrenTable.java // public class ChildrenTable { // private String name; // private String primaryKey; // private String joinKey; // private String parentKey; // // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getPrimaryKey() { // return primaryKey; // } // public void setPrimaryKey(String primaryKey) { // this.primaryKey = primaryKey; // } // public String getJoinKey() { // return joinKey; // } // public void setJoinKey(String joinKey) { // this.joinKey = joinKey; // } // public String getParentKey() { // return parentKey; // } // public void setParentKey(String parentKey) { // this.parentKey = parentKey; // } // // // } // // Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // } // Path: src/main/java/org/mycat/web/service/cluster/ChildrenTableService.java import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.cluster.ChildrenTable; import org.mycat.web.service.AbstractConfigSevice; import org.mycat.web.util.Constant; import org.springframework.stereotype.Service; package org.mycat.web.service.cluster; @Service("childrenTableService") public class ChildrenTableService extends AbstractConfigSevice { private Class<ChildrenTable> clazz = ChildrenTable.class;
private String menuPath = Constant.MYCAT_CLUSTER_KEY;
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/service/cluster/DataNodeService.java
// Path: src/main/java/org/mycat/web/model/cluster/DataNode.java // public class DataNode { // // private String name; // private String dataHost; // private String database; // // // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getDataHost() { // return dataHost; // } // public void setDataHost(String dataHost) { // this.dataHost = dataHost; // } // public String getDatabase() { // return database; // } // public void setDatabase(String database) { // this.database = database; // } // // // } // // Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // }
import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.cluster.DataNode; import org.mycat.web.service.AbstractConfigSevice; import org.mycat.web.util.Constant; import org.springframework.stereotype.Service;
package org.mycat.web.service.cluster; @Service("dataNodeService") public class DataNodeService extends AbstractConfigSevice {
// Path: src/main/java/org/mycat/web/model/cluster/DataNode.java // public class DataNode { // // private String name; // private String dataHost; // private String database; // // // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getDataHost() { // return dataHost; // } // public void setDataHost(String dataHost) { // this.dataHost = dataHost; // } // public String getDatabase() { // return database; // } // public void setDatabase(String database) { // this.database = database; // } // // // } // // Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // } // Path: src/main/java/org/mycat/web/service/cluster/DataNodeService.java import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.cluster.DataNode; import org.mycat.web.service.AbstractConfigSevice; import org.mycat.web.util.Constant; import org.springframework.stereotype.Service; package org.mycat.web.service.cluster; @Service("dataNodeService") public class DataNodeService extends AbstractConfigSevice {
private Class<DataNode> clazz = DataNode.class;
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/service/cluster/DataNodeService.java
// Path: src/main/java/org/mycat/web/model/cluster/DataNode.java // public class DataNode { // // private String name; // private String dataHost; // private String database; // // // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getDataHost() { // return dataHost; // } // public void setDataHost(String dataHost) { // this.dataHost = dataHost; // } // public String getDatabase() { // return database; // } // public void setDatabase(String database) { // this.database = database; // } // // // } // // Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // }
import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.cluster.DataNode; import org.mycat.web.service.AbstractConfigSevice; import org.mycat.web.util.Constant; import org.springframework.stereotype.Service;
package org.mycat.web.service.cluster; @Service("dataNodeService") public class DataNodeService extends AbstractConfigSevice { private Class<DataNode> clazz = DataNode.class;
// Path: src/main/java/org/mycat/web/model/cluster/DataNode.java // public class DataNode { // // private String name; // private String dataHost; // private String database; // // // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getDataHost() { // return dataHost; // } // public void setDataHost(String dataHost) { // this.dataHost = dataHost; // } // public String getDatabase() { // return database; // } // public void setDatabase(String database) { // this.database = database; // } // // // } // // Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // } // Path: src/main/java/org/mycat/web/service/cluster/DataNodeService.java import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.cluster.DataNode; import org.mycat.web.service.AbstractConfigSevice; import org.mycat.web.util.Constant; import org.springframework.stereotype.Service; package org.mycat.web.service.cluster; @Service("dataNodeService") public class DataNodeService extends AbstractConfigSevice { private Class<DataNode> clazz = DataNode.class;
private String menuPath = Constant.MYCAT_CLUSTER_KEY;
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/action/JMServer.java
// Path: src/main/java/org/mycat/web/jmonitor/JMConnBean.java // public class JMConnBean { // // private JMXConnector connector; // private String name; // private String host; // private String user; // private String pwd; // private int port; // // public JMXConnector getConnector() { // return connector; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public void setConnector(JMXConnector connector) { // this.connector = connector; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public String getUser() { // return user; // } // // public void setUser(String user) { // this.user = user; // } // // public String getPwd() { // return pwd; // } // // public void setPwd(String pwd) { // this.pwd = pwd; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // }
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.lang.Thread.State; import java.lang.management.ClassLoadingMXBean; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryUsage; import java.lang.management.RuntimeMXBean; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.text.DateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.mycat.web.jmonitor.JMConnBean; import org.mycat.web.service.JMConnManager; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.sun.management.OperatingSystemMXBean;
data.put("classLoadedNow", cBean.getLoadedClassCount()); data.put("classUnloadedAll", cBean.getUnloadedClassCount()); data.put("classLoadedAll", cBean.getTotalLoadedClassCount()); data.putAll(props); JSONObject json = new JSONObject(true); json.putAll(data); return json; } catch (IOException e) { throw new RuntimeException(e); } } @RequestMapping("/doGC") @ResponseBody public String doVMGC(HttpServletRequest request) { try { String app = request.getParameter("app"); JMConnManager.getMemoryMBean(app).gc(); return "success"; } catch (IOException e) { throw new RuntimeException(e); } } @RequestMapping("/doHeapDump") @ResponseBody public JSONObject doHeapDump(HttpServletRequest request) { try { String app = request.getParameter("app");
// Path: src/main/java/org/mycat/web/jmonitor/JMConnBean.java // public class JMConnBean { // // private JMXConnector connector; // private String name; // private String host; // private String user; // private String pwd; // private int port; // // public JMXConnector getConnector() { // return connector; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public void setConnector(JMXConnector connector) { // this.connector = connector; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public String getUser() { // return user; // } // // public void setUser(String user) { // this.user = user; // } // // public String getPwd() { // return pwd; // } // // public void setPwd(String pwd) { // this.pwd = pwd; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // } // Path: src/main/java/org/mycat/web/action/JMServer.java import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.lang.Thread.State; import java.lang.management.ClassLoadingMXBean; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryUsage; import java.lang.management.RuntimeMXBean; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.text.DateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.mycat.web.jmonitor.JMConnBean; import org.mycat.web.service.JMConnManager; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.sun.management.OperatingSystemMXBean; data.put("classLoadedNow", cBean.getLoadedClassCount()); data.put("classUnloadedAll", cBean.getUnloadedClassCount()); data.put("classLoadedAll", cBean.getTotalLoadedClassCount()); data.putAll(props); JSONObject json = new JSONObject(true); json.putAll(data); return json; } catch (IOException e) { throw new RuntimeException(e); } } @RequestMapping("/doGC") @ResponseBody public String doVMGC(HttpServletRequest request) { try { String app = request.getParameter("app"); JMConnManager.getMemoryMBean(app).gc(); return "success"; } catch (IOException e) { throw new RuntimeException(e); } } @RequestMapping("/doHeapDump") @ResponseBody public JSONObject doHeapDump(HttpServletRequest request) { try { String app = request.getParameter("app");
JMConnBean bean = JMConnManager.getApps().get(app);
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/service/MycatHostService.java
// Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // }
import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.MycatHost; import org.mycat.web.util.Constant; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service;
package org.mycat.web.service; @Lazy @Service("mycatHostService") public class MycatHostService extends AbstractConfigSevice { private Class<MycatHost> clazz = MycatHost.class;
// Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // } // Path: src/main/java/org/mycat/web/service/MycatHostService.java import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.MycatHost; import org.mycat.web.util.Constant; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; package org.mycat.web.service; @Lazy @Service("mycatHostService") public class MycatHostService extends AbstractConfigSevice { private Class<MycatHost> clazz = MycatHost.class;
private String menuPath = Constant.MYCAT_HOST_KEY;
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/service/JMXService.java
// Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // }
import java.io.File; import java.util.Map; import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.hx.rainbow.common.core.service.BaseService; import org.hx.rainbow.common.exception.AppException; import org.hx.rainbow.common.util.ObjectId; import org.mycat.web.util.Constant; import org.mycat.web.util.JrdsUtils; import org.mycat.web.util.ZookeeperCuratorHandler; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON;
package org.mycat.web.service; @Lazy @Service("jmxservice") public class JMXService extends BaseService { //private static final String NAMESPACE = "SYSJMX"; private ZookeeperCuratorHandler zkHander= ZookeeperCuratorHandler.getInstance(); public RainbowContext query(RainbowContext context) throws Exception { //super.query(context, NAMESPACE); //context.addRows(ZookeeperService.getInstance().getJmx());
// Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // } // Path: src/main/java/org/mycat/web/service/JMXService.java import java.io.File; import java.util.Map; import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.hx.rainbow.common.core.service.BaseService; import org.hx.rainbow.common.exception.AppException; import org.hx.rainbow.common.util.ObjectId; import org.mycat.web.util.Constant; import org.mycat.web.util.JrdsUtils; import org.mycat.web.util.ZookeeperCuratorHandler; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; package org.mycat.web.service; @Lazy @Service("jmxservice") public class JMXService extends BaseService { //private static final String NAMESPACE = "SYSJMX"; private ZookeeperCuratorHandler zkHander= ZookeeperCuratorHandler.getInstance(); public RainbowContext query(RainbowContext context) throws Exception { //super.query(context, NAMESPACE); //context.addRows(ZookeeperService.getInstance().getJmx());
context.addRows(zkHander.getChildNodeData(Constant.MYCAT_JMX));
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/service/MycatService.java
// Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // }
import java.io.File; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.hx.rainbow.common.core.service.BaseService; import org.hx.rainbow.common.exception.AppException; import org.hx.rainbow.common.util.ObjectId; import org.mycat.web.util.Constant; import org.mycat.web.util.JrdsUtils; import org.mycat.web.util.ZookeeperCuratorHandler; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON;
package org.mycat.web.service; @Lazy @Service("mycatService") public class MycatService extends BaseService { //private static final String NAMESPACE = "SYSMYCAT"; private ZookeeperCuratorHandler zkHander= ZookeeperCuratorHandler.getInstance(); public RainbowContext query(RainbowContext context) throws Exception{ //super.query(context, NAMESPACE); return queryByPage(context); } public RainbowContext queryByPage(RainbowContext context) throws Exception { //super.queryByPage(context, NAMESPACE); String mycatName=(String)context.getAttr("mycatName");
// Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // } // Path: src/main/java/org/mycat/web/service/MycatService.java import java.io.File; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.hx.rainbow.common.core.service.BaseService; import org.hx.rainbow.common.exception.AppException; import org.hx.rainbow.common.util.ObjectId; import org.mycat.web.util.Constant; import org.mycat.web.util.JrdsUtils; import org.mycat.web.util.ZookeeperCuratorHandler; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; package org.mycat.web.service; @Lazy @Service("mycatService") public class MycatService extends BaseService { //private static final String NAMESPACE = "SYSMYCAT"; private ZookeeperCuratorHandler zkHander= ZookeeperCuratorHandler.getInstance(); public RainbowContext query(RainbowContext context) throws Exception{ //super.query(context, NAMESPACE); return queryByPage(context); } public RainbowContext queryByPage(RainbowContext context) throws Exception { //super.queryByPage(context, NAMESPACE); String mycatName=(String)context.getAttr("mycatName");
List<Map<String, Object>> mycatlist = zkHander.getChildNodeData(Constant.MYCATS);
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/service/cluster/DataHostService.java
// Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // }
import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.cluster.DataHost; import org.mycat.web.service.AbstractConfigSevice; import org.mycat.web.util.Constant; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service;
package org.mycat.web.service.cluster; @Lazy @Service("dataHostService") public class DataHostService extends AbstractConfigSevice { private Class<DataHost> clazz = DataHost.class;
// Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // } // Path: src/main/java/org/mycat/web/service/cluster/DataHostService.java import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.cluster.DataHost; import org.mycat.web.service.AbstractConfigSevice; import org.mycat.web.util.Constant; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; package org.mycat.web.service.cluster; @Lazy @Service("dataHostService") public class DataHostService extends AbstractConfigSevice { private Class<DataHost> clazz = DataHost.class;
private String menuPath = Constant.MYCAT_CLUSTER_KEY;
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/service/cluster/UserService.java
// Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // }
import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.cluster.User; import org.mycat.web.service.AbstractConfigSevice; import org.mycat.web.util.Constant; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service;
package org.mycat.web.service.cluster; @Lazy @Service("userService") public class UserService extends AbstractConfigSevice { private Class<User> clazz = User.class;
// Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // } // Path: src/main/java/org/mycat/web/service/cluster/UserService.java import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.cluster.User; import org.mycat.web.service.AbstractConfigSevice; import org.mycat.web.util.Constant; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; package org.mycat.web.service.cluster; @Lazy @Service("userService") public class UserService extends AbstractConfigSevice { private Class<User> clazz = User.class;
private String menuPath = Constant.MYCAT_CLUSTER_KEY;
MyCATApache/Mycat-Web
src/main/java/org/mycat/web/service/cluster/SequenceService.java
// Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // }
import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.cluster.Sequence; import org.mycat.web.service.AbstractConfigSevice; import org.mycat.web.util.Constant; import org.springframework.stereotype.Service;
package org.mycat.web.service.cluster; @Service("sequenceService") public class SequenceService extends AbstractConfigSevice{ private Class<Sequence> clazz = Sequence.class;
// Path: src/main/java/org/mycat/web/util/Constant.java // public final class Constant { // private Constant() { // // } // // /** * ็ปŸไธ€็š„็ผ–็  */ // public static final String CHARSET = "UTF-8"; // // public static final String LOCAL_ZK_URL_NAME = "mycat"; // public static final String MYCAT_CLUSTER_KEY = "mycat-cluster"; // public static final String MYCAT_ZONE_KEY = "mycat-zones"; // public static final String MYCAT_NODES_KEY = "mycat-nodes"; // public static final String MYCAT_HOST_KEY = "mycat-hosts"; // public static final String MYCAT_MYSQLS_KEY = "mycat-mysqls"; // public static final String MYCAT_MYSQL_GROUP_KEY = "mycat-mysqlgroup"; // // public static final String MYCAT_EYE="/mycat-eye"; // // public static final String CLUSTER_USER = "user"; // public static final String CLUSTER_DATANODE = "datanode"; // public static final String CLUSTER_DATAHOST = "datahost"; // public static final String CLUSTER_SCHEMA = "schema"; // public static final String CLUSTER_RULE = "rule"; // public static final String CLUSTER_SEQUENCE = "sequence"; // public static final String CLUSTER_BLOCKSQLS = "blockSQLs"; // // // public static final String MYCATS = MYCAT_EYE+"/mycat"; // public static final String MYCAT_JMX = MYCAT_EYE+"/mycat_jmx"; // public static final String MYCAT_MYSQL = MYCAT_EYE+"/mysql"; // public static final String MYCAT_SNMP = MYCAT_EYE+"/mycat_snmp"; // public static final String MYCAT_PROCESSOR = MYCAT_EYE+"/mycat_processor"; // // public static boolean Mycat_JRDS=false; // // // public static final String MYCATY_WARN_MAIL = "mycat_warn_mail"; // } // Path: src/main/java/org/mycat/web/service/cluster/SequenceService.java import org.apache.curator.utils.ZKPaths; import org.hx.rainbow.common.context.RainbowContext; import org.mycat.web.model.cluster.Sequence; import org.mycat.web.service.AbstractConfigSevice; import org.mycat.web.util.Constant; import org.springframework.stereotype.Service; package org.mycat.web.service.cluster; @Service("sequenceService") public class SequenceService extends AbstractConfigSevice{ private Class<Sequence> clazz = Sequence.class;
private String menuPath = Constant.MYCAT_CLUSTER_KEY;
patrickvankann/rxmqtt
src/main/java/net/eusashead/iot/mqtt/paho/PublishFactory.java
// Path: src/main/java/net/eusashead/iot/mqtt/MqttMessage.java // public interface MqttMessage { // // boolean isRetained(); // // int getQos(); // // byte[] getPayload(); // // } // // Path: src/main/java/net/eusashead/iot/mqtt/PublishToken.java // public interface PublishToken extends MqttToken { // // }
import io.reactivex.SingleEmitter; import net.eusashead.iot.mqtt.MqttMessage; import java.util.Objects; import net.eusashead.iot.mqtt.PublishToken; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.paho.client.mqttv3.IMqttAsyncClient; import org.eclipse.paho.client.mqttv3.IMqttToken; import org.eclipse.paho.client.mqttv3.MqttException; import io.reactivex.Single;
package net.eusashead.iot.mqtt.paho; /* * #[license] * rxmqtt * %% * Copyright (C) 2013 - 2016 Eusa's Head * %% * 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. * %[license] */ public class PublishFactory extends BaseMqttActionFactory { private final static Logger LOGGER = Logger .getLogger(PublishFactory.class.getName()); static final class PublishActionListener extends BaseEmitterMqttActionListener {
// Path: src/main/java/net/eusashead/iot/mqtt/MqttMessage.java // public interface MqttMessage { // // boolean isRetained(); // // int getQos(); // // byte[] getPayload(); // // } // // Path: src/main/java/net/eusashead/iot/mqtt/PublishToken.java // public interface PublishToken extends MqttToken { // // } // Path: src/main/java/net/eusashead/iot/mqtt/paho/PublishFactory.java import io.reactivex.SingleEmitter; import net.eusashead.iot.mqtt.MqttMessage; import java.util.Objects; import net.eusashead.iot.mqtt.PublishToken; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.paho.client.mqttv3.IMqttAsyncClient; import org.eclipse.paho.client.mqttv3.IMqttToken; import org.eclipse.paho.client.mqttv3.MqttException; import io.reactivex.Single; package net.eusashead.iot.mqtt.paho; /* * #[license] * rxmqtt * %% * Copyright (C) 2013 - 2016 Eusa's Head * %% * 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. * %[license] */ public class PublishFactory extends BaseMqttActionFactory { private final static Logger LOGGER = Logger .getLogger(PublishFactory.class.getName()); static final class PublishActionListener extends BaseEmitterMqttActionListener {
private final SingleEmitter<? super PublishToken> emitter;
patrickvankann/rxmqtt
src/main/java/net/eusashead/iot/mqtt/paho/PublishFactory.java
// Path: src/main/java/net/eusashead/iot/mqtt/MqttMessage.java // public interface MqttMessage { // // boolean isRetained(); // // int getQos(); // // byte[] getPayload(); // // } // // Path: src/main/java/net/eusashead/iot/mqtt/PublishToken.java // public interface PublishToken extends MqttToken { // // }
import io.reactivex.SingleEmitter; import net.eusashead.iot.mqtt.MqttMessage; import java.util.Objects; import net.eusashead.iot.mqtt.PublishToken; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.paho.client.mqttv3.IMqttAsyncClient; import org.eclipse.paho.client.mqttv3.IMqttToken; import org.eclipse.paho.client.mqttv3.MqttException; import io.reactivex.Single;
@Override public String getClientId() { return mqttToken.getClient().getClientId(); } @Override public String[] getTopics() { return mqttToken.getTopics(); } @Override public int getMessageId() { return mqttToken.getMessageId(); } @Override public boolean getSessionPresent() { return mqttToken.getSessionPresent(); } }; this.emitter.onSuccess(publishToken); } } public PublishFactory(final IMqttAsyncClient client) { super(client); } public Single<PublishToken> create(final String topic,
// Path: src/main/java/net/eusashead/iot/mqtt/MqttMessage.java // public interface MqttMessage { // // boolean isRetained(); // // int getQos(); // // byte[] getPayload(); // // } // // Path: src/main/java/net/eusashead/iot/mqtt/PublishToken.java // public interface PublishToken extends MqttToken { // // } // Path: src/main/java/net/eusashead/iot/mqtt/paho/PublishFactory.java import io.reactivex.SingleEmitter; import net.eusashead.iot.mqtt.MqttMessage; import java.util.Objects; import net.eusashead.iot.mqtt.PublishToken; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.paho.client.mqttv3.IMqttAsyncClient; import org.eclipse.paho.client.mqttv3.IMqttToken; import org.eclipse.paho.client.mqttv3.MqttException; import io.reactivex.Single; @Override public String getClientId() { return mqttToken.getClient().getClientId(); } @Override public String[] getTopics() { return mqttToken.getTopics(); } @Override public int getMessageId() { return mqttToken.getMessageId(); } @Override public boolean getSessionPresent() { return mqttToken.getSessionPresent(); } }; this.emitter.onSuccess(publishToken); } } public PublishFactory(final IMqttAsyncClient client) { super(client); } public Single<PublishToken> create(final String topic,
final MqttMessage msg) {