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 |
|---|---|---|---|---|---|---|
rust-keylock/rust-keylock-android | java/src/main/java/org/astonbitecode/rustkeylock/fragments/DirectorySelector.java | // Path: java/src/main/java/org/astonbitecode/rustkeylock/adapters/DirectoriesAdapter.java
// public class DirectoriesAdapter extends ArrayAdapter<DirectorySelector.DirectoryEntry> {
// private List<DirectorySelector.DirectoryEntry> entries;
// private Context context;
// private int layoutResourceId;
//
// public DirectoriesAdapter(Context context, int resourceId, List<DirectorySelector.DirectoryEntry> entries) {
// super(context, resourceId, entries);
// this.entries = entries;
// this.context = context;
// this.layoutResourceId = resourceId;
// }
//
// public View getView(int position, View convertView, ViewGroup parent) {
// View v = convertView;
//
// if (v == null) {
// LayoutInflater inflater = ((Activity) context).getLayoutInflater();
// v = inflater.inflate(layoutResourceId, parent, false);
// }
//
// DirectorySelector.DirectoryEntry i = entries.get(position);
//
// if (i != null) {
// TextView tvn = (TextView) v.findViewById(R.id.directoryname);
//
// if (tvn != null) {
// tvn.setText(i.getName());
// }
// }
// return v;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/handlers/back/BackButtonHandler.java
// public interface BackButtonHandler extends Serializable {
// void onBackButton();
// }
| import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import org.astonbitecode.rustkeylock.R;
import org.astonbitecode.rustkeylock.adapters.DirectoriesAdapter;
import org.astonbitecode.rustkeylock.handlers.back.BackButtonHandler;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast; | // Copyright 2017 astonbitecode
// This file is part of rust-keylock password manager.
//
// rust-keylock is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rust-keylock is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with rust-keylock. If not, see <http://www.gnu.org/licenses/>.
package org.astonbitecode.rustkeylock.fragments;
public class DirectorySelector extends ListFragment implements OnClickListener, BackButtonHandler {
private static final long serialVersionUID = 1382314701594691684L;
private final String TAG = getClass().getName();
private final String PARENT_IDENTIFIER = "..";
private final String CURR_DIR_PREFIX = "Current directory: ";
| // Path: java/src/main/java/org/astonbitecode/rustkeylock/adapters/DirectoriesAdapter.java
// public class DirectoriesAdapter extends ArrayAdapter<DirectorySelector.DirectoryEntry> {
// private List<DirectorySelector.DirectoryEntry> entries;
// private Context context;
// private int layoutResourceId;
//
// public DirectoriesAdapter(Context context, int resourceId, List<DirectorySelector.DirectoryEntry> entries) {
// super(context, resourceId, entries);
// this.entries = entries;
// this.context = context;
// this.layoutResourceId = resourceId;
// }
//
// public View getView(int position, View convertView, ViewGroup parent) {
// View v = convertView;
//
// if (v == null) {
// LayoutInflater inflater = ((Activity) context).getLayoutInflater();
// v = inflater.inflate(layoutResourceId, parent, false);
// }
//
// DirectorySelector.DirectoryEntry i = entries.get(position);
//
// if (i != null) {
// TextView tvn = (TextView) v.findViewById(R.id.directoryname);
//
// if (tvn != null) {
// tvn.setText(i.getName());
// }
// }
// return v;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/handlers/back/BackButtonHandler.java
// public interface BackButtonHandler extends Serializable {
// void onBackButton();
// }
// Path: java/src/main/java/org/astonbitecode/rustkeylock/fragments/DirectorySelector.java
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import org.astonbitecode.rustkeylock.R;
import org.astonbitecode.rustkeylock.adapters.DirectoriesAdapter;
import org.astonbitecode.rustkeylock.handlers.back.BackButtonHandler;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
// Copyright 2017 astonbitecode
// This file is part of rust-keylock password manager.
//
// rust-keylock is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rust-keylock is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with rust-keylock. If not, see <http://www.gnu.org/licenses/>.
package org.astonbitecode.rustkeylock.fragments;
public class DirectorySelector extends ListFragment implements OnClickListener, BackButtonHandler {
private static final long serialVersionUID = 1382314701594691684L;
private final String TAG = getClass().getName();
private final String PARENT_IDENTIFIER = "..";
private final String CURR_DIR_PREFIX = "Current directory: ";
| private DirectoriesAdapter directoriesAdapter; |
rust-keylock/rust-keylock-android | java/src/main/java/org/astonbitecode/rustkeylock/fragments/EnterPassword.java | // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/InterfaceWithRust.java
// public class InterfaceWithRust {
// private final String TAG = getClass().getName();
// public static final InterfaceWithRust INSTANCE = new InterfaceWithRust();
// private AtomicReference<NativeCallbackToRustChannelSupport> callback = new AtomicReference<>(null);
// private AtomicReference<Fragment> previousFragment = new AtomicReference<>(null);
//
// private InterfaceWithRust() {
// Log.i(TAG, "Initializing the native interface with Rust...");
// System.loadLibrary("rustkeylockandroid");
// Log.i(TAG, "The native interface with Rust is initialized!");
// }
//
// public native void execute(Instance<String> certFilePath);
//
// private void call(Object obj) {
// callback.get().doCallback(obj);
// }
//
// public void set_password(String password, int number) {
// Map<String, Object> m = GuiResponse.ChangePassword(password, number);
// call(m);
// }
//
// public void go_to_menu(Map<String, Object> menu) {
// Map<String, Object> m = GuiResponse.GoToMenu(menu);
// call(m);
// }
//
// public void go_to_menu(String menu) {
// Map<String, Object> m = GuiResponse.GoToMenu(menu);
// call(m);
// }
//
// public void add_entry(JavaEntry javaEntry) {
// Map<String, Object> m = GuiResponse.AddEntry(javaEntry);
// call(m);
// }
//
// public void replace_entry(JavaEntry javaEntry, int index) {
// Map<String, Object> m = GuiResponse.ReplaceEntry(javaEntry, index);
// call(m);
// }
//
// public void delete_entry(int index) {
// Map<String, Object> m = GuiResponse.DeleteEntry(index);
// call(m);
// }
//
// public void generate_passphrase(JavaEntry javaEntry, int index) {
// Map<String, Object> m = GuiResponse.GeneratePassphrase(javaEntry, index);
// call(m);
// }
//
// public void export_import(String path, int export, String password, int number) {
// Map<String, Object> m = GuiResponse.ExportImport(path, export, password, number);
// call(m);
// }
//
// public void user_option_selected(String label, String value, String short_label) {
// JavaUserOption juo = new JavaUserOption(label, value, short_label);
// Map<String, Object> m = GuiResponse.UserOptionSelected(juo);
// call(m);
// }
//
// public void set_configuration(List<String> stringList) {
// Map<String, Object> m = GuiResponse.SetConfiguration(stringList);
// call(m);
// }
//
// public void copy(String data) {
// Map<String, Object> m = GuiResponse.Copy(data);
// call(m);
// }
//
// public void check_passwords() {
// call(GuiResponse.CheckPasswords());
// }
//
// public void setCallback(NativeCallbackToRustChannelSupport newCallback) {
// callback.set(newCallback);
// }
//
// public void updateState(Fragment newFragment) {
// previousFragment.set(newFragment);
// }
//
// public Fragment getPreviousFragment() {
// return previousFragment.get();
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/handlers/back/BackButtonHandler.java
// public interface BackButtonHandler extends Serializable {
// void onBackButton();
// }
| import org.astonbitecode.rustkeylock.R;
import org.astonbitecode.rustkeylock.api.InterfaceWithRust;
import org.astonbitecode.rustkeylock.handlers.back.BackButtonHandler;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText; | } else if (month >= Calendar.JUNE && month < Calendar.SEPTEMBER) {
image.setImageResource(R.drawable.summer);
} else if (month >= Calendar.SEPTEMBER && month < Calendar.NOVEMBER) {
image.setImageResource(R.drawable.unmbrella);
}
*/
EditText passwordText = (EditText) rootView.findViewById(R.id.editPassword);
this.passwordText = passwordText;
EditText numberText = (EditText) rootView.findViewById(R.id.editFavoriteNumber);
this.numberText = numberText;
Button b = (Button) rootView.findViewById(R.id.buttonDecrypt);
b.setOnClickListener(this);
return rootView;
}
@Override
public void onClick(View view) {
String pass = passwordText.getText() != null ? passwordText.getText().toString() : "";
String numString = numberText.getText() != null ? numberText.getText().toString() : "";
if (pass.isEmpty()) {
passwordText.setError("Required Field");
passwordText.setText("");
} else if (numString.isEmpty()) {
numberText.setText("");
numberText.setError("Required Field");
} else {
try {
int num = new Integer(numString); | // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/InterfaceWithRust.java
// public class InterfaceWithRust {
// private final String TAG = getClass().getName();
// public static final InterfaceWithRust INSTANCE = new InterfaceWithRust();
// private AtomicReference<NativeCallbackToRustChannelSupport> callback = new AtomicReference<>(null);
// private AtomicReference<Fragment> previousFragment = new AtomicReference<>(null);
//
// private InterfaceWithRust() {
// Log.i(TAG, "Initializing the native interface with Rust...");
// System.loadLibrary("rustkeylockandroid");
// Log.i(TAG, "The native interface with Rust is initialized!");
// }
//
// public native void execute(Instance<String> certFilePath);
//
// private void call(Object obj) {
// callback.get().doCallback(obj);
// }
//
// public void set_password(String password, int number) {
// Map<String, Object> m = GuiResponse.ChangePassword(password, number);
// call(m);
// }
//
// public void go_to_menu(Map<String, Object> menu) {
// Map<String, Object> m = GuiResponse.GoToMenu(menu);
// call(m);
// }
//
// public void go_to_menu(String menu) {
// Map<String, Object> m = GuiResponse.GoToMenu(menu);
// call(m);
// }
//
// public void add_entry(JavaEntry javaEntry) {
// Map<String, Object> m = GuiResponse.AddEntry(javaEntry);
// call(m);
// }
//
// public void replace_entry(JavaEntry javaEntry, int index) {
// Map<String, Object> m = GuiResponse.ReplaceEntry(javaEntry, index);
// call(m);
// }
//
// public void delete_entry(int index) {
// Map<String, Object> m = GuiResponse.DeleteEntry(index);
// call(m);
// }
//
// public void generate_passphrase(JavaEntry javaEntry, int index) {
// Map<String, Object> m = GuiResponse.GeneratePassphrase(javaEntry, index);
// call(m);
// }
//
// public void export_import(String path, int export, String password, int number) {
// Map<String, Object> m = GuiResponse.ExportImport(path, export, password, number);
// call(m);
// }
//
// public void user_option_selected(String label, String value, String short_label) {
// JavaUserOption juo = new JavaUserOption(label, value, short_label);
// Map<String, Object> m = GuiResponse.UserOptionSelected(juo);
// call(m);
// }
//
// public void set_configuration(List<String> stringList) {
// Map<String, Object> m = GuiResponse.SetConfiguration(stringList);
// call(m);
// }
//
// public void copy(String data) {
// Map<String, Object> m = GuiResponse.Copy(data);
// call(m);
// }
//
// public void check_passwords() {
// call(GuiResponse.CheckPasswords());
// }
//
// public void setCallback(NativeCallbackToRustChannelSupport newCallback) {
// callback.set(newCallback);
// }
//
// public void updateState(Fragment newFragment) {
// previousFragment.set(newFragment);
// }
//
// public Fragment getPreviousFragment() {
// return previousFragment.get();
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/handlers/back/BackButtonHandler.java
// public interface BackButtonHandler extends Serializable {
// void onBackButton();
// }
// Path: java/src/main/java/org/astonbitecode/rustkeylock/fragments/EnterPassword.java
import org.astonbitecode.rustkeylock.R;
import org.astonbitecode.rustkeylock.api.InterfaceWithRust;
import org.astonbitecode.rustkeylock.handlers.back.BackButtonHandler;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
} else if (month >= Calendar.JUNE && month < Calendar.SEPTEMBER) {
image.setImageResource(R.drawable.summer);
} else if (month >= Calendar.SEPTEMBER && month < Calendar.NOVEMBER) {
image.setImageResource(R.drawable.unmbrella);
}
*/
EditText passwordText = (EditText) rootView.findViewById(R.id.editPassword);
this.passwordText = passwordText;
EditText numberText = (EditText) rootView.findViewById(R.id.editFavoriteNumber);
this.numberText = numberText;
Button b = (Button) rootView.findViewById(R.id.buttonDecrypt);
b.setOnClickListener(this);
return rootView;
}
@Override
public void onClick(View view) {
String pass = passwordText.getText() != null ? passwordText.getText().toString() : "";
String numString = numberText.getText() != null ? numberText.getText().toString() : "";
if (pass.isEmpty()) {
passwordText.setError("Required Field");
passwordText.setText("");
} else if (numString.isEmpty()) {
numberText.setText("");
numberText.setError("Required Field");
} else {
try {
int num = new Integer(numString); | InterfaceWithRust.INSTANCE.set_password(pass, num); |
rust-keylock/rust-keylock-android | java/src/main/java/org/astonbitecode/rustkeylock/adapters/EntriesAdapter.java | // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/JavaEntry.java
// public class JavaEntry implements Serializable {
//
// public String name;
// public String url;
// public String user;
// public String pass;
// public String desc;
// public JavaEntryMeta meta;
//
// public JavaEntry() {
//
// }
//
// public String getName() {
// return name;
// }
//
// public String getUrl() {
// return url;
// }
//
// public String getUser() {
// return user;
// }
//
// public String getPass() {
// return pass;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public void setPass(String pass) {
// this.pass = pass;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public JavaEntryMeta getMeta() {
// return meta;
// }
//
// public void setMeta(JavaEntryMeta meta) {
// this.meta = meta;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/utils/Defs.java
// public class Defs {
// public static final String MENU_TRY_PASS = "TryPass";
// public static final String MENU_CHANGE_PASS = "ChangePass";
// public static final String MENU_MAIN = "Main";
// public static final String MENU_ENTRIES_LIST = "EntriesList";
// public static final String MENU_SHOW_ENTRY = "ShowEntry";
// public static final String MENU_SAVE = "Save";
// public static final String MENU_EXIT = "Exit";
// public static final String MENU_FORCE_EXIT = "ForceExit";
// public static final String MENU_EDIT_ENTRY = "EditEntry";
// public static final String MENU_DELETE_ENTRY = "DeleteEntry";
// public static final String MENU_NEW_ENTRY = "NewEntry";
// public static final String MENU_EXPORT_ENTRIES = "ExportEntries";
// public static final String MENU_IMPORT_ENTRIES = "ImportEntries";
// public static final String MENU_SHOW_CONFIGURATION = "ShowConfiguration";
// public static final String MENU_SET_DB_TOKEN = "SetDbxToken";
// public static final String MENU_CURRENT = "Current";
// public static final String EMPTY_ARG = "null";
// public static final String CHECK_PASSWORDS = "CheckPasswords";
// public static final int BACKROUND_ERROR = Color.argb(255, 246, 147, 100);
// public static final int BACKROUND_NO_ERROR = Color.TRANSPARENT;
// }
| import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.astonbitecode.rustkeylock.R;
import org.astonbitecode.rustkeylock.api.JavaEntry;
import org.astonbitecode.rustkeylock.utils.Defs;
import java.util.List; | // Copyright 2017 astonbitecode
// This file is part of rust-keylock password manager.
//
// rust-keylock is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rust-keylock is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with rust-keylock. If not, see <http://www.gnu.org/licenses/>.
package org.astonbitecode.rustkeylock.adapters;
public class EntriesAdapter extends ArrayAdapter<JavaEntry> {
private List<JavaEntry> entries;
private Context context;
private int layoutResourceId;
public EntriesAdapter(Context context, int resourceId, List<JavaEntry> entries) {
super(context, resourceId, entries);
this.entries = entries;
this.context = context;
this.layoutResourceId = resourceId;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
v = inflater.inflate(layoutResourceId, parent, false);
}
JavaEntry i = entries.get(position);
if (i != null) {
TextView tvn = (TextView) v.findViewById(R.id.entryname);
if (tvn != null) {
tvn.setText(i.getName());
LinearLayout ll = (LinearLayout) v.findViewById(R.id.entrynamecontainer);
if (i.getMeta().isLeakedpassword()) { | // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/JavaEntry.java
// public class JavaEntry implements Serializable {
//
// public String name;
// public String url;
// public String user;
// public String pass;
// public String desc;
// public JavaEntryMeta meta;
//
// public JavaEntry() {
//
// }
//
// public String getName() {
// return name;
// }
//
// public String getUrl() {
// return url;
// }
//
// public String getUser() {
// return user;
// }
//
// public String getPass() {
// return pass;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public void setPass(String pass) {
// this.pass = pass;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public JavaEntryMeta getMeta() {
// return meta;
// }
//
// public void setMeta(JavaEntryMeta meta) {
// this.meta = meta;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/utils/Defs.java
// public class Defs {
// public static final String MENU_TRY_PASS = "TryPass";
// public static final String MENU_CHANGE_PASS = "ChangePass";
// public static final String MENU_MAIN = "Main";
// public static final String MENU_ENTRIES_LIST = "EntriesList";
// public static final String MENU_SHOW_ENTRY = "ShowEntry";
// public static final String MENU_SAVE = "Save";
// public static final String MENU_EXIT = "Exit";
// public static final String MENU_FORCE_EXIT = "ForceExit";
// public static final String MENU_EDIT_ENTRY = "EditEntry";
// public static final String MENU_DELETE_ENTRY = "DeleteEntry";
// public static final String MENU_NEW_ENTRY = "NewEntry";
// public static final String MENU_EXPORT_ENTRIES = "ExportEntries";
// public static final String MENU_IMPORT_ENTRIES = "ImportEntries";
// public static final String MENU_SHOW_CONFIGURATION = "ShowConfiguration";
// public static final String MENU_SET_DB_TOKEN = "SetDbxToken";
// public static final String MENU_CURRENT = "Current";
// public static final String EMPTY_ARG = "null";
// public static final String CHECK_PASSWORDS = "CheckPasswords";
// public static final int BACKROUND_ERROR = Color.argb(255, 246, 147, 100);
// public static final int BACKROUND_NO_ERROR = Color.TRANSPARENT;
// }
// Path: java/src/main/java/org/astonbitecode/rustkeylock/adapters/EntriesAdapter.java
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.astonbitecode.rustkeylock.R;
import org.astonbitecode.rustkeylock.api.JavaEntry;
import org.astonbitecode.rustkeylock.utils.Defs;
import java.util.List;
// Copyright 2017 astonbitecode
// This file is part of rust-keylock password manager.
//
// rust-keylock is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rust-keylock is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with rust-keylock. If not, see <http://www.gnu.org/licenses/>.
package org.astonbitecode.rustkeylock.adapters;
public class EntriesAdapter extends ArrayAdapter<JavaEntry> {
private List<JavaEntry> entries;
private Context context;
private int layoutResourceId;
public EntriesAdapter(Context context, int resourceId, List<JavaEntry> entries) {
super(context, resourceId, entries);
this.entries = entries;
this.context = context;
this.layoutResourceId = resourceId;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
v = inflater.inflate(layoutResourceId, parent, false);
}
JavaEntry i = entries.get(position);
if (i != null) {
TextView tvn = (TextView) v.findViewById(R.id.entryname);
if (tvn != null) {
tvn.setText(i.getName());
LinearLayout ll = (LinearLayout) v.findViewById(R.id.entrynamecontainer);
if (i.getMeta().isLeakedpassword()) { | ll.setBackgroundColor(Defs.BACKROUND_ERROR); |
rust-keylock/rust-keylock-android | java/src/main/java/org/astonbitecode/rustkeylock/MainActivity.java | // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/InterfaceWithRust.java
// public class InterfaceWithRust {
// private final String TAG = getClass().getName();
// public static final InterfaceWithRust INSTANCE = new InterfaceWithRust();
// private AtomicReference<NativeCallbackToRustChannelSupport> callback = new AtomicReference<>(null);
// private AtomicReference<Fragment> previousFragment = new AtomicReference<>(null);
//
// private InterfaceWithRust() {
// Log.i(TAG, "Initializing the native interface with Rust...");
// System.loadLibrary("rustkeylockandroid");
// Log.i(TAG, "The native interface with Rust is initialized!");
// }
//
// public native void execute(Instance<String> certFilePath);
//
// private void call(Object obj) {
// callback.get().doCallback(obj);
// }
//
// public void set_password(String password, int number) {
// Map<String, Object> m = GuiResponse.ChangePassword(password, number);
// call(m);
// }
//
// public void go_to_menu(Map<String, Object> menu) {
// Map<String, Object> m = GuiResponse.GoToMenu(menu);
// call(m);
// }
//
// public void go_to_menu(String menu) {
// Map<String, Object> m = GuiResponse.GoToMenu(menu);
// call(m);
// }
//
// public void add_entry(JavaEntry javaEntry) {
// Map<String, Object> m = GuiResponse.AddEntry(javaEntry);
// call(m);
// }
//
// public void replace_entry(JavaEntry javaEntry, int index) {
// Map<String, Object> m = GuiResponse.ReplaceEntry(javaEntry, index);
// call(m);
// }
//
// public void delete_entry(int index) {
// Map<String, Object> m = GuiResponse.DeleteEntry(index);
// call(m);
// }
//
// public void generate_passphrase(JavaEntry javaEntry, int index) {
// Map<String, Object> m = GuiResponse.GeneratePassphrase(javaEntry, index);
// call(m);
// }
//
// public void export_import(String path, int export, String password, int number) {
// Map<String, Object> m = GuiResponse.ExportImport(path, export, password, number);
// call(m);
// }
//
// public void user_option_selected(String label, String value, String short_label) {
// JavaUserOption juo = new JavaUserOption(label, value, short_label);
// Map<String, Object> m = GuiResponse.UserOptionSelected(juo);
// call(m);
// }
//
// public void set_configuration(List<String> stringList) {
// Map<String, Object> m = GuiResponse.SetConfiguration(stringList);
// call(m);
// }
//
// public void copy(String data) {
// Map<String, Object> m = GuiResponse.Copy(data);
// call(m);
// }
//
// public void check_passwords() {
// call(GuiResponse.CheckPasswords());
// }
//
// public void setCallback(NativeCallbackToRustChannelSupport newCallback) {
// callback.set(newCallback);
// }
//
// public void updateState(Fragment newFragment) {
// previousFragment.set(newFragment);
// }
//
// public Fragment getPreviousFragment() {
// return previousFragment.get();
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/handlers/back/BackButtonHandlable.java
// public interface BackButtonHandlable {
// void setBackButtonHandler(BackButtonHandler backButtonHandler);
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/handlers/back/BackButtonHandler.java
// public interface BackButtonHandler extends Serializable {
// void onBackButton();
// }
| import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import org.astonbitecode.rustkeylock.api.InterfaceWithRust;
import org.astonbitecode.rustkeylock.handlers.back.BackButtonHandlable;
import org.astonbitecode.rustkeylock.handlers.back.BackButtonHandler; | // Copyright 2017 astonbitecode
// This file is part of rust-keylock password manager.
//
// rust-keylock is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rust-keylock is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with rust-keylock. If not, see <http://www.gnu.org/licenses/>.
package org.astonbitecode.rustkeylock;
public class MainActivity extends Activity implements BackButtonHandlable {
private static MainActivity ACTIVE_ACTIVITY;
public static MainActivity getActiveActivity() {
return ACTIVE_ACTIVITY;
}
private final String TAG = getClass().getName();
private Thread rustThread = null; | // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/InterfaceWithRust.java
// public class InterfaceWithRust {
// private final String TAG = getClass().getName();
// public static final InterfaceWithRust INSTANCE = new InterfaceWithRust();
// private AtomicReference<NativeCallbackToRustChannelSupport> callback = new AtomicReference<>(null);
// private AtomicReference<Fragment> previousFragment = new AtomicReference<>(null);
//
// private InterfaceWithRust() {
// Log.i(TAG, "Initializing the native interface with Rust...");
// System.loadLibrary("rustkeylockandroid");
// Log.i(TAG, "The native interface with Rust is initialized!");
// }
//
// public native void execute(Instance<String> certFilePath);
//
// private void call(Object obj) {
// callback.get().doCallback(obj);
// }
//
// public void set_password(String password, int number) {
// Map<String, Object> m = GuiResponse.ChangePassword(password, number);
// call(m);
// }
//
// public void go_to_menu(Map<String, Object> menu) {
// Map<String, Object> m = GuiResponse.GoToMenu(menu);
// call(m);
// }
//
// public void go_to_menu(String menu) {
// Map<String, Object> m = GuiResponse.GoToMenu(menu);
// call(m);
// }
//
// public void add_entry(JavaEntry javaEntry) {
// Map<String, Object> m = GuiResponse.AddEntry(javaEntry);
// call(m);
// }
//
// public void replace_entry(JavaEntry javaEntry, int index) {
// Map<String, Object> m = GuiResponse.ReplaceEntry(javaEntry, index);
// call(m);
// }
//
// public void delete_entry(int index) {
// Map<String, Object> m = GuiResponse.DeleteEntry(index);
// call(m);
// }
//
// public void generate_passphrase(JavaEntry javaEntry, int index) {
// Map<String, Object> m = GuiResponse.GeneratePassphrase(javaEntry, index);
// call(m);
// }
//
// public void export_import(String path, int export, String password, int number) {
// Map<String, Object> m = GuiResponse.ExportImport(path, export, password, number);
// call(m);
// }
//
// public void user_option_selected(String label, String value, String short_label) {
// JavaUserOption juo = new JavaUserOption(label, value, short_label);
// Map<String, Object> m = GuiResponse.UserOptionSelected(juo);
// call(m);
// }
//
// public void set_configuration(List<String> stringList) {
// Map<String, Object> m = GuiResponse.SetConfiguration(stringList);
// call(m);
// }
//
// public void copy(String data) {
// Map<String, Object> m = GuiResponse.Copy(data);
// call(m);
// }
//
// public void check_passwords() {
// call(GuiResponse.CheckPasswords());
// }
//
// public void setCallback(NativeCallbackToRustChannelSupport newCallback) {
// callback.set(newCallback);
// }
//
// public void updateState(Fragment newFragment) {
// previousFragment.set(newFragment);
// }
//
// public Fragment getPreviousFragment() {
// return previousFragment.get();
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/handlers/back/BackButtonHandlable.java
// public interface BackButtonHandlable {
// void setBackButtonHandler(BackButtonHandler backButtonHandler);
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/handlers/back/BackButtonHandler.java
// public interface BackButtonHandler extends Serializable {
// void onBackButton();
// }
// Path: java/src/main/java/org/astonbitecode/rustkeylock/MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import org.astonbitecode.rustkeylock.api.InterfaceWithRust;
import org.astonbitecode.rustkeylock.handlers.back.BackButtonHandlable;
import org.astonbitecode.rustkeylock.handlers.back.BackButtonHandler;
// Copyright 2017 astonbitecode
// This file is part of rust-keylock password manager.
//
// rust-keylock is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rust-keylock is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with rust-keylock. If not, see <http://www.gnu.org/licenses/>.
package org.astonbitecode.rustkeylock;
public class MainActivity extends Activity implements BackButtonHandlable {
private static MainActivity ACTIVE_ACTIVITY;
public static MainActivity getActiveActivity() {
return ACTIVE_ACTIVITY;
}
private final String TAG = getClass().getName();
private Thread rustThread = null; | private BackButtonHandler backButtonHandler; |
rust-keylock/rust-keylock-android | java/src/main/java/org/astonbitecode/rustkeylock/RustRunnable.java | // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/InterfaceWithRust.java
// public class InterfaceWithRust {
// private final String TAG = getClass().getName();
// public static final InterfaceWithRust INSTANCE = new InterfaceWithRust();
// private AtomicReference<NativeCallbackToRustChannelSupport> callback = new AtomicReference<>(null);
// private AtomicReference<Fragment> previousFragment = new AtomicReference<>(null);
//
// private InterfaceWithRust() {
// Log.i(TAG, "Initializing the native interface with Rust...");
// System.loadLibrary("rustkeylockandroid");
// Log.i(TAG, "The native interface with Rust is initialized!");
// }
//
// public native void execute(Instance<String> certFilePath);
//
// private void call(Object obj) {
// callback.get().doCallback(obj);
// }
//
// public void set_password(String password, int number) {
// Map<String, Object> m = GuiResponse.ChangePassword(password, number);
// call(m);
// }
//
// public void go_to_menu(Map<String, Object> menu) {
// Map<String, Object> m = GuiResponse.GoToMenu(menu);
// call(m);
// }
//
// public void go_to_menu(String menu) {
// Map<String, Object> m = GuiResponse.GoToMenu(menu);
// call(m);
// }
//
// public void add_entry(JavaEntry javaEntry) {
// Map<String, Object> m = GuiResponse.AddEntry(javaEntry);
// call(m);
// }
//
// public void replace_entry(JavaEntry javaEntry, int index) {
// Map<String, Object> m = GuiResponse.ReplaceEntry(javaEntry, index);
// call(m);
// }
//
// public void delete_entry(int index) {
// Map<String, Object> m = GuiResponse.DeleteEntry(index);
// call(m);
// }
//
// public void generate_passphrase(JavaEntry javaEntry, int index) {
// Map<String, Object> m = GuiResponse.GeneratePassphrase(javaEntry, index);
// call(m);
// }
//
// public void export_import(String path, int export, String password, int number) {
// Map<String, Object> m = GuiResponse.ExportImport(path, export, password, number);
// call(m);
// }
//
// public void user_option_selected(String label, String value, String short_label) {
// JavaUserOption juo = new JavaUserOption(label, value, short_label);
// Map<String, Object> m = GuiResponse.UserOptionSelected(juo);
// call(m);
// }
//
// public void set_configuration(List<String> stringList) {
// Map<String, Object> m = GuiResponse.SetConfiguration(stringList);
// call(m);
// }
//
// public void copy(String data) {
// Map<String, Object> m = GuiResponse.Copy(data);
// call(m);
// }
//
// public void check_passwords() {
// call(GuiResponse.CheckPasswords());
// }
//
// public void setCallback(NativeCallbackToRustChannelSupport newCallback) {
// callback.set(newCallback);
// }
//
// public void updateState(Fragment newFragment) {
// previousFragment.set(newFragment);
// }
//
// public Fragment getPreviousFragment() {
// return previousFragment.get();
// }
// }
| import android.util.Log;
import org.astonbitecode.j4rs.api.java2rust.Java2RustUtils;
import org.astonbitecode.rustkeylock.api.InterfaceWithRust;
import org.astonbitecode.rustkeylock.callbacks.*;
import java.io.*; |
private void copyCerts(MainActivity mainActivity) {
try {
File targetExternal = new File(CertsExternalBasePath);
targetExternal.mkdirs();
File target = new File(CertTargetPath);
if (!target.exists()) {
File base = new File(CertsBasePath);
base.mkdirs();
Log.w(TAG, "Copying the certificates in " + CertTargetPath);
final InputStream in = mainActivity.getAssets().open("certs/rkl_cacert.pem");
byte[] buffer = new byte[in.available()];
in.read(buffer);
OutputStream out = new FileOutputStream(target);
out.write(buffer);
out.flush();
out.close();
in.close();
}
} catch (IOException error) {
Log.e(TAG, "Could not copy the certificates...", error);
}
}
@Override
public void run() {
Log.d(TAG, "Initializing rust-keylock native");
try { | // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/InterfaceWithRust.java
// public class InterfaceWithRust {
// private final String TAG = getClass().getName();
// public static final InterfaceWithRust INSTANCE = new InterfaceWithRust();
// private AtomicReference<NativeCallbackToRustChannelSupport> callback = new AtomicReference<>(null);
// private AtomicReference<Fragment> previousFragment = new AtomicReference<>(null);
//
// private InterfaceWithRust() {
// Log.i(TAG, "Initializing the native interface with Rust...");
// System.loadLibrary("rustkeylockandroid");
// Log.i(TAG, "The native interface with Rust is initialized!");
// }
//
// public native void execute(Instance<String> certFilePath);
//
// private void call(Object obj) {
// callback.get().doCallback(obj);
// }
//
// public void set_password(String password, int number) {
// Map<String, Object> m = GuiResponse.ChangePassword(password, number);
// call(m);
// }
//
// public void go_to_menu(Map<String, Object> menu) {
// Map<String, Object> m = GuiResponse.GoToMenu(menu);
// call(m);
// }
//
// public void go_to_menu(String menu) {
// Map<String, Object> m = GuiResponse.GoToMenu(menu);
// call(m);
// }
//
// public void add_entry(JavaEntry javaEntry) {
// Map<String, Object> m = GuiResponse.AddEntry(javaEntry);
// call(m);
// }
//
// public void replace_entry(JavaEntry javaEntry, int index) {
// Map<String, Object> m = GuiResponse.ReplaceEntry(javaEntry, index);
// call(m);
// }
//
// public void delete_entry(int index) {
// Map<String, Object> m = GuiResponse.DeleteEntry(index);
// call(m);
// }
//
// public void generate_passphrase(JavaEntry javaEntry, int index) {
// Map<String, Object> m = GuiResponse.GeneratePassphrase(javaEntry, index);
// call(m);
// }
//
// public void export_import(String path, int export, String password, int number) {
// Map<String, Object> m = GuiResponse.ExportImport(path, export, password, number);
// call(m);
// }
//
// public void user_option_selected(String label, String value, String short_label) {
// JavaUserOption juo = new JavaUserOption(label, value, short_label);
// Map<String, Object> m = GuiResponse.UserOptionSelected(juo);
// call(m);
// }
//
// public void set_configuration(List<String> stringList) {
// Map<String, Object> m = GuiResponse.SetConfiguration(stringList);
// call(m);
// }
//
// public void copy(String data) {
// Map<String, Object> m = GuiResponse.Copy(data);
// call(m);
// }
//
// public void check_passwords() {
// call(GuiResponse.CheckPasswords());
// }
//
// public void setCallback(NativeCallbackToRustChannelSupport newCallback) {
// callback.set(newCallback);
// }
//
// public void updateState(Fragment newFragment) {
// previousFragment.set(newFragment);
// }
//
// public Fragment getPreviousFragment() {
// return previousFragment.get();
// }
// }
// Path: java/src/main/java/org/astonbitecode/rustkeylock/RustRunnable.java
import android.util.Log;
import org.astonbitecode.j4rs.api.java2rust.Java2RustUtils;
import org.astonbitecode.rustkeylock.api.InterfaceWithRust;
import org.astonbitecode.rustkeylock.callbacks.*;
import java.io.*;
private void copyCerts(MainActivity mainActivity) {
try {
File targetExternal = new File(CertsExternalBasePath);
targetExternal.mkdirs();
File target = new File(CertTargetPath);
if (!target.exists()) {
File base = new File(CertsBasePath);
base.mkdirs();
Log.w(TAG, "Copying the certificates in " + CertTargetPath);
final InputStream in = mainActivity.getAssets().open("certs/rkl_cacert.pem");
byte[] buffer = new byte[in.available()];
in.read(buffer);
OutputStream out = new FileOutputStream(target);
out.write(buffer);
out.flush();
out.close();
in.close();
}
} catch (IOException error) {
Log.e(TAG, "Could not copy the certificates...", error);
}
}
@Override
public void run() {
Log.d(TAG, "Initializing rust-keylock native");
try { | InterfaceWithRust.INSTANCE.execute(Java2RustUtils.createInstance(CertTargetPath)); |
rust-keylock/rust-keylock-android | java/src/main/java/org/astonbitecode/rustkeylock/api/InterfaceWithRust.java | // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/stubs/GuiResponse.java
// public class GuiResponse {
// public static Map<String, Object> ChangePassword(String password, Integer number) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("password", password);
// inner.put("number", number);
// Map<String, Object> map = new HashMap<>();
// map.put("ProvidedPassword", inner);
// return map;
// }
//
// public static Map<String, Object> GoToMenu(Map<String, Object> m) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("menu", m);
// Map<String, Object> map = new HashMap<>();
// map.put("GoToMenu", inner);
// return map;
// }
//
// public static Map<String, Object> GoToMenu(String m) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("menu", m);
// Map<String, Object> map = new HashMap<>();
// map.put("GoToMenu", inner);
// return map;
// }
//
// public static Map<String, Object> DeleteEntry(Integer index) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("index", index);
// Map<String, Object> map = new HashMap<>();
// map.put("DeleteEntry", inner);
// return map;
// }
//
// public static Map<String, Object> ReplaceEntry(JavaEntry entry, Integer index) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("entry", entry);
// inner.put("index", index);
// Map<String, Object> map = new HashMap<>();
// map.put("ReplaceEntry", inner);
// return map;
// }
//
// public static Map<String, Object> GeneratePassphrase(JavaEntry entry, Integer index) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("entry", entry);
// inner.put("index", index);
// Map<String, Object> map = new HashMap<>();
// map.put("GeneratePassphrase", inner);
// return map;
// }
//
// public static Map<String, Object> AddEntry(JavaEntry entry) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("entry", entry);
// Map<String, Object> map = new HashMap<>();
// map.put("AddEntry", inner);
// return map;
// }
//
// public static Map<String, Object> SetConfiguration(java.util.List<String> strings) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("strings", strings);
// Map<String, Object> map = new HashMap<>();
// map.put("SetConfiguration", inner);
// return map;
// }
//
// public static Map<String, Object> UserOptionSelected(JavaUserOption userOption) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("user_option", userOption);
// Map<String, Object> map = new HashMap<>();
// map.put("UserOptionSelected", inner);
// return map;
// }
//
// public static Map<String, Object> ExportImport(String path, Integer mode, String password, Integer number) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("path", path);
// inner.put("mode", mode);
// inner.put("password", password);
// inner.put("number", number);
// Map<String, Object> map = new HashMap<>();
// map.put("ExportImport", inner);
// return map;
// }
//
// public static Map<String, Object> Copy(String data) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("data", data);
// Map<String, Object> map = new HashMap<>();
// map.put("Copy", inner);
// return map;
// }
//
// public static String CheckPasswords() {
// return Defs.CHECK_PASSWORDS;
// }
// }
| import android.app.Fragment;
import android.util.Log;
import org.astonbitecode.j4rs.api.Instance;
import org.astonbitecode.j4rs.api.invocation.NativeCallbackToRustChannelSupport;
import org.astonbitecode.rustkeylock.api.stubs.GuiResponse;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference; | // Copyright 2017 astonbitecode
// This file is part of rust-keylock password manager.
//
// rust-keylock is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rust-keylock is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with rust-keylock. If not, see <http://www.gnu.org/licenses/>.
package org.astonbitecode.rustkeylock.api;
public class InterfaceWithRust {
private final String TAG = getClass().getName();
public static final InterfaceWithRust INSTANCE = new InterfaceWithRust();
private AtomicReference<NativeCallbackToRustChannelSupport> callback = new AtomicReference<>(null);
private AtomicReference<Fragment> previousFragment = new AtomicReference<>(null);
private InterfaceWithRust() {
Log.i(TAG, "Initializing the native interface with Rust...");
System.loadLibrary("rustkeylockandroid");
Log.i(TAG, "The native interface with Rust is initialized!");
}
public native void execute(Instance<String> certFilePath);
private void call(Object obj) {
callback.get().doCallback(obj);
}
public void set_password(String password, int number) { | // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/stubs/GuiResponse.java
// public class GuiResponse {
// public static Map<String, Object> ChangePassword(String password, Integer number) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("password", password);
// inner.put("number", number);
// Map<String, Object> map = new HashMap<>();
// map.put("ProvidedPassword", inner);
// return map;
// }
//
// public static Map<String, Object> GoToMenu(Map<String, Object> m) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("menu", m);
// Map<String, Object> map = new HashMap<>();
// map.put("GoToMenu", inner);
// return map;
// }
//
// public static Map<String, Object> GoToMenu(String m) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("menu", m);
// Map<String, Object> map = new HashMap<>();
// map.put("GoToMenu", inner);
// return map;
// }
//
// public static Map<String, Object> DeleteEntry(Integer index) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("index", index);
// Map<String, Object> map = new HashMap<>();
// map.put("DeleteEntry", inner);
// return map;
// }
//
// public static Map<String, Object> ReplaceEntry(JavaEntry entry, Integer index) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("entry", entry);
// inner.put("index", index);
// Map<String, Object> map = new HashMap<>();
// map.put("ReplaceEntry", inner);
// return map;
// }
//
// public static Map<String, Object> GeneratePassphrase(JavaEntry entry, Integer index) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("entry", entry);
// inner.put("index", index);
// Map<String, Object> map = new HashMap<>();
// map.put("GeneratePassphrase", inner);
// return map;
// }
//
// public static Map<String, Object> AddEntry(JavaEntry entry) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("entry", entry);
// Map<String, Object> map = new HashMap<>();
// map.put("AddEntry", inner);
// return map;
// }
//
// public static Map<String, Object> SetConfiguration(java.util.List<String> strings) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("strings", strings);
// Map<String, Object> map = new HashMap<>();
// map.put("SetConfiguration", inner);
// return map;
// }
//
// public static Map<String, Object> UserOptionSelected(JavaUserOption userOption) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("user_option", userOption);
// Map<String, Object> map = new HashMap<>();
// map.put("UserOptionSelected", inner);
// return map;
// }
//
// public static Map<String, Object> ExportImport(String path, Integer mode, String password, Integer number) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("path", path);
// inner.put("mode", mode);
// inner.put("password", password);
// inner.put("number", number);
// Map<String, Object> map = new HashMap<>();
// map.put("ExportImport", inner);
// return map;
// }
//
// public static Map<String, Object> Copy(String data) {
// Map<String, Object> inner = new HashMap<>();
// inner.put("data", data);
// Map<String, Object> map = new HashMap<>();
// map.put("Copy", inner);
// return map;
// }
//
// public static String CheckPasswords() {
// return Defs.CHECK_PASSWORDS;
// }
// }
// Path: java/src/main/java/org/astonbitecode/rustkeylock/api/InterfaceWithRust.java
import android.app.Fragment;
import android.util.Log;
import org.astonbitecode.j4rs.api.Instance;
import org.astonbitecode.j4rs.api.invocation.NativeCallbackToRustChannelSupport;
import org.astonbitecode.rustkeylock.api.stubs.GuiResponse;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
// Copyright 2017 astonbitecode
// This file is part of rust-keylock password manager.
//
// rust-keylock is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rust-keylock is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with rust-keylock. If not, see <http://www.gnu.org/licenses/>.
package org.astonbitecode.rustkeylock.api;
public class InterfaceWithRust {
private final String TAG = getClass().getName();
public static final InterfaceWithRust INSTANCE = new InterfaceWithRust();
private AtomicReference<NativeCallbackToRustChannelSupport> callback = new AtomicReference<>(null);
private AtomicReference<Fragment> previousFragment = new AtomicReference<>(null);
private InterfaceWithRust() {
Log.i(TAG, "Initializing the native interface with Rust...");
System.loadLibrary("rustkeylockandroid");
Log.i(TAG, "The native interface with Rust is initialized!");
}
public native void execute(Instance<String> certFilePath);
private void call(Object obj) {
callback.get().doCallback(obj);
}
public void set_password(String password, int number) { | Map<String, Object> m = GuiResponse.ChangePassword(password, number); |
rust-keylock/rust-keylock-android | java/src/main/java/org/astonbitecode/rustkeylock/fragments/FileSelector.java | // Path: java/src/main/java/org/astonbitecode/rustkeylock/adapters/FilesAdapter.java
// public class FilesAdapter extends ArrayAdapter<FileSelector.FileEntry> {
// private List<FileSelector.FileEntry> entries;
// private Context context;
// private int layoutResourceId;
//
// public FilesAdapter(Context context, int resourceId, List<FileSelector.FileEntry> entries) {
// super(context, resourceId, entries);
// this.entries = entries;
// this.context = context;
// this.layoutResourceId = resourceId;
// }
//
// public View getView(int position, View convertView, ViewGroup parent) {
// View v = convertView;
//
// if (v == null) {
// LayoutInflater inflater = ((Activity) context).getLayoutInflater();
// v = inflater.inflate(layoutResourceId, parent, false);
// }
//
// FileSelector.FileEntry i = entries.get(position);
//
// if (i != null) {
// TextView tvn = (TextView) v.findViewById(R.id.filename);
//
// if (tvn != null) {
// tvn.setText(i.getName());
// }
// }
// return v;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/handlers/back/BackButtonHandler.java
// public interface BackButtonHandler extends Serializable {
// void onBackButton();
// }
| import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import org.astonbitecode.rustkeylock.R;
import org.astonbitecode.rustkeylock.adapters.FilesAdapter;
import org.astonbitecode.rustkeylock.handlers.back.BackButtonHandler;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView; | // Copyright 2017 astonbitecode
// This file is part of rust-keylock password manager.
//
// rust-keylock is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rust-keylock is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with rust-keylock. If not, see <http://www.gnu.org/licenses/>.
package org.astonbitecode.rustkeylock.fragments;
public class FileSelector extends ListFragment implements OnClickListener, BackButtonHandler {
private static final long serialVersionUID = 1382314701594691684L;
private final String TAG = getClass().getName();
private final String NO_FILE_SELECTED = "No File selected";
| // Path: java/src/main/java/org/astonbitecode/rustkeylock/adapters/FilesAdapter.java
// public class FilesAdapter extends ArrayAdapter<FileSelector.FileEntry> {
// private List<FileSelector.FileEntry> entries;
// private Context context;
// private int layoutResourceId;
//
// public FilesAdapter(Context context, int resourceId, List<FileSelector.FileEntry> entries) {
// super(context, resourceId, entries);
// this.entries = entries;
// this.context = context;
// this.layoutResourceId = resourceId;
// }
//
// public View getView(int position, View convertView, ViewGroup parent) {
// View v = convertView;
//
// if (v == null) {
// LayoutInflater inflater = ((Activity) context).getLayoutInflater();
// v = inflater.inflate(layoutResourceId, parent, false);
// }
//
// FileSelector.FileEntry i = entries.get(position);
//
// if (i != null) {
// TextView tvn = (TextView) v.findViewById(R.id.filename);
//
// if (tvn != null) {
// tvn.setText(i.getName());
// }
// }
// return v;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/handlers/back/BackButtonHandler.java
// public interface BackButtonHandler extends Serializable {
// void onBackButton();
// }
// Path: java/src/main/java/org/astonbitecode/rustkeylock/fragments/FileSelector.java
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import org.astonbitecode.rustkeylock.R;
import org.astonbitecode.rustkeylock.adapters.FilesAdapter;
import org.astonbitecode.rustkeylock.handlers.back.BackButtonHandler;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
// Copyright 2017 astonbitecode
// This file is part of rust-keylock password manager.
//
// rust-keylock is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rust-keylock is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with rust-keylock. If not, see <http://www.gnu.org/licenses/>.
package org.astonbitecode.rustkeylock.fragments;
public class FileSelector extends ListFragment implements OnClickListener, BackButtonHandler {
private static final long serialVersionUID = 1382314701594691684L;
private final String TAG = getClass().getName();
private final String NO_FILE_SELECTED = "No File selected";
| private FilesAdapter filesAdapter; |
rust-keylock/rust-keylock-android | java/src/main/java/org/astonbitecode/rustkeylock/api/stubs/JavaMenu.java | // Path: java/src/main/java/org/astonbitecode/rustkeylock/utils/Defs.java
// public class Defs {
// public static final String MENU_TRY_PASS = "TryPass";
// public static final String MENU_CHANGE_PASS = "ChangePass";
// public static final String MENU_MAIN = "Main";
// public static final String MENU_ENTRIES_LIST = "EntriesList";
// public static final String MENU_SHOW_ENTRY = "ShowEntry";
// public static final String MENU_SAVE = "Save";
// public static final String MENU_EXIT = "Exit";
// public static final String MENU_FORCE_EXIT = "ForceExit";
// public static final String MENU_EDIT_ENTRY = "EditEntry";
// public static final String MENU_DELETE_ENTRY = "DeleteEntry";
// public static final String MENU_NEW_ENTRY = "NewEntry";
// public static final String MENU_EXPORT_ENTRIES = "ExportEntries";
// public static final String MENU_IMPORT_ENTRIES = "ImportEntries";
// public static final String MENU_SHOW_CONFIGURATION = "ShowConfiguration";
// public static final String MENU_SET_DB_TOKEN = "SetDbxToken";
// public static final String MENU_CURRENT = "Current";
// public static final String EMPTY_ARG = "null";
// public static final String CHECK_PASSWORDS = "CheckPasswords";
// public static final int BACKROUND_ERROR = Color.argb(255, 246, 147, 100);
// public static final int BACKROUND_NO_ERROR = Color.TRANSPARENT;
// }
| import org.astonbitecode.rustkeylock.utils.Defs;
import java.util.HashMap;
import java.util.Map; | // Copyright 2019 astonbitecode
// This file is part of rust-keylock password manager.
//
// rust-keylock is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rust-keylock is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with rust-keylock. If not, see <http://www.gnu.org/licenses/>.
package org.astonbitecode.rustkeylock.api.stubs;
public class JavaMenu {
public static Map<String, Object> EntriesList(String filter) {
Map<String, Object> inner = new HashMap<>();
inner.put("filter", filter);
Map<String, Object> map = new HashMap<>(); | // Path: java/src/main/java/org/astonbitecode/rustkeylock/utils/Defs.java
// public class Defs {
// public static final String MENU_TRY_PASS = "TryPass";
// public static final String MENU_CHANGE_PASS = "ChangePass";
// public static final String MENU_MAIN = "Main";
// public static final String MENU_ENTRIES_LIST = "EntriesList";
// public static final String MENU_SHOW_ENTRY = "ShowEntry";
// public static final String MENU_SAVE = "Save";
// public static final String MENU_EXIT = "Exit";
// public static final String MENU_FORCE_EXIT = "ForceExit";
// public static final String MENU_EDIT_ENTRY = "EditEntry";
// public static final String MENU_DELETE_ENTRY = "DeleteEntry";
// public static final String MENU_NEW_ENTRY = "NewEntry";
// public static final String MENU_EXPORT_ENTRIES = "ExportEntries";
// public static final String MENU_IMPORT_ENTRIES = "ImportEntries";
// public static final String MENU_SHOW_CONFIGURATION = "ShowConfiguration";
// public static final String MENU_SET_DB_TOKEN = "SetDbxToken";
// public static final String MENU_CURRENT = "Current";
// public static final String EMPTY_ARG = "null";
// public static final String CHECK_PASSWORDS = "CheckPasswords";
// public static final int BACKROUND_ERROR = Color.argb(255, 246, 147, 100);
// public static final int BACKROUND_NO_ERROR = Color.TRANSPARENT;
// }
// Path: java/src/main/java/org/astonbitecode/rustkeylock/api/stubs/JavaMenu.java
import org.astonbitecode.rustkeylock.utils.Defs;
import java.util.HashMap;
import java.util.Map;
// Copyright 2019 astonbitecode
// This file is part of rust-keylock password manager.
//
// rust-keylock is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rust-keylock is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with rust-keylock. If not, see <http://www.gnu.org/licenses/>.
package org.astonbitecode.rustkeylock.api.stubs;
public class JavaMenu {
public static Map<String, Object> EntriesList(String filter) {
Map<String, Object> inner = new HashMap<>();
inner.put("filter", filter);
Map<String, Object> map = new HashMap<>(); | map.put(Defs.MENU_ENTRIES_LIST, inner); |
rust-keylock/rust-keylock-android | java/src/main/java/org/astonbitecode/rustkeylock/api/stubs/GuiResponse.java | // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/JavaEntry.java
// public class JavaEntry implements Serializable {
//
// public String name;
// public String url;
// public String user;
// public String pass;
// public String desc;
// public JavaEntryMeta meta;
//
// public JavaEntry() {
//
// }
//
// public String getName() {
// return name;
// }
//
// public String getUrl() {
// return url;
// }
//
// public String getUser() {
// return user;
// }
//
// public String getPass() {
// return pass;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public void setPass(String pass) {
// this.pass = pass;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public JavaEntryMeta getMeta() {
// return meta;
// }
//
// public void setMeta(JavaEntryMeta meta) {
// this.meta = meta;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/api/JavaUserOption.java
// public class JavaUserOption implements Serializable {
// private static final long serialVersionUID = 8738491202638465205L;
//
// public String label;
// public String value;
// public String short_label;
//
// public JavaUserOption() {
//
// }
//
// public JavaUserOption(String label, String value, String shortLabel) {
// this.label = label;
// this.value = value;
// this.short_label = shortLabel;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// public String getShort_label() {
// return short_label;
// }
//
// public void setShort_label(String short_label) {
// this.short_label = short_label;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/utils/Defs.java
// public class Defs {
// public static final String MENU_TRY_PASS = "TryPass";
// public static final String MENU_CHANGE_PASS = "ChangePass";
// public static final String MENU_MAIN = "Main";
// public static final String MENU_ENTRIES_LIST = "EntriesList";
// public static final String MENU_SHOW_ENTRY = "ShowEntry";
// public static final String MENU_SAVE = "Save";
// public static final String MENU_EXIT = "Exit";
// public static final String MENU_FORCE_EXIT = "ForceExit";
// public static final String MENU_EDIT_ENTRY = "EditEntry";
// public static final String MENU_DELETE_ENTRY = "DeleteEntry";
// public static final String MENU_NEW_ENTRY = "NewEntry";
// public static final String MENU_EXPORT_ENTRIES = "ExportEntries";
// public static final String MENU_IMPORT_ENTRIES = "ImportEntries";
// public static final String MENU_SHOW_CONFIGURATION = "ShowConfiguration";
// public static final String MENU_SET_DB_TOKEN = "SetDbxToken";
// public static final String MENU_CURRENT = "Current";
// public static final String EMPTY_ARG = "null";
// public static final String CHECK_PASSWORDS = "CheckPasswords";
// public static final int BACKROUND_ERROR = Color.argb(255, 246, 147, 100);
// public static final int BACKROUND_NO_ERROR = Color.TRANSPARENT;
// }
| import org.astonbitecode.rustkeylock.api.JavaEntry;
import org.astonbitecode.rustkeylock.api.JavaUserOption;
import org.astonbitecode.rustkeylock.utils.Defs;
import java.util.HashMap;
import java.util.Map; | inner.put("number", number);
Map<String, Object> map = new HashMap<>();
map.put("ProvidedPassword", inner);
return map;
}
public static Map<String, Object> GoToMenu(Map<String, Object> m) {
Map<String, Object> inner = new HashMap<>();
inner.put("menu", m);
Map<String, Object> map = new HashMap<>();
map.put("GoToMenu", inner);
return map;
}
public static Map<String, Object> GoToMenu(String m) {
Map<String, Object> inner = new HashMap<>();
inner.put("menu", m);
Map<String, Object> map = new HashMap<>();
map.put("GoToMenu", inner);
return map;
}
public static Map<String, Object> DeleteEntry(Integer index) {
Map<String, Object> inner = new HashMap<>();
inner.put("index", index);
Map<String, Object> map = new HashMap<>();
map.put("DeleteEntry", inner);
return map;
}
| // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/JavaEntry.java
// public class JavaEntry implements Serializable {
//
// public String name;
// public String url;
// public String user;
// public String pass;
// public String desc;
// public JavaEntryMeta meta;
//
// public JavaEntry() {
//
// }
//
// public String getName() {
// return name;
// }
//
// public String getUrl() {
// return url;
// }
//
// public String getUser() {
// return user;
// }
//
// public String getPass() {
// return pass;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public void setPass(String pass) {
// this.pass = pass;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public JavaEntryMeta getMeta() {
// return meta;
// }
//
// public void setMeta(JavaEntryMeta meta) {
// this.meta = meta;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/api/JavaUserOption.java
// public class JavaUserOption implements Serializable {
// private static final long serialVersionUID = 8738491202638465205L;
//
// public String label;
// public String value;
// public String short_label;
//
// public JavaUserOption() {
//
// }
//
// public JavaUserOption(String label, String value, String shortLabel) {
// this.label = label;
// this.value = value;
// this.short_label = shortLabel;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// public String getShort_label() {
// return short_label;
// }
//
// public void setShort_label(String short_label) {
// this.short_label = short_label;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/utils/Defs.java
// public class Defs {
// public static final String MENU_TRY_PASS = "TryPass";
// public static final String MENU_CHANGE_PASS = "ChangePass";
// public static final String MENU_MAIN = "Main";
// public static final String MENU_ENTRIES_LIST = "EntriesList";
// public static final String MENU_SHOW_ENTRY = "ShowEntry";
// public static final String MENU_SAVE = "Save";
// public static final String MENU_EXIT = "Exit";
// public static final String MENU_FORCE_EXIT = "ForceExit";
// public static final String MENU_EDIT_ENTRY = "EditEntry";
// public static final String MENU_DELETE_ENTRY = "DeleteEntry";
// public static final String MENU_NEW_ENTRY = "NewEntry";
// public static final String MENU_EXPORT_ENTRIES = "ExportEntries";
// public static final String MENU_IMPORT_ENTRIES = "ImportEntries";
// public static final String MENU_SHOW_CONFIGURATION = "ShowConfiguration";
// public static final String MENU_SET_DB_TOKEN = "SetDbxToken";
// public static final String MENU_CURRENT = "Current";
// public static final String EMPTY_ARG = "null";
// public static final String CHECK_PASSWORDS = "CheckPasswords";
// public static final int BACKROUND_ERROR = Color.argb(255, 246, 147, 100);
// public static final int BACKROUND_NO_ERROR = Color.TRANSPARENT;
// }
// Path: java/src/main/java/org/astonbitecode/rustkeylock/api/stubs/GuiResponse.java
import org.astonbitecode.rustkeylock.api.JavaEntry;
import org.astonbitecode.rustkeylock.api.JavaUserOption;
import org.astonbitecode.rustkeylock.utils.Defs;
import java.util.HashMap;
import java.util.Map;
inner.put("number", number);
Map<String, Object> map = new HashMap<>();
map.put("ProvidedPassword", inner);
return map;
}
public static Map<String, Object> GoToMenu(Map<String, Object> m) {
Map<String, Object> inner = new HashMap<>();
inner.put("menu", m);
Map<String, Object> map = new HashMap<>();
map.put("GoToMenu", inner);
return map;
}
public static Map<String, Object> GoToMenu(String m) {
Map<String, Object> inner = new HashMap<>();
inner.put("menu", m);
Map<String, Object> map = new HashMap<>();
map.put("GoToMenu", inner);
return map;
}
public static Map<String, Object> DeleteEntry(Integer index) {
Map<String, Object> inner = new HashMap<>();
inner.put("index", index);
Map<String, Object> map = new HashMap<>();
map.put("DeleteEntry", inner);
return map;
}
| public static Map<String, Object> ReplaceEntry(JavaEntry entry, Integer index) { |
rust-keylock/rust-keylock-android | java/src/main/java/org/astonbitecode/rustkeylock/api/stubs/GuiResponse.java | // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/JavaEntry.java
// public class JavaEntry implements Serializable {
//
// public String name;
// public String url;
// public String user;
// public String pass;
// public String desc;
// public JavaEntryMeta meta;
//
// public JavaEntry() {
//
// }
//
// public String getName() {
// return name;
// }
//
// public String getUrl() {
// return url;
// }
//
// public String getUser() {
// return user;
// }
//
// public String getPass() {
// return pass;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public void setPass(String pass) {
// this.pass = pass;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public JavaEntryMeta getMeta() {
// return meta;
// }
//
// public void setMeta(JavaEntryMeta meta) {
// this.meta = meta;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/api/JavaUserOption.java
// public class JavaUserOption implements Serializable {
// private static final long serialVersionUID = 8738491202638465205L;
//
// public String label;
// public String value;
// public String short_label;
//
// public JavaUserOption() {
//
// }
//
// public JavaUserOption(String label, String value, String shortLabel) {
// this.label = label;
// this.value = value;
// this.short_label = shortLabel;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// public String getShort_label() {
// return short_label;
// }
//
// public void setShort_label(String short_label) {
// this.short_label = short_label;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/utils/Defs.java
// public class Defs {
// public static final String MENU_TRY_PASS = "TryPass";
// public static final String MENU_CHANGE_PASS = "ChangePass";
// public static final String MENU_MAIN = "Main";
// public static final String MENU_ENTRIES_LIST = "EntriesList";
// public static final String MENU_SHOW_ENTRY = "ShowEntry";
// public static final String MENU_SAVE = "Save";
// public static final String MENU_EXIT = "Exit";
// public static final String MENU_FORCE_EXIT = "ForceExit";
// public static final String MENU_EDIT_ENTRY = "EditEntry";
// public static final String MENU_DELETE_ENTRY = "DeleteEntry";
// public static final String MENU_NEW_ENTRY = "NewEntry";
// public static final String MENU_EXPORT_ENTRIES = "ExportEntries";
// public static final String MENU_IMPORT_ENTRIES = "ImportEntries";
// public static final String MENU_SHOW_CONFIGURATION = "ShowConfiguration";
// public static final String MENU_SET_DB_TOKEN = "SetDbxToken";
// public static final String MENU_CURRENT = "Current";
// public static final String EMPTY_ARG = "null";
// public static final String CHECK_PASSWORDS = "CheckPasswords";
// public static final int BACKROUND_ERROR = Color.argb(255, 246, 147, 100);
// public static final int BACKROUND_NO_ERROR = Color.TRANSPARENT;
// }
| import org.astonbitecode.rustkeylock.api.JavaEntry;
import org.astonbitecode.rustkeylock.api.JavaUserOption;
import org.astonbitecode.rustkeylock.utils.Defs;
import java.util.HashMap;
import java.util.Map; | Map<String, Object> map = new HashMap<>();
map.put("ReplaceEntry", inner);
return map;
}
public static Map<String, Object> GeneratePassphrase(JavaEntry entry, Integer index) {
Map<String, Object> inner = new HashMap<>();
inner.put("entry", entry);
inner.put("index", index);
Map<String, Object> map = new HashMap<>();
map.put("GeneratePassphrase", inner);
return map;
}
public static Map<String, Object> AddEntry(JavaEntry entry) {
Map<String, Object> inner = new HashMap<>();
inner.put("entry", entry);
Map<String, Object> map = new HashMap<>();
map.put("AddEntry", inner);
return map;
}
public static Map<String, Object> SetConfiguration(java.util.List<String> strings) {
Map<String, Object> inner = new HashMap<>();
inner.put("strings", strings);
Map<String, Object> map = new HashMap<>();
map.put("SetConfiguration", inner);
return map;
}
| // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/JavaEntry.java
// public class JavaEntry implements Serializable {
//
// public String name;
// public String url;
// public String user;
// public String pass;
// public String desc;
// public JavaEntryMeta meta;
//
// public JavaEntry() {
//
// }
//
// public String getName() {
// return name;
// }
//
// public String getUrl() {
// return url;
// }
//
// public String getUser() {
// return user;
// }
//
// public String getPass() {
// return pass;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public void setPass(String pass) {
// this.pass = pass;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public JavaEntryMeta getMeta() {
// return meta;
// }
//
// public void setMeta(JavaEntryMeta meta) {
// this.meta = meta;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/api/JavaUserOption.java
// public class JavaUserOption implements Serializable {
// private static final long serialVersionUID = 8738491202638465205L;
//
// public String label;
// public String value;
// public String short_label;
//
// public JavaUserOption() {
//
// }
//
// public JavaUserOption(String label, String value, String shortLabel) {
// this.label = label;
// this.value = value;
// this.short_label = shortLabel;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// public String getShort_label() {
// return short_label;
// }
//
// public void setShort_label(String short_label) {
// this.short_label = short_label;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/utils/Defs.java
// public class Defs {
// public static final String MENU_TRY_PASS = "TryPass";
// public static final String MENU_CHANGE_PASS = "ChangePass";
// public static final String MENU_MAIN = "Main";
// public static final String MENU_ENTRIES_LIST = "EntriesList";
// public static final String MENU_SHOW_ENTRY = "ShowEntry";
// public static final String MENU_SAVE = "Save";
// public static final String MENU_EXIT = "Exit";
// public static final String MENU_FORCE_EXIT = "ForceExit";
// public static final String MENU_EDIT_ENTRY = "EditEntry";
// public static final String MENU_DELETE_ENTRY = "DeleteEntry";
// public static final String MENU_NEW_ENTRY = "NewEntry";
// public static final String MENU_EXPORT_ENTRIES = "ExportEntries";
// public static final String MENU_IMPORT_ENTRIES = "ImportEntries";
// public static final String MENU_SHOW_CONFIGURATION = "ShowConfiguration";
// public static final String MENU_SET_DB_TOKEN = "SetDbxToken";
// public static final String MENU_CURRENT = "Current";
// public static final String EMPTY_ARG = "null";
// public static final String CHECK_PASSWORDS = "CheckPasswords";
// public static final int BACKROUND_ERROR = Color.argb(255, 246, 147, 100);
// public static final int BACKROUND_NO_ERROR = Color.TRANSPARENT;
// }
// Path: java/src/main/java/org/astonbitecode/rustkeylock/api/stubs/GuiResponse.java
import org.astonbitecode.rustkeylock.api.JavaEntry;
import org.astonbitecode.rustkeylock.api.JavaUserOption;
import org.astonbitecode.rustkeylock.utils.Defs;
import java.util.HashMap;
import java.util.Map;
Map<String, Object> map = new HashMap<>();
map.put("ReplaceEntry", inner);
return map;
}
public static Map<String, Object> GeneratePassphrase(JavaEntry entry, Integer index) {
Map<String, Object> inner = new HashMap<>();
inner.put("entry", entry);
inner.put("index", index);
Map<String, Object> map = new HashMap<>();
map.put("GeneratePassphrase", inner);
return map;
}
public static Map<String, Object> AddEntry(JavaEntry entry) {
Map<String, Object> inner = new HashMap<>();
inner.put("entry", entry);
Map<String, Object> map = new HashMap<>();
map.put("AddEntry", inner);
return map;
}
public static Map<String, Object> SetConfiguration(java.util.List<String> strings) {
Map<String, Object> inner = new HashMap<>();
inner.put("strings", strings);
Map<String, Object> map = new HashMap<>();
map.put("SetConfiguration", inner);
return map;
}
| public static Map<String, Object> UserOptionSelected(JavaUserOption userOption) { |
rust-keylock/rust-keylock-android | java/src/main/java/org/astonbitecode/rustkeylock/api/stubs/GuiResponse.java | // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/JavaEntry.java
// public class JavaEntry implements Serializable {
//
// public String name;
// public String url;
// public String user;
// public String pass;
// public String desc;
// public JavaEntryMeta meta;
//
// public JavaEntry() {
//
// }
//
// public String getName() {
// return name;
// }
//
// public String getUrl() {
// return url;
// }
//
// public String getUser() {
// return user;
// }
//
// public String getPass() {
// return pass;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public void setPass(String pass) {
// this.pass = pass;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public JavaEntryMeta getMeta() {
// return meta;
// }
//
// public void setMeta(JavaEntryMeta meta) {
// this.meta = meta;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/api/JavaUserOption.java
// public class JavaUserOption implements Serializable {
// private static final long serialVersionUID = 8738491202638465205L;
//
// public String label;
// public String value;
// public String short_label;
//
// public JavaUserOption() {
//
// }
//
// public JavaUserOption(String label, String value, String shortLabel) {
// this.label = label;
// this.value = value;
// this.short_label = shortLabel;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// public String getShort_label() {
// return short_label;
// }
//
// public void setShort_label(String short_label) {
// this.short_label = short_label;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/utils/Defs.java
// public class Defs {
// public static final String MENU_TRY_PASS = "TryPass";
// public static final String MENU_CHANGE_PASS = "ChangePass";
// public static final String MENU_MAIN = "Main";
// public static final String MENU_ENTRIES_LIST = "EntriesList";
// public static final String MENU_SHOW_ENTRY = "ShowEntry";
// public static final String MENU_SAVE = "Save";
// public static final String MENU_EXIT = "Exit";
// public static final String MENU_FORCE_EXIT = "ForceExit";
// public static final String MENU_EDIT_ENTRY = "EditEntry";
// public static final String MENU_DELETE_ENTRY = "DeleteEntry";
// public static final String MENU_NEW_ENTRY = "NewEntry";
// public static final String MENU_EXPORT_ENTRIES = "ExportEntries";
// public static final String MENU_IMPORT_ENTRIES = "ImportEntries";
// public static final String MENU_SHOW_CONFIGURATION = "ShowConfiguration";
// public static final String MENU_SET_DB_TOKEN = "SetDbxToken";
// public static final String MENU_CURRENT = "Current";
// public static final String EMPTY_ARG = "null";
// public static final String CHECK_PASSWORDS = "CheckPasswords";
// public static final int BACKROUND_ERROR = Color.argb(255, 246, 147, 100);
// public static final int BACKROUND_NO_ERROR = Color.TRANSPARENT;
// }
| import org.astonbitecode.rustkeylock.api.JavaEntry;
import org.astonbitecode.rustkeylock.api.JavaUserOption;
import org.astonbitecode.rustkeylock.utils.Defs;
import java.util.HashMap;
import java.util.Map; | }
public static Map<String, Object> UserOptionSelected(JavaUserOption userOption) {
Map<String, Object> inner = new HashMap<>();
inner.put("user_option", userOption);
Map<String, Object> map = new HashMap<>();
map.put("UserOptionSelected", inner);
return map;
}
public static Map<String, Object> ExportImport(String path, Integer mode, String password, Integer number) {
Map<String, Object> inner = new HashMap<>();
inner.put("path", path);
inner.put("mode", mode);
inner.put("password", password);
inner.put("number", number);
Map<String, Object> map = new HashMap<>();
map.put("ExportImport", inner);
return map;
}
public static Map<String, Object> Copy(String data) {
Map<String, Object> inner = new HashMap<>();
inner.put("data", data);
Map<String, Object> map = new HashMap<>();
map.put("Copy", inner);
return map;
}
public static String CheckPasswords() { | // Path: java/src/main/java/org/astonbitecode/rustkeylock/api/JavaEntry.java
// public class JavaEntry implements Serializable {
//
// public String name;
// public String url;
// public String user;
// public String pass;
// public String desc;
// public JavaEntryMeta meta;
//
// public JavaEntry() {
//
// }
//
// public String getName() {
// return name;
// }
//
// public String getUrl() {
// return url;
// }
//
// public String getUser() {
// return user;
// }
//
// public String getPass() {
// return pass;
// }
//
// public String getDesc() {
// return desc;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public void setUser(String user) {
// this.user = user;
// }
//
// public void setPass(String pass) {
// this.pass = pass;
// }
//
// public void setDesc(String desc) {
// this.desc = desc;
// }
//
// public JavaEntryMeta getMeta() {
// return meta;
// }
//
// public void setMeta(JavaEntryMeta meta) {
// this.meta = meta;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/api/JavaUserOption.java
// public class JavaUserOption implements Serializable {
// private static final long serialVersionUID = 8738491202638465205L;
//
// public String label;
// public String value;
// public String short_label;
//
// public JavaUserOption() {
//
// }
//
// public JavaUserOption(String label, String value, String shortLabel) {
// this.label = label;
// this.value = value;
// this.short_label = shortLabel;
// }
//
// public String getLabel() {
// return label;
// }
//
// public void setLabel(String label) {
// this.label = label;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// public String getShort_label() {
// return short_label;
// }
//
// public void setShort_label(String short_label) {
// this.short_label = short_label;
// }
// }
//
// Path: java/src/main/java/org/astonbitecode/rustkeylock/utils/Defs.java
// public class Defs {
// public static final String MENU_TRY_PASS = "TryPass";
// public static final String MENU_CHANGE_PASS = "ChangePass";
// public static final String MENU_MAIN = "Main";
// public static final String MENU_ENTRIES_LIST = "EntriesList";
// public static final String MENU_SHOW_ENTRY = "ShowEntry";
// public static final String MENU_SAVE = "Save";
// public static final String MENU_EXIT = "Exit";
// public static final String MENU_FORCE_EXIT = "ForceExit";
// public static final String MENU_EDIT_ENTRY = "EditEntry";
// public static final String MENU_DELETE_ENTRY = "DeleteEntry";
// public static final String MENU_NEW_ENTRY = "NewEntry";
// public static final String MENU_EXPORT_ENTRIES = "ExportEntries";
// public static final String MENU_IMPORT_ENTRIES = "ImportEntries";
// public static final String MENU_SHOW_CONFIGURATION = "ShowConfiguration";
// public static final String MENU_SET_DB_TOKEN = "SetDbxToken";
// public static final String MENU_CURRENT = "Current";
// public static final String EMPTY_ARG = "null";
// public static final String CHECK_PASSWORDS = "CheckPasswords";
// public static final int BACKROUND_ERROR = Color.argb(255, 246, 147, 100);
// public static final int BACKROUND_NO_ERROR = Color.TRANSPARENT;
// }
// Path: java/src/main/java/org/astonbitecode/rustkeylock/api/stubs/GuiResponse.java
import org.astonbitecode.rustkeylock.api.JavaEntry;
import org.astonbitecode.rustkeylock.api.JavaUserOption;
import org.astonbitecode.rustkeylock.utils.Defs;
import java.util.HashMap;
import java.util.Map;
}
public static Map<String, Object> UserOptionSelected(JavaUserOption userOption) {
Map<String, Object> inner = new HashMap<>();
inner.put("user_option", userOption);
Map<String, Object> map = new HashMap<>();
map.put("UserOptionSelected", inner);
return map;
}
public static Map<String, Object> ExportImport(String path, Integer mode, String password, Integer number) {
Map<String, Object> inner = new HashMap<>();
inner.put("path", path);
inner.put("mode", mode);
inner.put("password", password);
inner.put("number", number);
Map<String, Object> map = new HashMap<>();
map.put("ExportImport", inner);
return map;
}
public static Map<String, Object> Copy(String data) {
Map<String, Object> inner = new HashMap<>();
inner.put("data", data);
Map<String, Object> map = new HashMap<>();
map.put("Copy", inner);
return map;
}
public static String CheckPasswords() { | return Defs.CHECK_PASSWORDS; |
JorenSix/TarsosLSH | src/be/tarsos/mih/TarsosMIH.java | // Path: src/be/tarsos/mih/storage/MapDBStorage.java
// public class MapDBStorage implements MIHStorage{
//
// private final DB db;
// private final List<HTreeMap<Integer, long[]>> hashtables;
//
// public MapDBStorage(int numberOfTables,String fileName){
//
// hashtables = new ArrayList<>();
//
// db = DBMaker.fileDB(fileName).fileMmapEnable().closeOnJvmShutdown().make();
//
// for(int i = 0 ; i < numberOfTables ; i++){
// HTreeMap<Integer, long[]> map = db.hashMap("map_"+i)
// .keySerializer(Serializer.INTEGER)
// .valueSerializer(Serializer.LONG_ARRAY)
// .counterEnable()
// .createOrOpen();
// hashtables.add(map);
// }
// }
//
//
// @Override
// public boolean containsKey(int hashtableIndex, int key) {
// return hashtables.get(hashtableIndex).containsKey(key);
// }
//
//
// @Override
// public long[] put(int hashtableIndex, int key, long[] newList) {
// return hashtables.get(hashtableIndex).put(key,newList);
// }
//
// @Override
// public long[] get(int hashtableIndex, int key) {
// return hashtables.get(hashtableIndex).get(key);
// }
//
// @Override
// public int size(int hashtableIndex) {
// return hashtables.get(hashtableIndex).size();
// }
//
// @Override
// public Set<Integer> getKeys(int hashtableIndex) {
// return hashtables.get(hashtableIndex).getKeys();
// }
//
// public void close() {
// db.close();
// }
//
// public void commit() {
// db.commit();
// }
// }
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.BitSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import be.tarsos.mih.storage.MapDBStorage; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.mih;
public class TarsosMIH {
public static void main(String[] args) throws IOException {
| // Path: src/be/tarsos/mih/storage/MapDBStorage.java
// public class MapDBStorage implements MIHStorage{
//
// private final DB db;
// private final List<HTreeMap<Integer, long[]>> hashtables;
//
// public MapDBStorage(int numberOfTables,String fileName){
//
// hashtables = new ArrayList<>();
//
// db = DBMaker.fileDB(fileName).fileMmapEnable().closeOnJvmShutdown().make();
//
// for(int i = 0 ; i < numberOfTables ; i++){
// HTreeMap<Integer, long[]> map = db.hashMap("map_"+i)
// .keySerializer(Serializer.INTEGER)
// .valueSerializer(Serializer.LONG_ARRAY)
// .counterEnable()
// .createOrOpen();
// hashtables.add(map);
// }
// }
//
//
// @Override
// public boolean containsKey(int hashtableIndex, int key) {
// return hashtables.get(hashtableIndex).containsKey(key);
// }
//
//
// @Override
// public long[] put(int hashtableIndex, int key, long[] newList) {
// return hashtables.get(hashtableIndex).put(key,newList);
// }
//
// @Override
// public long[] get(int hashtableIndex, int key) {
// return hashtables.get(hashtableIndex).get(key);
// }
//
// @Override
// public int size(int hashtableIndex) {
// return hashtables.get(hashtableIndex).size();
// }
//
// @Override
// public Set<Integer> getKeys(int hashtableIndex) {
// return hashtables.get(hashtableIndex).getKeys();
// }
//
// public void close() {
// db.close();
// }
//
// public void commit() {
// db.commit();
// }
// }
// Path: src/be/tarsos/mih/TarsosMIH.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.BitSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import be.tarsos.mih.storage.MapDBStorage;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.mih;
public class TarsosMIH {
public static void main(String[] args) throws IOException {
| MultiIndexHasher mih = new MultiIndexHasher(64, 8, 4, new MapDBStorage(4,"test.db")); |
JorenSix/TarsosLSH | src/be/tarsos/lsh/families/CityBlockHash.java | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
| import be.tarsos.lsh.Vector;
import java.util.Arrays;
import java.util.Random; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.families;
public class CityBlockHash implements HashFunction {
/**
*
*/
private static final long serialVersionUID = -635398900309516287L;
private int w; | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
// Path: src/be/tarsos/lsh/families/CityBlockHash.java
import be.tarsos.lsh.Vector;
import java.util.Arrays;
import java.util.Random;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.families;
public class CityBlockHash implements HashFunction {
/**
*
*/
private static final long serialVersionUID = -635398900309516287L;
private int w; | private Vector randomPartition; |
JorenSix/TarsosLSH | src/be/tarsos/lsh/families/CosineDistance.java | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
| import be.tarsos.lsh.Vector; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
/*
* _______ __ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six at
* The School of Arts,
* University College Ghent,
* Hoogpoort 64, 9000 Ghent - Belgium
*
* -----------------------------------------------------------
*
* Info : http://tarsos.0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://tarsos.0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.families;
public class CosineDistance implements DistanceMeasure {
@Override | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
// Path: src/be/tarsos/lsh/families/CosineDistance.java
import be.tarsos.lsh.Vector;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
/*
* _______ __ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six at
* The School of Arts,
* University College Ghent,
* Hoogpoort 64, 9000 Ghent - Belgium
*
* -----------------------------------------------------------
*
* Info : http://tarsos.0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://tarsos.0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.families;
public class CosineDistance implements DistanceMeasure {
@Override | public double distance(Vector one, Vector other) { |
JorenSix/TarsosLSH | src/be/tarsos/lsh/families/CosineHash.java | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
| import be.tarsos.lsh.Vector;
import java.util.Random; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.families;
public class CosineHash implements HashFunction{
/**
*
*/
private static final long serialVersionUID = 778951747630668248L; | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
// Path: src/be/tarsos/lsh/families/CosineHash.java
import be.tarsos.lsh.Vector;
import java.util.Random;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.families;
public class CosineHash implements HashFunction{
/**
*
*/
private static final long serialVersionUID = 778951747630668248L; | final Vector randomProjection; |
JorenSix/TarsosLSH | src/be/tarsos/lsh/families/EuclideanHash.java | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
| import be.tarsos.lsh.Vector;
import java.util.Random; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.families;
public class EuclideanHash implements HashFunction{
/**
*
*/
private static final long serialVersionUID = -3784656820380622717L; | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
// Path: src/be/tarsos/lsh/families/EuclideanHash.java
import be.tarsos.lsh.Vector;
import java.util.Random;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.families;
public class EuclideanHash implements HashFunction{
/**
*
*/
private static final long serialVersionUID = -3784656820380622717L; | private Vector randomProjection; |
JorenSix/TarsosLSH | test/be/tarsos/lsh/test/VectorTests.java | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
| import org.junit.Test;
import be.tarsos.lsh.Vector;
import static org.junit.Assert.*; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.test;
public class VectorTests {
@Test
public void testDotProduct(){ | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
// Path: test/be/tarsos/lsh/test/VectorTests.java
import org.junit.Test;
import be.tarsos.lsh.Vector;
import static org.junit.Assert.*;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.test;
public class VectorTests {
@Test
public void testDotProduct(){ | Vector one = new Vector(3); |
JorenSix/TarsosLSH | src/be/tarsos/lsh/HashTable.java | // Path: src/be/tarsos/lsh/families/HashFamily.java
// public interface HashFamily extends Serializable {
//
// /**
// * Create a new hash function of this family.
// *
// * @return A new hash function of this family.
// */
// HashFunction createHashFunction();
//
// /**
// * Combine a number of hashes generated by members of this hash function
// * family.
// *
// * @param hashes
// * The raw hashes that need to be combined.
// * @return An integer representing a combination of the hashes. Normally,
// * unique hash values result in a unique, deterministic combined
// * hash value.
// */
// String combine(int[] hashes);
//
// /**
// * Create a new distance measure.
// *
// * @return The distance measure used to sort neighbourhood candidates.
// */
// DistanceMeasure createDistanceMeasure();
//
// }
//
// Path: src/be/tarsos/lsh/families/HashFunction.java
// public interface HashFunction extends Serializable {
// /**
// * Hashes a vector of arbitrary dimensions to an integer. The hash function
// * needs to be locality sensitive to work in the locality sensitive hash (LSH)
// * scheme. Meaning that vectors that are 'close' according to some metric
// * have a high probability to end up with the same hash.
// *
// * @param vector
// * The vector to hash. Can have any number of dimensions.
// * @return A locality sensitive hash (LSH). Vectors that are 'close'
// * according to some metric have a high probability to end up with
// * the same hash.
// */
// int hash(Vector vector);
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import be.tarsos.lsh.families.HashFamily;
import be.tarsos.lsh.families.HashFunction; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh;
/**
* An index contains one or more locality sensitive hash tables. These hash
* tables contain the mapping between a combination of a number of hashes
* (encoded using an integer) and a list of possible nearest neighbours.
*
* @author Joren Six
*/
class HashTable implements Serializable {
private static final long serialVersionUID = -5410017645908038641L;
/**
* Contains the mapping between a combination of a number of hashes (encoded
* using an integer) and a list of possible nearest neighbours
*/
private HashMap<String,List<Vector>> hashTable; | // Path: src/be/tarsos/lsh/families/HashFamily.java
// public interface HashFamily extends Serializable {
//
// /**
// * Create a new hash function of this family.
// *
// * @return A new hash function of this family.
// */
// HashFunction createHashFunction();
//
// /**
// * Combine a number of hashes generated by members of this hash function
// * family.
// *
// * @param hashes
// * The raw hashes that need to be combined.
// * @return An integer representing a combination of the hashes. Normally,
// * unique hash values result in a unique, deterministic combined
// * hash value.
// */
// String combine(int[] hashes);
//
// /**
// * Create a new distance measure.
// *
// * @return The distance measure used to sort neighbourhood candidates.
// */
// DistanceMeasure createDistanceMeasure();
//
// }
//
// Path: src/be/tarsos/lsh/families/HashFunction.java
// public interface HashFunction extends Serializable {
// /**
// * Hashes a vector of arbitrary dimensions to an integer. The hash function
// * needs to be locality sensitive to work in the locality sensitive hash (LSH)
// * scheme. Meaning that vectors that are 'close' according to some metric
// * have a high probability to end up with the same hash.
// *
// * @param vector
// * The vector to hash. Can have any number of dimensions.
// * @return A locality sensitive hash (LSH). Vectors that are 'close'
// * according to some metric have a high probability to end up with
// * the same hash.
// */
// int hash(Vector vector);
// }
// Path: src/be/tarsos/lsh/HashTable.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import be.tarsos.lsh.families.HashFamily;
import be.tarsos.lsh.families.HashFunction;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh;
/**
* An index contains one or more locality sensitive hash tables. These hash
* tables contain the mapping between a combination of a number of hashes
* (encoded using an integer) and a list of possible nearest neighbours.
*
* @author Joren Six
*/
class HashTable implements Serializable {
private static final long serialVersionUID = -5410017645908038641L;
/**
* Contains the mapping between a combination of a number of hashes (encoded
* using an integer) and a list of possible nearest neighbours
*/
private HashMap<String,List<Vector>> hashTable; | private HashFunction[] hashFunctions; |
JorenSix/TarsosLSH | src/be/tarsos/lsh/HashTable.java | // Path: src/be/tarsos/lsh/families/HashFamily.java
// public interface HashFamily extends Serializable {
//
// /**
// * Create a new hash function of this family.
// *
// * @return A new hash function of this family.
// */
// HashFunction createHashFunction();
//
// /**
// * Combine a number of hashes generated by members of this hash function
// * family.
// *
// * @param hashes
// * The raw hashes that need to be combined.
// * @return An integer representing a combination of the hashes. Normally,
// * unique hash values result in a unique, deterministic combined
// * hash value.
// */
// String combine(int[] hashes);
//
// /**
// * Create a new distance measure.
// *
// * @return The distance measure used to sort neighbourhood candidates.
// */
// DistanceMeasure createDistanceMeasure();
//
// }
//
// Path: src/be/tarsos/lsh/families/HashFunction.java
// public interface HashFunction extends Serializable {
// /**
// * Hashes a vector of arbitrary dimensions to an integer. The hash function
// * needs to be locality sensitive to work in the locality sensitive hash (LSH)
// * scheme. Meaning that vectors that are 'close' according to some metric
// * have a high probability to end up with the same hash.
// *
// * @param vector
// * The vector to hash. Can have any number of dimensions.
// * @return A locality sensitive hash (LSH). Vectors that are 'close'
// * according to some metric have a high probability to end up with
// * the same hash.
// */
// int hash(Vector vector);
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import be.tarsos.lsh.families.HashFamily;
import be.tarsos.lsh.families.HashFunction; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh;
/**
* An index contains one or more locality sensitive hash tables. These hash
* tables contain the mapping between a combination of a number of hashes
* (encoded using an integer) and a list of possible nearest neighbours.
*
* @author Joren Six
*/
class HashTable implements Serializable {
private static final long serialVersionUID = -5410017645908038641L;
/**
* Contains the mapping between a combination of a number of hashes (encoded
* using an integer) and a list of possible nearest neighbours
*/
private HashMap<String,List<Vector>> hashTable;
private HashFunction[] hashFunctions; | // Path: src/be/tarsos/lsh/families/HashFamily.java
// public interface HashFamily extends Serializable {
//
// /**
// * Create a new hash function of this family.
// *
// * @return A new hash function of this family.
// */
// HashFunction createHashFunction();
//
// /**
// * Combine a number of hashes generated by members of this hash function
// * family.
// *
// * @param hashes
// * The raw hashes that need to be combined.
// * @return An integer representing a combination of the hashes. Normally,
// * unique hash values result in a unique, deterministic combined
// * hash value.
// */
// String combine(int[] hashes);
//
// /**
// * Create a new distance measure.
// *
// * @return The distance measure used to sort neighbourhood candidates.
// */
// DistanceMeasure createDistanceMeasure();
//
// }
//
// Path: src/be/tarsos/lsh/families/HashFunction.java
// public interface HashFunction extends Serializable {
// /**
// * Hashes a vector of arbitrary dimensions to an integer. The hash function
// * needs to be locality sensitive to work in the locality sensitive hash (LSH)
// * scheme. Meaning that vectors that are 'close' according to some metric
// * have a high probability to end up with the same hash.
// *
// * @param vector
// * The vector to hash. Can have any number of dimensions.
// * @return A locality sensitive hash (LSH). Vectors that are 'close'
// * according to some metric have a high probability to end up with
// * the same hash.
// */
// int hash(Vector vector);
// }
// Path: src/be/tarsos/lsh/HashTable.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import be.tarsos.lsh.families.HashFamily;
import be.tarsos.lsh.families.HashFunction;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh;
/**
* An index contains one or more locality sensitive hash tables. These hash
* tables contain the mapping between a combination of a number of hashes
* (encoded using an integer) and a list of possible nearest neighbours.
*
* @author Joren Six
*/
class HashTable implements Serializable {
private static final long serialVersionUID = -5410017645908038641L;
/**
* Contains the mapping between a combination of a number of hashes (encoded
* using an integer) and a list of possible nearest neighbours
*/
private HashMap<String,List<Vector>> hashTable;
private HashFunction[] hashFunctions; | private HashFamily family; |
JorenSix/TarsosLSH | test/be/tarsos/lsh/test/CosineHashFamilyTest.java | // Path: src/be/tarsos/lsh/families/CosineHashFamily.java
// public class CosineHashFamily implements HashFamily {
//
// /**
// *
// */
// private static final long serialVersionUID = 7678152513757669089L;
// private final int dimensions;
//
// public CosineHashFamily(int dimensions) {
// this.dimensions = dimensions;
// }
//
// @Override
// public HashFunction createHashFunction() {
// return new CosineHash(dimensions);
// }
//
// @Override
// public String combine(int[] hashes) {
// //Treat the hashes as a series of bits.
// //They are either zero or one, the index
// //represents the value.
// //int result = 0;
// //factor holds the power of two.
// //int factor = 1;
// //for(int i = 0 ; i < hashes.length ; i++){
// //result += hashes[i] == 0 ? 0 : factor;
// //factor *= 2;
// //}
// //return result;
// return Arrays.toString(hashes);
// }
//
// @Override
// public DistanceMeasure createDistanceMeasure() {
// return new CosineDistance();
// }
// }
| import org.junit.Test;
import be.tarsos.lsh.families.CosineHashFamily;
import static org.junit.Assert.assertEquals; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.test;
public class CosineHashFamilyTest {
@Test
public void testCombination(){ | // Path: src/be/tarsos/lsh/families/CosineHashFamily.java
// public class CosineHashFamily implements HashFamily {
//
// /**
// *
// */
// private static final long serialVersionUID = 7678152513757669089L;
// private final int dimensions;
//
// public CosineHashFamily(int dimensions) {
// this.dimensions = dimensions;
// }
//
// @Override
// public HashFunction createHashFunction() {
// return new CosineHash(dimensions);
// }
//
// @Override
// public String combine(int[] hashes) {
// //Treat the hashes as a series of bits.
// //They are either zero or one, the index
// //represents the value.
// //int result = 0;
// //factor holds the power of two.
// //int factor = 1;
// //for(int i = 0 ; i < hashes.length ; i++){
// //result += hashes[i] == 0 ? 0 : factor;
// //factor *= 2;
// //}
// //return result;
// return Arrays.toString(hashes);
// }
//
// @Override
// public DistanceMeasure createDistanceMeasure() {
// return new CosineDistance();
// }
// }
// Path: test/be/tarsos/lsh/test/CosineHashFamilyTest.java
import org.junit.Test;
import be.tarsos.lsh.families.CosineHashFamily;
import static org.junit.Assert.assertEquals;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.test;
public class CosineHashFamilyTest {
@Test
public void testCombination(){ | CosineHashFamily chf = new CosineHashFamily(4); |
JorenSix/TarsosLSH | test/be/tarsos/lsh/test/CosineDistanceTest.java | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
//
// Path: src/be/tarsos/lsh/families/CosineDistance.java
// public class CosineDistance implements DistanceMeasure {
//
// @Override
// public double distance(Vector one, Vector other) {
// double distance=0;
// double similarity = one.dot(other) / Math.sqrt(one.dot(one) * other.dot(other));
// distance = 1 - similarity;
// return distance;
// }
// }
| import org.junit.Test;
import be.tarsos.lsh.Vector;
import be.tarsos.lsh.families.CosineDistance;
import static org.junit.Assert.*; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.test;
public class CosineDistanceTest {
@Test
public void testDistance(){ | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
//
// Path: src/be/tarsos/lsh/families/CosineDistance.java
// public class CosineDistance implements DistanceMeasure {
//
// @Override
// public double distance(Vector one, Vector other) {
// double distance=0;
// double similarity = one.dot(other) / Math.sqrt(one.dot(one) * other.dot(other));
// distance = 1 - similarity;
// return distance;
// }
// }
// Path: test/be/tarsos/lsh/test/CosineDistanceTest.java
import org.junit.Test;
import be.tarsos.lsh.Vector;
import be.tarsos.lsh.families.CosineDistance;
import static org.junit.Assert.*;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.test;
public class CosineDistanceTest {
@Test
public void testDistance(){ | Vector v = new Vector(3); |
JorenSix/TarsosLSH | test/be/tarsos/lsh/test/CosineDistanceTest.java | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
//
// Path: src/be/tarsos/lsh/families/CosineDistance.java
// public class CosineDistance implements DistanceMeasure {
//
// @Override
// public double distance(Vector one, Vector other) {
// double distance=0;
// double similarity = one.dot(other) / Math.sqrt(one.dot(one) * other.dot(other));
// distance = 1 - similarity;
// return distance;
// }
// }
| import org.junit.Test;
import be.tarsos.lsh.Vector;
import be.tarsos.lsh.families.CosineDistance;
import static org.junit.Assert.*; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.test;
public class CosineDistanceTest {
@Test
public void testDistance(){
Vector v = new Vector(3);
v.set(0, 1);
v.set(1, 2);
v.set(2, 3);
Vector other = new Vector(3);
other.set(0, 3);
other.set(1, 5);
other.set(2, 7);
| // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
//
// Path: src/be/tarsos/lsh/families/CosineDistance.java
// public class CosineDistance implements DistanceMeasure {
//
// @Override
// public double distance(Vector one, Vector other) {
// double distance=0;
// double similarity = one.dot(other) / Math.sqrt(one.dot(one) * other.dot(other));
// distance = 1 - similarity;
// return distance;
// }
// }
// Path: test/be/tarsos/lsh/test/CosineDistanceTest.java
import org.junit.Test;
import be.tarsos.lsh.Vector;
import be.tarsos.lsh.families.CosineDistance;
import static org.junit.Assert.*;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.test;
public class CosineDistanceTest {
@Test
public void testDistance(){
Vector v = new Vector(3);
v.set(0, 1);
v.set(1, 2);
v.set(2, 3);
Vector other = new Vector(3);
other.set(0, 3);
other.set(1, 5);
other.set(2, 7);
| CosineDistance distance = new CosineDistance(); |
JorenSix/TarsosLSH | src/be/tarsos/lsh/families/EuclideanDistance.java | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
| import be.tarsos.lsh.Vector; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.families;
/**
* Calculates the <a
* href="http://en.wikipedia.org/wiki/Euclidean_distance">Euclidean distance</a>
* between two vectors. Sometimes this is also called the L<sub>2</sub>
* distance.
*
* @author Joren Six
*/
public class EuclideanDistance implements DistanceMeasure {
/* (non-Javadoc)
* @see be.hogent.tarsos.lsh.families.DistanceMeasure#distance(be.hogent.tarsos.lsh.Vector, be.hogent.tarsos.lsh.Vector)
*/
@Override | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
// Path: src/be/tarsos/lsh/families/EuclideanDistance.java
import be.tarsos.lsh.Vector;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.families;
/**
* Calculates the <a
* href="http://en.wikipedia.org/wiki/Euclidean_distance">Euclidean distance</a>
* between two vectors. Sometimes this is also called the L<sub>2</sub>
* distance.
*
* @author Joren Six
*/
public class EuclideanDistance implements DistanceMeasure {
/* (non-Javadoc)
* @see be.hogent.tarsos.lsh.families.DistanceMeasure#distance(be.hogent.tarsos.lsh.Vector, be.hogent.tarsos.lsh.Vector)
*/
@Override | public double distance(Vector one, Vector other) { |
JorenSix/TarsosLSH | test/be/tarsos/mih/tests/VectorTest.java | // Path: src/be/tarsos/mih/BitSetWithID.java
// public class BitSetWithID {
//
// /**
// *
// * Bit values are stored in a bit set which is backed by an array of longs.
// */
// private final BitSet bitSet;
//
// /**
// * The identifier to use, 64bits.
// */
// private final long identifier;
//
// /**
// * A representation of this vector used for storage.
// */
// private long[] longRepresentation = null;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param bytes The number of bytes.
// */
// public BitSetWithID(long id, BitSet bitSet) {
// this.bitSet = bitSet;
// this.identifier = id;
// }
//
// /**
// * A copy constructor.
// * @param original The original bit set.
// */
// public BitSetWithID(BitSetWithID original) {
// this.bitSet = (BitSet) original.bitSet.clone();
// this.identifier = original.identifier;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
//
// int actualBits = (int) Math.ceil(bitSet.length() / 64.0) * 64;
// for(int d=0; d < actualBits ; d++) {
// sb.append(bitSet.get(d)? "1" : "0");
// }
// sb.append(";");
// sb.append(String.format("%019d", identifier));
// return sb.toString();
// }
//
// /**
// * @return the number of bits actually in use.
// */
// public int getNumberOfBits() {
// return bitSet.size();
// }
//
// /**
// * Calculates the hamming distance between this and the other.
// * This is not the most efficient implementation: values are copied.
// * @param other the other vector.
// * @return The hamming distance between this and the other.
// */
// public int hammingDistance(BitSetWithID other) {
// //clone the bit set of this object
// BitSet xored = (BitSet) bitSet.clone();
//
// //xor (modify) the bit set
// xored.xor(other.bitSet);
// //return the number of 1's
// return xored.cardinality();
// }
//
// /**
// * Set a bit at the specified index for the underlying bit set.
// * @param bitIndex The index.
// * @param value The value.
// */
// public void set(int bitIndex, boolean value) {
// bitSet.set(bitIndex, value);
// }
//
// /**
// * Get a bit value at the specified index for the underlying bit set.
// * @param bitIndex The index.
// * @return the value of the bit.
// */
// public boolean get(int bitIndex) {
// return bitSet.get(bitIndex);
// }
//
// /**
// * Flip a bit at the specified index for the underlying bit set.
// * @param bitIndex The index.
// */
// public void flip(int bitIndex){
// bitSet.flip(bitIndex);
// }
//
//
// /**
// * @return the underlying bit set. For performance reasons no clone is done, so please do not modify.
// */
// public BitSet getBitSet() {
// return bitSet;
// }
//
// /**
// * @return The identifier
// */
// public long getIdentifier(){
// return identifier;
// }
//
//
// /**
// * For storage map this vector to an array of longs.
// * @return a long[] representation of this vector
// */
// public long[] toLongArray(){
// if(longRepresentation == null){
// long[] data = bitSet.toLongArray();
//
// longRepresentation = new long[1 + data.length];
// longRepresentation[0] = identifier;
// for(int i = 0 ; i < data.length ;i++){
// longRepresentation[i+1] = data[i];
// }
// }
// return longRepresentation;
// }
//
// /**
// * Creates a bit set with an identifier from a long array representation.
// * @param source The source array.
// * @return A bit set with an identifier and values according to the long array values.
// */
// public static BitSetWithID fromLongArray(long[] source){
// long[] bits = new long[source.length-1];
// for(int i = 0 ; i < bits.length ; i++){
// bits[i] = source[i+1];
// }
// return new BitSetWithID(source[0],BitSet.valueOf(bits));
// }
// }
| import static org.junit.Assert.assertEquals;
import java.util.BitSet;
import java.util.Random;
import org.junit.Test;
import be.tarsos.mih.BitSetWithID; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.mih.tests;
public class VectorTest {
@Test
public void testVectorToLongEncoding(){
Random r = new Random();
long[] bits = {r.nextLong(),r.nextLong()};
BitSet originalBitSet = BitSet.valueOf(bits);
int identifier = r.nextInt(); | // Path: src/be/tarsos/mih/BitSetWithID.java
// public class BitSetWithID {
//
// /**
// *
// * Bit values are stored in a bit set which is backed by an array of longs.
// */
// private final BitSet bitSet;
//
// /**
// * The identifier to use, 64bits.
// */
// private final long identifier;
//
// /**
// * A representation of this vector used for storage.
// */
// private long[] longRepresentation = null;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param bytes The number of bytes.
// */
// public BitSetWithID(long id, BitSet bitSet) {
// this.bitSet = bitSet;
// this.identifier = id;
// }
//
// /**
// * A copy constructor.
// * @param original The original bit set.
// */
// public BitSetWithID(BitSetWithID original) {
// this.bitSet = (BitSet) original.bitSet.clone();
// this.identifier = original.identifier;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
//
// int actualBits = (int) Math.ceil(bitSet.length() / 64.0) * 64;
// for(int d=0; d < actualBits ; d++) {
// sb.append(bitSet.get(d)? "1" : "0");
// }
// sb.append(";");
// sb.append(String.format("%019d", identifier));
// return sb.toString();
// }
//
// /**
// * @return the number of bits actually in use.
// */
// public int getNumberOfBits() {
// return bitSet.size();
// }
//
// /**
// * Calculates the hamming distance between this and the other.
// * This is not the most efficient implementation: values are copied.
// * @param other the other vector.
// * @return The hamming distance between this and the other.
// */
// public int hammingDistance(BitSetWithID other) {
// //clone the bit set of this object
// BitSet xored = (BitSet) bitSet.clone();
//
// //xor (modify) the bit set
// xored.xor(other.bitSet);
// //return the number of 1's
// return xored.cardinality();
// }
//
// /**
// * Set a bit at the specified index for the underlying bit set.
// * @param bitIndex The index.
// * @param value The value.
// */
// public void set(int bitIndex, boolean value) {
// bitSet.set(bitIndex, value);
// }
//
// /**
// * Get a bit value at the specified index for the underlying bit set.
// * @param bitIndex The index.
// * @return the value of the bit.
// */
// public boolean get(int bitIndex) {
// return bitSet.get(bitIndex);
// }
//
// /**
// * Flip a bit at the specified index for the underlying bit set.
// * @param bitIndex The index.
// */
// public void flip(int bitIndex){
// bitSet.flip(bitIndex);
// }
//
//
// /**
// * @return the underlying bit set. For performance reasons no clone is done, so please do not modify.
// */
// public BitSet getBitSet() {
// return bitSet;
// }
//
// /**
// * @return The identifier
// */
// public long getIdentifier(){
// return identifier;
// }
//
//
// /**
// * For storage map this vector to an array of longs.
// * @return a long[] representation of this vector
// */
// public long[] toLongArray(){
// if(longRepresentation == null){
// long[] data = bitSet.toLongArray();
//
// longRepresentation = new long[1 + data.length];
// longRepresentation[0] = identifier;
// for(int i = 0 ; i < data.length ;i++){
// longRepresentation[i+1] = data[i];
// }
// }
// return longRepresentation;
// }
//
// /**
// * Creates a bit set with an identifier from a long array representation.
// * @param source The source array.
// * @return A bit set with an identifier and values according to the long array values.
// */
// public static BitSetWithID fromLongArray(long[] source){
// long[] bits = new long[source.length-1];
// for(int i = 0 ; i < bits.length ; i++){
// bits[i] = source[i+1];
// }
// return new BitSetWithID(source[0],BitSet.valueOf(bits));
// }
// }
// Path: test/be/tarsos/mih/tests/VectorTest.java
import static org.junit.Assert.assertEquals;
import java.util.BitSet;
import java.util.Random;
import org.junit.Test;
import be.tarsos.mih.BitSetWithID;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.mih.tests;
public class VectorTest {
@Test
public void testVectorToLongEncoding(){
Random r = new Random();
long[] bits = {r.nextLong(),r.nextLong()};
BitSet originalBitSet = BitSet.valueOf(bits);
int identifier = r.nextInt(); | BitSetWithID originalVector = new BitSetWithID(identifier,originalBitSet); |
JorenSix/TarsosLSH | src/be/tarsos/mih/MultiIndexHasher.java | // Path: src/be/tarsos/mih/storage/MIHStorage.java
// public interface MIHStorage {
//
// boolean containsKey(int hashtableIndex, int key);
//
// long[] put(int hashtableIndex, int key, long[] newList);
//
// long[] get(int hashtableIndex, int key);
//
// int size(int hashtableIndex);
//
// Set<Integer> getKeys(int hashtableIndex);
//
// void close();
// }
| import be.tarsos.mih.storage.MIHStorage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.mih;
/**
* Implements a multi-index hash algorithm as
* described in <a href="http://www.cs.toronto.edu/~norouzi/research/papers/multi_index_hashing.pdf">Fast
* Search in Hamming Space with Multi-Index Hashing</a> by Mohammad Norouzi, Ali Punjani, David Fleet - IEEE
* Computer Vision and Pattern Recognition (CVPR) 2012
*
*
* @author Joren Six
*/
public class MultiIndexHasher {
private final int numBits;//B in the paper
private final int hammingSearchRadius;//D
private final int hammingSearchRadiusPerSubstring;//d
private final int numberOfChunks;//m
private final int bitsPerChunk;//b
private static Logger LOG = Logger.getLogger(MultiIndexHasher.class.getName()); | // Path: src/be/tarsos/mih/storage/MIHStorage.java
// public interface MIHStorage {
//
// boolean containsKey(int hashtableIndex, int key);
//
// long[] put(int hashtableIndex, int key, long[] newList);
//
// long[] get(int hashtableIndex, int key);
//
// int size(int hashtableIndex);
//
// Set<Integer> getKeys(int hashtableIndex);
//
// void close();
// }
// Path: src/be/tarsos/mih/MultiIndexHasher.java
import be.tarsos.mih.storage.MIHStorage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.mih;
/**
* Implements a multi-index hash algorithm as
* described in <a href="http://www.cs.toronto.edu/~norouzi/research/papers/multi_index_hashing.pdf">Fast
* Search in Hamming Space with Multi-Index Hashing</a> by Mohammad Norouzi, Ali Punjani, David Fleet - IEEE
* Computer Vision and Pattern Recognition (CVPR) 2012
*
*
* @author Joren Six
*/
public class MultiIndexHasher {
private final int numBits;//B in the paper
private final int hammingSearchRadius;//D
private final int hammingSearchRadiusPerSubstring;//d
private final int numberOfChunks;//m
private final int bitsPerChunk;//b
private static Logger LOG = Logger.getLogger(MultiIndexHasher.class.getName()); | private final MIHStorage storage; |
JorenSix/TarsosLSH | src/be/tarsos/lsh/families/IntersectionDistance.java | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
| import be.tarsos.lsh.Vector; | /*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.families;
/**
* <p>
* Calculates the intersection of one vector with an other vector. Intersection
* is normally between 0 and 1. 1 meaning 100% overlap. To make it a distance
* measure, 1 - intersection is done, so 1 becomes no intersection, 0 total
* overlap.
* </p>
* <p>
* This distance measure has no related hash family.
* </p>
* @author Joren Six
*/
public class IntersectionDistance implements DistanceMeasure {
@Override | // Path: src/be/tarsos/lsh/Vector.java
// public class Vector implements Serializable {
//
// private static final long serialVersionUID = 5169504339456492327L;
//
//
// /**
// * Values are stored here.
// */
// private double[] values;
//
//
// /**
// * An optional key, identifier for the vector.
// */
// private String key;
//
// /**
// * Creates a new vector with the requested number of dimensions.
// * @param dimensions The number of dimensions.
// */
// public Vector(int dimensions) {
// this(null,new double[dimensions]);
// }
//
//
// /**
// * Copy constructor.
// * @param other The other vector.
// */
// public Vector(Vector other){
// //copy the values
// this(other.getKey(),Arrays.copyOf(other.values, other.values.length));
// }
//
// /**
// * Creates a vector with the values and a key
// * @param key The key of the vector.
// * @param values The values of the vector.
// */
// public Vector(String key,double[] values){
// this.values = values;
// this.key = key;
// }
//
// /**
// * Moves the vector slightly, adds a value selected from -radius to +radius to each element.
// * @param radius The radius determines the amount to change the vector.
// */
// public void moveSlightly(double radius){
// Random rand = new Random();
// for (int d = 0; d < getDimensions(); d++) {
// //copy the point but add or subtract a value between -radius and +radius
// double diff = radius + (-radius - radius) * rand.nextDouble();
// double point = get(d) + diff;
// set(d, point);
// }
// }
//
//
//
// /**
// * Set a value at a certain dimension d.
// * @param dimension The dimension, index for the value.
// * @param value The value to set.
// */
// public void set(int dimension, double value) {
// values[dimension] = value;
// }
//
// /**
// * Returns the value at the requested dimension.
// * @param dimension The dimension, index for the value.
// * @return Returns the value at the requested dimension.
// */
// public double get(int dimension) {
// return values[dimension];
// }
//
// /**
// * @return The number of dimensions this vector has.
// */
// public int getDimensions(){
// return values.length;
// }
//
// /**
// * Calculates the dot product, or scalar product, of this vector with the
// * other vector.
// *
// * @param other
// * The other vector, should have the same number of dimensions.
// * @return The dot product of this vector with the other vector.
// * @exception ArrayIndexOutOfBoundsException
// * when the two vectors do not have the same dimensions.
// */
// public double dot(Vector other) {
// double sum = 0.0;
// for(int i=0; i < getDimensions(); i++) {
// sum += values[i] * other.values[i];
// }
// return sum;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getKey() {
// return key;
// }
//
// public String toString(){
// StringBuilder sb= new StringBuilder();
// sb.append("values:[");
// for(int d=0; d < getDimensions() - 1; d++) {
// sb.append(values[d]).append(",");
// }
// sb.append(values[getDimensions()-1]).append("]");
// return sb.toString();
// }
// }
// Path: src/be/tarsos/lsh/families/IntersectionDistance.java
import be.tarsos.lsh.Vector;
/*
* _______ _ ____ _ _
* |__ __| | | / ____| | | |
* | | __ _ _ __ ___ ___ ___| | | (___ | |___| |
* | |/ _` | '__/ __|/ _ \/ __| | \___ \| ___ |
* | | (_| | | \__ \ (_) \__ \ |____ ____) | | | |
* |_|\__,_|_| |___/\___/|___/_____/|_____/|_| |_|
*
* -----------------------------------------------------------
*
* TarsosLSH is developed by Joren Six.
*
* -----------------------------------------------------------
*
* Info : http://0110.be/tag/TarsosLSH
* Github : https://github.com/JorenSix/TarsosLSH
* Releases: http://0110.be/releases/TarsosLSH/
*
*/
package be.tarsos.lsh.families;
/**
* <p>
* Calculates the intersection of one vector with an other vector. Intersection
* is normally between 0 and 1. 1 meaning 100% overlap. To make it a distance
* measure, 1 - intersection is done, so 1 becomes no intersection, 0 total
* overlap.
* </p>
* <p>
* This distance measure has no related hash family.
* </p>
* @author Joren Six
*/
public class IntersectionDistance implements DistanceMeasure {
@Override | public double distance(Vector one, Vector other) { |
SiMolecule/centres | core/src/main/java/com/simolecule/centres/rules/Rules.java | // Path: core/src/main/java/com/simolecule/centres/BaseMol.java
// public abstract class BaseMol<A, B> {
//
// private Fraction[] atomnums;
//
// public static final String CIP_LABEL_KEY = "cip.label";
// public static final String CONF_INDEX = "conf.index";
//
// public abstract Object getBaseImpl();
//
// public abstract int getNumAtoms();
//
// public abstract int getNumBonds();
//
// public abstract A getAtom(int idx);
//
// public abstract int getAtomIdx(A atom);
//
// public Iterable<A> atoms() {
// return new Iterable<A>() {
// @Override
// public Iterator<A> iterator()
// {
// return new Iterator<A>() {
// private int pos = 0;
//
// @Override
// public boolean hasNext()
// {
// return pos < getNumAtoms();
// }
//
// @Override
// public A next()
// {
// return getAtom(pos++);
// }
//
// @Override
// public void remove()
// {
// throw new UnsupportedOperationException();
// }
// };
// }
// };
// }
//
// public abstract B getBond(int idx);
//
// public abstract int getBondIdx(B bond);
//
// public abstract Iterable<B> getBonds(A atom);
//
// public abstract A getOther(B bond, A atom);
//
// public abstract A getBeg(B bond);
//
// public abstract A getEnd(B bond);
//
// public abstract boolean isInRing(B bond);
//
// public abstract int getAtomicNum(A atom);
//
// public Fraction getFractionalAtomicNum(A atom) {
// if (atomnums == null)
// atomnums = Mancude.CalcFracAtomNums(this);
// return atomnums[getAtomIdx(atom)];
// }
//
// public abstract int getNumHydrogens(A atom);
//
// public abstract int getMassNum(A atom);
//
// public abstract int getCharge(A atom);
//
// public abstract int getBondOrder(B bond);
//
// public abstract void setAtomProp(A atom, String key, Object val);
//
// public abstract <V> V getAtomProp(A atom, String key);
//
// public abstract void setBondProp(B bond, String key, Object val);
//
// public abstract <V> V getBondProp(B bond, String key);
//
// public abstract String dumpDigraph(Digraph<A,B> digraph);
//
//
// }
| import java.util.List;
import com.simolecule.centres.BaseMol;
import com.simolecule.centres.Edge;
import java.util.ArrayList; | }
public void add(SequenceRule<A, B> rule) {
if (rule == null)
throw new NullPointerException("No sequence rule provided");
rules.add(rule);
rule.setSorter(createSorter(rules));
}
public Sort<A, B> createSorter(List<SequenceRule<A, B>> rules) {
List<SequenceRule<A, B>> subrules = new ArrayList<>(rules.size());
for (SequenceRule<A, B> rule : rules) {
if (!SORT_BRANCHES_WITH_RULE5 && rule instanceof Rule5)
continue;
subrules.add(rule);
}
return new Sort<A, B>(subrules);
}
@Override
public int getNumSubRules() {
return rules.size();
}
public Sort<A, B> getSorter() {
return new Sort<A, B>(rules);
}
@Override | // Path: core/src/main/java/com/simolecule/centres/BaseMol.java
// public abstract class BaseMol<A, B> {
//
// private Fraction[] atomnums;
//
// public static final String CIP_LABEL_KEY = "cip.label";
// public static final String CONF_INDEX = "conf.index";
//
// public abstract Object getBaseImpl();
//
// public abstract int getNumAtoms();
//
// public abstract int getNumBonds();
//
// public abstract A getAtom(int idx);
//
// public abstract int getAtomIdx(A atom);
//
// public Iterable<A> atoms() {
// return new Iterable<A>() {
// @Override
// public Iterator<A> iterator()
// {
// return new Iterator<A>() {
// private int pos = 0;
//
// @Override
// public boolean hasNext()
// {
// return pos < getNumAtoms();
// }
//
// @Override
// public A next()
// {
// return getAtom(pos++);
// }
//
// @Override
// public void remove()
// {
// throw new UnsupportedOperationException();
// }
// };
// }
// };
// }
//
// public abstract B getBond(int idx);
//
// public abstract int getBondIdx(B bond);
//
// public abstract Iterable<B> getBonds(A atom);
//
// public abstract A getOther(B bond, A atom);
//
// public abstract A getBeg(B bond);
//
// public abstract A getEnd(B bond);
//
// public abstract boolean isInRing(B bond);
//
// public abstract int getAtomicNum(A atom);
//
// public Fraction getFractionalAtomicNum(A atom) {
// if (atomnums == null)
// atomnums = Mancude.CalcFracAtomNums(this);
// return atomnums[getAtomIdx(atom)];
// }
//
// public abstract int getNumHydrogens(A atom);
//
// public abstract int getMassNum(A atom);
//
// public abstract int getCharge(A atom);
//
// public abstract int getBondOrder(B bond);
//
// public abstract void setAtomProp(A atom, String key, Object val);
//
// public abstract <V> V getAtomProp(A atom, String key);
//
// public abstract void setBondProp(B bond, String key, Object val);
//
// public abstract <V> V getBondProp(B bond, String key);
//
// public abstract String dumpDigraph(Digraph<A,B> digraph);
//
//
// }
// Path: core/src/main/java/com/simolecule/centres/rules/Rules.java
import java.util.List;
import com.simolecule.centres.BaseMol;
import com.simolecule.centres.Edge;
import java.util.ArrayList;
}
public void add(SequenceRule<A, B> rule) {
if (rule == null)
throw new NullPointerException("No sequence rule provided");
rules.add(rule);
rule.setSorter(createSorter(rules));
}
public Sort<A, B> createSorter(List<SequenceRule<A, B>> rules) {
List<SequenceRule<A, B>> subrules = new ArrayList<>(rules.size());
for (SequenceRule<A, B> rule : rules) {
if (!SORT_BRANCHES_WITH_RULE5 && rule instanceof Rule5)
continue;
subrules.add(rule);
}
return new Sort<A, B>(subrules);
}
@Override
public int getNumSubRules() {
return rules.size();
}
public Sort<A, B> getSorter() {
return new Sort<A, B>(rules);
}
@Override | public BaseMol<A, B> getMol() { |
SiMolecule/centres | core/src/test/java/centres/AbstractValidationSuite.java | // Path: core/src/main/java/com/simolecule/centres/BaseMol.java
// public abstract class BaseMol<A, B> {
//
// private Fraction[] atomnums;
//
// public static final String CIP_LABEL_KEY = "cip.label";
// public static final String CONF_INDEX = "conf.index";
//
// public abstract Object getBaseImpl();
//
// public abstract int getNumAtoms();
//
// public abstract int getNumBonds();
//
// public abstract A getAtom(int idx);
//
// public abstract int getAtomIdx(A atom);
//
// public Iterable<A> atoms() {
// return new Iterable<A>() {
// @Override
// public Iterator<A> iterator()
// {
// return new Iterator<A>() {
// private int pos = 0;
//
// @Override
// public boolean hasNext()
// {
// return pos < getNumAtoms();
// }
//
// @Override
// public A next()
// {
// return getAtom(pos++);
// }
//
// @Override
// public void remove()
// {
// throw new UnsupportedOperationException();
// }
// };
// }
// };
// }
//
// public abstract B getBond(int idx);
//
// public abstract int getBondIdx(B bond);
//
// public abstract Iterable<B> getBonds(A atom);
//
// public abstract A getOther(B bond, A atom);
//
// public abstract A getBeg(B bond);
//
// public abstract A getEnd(B bond);
//
// public abstract boolean isInRing(B bond);
//
// public abstract int getAtomicNum(A atom);
//
// public Fraction getFractionalAtomicNum(A atom) {
// if (atomnums == null)
// atomnums = Mancude.CalcFracAtomNums(this);
// return atomnums[getAtomIdx(atom)];
// }
//
// public abstract int getNumHydrogens(A atom);
//
// public abstract int getMassNum(A atom);
//
// public abstract int getCharge(A atom);
//
// public abstract int getBondOrder(B bond);
//
// public abstract void setAtomProp(A atom, String key, Object val);
//
// public abstract <V> V getAtomProp(A atom, String key);
//
// public abstract void setBondProp(B bond, String key, Object val);
//
// public abstract <V> V getBondProp(B bond, String key);
//
// public abstract String dumpDigraph(Digraph<A,B> digraph);
//
//
// }
| import com.simolecule.centres.BaseMol;
import com.simolecule.centres.Descriptor;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | /*
* Copyright (c) 2020 John Mayfield
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package centres;
@RunWith(Parameterized.class)
public abstract class AbstractValidationSuite {
public enum Context {
Atom,
Bond
}
public static abstract class GenSmiles { | // Path: core/src/main/java/com/simolecule/centres/BaseMol.java
// public abstract class BaseMol<A, B> {
//
// private Fraction[] atomnums;
//
// public static final String CIP_LABEL_KEY = "cip.label";
// public static final String CONF_INDEX = "conf.index";
//
// public abstract Object getBaseImpl();
//
// public abstract int getNumAtoms();
//
// public abstract int getNumBonds();
//
// public abstract A getAtom(int idx);
//
// public abstract int getAtomIdx(A atom);
//
// public Iterable<A> atoms() {
// return new Iterable<A>() {
// @Override
// public Iterator<A> iterator()
// {
// return new Iterator<A>() {
// private int pos = 0;
//
// @Override
// public boolean hasNext()
// {
// return pos < getNumAtoms();
// }
//
// @Override
// public A next()
// {
// return getAtom(pos++);
// }
//
// @Override
// public void remove()
// {
// throw new UnsupportedOperationException();
// }
// };
// }
// };
// }
//
// public abstract B getBond(int idx);
//
// public abstract int getBondIdx(B bond);
//
// public abstract Iterable<B> getBonds(A atom);
//
// public abstract A getOther(B bond, A atom);
//
// public abstract A getBeg(B bond);
//
// public abstract A getEnd(B bond);
//
// public abstract boolean isInRing(B bond);
//
// public abstract int getAtomicNum(A atom);
//
// public Fraction getFractionalAtomicNum(A atom) {
// if (atomnums == null)
// atomnums = Mancude.CalcFracAtomNums(this);
// return atomnums[getAtomIdx(atom)];
// }
//
// public abstract int getNumHydrogens(A atom);
//
// public abstract int getMassNum(A atom);
//
// public abstract int getCharge(A atom);
//
// public abstract int getBondOrder(B bond);
//
// public abstract void setAtomProp(A atom, String key, Object val);
//
// public abstract <V> V getAtomProp(A atom, String key);
//
// public abstract void setBondProp(B bond, String key, Object val);
//
// public abstract <V> V getBondProp(B bond, String key);
//
// public abstract String dumpDigraph(Digraph<A,B> digraph);
//
//
// }
// Path: core/src/test/java/centres/AbstractValidationSuite.java
import com.simolecule.centres.BaseMol;
import com.simolecule.centres.Descriptor;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* Copyright (c) 2020 John Mayfield
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package centres;
@RunWith(Parameterized.class)
public abstract class AbstractValidationSuite {
public enum Context {
Atom,
Bond
}
public static abstract class GenSmiles { | public abstract String generate(BaseMol mol); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/loadscene/step2/LoadSceneTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import com.badlogic.gdx.utils.Array;
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Vector3; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.loadscene.step2;
/**
* See: http://blog.xoppa.com/loading-a-scene-with-libgdx/
* @author Xoppa
*/
public class LoadSceneTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public AssetManager assets;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public Environment environment;
public boolean loading;
public Array<ModelInstance> blocks = new Array<ModelInstance>();
public Array<ModelInstance> invaders = new Array<ModelInstance>();
public ModelInstance ship;
public ModelInstance space;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/loadscene/step2/LoadSceneTest.java
import com.badlogic.gdx.utils.Array;
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Vector3;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.loadscene.step2;
/**
* See: http://blog.xoppa.com/loading-a-scene-with-libgdx/
* @author Xoppa
*/
public class LoadSceneTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public AssetManager assets;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public Environment environment;
public boolean loading;
public Array<ModelInstance> blocks = new Array<ModelInstance>();
public Array<ModelInstance> invaders = new Array<ModelInstance>();
public ModelInstance ship;
public ModelInstance space;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | assets.load(data+"/invaders.g3db", Model.class); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step5/TestShader.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.createshader.step5;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
@Override
public void init() { | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step5/TestShader.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.createshader.step5;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
@Override
public void init() { | String vert = Gdx.files.internal(data+"/test.vertex.glsl").readString(); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step2/CardGame.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.OrthographicCamera; | package com.xoppa.blog.libgdx.g3d.cardgame.step2;
public class CardGame extends ApplicationAdapter {
public final static float CARD_WIDTH = 1f;
public final static float CARD_HEIGHT = CARD_WIDTH * 277f / 200f;
public final static float MINIMUM_VIEWPORT_SIZE = 5f;
SpriteBatch spriteBatch;
TextureAtlas atlas;
Sprite front;
Sprite back;
OrthographicCamera cam;
@Override
public void create() {
spriteBatch = new SpriteBatch(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step2/CardGame.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.OrthographicCamera;
package com.xoppa.blog.libgdx.g3d.cardgame.step2;
public class CardGame extends ApplicationAdapter {
public final static float CARD_WIDTH = 1f;
public final static float CARD_HEIGHT = CARD_WIDTH * 277f / 200f;
public final static float MINIMUM_VIEWPORT_SIZE = 5f;
SpriteBatch spriteBatch;
TextureAtlas atlas;
Sprite front;
Sprite back;
OrthographicCamera cam;
@Override
public void create() {
spriteBatch = new SpriteBatch(); | atlas = new TextureAtlas(data + "/carddeck.atlas"); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/loadscene/step1/LoadSceneTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import com.badlogic.gdx.utils.Array;
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Vector3; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.loadscene.step1;
/**
* See: http://blog.xoppa.com/loading-a-scene-with-libgdx/
* @author Xoppa
*/
public class LoadSceneTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public AssetManager assets;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public Environment environment;
public boolean loading;
public Array<ModelInstance> blocks = new Array<ModelInstance>();
public Array<ModelInstance> invaders = new Array<ModelInstance>();
public ModelInstance ship;
public ModelInstance space;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/loadscene/step1/LoadSceneTest.java
import com.badlogic.gdx.utils.Array;
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Vector3;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.loadscene.step1;
/**
* See: http://blog.xoppa.com/loading-a-scene-with-libgdx/
* @author Xoppa
*/
public class LoadSceneTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public AssetManager assets;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public Environment environment;
public boolean loading;
public Array<ModelInstance> blocks = new Array<ModelInstance>();
public Array<ModelInstance> invaders = new Array<ModelInstance>();
public ModelInstance ship;
public ModelInstance space;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | assets.load(data+"/ship.obj", Model.class); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/loadscene/step3/LoadSceneTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import com.badlogic.gdx.utils.Array;
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.model.Node;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.loadscene.step3;
/**
* See: http://blog.xoppa.com/loading-a-scene-with-libgdx/
* @author Xoppa
*/
public class LoadSceneTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public AssetManager assets;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public Environment environment;
public boolean loading;
public Array<ModelInstance> blocks = new Array<ModelInstance>();
public Array<ModelInstance> invaders = new Array<ModelInstance>();
public ModelInstance ship;
public ModelInstance space;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/loadscene/step3/LoadSceneTest.java
import com.badlogic.gdx.utils.Array;
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.model.Node;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.loadscene.step3;
/**
* See: http://blog.xoppa.com/loading-a-scene-with-libgdx/
* @author Xoppa
*/
public class LoadSceneTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public AssetManager assets;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public Environment environment;
public boolean loading;
public Array<ModelInstance> blocks = new Array<ModelInstance>();
public Array<ModelInstance> invaders = new Array<ModelInstance>();
public ModelInstance ship;
public ModelInstance space;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | assets.load(data+"/invaderscene.g3db", Model.class); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/loadmodels/step4/LoadModelsTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.utils.Array; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.loadmodels.step4;
/**
* See: http://blog.xoppa.com/loading-models-using-libgdx/
* @author Xoppa
*/
public class LoadModelsTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public AssetManager assets;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public Environment environment;
public boolean loading;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(7f, 7f, 7f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/loadmodels/step4/LoadModelsTest.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.utils.Array;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.loadmodels.step4;
/**
* See: http://blog.xoppa.com/loading-models-using-libgdx/
* @author Xoppa
*/
public class LoadModelsTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public AssetManager assets;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public Environment environment;
public boolean loading;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(7f, 7f, 7f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | assets.load(data+"/ship.g3db", Model.class); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step4/TestShader.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.createshader.step4;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
@Override
public void init() { | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step4/TestShader.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.createshader.step4;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
@Override
public void init() { | String vert = Gdx.files.internal(data+"/test.vertex.glsl").readString(); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step5/CardGame.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectSet; | public CardDeck(TextureAtlas atlas, int backIndex) {
cards = new Card[Suit.values().length][];
for (Suit suit : Suit.values()) {
cards[suit.index] = new Card[Pip.values().length];
for (Pip pip : Pip.values()) {
Sprite front = atlas.createSprite(suit.name, pip.value);
Sprite back = atlas.createSprite("back", backIndex);
cards[suit.index][pip.index] = new Card(suit, pip, back, front);
}
}
}
public Card getCard(Suit suit, Pip pip) {
return cards[suit.index][pip.index];
}
}
SpriteBatch spriteBatch;
TextureAtlas atlas;
Sprite front;
Sprite back;
PerspectiveCamera cam;
CardDeck deck;
ObjectSet<Card> cards;
CameraInputController camController;
@Override
public void create() {
spriteBatch = new SpriteBatch(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step5/CardGame.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectSet;
public CardDeck(TextureAtlas atlas, int backIndex) {
cards = new Card[Suit.values().length][];
for (Suit suit : Suit.values()) {
cards[suit.index] = new Card[Pip.values().length];
for (Pip pip : Pip.values()) {
Sprite front = atlas.createSprite(suit.name, pip.value);
Sprite back = atlas.createSprite("back", backIndex);
cards[suit.index][pip.index] = new Card(suit, pip, back, front);
}
}
}
public Card getCard(Suit suit, Pip pip) {
return cards[suit.index][pip.index];
}
}
SpriteBatch spriteBatch;
TextureAtlas atlas;
Sprite front;
Sprite back;
PerspectiveCamera cam;
CardDeck deck;
ObjectSet<Card> cards;
CameraInputController camController;
@Override
public void create() {
spriteBatch = new SpriteBatch(); | atlas = new TextureAtlas(data + "/carddeck.atlas"); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/frustumculling/step2/FrustumCullingTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Array; |
protected Stage stage;
protected Label label;
protected BitmapFont font;
protected StringBuilder stringBuilder;
@Override
public void create () {
stage = new Stage();
font = new BitmapFont();
label = new Label(" ", new Label.LabelStyle(font, Color.WHITE));
stage.addActor(label);
stringBuilder = new StringBuilder();
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/frustumculling/step2/FrustumCullingTest.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Array;
protected Stage stage;
protected Label label;
protected BitmapFont font;
protected StringBuilder stringBuilder;
@Override
public void create () {
stage = new Stage();
font = new BitmapFont();
label = new Label(" ", new Label.LabelStyle(font, Color.WHITE));
stage.addActor(label);
stringBuilder = new StringBuilder();
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | assets.load(data+"/invaderscene.g3db", Model.class); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/shapes/step4/ShapeTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.math.collision.Ray;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Array; | private Vector3 position = new Vector3();
private int selected = -1, selecting = -1;
private Material selectionMaterial;
private Material originalMaterial;
@Override
public void create () {
stage = new Stage();
font = new BitmapFont();
label = new Label(" ", new Label.LabelStyle(font, Color.WHITE));
stage.addActor(label);
stringBuilder = new StringBuilder();
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0, 0, 0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(new InputMultiplexer(this, camController));
assets = new AssetManager(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/shapes/step4/ShapeTest.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.math.collision.Ray;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Array;
private Vector3 position = new Vector3();
private int selected = -1, selecting = -1;
private Material selectionMaterial;
private Material originalMaterial;
@Override
public void create () {
stage = new Stage();
font = new BitmapFont();
label = new Label(" ", new Label.LabelStyle(font, Color.WHITE));
stage.addActor(label);
stringBuilder = new StringBuilder();
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0, 0, 0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(new InputMultiplexer(this, camController));
assets = new AssetManager(); | assets.load(data + "/invaderscene.g3db", Model.class); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step1/CardGame.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas; | package com.xoppa.blog.libgdx.g3d.cardgame.step1;
public class CardGame extends ApplicationAdapter {
SpriteBatch spriteBatch;
TextureAtlas atlas;
Sprite front;
Sprite back;
@Override
public void create() {
spriteBatch = new SpriteBatch(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step1/CardGame.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
package com.xoppa.blog.libgdx.g3d.cardgame.step1;
public class CardGame extends ApplicationAdapter {
SpriteBatch spriteBatch;
TextureAtlas atlas;
Sprite front;
Sprite back;
@Override
public void create() {
spriteBatch = new SpriteBatch(); | atlas = new TextureAtlas(data + "/carddeck.atlas"); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step3/CardGame.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectSet; |
public CardDeck(TextureAtlas atlas, int backIndex) {
cards = new Card[Suit.values().length][];
for (Suit suit : Suit.values()) {
cards[suit.index] = new Card[Pip.values().length];
for (Pip pip : Pip.values()) {
Sprite front = atlas.createSprite(suit.name, pip.value);
Sprite back = atlas.createSprite("back", backIndex);
cards[suit.index][pip.index] = new Card(suit, pip, back, front);
}
}
}
public Card getCard(Suit suit, Pip pip) {
return cards[suit.index][pip.index];
}
}
SpriteBatch spriteBatch;
TextureAtlas atlas;
Sprite front;
Sprite back;
OrthographicCamera cam;
CardDeck deck;
ObjectSet<Card> cards;
@Override
public void create() {
spriteBatch = new SpriteBatch(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step3/CardGame.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectSet;
public CardDeck(TextureAtlas atlas, int backIndex) {
cards = new Card[Suit.values().length][];
for (Suit suit : Suit.values()) {
cards[suit.index] = new Card[Pip.values().length];
for (Pip pip : Pip.values()) {
Sprite front = atlas.createSprite(suit.name, pip.value);
Sprite back = atlas.createSprite("back", backIndex);
cards[suit.index][pip.index] = new Card(suit, pip, back, front);
}
}
}
public Card getCard(Suit suit, Pip pip) {
return cards[suit.index][pip.index];
}
}
SpriteBatch spriteBatch;
TextureAtlas atlas;
Sprite front;
Sprite back;
OrthographicCamera cam;
CardDeck deck;
ObjectSet<Card> cards;
@Override
public void create() {
spriteBatch = new SpriteBatch(); | atlas = new TextureAtlas(data + "/carddeck.atlas"); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/raypicking/step2/RayPickingTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.math.collision.Ray;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Array; | private Vector3 position = new Vector3();
private int selected = -1, selecting = -1;
private Material selectionMaterial;
private Material originalMaterial;
@Override
public void create () {
stage = new Stage();
font = new BitmapFont();
label = new Label(" ", new Label.LabelStyle(font, Color.WHITE));
stage.addActor(label);
stringBuilder = new StringBuilder();
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0, 0, 0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(new InputMultiplexer(this, camController));
assets = new AssetManager(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/raypicking/step2/RayPickingTest.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.math.collision.Ray;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Array;
private Vector3 position = new Vector3();
private int selected = -1, selecting = -1;
private Material selectionMaterial;
private Material originalMaterial;
@Override
public void create () {
stage = new Stage();
font = new BitmapFont();
label = new Label(" ", new Label.LabelStyle(font, Color.WHITE));
stage.addActor(label);
stringBuilder = new StringBuilder();
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0, 0, 0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(new InputMultiplexer(this, camController));
assets = new AssetManager(); | assets.load(data + "/invaderscene.g3db", Model.class); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/stepa/CardGame.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
//
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step7/CardGame.java
// public static class CardBatch extends ObjectSet<Card> implements RenderableProvider, Disposable {
// Renderable renderable;
// Mesh mesh;
// MeshBuilder meshBuilder;
//
// public CardBatch(Material material) {
// final int maxNumberOfCards = 52;
// final int maxNumberOfVertices = maxNumberOfCards * 8;
// final int maxNumberOfIndices = maxNumberOfCards * 12;
// mesh = new Mesh(false, maxNumberOfVertices, maxNumberOfIndices,
// VertexAttribute.Position(), VertexAttribute.Normal(), VertexAttribute.TexCoords(0));
// meshBuilder = new MeshBuilder();
//
// renderable = new Renderable();
// renderable.material = material;
// }
//
// @Override
// public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) {
// meshBuilder.begin(mesh.getVertexAttributes());
// meshBuilder.part("cards", GL20.GL_TRIANGLES, renderable.meshPart);
// for (Card card : this) {
// meshBuilder.setVertexTransform(card.transform);
// meshBuilder.addMesh(card.vertices, card.indices);
// }
// meshBuilder.end(mesh);
//
// renderables.add(renderable);
// }
//
// @Override
// public void dispose() {
// mesh.dispose();
// }
// }
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.RenderableProvider;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalShadowLight;
import com.badlogic.gdx.graphics.g3d.model.MeshPart;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.DepthShaderProvider;
import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectSet;
import com.badlogic.gdx.utils.Pool;
import com.xoppa.blog.libgdx.g3d.cardgame.step7.CardGame.CardBatch; |
public void update() {
float z = position.z + 0.5f * Math.abs(MathUtils.sinDeg(angle));
transform.setToRotation(Vector3.Y, angle);
transform.trn(position.x, position.y, z);
}
}
public static class CardDeck {
private final Card[][] cards;
public CardDeck(TextureAtlas atlas, int backIndex) {
cards = new Card[Suit.values().length][];
for (Suit suit : Suit.values()) {
cards[suit.index] = new Card[Pip.values().length];
for (Pip pip : Pip.values()) {
Sprite front = atlas.createSprite(suit.name, pip.value);
front.setSize(CARD_WIDTH, CARD_HEIGHT);
Sprite back = atlas.createSprite("back", backIndex);
back.setSize(CARD_WIDTH, CARD_HEIGHT);
cards[suit.index][pip.index] = new Card(suit, pip, back, front);
}
}
}
public Card getCard(Suit suit, Pip pip) {
return cards[suit.index][pip.index];
}
}
| // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
//
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step7/CardGame.java
// public static class CardBatch extends ObjectSet<Card> implements RenderableProvider, Disposable {
// Renderable renderable;
// Mesh mesh;
// MeshBuilder meshBuilder;
//
// public CardBatch(Material material) {
// final int maxNumberOfCards = 52;
// final int maxNumberOfVertices = maxNumberOfCards * 8;
// final int maxNumberOfIndices = maxNumberOfCards * 12;
// mesh = new Mesh(false, maxNumberOfVertices, maxNumberOfIndices,
// VertexAttribute.Position(), VertexAttribute.Normal(), VertexAttribute.TexCoords(0));
// meshBuilder = new MeshBuilder();
//
// renderable = new Renderable();
// renderable.material = material;
// }
//
// @Override
// public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) {
// meshBuilder.begin(mesh.getVertexAttributes());
// meshBuilder.part("cards", GL20.GL_TRIANGLES, renderable.meshPart);
// for (Card card : this) {
// meshBuilder.setVertexTransform(card.transform);
// meshBuilder.addMesh(card.vertices, card.indices);
// }
// meshBuilder.end(mesh);
//
// renderables.add(renderable);
// }
//
// @Override
// public void dispose() {
// mesh.dispose();
// }
// }
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/stepa/CardGame.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.RenderableProvider;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalShadowLight;
import com.badlogic.gdx.graphics.g3d.model.MeshPart;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.DepthShaderProvider;
import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectSet;
import com.badlogic.gdx.utils.Pool;
import com.xoppa.blog.libgdx.g3d.cardgame.step7.CardGame.CardBatch;
public void update() {
float z = position.z + 0.5f * Math.abs(MathUtils.sinDeg(angle));
transform.setToRotation(Vector3.Y, angle);
transform.trn(position.x, position.y, z);
}
}
public static class CardDeck {
private final Card[][] cards;
public CardDeck(TextureAtlas atlas, int backIndex) {
cards = new Card[Suit.values().length][];
for (Suit suit : Suit.values()) {
cards[suit.index] = new Card[Pip.values().length];
for (Pip pip : Pip.values()) {
Sprite front = atlas.createSprite(suit.name, pip.value);
front.setSize(CARD_WIDTH, CARD_HEIGHT);
Sprite back = atlas.createSprite("back", backIndex);
back.setSize(CARD_WIDTH, CARD_HEIGHT);
cards[suit.index][pip.index] = new Card(suit, pip, back, front);
}
}
}
public Card getCard(Suit suit, Pip pip) {
return cards[suit.index][pip.index];
}
}
| public static class CardBatch extends ObjectSet<Card> implements RenderableProvider, Disposable { |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/stepa/CardGame.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
//
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step7/CardGame.java
// public static class CardBatch extends ObjectSet<Card> implements RenderableProvider, Disposable {
// Renderable renderable;
// Mesh mesh;
// MeshBuilder meshBuilder;
//
// public CardBatch(Material material) {
// final int maxNumberOfCards = 52;
// final int maxNumberOfVertices = maxNumberOfCards * 8;
// final int maxNumberOfIndices = maxNumberOfCards * 12;
// mesh = new Mesh(false, maxNumberOfVertices, maxNumberOfIndices,
// VertexAttribute.Position(), VertexAttribute.Normal(), VertexAttribute.TexCoords(0));
// meshBuilder = new MeshBuilder();
//
// renderable = new Renderable();
// renderable.material = material;
// }
//
// @Override
// public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) {
// meshBuilder.begin(mesh.getVertexAttributes());
// meshBuilder.part("cards", GL20.GL_TRIANGLES, renderable.meshPart);
// for (Card card : this) {
// meshBuilder.setVertexTransform(card.transform);
// meshBuilder.addMesh(card.vertices, card.indices);
// }
// meshBuilder.end(mesh);
//
// renderables.add(renderable);
// }
//
// @Override
// public void dispose() {
// mesh.dispose();
// }
// }
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.RenderableProvider;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalShadowLight;
import com.badlogic.gdx.graphics.g3d.model.MeshPart;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.DepthShaderProvider;
import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectSet;
import com.badlogic.gdx.utils.Pool;
import com.xoppa.blog.libgdx.g3d.cardgame.step7.CardGame.CardBatch; | }
public void animate(Card card, float x, float y, float z, float angle, float speed) {
CardAction action = actionPool.obtain();
action.reset(card);
action.toPosition.set(x, y, z);
action.toAngle = angle;
action.speed = speed;
actions.add(action);
}
}
TextureAtlas atlas;
Sprite front;
Sprite back;
PerspectiveCamera cam;
CardDeck deck;
CardBatch cards;
CameraInputController camController;
ModelBatch modelBatch;
Model tableTopModel;
ModelInstance tableTop;
Environment environment;
DirectionalShadowLight shadowLight;
ModelBatch shadowBatch;
CardActions actions;
@Override
public void create() {
modelBatch = new ModelBatch(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
//
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step7/CardGame.java
// public static class CardBatch extends ObjectSet<Card> implements RenderableProvider, Disposable {
// Renderable renderable;
// Mesh mesh;
// MeshBuilder meshBuilder;
//
// public CardBatch(Material material) {
// final int maxNumberOfCards = 52;
// final int maxNumberOfVertices = maxNumberOfCards * 8;
// final int maxNumberOfIndices = maxNumberOfCards * 12;
// mesh = new Mesh(false, maxNumberOfVertices, maxNumberOfIndices,
// VertexAttribute.Position(), VertexAttribute.Normal(), VertexAttribute.TexCoords(0));
// meshBuilder = new MeshBuilder();
//
// renderable = new Renderable();
// renderable.material = material;
// }
//
// @Override
// public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) {
// meshBuilder.begin(mesh.getVertexAttributes());
// meshBuilder.part("cards", GL20.GL_TRIANGLES, renderable.meshPart);
// for (Card card : this) {
// meshBuilder.setVertexTransform(card.transform);
// meshBuilder.addMesh(card.vertices, card.indices);
// }
// meshBuilder.end(mesh);
//
// renderables.add(renderable);
// }
//
// @Override
// public void dispose() {
// mesh.dispose();
// }
// }
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/stepa/CardGame.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.RenderableProvider;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalShadowLight;
import com.badlogic.gdx.graphics.g3d.model.MeshPart;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.DepthShaderProvider;
import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectSet;
import com.badlogic.gdx.utils.Pool;
import com.xoppa.blog.libgdx.g3d.cardgame.step7.CardGame.CardBatch;
}
public void animate(Card card, float x, float y, float z, float angle, float speed) {
CardAction action = actionPool.obtain();
action.reset(card);
action.toPosition.set(x, y, z);
action.toAngle = angle;
action.speed = speed;
actions.add(action);
}
}
TextureAtlas atlas;
Sprite front;
Sprite back;
PerspectiveCamera cam;
CardDeck deck;
CardBatch cards;
CameraInputController camController;
ModelBatch modelBatch;
Model tableTopModel;
ModelInstance tableTop;
Environment environment;
DirectionalShadowLight shadowLight;
ModelBatch shadowBatch;
CardActions actions;
@Override
public void create() {
modelBatch = new ModelBatch(); | atlas = new TextureAtlas(data + "/carddeck.atlas"); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/loadmodels/step3/LoadModelsTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import com.badlogic.gdx.utils.Array;
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.loadmodels.step3;
/**
* See: http://blog.xoppa.com/loading-models-using-libgdx/
* @author Xoppa
*/
public class LoadModelsTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public AssetManager assets;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public Environment environment;
public boolean loading;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(7f, 7f, 7f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/loadmodels/step3/LoadModelsTest.java
import com.badlogic.gdx.utils.Array;
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.loadmodels.step3;
/**
* See: http://blog.xoppa.com/loading-models-using-libgdx/
* @author Xoppa
*/
public class LoadModelsTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public AssetManager assets;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public Environment environment;
public boolean loading;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(7f, 7f, 7f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | assets.load(data+"/ship.obj", Model.class); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step4/CardGame.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectSet; |
public CardDeck(TextureAtlas atlas, int backIndex) {
cards = new Card[Suit.values().length][];
for (Suit suit : Suit.values()) {
cards[suit.index] = new Card[Pip.values().length];
for (Pip pip : Pip.values()) {
Sprite front = atlas.createSprite(suit.name, pip.value);
Sprite back = atlas.createSprite("back", backIndex);
cards[suit.index][pip.index] = new Card(suit, pip, back, front);
}
}
}
public Card getCard(Suit suit, Pip pip) {
return cards[suit.index][pip.index];
}
}
SpriteBatch spriteBatch;
TextureAtlas atlas;
Sprite front;
Sprite back;
OrthographicCamera cam;
CardDeck deck;
ObjectSet<Card> cards;
CameraInputController camController;
@Override
public void create() {
spriteBatch = new SpriteBatch(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step4/CardGame.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectSet;
public CardDeck(TextureAtlas atlas, int backIndex) {
cards = new Card[Suit.values().length][];
for (Suit suit : Suit.values()) {
cards[suit.index] = new Card[Pip.values().length];
for (Pip pip : Pip.values()) {
Sprite front = atlas.createSprite(suit.name, pip.value);
Sprite back = atlas.createSprite("back", backIndex);
cards[suit.index][pip.index] = new Card(suit, pip, back, front);
}
}
}
public Card getCard(Suit suit, Pip pip) {
return cards[suit.index][pip.index];
}
}
SpriteBatch spriteBatch;
TextureAtlas atlas;
Sprite front;
Sprite back;
OrthographicCamera cam;
CardDeck deck;
ObjectSet<Card> cards;
CameraInputController camController;
@Override
public void create() {
spriteBatch = new SpriteBatch(); | atlas = new TextureAtlas(data + "/carddeck.atlas"); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step2/TestShader.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.GdxRuntimeException; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step2;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_color;
@Override
public void init() { | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step2/TestShader.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.GdxRuntimeException;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step2;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_color;
@Override
public void init() { | String vert = Gdx.files.internal(data+"/color.vertex.glsl").readString(); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step7/MaterialTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step7/TestShader.java
// public static class TestColorAttribute extends ColorAttribute {
// public final static String DiffuseUAlias = "diffuseUColor";
// public final static long DiffuseU = register(DiffuseUAlias);
//
// public final static String DiffuseVAlias = "diffuseVColor";
// public final static long DiffuseV = register(DiffuseVAlias);
//
// static {
// Mask = Mask | DiffuseU | DiffuseV;
// }
//
// public TestColorAttribute (long type, float r, float g, float b, float a) {
// super(type, r, g, b, a);
// }
// }
| import com.xoppa.blog.libgdx.g3d.usingmaterials.step7.TestShader.TestColorAttribute;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.utils.Array; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step7;
/**
* See: http://blog.xoppa.com/using-materials-with-libgdx
* @author Xoppa
*/
public class MaterialTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public Shader shader;
public Model model;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public ModelBatch modelBatch;
@Override
public void create () {
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 8f, 8f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20,
new Material(),
Usage.Position | Usage.Normal | Usage.TextureCoordinates);
for (int x = -5; x <= 5; x+=2) {
for (int z = -5; z<=5; z+=2) {
ModelInstance instance = new ModelInstance(model, x, 0, z); | // Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step7/TestShader.java
// public static class TestColorAttribute extends ColorAttribute {
// public final static String DiffuseUAlias = "diffuseUColor";
// public final static long DiffuseU = register(DiffuseUAlias);
//
// public final static String DiffuseVAlias = "diffuseVColor";
// public final static long DiffuseV = register(DiffuseVAlias);
//
// static {
// Mask = Mask | DiffuseU | DiffuseV;
// }
//
// public TestColorAttribute (long type, float r, float g, float b, float a) {
// super(type, r, g, b, a);
// }
// }
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step7/MaterialTest.java
import com.xoppa.blog.libgdx.g3d.usingmaterials.step7.TestShader.TestColorAttribute;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.utils.Array;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step7;
/**
* See: http://blog.xoppa.com/using-materials-with-libgdx
* @author Xoppa
*/
public class MaterialTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public Shader shader;
public Model model;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public ModelBatch modelBatch;
@Override
public void create () {
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 8f, 8f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20,
new Material(),
Usage.Position | Usage.Normal | Usage.TextureCoordinates);
for (int x = -5; x <= 5; x+=2) {
for (int z = -5; z<=5; z+=2) {
ModelInstance instance = new ModelInstance(model, x, 0, z); | ColorAttribute attrU = new TestColorAttribute(TestColorAttribute.DiffuseU, (x+5f)/10f, 1f - (z+5f)/10f, 0, 1); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step4/TestShader.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step4;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_color;
@Override
public void init() { | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step4/TestShader.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step4;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_color;
@Override
public void init() { | String vert = Gdx.files.internal(data+"/color.vertex.glsl").readString(); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step8/TestShader.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step8;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
public static class TestColorAttribute extends ColorAttribute {
public final static String DiffuseUAlias = "diffuseUColor";
public final static long DiffuseU = register(DiffuseUAlias);
public final static String DiffuseVAlias = "diffuseVColor";
public final static long DiffuseV = register(DiffuseVAlias);
static {
Mask = Mask | DiffuseU | DiffuseV;
}
public TestColorAttribute (long type, float r, float g, float b, float a) {
super(type, r, g, b, a);
}
}
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_colorU;
int u_colorV;
@Override
public void init() { | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step8/TestShader.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step8;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
public static class TestColorAttribute extends ColorAttribute {
public final static String DiffuseUAlias = "diffuseUColor";
public final static long DiffuseU = register(DiffuseUAlias);
public final static String DiffuseVAlias = "diffuseVColor";
public final static long DiffuseV = register(DiffuseVAlias);
static {
Mask = Mask | DiffuseU | DiffuseV;
}
public TestColorAttribute (long type, float r, float g, float b, float a) {
super(type, r, g, b, a);
}
}
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_colorU;
int u_colorV;
@Override
public void init() { | String vert = Gdx.files.internal(data+"/uvcolor.vertex.glsl").readString(); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step1/TestShader.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step1;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
@Override
public void init() { | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step1/TestShader.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step1;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
@Override
public void init() { | String vert = Gdx.files.internal(data+"/test.vertex.glsl").readString(); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/shapes/step1/ShapeTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.math.collision.Ray;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Array; | private Vector3 position = new Vector3();
private int selected = -1, selecting = -1;
private Material selectionMaterial;
private Material originalMaterial;
@Override
public void create () {
stage = new Stage();
font = new BitmapFont();
label = new Label(" ", new Label.LabelStyle(font, Color.WHITE));
stage.addActor(label);
stringBuilder = new StringBuilder();
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0, 0, 0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(new InputMultiplexer(this, camController));
assets = new AssetManager(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/shapes/step1/ShapeTest.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.math.collision.Ray;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Array;
private Vector3 position = new Vector3();
private int selected = -1, selecting = -1;
private Material selectionMaterial;
private Material originalMaterial;
@Override
public void create () {
stage = new Stage();
font = new BitmapFont();
label = new Label(" ", new Label.LabelStyle(font, Color.WHITE));
stage.addActor(label);
stringBuilder = new StringBuilder();
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0, 0, 0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(new InputMultiplexer(this, camController));
assets = new AssetManager(); | assets.load(data + "/invaderscene.g3db", Model.class); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step3/TestShader.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step3;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_color;
@Override
public void init() { | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step3/TestShader.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step3;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_color;
@Override
public void init() { | String vert = Gdx.files.internal(data+"/color.vertex.glsl").readString(); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step5/TestShader.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step5;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_color;
@Override
public void init() { | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step5/TestShader.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step5;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_color;
@Override
public void init() { | String vert = Gdx.files.internal(data+"/color.vertex.glsl").readString(); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step6/BehindTheScenesTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import com.badlogic.gdx.graphics.g3d.model.data.ModelData;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.TextureProvider;
import com.badlogic.gdx.utils.JsonReader;
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.loaders.ModelLoader;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader;
import com.badlogic.gdx.graphics.g3d.model.NodePart; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.behindscenes.step6;
/**
* See: http://blog.xoppa.com/behind-the-3d-scenes-part2/
* @author Xoppa
*/
public class BehindTheScenesTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public Model model;
public Environment environment;
public Renderable renderable;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(2f, 2f, 2f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
ModelLoader<?> modelLoader = new G3dModelLoader(new JsonReader()); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step6/BehindTheScenesTest.java
import com.badlogic.gdx.graphics.g3d.model.data.ModelData;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.TextureProvider;
import com.badlogic.gdx.utils.JsonReader;
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.loaders.ModelLoader;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader;
import com.badlogic.gdx.graphics.g3d.model.NodePart;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.behindscenes.step6;
/**
* See: http://blog.xoppa.com/behind-the-3d-scenes-part2/
* @author Xoppa
*/
public class BehindTheScenesTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public Model model;
public Environment environment;
public Renderable renderable;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(2f, 2f, 2f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
ModelLoader<?> modelLoader = new G3dModelLoader(new JsonReader()); | ModelData modelData = modelLoader.loadModelData(Gdx.files.internal(data+"/invaderscene.g3dj")); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step9/MaterialTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step9/TestShader.java
// public static class DoubleColorAttribute extends Attribute {
// public final static String DiffuseUVAlias = "diffuseUVColor";
// public final static long DiffuseUV = register(DiffuseUVAlias);
//
// public final Color color1 = new Color();
// public final Color color2 = new Color();
//
// protected DoubleColorAttribute (long type, Color c1, Color c2) {
// super(type);
// color1.set(c1);
// color2.set(c2);
// }
//
// @Override
// public Attribute copy () {
// return new DoubleColorAttribute(type, color1, color2);
// }
//
// @Override
// protected boolean equals (Attribute other) {
// DoubleColorAttribute attr = (DoubleColorAttribute) other;
// return type == other.type && color1.equals(attr.color1)
// && color2.equals(attr.color2);
// }
//
// @Override
// public int compareTo (Attribute other) {
// if (type != other.type)
// return (int) (type - other.type);
// DoubleColorAttribute attr = (DoubleColorAttribute) other;
// return color1.equals(attr.color1)
// ? attr.color2.toIntBits() - color2.toIntBits()
// : attr.color1.toIntBits() - color1.toIntBits();
// }
// }
| import com.xoppa.blog.libgdx.g3d.usingmaterials.step9.TestShader.DoubleColorAttribute;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.utils.Array; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step9;
/**
* See: http://blog.xoppa.com/using-materials-with-libgdx
* @author Xoppa
*/
public class MaterialTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public Shader shader;
public Model model;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public ModelBatch modelBatch;
@Override
public void create () {
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 8f, 8f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20,
new Material(),
Usage.Position | Usage.Normal | Usage.TextureCoordinates);
Color colorU = new Color(), colorV = new Color();
for (int x = -5; x <= 5; x+=2) {
for (int z = -5; z<=5; z+=2) {
ModelInstance instance = new ModelInstance(model, x, 0, z); | // Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step9/TestShader.java
// public static class DoubleColorAttribute extends Attribute {
// public final static String DiffuseUVAlias = "diffuseUVColor";
// public final static long DiffuseUV = register(DiffuseUVAlias);
//
// public final Color color1 = new Color();
// public final Color color2 = new Color();
//
// protected DoubleColorAttribute (long type, Color c1, Color c2) {
// super(type);
// color1.set(c1);
// color2.set(c2);
// }
//
// @Override
// public Attribute copy () {
// return new DoubleColorAttribute(type, color1, color2);
// }
//
// @Override
// protected boolean equals (Attribute other) {
// DoubleColorAttribute attr = (DoubleColorAttribute) other;
// return type == other.type && color1.equals(attr.color1)
// && color2.equals(attr.color2);
// }
//
// @Override
// public int compareTo (Attribute other) {
// if (type != other.type)
// return (int) (type - other.type);
// DoubleColorAttribute attr = (DoubleColorAttribute) other;
// return color1.equals(attr.color1)
// ? attr.color2.toIntBits() - color2.toIntBits()
// : attr.color1.toIntBits() - color1.toIntBits();
// }
// }
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step9/MaterialTest.java
import com.xoppa.blog.libgdx.g3d.usingmaterials.step9.TestShader.DoubleColorAttribute;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.utils.Array;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step9;
/**
* See: http://blog.xoppa.com/using-materials-with-libgdx
* @author Xoppa
*/
public class MaterialTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public Shader shader;
public Model model;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public ModelBatch modelBatch;
@Override
public void create () {
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 8f, 8f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createSphere(2f, 2f, 2f, 20, 20,
new Material(),
Usage.Position | Usage.Normal | Usage.TextureCoordinates);
Color colorU = new Color(), colorV = new Color();
for (int x = -5; x <= 5; x+=2) {
for (int z = -5; z<=5; z+=2) {
ModelInstance instance = new ModelInstance(model, x, 0, z); | DoubleColorAttribute attr = new DoubleColorAttribute(DoubleColorAttribute.DiffuseUV, |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step6/TestShader.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.createshader.step6;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
@Override
public void init() { | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/createshader/step6/TestShader.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.createshader.step6;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
@Override
public void init() { | String vert = Gdx.files.internal(data+"/test.vertex.glsl").readString(); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/frustumculling/step3/FrustumCullingTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Array; |
protected Stage stage;
protected Label label;
protected BitmapFont font;
protected StringBuilder stringBuilder;
@Override
public void create () {
stage = new Stage();
font = new BitmapFont();
label = new Label(" ", new Label.LabelStyle(font, Color.WHITE));
stage.addActor(label);
stringBuilder = new StringBuilder();
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/frustumculling/step3/FrustumCullingTest.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Array;
protected Stage stage;
protected Label label;
protected BitmapFont font;
protected StringBuilder stringBuilder;
@Override
public void create () {
stage = new Stage();
font = new BitmapFont();
label = new Label(" ", new Label.LabelStyle(font, Color.WHITE));
stage.addActor(label);
stringBuilder = new StringBuilder();
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | assets.load(data+"/invaderscene.g3db", Model.class); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step7/BehindTheScenesTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.loaders.ModelLoader;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader;
import com.badlogic.gdx.graphics.g3d.model.NodePart;
import com.badlogic.gdx.graphics.g3d.model.data.ModelData;
import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.DefaultTextureBinder;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.g3d.utils.TextureProvider;
import com.badlogic.gdx.utils.JsonReader; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.behindscenes.step7;
/**
* See: http://blog.xoppa.com/behind-the-3d-scenes-part2/
* @author Xoppa
*/
public class BehindTheScenesTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public Shader shader;
public RenderContext renderContext;
public Model model;
public Environment environment;
public Renderable renderable;
@Override
public void create () {
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(2f, 2f, 2f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
ModelLoader<?> modelLoader = new G3dModelLoader(new JsonReader()); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/behindscenes/step7/BehindTheScenesTest.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.loaders.ModelLoader;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader;
import com.badlogic.gdx.graphics.g3d.model.NodePart;
import com.badlogic.gdx.graphics.g3d.model.data.ModelData;
import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.DefaultTextureBinder;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.g3d.utils.TextureProvider;
import com.badlogic.gdx.utils.JsonReader;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.behindscenes.step7;
/**
* See: http://blog.xoppa.com/behind-the-3d-scenes-part2/
* @author Xoppa
*/
public class BehindTheScenesTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public Shader shader;
public RenderContext renderContext;
public Model model;
public Environment environment;
public Renderable renderable;
@Override
public void create () {
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(2f, 2f, 2f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
ModelLoader<?> modelLoader = new G3dModelLoader(new JsonReader()); | ModelData modelData = modelLoader.loadModelData(Gdx.files.internal(data+"/invaderscene.g3dj")); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step7/TestShader.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step7;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
public static class TestColorAttribute extends ColorAttribute {
public final static String DiffuseUAlias = "diffuseUColor";
public final static long DiffuseU = register(DiffuseUAlias);
public final static String DiffuseVAlias = "diffuseVColor";
public final static long DiffuseV = register(DiffuseVAlias);
static {
Mask = Mask | DiffuseU | DiffuseV;
}
public TestColorAttribute (long type, float r, float g, float b, float a) {
super(type, r, g, b, a);
}
}
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_colorU;
int u_colorV;
@Override
public void init() { | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step7/TestShader.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step7;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
public static class TestColorAttribute extends ColorAttribute {
public final static String DiffuseUAlias = "diffuseUColor";
public final static long DiffuseU = register(DiffuseUAlias);
public final static String DiffuseVAlias = "diffuseVColor";
public final static long DiffuseV = register(DiffuseVAlias);
static {
Mask = Mask | DiffuseU | DiffuseV;
}
public TestColorAttribute (long type, float r, float g, float b, float a) {
super(type, r, g, b, a);
}
}
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_colorU;
int u_colorV;
@Override
public void init() { | String vert = Gdx.files.internal(data+"/uvcolor.vertex.glsl").readString(); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step6/CardGame.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectSet; | private final Card[][] cards;
public CardDeck(TextureAtlas atlas, int backIndex) {
cards = new Card[Suit.values().length][];
for (Suit suit : Suit.values()) {
cards[suit.index] = new Card[Pip.values().length];
for (Pip pip : Pip.values()) {
Sprite front = atlas.createSprite(suit.name, pip.value);
Sprite back = atlas.createSprite("back", backIndex);
cards[suit.index][pip.index] = new Card(suit, pip, back, front);
}
}
}
public Card getCard(Suit suit, Pip pip) {
return cards[suit.index][pip.index];
}
}
TextureAtlas atlas;
PerspectiveCamera cam;
CardDeck deck;
ObjectSet<Card> cards;
CameraInputController camController;
ModelBatch modelBatch;
@Override
public void create() {
modelBatch = new ModelBatch();
| // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step6/CardGame.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectSet;
private final Card[][] cards;
public CardDeck(TextureAtlas atlas, int backIndex) {
cards = new Card[Suit.values().length][];
for (Suit suit : Suit.values()) {
cards[suit.index] = new Card[Pip.values().length];
for (Pip pip : Pip.values()) {
Sprite front = atlas.createSprite(suit.name, pip.value);
Sprite back = atlas.createSprite("back", backIndex);
cards[suit.index][pip.index] = new Card(suit, pip, back, front);
}
}
}
public Card getCard(Suit suit, Pip pip) {
return cards[suit.index][pip.index];
}
}
TextureAtlas atlas;
PerspectiveCamera cam;
CardDeck deck;
ObjectSet<Card> cards;
CameraInputController camController;
ModelBatch modelBatch;
@Override
public void create() {
modelBatch = new ModelBatch();
| atlas = new TextureAtlas(data + "/carddeck.atlas"); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/loadmodels/step2/LoadModelsTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.utils.Array; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.loadmodels.step2;
/**
* See: http://blog.xoppa.com/loading-models-using-libgdx/
* @author Xoppa
*/
public class LoadModelsTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public AssetManager assets;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public Environment environment;
public boolean loading;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(1f, 1f, 1f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/loadmodels/step2/LoadModelsTest.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.utils.Array;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.loadmodels.step2;
/**
* See: http://blog.xoppa.com/loading-models-using-libgdx/
* @author Xoppa
*/
public class LoadModelsTest implements ApplicationListener {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public AssetManager assets;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public Environment environment;
public boolean loading;
@Override
public void create () {
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(1f, 1f, 1f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | assets.load(data+"/ship.obj", Model.class); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step6/TestShader.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException; | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step6;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_colorU;
int u_colorV;
@Override
public void init() { | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step6/TestShader.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.xoppa.blog.libgdx.g3d.usingmaterials.step6;
/**
* See: http://blog.xoppa.com/creating-a-shader-with-libgdx
* @author Xoppa
*/
public class TestShader implements Shader {
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_colorU;
int u_colorV;
@Override
public void init() { | String vert = Gdx.files.internal(data+"/uvcolor.vertex.glsl").readString(); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step9/TestShader.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Attribute;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException; | }
@Override
protected boolean equals (Attribute other) {
DoubleColorAttribute attr = (DoubleColorAttribute) other;
return type == other.type && color1.equals(attr.color1)
&& color2.equals(attr.color2);
}
@Override
public int compareTo (Attribute other) {
if (type != other.type)
return (int) (type - other.type);
DoubleColorAttribute attr = (DoubleColorAttribute) other;
return color1.equals(attr.color1)
? attr.color2.toIntBits() - color2.toIntBits()
: attr.color1.toIntBits() - color1.toIntBits();
}
}
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_colorU;
int u_colorV;
@Override
public void init() { | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/usingmaterials/step9/TestShader.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g3d.Attribute;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.Shader;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.GdxRuntimeException;
}
@Override
protected boolean equals (Attribute other) {
DoubleColorAttribute attr = (DoubleColorAttribute) other;
return type == other.type && color1.equals(attr.color1)
&& color2.equals(attr.color2);
}
@Override
public int compareTo (Attribute other) {
if (type != other.type)
return (int) (type - other.type);
DoubleColorAttribute attr = (DoubleColorAttribute) other;
return color1.equals(attr.color1)
? attr.color2.toIntBits() - color2.toIntBits()
: attr.color1.toIntBits() - color1.toIntBits();
}
}
ShaderProgram program;
Camera camera;
RenderContext context;
int u_projTrans;
int u_worldTrans;
int u_colorU;
int u_colorV;
@Override
public void init() { | String vert = Gdx.files.internal(data + "/uvcolor.vertex.glsl") |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step8/CardGame.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.RenderableProvider;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectSet;
import com.badlogic.gdx.utils.Pool; | for (Card card : this) {
meshBuilder.setVertexTransform(card.transform);
meshBuilder.addMesh(card.vertices, card.indices);
}
meshBuilder.end(mesh);
renderables.add(renderable);
}
@Override
public void dispose() {
mesh.dispose();
}
}
TextureAtlas atlas;
Sprite front;
Sprite back;
PerspectiveCamera cam;
CardDeck deck;
CardBatch cards;
CameraInputController camController;
ModelBatch modelBatch;
Model tableTopModel;
ModelInstance tableTop;
Environment environment;
@Override
public void create() {
modelBatch = new ModelBatch(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step8/CardGame.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.RenderableProvider;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectSet;
import com.badlogic.gdx.utils.Pool;
for (Card card : this) {
meshBuilder.setVertexTransform(card.transform);
meshBuilder.addMesh(card.vertices, card.indices);
}
meshBuilder.end(mesh);
renderables.add(renderable);
}
@Override
public void dispose() {
mesh.dispose();
}
}
TextureAtlas atlas;
Sprite front;
Sprite back;
PerspectiveCamera cam;
CardDeck deck;
CardBatch cards;
CameraInputController camController;
ModelBatch modelBatch;
Model tableTopModel;
ModelInstance tableTop;
Environment environment;
@Override
public void create() {
modelBatch = new ModelBatch(); | atlas = new TextureAtlas(data + "/carddeck.atlas"); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step7/CardGame.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import java.nio.IntBuffer;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.RenderableProvider;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.model.MeshPart;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectSet;
import com.badlogic.gdx.utils.Pool; | public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) {
meshBuilder.begin(mesh.getVertexAttributes());
meshBuilder.part("cards", GL20.GL_TRIANGLES, renderable.meshPart);
for (Card card : this) {
meshBuilder.setVertexTransform(card.transform);
meshBuilder.addMesh(card.vertices, card.indices);
}
meshBuilder.end(mesh);
renderables.add(renderable);
}
@Override
public void dispose() {
mesh.dispose();
}
}
TextureAtlas atlas;
Sprite front;
Sprite back;
PerspectiveCamera cam;
CardDeck deck;
CardBatch cards;
CameraInputController camController;
ModelBatch modelBatch;
@Override
public void create() {
modelBatch = new ModelBatch(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step7/CardGame.java
import static com.xoppa.blog.libgdx.Main.data;
import java.nio.IntBuffer;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.RenderableProvider;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.model.MeshPart;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectSet;
import com.badlogic.gdx.utils.Pool;
public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) {
meshBuilder.begin(mesh.getVertexAttributes());
meshBuilder.part("cards", GL20.GL_TRIANGLES, renderable.meshPart);
for (Card card : this) {
meshBuilder.setVertexTransform(card.transform);
meshBuilder.addMesh(card.vertices, card.indices);
}
meshBuilder.end(mesh);
renderables.add(renderable);
}
@Override
public void dispose() {
mesh.dispose();
}
}
TextureAtlas atlas;
Sprite front;
Sprite back;
PerspectiveCamera cam;
CardDeck deck;
CardBatch cards;
CameraInputController camController;
ModelBatch modelBatch;
@Override
public void create() {
modelBatch = new ModelBatch(); | atlas = new TextureAtlas(data + "/carddeck.atlas"); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/frustumculling/step4/FrustumCullingTest.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Array; |
protected Stage stage;
protected Label label;
protected BitmapFont font;
protected StringBuilder stringBuilder;
@Override
public void create () {
stage = new Stage();
font = new BitmapFont();
label = new Label(" ", new Label.LabelStyle(font, Color.WHITE));
stage.addActor(label);
stringBuilder = new StringBuilder();
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/frustumculling/step4/FrustumCullingTest.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Array;
protected Stage stage;
protected Label label;
protected BitmapFont font;
protected StringBuilder stringBuilder;
@Override
public void create () {
stage = new Stage();
font = new BitmapFont();
label = new Label(" ", new Label.LabelStyle(font, Color.WHITE));
stage.addActor(label);
stringBuilder = new StringBuilder();
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
assets = new AssetManager(); | assets.load(data+"/invaderscene.g3db", Model.class); |
xoppa/blog | tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step9/CardGame.java | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
| import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.RenderableProvider;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectSet;
import com.badlogic.gdx.utils.Pool; | for (Card card : this) {
meshBuilder.setVertexTransform(card.transform);
meshBuilder.addMesh(card.vertices, card.indices);
}
meshBuilder.end(mesh);
renderables.add(renderable);
}
@Override
public void dispose() {
mesh.dispose();
}
}
TextureAtlas atlas;
Sprite front;
Sprite back;
PerspectiveCamera cam;
CardDeck deck;
CardBatch cards;
CameraInputController camController;
ModelBatch modelBatch;
Model tableTopModel;
ModelInstance tableTop;
Environment environment;
@Override
public void create() {
modelBatch = new ModelBatch(); | // Path: tutorials/src/com/xoppa/blog/libgdx/Main.java
// public static String data;
// Path: tutorials/src/com/xoppa/blog/libgdx/g3d/cardgame/step9/CardGame.java
import static com.xoppa.blog.libgdx.Main.data;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.RenderableProvider;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.FloatAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.ObjectSet;
import com.badlogic.gdx.utils.Pool;
for (Card card : this) {
meshBuilder.setVertexTransform(card.transform);
meshBuilder.addMesh(card.vertices, card.indices);
}
meshBuilder.end(mesh);
renderables.add(renderable);
}
@Override
public void dispose() {
mesh.dispose();
}
}
TextureAtlas atlas;
Sprite front;
Sprite back;
PerspectiveCamera cam;
CardDeck deck;
CardBatch cards;
CameraInputController camController;
ModelBatch modelBatch;
Model tableTopModel;
ModelInstance tableTop;
Environment environment;
@Override
public void create() {
modelBatch = new ModelBatch(); | atlas = new TextureAtlas(data + "/carddeck.atlas"); |
TritonHo/supportsmallshop-android | src/com/marspotato/supportsmallshop/ShopDetailActivity.java | // Path: src/com/marspotato/supportsmallshop/BO/Shop.java
// public class Shop implements Serializable {
// private static final long serialVersionUID = 1L;
//
// @Expose
// public String id;
// @Expose
// public String name;
// @Expose
// public String shortDescription;
// @Expose
// public String fullDescription;
// @Expose
// public String searchTags;
// @Expose
// public String shopType;
// @Expose
// public String openHours;
// @Expose
// public int district;
// @Expose
// public String address;
// @Expose
// public String phone;
// @Expose
// public int latitude1000000; /* the value of latitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public int longitude1000000; /* the value of longitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public String photoUrl;
// }
//
// Path: src/com/marspotato/supportsmallshop/util/Config.java
// public class Config {
// //some enum about network
// public static int WIFI_ERROR = 0;
// public static int NETWORK_ERROR = 1;
// public static int OTHERS_ERROR = 2;
//
// public static int NAME_MAX_LENGTH = 20;
// public static int SHORT_DESCRIPTION_MAX_LENGTH = 30;
// public static int FULL_DESCRIPTION_MAX_LENGTH = 200;
// public static int OPEN_HOURS_MAX_LENGTH = 100;
// public static int SEARCH_TAGS_MAX_LENGTH = 200;
// public static int ADDRESS_MAX_LENGTH = 150;
// public static int PHONE_MAX_LENGTH = 10;
//
// public final static String licenseUrl = "http://www.gnu.org/licenses/gpl-3.0.txt";
// public final static String[] shopTypes = new String[]{"食肆", "零售(食物)","零售(其他)", "服務"};
// public final static String deviceType = "google-android";
//
// public final static int DEFAULT_SEARCH_RANGE = 100;
//
// public final static int WHOLE_HK = 0;
// public final static int HK_ISLAND = 1;
// public final static int KOWL0ON = 2;
// public final static int NEW_TERRITORIES = 3;
//
// public final static int HK_NORTH_LAT1000000 = 22562222;
// public final static int HK_SOUTH_LAT1000000 = 22153889;
// public final static int HK_EAST_LNG1000000 = 114441667;
// public final static int HK_WEST_LNG1000000 = 113835278;
//
// //REMARKS: this is development purpose ID, and URL
// public static final String GCM_SENDER_ID = "458074465130";
// public static final String HOST_URL = "http://supportsmallshop1.marspotato.com//supportsmallshop";
// //public static final String HOST_URL = "http://supportsmallshop.marspotato.com/supportsmallshop";
//
// //the default http timeout
// public static final int DEFAULT_HTTP_TIMEOUT = 10000;//10000ms = 10 seconds
//
// //after the initial fail, the number of retry of http call
// public static final int DEFAULT_HTTP_MAX_RETRY = 1;
//
// //max number of image to be cached in disk
// public static final int MAX_DISK_CACHE_IMAGE = 100;
//
// public static DateTimeFormatter defaultDisplayDateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
//
// public static DateTimeFormatter defaultDateTimeFormatter = ISODateTimeFormat.basicDateTimeNoMillis();
//
// public static Gson defaultGSON = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeTypeConverter()).setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
//
// //time for a button to be disabled to avoid double action
// public static final int AVOID_DOUBLE_CLICK_PERIOD = 500;//500ms
//
// //THE time(in ms) that the progress bar will be delayed to show
// public static final int MS_GAME_PROGRESS_BAR_DELAY = 500;
//
// }
| import org.joda.time.DateTime;
import com.marspotato.supportsmallshop.BO.Shop;
import com.marspotato.supportsmallshop.util.Config;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
| package com.marspotato.supportsmallshop;
public class ShopDetailActivity extends Activity {
private static final int CHILDREN_RESULT_CODE = 0;
private String regId;
private String helperId;
| // Path: src/com/marspotato/supportsmallshop/BO/Shop.java
// public class Shop implements Serializable {
// private static final long serialVersionUID = 1L;
//
// @Expose
// public String id;
// @Expose
// public String name;
// @Expose
// public String shortDescription;
// @Expose
// public String fullDescription;
// @Expose
// public String searchTags;
// @Expose
// public String shopType;
// @Expose
// public String openHours;
// @Expose
// public int district;
// @Expose
// public String address;
// @Expose
// public String phone;
// @Expose
// public int latitude1000000; /* the value of latitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public int longitude1000000; /* the value of longitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public String photoUrl;
// }
//
// Path: src/com/marspotato/supportsmallshop/util/Config.java
// public class Config {
// //some enum about network
// public static int WIFI_ERROR = 0;
// public static int NETWORK_ERROR = 1;
// public static int OTHERS_ERROR = 2;
//
// public static int NAME_MAX_LENGTH = 20;
// public static int SHORT_DESCRIPTION_MAX_LENGTH = 30;
// public static int FULL_DESCRIPTION_MAX_LENGTH = 200;
// public static int OPEN_HOURS_MAX_LENGTH = 100;
// public static int SEARCH_TAGS_MAX_LENGTH = 200;
// public static int ADDRESS_MAX_LENGTH = 150;
// public static int PHONE_MAX_LENGTH = 10;
//
// public final static String licenseUrl = "http://www.gnu.org/licenses/gpl-3.0.txt";
// public final static String[] shopTypes = new String[]{"食肆", "零售(食物)","零售(其他)", "服務"};
// public final static String deviceType = "google-android";
//
// public final static int DEFAULT_SEARCH_RANGE = 100;
//
// public final static int WHOLE_HK = 0;
// public final static int HK_ISLAND = 1;
// public final static int KOWL0ON = 2;
// public final static int NEW_TERRITORIES = 3;
//
// public final static int HK_NORTH_LAT1000000 = 22562222;
// public final static int HK_SOUTH_LAT1000000 = 22153889;
// public final static int HK_EAST_LNG1000000 = 114441667;
// public final static int HK_WEST_LNG1000000 = 113835278;
//
// //REMARKS: this is development purpose ID, and URL
// public static final String GCM_SENDER_ID = "458074465130";
// public static final String HOST_URL = "http://supportsmallshop1.marspotato.com//supportsmallshop";
// //public static final String HOST_URL = "http://supportsmallshop.marspotato.com/supportsmallshop";
//
// //the default http timeout
// public static final int DEFAULT_HTTP_TIMEOUT = 10000;//10000ms = 10 seconds
//
// //after the initial fail, the number of retry of http call
// public static final int DEFAULT_HTTP_MAX_RETRY = 1;
//
// //max number of image to be cached in disk
// public static final int MAX_DISK_CACHE_IMAGE = 100;
//
// public static DateTimeFormatter defaultDisplayDateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
//
// public static DateTimeFormatter defaultDateTimeFormatter = ISODateTimeFormat.basicDateTimeNoMillis();
//
// public static Gson defaultGSON = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeTypeConverter()).setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
//
// //time for a button to be disabled to avoid double action
// public static final int AVOID_DOUBLE_CLICK_PERIOD = 500;//500ms
//
// //THE time(in ms) that the progress bar will be delayed to show
// public static final int MS_GAME_PROGRESS_BAR_DELAY = 500;
//
// }
// Path: src/com/marspotato/supportsmallshop/ShopDetailActivity.java
import org.joda.time.DateTime;
import com.marspotato.supportsmallshop.BO.Shop;
import com.marspotato.supportsmallshop.util.Config;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
package com.marspotato.supportsmallshop;
public class ShopDetailActivity extends Activity {
private static final int CHILDREN_RESULT_CODE = 0;
private String regId;
private String helperId;
| private Shop shop;
|
TritonHo/supportsmallshop-android | src/com/marspotato/supportsmallshop/adaptor/ShopListAdapter.java | // Path: src/com/marspotato/supportsmallshop/BO/Shop.java
// public class Shop implements Serializable {
// private static final long serialVersionUID = 1L;
//
// @Expose
// public String id;
// @Expose
// public String name;
// @Expose
// public String shortDescription;
// @Expose
// public String fullDescription;
// @Expose
// public String searchTags;
// @Expose
// public String shopType;
// @Expose
// public String openHours;
// @Expose
// public int district;
// @Expose
// public String address;
// @Expose
// public String phone;
// @Expose
// public int latitude1000000; /* the value of latitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public int longitude1000000; /* the value of longitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public String photoUrl;
// }
| import com.marspotato.supportsmallshop.R;
import com.marspotato.supportsmallshop.BO.Shop;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
| package com.marspotato.supportsmallshop.adaptor;
public class ShopListAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
| // Path: src/com/marspotato/supportsmallshop/BO/Shop.java
// public class Shop implements Serializable {
// private static final long serialVersionUID = 1L;
//
// @Expose
// public String id;
// @Expose
// public String name;
// @Expose
// public String shortDescription;
// @Expose
// public String fullDescription;
// @Expose
// public String searchTags;
// @Expose
// public String shopType;
// @Expose
// public String openHours;
// @Expose
// public int district;
// @Expose
// public String address;
// @Expose
// public String phone;
// @Expose
// public int latitude1000000; /* the value of latitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public int longitude1000000; /* the value of longitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public String photoUrl;
// }
// Path: src/com/marspotato/supportsmallshop/adaptor/ShopListAdapter.java
import com.marspotato.supportsmallshop.R;
import com.marspotato.supportsmallshop.BO.Shop;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
package com.marspotato.supportsmallshop.adaptor;
public class ShopListAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
| private Shop[] shopArray;
|
TritonHo/supportsmallshop-android | src/com/marspotato/supportsmallshop/output/CreateShopSubmissionOutput.java | // Path: src/com/marspotato/supportsmallshop/BO/CreateShopSubmission.java
// public class CreateShopSubmission implements Serializable {
// private static final long serialVersionUID = 1L;
//
//
//
// @Expose
// public String id;
// @Expose
// public String helperId;
// @Expose
// public String name;
// @Expose
// public String shortDescription;
// @Expose
// public String fullDescription;
// @Expose
// public String searchTags;
//
// @Expose
// public String shopType;
// @Expose
// public String openHours;
// @Expose
// public int district;
// @Expose
// public String address;
// @Expose
// public String phone;
// @Expose
// public int latitude1000000; /* the value of latitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public int longitude1000000; /* the value of longitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public String photoUrl;
// }
| import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.marspotato.supportsmallshop.BO.CreateShopSubmission;
| package com.marspotato.supportsmallshop.output;
public class CreateShopSubmissionOutput implements Serializable {
private static final long serialVersionUID = 1L;
@Expose
| // Path: src/com/marspotato/supportsmallshop/BO/CreateShopSubmission.java
// public class CreateShopSubmission implements Serializable {
// private static final long serialVersionUID = 1L;
//
//
//
// @Expose
// public String id;
// @Expose
// public String helperId;
// @Expose
// public String name;
// @Expose
// public String shortDescription;
// @Expose
// public String fullDescription;
// @Expose
// public String searchTags;
//
// @Expose
// public String shopType;
// @Expose
// public String openHours;
// @Expose
// public int district;
// @Expose
// public String address;
// @Expose
// public String phone;
// @Expose
// public int latitude1000000; /* the value of latitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public int longitude1000000; /* the value of longitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public String photoUrl;
// }
// Path: src/com/marspotato/supportsmallshop/output/CreateShopSubmissionOutput.java
import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.marspotato.supportsmallshop.BO.CreateShopSubmission;
package com.marspotato.supportsmallshop.output;
public class CreateShopSubmissionOutput implements Serializable {
private static final long serialVersionUID = 1L;
@Expose
| public CreateShopSubmission s;
|
TritonHo/supportsmallshop-android | src/com/marspotato/supportsmallshop/MyApplication.java | // Path: src/com/marspotato/supportsmallshop/util/Config.java
// public class Config {
// //some enum about network
// public static int WIFI_ERROR = 0;
// public static int NETWORK_ERROR = 1;
// public static int OTHERS_ERROR = 2;
//
// public static int NAME_MAX_LENGTH = 20;
// public static int SHORT_DESCRIPTION_MAX_LENGTH = 30;
// public static int FULL_DESCRIPTION_MAX_LENGTH = 200;
// public static int OPEN_HOURS_MAX_LENGTH = 100;
// public static int SEARCH_TAGS_MAX_LENGTH = 200;
// public static int ADDRESS_MAX_LENGTH = 150;
// public static int PHONE_MAX_LENGTH = 10;
//
// public final static String licenseUrl = "http://www.gnu.org/licenses/gpl-3.0.txt";
// public final static String[] shopTypes = new String[]{"食肆", "零售(食物)","零售(其他)", "服務"};
// public final static String deviceType = "google-android";
//
// public final static int DEFAULT_SEARCH_RANGE = 100;
//
// public final static int WHOLE_HK = 0;
// public final static int HK_ISLAND = 1;
// public final static int KOWL0ON = 2;
// public final static int NEW_TERRITORIES = 3;
//
// public final static int HK_NORTH_LAT1000000 = 22562222;
// public final static int HK_SOUTH_LAT1000000 = 22153889;
// public final static int HK_EAST_LNG1000000 = 114441667;
// public final static int HK_WEST_LNG1000000 = 113835278;
//
// //REMARKS: this is development purpose ID, and URL
// public static final String GCM_SENDER_ID = "458074465130";
// public static final String HOST_URL = "http://supportsmallshop1.marspotato.com//supportsmallshop";
// //public static final String HOST_URL = "http://supportsmallshop.marspotato.com/supportsmallshop";
//
// //the default http timeout
// public static final int DEFAULT_HTTP_TIMEOUT = 10000;//10000ms = 10 seconds
//
// //after the initial fail, the number of retry of http call
// public static final int DEFAULT_HTTP_MAX_RETRY = 1;
//
// //max number of image to be cached in disk
// public static final int MAX_DISK_CACHE_IMAGE = 100;
//
// public static DateTimeFormatter defaultDisplayDateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
//
// public static DateTimeFormatter defaultDateTimeFormatter = ISODateTimeFormat.basicDateTimeNoMillis();
//
// public static Gson defaultGSON = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeTypeConverter()).setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
//
// //time for a button to be disabled to avoid double action
// public static final int AVOID_DOUBLE_CLICK_PERIOD = 500;//500ms
//
// //THE time(in ms) that the progress bar will be delayed to show
// public static final int MS_GAME_PROGRESS_BAR_DELAY = 500;
//
// }
//
// Path: src/com/marspotato/supportsmallshop/util/RequestManager.java
// public class RequestManager {
//
// private static RequestManager instance;
// private RequestQueue mRequestQueue;
//
//
// private RequestManager(Context context) {
// mRequestQueue = Volley.newRequestQueue(context.getApplicationContext());
// }
// public RequestQueue getRequestQueue()
// {
// return mRequestQueue;
// }
//
// // This method should be called first to do singleton initialization
// public static synchronized RequestManager getInstance(Context context) {
// if (instance == null) {
// instance = new RequestManager(context);
// }
// return instance;
// }
//
// public static synchronized RequestManager getInstance() {
// if (instance == null) {
// throw new IllegalStateException(RequestManager.class.getSimpleName() +
// " is not initialized, call getInstance(..) method first.");
// }
// return instance;
// }
// }
| import com.marspotato.supportsmallshop.util.Config;
import com.marspotato.supportsmallshop.util.RequestManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import android.app.Application;
| package com.marspotato.supportsmallshop;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// RequestManager initialization
| // Path: src/com/marspotato/supportsmallshop/util/Config.java
// public class Config {
// //some enum about network
// public static int WIFI_ERROR = 0;
// public static int NETWORK_ERROR = 1;
// public static int OTHERS_ERROR = 2;
//
// public static int NAME_MAX_LENGTH = 20;
// public static int SHORT_DESCRIPTION_MAX_LENGTH = 30;
// public static int FULL_DESCRIPTION_MAX_LENGTH = 200;
// public static int OPEN_HOURS_MAX_LENGTH = 100;
// public static int SEARCH_TAGS_MAX_LENGTH = 200;
// public static int ADDRESS_MAX_LENGTH = 150;
// public static int PHONE_MAX_LENGTH = 10;
//
// public final static String licenseUrl = "http://www.gnu.org/licenses/gpl-3.0.txt";
// public final static String[] shopTypes = new String[]{"食肆", "零售(食物)","零售(其他)", "服務"};
// public final static String deviceType = "google-android";
//
// public final static int DEFAULT_SEARCH_RANGE = 100;
//
// public final static int WHOLE_HK = 0;
// public final static int HK_ISLAND = 1;
// public final static int KOWL0ON = 2;
// public final static int NEW_TERRITORIES = 3;
//
// public final static int HK_NORTH_LAT1000000 = 22562222;
// public final static int HK_SOUTH_LAT1000000 = 22153889;
// public final static int HK_EAST_LNG1000000 = 114441667;
// public final static int HK_WEST_LNG1000000 = 113835278;
//
// //REMARKS: this is development purpose ID, and URL
// public static final String GCM_SENDER_ID = "458074465130";
// public static final String HOST_URL = "http://supportsmallshop1.marspotato.com//supportsmallshop";
// //public static final String HOST_URL = "http://supportsmallshop.marspotato.com/supportsmallshop";
//
// //the default http timeout
// public static final int DEFAULT_HTTP_TIMEOUT = 10000;//10000ms = 10 seconds
//
// //after the initial fail, the number of retry of http call
// public static final int DEFAULT_HTTP_MAX_RETRY = 1;
//
// //max number of image to be cached in disk
// public static final int MAX_DISK_CACHE_IMAGE = 100;
//
// public static DateTimeFormatter defaultDisplayDateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
//
// public static DateTimeFormatter defaultDateTimeFormatter = ISODateTimeFormat.basicDateTimeNoMillis();
//
// public static Gson defaultGSON = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeTypeConverter()).setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
//
// //time for a button to be disabled to avoid double action
// public static final int AVOID_DOUBLE_CLICK_PERIOD = 500;//500ms
//
// //THE time(in ms) that the progress bar will be delayed to show
// public static final int MS_GAME_PROGRESS_BAR_DELAY = 500;
//
// }
//
// Path: src/com/marspotato/supportsmallshop/util/RequestManager.java
// public class RequestManager {
//
// private static RequestManager instance;
// private RequestQueue mRequestQueue;
//
//
// private RequestManager(Context context) {
// mRequestQueue = Volley.newRequestQueue(context.getApplicationContext());
// }
// public RequestQueue getRequestQueue()
// {
// return mRequestQueue;
// }
//
// // This method should be called first to do singleton initialization
// public static synchronized RequestManager getInstance(Context context) {
// if (instance == null) {
// instance = new RequestManager(context);
// }
// return instance;
// }
//
// public static synchronized RequestManager getInstance() {
// if (instance == null) {
// throw new IllegalStateException(RequestManager.class.getSimpleName() +
// " is not initialized, call getInstance(..) method first.");
// }
// return instance;
// }
// }
// Path: src/com/marspotato/supportsmallshop/MyApplication.java
import com.marspotato.supportsmallshop.util.Config;
import com.marspotato.supportsmallshop.util.RequestManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import android.app.Application;
package com.marspotato.supportsmallshop;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// RequestManager initialization
| RequestManager.getInstance(getApplicationContext());
|
TritonHo/supportsmallshop-android | src/com/marspotato/supportsmallshop/MyApplication.java | // Path: src/com/marspotato/supportsmallshop/util/Config.java
// public class Config {
// //some enum about network
// public static int WIFI_ERROR = 0;
// public static int NETWORK_ERROR = 1;
// public static int OTHERS_ERROR = 2;
//
// public static int NAME_MAX_LENGTH = 20;
// public static int SHORT_DESCRIPTION_MAX_LENGTH = 30;
// public static int FULL_DESCRIPTION_MAX_LENGTH = 200;
// public static int OPEN_HOURS_MAX_LENGTH = 100;
// public static int SEARCH_TAGS_MAX_LENGTH = 200;
// public static int ADDRESS_MAX_LENGTH = 150;
// public static int PHONE_MAX_LENGTH = 10;
//
// public final static String licenseUrl = "http://www.gnu.org/licenses/gpl-3.0.txt";
// public final static String[] shopTypes = new String[]{"食肆", "零售(食物)","零售(其他)", "服務"};
// public final static String deviceType = "google-android";
//
// public final static int DEFAULT_SEARCH_RANGE = 100;
//
// public final static int WHOLE_HK = 0;
// public final static int HK_ISLAND = 1;
// public final static int KOWL0ON = 2;
// public final static int NEW_TERRITORIES = 3;
//
// public final static int HK_NORTH_LAT1000000 = 22562222;
// public final static int HK_SOUTH_LAT1000000 = 22153889;
// public final static int HK_EAST_LNG1000000 = 114441667;
// public final static int HK_WEST_LNG1000000 = 113835278;
//
// //REMARKS: this is development purpose ID, and URL
// public static final String GCM_SENDER_ID = "458074465130";
// public static final String HOST_URL = "http://supportsmallshop1.marspotato.com//supportsmallshop";
// //public static final String HOST_URL = "http://supportsmallshop.marspotato.com/supportsmallshop";
//
// //the default http timeout
// public static final int DEFAULT_HTTP_TIMEOUT = 10000;//10000ms = 10 seconds
//
// //after the initial fail, the number of retry of http call
// public static final int DEFAULT_HTTP_MAX_RETRY = 1;
//
// //max number of image to be cached in disk
// public static final int MAX_DISK_CACHE_IMAGE = 100;
//
// public static DateTimeFormatter defaultDisplayDateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
//
// public static DateTimeFormatter defaultDateTimeFormatter = ISODateTimeFormat.basicDateTimeNoMillis();
//
// public static Gson defaultGSON = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeTypeConverter()).setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
//
// //time for a button to be disabled to avoid double action
// public static final int AVOID_DOUBLE_CLICK_PERIOD = 500;//500ms
//
// //THE time(in ms) that the progress bar will be delayed to show
// public static final int MS_GAME_PROGRESS_BAR_DELAY = 500;
//
// }
//
// Path: src/com/marspotato/supportsmallshop/util/RequestManager.java
// public class RequestManager {
//
// private static RequestManager instance;
// private RequestQueue mRequestQueue;
//
//
// private RequestManager(Context context) {
// mRequestQueue = Volley.newRequestQueue(context.getApplicationContext());
// }
// public RequestQueue getRequestQueue()
// {
// return mRequestQueue;
// }
//
// // This method should be called first to do singleton initialization
// public static synchronized RequestManager getInstance(Context context) {
// if (instance == null) {
// instance = new RequestManager(context);
// }
// return instance;
// }
//
// public static synchronized RequestManager getInstance() {
// if (instance == null) {
// throw new IllegalStateException(RequestManager.class.getSimpleName() +
// " is not initialized, call getInstance(..) method first.");
// }
// return instance;
// }
// }
| import com.marspotato.supportsmallshop.util.Config;
import com.marspotato.supportsmallshop.util.RequestManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import android.app.Application;
| package com.marspotato.supportsmallshop;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// RequestManager initialization
RequestManager.getInstance(getApplicationContext());
// Create global configuration and initialize ImageLoader with this configuration
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.memoryCacheSizePercentage(5) //only use 5 percent of memory for image cache
| // Path: src/com/marspotato/supportsmallshop/util/Config.java
// public class Config {
// //some enum about network
// public static int WIFI_ERROR = 0;
// public static int NETWORK_ERROR = 1;
// public static int OTHERS_ERROR = 2;
//
// public static int NAME_MAX_LENGTH = 20;
// public static int SHORT_DESCRIPTION_MAX_LENGTH = 30;
// public static int FULL_DESCRIPTION_MAX_LENGTH = 200;
// public static int OPEN_HOURS_MAX_LENGTH = 100;
// public static int SEARCH_TAGS_MAX_LENGTH = 200;
// public static int ADDRESS_MAX_LENGTH = 150;
// public static int PHONE_MAX_LENGTH = 10;
//
// public final static String licenseUrl = "http://www.gnu.org/licenses/gpl-3.0.txt";
// public final static String[] shopTypes = new String[]{"食肆", "零售(食物)","零售(其他)", "服務"};
// public final static String deviceType = "google-android";
//
// public final static int DEFAULT_SEARCH_RANGE = 100;
//
// public final static int WHOLE_HK = 0;
// public final static int HK_ISLAND = 1;
// public final static int KOWL0ON = 2;
// public final static int NEW_TERRITORIES = 3;
//
// public final static int HK_NORTH_LAT1000000 = 22562222;
// public final static int HK_SOUTH_LAT1000000 = 22153889;
// public final static int HK_EAST_LNG1000000 = 114441667;
// public final static int HK_WEST_LNG1000000 = 113835278;
//
// //REMARKS: this is development purpose ID, and URL
// public static final String GCM_SENDER_ID = "458074465130";
// public static final String HOST_URL = "http://supportsmallshop1.marspotato.com//supportsmallshop";
// //public static final String HOST_URL = "http://supportsmallshop.marspotato.com/supportsmallshop";
//
// //the default http timeout
// public static final int DEFAULT_HTTP_TIMEOUT = 10000;//10000ms = 10 seconds
//
// //after the initial fail, the number of retry of http call
// public static final int DEFAULT_HTTP_MAX_RETRY = 1;
//
// //max number of image to be cached in disk
// public static final int MAX_DISK_CACHE_IMAGE = 100;
//
// public static DateTimeFormatter defaultDisplayDateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
//
// public static DateTimeFormatter defaultDateTimeFormatter = ISODateTimeFormat.basicDateTimeNoMillis();
//
// public static Gson defaultGSON = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeTypeConverter()).setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
//
// //time for a button to be disabled to avoid double action
// public static final int AVOID_DOUBLE_CLICK_PERIOD = 500;//500ms
//
// //THE time(in ms) that the progress bar will be delayed to show
// public static final int MS_GAME_PROGRESS_BAR_DELAY = 500;
//
// }
//
// Path: src/com/marspotato/supportsmallshop/util/RequestManager.java
// public class RequestManager {
//
// private static RequestManager instance;
// private RequestQueue mRequestQueue;
//
//
// private RequestManager(Context context) {
// mRequestQueue = Volley.newRequestQueue(context.getApplicationContext());
// }
// public RequestQueue getRequestQueue()
// {
// return mRequestQueue;
// }
//
// // This method should be called first to do singleton initialization
// public static synchronized RequestManager getInstance(Context context) {
// if (instance == null) {
// instance = new RequestManager(context);
// }
// return instance;
// }
//
// public static synchronized RequestManager getInstance() {
// if (instance == null) {
// throw new IllegalStateException(RequestManager.class.getSimpleName() +
// " is not initialized, call getInstance(..) method first.");
// }
// return instance;
// }
// }
// Path: src/com/marspotato/supportsmallshop/MyApplication.java
import com.marspotato.supportsmallshop.util.Config;
import com.marspotato.supportsmallshop.util.RequestManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import android.app.Application;
package com.marspotato.supportsmallshop;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// RequestManager initialization
RequestManager.getInstance(getApplicationContext());
// Create global configuration and initialize ImageLoader with this configuration
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.memoryCacheSizePercentage(5) //only use 5 percent of memory for image cache
| .diskCacheFileCount(Config.MAX_DISK_CACHE_IMAGE) //limit the disc to store at most 100 image only
|
TritonHo/supportsmallshop-android | src/com/marspotato/supportsmallshop/util/AuthCodeUtil.java | // Path: src/com/marspotato/supportsmallshop/output/Dummy.java
// public class Dummy {
// //a silly but working method to check if the network redirected by WIFI.
// //remarks: it can check WIFI redirect only, is not used for defends man-in-middle
//
// @Expose
// public int intColumn;
// @Expose
// public String stringColumn;
//
// public void checkValid() throws Exception
// {
// if (intColumn != 123 || "456".equals(stringColumn) == false)
// throw new Exception("Wrong dummyJson" );
// }
// }
| import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.joda.time.DateTime;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.marspotato.supportsmallshop.output.Dummy; | package com.marspotato.supportsmallshop.util;
public class AuthCodeUtil {
public static void sendAuthCodeRequest(final AuthCodeRequester receiver, String regId)
{
Response.Listener<String> listener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try { | // Path: src/com/marspotato/supportsmallshop/output/Dummy.java
// public class Dummy {
// //a silly but working method to check if the network redirected by WIFI.
// //remarks: it can check WIFI redirect only, is not used for defends man-in-middle
//
// @Expose
// public int intColumn;
// @Expose
// public String stringColumn;
//
// public void checkValid() throws Exception
// {
// if (intColumn != 123 || "456".equals(stringColumn) == false)
// throw new Exception("Wrong dummyJson" );
// }
// }
// Path: src/com/marspotato/supportsmallshop/util/AuthCodeUtil.java
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.joda.time.DateTime;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.marspotato.supportsmallshop.output.Dummy;
package com.marspotato.supportsmallshop.util;
public class AuthCodeUtil {
public static void sendAuthCodeRequest(final AuthCodeRequester receiver, String regId)
{
Response.Listener<String> listener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try { | Dummy dummy = Config.defaultGSON.fromJson(response, Dummy.class); |
TritonHo/supportsmallshop-android | src/com/marspotato/supportsmallshop/output/UpdateShopSubmissionOutput.java | // Path: src/com/marspotato/supportsmallshop/BO/Shop.java
// public class Shop implements Serializable {
// private static final long serialVersionUID = 1L;
//
// @Expose
// public String id;
// @Expose
// public String name;
// @Expose
// public String shortDescription;
// @Expose
// public String fullDescription;
// @Expose
// public String searchTags;
// @Expose
// public String shopType;
// @Expose
// public String openHours;
// @Expose
// public int district;
// @Expose
// public String address;
// @Expose
// public String phone;
// @Expose
// public int latitude1000000; /* the value of latitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public int longitude1000000; /* the value of longitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public String photoUrl;
// }
//
// Path: src/com/marspotato/supportsmallshop/BO/UpdateShopSubmission.java
// public class UpdateShopSubmission implements Serializable {
// private static final long serialVersionUID = 1L;
//
// @Expose
// public String shopId;
// @Expose
// public boolean updateShopType;
// @Expose
// public boolean updateDistrict;
// @Expose
// public boolean updateLocation;
//
// @Expose
// public String id;
// @Expose
// public String helperId;
// @Expose
// public String name;
// @Expose
// public String shortDescription;
// @Expose
// public String fullDescription;
// @Expose
// public String searchTags;
//
// @Expose
// public String shopType;
// @Expose
// public String openHours;
// @Expose
// public int district;
// @Expose
// public String address;
// @Expose
// public String phone;
// @Expose
// public int latitude1000000; /* the value of latitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public int longitude1000000; /* the value of longitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public String photoUrl;
// }
| import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.marspotato.supportsmallshop.BO.Shop;
import com.marspotato.supportsmallshop.BO.UpdateShopSubmission;
| package com.marspotato.supportsmallshop.output;
public class UpdateShopSubmissionOutput implements Serializable {
private static final long serialVersionUID = 1L;
@Expose
| // Path: src/com/marspotato/supportsmallshop/BO/Shop.java
// public class Shop implements Serializable {
// private static final long serialVersionUID = 1L;
//
// @Expose
// public String id;
// @Expose
// public String name;
// @Expose
// public String shortDescription;
// @Expose
// public String fullDescription;
// @Expose
// public String searchTags;
// @Expose
// public String shopType;
// @Expose
// public String openHours;
// @Expose
// public int district;
// @Expose
// public String address;
// @Expose
// public String phone;
// @Expose
// public int latitude1000000; /* the value of latitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public int longitude1000000; /* the value of longitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public String photoUrl;
// }
//
// Path: src/com/marspotato/supportsmallshop/BO/UpdateShopSubmission.java
// public class UpdateShopSubmission implements Serializable {
// private static final long serialVersionUID = 1L;
//
// @Expose
// public String shopId;
// @Expose
// public boolean updateShopType;
// @Expose
// public boolean updateDistrict;
// @Expose
// public boolean updateLocation;
//
// @Expose
// public String id;
// @Expose
// public String helperId;
// @Expose
// public String name;
// @Expose
// public String shortDescription;
// @Expose
// public String fullDescription;
// @Expose
// public String searchTags;
//
// @Expose
// public String shopType;
// @Expose
// public String openHours;
// @Expose
// public int district;
// @Expose
// public String address;
// @Expose
// public String phone;
// @Expose
// public int latitude1000000; /* the value of latitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public int longitude1000000; /* the value of longitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public String photoUrl;
// }
// Path: src/com/marspotato/supportsmallshop/output/UpdateShopSubmissionOutput.java
import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.marspotato.supportsmallshop.BO.Shop;
import com.marspotato.supportsmallshop.BO.UpdateShopSubmission;
package com.marspotato.supportsmallshop.output;
public class UpdateShopSubmissionOutput implements Serializable {
private static final long serialVersionUID = 1L;
@Expose
| public UpdateShopSubmission s;
|
TritonHo/supportsmallshop-android | src/com/marspotato/supportsmallshop/output/UpdateShopSubmissionOutput.java | // Path: src/com/marspotato/supportsmallshop/BO/Shop.java
// public class Shop implements Serializable {
// private static final long serialVersionUID = 1L;
//
// @Expose
// public String id;
// @Expose
// public String name;
// @Expose
// public String shortDescription;
// @Expose
// public String fullDescription;
// @Expose
// public String searchTags;
// @Expose
// public String shopType;
// @Expose
// public String openHours;
// @Expose
// public int district;
// @Expose
// public String address;
// @Expose
// public String phone;
// @Expose
// public int latitude1000000; /* the value of latitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public int longitude1000000; /* the value of longitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public String photoUrl;
// }
//
// Path: src/com/marspotato/supportsmallshop/BO/UpdateShopSubmission.java
// public class UpdateShopSubmission implements Serializable {
// private static final long serialVersionUID = 1L;
//
// @Expose
// public String shopId;
// @Expose
// public boolean updateShopType;
// @Expose
// public boolean updateDistrict;
// @Expose
// public boolean updateLocation;
//
// @Expose
// public String id;
// @Expose
// public String helperId;
// @Expose
// public String name;
// @Expose
// public String shortDescription;
// @Expose
// public String fullDescription;
// @Expose
// public String searchTags;
//
// @Expose
// public String shopType;
// @Expose
// public String openHours;
// @Expose
// public int district;
// @Expose
// public String address;
// @Expose
// public String phone;
// @Expose
// public int latitude1000000; /* the value of latitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public int longitude1000000; /* the value of longitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public String photoUrl;
// }
| import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.marspotato.supportsmallshop.BO.Shop;
import com.marspotato.supportsmallshop.BO.UpdateShopSubmission;
| package com.marspotato.supportsmallshop.output;
public class UpdateShopSubmissionOutput implements Serializable {
private static final long serialVersionUID = 1L;
@Expose
public UpdateShopSubmission s;
@Expose
| // Path: src/com/marspotato/supportsmallshop/BO/Shop.java
// public class Shop implements Serializable {
// private static final long serialVersionUID = 1L;
//
// @Expose
// public String id;
// @Expose
// public String name;
// @Expose
// public String shortDescription;
// @Expose
// public String fullDescription;
// @Expose
// public String searchTags;
// @Expose
// public String shopType;
// @Expose
// public String openHours;
// @Expose
// public int district;
// @Expose
// public String address;
// @Expose
// public String phone;
// @Expose
// public int latitude1000000; /* the value of latitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public int longitude1000000; /* the value of longitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public String photoUrl;
// }
//
// Path: src/com/marspotato/supportsmallshop/BO/UpdateShopSubmission.java
// public class UpdateShopSubmission implements Serializable {
// private static final long serialVersionUID = 1L;
//
// @Expose
// public String shopId;
// @Expose
// public boolean updateShopType;
// @Expose
// public boolean updateDistrict;
// @Expose
// public boolean updateLocation;
//
// @Expose
// public String id;
// @Expose
// public String helperId;
// @Expose
// public String name;
// @Expose
// public String shortDescription;
// @Expose
// public String fullDescription;
// @Expose
// public String searchTags;
//
// @Expose
// public String shopType;
// @Expose
// public String openHours;
// @Expose
// public int district;
// @Expose
// public String address;
// @Expose
// public String phone;
// @Expose
// public int latitude1000000; /* the value of latitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public int longitude1000000; /* the value of longitude * 1000000, the Accuracy is ~0.1m */
// @Expose
// public String photoUrl;
// }
// Path: src/com/marspotato/supportsmallshop/output/UpdateShopSubmissionOutput.java
import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.marspotato.supportsmallshop.BO.Shop;
import com.marspotato.supportsmallshop.BO.UpdateShopSubmission;
package com.marspotato.supportsmallshop.output;
public class UpdateShopSubmissionOutput implements Serializable {
private static final long serialVersionUID = 1L;
@Expose
public UpdateShopSubmission s;
@Expose
| public Shop shop;
|
TritonHo/supportsmallshop-android | src/com/marspotato/supportsmallshop/adaptor/SubmissionListAdapter.java | // Path: src/com/marspotato/supportsmallshop/BO/GenericSubmission.java
// public class GenericSubmission {
// public static final int CREATE_TYPE = 1;
// public static final int UPDATE_TYPE = 2;
// public static final int DELETE_TYPE = 3;
//
// @Expose
// public int submissionType;
// @Expose
// public String submissionId;//null for CreateShopSubmission
// @Expose
// public String shopName;
// @Expose
// public String shopShortDesc;
// }
| import com.marspotato.supportsmallshop.R;
import com.marspotato.supportsmallshop.BO.GenericSubmission;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
| package com.marspotato.supportsmallshop.adaptor;
public class SubmissionListAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
| // Path: src/com/marspotato/supportsmallshop/BO/GenericSubmission.java
// public class GenericSubmission {
// public static final int CREATE_TYPE = 1;
// public static final int UPDATE_TYPE = 2;
// public static final int DELETE_TYPE = 3;
//
// @Expose
// public int submissionType;
// @Expose
// public String submissionId;//null for CreateShopSubmission
// @Expose
// public String shopName;
// @Expose
// public String shopShortDesc;
// }
// Path: src/com/marspotato/supportsmallshop/adaptor/SubmissionListAdapter.java
import com.marspotato.supportsmallshop.R;
import com.marspotato.supportsmallshop.BO.GenericSubmission;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
package com.marspotato.supportsmallshop.adaptor;
public class SubmissionListAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
| private GenericSubmission[] gsArray;
|
confluentinc/rest-utils | core/src/main/java/io/confluent/rest/RestConfig.java | // Path: core/src/main/java/io/confluent/rest/extension/ResourceExtension.java
// public interface ResourceExtension<AppT extends Application<? extends RestConfig>>
// extends Closeable {
//
// /**
// * Called to register the extension's resources when the rest server starts up.
// *
// * @param config the configuration used to register resources
// * @param app the application.
// */
// void register(Configurable<?> config, AppT app);
//
// @SuppressWarnings("RedundantThrows")
// default void close() throws IOException {
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/metrics/RestMetricsContext.java
// public final class RestMetricsContext implements MetricsContext {
// /**
// * Client or Service's metadata map.
// */
// private final Map<String, String> contextLabels;
//
// public RestMetricsContext(String namespace,
// Map<String, Object> config) {
// contextLabels = new HashMap<>();
// contextLabels.put(MetricsContext.NAMESPACE, namespace);
// config.forEach((key, value) -> contextLabels.put(key, value.toString()));
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// this.contextLabels.put(labelKey, labelValue);
// }
//
// public void setLabels(Map<String, String> labels) {
// labels.forEach(this::setLabel);
// }
//
// /**
// * Returns the value associated with the specified label else
// * {@code null}.
// */
// public String getLabel(String label) {
// return contextLabels.get(label);
// }
//
// /**
// * Returns {@link MetricsContext} as an unmodifiable Map.
// */
// @Override
// public Map<String, String> contextLabels() {
// return Collections.unmodifiableMap(contextLabels);
// }
// }
| import io.confluent.rest.extension.ResourceExtension;
import io.confluent.rest.metrics.RestMetricsContext;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.kafka.common.config.AbstractConfig;
import org.apache.kafka.common.config.ConfigException;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigDef.Type;
import org.apache.kafka.common.config.ConfigDef.Importance;
import org.apache.kafka.common.utils.Time;
import static java.util.Collections.emptyList;
import static org.apache.kafka.clients.CommonClientConfigs.METRICS_CONTEXT_PREFIX; | public static final ConfigDef.ValidString AUTHENTICATION_METHOD_VALIDATOR =
ConfigDef.ValidString.in(
AUTHENTICATION_METHOD_NONE,
AUTHENTICATION_METHOD_BASIC,
AUTHENTICATION_METHOD_BEARER
);
public static final String AUTHENTICATION_REALM_CONFIG = "authentication.realm";
public static final String AUTHENTICATION_REALM_DOC =
"Security realm to be used in authentication.";
public static final String AUTHENTICATION_ROLES_CONFIG = "authentication.roles";
public static final String AUTHENTICATION_ROLES_DOC = "Valid roles to authenticate against.";
public static final List<String> AUTHENTICATION_ROLES_DEFAULT =
Collections.unmodifiableList(Arrays.asList("*"));
public static final String AUTHENTICATION_SKIP_PATHS = "authentication.skip.paths";
public static final String AUTHENTICATION_SKIP_PATHS_DOC = "Comma separated list of paths that "
+ "can be "
+ "accessed without authentication";
public static final String AUTHENTICATION_SKIP_PATHS_DEFAULT = "";
public static final String WEBSOCKET_PATH_PREFIX_CONFIG = "websocket.path.prefix";
public static final String WEBSOCKET_PATH_PREFIX_DOC =
"Path under which this app can register websocket endpoints.";
public static final String ENABLE_GZIP_COMPRESSION_CONFIG = "compression.enable";
protected static final String ENABLE_GZIP_COMPRESSION_DOC = "Enable gzip compression";
private static final boolean ENABLE_GZIP_COMPRESSION_DEFAULT = true;
public static final String RESOURCE_EXTENSION_CLASSES_CONFIG = "resource.extension.classes";
private static final String RESOURCE_EXTENSION_CLASSES_DOC = "" | // Path: core/src/main/java/io/confluent/rest/extension/ResourceExtension.java
// public interface ResourceExtension<AppT extends Application<? extends RestConfig>>
// extends Closeable {
//
// /**
// * Called to register the extension's resources when the rest server starts up.
// *
// * @param config the configuration used to register resources
// * @param app the application.
// */
// void register(Configurable<?> config, AppT app);
//
// @SuppressWarnings("RedundantThrows")
// default void close() throws IOException {
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/metrics/RestMetricsContext.java
// public final class RestMetricsContext implements MetricsContext {
// /**
// * Client or Service's metadata map.
// */
// private final Map<String, String> contextLabels;
//
// public RestMetricsContext(String namespace,
// Map<String, Object> config) {
// contextLabels = new HashMap<>();
// contextLabels.put(MetricsContext.NAMESPACE, namespace);
// config.forEach((key, value) -> contextLabels.put(key, value.toString()));
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// this.contextLabels.put(labelKey, labelValue);
// }
//
// public void setLabels(Map<String, String> labels) {
// labels.forEach(this::setLabel);
// }
//
// /**
// * Returns the value associated with the specified label else
// * {@code null}.
// */
// public String getLabel(String label) {
// return contextLabels.get(label);
// }
//
// /**
// * Returns {@link MetricsContext} as an unmodifiable Map.
// */
// @Override
// public Map<String, String> contextLabels() {
// return Collections.unmodifiableMap(contextLabels);
// }
// }
// Path: core/src/main/java/io/confluent/rest/RestConfig.java
import io.confluent.rest.extension.ResourceExtension;
import io.confluent.rest.metrics.RestMetricsContext;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.kafka.common.config.AbstractConfig;
import org.apache.kafka.common.config.ConfigException;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigDef.Type;
import org.apache.kafka.common.config.ConfigDef.Importance;
import org.apache.kafka.common.utils.Time;
import static java.util.Collections.emptyList;
import static org.apache.kafka.clients.CommonClientConfigs.METRICS_CONTEXT_PREFIX;
public static final ConfigDef.ValidString AUTHENTICATION_METHOD_VALIDATOR =
ConfigDef.ValidString.in(
AUTHENTICATION_METHOD_NONE,
AUTHENTICATION_METHOD_BASIC,
AUTHENTICATION_METHOD_BEARER
);
public static final String AUTHENTICATION_REALM_CONFIG = "authentication.realm";
public static final String AUTHENTICATION_REALM_DOC =
"Security realm to be used in authentication.";
public static final String AUTHENTICATION_ROLES_CONFIG = "authentication.roles";
public static final String AUTHENTICATION_ROLES_DOC = "Valid roles to authenticate against.";
public static final List<String> AUTHENTICATION_ROLES_DEFAULT =
Collections.unmodifiableList(Arrays.asList("*"));
public static final String AUTHENTICATION_SKIP_PATHS = "authentication.skip.paths";
public static final String AUTHENTICATION_SKIP_PATHS_DOC = "Comma separated list of paths that "
+ "can be "
+ "accessed without authentication";
public static final String AUTHENTICATION_SKIP_PATHS_DEFAULT = "";
public static final String WEBSOCKET_PATH_PREFIX_CONFIG = "websocket.path.prefix";
public static final String WEBSOCKET_PATH_PREFIX_DOC =
"Path under which this app can register websocket endpoints.";
public static final String ENABLE_GZIP_COMPRESSION_CONFIG = "compression.enable";
protected static final String ENABLE_GZIP_COMPRESSION_DOC = "Enable gzip compression";
private static final boolean ENABLE_GZIP_COMPRESSION_DEFAULT = true;
public static final String RESOURCE_EXTENSION_CLASSES_CONFIG = "resource.extension.classes";
private static final String RESOURCE_EXTENSION_CLASSES_DOC = "" | + "Zero or more classes that implement '" + ResourceExtension.class.getName() |
confluentinc/rest-utils | core/src/test/java/io/confluent/rest/JsonMappingExceptionMapperTest.java | // Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/JsonMappingExceptionMapper.java
// @Provider
// public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {
//
// public static final int BAD_REQUEST_CODE = 400;
//
// @Override
// public Response toResponse(JsonMappingException exception) {
// ErrorMessage message = new ErrorMessage(
// BAD_REQUEST_CODE,
// exception.getMessage()
// );
//
// return Response.status(BAD_REQUEST_CODE)
// .entity(message)
// .build();
// }
// }
| import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.exceptions.JsonMappingExceptionMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.ws.rs.core.Response;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail; | /*
* Copyright 2021 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest;
public class JsonMappingExceptionMapperTest {
private JsonMappingExceptionMapper mapper;
@BeforeEach
public void setUp() {
mapper = new JsonMappingExceptionMapper();
}
@Test
public void testJsonMappingException() {
try {
String json = "{\"name\":{}}";
ObjectMapper mapper = new ObjectMapper();
// try to parse a json where the User name is expecting a string but input an Object
mapper.reader().forType(User.class).readValue(json);
} catch (JsonMappingException e) {
Response response = mapper.toResponse(e);
assertEquals(400, response.getStatus()); | // Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/JsonMappingExceptionMapper.java
// @Provider
// public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {
//
// public static final int BAD_REQUEST_CODE = 400;
//
// @Override
// public Response toResponse(JsonMappingException exception) {
// ErrorMessage message = new ErrorMessage(
// BAD_REQUEST_CODE,
// exception.getMessage()
// );
//
// return Response.status(BAD_REQUEST_CODE)
// .entity(message)
// .build();
// }
// }
// Path: core/src/test/java/io/confluent/rest/JsonMappingExceptionMapperTest.java
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.exceptions.JsonMappingExceptionMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.ws.rs.core.Response;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
/*
* Copyright 2021 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest;
public class JsonMappingExceptionMapperTest {
private JsonMappingExceptionMapper mapper;
@BeforeEach
public void setUp() {
mapper = new JsonMappingExceptionMapper();
}
@Test
public void testJsonMappingException() {
try {
String json = "{\"name\":{}}";
ObjectMapper mapper = new ObjectMapper();
// try to parse a json where the User name is expecting a string but input an Object
mapper.reader().forType(User.class).readValue(json);
} catch (JsonMappingException e) {
Response response = mapper.toResponse(e);
assertEquals(400, response.getStatus()); | ErrorMessage out = (ErrorMessage)response.getEntity(); |
confluentinc/rest-utils | core/src/test/java/io/confluent/rest/metrics/MetricsResourceMethodApplicationListenerIntegrationTest.java | // Path: core/src/main/java/io/confluent/rest/metrics/MetricsResourceMethodApplicationListener.java
// protected static final String HTTP_STATUS_CODE_TAG = "http_status_code";
| import io.confluent.rest.*;
import org.apache.kafka.common.metrics.KafkaMetric;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.glassfish.jersey.server.ServerProperties;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import static io.confluent.rest.metrics.MetricsResourceMethodApplicationListener.HTTP_STATUS_CODE_TAG;
import static org.junit.jupiter.api.Assertions.*; |
@Test
public void testExceptionMetrics() {
Response response = ClientBuilder.newClient(app.resourceConfig.getConfiguration())
.target(server.getURI())
.path("/private/fake")
.request(MediaType.APPLICATION_JSON_TYPE)
.get();
assertEquals(404, response.getStatus());
ClientBuilder.newClient(app.resourceConfig.getConfiguration())
.target(server.getURI())
.path("/private/fake")
.request(MediaType.APPLICATION_JSON_TYPE)
.get();
//checkpoints ensure that all the assertions are tested
int rateCheckpoint4xx = 0;
int windowCheckpoint4xx = 0;
int rateCheckpointNot4xx = 0;
int windowCheckpointNot4xx = 0;
int anyErrorRateCheckpoint = 0;
int anyErrorWindowCheckpoint = 0;
for (KafkaMetric metric : TestMetricsReporter.getMetricTimeseries()) {
if (metric.metricName().name().equals("request-error-rate")) {
assertTrue(metric.measurable().toString().toLowerCase().startsWith("rate"));
Object metricValue = metric.metricValue();
assertTrue(metricValue instanceof Double, "Error rate metrics should be measurable");
double errorRateValue = (double) metricValue; | // Path: core/src/main/java/io/confluent/rest/metrics/MetricsResourceMethodApplicationListener.java
// protected static final String HTTP_STATUS_CODE_TAG = "http_status_code";
// Path: core/src/test/java/io/confluent/rest/metrics/MetricsResourceMethodApplicationListenerIntegrationTest.java
import io.confluent.rest.*;
import org.apache.kafka.common.metrics.KafkaMetric;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.glassfish.jersey.server.ServerProperties;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import static io.confluent.rest.metrics.MetricsResourceMethodApplicationListener.HTTP_STATUS_CODE_TAG;
import static org.junit.jupiter.api.Assertions.*;
@Test
public void testExceptionMetrics() {
Response response = ClientBuilder.newClient(app.resourceConfig.getConfiguration())
.target(server.getURI())
.path("/private/fake")
.request(MediaType.APPLICATION_JSON_TYPE)
.get();
assertEquals(404, response.getStatus());
ClientBuilder.newClient(app.resourceConfig.getConfiguration())
.target(server.getURI())
.path("/private/fake")
.request(MediaType.APPLICATION_JSON_TYPE)
.get();
//checkpoints ensure that all the assertions are tested
int rateCheckpoint4xx = 0;
int windowCheckpoint4xx = 0;
int rateCheckpointNot4xx = 0;
int windowCheckpointNot4xx = 0;
int anyErrorRateCheckpoint = 0;
int anyErrorWindowCheckpoint = 0;
for (KafkaMetric metric : TestMetricsReporter.getMetricTimeseries()) {
if (metric.metricName().name().equals("request-error-rate")) {
assertTrue(metric.measurable().toString().toLowerCase().startsWith("rate"));
Object metricValue = metric.metricValue();
assertTrue(metricValue instanceof Double, "Error rate metrics should be measurable");
double errorRateValue = (double) metricValue; | if (metric.metricName().tags().getOrDefault(HTTP_STATUS_CODE_TAG, "").equals("4xx")) { |
confluentinc/rest-utils | core/src/test/java/io/confluent/rest/WebApplicationExceptionMapperTest.java | // Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestException.java
// public class RestException extends WebApplicationException {
//
// private int errorCode;
//
// public RestException(final String message, final int status, final int errorCode) {
// this(message, status, errorCode, (Throwable) null);
// }
//
// public RestException(final String message, final int status, final int errorCode,
// final Throwable cause) {
// super(message, cause, status);
// this.errorCode = errorCode;
// }
//
// public int getStatus() {
// return getResponse().getStatus();
// }
//
// public int getErrorCode() {
// return errorCode;
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/WebApplicationExceptionMapper.java
// public class WebApplicationExceptionMapper
// extends DebuggableExceptionMapper<WebApplicationException> {
//
// @Context
// HttpHeaders headers;
//
// public WebApplicationExceptionMapper(RestConfig restConfig) {
// super(restConfig);
// }
//
// @Override
// public Response toResponse(WebApplicationException exc) {
// // WebApplicationException unfortunately doesn't expose the status, or even status code,
// // directly.
// Response.StatusType status = Response.Status.fromStatusCode(exc.getResponse().getStatus());
//
//
//
// // The human-readable message for these can use the exception message directly. Since
// // WebApplicationExceptions are expected to be passed back to users, it will either contain a
// // situation-specific message or the HTTP status message
// int errorCode = (exc instanceof RestException) ? ((RestException)exc).getErrorCode()
// : status.getStatusCode();
//
// // Response.Status does not contain all http status. This results in
// // status to be null above for the cases of some valid 4xx status i.e 422.
// // Below we are trying to replace the null with the status passed in the exception itself
//
// Response.ResponseBuilder response = createResponse(exc, errorCode,
// status != null ? status :
// new HttpStatus(exc.getResponse().getStatus(), exc.getMessage()),
// exc.getMessage());
//
// // Apparently, 415 Unsupported Media Type errors disable content negotiation in Jersey, which
// // causes use to return data without a content type. Work around this by detecting that specific
// // type of error and performing the negotiation manually.
// if (status == Response.Status.UNSUPPORTED_MEDIA_TYPE) {
// response.type(negotiateContentType());
// }
//
// return response.build();
// }
//
// private String negotiateContentType() {
// List<MediaType> acceptable = headers.getAcceptableMediaTypes();
// for (MediaType mt : acceptable) {
// for (String providable : restConfig.getList(RestConfig.RESPONSE_MEDIATYPE_PREFERRED_CONFIG)) {
// if (mt.toString().equals(providable)) {
// return providable;
// }
// }
// }
// return restConfig.getString(RestConfig.RESPONSE_MEDIATYPE_DEFAULT_CONFIG);
// }
// }
| import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.exceptions.RestException;
import io.confluent.rest.exceptions.WebApplicationExceptionMapper;
import static org.junit.jupiter.api.Assertions.*; | /*
* Copyright 2015 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest;
public class WebApplicationExceptionMapperTest {
private WebApplicationExceptionMapper mapper;
@BeforeEach
public void setUp() {
Properties props = new Properties();
props.setProperty("debug", "false");
RestConfig config = new TestRestConfig(props);
mapper = new WebApplicationExceptionMapper(config);
}
@Test
public void testRestException() { | // Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestException.java
// public class RestException extends WebApplicationException {
//
// private int errorCode;
//
// public RestException(final String message, final int status, final int errorCode) {
// this(message, status, errorCode, (Throwable) null);
// }
//
// public RestException(final String message, final int status, final int errorCode,
// final Throwable cause) {
// super(message, cause, status);
// this.errorCode = errorCode;
// }
//
// public int getStatus() {
// return getResponse().getStatus();
// }
//
// public int getErrorCode() {
// return errorCode;
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/WebApplicationExceptionMapper.java
// public class WebApplicationExceptionMapper
// extends DebuggableExceptionMapper<WebApplicationException> {
//
// @Context
// HttpHeaders headers;
//
// public WebApplicationExceptionMapper(RestConfig restConfig) {
// super(restConfig);
// }
//
// @Override
// public Response toResponse(WebApplicationException exc) {
// // WebApplicationException unfortunately doesn't expose the status, or even status code,
// // directly.
// Response.StatusType status = Response.Status.fromStatusCode(exc.getResponse().getStatus());
//
//
//
// // The human-readable message for these can use the exception message directly. Since
// // WebApplicationExceptions are expected to be passed back to users, it will either contain a
// // situation-specific message or the HTTP status message
// int errorCode = (exc instanceof RestException) ? ((RestException)exc).getErrorCode()
// : status.getStatusCode();
//
// // Response.Status does not contain all http status. This results in
// // status to be null above for the cases of some valid 4xx status i.e 422.
// // Below we are trying to replace the null with the status passed in the exception itself
//
// Response.ResponseBuilder response = createResponse(exc, errorCode,
// status != null ? status :
// new HttpStatus(exc.getResponse().getStatus(), exc.getMessage()),
// exc.getMessage());
//
// // Apparently, 415 Unsupported Media Type errors disable content negotiation in Jersey, which
// // causes use to return data without a content type. Work around this by detecting that specific
// // type of error and performing the negotiation manually.
// if (status == Response.Status.UNSUPPORTED_MEDIA_TYPE) {
// response.type(negotiateContentType());
// }
//
// return response.build();
// }
//
// private String negotiateContentType() {
// List<MediaType> acceptable = headers.getAcceptableMediaTypes();
// for (MediaType mt : acceptable) {
// for (String providable : restConfig.getList(RestConfig.RESPONSE_MEDIATYPE_PREFERRED_CONFIG)) {
// if (mt.toString().equals(providable)) {
// return providable;
// }
// }
// }
// return restConfig.getString(RestConfig.RESPONSE_MEDIATYPE_DEFAULT_CONFIG);
// }
// }
// Path: core/src/test/java/io/confluent/rest/WebApplicationExceptionMapperTest.java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.exceptions.RestException;
import io.confluent.rest.exceptions.WebApplicationExceptionMapper;
import static org.junit.jupiter.api.Assertions.*;
/*
* Copyright 2015 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest;
public class WebApplicationExceptionMapperTest {
private WebApplicationExceptionMapper mapper;
@BeforeEach
public void setUp() {
Properties props = new Properties();
props.setProperty("debug", "false");
RestConfig config = new TestRestConfig(props);
mapper = new WebApplicationExceptionMapper(config);
}
@Test
public void testRestException() { | Response response = mapper.toResponse(new RestException("msg", 400, 1000)); |
confluentinc/rest-utils | core/src/test/java/io/confluent/rest/WebApplicationExceptionMapperTest.java | // Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestException.java
// public class RestException extends WebApplicationException {
//
// private int errorCode;
//
// public RestException(final String message, final int status, final int errorCode) {
// this(message, status, errorCode, (Throwable) null);
// }
//
// public RestException(final String message, final int status, final int errorCode,
// final Throwable cause) {
// super(message, cause, status);
// this.errorCode = errorCode;
// }
//
// public int getStatus() {
// return getResponse().getStatus();
// }
//
// public int getErrorCode() {
// return errorCode;
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/WebApplicationExceptionMapper.java
// public class WebApplicationExceptionMapper
// extends DebuggableExceptionMapper<WebApplicationException> {
//
// @Context
// HttpHeaders headers;
//
// public WebApplicationExceptionMapper(RestConfig restConfig) {
// super(restConfig);
// }
//
// @Override
// public Response toResponse(WebApplicationException exc) {
// // WebApplicationException unfortunately doesn't expose the status, or even status code,
// // directly.
// Response.StatusType status = Response.Status.fromStatusCode(exc.getResponse().getStatus());
//
//
//
// // The human-readable message for these can use the exception message directly. Since
// // WebApplicationExceptions are expected to be passed back to users, it will either contain a
// // situation-specific message or the HTTP status message
// int errorCode = (exc instanceof RestException) ? ((RestException)exc).getErrorCode()
// : status.getStatusCode();
//
// // Response.Status does not contain all http status. This results in
// // status to be null above for the cases of some valid 4xx status i.e 422.
// // Below we are trying to replace the null with the status passed in the exception itself
//
// Response.ResponseBuilder response = createResponse(exc, errorCode,
// status != null ? status :
// new HttpStatus(exc.getResponse().getStatus(), exc.getMessage()),
// exc.getMessage());
//
// // Apparently, 415 Unsupported Media Type errors disable content negotiation in Jersey, which
// // causes use to return data without a content type. Work around this by detecting that specific
// // type of error and performing the negotiation manually.
// if (status == Response.Status.UNSUPPORTED_MEDIA_TYPE) {
// response.type(negotiateContentType());
// }
//
// return response.build();
// }
//
// private String negotiateContentType() {
// List<MediaType> acceptable = headers.getAcceptableMediaTypes();
// for (MediaType mt : acceptable) {
// for (String providable : restConfig.getList(RestConfig.RESPONSE_MEDIATYPE_PREFERRED_CONFIG)) {
// if (mt.toString().equals(providable)) {
// return providable;
// }
// }
// }
// return restConfig.getString(RestConfig.RESPONSE_MEDIATYPE_DEFAULT_CONFIG);
// }
// }
| import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.exceptions.RestException;
import io.confluent.rest.exceptions.WebApplicationExceptionMapper;
import static org.junit.jupiter.api.Assertions.*; | /*
* Copyright 2015 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest;
public class WebApplicationExceptionMapperTest {
private WebApplicationExceptionMapper mapper;
@BeforeEach
public void setUp() {
Properties props = new Properties();
props.setProperty("debug", "false");
RestConfig config = new TestRestConfig(props);
mapper = new WebApplicationExceptionMapper(config);
}
@Test
public void testRestException() {
Response response = mapper.toResponse(new RestException("msg", 400, 1000));
assertEquals(400, response.getStatus()); | // Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestException.java
// public class RestException extends WebApplicationException {
//
// private int errorCode;
//
// public RestException(final String message, final int status, final int errorCode) {
// this(message, status, errorCode, (Throwable) null);
// }
//
// public RestException(final String message, final int status, final int errorCode,
// final Throwable cause) {
// super(message, cause, status);
// this.errorCode = errorCode;
// }
//
// public int getStatus() {
// return getResponse().getStatus();
// }
//
// public int getErrorCode() {
// return errorCode;
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/WebApplicationExceptionMapper.java
// public class WebApplicationExceptionMapper
// extends DebuggableExceptionMapper<WebApplicationException> {
//
// @Context
// HttpHeaders headers;
//
// public WebApplicationExceptionMapper(RestConfig restConfig) {
// super(restConfig);
// }
//
// @Override
// public Response toResponse(WebApplicationException exc) {
// // WebApplicationException unfortunately doesn't expose the status, or even status code,
// // directly.
// Response.StatusType status = Response.Status.fromStatusCode(exc.getResponse().getStatus());
//
//
//
// // The human-readable message for these can use the exception message directly. Since
// // WebApplicationExceptions are expected to be passed back to users, it will either contain a
// // situation-specific message or the HTTP status message
// int errorCode = (exc instanceof RestException) ? ((RestException)exc).getErrorCode()
// : status.getStatusCode();
//
// // Response.Status does not contain all http status. This results in
// // status to be null above for the cases of some valid 4xx status i.e 422.
// // Below we are trying to replace the null with the status passed in the exception itself
//
// Response.ResponseBuilder response = createResponse(exc, errorCode,
// status != null ? status :
// new HttpStatus(exc.getResponse().getStatus(), exc.getMessage()),
// exc.getMessage());
//
// // Apparently, 415 Unsupported Media Type errors disable content negotiation in Jersey, which
// // causes use to return data without a content type. Work around this by detecting that specific
// // type of error and performing the negotiation manually.
// if (status == Response.Status.UNSUPPORTED_MEDIA_TYPE) {
// response.type(negotiateContentType());
// }
//
// return response.build();
// }
//
// private String negotiateContentType() {
// List<MediaType> acceptable = headers.getAcceptableMediaTypes();
// for (MediaType mt : acceptable) {
// for (String providable : restConfig.getList(RestConfig.RESPONSE_MEDIATYPE_PREFERRED_CONFIG)) {
// if (mt.toString().equals(providable)) {
// return providable;
// }
// }
// }
// return restConfig.getString(RestConfig.RESPONSE_MEDIATYPE_DEFAULT_CONFIG);
// }
// }
// Path: core/src/test/java/io/confluent/rest/WebApplicationExceptionMapperTest.java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Properties;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.exceptions.RestException;
import io.confluent.rest.exceptions.WebApplicationExceptionMapper;
import static org.junit.jupiter.api.Assertions.*;
/*
* Copyright 2015 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest;
public class WebApplicationExceptionMapperTest {
private WebApplicationExceptionMapper mapper;
@BeforeEach
public void setUp() {
Properties props = new Properties();
props.setProperty("debug", "false");
RestConfig config = new TestRestConfig(props);
mapper = new WebApplicationExceptionMapper(config);
}
@Test
public void testRestException() {
Response response = mapper.toResponse(new RestException("msg", 400, 1000));
assertEquals(400, response.getStatus()); | ErrorMessage out = (ErrorMessage)response.getEntity(); |
confluentinc/rest-utils | core/src/main/java/io/confluent/rest/exceptions/JsonMappingExceptionMapper.java | // Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
| import com.fasterxml.jackson.databind.JsonMappingException;
import io.confluent.rest.entities.ErrorMessage;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider; | /*
* Copyright 2021 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest.exceptions;
@Provider
public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {
public static final int BAD_REQUEST_CODE = 400;
@Override
public Response toResponse(JsonMappingException exception) { | // Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
// Path: core/src/main/java/io/confluent/rest/exceptions/JsonMappingExceptionMapper.java
import com.fasterxml.jackson.databind.JsonMappingException;
import io.confluent.rest.entities.ErrorMessage;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
/*
* Copyright 2021 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest.exceptions;
@Provider
public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {
public static final int BAD_REQUEST_CODE = 400;
@Override
public Response toResponse(JsonMappingException exception) { | ErrorMessage message = new ErrorMessage( |
confluentinc/rest-utils | core/src/test/java/io/confluent/rest/ExceptionHandlingTest.java | // Path: core/src/main/java/io/confluent/rest/exceptions/RestTimeoutException.java
// public class RestTimeoutException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.REQUEST_TIMEOUT.getStatusCode();
//
// public RestTimeoutException(String message, int status, int errorCode) {
// super(message, status, errorCode);
// }
//
// public RestTimeoutException(String message, int status, int errorCode, Throwable cause) {
// super(message, status, errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestNotFoundException.java
// public class RestNotFoundException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.NOT_FOUND.getStatusCode();
//
// public RestNotFoundException(String message, int errorCode) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode);
// }
//
// public RestNotFoundException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestServerErrorException.java
// public class RestServerErrorException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE =
// Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
//
// public RestServerErrorException(String message, int errorCode) {
// this(message, errorCode, null);
// }
//
// public RestServerErrorException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), errorCode, cause);
// }
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.Response;
import io.confluent.rest.exceptions.RestTimeoutException;
import org.eclipse.jetty.server.Server;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.exceptions.RestNotFoundException;
import io.confluent.rest.exceptions.RestServerErrorException; | /*
* Copyright 2015 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest;
/**
* Tests that a demo app catches exceptions correctly and returns errors in the expected format.
*/
public class ExceptionHandlingTest {
private TestRestConfig config;
private Server server;
private ExceptionApplication application;
@BeforeEach
public void setUp() throws Exception {
Properties props = new Properties();
props.setProperty("debug", "false");
props.setProperty("listeners", "http://localhost:0");
config = new TestRestConfig(props);
application = new ExceptionApplication(config);
server = application.createServer();
server.start();
}
@AfterEach
public void tearDown() throws Exception {
server.stop();
server.join();
}
private void testGetException(String path, int expectedStatus, int expectedErrorCode,
String expectedMessage) {
Response response = ClientBuilder.newClient(application.resourceConfig.getConfiguration())
.target(server.getURI())
.path(path)
.request()
.get();
assertEquals(expectedStatus, response.getStatus());
| // Path: core/src/main/java/io/confluent/rest/exceptions/RestTimeoutException.java
// public class RestTimeoutException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.REQUEST_TIMEOUT.getStatusCode();
//
// public RestTimeoutException(String message, int status, int errorCode) {
// super(message, status, errorCode);
// }
//
// public RestTimeoutException(String message, int status, int errorCode, Throwable cause) {
// super(message, status, errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestNotFoundException.java
// public class RestNotFoundException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.NOT_FOUND.getStatusCode();
//
// public RestNotFoundException(String message, int errorCode) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode);
// }
//
// public RestNotFoundException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestServerErrorException.java
// public class RestServerErrorException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE =
// Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
//
// public RestServerErrorException(String message, int errorCode) {
// this(message, errorCode, null);
// }
//
// public RestServerErrorException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), errorCode, cause);
// }
// }
// Path: core/src/test/java/io/confluent/rest/ExceptionHandlingTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.Response;
import io.confluent.rest.exceptions.RestTimeoutException;
import org.eclipse.jetty.server.Server;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.exceptions.RestNotFoundException;
import io.confluent.rest.exceptions.RestServerErrorException;
/*
* Copyright 2015 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest;
/**
* Tests that a demo app catches exceptions correctly and returns errors in the expected format.
*/
public class ExceptionHandlingTest {
private TestRestConfig config;
private Server server;
private ExceptionApplication application;
@BeforeEach
public void setUp() throws Exception {
Properties props = new Properties();
props.setProperty("debug", "false");
props.setProperty("listeners", "http://localhost:0");
config = new TestRestConfig(props);
application = new ExceptionApplication(config);
server = application.createServer();
server.start();
}
@AfterEach
public void tearDown() throws Exception {
server.stop();
server.join();
}
private void testGetException(String path, int expectedStatus, int expectedErrorCode,
String expectedMessage) {
Response response = ClientBuilder.newClient(application.resourceConfig.getConfiguration())
.target(server.getURI())
.path(path)
.request()
.get();
assertEquals(expectedStatus, response.getStatus());
| ErrorMessage msg = response.readEntity(ErrorMessage.class); |
confluentinc/rest-utils | core/src/test/java/io/confluent/rest/ExceptionHandlingTest.java | // Path: core/src/main/java/io/confluent/rest/exceptions/RestTimeoutException.java
// public class RestTimeoutException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.REQUEST_TIMEOUT.getStatusCode();
//
// public RestTimeoutException(String message, int status, int errorCode) {
// super(message, status, errorCode);
// }
//
// public RestTimeoutException(String message, int status, int errorCode, Throwable cause) {
// super(message, status, errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestNotFoundException.java
// public class RestNotFoundException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.NOT_FOUND.getStatusCode();
//
// public RestNotFoundException(String message, int errorCode) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode);
// }
//
// public RestNotFoundException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestServerErrorException.java
// public class RestServerErrorException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE =
// Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
//
// public RestServerErrorException(String message, int errorCode) {
// this(message, errorCode, null);
// }
//
// public RestServerErrorException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), errorCode, cause);
// }
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.Response;
import io.confluent.rest.exceptions.RestTimeoutException;
import org.eclipse.jetty.server.Server;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.exceptions.RestNotFoundException;
import io.confluent.rest.exceptions.RestServerErrorException; | Map<String, String> m = new HashMap<>();
m.put("something", "something");
m.put("something-else", "something-else");
testPostException(
"/unrecognizedfield", Entity.json(m), 422, 422, "Unrecognized field: something-else");
}
// Test app just has endpoints that trigger different types of exceptions.
private static class ExceptionApplication extends Application<TestRestConfig> {
Configurable<?> resourceConfig;
ExceptionApplication(TestRestConfig props) {
super(props);
}
@Override
public void setupResources(Configurable<?> config, TestRestConfig appConfig) {
resourceConfig = config;
config.register(ExceptionResource.class);
}
}
@Produces("application/json")
@Path("/")
public static class ExceptionResource {
@GET
@Path("/restnotfound")
public String restNotFound() { | // Path: core/src/main/java/io/confluent/rest/exceptions/RestTimeoutException.java
// public class RestTimeoutException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.REQUEST_TIMEOUT.getStatusCode();
//
// public RestTimeoutException(String message, int status, int errorCode) {
// super(message, status, errorCode);
// }
//
// public RestTimeoutException(String message, int status, int errorCode, Throwable cause) {
// super(message, status, errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestNotFoundException.java
// public class RestNotFoundException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.NOT_FOUND.getStatusCode();
//
// public RestNotFoundException(String message, int errorCode) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode);
// }
//
// public RestNotFoundException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestServerErrorException.java
// public class RestServerErrorException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE =
// Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
//
// public RestServerErrorException(String message, int errorCode) {
// this(message, errorCode, null);
// }
//
// public RestServerErrorException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), errorCode, cause);
// }
// }
// Path: core/src/test/java/io/confluent/rest/ExceptionHandlingTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.Response;
import io.confluent.rest.exceptions.RestTimeoutException;
import org.eclipse.jetty.server.Server;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.exceptions.RestNotFoundException;
import io.confluent.rest.exceptions.RestServerErrorException;
Map<String, String> m = new HashMap<>();
m.put("something", "something");
m.put("something-else", "something-else");
testPostException(
"/unrecognizedfield", Entity.json(m), 422, 422, "Unrecognized field: something-else");
}
// Test app just has endpoints that trigger different types of exceptions.
private static class ExceptionApplication extends Application<TestRestConfig> {
Configurable<?> resourceConfig;
ExceptionApplication(TestRestConfig props) {
super(props);
}
@Override
public void setupResources(Configurable<?> config, TestRestConfig appConfig) {
resourceConfig = config;
config.register(ExceptionResource.class);
}
}
@Produces("application/json")
@Path("/")
public static class ExceptionResource {
@GET
@Path("/restnotfound")
public String restNotFound() { | throw new RestNotFoundException("Rest Not Found", 4040); |
confluentinc/rest-utils | core/src/test/java/io/confluent/rest/ExceptionHandlingTest.java | // Path: core/src/main/java/io/confluent/rest/exceptions/RestTimeoutException.java
// public class RestTimeoutException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.REQUEST_TIMEOUT.getStatusCode();
//
// public RestTimeoutException(String message, int status, int errorCode) {
// super(message, status, errorCode);
// }
//
// public RestTimeoutException(String message, int status, int errorCode, Throwable cause) {
// super(message, status, errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestNotFoundException.java
// public class RestNotFoundException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.NOT_FOUND.getStatusCode();
//
// public RestNotFoundException(String message, int errorCode) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode);
// }
//
// public RestNotFoundException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestServerErrorException.java
// public class RestServerErrorException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE =
// Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
//
// public RestServerErrorException(String message, int errorCode) {
// this(message, errorCode, null);
// }
//
// public RestServerErrorException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), errorCode, cause);
// }
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.Response;
import io.confluent.rest.exceptions.RestTimeoutException;
import org.eclipse.jetty.server.Server;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.exceptions.RestNotFoundException;
import io.confluent.rest.exceptions.RestServerErrorException; | ExceptionApplication(TestRestConfig props) {
super(props);
}
@Override
public void setupResources(Configurable<?> config, TestRestConfig appConfig) {
resourceConfig = config;
config.register(ExceptionResource.class);
}
}
@Produces("application/json")
@Path("/")
public static class ExceptionResource {
@GET
@Path("/restnotfound")
public String restNotFound() {
throw new RestNotFoundException("Rest Not Found", 4040);
}
@GET
@Path("/notfound")
public String notFound() {
throw new javax.ws.rs.NotFoundException("Generic Not Found");
}
@GET
@Path("/unexpected")
public String unexpected() { | // Path: core/src/main/java/io/confluent/rest/exceptions/RestTimeoutException.java
// public class RestTimeoutException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.REQUEST_TIMEOUT.getStatusCode();
//
// public RestTimeoutException(String message, int status, int errorCode) {
// super(message, status, errorCode);
// }
//
// public RestTimeoutException(String message, int status, int errorCode, Throwable cause) {
// super(message, status, errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestNotFoundException.java
// public class RestNotFoundException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.NOT_FOUND.getStatusCode();
//
// public RestNotFoundException(String message, int errorCode) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode);
// }
//
// public RestNotFoundException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestServerErrorException.java
// public class RestServerErrorException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE =
// Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
//
// public RestServerErrorException(String message, int errorCode) {
// this(message, errorCode, null);
// }
//
// public RestServerErrorException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), errorCode, cause);
// }
// }
// Path: core/src/test/java/io/confluent/rest/ExceptionHandlingTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.Response;
import io.confluent.rest.exceptions.RestTimeoutException;
import org.eclipse.jetty.server.Server;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.exceptions.RestNotFoundException;
import io.confluent.rest.exceptions.RestServerErrorException;
ExceptionApplication(TestRestConfig props) {
super(props);
}
@Override
public void setupResources(Configurable<?> config, TestRestConfig appConfig) {
resourceConfig = config;
config.register(ExceptionResource.class);
}
}
@Produces("application/json")
@Path("/")
public static class ExceptionResource {
@GET
@Path("/restnotfound")
public String restNotFound() {
throw new RestNotFoundException("Rest Not Found", 4040);
}
@GET
@Path("/notfound")
public String notFound() {
throw new javax.ws.rs.NotFoundException("Generic Not Found");
}
@GET
@Path("/unexpected")
public String unexpected() { | throw new RestServerErrorException("Internal Server Error", 50001); |
confluentinc/rest-utils | core/src/test/java/io/confluent/rest/ExceptionHandlingTest.java | // Path: core/src/main/java/io/confluent/rest/exceptions/RestTimeoutException.java
// public class RestTimeoutException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.REQUEST_TIMEOUT.getStatusCode();
//
// public RestTimeoutException(String message, int status, int errorCode) {
// super(message, status, errorCode);
// }
//
// public RestTimeoutException(String message, int status, int errorCode, Throwable cause) {
// super(message, status, errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestNotFoundException.java
// public class RestNotFoundException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.NOT_FOUND.getStatusCode();
//
// public RestNotFoundException(String message, int errorCode) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode);
// }
//
// public RestNotFoundException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestServerErrorException.java
// public class RestServerErrorException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE =
// Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
//
// public RestServerErrorException(String message, int errorCode) {
// this(message, errorCode, null);
// }
//
// public RestServerErrorException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), errorCode, cause);
// }
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.Response;
import io.confluent.rest.exceptions.RestTimeoutException;
import org.eclipse.jetty.server.Server;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.exceptions.RestNotFoundException;
import io.confluent.rest.exceptions.RestServerErrorException; | @Path("/")
public static class ExceptionResource {
@GET
@Path("/restnotfound")
public String restNotFound() {
throw new RestNotFoundException("Rest Not Found", 4040);
}
@GET
@Path("/notfound")
public String notFound() {
throw new javax.ws.rs.NotFoundException("Generic Not Found");
}
@GET
@Path("/unexpected")
public String unexpected() {
throw new RestServerErrorException("Internal Server Error", 50001);
}
@POST
@Path("/unrecognizedfield")
public String blah(FakeType ft) {
return ft.something;
}
@POST
@Path("/readTimeout")
public String restTimeout() { | // Path: core/src/main/java/io/confluent/rest/exceptions/RestTimeoutException.java
// public class RestTimeoutException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.REQUEST_TIMEOUT.getStatusCode();
//
// public RestTimeoutException(String message, int status, int errorCode) {
// super(message, status, errorCode);
// }
//
// public RestTimeoutException(String message, int status, int errorCode, Throwable cause) {
// super(message, status, errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestNotFoundException.java
// public class RestNotFoundException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.NOT_FOUND.getStatusCode();
//
// public RestNotFoundException(String message, int errorCode) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode);
// }
//
// public RestNotFoundException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.NOT_FOUND.getStatusCode(), errorCode, cause);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/exceptions/RestServerErrorException.java
// public class RestServerErrorException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE =
// Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
//
// public RestServerErrorException(String message, int errorCode) {
// this(message, errorCode, null);
// }
//
// public RestServerErrorException(String message, int errorCode, Throwable cause) {
// super(message, Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), errorCode, cause);
// }
// }
// Path: core/src/test/java/io/confluent/rest/ExceptionHandlingTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.Response;
import io.confluent.rest.exceptions.RestTimeoutException;
import org.eclipse.jetty.server.Server;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.exceptions.RestNotFoundException;
import io.confluent.rest.exceptions.RestServerErrorException;
@Path("/")
public static class ExceptionResource {
@GET
@Path("/restnotfound")
public String restNotFound() {
throw new RestNotFoundException("Rest Not Found", 4040);
}
@GET
@Path("/notfound")
public String notFound() {
throw new javax.ws.rs.NotFoundException("Generic Not Found");
}
@GET
@Path("/unexpected")
public String unexpected() {
throw new RestServerErrorException("Internal Server Error", 50001);
}
@POST
@Path("/unrecognizedfield")
public String blah(FakeType ft) {
return ft.something;
}
@POST
@Path("/readTimeout")
public String restTimeout() { | throw new RestTimeoutException("Idle timeout expired", 408, 408); |
confluentinc/rest-utils | core/src/test/java/io/confluent/rest/TestRestConfig.java | // Path: core/src/main/java/io/confluent/rest/metrics/RestMetricsContext.java
// public final class RestMetricsContext implements MetricsContext {
// /**
// * Client or Service's metadata map.
// */
// private final Map<String, String> contextLabels;
//
// public RestMetricsContext(String namespace,
// Map<String, Object> config) {
// contextLabels = new HashMap<>();
// contextLabels.put(MetricsContext.NAMESPACE, namespace);
// config.forEach((key, value) -> contextLabels.put(key, value.toString()));
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// this.contextLabels.put(labelKey, labelValue);
// }
//
// public void setLabels(Map<String, String> labels) {
// labels.forEach(this::setLabel);
// }
//
// /**
// * Returns the value associated with the specified label else
// * {@code null}.
// */
// public String getLabel(String label) {
// return contextLabels.get(label);
// }
//
// /**
// * Returns {@link MetricsContext} as an unmodifiable Map.
// */
// @Override
// public Map<String, String> contextLabels() {
// return Collections.unmodifiableMap(contextLabels);
// }
// }
//
// Path: core/src/test/java/io/confluent/rest/metrics/TestRestMetricsContext.java
// public final class TestRestMetricsContext {
// /**
// * MetricsContext Label's for use by Confluent's TelemetryReporter
// */
// private final RestMetricsContext metricsContext;
// public static final String RESOURCE_LABEL_PREFIX = "resource.";
// public static final String RESOURCE_LABEL_TYPE = RESOURCE_LABEL_PREFIX + "type";
//
// public TestRestMetricsContext(String namespace, Map<String, Object> config) {
// metricsContext = new RestMetricsContext(namespace, config);
//
// this.setResourceLabel(RESOURCE_LABEL_TYPE,
// namespace);
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// /* Remove resource label if present */
// if (labelKey.startsWith(RESOURCE_LABEL_PREFIX))
// setResourceLabel(labelKey, labelValue);
//
// metricsContext.setLabel(labelKey, labelValue);
// }
//
// /**
// * Sets {@link MetricsContext} resource label if not previously set.
// */
// private void setResourceLabel(String resource, String value) {
// if (metricsContext.getLabel(resource) == null) {
// metricsContext.setLabel(resource, value);
// }
// }
//
// public RestMetricsContext metricsContext() {
// return metricsContext;
// }
//
// }
| import static java.util.Collections.emptyMap;
import static org.apache.kafka.clients.CommonClientConfigs.METRICS_CONTEXT_PREFIX;
import io.confluent.rest.metrics.RestMetricsContext;
import io.confluent.rest.metrics.TestRestMetricsContext;
import org.apache.kafka.common.config.ConfigDef;
import java.util.HashMap;
import java.util.Map; | /*
* Copyright 2015 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest;
/**
* Test config class that only uses the built-in properties of RestConfig.
*/
public class TestRestConfig extends RestConfig {
private static final ConfigDef config;
static {
config = baseConfigDef();
}
public TestRestConfig() {
this(emptyMap());
}
public TestRestConfig(Map<?,?> originals) {
super(config, createConfigs(originals));
}
private static Map<Object, Object> createConfigs(Map<?, ?> originals) {
HashMap<Object, Object> configs = new HashMap<>();
configs.put("listeners", "http://localhost:0");
configs.putAll(originals);
return configs;
}
@Override | // Path: core/src/main/java/io/confluent/rest/metrics/RestMetricsContext.java
// public final class RestMetricsContext implements MetricsContext {
// /**
// * Client or Service's metadata map.
// */
// private final Map<String, String> contextLabels;
//
// public RestMetricsContext(String namespace,
// Map<String, Object> config) {
// contextLabels = new HashMap<>();
// contextLabels.put(MetricsContext.NAMESPACE, namespace);
// config.forEach((key, value) -> contextLabels.put(key, value.toString()));
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// this.contextLabels.put(labelKey, labelValue);
// }
//
// public void setLabels(Map<String, String> labels) {
// labels.forEach(this::setLabel);
// }
//
// /**
// * Returns the value associated with the specified label else
// * {@code null}.
// */
// public String getLabel(String label) {
// return contextLabels.get(label);
// }
//
// /**
// * Returns {@link MetricsContext} as an unmodifiable Map.
// */
// @Override
// public Map<String, String> contextLabels() {
// return Collections.unmodifiableMap(contextLabels);
// }
// }
//
// Path: core/src/test/java/io/confluent/rest/metrics/TestRestMetricsContext.java
// public final class TestRestMetricsContext {
// /**
// * MetricsContext Label's for use by Confluent's TelemetryReporter
// */
// private final RestMetricsContext metricsContext;
// public static final String RESOURCE_LABEL_PREFIX = "resource.";
// public static final String RESOURCE_LABEL_TYPE = RESOURCE_LABEL_PREFIX + "type";
//
// public TestRestMetricsContext(String namespace, Map<String, Object> config) {
// metricsContext = new RestMetricsContext(namespace, config);
//
// this.setResourceLabel(RESOURCE_LABEL_TYPE,
// namespace);
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// /* Remove resource label if present */
// if (labelKey.startsWith(RESOURCE_LABEL_PREFIX))
// setResourceLabel(labelKey, labelValue);
//
// metricsContext.setLabel(labelKey, labelValue);
// }
//
// /**
// * Sets {@link MetricsContext} resource label if not previously set.
// */
// private void setResourceLabel(String resource, String value) {
// if (metricsContext.getLabel(resource) == null) {
// metricsContext.setLabel(resource, value);
// }
// }
//
// public RestMetricsContext metricsContext() {
// return metricsContext;
// }
//
// }
// Path: core/src/test/java/io/confluent/rest/TestRestConfig.java
import static java.util.Collections.emptyMap;
import static org.apache.kafka.clients.CommonClientConfigs.METRICS_CONTEXT_PREFIX;
import io.confluent.rest.metrics.RestMetricsContext;
import io.confluent.rest.metrics.TestRestMetricsContext;
import org.apache.kafka.common.config.ConfigDef;
import java.util.HashMap;
import java.util.Map;
/*
* Copyright 2015 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest;
/**
* Test config class that only uses the built-in properties of RestConfig.
*/
public class TestRestConfig extends RestConfig {
private static final ConfigDef config;
static {
config = baseConfigDef();
}
public TestRestConfig() {
this(emptyMap());
}
public TestRestConfig(Map<?,?> originals) {
super(config, createConfigs(originals));
}
private static Map<Object, Object> createConfigs(Map<?, ?> originals) {
HashMap<Object, Object> configs = new HashMap<>();
configs.put("listeners", "http://localhost:0");
configs.putAll(originals);
return configs;
}
@Override | public RestMetricsContext getMetricsContext() { |
confluentinc/rest-utils | core/src/test/java/io/confluent/rest/TestRestConfig.java | // Path: core/src/main/java/io/confluent/rest/metrics/RestMetricsContext.java
// public final class RestMetricsContext implements MetricsContext {
// /**
// * Client or Service's metadata map.
// */
// private final Map<String, String> contextLabels;
//
// public RestMetricsContext(String namespace,
// Map<String, Object> config) {
// contextLabels = new HashMap<>();
// contextLabels.put(MetricsContext.NAMESPACE, namespace);
// config.forEach((key, value) -> contextLabels.put(key, value.toString()));
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// this.contextLabels.put(labelKey, labelValue);
// }
//
// public void setLabels(Map<String, String> labels) {
// labels.forEach(this::setLabel);
// }
//
// /**
// * Returns the value associated with the specified label else
// * {@code null}.
// */
// public String getLabel(String label) {
// return contextLabels.get(label);
// }
//
// /**
// * Returns {@link MetricsContext} as an unmodifiable Map.
// */
// @Override
// public Map<String, String> contextLabels() {
// return Collections.unmodifiableMap(contextLabels);
// }
// }
//
// Path: core/src/test/java/io/confluent/rest/metrics/TestRestMetricsContext.java
// public final class TestRestMetricsContext {
// /**
// * MetricsContext Label's for use by Confluent's TelemetryReporter
// */
// private final RestMetricsContext metricsContext;
// public static final String RESOURCE_LABEL_PREFIX = "resource.";
// public static final String RESOURCE_LABEL_TYPE = RESOURCE_LABEL_PREFIX + "type";
//
// public TestRestMetricsContext(String namespace, Map<String, Object> config) {
// metricsContext = new RestMetricsContext(namespace, config);
//
// this.setResourceLabel(RESOURCE_LABEL_TYPE,
// namespace);
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// /* Remove resource label if present */
// if (labelKey.startsWith(RESOURCE_LABEL_PREFIX))
// setResourceLabel(labelKey, labelValue);
//
// metricsContext.setLabel(labelKey, labelValue);
// }
//
// /**
// * Sets {@link MetricsContext} resource label if not previously set.
// */
// private void setResourceLabel(String resource, String value) {
// if (metricsContext.getLabel(resource) == null) {
// metricsContext.setLabel(resource, value);
// }
// }
//
// public RestMetricsContext metricsContext() {
// return metricsContext;
// }
//
// }
| import static java.util.Collections.emptyMap;
import static org.apache.kafka.clients.CommonClientConfigs.METRICS_CONTEXT_PREFIX;
import io.confluent.rest.metrics.RestMetricsContext;
import io.confluent.rest.metrics.TestRestMetricsContext;
import org.apache.kafka.common.config.ConfigDef;
import java.util.HashMap;
import java.util.Map; | /*
* Copyright 2015 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest;
/**
* Test config class that only uses the built-in properties of RestConfig.
*/
public class TestRestConfig extends RestConfig {
private static final ConfigDef config;
static {
config = baseConfigDef();
}
public TestRestConfig() {
this(emptyMap());
}
public TestRestConfig(Map<?,?> originals) {
super(config, createConfigs(originals));
}
private static Map<Object, Object> createConfigs(Map<?, ?> originals) {
HashMap<Object, Object> configs = new HashMap<>();
configs.put("listeners", "http://localhost:0");
configs.putAll(originals);
return configs;
}
@Override
public RestMetricsContext getMetricsContext() { | // Path: core/src/main/java/io/confluent/rest/metrics/RestMetricsContext.java
// public final class RestMetricsContext implements MetricsContext {
// /**
// * Client or Service's metadata map.
// */
// private final Map<String, String> contextLabels;
//
// public RestMetricsContext(String namespace,
// Map<String, Object> config) {
// contextLabels = new HashMap<>();
// contextLabels.put(MetricsContext.NAMESPACE, namespace);
// config.forEach((key, value) -> contextLabels.put(key, value.toString()));
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// this.contextLabels.put(labelKey, labelValue);
// }
//
// public void setLabels(Map<String, String> labels) {
// labels.forEach(this::setLabel);
// }
//
// /**
// * Returns the value associated with the specified label else
// * {@code null}.
// */
// public String getLabel(String label) {
// return contextLabels.get(label);
// }
//
// /**
// * Returns {@link MetricsContext} as an unmodifiable Map.
// */
// @Override
// public Map<String, String> contextLabels() {
// return Collections.unmodifiableMap(contextLabels);
// }
// }
//
// Path: core/src/test/java/io/confluent/rest/metrics/TestRestMetricsContext.java
// public final class TestRestMetricsContext {
// /**
// * MetricsContext Label's for use by Confluent's TelemetryReporter
// */
// private final RestMetricsContext metricsContext;
// public static final String RESOURCE_LABEL_PREFIX = "resource.";
// public static final String RESOURCE_LABEL_TYPE = RESOURCE_LABEL_PREFIX + "type";
//
// public TestRestMetricsContext(String namespace, Map<String, Object> config) {
// metricsContext = new RestMetricsContext(namespace, config);
//
// this.setResourceLabel(RESOURCE_LABEL_TYPE,
// namespace);
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// /* Remove resource label if present */
// if (labelKey.startsWith(RESOURCE_LABEL_PREFIX))
// setResourceLabel(labelKey, labelValue);
//
// metricsContext.setLabel(labelKey, labelValue);
// }
//
// /**
// * Sets {@link MetricsContext} resource label if not previously set.
// */
// private void setResourceLabel(String resource, String value) {
// if (metricsContext.getLabel(resource) == null) {
// metricsContext.setLabel(resource, value);
// }
// }
//
// public RestMetricsContext metricsContext() {
// return metricsContext;
// }
//
// }
// Path: core/src/test/java/io/confluent/rest/TestRestConfig.java
import static java.util.Collections.emptyMap;
import static org.apache.kafka.clients.CommonClientConfigs.METRICS_CONTEXT_PREFIX;
import io.confluent.rest.metrics.RestMetricsContext;
import io.confluent.rest.metrics.TestRestMetricsContext;
import org.apache.kafka.common.config.ConfigDef;
import java.util.HashMap;
import java.util.Map;
/*
* Copyright 2015 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest;
/**
* Test config class that only uses the built-in properties of RestConfig.
*/
public class TestRestConfig extends RestConfig {
private static final ConfigDef config;
static {
config = baseConfigDef();
}
public TestRestConfig() {
this(emptyMap());
}
public TestRestConfig(Map<?,?> originals) {
super(config, createConfigs(originals));
}
private static Map<Object, Object> createConfigs(Map<?, ?> originals) {
HashMap<Object, Object> configs = new HashMap<>();
configs.put("listeners", "http://localhost:0");
configs.putAll(originals);
return configs;
}
@Override
public RestMetricsContext getMetricsContext() { | return new TestRestMetricsContext( |
confluentinc/rest-utils | core/src/main/java/io/confluent/rest/validation/JacksonMessageBodyProvider.java | // Path: core/src/main/java/io/confluent/rest/exceptions/RestTimeoutException.java
// public class RestTimeoutException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.REQUEST_TIMEOUT.getStatusCode();
//
// public RestTimeoutException(String message, int status, int errorCode) {
// super(message, status, errorCode);
// }
//
// public RestTimeoutException(String message, int status, int errorCode, Throwable cause) {
// super(message, status, errorCode, cause);
// }
// }
| import java.lang.reflect.Type;
import java.util.concurrent.TimeoutException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import io.confluent.rest.exceptions.RestTimeoutException;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation; | }
@Override
public Object readFrom(Class<Object> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException {
try {
return super.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream);
} catch (UnrecognizedPropertyException e) {
throw ConstraintViolations.simpleException("Unrecognized field: " + e.getPropertyName());
} catch (JsonMappingException e) {
// This needs to handle 2 JSON parsing error cases. Normally you would expect to see a
// JsonMappingException because the data couldn't be parsed, but it can also occur when the
// raw JSON is valid and satisfies the validation constraint annotations, but an exception is
// thrown by the entity during construction. In the former case, we want to return a 400
// (Bad Request), in the latter a 422 (Unprocessable Entity) with a useful error message. We
// don't want to expose just any exception message via the API, so this code specifically
// detects ConstraintViolationExceptions that were thrown *after* the normal validation
// checks, i.e. when the entity Java object was being constructed.
Throwable cause = e.getCause();
if (cause instanceof ConstraintViolationException) {
throw (ConstraintViolationException) cause;
}
throw e;
} catch (IOException e) {
Throwable cause = e.getCause();
if (cause instanceof TimeoutException) { | // Path: core/src/main/java/io/confluent/rest/exceptions/RestTimeoutException.java
// public class RestTimeoutException extends RestException {
//
// public static final int DEFAULT_ERROR_CODE = Response.Status.REQUEST_TIMEOUT.getStatusCode();
//
// public RestTimeoutException(String message, int status, int errorCode) {
// super(message, status, errorCode);
// }
//
// public RestTimeoutException(String message, int status, int errorCode, Throwable cause) {
// super(message, status, errorCode, cause);
// }
// }
// Path: core/src/main/java/io/confluent/rest/validation/JacksonMessageBodyProvider.java
import java.lang.reflect.Type;
import java.util.concurrent.TimeoutException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import io.confluent.rest.exceptions.RestTimeoutException;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
}
@Override
public Object readFrom(Class<Object> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException {
try {
return super.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream);
} catch (UnrecognizedPropertyException e) {
throw ConstraintViolations.simpleException("Unrecognized field: " + e.getPropertyName());
} catch (JsonMappingException e) {
// This needs to handle 2 JSON parsing error cases. Normally you would expect to see a
// JsonMappingException because the data couldn't be parsed, but it can also occur when the
// raw JSON is valid and satisfies the validation constraint annotations, but an exception is
// thrown by the entity during construction. In the former case, we want to return a 400
// (Bad Request), in the latter a 422 (Unprocessable Entity) with a useful error message. We
// don't want to expose just any exception message via the API, so this code specifically
// detects ConstraintViolationExceptions that were thrown *after* the normal validation
// checks, i.e. when the entity Java object was being constructed.
Throwable cause = e.getCause();
if (cause instanceof ConstraintViolationException) {
throw (ConstraintViolationException) cause;
}
throw e;
} catch (IOException e) {
Throwable cause = e.getCause();
if (cause instanceof TimeoutException) { | throw new RestTimeoutException("Timeout while reading from inputStream", |
confluentinc/rest-utils | core/src/main/java/io/confluent/rest/exceptions/ConstraintViolationExceptionMapper.java | // Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/validation/ConstraintViolations.java
// public class ConstraintViolations {
//
// private ConstraintViolations() {
// /* singleton */
// }
//
// public static <T> String format(ConstraintViolation<T> v) {
// return String.format("%s %s (was %s)",
// v.getPropertyPath(),
// v.getMessage(),
// v.getInvalidValue());
// }
//
// public static String formatUntyped(Set<ConstraintViolation<?>> violations) {
// StringBuilder builder = new StringBuilder();
// boolean first = true;
// for (ConstraintViolation<?> v : violations) {
// if (!first) {
// builder.append("; ");
// }
// builder.append(format(v));
// first = false;
// }
// return builder.toString();
// }
//
// public static ConstraintViolationException simpleException(String msg) {
// return new ConstraintViolationException(msg, new HashSet<>());
// }
// }
| import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.validation.ConstraintViolations; | /*
* Copyright 2014 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest.exceptions;
@Provider
public class ConstraintViolationExceptionMapper
implements ExceptionMapper<ConstraintViolationException> {
public static final int UNPROCESSABLE_ENTITY_CODE = 422;
public static final Response.StatusType UNPROCESSABLE_ENTITY = new Response.StatusType() {
@Override
public int getStatusCode() {
return UNPROCESSABLE_ENTITY_CODE;
}
@Override
public Response.Status.Family getFamily() {
return Response.Status.Family.CLIENT_ERROR;
}
@Override
public String getReasonPhrase() {
return "Unprocessable entity";
}
};
@Override
public Response toResponse(ConstraintViolationException exception) { | // Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/validation/ConstraintViolations.java
// public class ConstraintViolations {
//
// private ConstraintViolations() {
// /* singleton */
// }
//
// public static <T> String format(ConstraintViolation<T> v) {
// return String.format("%s %s (was %s)",
// v.getPropertyPath(),
// v.getMessage(),
// v.getInvalidValue());
// }
//
// public static String formatUntyped(Set<ConstraintViolation<?>> violations) {
// StringBuilder builder = new StringBuilder();
// boolean first = true;
// for (ConstraintViolation<?> v : violations) {
// if (!first) {
// builder.append("; ");
// }
// builder.append(format(v));
// first = false;
// }
// return builder.toString();
// }
//
// public static ConstraintViolationException simpleException(String msg) {
// return new ConstraintViolationException(msg, new HashSet<>());
// }
// }
// Path: core/src/main/java/io/confluent/rest/exceptions/ConstraintViolationExceptionMapper.java
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.validation.ConstraintViolations;
/*
* Copyright 2014 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest.exceptions;
@Provider
public class ConstraintViolationExceptionMapper
implements ExceptionMapper<ConstraintViolationException> {
public static final int UNPROCESSABLE_ENTITY_CODE = 422;
public static final Response.StatusType UNPROCESSABLE_ENTITY = new Response.StatusType() {
@Override
public int getStatusCode() {
return UNPROCESSABLE_ENTITY_CODE;
}
@Override
public Response.Status.Family getFamily() {
return Response.Status.Family.CLIENT_ERROR;
}
@Override
public String getReasonPhrase() {
return "Unprocessable entity";
}
};
@Override
public Response toResponse(ConstraintViolationException exception) { | final ErrorMessage message; |
confluentinc/rest-utils | core/src/main/java/io/confluent/rest/exceptions/ConstraintViolationExceptionMapper.java | // Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/validation/ConstraintViolations.java
// public class ConstraintViolations {
//
// private ConstraintViolations() {
// /* singleton */
// }
//
// public static <T> String format(ConstraintViolation<T> v) {
// return String.format("%s %s (was %s)",
// v.getPropertyPath(),
// v.getMessage(),
// v.getInvalidValue());
// }
//
// public static String formatUntyped(Set<ConstraintViolation<?>> violations) {
// StringBuilder builder = new StringBuilder();
// boolean first = true;
// for (ConstraintViolation<?> v : violations) {
// if (!first) {
// builder.append("; ");
// }
// builder.append(format(v));
// first = false;
// }
// return builder.toString();
// }
//
// public static ConstraintViolationException simpleException(String msg) {
// return new ConstraintViolationException(msg, new HashSet<>());
// }
// }
| import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.validation.ConstraintViolations; | /*
* Copyright 2014 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest.exceptions;
@Provider
public class ConstraintViolationExceptionMapper
implements ExceptionMapper<ConstraintViolationException> {
public static final int UNPROCESSABLE_ENTITY_CODE = 422;
public static final Response.StatusType UNPROCESSABLE_ENTITY = new Response.StatusType() {
@Override
public int getStatusCode() {
return UNPROCESSABLE_ENTITY_CODE;
}
@Override
public Response.Status.Family getFamily() {
return Response.Status.Family.CLIENT_ERROR;
}
@Override
public String getReasonPhrase() {
return "Unprocessable entity";
}
};
@Override
public Response toResponse(ConstraintViolationException exception) {
final ErrorMessage message;
if (exception instanceof RestConstraintViolationException) {
RestConstraintViolationException restException = (RestConstraintViolationException)exception;
message = new ErrorMessage(restException.getErrorCode(), restException.getMessage());
} else { | // Path: core/src/main/java/io/confluent/rest/entities/ErrorMessage.java
// public class ErrorMessage {
//
// private int errorCode;
// private String message;
//
// public ErrorMessage(
// @JsonProperty("error_code") int errorCode,
// @JsonProperty("message") String message
// ) {
// this.errorCode = errorCode;
// this.message = message;
// }
//
// @JsonProperty("error_code")
// public int getErrorCode() {
// return errorCode;
// }
//
// @JsonProperty("error_code")
// public void setErrorCode(int errorCode) {
// this.errorCode = errorCode;
// }
//
// @JsonProperty
// public String getMessage() {
// return message;
// }
//
// @JsonProperty
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// ErrorMessage that = (ErrorMessage) o;
// return errorCode == that.errorCode
// && Objects.equals(message, that.message);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(errorCode, message);
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/validation/ConstraintViolations.java
// public class ConstraintViolations {
//
// private ConstraintViolations() {
// /* singleton */
// }
//
// public static <T> String format(ConstraintViolation<T> v) {
// return String.format("%s %s (was %s)",
// v.getPropertyPath(),
// v.getMessage(),
// v.getInvalidValue());
// }
//
// public static String formatUntyped(Set<ConstraintViolation<?>> violations) {
// StringBuilder builder = new StringBuilder();
// boolean first = true;
// for (ConstraintViolation<?> v : violations) {
// if (!first) {
// builder.append("; ");
// }
// builder.append(format(v));
// first = false;
// }
// return builder.toString();
// }
//
// public static ConstraintViolationException simpleException(String msg) {
// return new ConstraintViolationException(msg, new HashSet<>());
// }
// }
// Path: core/src/main/java/io/confluent/rest/exceptions/ConstraintViolationExceptionMapper.java
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import io.confluent.rest.entities.ErrorMessage;
import io.confluent.rest.validation.ConstraintViolations;
/*
* Copyright 2014 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.confluent.rest.exceptions;
@Provider
public class ConstraintViolationExceptionMapper
implements ExceptionMapper<ConstraintViolationException> {
public static final int UNPROCESSABLE_ENTITY_CODE = 422;
public static final Response.StatusType UNPROCESSABLE_ENTITY = new Response.StatusType() {
@Override
public int getStatusCode() {
return UNPROCESSABLE_ENTITY_CODE;
}
@Override
public Response.Status.Family getFamily() {
return Response.Status.Family.CLIENT_ERROR;
}
@Override
public String getReasonPhrase() {
return "Unprocessable entity";
}
};
@Override
public Response toResponse(ConstraintViolationException exception) {
final ErrorMessage message;
if (exception instanceof RestConstraintViolationException) {
RestConstraintViolationException restException = (RestConstraintViolationException)exception;
message = new ErrorMessage(restException.getErrorCode(), restException.getMessage());
} else { | String violationMessage = ConstraintViolations.formatUntyped( |
confluentinc/rest-utils | core/src/test/java/io/confluent/rest/ApplicationTest.java | // Path: core/src/test/java/io/confluent/rest/metrics/TestRestMetricsContext.java
// public static final String RESOURCE_LABEL_TYPE = RESOURCE_LABEL_PREFIX + "type";
//
// Path: core/src/main/java/io/confluent/rest/extension/ResourceExtension.java
// public interface ResourceExtension<AppT extends Application<? extends RestConfig>>
// extends Closeable {
//
// /**
// * Called to register the extension's resources when the rest server starts up.
// *
// * @param config the configuration used to register resources
// * @param app the application.
// */
// void register(Configurable<?> config, AppT app);
//
// @SuppressWarnings("RedundantThrows")
// default void close() throws IOException {
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/metrics/RestMetricsContext.java
// public final class RestMetricsContext implements MetricsContext {
// /**
// * Client or Service's metadata map.
// */
// private final Map<String, String> contextLabels;
//
// public RestMetricsContext(String namespace,
// Map<String, Object> config) {
// contextLabels = new HashMap<>();
// contextLabels.put(MetricsContext.NAMESPACE, namespace);
// config.forEach((key, value) -> contextLabels.put(key, value.toString()));
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// this.contextLabels.put(labelKey, labelValue);
// }
//
// public void setLabels(Map<String, String> labels) {
// labels.forEach(this::setLabel);
// }
//
// /**
// * Returns the value associated with the specified label else
// * {@code null}.
// */
// public String getLabel(String label) {
// return contextLabels.get(label);
// }
//
// /**
// * Returns {@link MetricsContext} as an unmodifiable Map.
// */
// @Override
// public Map<String, String> contextLabels() {
// return Collections.unmodifiableMap(contextLabels);
// }
// }
| import static io.confluent.rest.metrics.TestRestMetricsContext.RESOURCE_LABEL_TYPE;
import static org.apache.kafka.common.metrics.MetricsContext.NAMESPACE;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.ImmutableMap;
import io.confluent.rest.extension.ResourceExtension;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.MediaType;
import io.confluent.rest.metrics.RestMetricsContext;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.kafka.common.config.ConfigException;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpStatus.Code;
import org.eclipse.jetty.jaas.JAASLoginService;
import org.eclipse.jetty.security.authentication.LoginAuthenticator;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.security.Constraint;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | try (TestApp testApp = new TestApp(TestRegistryExtension.class)) {
assertThat(makeGetRequest(testApp, "/custom/resource"), is(Code.OK));
}
}
@Test
public void shouldThrowIfResourceExtensionThrows() {
Exception e = assertThrows(Exception.class,
() -> new TestApp(TestRegistryExtension.class, BadRegistryExtension.class));
assertThat(e.getMessage(), containsString("Exception throw by resource extension. ext:"));
}
@Test
public void shouldCloseResourceExtensions() throws Exception {
new TestApp(TestRegistryExtension.class).stop();
assertThat("close called", TestRegistryExtension.CLOSE_CALLED.get(), is(true));
}
@Test
public void shouldShutdownProperlyEvenIfResourceExtensionThrowsOnShutdown() throws Exception {
final TestApp testApp = new TestApp(UnstoppableRegistryExtension.class);
testApp.stop();
testApp.join();
assertThat("shutdown called", TestApp.SHUTDOWN_CALLED.get(), is(true));
}
@Test
public void testDefaultMetricsContext() throws Exception {
TestApp testApp = new TestApp();
| // Path: core/src/test/java/io/confluent/rest/metrics/TestRestMetricsContext.java
// public static final String RESOURCE_LABEL_TYPE = RESOURCE_LABEL_PREFIX + "type";
//
// Path: core/src/main/java/io/confluent/rest/extension/ResourceExtension.java
// public interface ResourceExtension<AppT extends Application<? extends RestConfig>>
// extends Closeable {
//
// /**
// * Called to register the extension's resources when the rest server starts up.
// *
// * @param config the configuration used to register resources
// * @param app the application.
// */
// void register(Configurable<?> config, AppT app);
//
// @SuppressWarnings("RedundantThrows")
// default void close() throws IOException {
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/metrics/RestMetricsContext.java
// public final class RestMetricsContext implements MetricsContext {
// /**
// * Client or Service's metadata map.
// */
// private final Map<String, String> contextLabels;
//
// public RestMetricsContext(String namespace,
// Map<String, Object> config) {
// contextLabels = new HashMap<>();
// contextLabels.put(MetricsContext.NAMESPACE, namespace);
// config.forEach((key, value) -> contextLabels.put(key, value.toString()));
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// this.contextLabels.put(labelKey, labelValue);
// }
//
// public void setLabels(Map<String, String> labels) {
// labels.forEach(this::setLabel);
// }
//
// /**
// * Returns the value associated with the specified label else
// * {@code null}.
// */
// public String getLabel(String label) {
// return contextLabels.get(label);
// }
//
// /**
// * Returns {@link MetricsContext} as an unmodifiable Map.
// */
// @Override
// public Map<String, String> contextLabels() {
// return Collections.unmodifiableMap(contextLabels);
// }
// }
// Path: core/src/test/java/io/confluent/rest/ApplicationTest.java
import static io.confluent.rest.metrics.TestRestMetricsContext.RESOURCE_LABEL_TYPE;
import static org.apache.kafka.common.metrics.MetricsContext.NAMESPACE;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.ImmutableMap;
import io.confluent.rest.extension.ResourceExtension;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.MediaType;
import io.confluent.rest.metrics.RestMetricsContext;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.kafka.common.config.ConfigException;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpStatus.Code;
import org.eclipse.jetty.jaas.JAASLoginService;
import org.eclipse.jetty.security.authentication.LoginAuthenticator;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.security.Constraint;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
try (TestApp testApp = new TestApp(TestRegistryExtension.class)) {
assertThat(makeGetRequest(testApp, "/custom/resource"), is(Code.OK));
}
}
@Test
public void shouldThrowIfResourceExtensionThrows() {
Exception e = assertThrows(Exception.class,
() -> new TestApp(TestRegistryExtension.class, BadRegistryExtension.class));
assertThat(e.getMessage(), containsString("Exception throw by resource extension. ext:"));
}
@Test
public void shouldCloseResourceExtensions() throws Exception {
new TestApp(TestRegistryExtension.class).stop();
assertThat("close called", TestRegistryExtension.CLOSE_CALLED.get(), is(true));
}
@Test
public void shouldShutdownProperlyEvenIfResourceExtensionThrowsOnShutdown() throws Exception {
final TestApp testApp = new TestApp(UnstoppableRegistryExtension.class);
testApp.stop();
testApp.join();
assertThat("shutdown called", TestApp.SHUTDOWN_CALLED.get(), is(true));
}
@Test
public void testDefaultMetricsContext() throws Exception {
TestApp testApp = new TestApp();
| assertEquals(testApp.metricsContext().getLabel(RESOURCE_LABEL_TYPE), |
confluentinc/rest-utils | core/src/test/java/io/confluent/rest/ApplicationTest.java | // Path: core/src/test/java/io/confluent/rest/metrics/TestRestMetricsContext.java
// public static final String RESOURCE_LABEL_TYPE = RESOURCE_LABEL_PREFIX + "type";
//
// Path: core/src/main/java/io/confluent/rest/extension/ResourceExtension.java
// public interface ResourceExtension<AppT extends Application<? extends RestConfig>>
// extends Closeable {
//
// /**
// * Called to register the extension's resources when the rest server starts up.
// *
// * @param config the configuration used to register resources
// * @param app the application.
// */
// void register(Configurable<?> config, AppT app);
//
// @SuppressWarnings("RedundantThrows")
// default void close() throws IOException {
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/metrics/RestMetricsContext.java
// public final class RestMetricsContext implements MetricsContext {
// /**
// * Client or Service's metadata map.
// */
// private final Map<String, String> contextLabels;
//
// public RestMetricsContext(String namespace,
// Map<String, Object> config) {
// contextLabels = new HashMap<>();
// contextLabels.put(MetricsContext.NAMESPACE, namespace);
// config.forEach((key, value) -> contextLabels.put(key, value.toString()));
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// this.contextLabels.put(labelKey, labelValue);
// }
//
// public void setLabels(Map<String, String> labels) {
// labels.forEach(this::setLabel);
// }
//
// /**
// * Returns the value associated with the specified label else
// * {@code null}.
// */
// public String getLabel(String label) {
// return contextLabels.get(label);
// }
//
// /**
// * Returns {@link MetricsContext} as an unmodifiable Map.
// */
// @Override
// public Map<String, String> contextLabels() {
// return Collections.unmodifiableMap(contextLabels);
// }
// }
| import static io.confluent.rest.metrics.TestRestMetricsContext.RESOURCE_LABEL_TYPE;
import static org.apache.kafka.common.metrics.MetricsContext.NAMESPACE;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.ImmutableMap;
import io.confluent.rest.extension.ResourceExtension;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.MediaType;
import io.confluent.rest.metrics.RestMetricsContext;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.kafka.common.config.ConfigException;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpStatus.Code;
import org.eclipse.jetty.jaas.JAASLoginService;
import org.eclipse.jetty.security.authentication.LoginAuthenticator;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.security.Constraint;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | public void testMetricsContextJMXBeanRegistration() throws Exception {
Map<String, Object> props = new HashMap<>();
props.put(RestConfig.METRICS_JMX_PREFIX_CONFIG, "FooApp");
new TestApp(props);
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
assertNotNull(server.getObjectInstance(new ObjectName("FooApp:type=kafka-metrics-count")));
}
private void assertExpectedUri(URI uri, String scheme, String host, int port) {
assertEquals(scheme, uri.getScheme(), "Scheme should be " + scheme);
assertEquals(host, uri.getHost(), "Host should be " + host);
assertEquals(port, uri.getPort(), "Port should be " + port);
}
@SuppressWarnings("SameParameterValue")
private HttpStatus.Code makeGetRequest(final TestApp app, final String path) throws Exception {
final HttpGet httpget = new HttpGet(app.getListeners().get(0).toString() + path);
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpget)) {
return HttpStatus.getCode(response.getStatusLine().getStatusCode());
}
}
private static class TestApp extends Application<TestRestConfig> implements AutoCloseable {
private static final AtomicBoolean SHUTDOWN_CALLED = new AtomicBoolean(true);
@SafeVarargs | // Path: core/src/test/java/io/confluent/rest/metrics/TestRestMetricsContext.java
// public static final String RESOURCE_LABEL_TYPE = RESOURCE_LABEL_PREFIX + "type";
//
// Path: core/src/main/java/io/confluent/rest/extension/ResourceExtension.java
// public interface ResourceExtension<AppT extends Application<? extends RestConfig>>
// extends Closeable {
//
// /**
// * Called to register the extension's resources when the rest server starts up.
// *
// * @param config the configuration used to register resources
// * @param app the application.
// */
// void register(Configurable<?> config, AppT app);
//
// @SuppressWarnings("RedundantThrows")
// default void close() throws IOException {
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/metrics/RestMetricsContext.java
// public final class RestMetricsContext implements MetricsContext {
// /**
// * Client or Service's metadata map.
// */
// private final Map<String, String> contextLabels;
//
// public RestMetricsContext(String namespace,
// Map<String, Object> config) {
// contextLabels = new HashMap<>();
// contextLabels.put(MetricsContext.NAMESPACE, namespace);
// config.forEach((key, value) -> contextLabels.put(key, value.toString()));
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// this.contextLabels.put(labelKey, labelValue);
// }
//
// public void setLabels(Map<String, String> labels) {
// labels.forEach(this::setLabel);
// }
//
// /**
// * Returns the value associated with the specified label else
// * {@code null}.
// */
// public String getLabel(String label) {
// return contextLabels.get(label);
// }
//
// /**
// * Returns {@link MetricsContext} as an unmodifiable Map.
// */
// @Override
// public Map<String, String> contextLabels() {
// return Collections.unmodifiableMap(contextLabels);
// }
// }
// Path: core/src/test/java/io/confluent/rest/ApplicationTest.java
import static io.confluent.rest.metrics.TestRestMetricsContext.RESOURCE_LABEL_TYPE;
import static org.apache.kafka.common.metrics.MetricsContext.NAMESPACE;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.ImmutableMap;
import io.confluent.rest.extension.ResourceExtension;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.MediaType;
import io.confluent.rest.metrics.RestMetricsContext;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.kafka.common.config.ConfigException;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpStatus.Code;
import org.eclipse.jetty.jaas.JAASLoginService;
import org.eclipse.jetty.security.authentication.LoginAuthenticator;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.security.Constraint;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public void testMetricsContextJMXBeanRegistration() throws Exception {
Map<String, Object> props = new HashMap<>();
props.put(RestConfig.METRICS_JMX_PREFIX_CONFIG, "FooApp");
new TestApp(props);
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
assertNotNull(server.getObjectInstance(new ObjectName("FooApp:type=kafka-metrics-count")));
}
private void assertExpectedUri(URI uri, String scheme, String host, int port) {
assertEquals(scheme, uri.getScheme(), "Scheme should be " + scheme);
assertEquals(host, uri.getHost(), "Host should be " + host);
assertEquals(port, uri.getPort(), "Port should be " + port);
}
@SuppressWarnings("SameParameterValue")
private HttpStatus.Code makeGetRequest(final TestApp app, final String path) throws Exception {
final HttpGet httpget = new HttpGet(app.getListeners().get(0).toString() + path);
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpget)) {
return HttpStatus.getCode(response.getStatusLine().getStatusCode());
}
}
private static class TestApp extends Application<TestRestConfig> implements AutoCloseable {
private static final AtomicBoolean SHUTDOWN_CALLED = new AtomicBoolean(true);
@SafeVarargs | private TestApp(final Class<? extends ResourceExtension>... extensions) throws Exception { |
confluentinc/rest-utils | core/src/test/java/io/confluent/rest/ApplicationTest.java | // Path: core/src/test/java/io/confluent/rest/metrics/TestRestMetricsContext.java
// public static final String RESOURCE_LABEL_TYPE = RESOURCE_LABEL_PREFIX + "type";
//
// Path: core/src/main/java/io/confluent/rest/extension/ResourceExtension.java
// public interface ResourceExtension<AppT extends Application<? extends RestConfig>>
// extends Closeable {
//
// /**
// * Called to register the extension's resources when the rest server starts up.
// *
// * @param config the configuration used to register resources
// * @param app the application.
// */
// void register(Configurable<?> config, AppT app);
//
// @SuppressWarnings("RedundantThrows")
// default void close() throws IOException {
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/metrics/RestMetricsContext.java
// public final class RestMetricsContext implements MetricsContext {
// /**
// * Client or Service's metadata map.
// */
// private final Map<String, String> contextLabels;
//
// public RestMetricsContext(String namespace,
// Map<String, Object> config) {
// contextLabels = new HashMap<>();
// contextLabels.put(MetricsContext.NAMESPACE, namespace);
// config.forEach((key, value) -> contextLabels.put(key, value.toString()));
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// this.contextLabels.put(labelKey, labelValue);
// }
//
// public void setLabels(Map<String, String> labels) {
// labels.forEach(this::setLabel);
// }
//
// /**
// * Returns the value associated with the specified label else
// * {@code null}.
// */
// public String getLabel(String label) {
// return contextLabels.get(label);
// }
//
// /**
// * Returns {@link MetricsContext} as an unmodifiable Map.
// */
// @Override
// public Map<String, String> contextLabels() {
// return Collections.unmodifiableMap(contextLabels);
// }
// }
| import static io.confluent.rest.metrics.TestRestMetricsContext.RESOURCE_LABEL_TYPE;
import static org.apache.kafka.common.metrics.MetricsContext.NAMESPACE;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.ImmutableMap;
import io.confluent.rest.extension.ResourceExtension;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.MediaType;
import io.confluent.rest.metrics.RestMetricsContext;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.kafka.common.config.ConfigException;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpStatus.Code;
import org.eclipse.jetty.jaas.JAASLoginService;
import org.eclipse.jetty.security.authentication.LoginAuthenticator;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.security.Constraint;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | private void assertExpectedUri(URI uri, String scheme, String host, int port) {
assertEquals(scheme, uri.getScheme(), "Scheme should be " + scheme);
assertEquals(host, uri.getHost(), "Host should be " + host);
assertEquals(port, uri.getPort(), "Port should be " + port);
}
@SuppressWarnings("SameParameterValue")
private HttpStatus.Code makeGetRequest(final TestApp app, final String path) throws Exception {
final HttpGet httpget = new HttpGet(app.getListeners().get(0).toString() + path);
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpget)) {
return HttpStatus.getCode(response.getStatusLine().getStatusCode());
}
}
private static class TestApp extends Application<TestRestConfig> implements AutoCloseable {
private static final AtomicBoolean SHUTDOWN_CALLED = new AtomicBoolean(true);
@SafeVarargs
private TestApp(final Class<? extends ResourceExtension>... extensions) throws Exception {
super(createConfig(extensions));
start();
}
public TestApp(final Map<String, Object> config) {
super(createConfig(config));
}
| // Path: core/src/test/java/io/confluent/rest/metrics/TestRestMetricsContext.java
// public static final String RESOURCE_LABEL_TYPE = RESOURCE_LABEL_PREFIX + "type";
//
// Path: core/src/main/java/io/confluent/rest/extension/ResourceExtension.java
// public interface ResourceExtension<AppT extends Application<? extends RestConfig>>
// extends Closeable {
//
// /**
// * Called to register the extension's resources when the rest server starts up.
// *
// * @param config the configuration used to register resources
// * @param app the application.
// */
// void register(Configurable<?> config, AppT app);
//
// @SuppressWarnings("RedundantThrows")
// default void close() throws IOException {
// }
// }
//
// Path: core/src/main/java/io/confluent/rest/metrics/RestMetricsContext.java
// public final class RestMetricsContext implements MetricsContext {
// /**
// * Client or Service's metadata map.
// */
// private final Map<String, String> contextLabels;
//
// public RestMetricsContext(String namespace,
// Map<String, Object> config) {
// contextLabels = new HashMap<>();
// contextLabels.put(MetricsContext.NAMESPACE, namespace);
// config.forEach((key, value) -> contextLabels.put(key, value.toString()));
// }
//
// /**
// * Sets a {@link MetricsContext} key, value pair.
// */
// public void setLabel(String labelKey, String labelValue) {
// this.contextLabels.put(labelKey, labelValue);
// }
//
// public void setLabels(Map<String, String> labels) {
// labels.forEach(this::setLabel);
// }
//
// /**
// * Returns the value associated with the specified label else
// * {@code null}.
// */
// public String getLabel(String label) {
// return contextLabels.get(label);
// }
//
// /**
// * Returns {@link MetricsContext} as an unmodifiable Map.
// */
// @Override
// public Map<String, String> contextLabels() {
// return Collections.unmodifiableMap(contextLabels);
// }
// }
// Path: core/src/test/java/io/confluent/rest/ApplicationTest.java
import static io.confluent.rest.metrics.TestRestMetricsContext.RESOURCE_LABEL_TYPE;
import static org.apache.kafka.common.metrics.MetricsContext.NAMESPACE;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.ImmutableMap;
import io.confluent.rest.extension.ResourceExtension;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Configurable;
import javax.ws.rs.core.MediaType;
import io.confluent.rest.metrics.RestMetricsContext;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.kafka.common.config.ConfigException;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpStatus.Code;
import org.eclipse.jetty.jaas.JAASLoginService;
import org.eclipse.jetty.security.authentication.LoginAuthenticator;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.security.Constraint;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
private void assertExpectedUri(URI uri, String scheme, String host, int port) {
assertEquals(scheme, uri.getScheme(), "Scheme should be " + scheme);
assertEquals(host, uri.getHost(), "Host should be " + host);
assertEquals(port, uri.getPort(), "Port should be " + port);
}
@SuppressWarnings("SameParameterValue")
private HttpStatus.Code makeGetRequest(final TestApp app, final String path) throws Exception {
final HttpGet httpget = new HttpGet(app.getListeners().get(0).toString() + path);
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpget)) {
return HttpStatus.getCode(response.getStatusLine().getStatusCode());
}
}
private static class TestApp extends Application<TestRestConfig> implements AutoCloseable {
private static final AtomicBoolean SHUTDOWN_CALLED = new AtomicBoolean(true);
@SafeVarargs
private TestApp(final Class<? extends ResourceExtension>... extensions) throws Exception {
super(createConfig(extensions));
start();
}
public TestApp(final Map<String, Object> config) {
super(createConfig(config));
}
| public RestMetricsContext metricsContext() { |
vikasdesale/News24x7-news-from-every-part-of-the-world | app/src/main/java/com/news/news24x7/retrofit/NewsResponse.java | // Path: app/src/main/java/com/news/news24x7/parcelable/Article.java
// public class Article implements Serializable, Parcelable {
//
// private final static long serialVersionUID = 8755682695955568073L;
// public final Parcelable.Creator<Article> CREATOR = new Parcelable.Creator<Article>() {
// @Override
// public Article createFromParcel(Parcel parcel) {
// return new Article(parcel);
// }
//
// @Override
// public Article[] newArray(int i) {
// return new Article[i];
// }
//
// };
// @SerializedName("author")
// private String author;
// @SerializedName("title")
// private String title;
// @SerializedName("description")
// private String description;
// @SerializedName("url")
// private String url;
// @SerializedName("urlToImage")
// private String urlToImage;
// @SerializedName("publishedAt")
// private String publishedAt;
//
// public Article(String mTitle, String mAuthor, String mDescription, String mUrl, String mUrlToImage, String mPublishedAt) {
// this.title = mTitle;
// this.author = mAuthor;
// this.description = mDescription;
// this.url = mUrl;
// this.urlToImage = mUrlToImage;
// this.publishedAt = mPublishedAt;
// }
//
//
// private Article(Parcel in) {
// this.author = in.readString();
// this.title = in.readString();
// this.description = in.readString();
// this.url = in.readString();
// this.urlToImage = in.readString();
// this.publishedAt = in.readString();
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getUrlToImage() {
// return urlToImage;
// }
//
// public void setUrlToImage(String urlToImage) {
// this.urlToImage = urlToImage;
// }
//
// public String getPublishedAt() {
// return publishedAt;
// }
//
// public void setPublishedAt(String publishedAt) {
// this.publishedAt = publishedAt;
// }
//
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeValue(author);
// dest.writeValue(title);
// dest.writeValue(description);
// dest.writeValue(url);
// dest.writeValue(urlToImage);
// dest.writeValue(publishedAt);
// }
//
// public int describeContents() {
// return 0;
// }
//
// }
| import com.news.news24x7.parcelable.Article;
import com.google.gson.annotations.SerializedName;
import java.util.List; | package com.news.news24x7.retrofit;
/**
* Created by Dell on 6/3/2017.
*/
public class NewsResponse {
@SerializedName("status")
private String status;
@SerializedName("source")
private String source;
@SerializedName("sortBy")
private String sortBy;
@SerializedName("articles") | // Path: app/src/main/java/com/news/news24x7/parcelable/Article.java
// public class Article implements Serializable, Parcelable {
//
// private final static long serialVersionUID = 8755682695955568073L;
// public final Parcelable.Creator<Article> CREATOR = new Parcelable.Creator<Article>() {
// @Override
// public Article createFromParcel(Parcel parcel) {
// return new Article(parcel);
// }
//
// @Override
// public Article[] newArray(int i) {
// return new Article[i];
// }
//
// };
// @SerializedName("author")
// private String author;
// @SerializedName("title")
// private String title;
// @SerializedName("description")
// private String description;
// @SerializedName("url")
// private String url;
// @SerializedName("urlToImage")
// private String urlToImage;
// @SerializedName("publishedAt")
// private String publishedAt;
//
// public Article(String mTitle, String mAuthor, String mDescription, String mUrl, String mUrlToImage, String mPublishedAt) {
// this.title = mTitle;
// this.author = mAuthor;
// this.description = mDescription;
// this.url = mUrl;
// this.urlToImage = mUrlToImage;
// this.publishedAt = mPublishedAt;
// }
//
//
// private Article(Parcel in) {
// this.author = in.readString();
// this.title = in.readString();
// this.description = in.readString();
// this.url = in.readString();
// this.urlToImage = in.readString();
// this.publishedAt = in.readString();
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getUrlToImage() {
// return urlToImage;
// }
//
// public void setUrlToImage(String urlToImage) {
// this.urlToImage = urlToImage;
// }
//
// public String getPublishedAt() {
// return publishedAt;
// }
//
// public void setPublishedAt(String publishedAt) {
// this.publishedAt = publishedAt;
// }
//
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeValue(author);
// dest.writeValue(title);
// dest.writeValue(description);
// dest.writeValue(url);
// dest.writeValue(urlToImage);
// dest.writeValue(publishedAt);
// }
//
// public int describeContents() {
// return 0;
// }
//
// }
// Path: app/src/main/java/com/news/news24x7/retrofit/NewsResponse.java
import com.news.news24x7.parcelable.Article;
import com.google.gson.annotations.SerializedName;
import java.util.List;
package com.news.news24x7.retrofit;
/**
* Created by Dell on 6/3/2017.
*/
public class NewsResponse {
@SerializedName("status")
private String status;
@SerializedName("source")
private String source;
@SerializedName("sortBy")
private String sortBy;
@SerializedName("articles") | private List<Article> articles = null; |
vikasdesale/News24x7-news-from-every-part-of-the-world | app/src/main/java/com/news/news24x7/fragments/NewsLoader.java | // Path: app/src/main/java/com/news/news24x7/adapter/NewsRecyclerViewAdapter.java
// public class NewsRecyclerViewAdapter extends CursorRecyclerViewAdapter<NewsRecyclerViewAdapter.ViewHolder> {
//
// public ClickListener clickListener;
// Cursor mCursor;
// private Context mContext;
// private View view;
//
// public NewsRecyclerViewAdapter(Context context, Cursor cursor) {
// super(cursor);
// mContext = context;
// mCursor = cursor;
// }
//
// @Override
// public void onBindViewHolderCursor(ViewHolder viewHolder, Cursor cursor) {
// String title = cursor.getString(cursor.getColumnIndex(ColumnsNews.TITLE));
// String url = cursor.getString(cursor.getColumnIndex(ColumnsNews.URL_TO_IMAGE));
// String publishedAt = cursor.getString(cursor.getColumnIndex(ColumnsNews.PUBLISHED_AT));
// viewHolder.imageView.setImageDrawable(null);
//
//
// if (title != null || url != null) {
// viewHolder.textView.setText(title);
// viewHolder.textView.setContentDescription(mContext.getString(R.string.content_desc_title)+title);
// viewHolder.dates.setText(Util.manipulateDateFormat(publishedAt));
// viewHolder.dates.setContentDescription(mContext.getString(R.string.content_description_dates)+Util.manipulateDateFormat(publishedAt));
// //Got Advantages why to use Glide over picasso that's why replaced picasso.
// Glide.with(mContext).load(url)
// .thumbnail(0.1f)
// .error(placeholder)
// .crossFade() //animation
// .diskCacheStrategy(DiskCacheStrategy.SOURCE)
// .skipMemoryCache(true)
// .into(viewHolder.imageView);
// viewHolder.imageView.setContentDescription(mContext.getString(R.string.article_image));
// } else {
// viewHolder.imageView.setImageDrawable(null);
// viewHolder.textView.setText(R.string.no_image_title);
// viewHolder.imageView.setImageResource(R.drawable.placeholder);
// // this enables better animations. even if we lose state due to a device rotation,
// // the animator can use this to re-find the original view
// ViewCompat.setTransitionName(viewHolder.imageView, "iconView" +cursor.getPosition());
//
// }
//
//
// }
//
// @Override
// public int getItemCount() {
// return mCursor.getCount();
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
//
// view = LayoutInflater.from(viewGroup.getContext())
// .inflate(R.layout.news_list, viewGroup, false);
//
//
// return new ViewHolder(view);
// }
//
// public void setClickListener(ClickListener clickListener) {
//
// this.clickListener = clickListener;
// }
//
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
//
// public interface ClickListener {
// public void itemClicked(View view, int position,NewsRecyclerViewAdapter.ViewHolder vh);
// }
//
// public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//
// @BindView(R.id.news_article_title)
// TextView textView;
// @BindView(R.id.news_published_at)
// TextView dates;
// @BindView(R.id.backdrop)
// public
// ImageView imageView;
//
// public ViewHolder(View itemView) {
// super(itemView);
// ButterKnife.bind(this, view);
// itemView.setOnClickListener(this);
//
// }
//
// @Override
// public void onClick(View v) {
// ViewHolder vh=new ViewHolder(v);
// if (clickListener != null) {
// clickListener.itemClicked(v, getPosition(), vh);
// }
// }
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/database/NewsProvider.java
// @ContentProvider(authority = NewsProvider.AUTHORITY, database = NewsDatabase.class)
// public class NewsProvider {
//
// public static final String AUTHORITY = "com.news.news24x7";
// public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
//
// private static Uri buildUri(String... paths) {
// Uri.Builder builder = BASE_CONTENT_URI.buildUpon();
// for (String path : paths) {
// builder.appendPath(path);
// }
// return builder.build();
// }
//
// interface Path {
// String MY_NEWS = "myNews";
// String FAVOURITE_NEWS = "myFavouriteNews";
// }
//
// @TableEndpoint(table = NewsDatabase.MY_NEWS)
// public static class MyNews {
// @ContentUri(
// path = Path.MY_NEWS,
// type = "vnd.android.cursor.dir/myNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI = buildUri(Path.MY_NEWS);
//
// }
//
// @TableEndpoint(table = NewsDatabase.FAVOURITE_NEWS)
// public static class NewsFavourite {
// @ContentUri(
// path = Path.FAVOURITE_NEWS,
// type = "vnd.android.cursor.dir/myFavouriteNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI_FAVOURITE = buildUri(Path.FAVOURITE_NEWS);
//
// }
// }
| import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import com.news.news24x7.adapter.NewsRecyclerViewAdapter;
import com.news.news24x7.database.NewsProvider; | package com.news.news24x7.fragments;
/**
* Created by Dell on 1/28/2017.
*/
public class NewsLoader implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int NEWS_LOADER = 0;
private static int favflag = -1;
private Fragment mAttachedFragment; | // Path: app/src/main/java/com/news/news24x7/adapter/NewsRecyclerViewAdapter.java
// public class NewsRecyclerViewAdapter extends CursorRecyclerViewAdapter<NewsRecyclerViewAdapter.ViewHolder> {
//
// public ClickListener clickListener;
// Cursor mCursor;
// private Context mContext;
// private View view;
//
// public NewsRecyclerViewAdapter(Context context, Cursor cursor) {
// super(cursor);
// mContext = context;
// mCursor = cursor;
// }
//
// @Override
// public void onBindViewHolderCursor(ViewHolder viewHolder, Cursor cursor) {
// String title = cursor.getString(cursor.getColumnIndex(ColumnsNews.TITLE));
// String url = cursor.getString(cursor.getColumnIndex(ColumnsNews.URL_TO_IMAGE));
// String publishedAt = cursor.getString(cursor.getColumnIndex(ColumnsNews.PUBLISHED_AT));
// viewHolder.imageView.setImageDrawable(null);
//
//
// if (title != null || url != null) {
// viewHolder.textView.setText(title);
// viewHolder.textView.setContentDescription(mContext.getString(R.string.content_desc_title)+title);
// viewHolder.dates.setText(Util.manipulateDateFormat(publishedAt));
// viewHolder.dates.setContentDescription(mContext.getString(R.string.content_description_dates)+Util.manipulateDateFormat(publishedAt));
// //Got Advantages why to use Glide over picasso that's why replaced picasso.
// Glide.with(mContext).load(url)
// .thumbnail(0.1f)
// .error(placeholder)
// .crossFade() //animation
// .diskCacheStrategy(DiskCacheStrategy.SOURCE)
// .skipMemoryCache(true)
// .into(viewHolder.imageView);
// viewHolder.imageView.setContentDescription(mContext.getString(R.string.article_image));
// } else {
// viewHolder.imageView.setImageDrawable(null);
// viewHolder.textView.setText(R.string.no_image_title);
// viewHolder.imageView.setImageResource(R.drawable.placeholder);
// // this enables better animations. even if we lose state due to a device rotation,
// // the animator can use this to re-find the original view
// ViewCompat.setTransitionName(viewHolder.imageView, "iconView" +cursor.getPosition());
//
// }
//
//
// }
//
// @Override
// public int getItemCount() {
// return mCursor.getCount();
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
//
// view = LayoutInflater.from(viewGroup.getContext())
// .inflate(R.layout.news_list, viewGroup, false);
//
//
// return new ViewHolder(view);
// }
//
// public void setClickListener(ClickListener clickListener) {
//
// this.clickListener = clickListener;
// }
//
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
//
// public interface ClickListener {
// public void itemClicked(View view, int position,NewsRecyclerViewAdapter.ViewHolder vh);
// }
//
// public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//
// @BindView(R.id.news_article_title)
// TextView textView;
// @BindView(R.id.news_published_at)
// TextView dates;
// @BindView(R.id.backdrop)
// public
// ImageView imageView;
//
// public ViewHolder(View itemView) {
// super(itemView);
// ButterKnife.bind(this, view);
// itemView.setOnClickListener(this);
//
// }
//
// @Override
// public void onClick(View v) {
// ViewHolder vh=new ViewHolder(v);
// if (clickListener != null) {
// clickListener.itemClicked(v, getPosition(), vh);
// }
// }
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/database/NewsProvider.java
// @ContentProvider(authority = NewsProvider.AUTHORITY, database = NewsDatabase.class)
// public class NewsProvider {
//
// public static final String AUTHORITY = "com.news.news24x7";
// public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
//
// private static Uri buildUri(String... paths) {
// Uri.Builder builder = BASE_CONTENT_URI.buildUpon();
// for (String path : paths) {
// builder.appendPath(path);
// }
// return builder.build();
// }
//
// interface Path {
// String MY_NEWS = "myNews";
// String FAVOURITE_NEWS = "myFavouriteNews";
// }
//
// @TableEndpoint(table = NewsDatabase.MY_NEWS)
// public static class MyNews {
// @ContentUri(
// path = Path.MY_NEWS,
// type = "vnd.android.cursor.dir/myNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI = buildUri(Path.MY_NEWS);
//
// }
//
// @TableEndpoint(table = NewsDatabase.FAVOURITE_NEWS)
// public static class NewsFavourite {
// @ContentUri(
// path = Path.FAVOURITE_NEWS,
// type = "vnd.android.cursor.dir/myFavouriteNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI_FAVOURITE = buildUri(Path.FAVOURITE_NEWS);
//
// }
// }
// Path: app/src/main/java/com/news/news24x7/fragments/NewsLoader.java
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import com.news.news24x7.adapter.NewsRecyclerViewAdapter;
import com.news.news24x7.database.NewsProvider;
package com.news.news24x7.fragments;
/**
* Created by Dell on 1/28/2017.
*/
public class NewsLoader implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int NEWS_LOADER = 0;
private static int favflag = -1;
private Fragment mAttachedFragment; | private NewsRecyclerViewAdapter gridAdapter; |
vikasdesale/News24x7-news-from-every-part-of-the-world | app/src/main/java/com/news/news24x7/database/NewsDatabase.java | // Path: app/src/main/java/com/news/news24x7/interfaces/ColumnsNews.java
// public interface ColumnsNews {
// @DataType(DataType.Type.INTEGER)
// @PrimaryKey
// @AutoIncrement
// String _ID = "_id";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String AUTHOR = "author";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String TITLE = "title";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String DESCRIPTION = "description";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL = "url";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL_TO_IMAGE = "urlToImage";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String PUBLISHED_AT = "publishedAt";
//
//
// }
| import com.news.news24x7.interfaces.ColumnsNews;
import net.simonvt.schematic.annotation.Database;
import net.simonvt.schematic.annotation.Table; | package com.news.news24x7.database;
/**
* Created by Dell on 6/4/2017.
*/
@Database(version = NewsDatabase.VERSION)
public class NewsDatabase {
public static final int VERSION = 2;
//temporary table | // Path: app/src/main/java/com/news/news24x7/interfaces/ColumnsNews.java
// public interface ColumnsNews {
// @DataType(DataType.Type.INTEGER)
// @PrimaryKey
// @AutoIncrement
// String _ID = "_id";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String AUTHOR = "author";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String TITLE = "title";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String DESCRIPTION = "description";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL = "url";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL_TO_IMAGE = "urlToImage";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String PUBLISHED_AT = "publishedAt";
//
//
// }
// Path: app/src/main/java/com/news/news24x7/database/NewsDatabase.java
import com.news.news24x7.interfaces.ColumnsNews;
import net.simonvt.schematic.annotation.Database;
import net.simonvt.schematic.annotation.Table;
package com.news.news24x7.database;
/**
* Created by Dell on 6/4/2017.
*/
@Database(version = NewsDatabase.VERSION)
public class NewsDatabase {
public static final int VERSION = 2;
//temporary table | @Table(ColumnsNews.class) |
vikasdesale/News24x7-news-from-every-part-of-the-world | app/src/main/java/com/news/news24x7/widget/NewsWidgetViewsFactory.java | // Path: app/src/main/java/com/news/news24x7/activities/DetailsActivity.java
// public class DetailsActivity extends AppCompatActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (Build.VERSION.SDK_INT >= 21) {
//
// TransitionInflater inflater = TransitionInflater.from(this);
// Transition transition = inflater.inflateTransition(R.transition.details_window_return_transition);
// getWindow().setExitTransition(transition);
// }
// // setUpWindowAnimations();
// setContentView(R.layout.activity_article_detail);
// if (savedInstanceState == null) {
// // Create the detail fragment and add it to the activity
// // using a fragment transaction.
//
// Bundle extras = getIntent().getExtras();
//
// DetailsFragment fragment = new DetailsFragment();
// extras.putBoolean(DetailsFragment.DETAIL_TRANSITION_ANIMATION, true);
//
// fragment.setArguments(extras);
// getSupportFragmentManager().beginTransaction()
// .add(R.id.container, fragment)
// .commit();
//
//
// // Being here means we are in animation mode
// supportPostponeEnterTransition();
// }
// }
//
// private void setUpWindowAnimations() {
// if (android.os.Build.VERSION.SDK_INT >= 21) {
// Slide slide = new Slide(Gravity.START);
// slide.setDuration(3000);
// getWindow().setEnterTransition(slide);
// }
// }
//
//
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
//
//
// return super.onOptionsItemSelected(item);
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/database/NewsProvider.java
// @ContentProvider(authority = NewsProvider.AUTHORITY, database = NewsDatabase.class)
// public class NewsProvider {
//
// public static final String AUTHORITY = "com.news.news24x7";
// public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
//
// private static Uri buildUri(String... paths) {
// Uri.Builder builder = BASE_CONTENT_URI.buildUpon();
// for (String path : paths) {
// builder.appendPath(path);
// }
// return builder.build();
// }
//
// interface Path {
// String MY_NEWS = "myNews";
// String FAVOURITE_NEWS = "myFavouriteNews";
// }
//
// @TableEndpoint(table = NewsDatabase.MY_NEWS)
// public static class MyNews {
// @ContentUri(
// path = Path.MY_NEWS,
// type = "vnd.android.cursor.dir/myNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI = buildUri(Path.MY_NEWS);
//
// }
//
// @TableEndpoint(table = NewsDatabase.FAVOURITE_NEWS)
// public static class NewsFavourite {
// @ContentUri(
// path = Path.FAVOURITE_NEWS,
// type = "vnd.android.cursor.dir/myFavouriteNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI_FAVOURITE = buildUri(Path.FAVOURITE_NEWS);
//
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/interfaces/ColumnsNews.java
// public interface ColumnsNews {
// @DataType(DataType.Type.INTEGER)
// @PrimaryKey
// @AutoIncrement
// String _ID = "_id";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String AUTHOR = "author";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String TITLE = "title";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String DESCRIPTION = "description";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL = "url";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL_TO_IMAGE = "urlToImage";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String PUBLISHED_AT = "publishedAt";
//
//
// }
| import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Binder;
import android.os.Bundle;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.news.news24x7.R;
import com.news.news24x7.activities.DetailsActivity;
import com.news.news24x7.database.NewsProvider;
import com.news.news24x7.interfaces.ColumnsNews;
import com.bumptech.glide.Glide;
import java.util.concurrent.ExecutionException; | package com.news.news24x7.widget;
/**
* Created by Dell on 6/10/2017.
*/
public class NewsWidgetViewsFactory implements RemoteViewsService.RemoteViewsFactory {
long token;
String mTitle;
String mAuthor;
String mDescription;
String mUrl;
String mUrlToImage;
String mPublishedAt;
private Cursor cursor;
private Context context = null;
private int appWidgetId;
public NewsWidgetViewsFactory(Context context, Intent intent) {
this.context = context;
this.appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
@Override
public void onCreate() {
query();
}
@Override
public void onDataSetChanged() {
query();
}
public void query() {
token = Binder.clearCallingIdentity(); | // Path: app/src/main/java/com/news/news24x7/activities/DetailsActivity.java
// public class DetailsActivity extends AppCompatActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (Build.VERSION.SDK_INT >= 21) {
//
// TransitionInflater inflater = TransitionInflater.from(this);
// Transition transition = inflater.inflateTransition(R.transition.details_window_return_transition);
// getWindow().setExitTransition(transition);
// }
// // setUpWindowAnimations();
// setContentView(R.layout.activity_article_detail);
// if (savedInstanceState == null) {
// // Create the detail fragment and add it to the activity
// // using a fragment transaction.
//
// Bundle extras = getIntent().getExtras();
//
// DetailsFragment fragment = new DetailsFragment();
// extras.putBoolean(DetailsFragment.DETAIL_TRANSITION_ANIMATION, true);
//
// fragment.setArguments(extras);
// getSupportFragmentManager().beginTransaction()
// .add(R.id.container, fragment)
// .commit();
//
//
// // Being here means we are in animation mode
// supportPostponeEnterTransition();
// }
// }
//
// private void setUpWindowAnimations() {
// if (android.os.Build.VERSION.SDK_INT >= 21) {
// Slide slide = new Slide(Gravity.START);
// slide.setDuration(3000);
// getWindow().setEnterTransition(slide);
// }
// }
//
//
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
//
//
// return super.onOptionsItemSelected(item);
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/database/NewsProvider.java
// @ContentProvider(authority = NewsProvider.AUTHORITY, database = NewsDatabase.class)
// public class NewsProvider {
//
// public static final String AUTHORITY = "com.news.news24x7";
// public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
//
// private static Uri buildUri(String... paths) {
// Uri.Builder builder = BASE_CONTENT_URI.buildUpon();
// for (String path : paths) {
// builder.appendPath(path);
// }
// return builder.build();
// }
//
// interface Path {
// String MY_NEWS = "myNews";
// String FAVOURITE_NEWS = "myFavouriteNews";
// }
//
// @TableEndpoint(table = NewsDatabase.MY_NEWS)
// public static class MyNews {
// @ContentUri(
// path = Path.MY_NEWS,
// type = "vnd.android.cursor.dir/myNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI = buildUri(Path.MY_NEWS);
//
// }
//
// @TableEndpoint(table = NewsDatabase.FAVOURITE_NEWS)
// public static class NewsFavourite {
// @ContentUri(
// path = Path.FAVOURITE_NEWS,
// type = "vnd.android.cursor.dir/myFavouriteNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI_FAVOURITE = buildUri(Path.FAVOURITE_NEWS);
//
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/interfaces/ColumnsNews.java
// public interface ColumnsNews {
// @DataType(DataType.Type.INTEGER)
// @PrimaryKey
// @AutoIncrement
// String _ID = "_id";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String AUTHOR = "author";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String TITLE = "title";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String DESCRIPTION = "description";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL = "url";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL_TO_IMAGE = "urlToImage";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String PUBLISHED_AT = "publishedAt";
//
//
// }
// Path: app/src/main/java/com/news/news24x7/widget/NewsWidgetViewsFactory.java
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Binder;
import android.os.Bundle;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.news.news24x7.R;
import com.news.news24x7.activities.DetailsActivity;
import com.news.news24x7.database.NewsProvider;
import com.news.news24x7.interfaces.ColumnsNews;
import com.bumptech.glide.Glide;
import java.util.concurrent.ExecutionException;
package com.news.news24x7.widget;
/**
* Created by Dell on 6/10/2017.
*/
public class NewsWidgetViewsFactory implements RemoteViewsService.RemoteViewsFactory {
long token;
String mTitle;
String mAuthor;
String mDescription;
String mUrl;
String mUrlToImage;
String mPublishedAt;
private Cursor cursor;
private Context context = null;
private int appWidgetId;
public NewsWidgetViewsFactory(Context context, Intent intent) {
this.context = context;
this.appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
@Override
public void onCreate() {
query();
}
@Override
public void onDataSetChanged() {
query();
}
public void query() {
token = Binder.clearCallingIdentity(); | cursor = context.getContentResolver().query(NewsProvider.MyNews.CONTENT_URI, |
vikasdesale/News24x7-news-from-every-part-of-the-world | app/src/main/java/com/news/news24x7/widget/NewsWidgetViewsFactory.java | // Path: app/src/main/java/com/news/news24x7/activities/DetailsActivity.java
// public class DetailsActivity extends AppCompatActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (Build.VERSION.SDK_INT >= 21) {
//
// TransitionInflater inflater = TransitionInflater.from(this);
// Transition transition = inflater.inflateTransition(R.transition.details_window_return_transition);
// getWindow().setExitTransition(transition);
// }
// // setUpWindowAnimations();
// setContentView(R.layout.activity_article_detail);
// if (savedInstanceState == null) {
// // Create the detail fragment and add it to the activity
// // using a fragment transaction.
//
// Bundle extras = getIntent().getExtras();
//
// DetailsFragment fragment = new DetailsFragment();
// extras.putBoolean(DetailsFragment.DETAIL_TRANSITION_ANIMATION, true);
//
// fragment.setArguments(extras);
// getSupportFragmentManager().beginTransaction()
// .add(R.id.container, fragment)
// .commit();
//
//
// // Being here means we are in animation mode
// supportPostponeEnterTransition();
// }
// }
//
// private void setUpWindowAnimations() {
// if (android.os.Build.VERSION.SDK_INT >= 21) {
// Slide slide = new Slide(Gravity.START);
// slide.setDuration(3000);
// getWindow().setEnterTransition(slide);
// }
// }
//
//
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
//
//
// return super.onOptionsItemSelected(item);
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/database/NewsProvider.java
// @ContentProvider(authority = NewsProvider.AUTHORITY, database = NewsDatabase.class)
// public class NewsProvider {
//
// public static final String AUTHORITY = "com.news.news24x7";
// public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
//
// private static Uri buildUri(String... paths) {
// Uri.Builder builder = BASE_CONTENT_URI.buildUpon();
// for (String path : paths) {
// builder.appendPath(path);
// }
// return builder.build();
// }
//
// interface Path {
// String MY_NEWS = "myNews";
// String FAVOURITE_NEWS = "myFavouriteNews";
// }
//
// @TableEndpoint(table = NewsDatabase.MY_NEWS)
// public static class MyNews {
// @ContentUri(
// path = Path.MY_NEWS,
// type = "vnd.android.cursor.dir/myNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI = buildUri(Path.MY_NEWS);
//
// }
//
// @TableEndpoint(table = NewsDatabase.FAVOURITE_NEWS)
// public static class NewsFavourite {
// @ContentUri(
// path = Path.FAVOURITE_NEWS,
// type = "vnd.android.cursor.dir/myFavouriteNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI_FAVOURITE = buildUri(Path.FAVOURITE_NEWS);
//
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/interfaces/ColumnsNews.java
// public interface ColumnsNews {
// @DataType(DataType.Type.INTEGER)
// @PrimaryKey
// @AutoIncrement
// String _ID = "_id";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String AUTHOR = "author";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String TITLE = "title";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String DESCRIPTION = "description";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL = "url";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL_TO_IMAGE = "urlToImage";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String PUBLISHED_AT = "publishedAt";
//
//
// }
| import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Binder;
import android.os.Bundle;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.news.news24x7.R;
import com.news.news24x7.activities.DetailsActivity;
import com.news.news24x7.database.NewsProvider;
import com.news.news24x7.interfaces.ColumnsNews;
import com.bumptech.glide.Glide;
import java.util.concurrent.ExecutionException; | }
public void query() {
token = Binder.clearCallingIdentity();
cursor = context.getContentResolver().query(NewsProvider.MyNews.CONTENT_URI,
null, null, null, null);
Binder.restoreCallingIdentity(token);
}
@Override
public void onDestroy() {
// Releases the cursor when we are done with it
if (cursor != null) {
cursor.close();
cursor = null;
}
}
@Override
public int getCount() {
// returns the count of the cursor or 0 if cursor is null
return cursor != null ? cursor.getCount() : 0;
}
@Override
public RemoteViews getViewAt(int position) {
// Check we have data at this view position - If we don't then exit with null
if (!cursor.moveToPosition(position))
return null; | // Path: app/src/main/java/com/news/news24x7/activities/DetailsActivity.java
// public class DetailsActivity extends AppCompatActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (Build.VERSION.SDK_INT >= 21) {
//
// TransitionInflater inflater = TransitionInflater.from(this);
// Transition transition = inflater.inflateTransition(R.transition.details_window_return_transition);
// getWindow().setExitTransition(transition);
// }
// // setUpWindowAnimations();
// setContentView(R.layout.activity_article_detail);
// if (savedInstanceState == null) {
// // Create the detail fragment and add it to the activity
// // using a fragment transaction.
//
// Bundle extras = getIntent().getExtras();
//
// DetailsFragment fragment = new DetailsFragment();
// extras.putBoolean(DetailsFragment.DETAIL_TRANSITION_ANIMATION, true);
//
// fragment.setArguments(extras);
// getSupportFragmentManager().beginTransaction()
// .add(R.id.container, fragment)
// .commit();
//
//
// // Being here means we are in animation mode
// supportPostponeEnterTransition();
// }
// }
//
// private void setUpWindowAnimations() {
// if (android.os.Build.VERSION.SDK_INT >= 21) {
// Slide slide = new Slide(Gravity.START);
// slide.setDuration(3000);
// getWindow().setEnterTransition(slide);
// }
// }
//
//
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
//
//
// return super.onOptionsItemSelected(item);
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/database/NewsProvider.java
// @ContentProvider(authority = NewsProvider.AUTHORITY, database = NewsDatabase.class)
// public class NewsProvider {
//
// public static final String AUTHORITY = "com.news.news24x7";
// public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
//
// private static Uri buildUri(String... paths) {
// Uri.Builder builder = BASE_CONTENT_URI.buildUpon();
// for (String path : paths) {
// builder.appendPath(path);
// }
// return builder.build();
// }
//
// interface Path {
// String MY_NEWS = "myNews";
// String FAVOURITE_NEWS = "myFavouriteNews";
// }
//
// @TableEndpoint(table = NewsDatabase.MY_NEWS)
// public static class MyNews {
// @ContentUri(
// path = Path.MY_NEWS,
// type = "vnd.android.cursor.dir/myNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI = buildUri(Path.MY_NEWS);
//
// }
//
// @TableEndpoint(table = NewsDatabase.FAVOURITE_NEWS)
// public static class NewsFavourite {
// @ContentUri(
// path = Path.FAVOURITE_NEWS,
// type = "vnd.android.cursor.dir/myFavouriteNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI_FAVOURITE = buildUri(Path.FAVOURITE_NEWS);
//
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/interfaces/ColumnsNews.java
// public interface ColumnsNews {
// @DataType(DataType.Type.INTEGER)
// @PrimaryKey
// @AutoIncrement
// String _ID = "_id";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String AUTHOR = "author";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String TITLE = "title";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String DESCRIPTION = "description";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL = "url";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL_TO_IMAGE = "urlToImage";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String PUBLISHED_AT = "publishedAt";
//
//
// }
// Path: app/src/main/java/com/news/news24x7/widget/NewsWidgetViewsFactory.java
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Binder;
import android.os.Bundle;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.news.news24x7.R;
import com.news.news24x7.activities.DetailsActivity;
import com.news.news24x7.database.NewsProvider;
import com.news.news24x7.interfaces.ColumnsNews;
import com.bumptech.glide.Glide;
import java.util.concurrent.ExecutionException;
}
public void query() {
token = Binder.clearCallingIdentity();
cursor = context.getContentResolver().query(NewsProvider.MyNews.CONTENT_URI,
null, null, null, null);
Binder.restoreCallingIdentity(token);
}
@Override
public void onDestroy() {
// Releases the cursor when we are done with it
if (cursor != null) {
cursor.close();
cursor = null;
}
}
@Override
public int getCount() {
// returns the count of the cursor or 0 if cursor is null
return cursor != null ? cursor.getCount() : 0;
}
@Override
public RemoteViews getViewAt(int position) {
// Check we have data at this view position - If we don't then exit with null
if (!cursor.moveToPosition(position))
return null; | mTitle = cursor.getString(cursor.getColumnIndex(ColumnsNews.TITLE)); |
vikasdesale/News24x7-news-from-every-part-of-the-world | app/src/main/java/com/news/news24x7/widget/NewsWidgetViewsFactory.java | // Path: app/src/main/java/com/news/news24x7/activities/DetailsActivity.java
// public class DetailsActivity extends AppCompatActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (Build.VERSION.SDK_INT >= 21) {
//
// TransitionInflater inflater = TransitionInflater.from(this);
// Transition transition = inflater.inflateTransition(R.transition.details_window_return_transition);
// getWindow().setExitTransition(transition);
// }
// // setUpWindowAnimations();
// setContentView(R.layout.activity_article_detail);
// if (savedInstanceState == null) {
// // Create the detail fragment and add it to the activity
// // using a fragment transaction.
//
// Bundle extras = getIntent().getExtras();
//
// DetailsFragment fragment = new DetailsFragment();
// extras.putBoolean(DetailsFragment.DETAIL_TRANSITION_ANIMATION, true);
//
// fragment.setArguments(extras);
// getSupportFragmentManager().beginTransaction()
// .add(R.id.container, fragment)
// .commit();
//
//
// // Being here means we are in animation mode
// supportPostponeEnterTransition();
// }
// }
//
// private void setUpWindowAnimations() {
// if (android.os.Build.VERSION.SDK_INT >= 21) {
// Slide slide = new Slide(Gravity.START);
// slide.setDuration(3000);
// getWindow().setEnterTransition(slide);
// }
// }
//
//
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
//
//
// return super.onOptionsItemSelected(item);
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/database/NewsProvider.java
// @ContentProvider(authority = NewsProvider.AUTHORITY, database = NewsDatabase.class)
// public class NewsProvider {
//
// public static final String AUTHORITY = "com.news.news24x7";
// public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
//
// private static Uri buildUri(String... paths) {
// Uri.Builder builder = BASE_CONTENT_URI.buildUpon();
// for (String path : paths) {
// builder.appendPath(path);
// }
// return builder.build();
// }
//
// interface Path {
// String MY_NEWS = "myNews";
// String FAVOURITE_NEWS = "myFavouriteNews";
// }
//
// @TableEndpoint(table = NewsDatabase.MY_NEWS)
// public static class MyNews {
// @ContentUri(
// path = Path.MY_NEWS,
// type = "vnd.android.cursor.dir/myNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI = buildUri(Path.MY_NEWS);
//
// }
//
// @TableEndpoint(table = NewsDatabase.FAVOURITE_NEWS)
// public static class NewsFavourite {
// @ContentUri(
// path = Path.FAVOURITE_NEWS,
// type = "vnd.android.cursor.dir/myFavouriteNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI_FAVOURITE = buildUri(Path.FAVOURITE_NEWS);
//
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/interfaces/ColumnsNews.java
// public interface ColumnsNews {
// @DataType(DataType.Type.INTEGER)
// @PrimaryKey
// @AutoIncrement
// String _ID = "_id";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String AUTHOR = "author";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String TITLE = "title";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String DESCRIPTION = "description";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL = "url";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL_TO_IMAGE = "urlToImage";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String PUBLISHED_AT = "publishedAt";
//
//
// }
| import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Binder;
import android.os.Bundle;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.news.news24x7.R;
import com.news.news24x7.activities.DetailsActivity;
import com.news.news24x7.database.NewsProvider;
import com.news.news24x7.interfaces.ColumnsNews;
import com.bumptech.glide.Glide;
import java.util.concurrent.ExecutionException; | Glide.
with(context).
load(mUrlToImage).
asBitmap().
into(200, 200). // Width and height
get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (bitmap != null) {
row.setImageViewBitmap(R.id.news_thumbnail, bitmap);
}
row.setTextViewText(R.id.news_article_title, mTitle);
row.setTextViewText(R.id.news_published_at, mPublishedAt);
Intent intent = new Intent();
Bundle extras = new Bundle();
extras.putString(NewsWidgetProvider.EXTRA_TITLE, mTitle);
extras.putString(NewsWidgetProvider.EXTRA_AUTHOR, mAuthor);
extras.putString(NewsWidgetProvider.EXTRA_DESCRIPTION, mDescription);
extras.putString(NewsWidgetProvider.EXTRA_IMAGE_URL, mUrlToImage);
extras.putString(NewsWidgetProvider.EXTRA_URL, mUrl);
extras.putString(NewsWidgetProvider.EXTRA_DATE, mPublishedAt);
intent.putExtras(extras);
row.setOnClickFillInIntent(android.R.id.text1, intent); | // Path: app/src/main/java/com/news/news24x7/activities/DetailsActivity.java
// public class DetailsActivity extends AppCompatActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (Build.VERSION.SDK_INT >= 21) {
//
// TransitionInflater inflater = TransitionInflater.from(this);
// Transition transition = inflater.inflateTransition(R.transition.details_window_return_transition);
// getWindow().setExitTransition(transition);
// }
// // setUpWindowAnimations();
// setContentView(R.layout.activity_article_detail);
// if (savedInstanceState == null) {
// // Create the detail fragment and add it to the activity
// // using a fragment transaction.
//
// Bundle extras = getIntent().getExtras();
//
// DetailsFragment fragment = new DetailsFragment();
// extras.putBoolean(DetailsFragment.DETAIL_TRANSITION_ANIMATION, true);
//
// fragment.setArguments(extras);
// getSupportFragmentManager().beginTransaction()
// .add(R.id.container, fragment)
// .commit();
//
//
// // Being here means we are in animation mode
// supportPostponeEnterTransition();
// }
// }
//
// private void setUpWindowAnimations() {
// if (android.os.Build.VERSION.SDK_INT >= 21) {
// Slide slide = new Slide(Gravity.START);
// slide.setDuration(3000);
// getWindow().setEnterTransition(slide);
// }
// }
//
//
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
//
//
// return super.onOptionsItemSelected(item);
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/database/NewsProvider.java
// @ContentProvider(authority = NewsProvider.AUTHORITY, database = NewsDatabase.class)
// public class NewsProvider {
//
// public static final String AUTHORITY = "com.news.news24x7";
// public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
//
// private static Uri buildUri(String... paths) {
// Uri.Builder builder = BASE_CONTENT_URI.buildUpon();
// for (String path : paths) {
// builder.appendPath(path);
// }
// return builder.build();
// }
//
// interface Path {
// String MY_NEWS = "myNews";
// String FAVOURITE_NEWS = "myFavouriteNews";
// }
//
// @TableEndpoint(table = NewsDatabase.MY_NEWS)
// public static class MyNews {
// @ContentUri(
// path = Path.MY_NEWS,
// type = "vnd.android.cursor.dir/myNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI = buildUri(Path.MY_NEWS);
//
// }
//
// @TableEndpoint(table = NewsDatabase.FAVOURITE_NEWS)
// public static class NewsFavourite {
// @ContentUri(
// path = Path.FAVOURITE_NEWS,
// type = "vnd.android.cursor.dir/myFavouriteNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI_FAVOURITE = buildUri(Path.FAVOURITE_NEWS);
//
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/interfaces/ColumnsNews.java
// public interface ColumnsNews {
// @DataType(DataType.Type.INTEGER)
// @PrimaryKey
// @AutoIncrement
// String _ID = "_id";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String AUTHOR = "author";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String TITLE = "title";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String DESCRIPTION = "description";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL = "url";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL_TO_IMAGE = "urlToImage";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String PUBLISHED_AT = "publishedAt";
//
//
// }
// Path: app/src/main/java/com/news/news24x7/widget/NewsWidgetViewsFactory.java
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Binder;
import android.os.Bundle;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.news.news24x7.R;
import com.news.news24x7.activities.DetailsActivity;
import com.news.news24x7.database.NewsProvider;
import com.news.news24x7.interfaces.ColumnsNews;
import com.bumptech.glide.Glide;
import java.util.concurrent.ExecutionException;
Glide.
with(context).
load(mUrlToImage).
asBitmap().
into(200, 200). // Width and height
get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (bitmap != null) {
row.setImageViewBitmap(R.id.news_thumbnail, bitmap);
}
row.setTextViewText(R.id.news_article_title, mTitle);
row.setTextViewText(R.id.news_published_at, mPublishedAt);
Intent intent = new Intent();
Bundle extras = new Bundle();
extras.putString(NewsWidgetProvider.EXTRA_TITLE, mTitle);
extras.putString(NewsWidgetProvider.EXTRA_AUTHOR, mAuthor);
extras.putString(NewsWidgetProvider.EXTRA_DESCRIPTION, mDescription);
extras.putString(NewsWidgetProvider.EXTRA_IMAGE_URL, mUrlToImage);
extras.putString(NewsWidgetProvider.EXTRA_URL, mUrl);
extras.putString(NewsWidgetProvider.EXTRA_DATE, mPublishedAt);
intent.putExtras(extras);
row.setOnClickFillInIntent(android.R.id.text1, intent); | Intent fillInIntent = new Intent(context, DetailsActivity.class); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.