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
Nulltilus/Appmatic-Android
app/src/main/java/com/appmatic/baseapp/contact/ContactInteractor.java
// Path: app/src/main/java/com/appmatic/baseapp/api/models/Contact.java // public class Contact { // private String contact_email; // private float latitude; // private float longitude; // private String contact_address; // private String contact_name; // private String contact_phone; // private String contact_website; // // public Contact(String contact_name, String contact_email, String contact_phone, float latitude, float longitude, String contact_address, String contact_website) { // this.contact_name = contact_name; // this.contact_email = contact_email; // this.contact_phone = contact_phone; // this.contact_address = contact_address; // this.contact_website = contact_website; // this.latitude = latitude; // this.longitude = longitude; // } // // public float getLongitude() { // return this.longitude; // } // // public void setLongitude(float longitude) { // this.longitude = longitude; // } // // public float getLatitude() { // return this.latitude; // } // // public void setLatitude(float latitude) { // this.latitude = latitude; // } // // public String getContact_phone() { // return this.contact_phone; // } // // public void setContact_phone(String contact_phone) { // this.contact_phone = contact_phone; // } // // public String getContact_email() { // return this.contact_email; // } // // public void setContact_email(String contact_email) { // this.contact_email = contact_email; // } // // public String getName() { // return this.contact_name; // } // // public void setName(String name) { // this.contact_name = name; // } // // public String getContact_website() { // return contact_website; // } // // public void setContact_website(String contact_website) { // this.contact_website = contact_website; // } // // public String getContact_address() { // return contact_address; // } // // public void setContact_address(String contact_address) { // this.contact_address = contact_address; // } // }
import android.content.Context; import android.support.annotation.NonNull; import com.appmatic.baseapp.api.models.Contact;
package com.appmatic.baseapp.contact; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ interface ContactInteractor { void retrieveContactData(@NonNull Context context, OnContactDataReceivedListener contactDataReceivedListener); interface OnContactDataReceivedListener {
// Path: app/src/main/java/com/appmatic/baseapp/api/models/Contact.java // public class Contact { // private String contact_email; // private float latitude; // private float longitude; // private String contact_address; // private String contact_name; // private String contact_phone; // private String contact_website; // // public Contact(String contact_name, String contact_email, String contact_phone, float latitude, float longitude, String contact_address, String contact_website) { // this.contact_name = contact_name; // this.contact_email = contact_email; // this.contact_phone = contact_phone; // this.contact_address = contact_address; // this.contact_website = contact_website; // this.latitude = latitude; // this.longitude = longitude; // } // // public float getLongitude() { // return this.longitude; // } // // public void setLongitude(float longitude) { // this.longitude = longitude; // } // // public float getLatitude() { // return this.latitude; // } // // public void setLatitude(float latitude) { // this.latitude = latitude; // } // // public String getContact_phone() { // return this.contact_phone; // } // // public void setContact_phone(String contact_phone) { // this.contact_phone = contact_phone; // } // // public String getContact_email() { // return this.contact_email; // } // // public void setContact_email(String contact_email) { // this.contact_email = contact_email; // } // // public String getName() { // return this.contact_name; // } // // public void setName(String name) { // this.contact_name = name; // } // // public String getContact_website() { // return contact_website; // } // // public void setContact_website(String contact_website) { // this.contact_website = contact_website; // } // // public String getContact_address() { // return contact_address; // } // // public void setContact_address(String contact_address) { // this.contact_address = contact_address; // } // } // Path: app/src/main/java/com/appmatic/baseapp/contact/ContactInteractor.java import android.content.Context; import android.support.annotation.NonNull; import com.appmatic.baseapp.api.models.Contact; package com.appmatic.baseapp.contact; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ interface ContactInteractor { void retrieveContactData(@NonNull Context context, OnContactDataReceivedListener contactDataReceivedListener); interface OnContactDataReceivedListener {
void onContactDataReceived(Contact contact);
Nulltilus/Appmatic-Android
app/src/main/java/com/appmatic/baseapp/gallery/adapters/GalleryAdapter.java
// Path: app/src/main/java/com/appmatic/baseapp/api/models/GalleryGroup.java // public class GalleryGroup { // private String title; // private ArrayList<Image> images; // // public GalleryGroup() { // } // // public GalleryGroup(String title, ArrayList<Image> images) { // this.title = title; // this.images = images; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public ArrayList<Image> getImages() { // return images; // } // // public void setImages(ArrayList<Image> images) { // this.images = images; // } // // public static class Image implements Parcelable { // public static final Creator<Image> CREATOR = new Creator<Image>() { // @Override // public Image createFromParcel(Parcel in) { // return new Image(in); // } // // @Override // public Image[] newArray(int size) { // return new Image[size]; // } // }; // private String url; // // public Image() { // } // // public Image(String url) { // this.url = url; // } // // protected Image(Parcel in) { // url = in.readString(); // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel parcel, int i) { // parcel.writeString(url); // } // } // }
import android.support.v4.view.ViewCompat; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.appmatic.baseapp.R; import com.appmatic.baseapp.api.models.GalleryGroup; import com.bumptech.glide.Glide; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife;
package com.appmatic.baseapp.gallery.adapters; /** * Created by grender on 13/04/17. */ public class GalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int VIEW_TYPE_GROUP = 0; private static final int VIEW_TYPE_IMAGE = 1; private GalleryCallbacks galleryCallbacks;
// Path: app/src/main/java/com/appmatic/baseapp/api/models/GalleryGroup.java // public class GalleryGroup { // private String title; // private ArrayList<Image> images; // // public GalleryGroup() { // } // // public GalleryGroup(String title, ArrayList<Image> images) { // this.title = title; // this.images = images; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public ArrayList<Image> getImages() { // return images; // } // // public void setImages(ArrayList<Image> images) { // this.images = images; // } // // public static class Image implements Parcelable { // public static final Creator<Image> CREATOR = new Creator<Image>() { // @Override // public Image createFromParcel(Parcel in) { // return new Image(in); // } // // @Override // public Image[] newArray(int size) { // return new Image[size]; // } // }; // private String url; // // public Image() { // } // // public Image(String url) { // this.url = url; // } // // protected Image(Parcel in) { // url = in.readString(); // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel parcel, int i) { // parcel.writeString(url); // } // } // } // Path: app/src/main/java/com/appmatic/baseapp/gallery/adapters/GalleryAdapter.java import android.support.v4.view.ViewCompat; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.appmatic.baseapp.R; import com.appmatic.baseapp.api.models.GalleryGroup; import com.bumptech.glide.Glide; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; package com.appmatic.baseapp.gallery.adapters; /** * Created by grender on 13/04/17. */ public class GalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int VIEW_TYPE_GROUP = 0; private static final int VIEW_TYPE_IMAGE = 1; private GalleryCallbacks galleryCallbacks;
private ArrayList<GalleryGroup> groups;
Nulltilus/Appmatic-Android
app/src/main/java/com/appmatic/baseapp/contact/ContactPresenterImpl.java
// Path: app/src/main/java/com/appmatic/baseapp/api/models/Contact.java // public class Contact { // private String contact_email; // private float latitude; // private float longitude; // private String contact_address; // private String contact_name; // private String contact_phone; // private String contact_website; // // public Contact(String contact_name, String contact_email, String contact_phone, float latitude, float longitude, String contact_address, String contact_website) { // this.contact_name = contact_name; // this.contact_email = contact_email; // this.contact_phone = contact_phone; // this.contact_address = contact_address; // this.contact_website = contact_website; // this.latitude = latitude; // this.longitude = longitude; // } // // public float getLongitude() { // return this.longitude; // } // // public void setLongitude(float longitude) { // this.longitude = longitude; // } // // public float getLatitude() { // return this.latitude; // } // // public void setLatitude(float latitude) { // this.latitude = latitude; // } // // public String getContact_phone() { // return this.contact_phone; // } // // public void setContact_phone(String contact_phone) { // this.contact_phone = contact_phone; // } // // public String getContact_email() { // return this.contact_email; // } // // public void setContact_email(String contact_email) { // this.contact_email = contact_email; // } // // public String getName() { // return this.contact_name; // } // // public void setName(String name) { // this.contact_name = name; // } // // public String getContact_website() { // return contact_website; // } // // public void setContact_website(String contact_website) { // this.contact_website = contact_website; // } // // public String getContact_address() { // return contact_address; // } // // public void setContact_address(String contact_address) { // this.contact_address = contact_address; // } // }
import com.appmatic.baseapp.api.models.Contact;
package com.appmatic.baseapp.contact; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ class ContactPresenterImpl implements ContactInteractorImpl.OnContactDataReceivedListener, ContactPresenter { private ContactView contactView; private ContactInteractor contactInteractor; ContactPresenterImpl(ContactView contactView) { this.contactView = contactView; contactInteractor = new ContactInteractorImpl(); } @Override public void setUpData() { contactInteractor.retrieveContactData(((ContactFragment) contactView).getActivity(), this); } @Override public void onDestroy() { contactView = null; } @Override
// Path: app/src/main/java/com/appmatic/baseapp/api/models/Contact.java // public class Contact { // private String contact_email; // private float latitude; // private float longitude; // private String contact_address; // private String contact_name; // private String contact_phone; // private String contact_website; // // public Contact(String contact_name, String contact_email, String contact_phone, float latitude, float longitude, String contact_address, String contact_website) { // this.contact_name = contact_name; // this.contact_email = contact_email; // this.contact_phone = contact_phone; // this.contact_address = contact_address; // this.contact_website = contact_website; // this.latitude = latitude; // this.longitude = longitude; // } // // public float getLongitude() { // return this.longitude; // } // // public void setLongitude(float longitude) { // this.longitude = longitude; // } // // public float getLatitude() { // return this.latitude; // } // // public void setLatitude(float latitude) { // this.latitude = latitude; // } // // public String getContact_phone() { // return this.contact_phone; // } // // public void setContact_phone(String contact_phone) { // this.contact_phone = contact_phone; // } // // public String getContact_email() { // return this.contact_email; // } // // public void setContact_email(String contact_email) { // this.contact_email = contact_email; // } // // public String getName() { // return this.contact_name; // } // // public void setName(String name) { // this.contact_name = name; // } // // public String getContact_website() { // return contact_website; // } // // public void setContact_website(String contact_website) { // this.contact_website = contact_website; // } // // public String getContact_address() { // return contact_address; // } // // public void setContact_address(String contact_address) { // this.contact_address = contact_address; // } // } // Path: app/src/main/java/com/appmatic/baseapp/contact/ContactPresenterImpl.java import com.appmatic.baseapp.api.models.Contact; package com.appmatic.baseapp.contact; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ class ContactPresenterImpl implements ContactInteractorImpl.OnContactDataReceivedListener, ContactPresenter { private ContactView contactView; private ContactInteractor contactInteractor; ContactPresenterImpl(ContactView contactView) { this.contactView = contactView; contactInteractor = new ContactInteractorImpl(); } @Override public void setUpData() { contactInteractor.retrieveContactData(((ContactFragment) contactView).getActivity(), this); } @Override public void onDestroy() { contactView = null; } @Override
public void onContactDataReceived(Contact contact) {
Nulltilus/Appmatic-Android
app/src/main/java/com/appmatic/baseapp/fcm/FCMHelper.java
// Path: app/src/main/java/com/appmatic/baseapp/utils/Constants.java // public class Constants { // public static final String APP_ID = "2"; // public static final String FCM_TOPIC = "TOPIC_" + APP_ID; // // public static final String BASE_URL = "https://cpanel.appmatic.nulltilus.com/"; // // public static final String BASE_URL = "http://cpanel.appmatic.sprueba.tk/"; // public static final String API_URL = BASE_URL + "api/"; // // public static final String APP_DATA_ENDPOINT = "get_app_content"; // public static final String APP_EXTRA_INFO_ENDPOINT = "get_extra_info"; // public static final String APP_EXTRA_CONTACT_ENDPOINT = "get_contact"; // public static final String APP_GALLERY_ENDPOINT = "get_gallery"; // // public static final String PREF_FIRST_BOOT = "preferences.first_boot"; // // // 0 to 127 (reserved for predefined views) // public static final int MENU_CONTACT_ID = 0; // public static final int MENU_GALLERY_ID = 1; // public static final String MENU_CONTACT_ICON = "ic_account_circle_black_48dp"; // public static final String MENU_GALLERY_ICON = "ic_collections_black_48dp"; // // }
import android.content.Context; import com.appmatic.baseapp.utils.Constants; import com.google.firebase.messaging.FirebaseMessaging; import es.dmoral.prefs.Prefs;
package com.appmatic.baseapp.fcm; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ public class FCMHelper { public static void subscribeToFCMTopic(Context context) {
// Path: app/src/main/java/com/appmatic/baseapp/utils/Constants.java // public class Constants { // public static final String APP_ID = "2"; // public static final String FCM_TOPIC = "TOPIC_" + APP_ID; // // public static final String BASE_URL = "https://cpanel.appmatic.nulltilus.com/"; // // public static final String BASE_URL = "http://cpanel.appmatic.sprueba.tk/"; // public static final String API_URL = BASE_URL + "api/"; // // public static final String APP_DATA_ENDPOINT = "get_app_content"; // public static final String APP_EXTRA_INFO_ENDPOINT = "get_extra_info"; // public static final String APP_EXTRA_CONTACT_ENDPOINT = "get_contact"; // public static final String APP_GALLERY_ENDPOINT = "get_gallery"; // // public static final String PREF_FIRST_BOOT = "preferences.first_boot"; // // // 0 to 127 (reserved for predefined views) // public static final int MENU_CONTACT_ID = 0; // public static final int MENU_GALLERY_ID = 1; // public static final String MENU_CONTACT_ICON = "ic_account_circle_black_48dp"; // public static final String MENU_GALLERY_ICON = "ic_collections_black_48dp"; // // } // Path: app/src/main/java/com/appmatic/baseapp/fcm/FCMHelper.java import android.content.Context; import com.appmatic.baseapp.utils.Constants; import com.google.firebase.messaging.FirebaseMessaging; import es.dmoral.prefs.Prefs; package com.appmatic.baseapp.fcm; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ public class FCMHelper { public static void subscribeToFCMTopic(Context context) {
if (Prefs.with(context).readBoolean(Constants.PREF_FIRST_BOOT, true)) {
Nulltilus/Appmatic-Android
app/src/main/java/com/appmatic/baseapp/main/MainPresenterImpl.java
// Path: app/src/main/java/com/appmatic/baseapp/api/models/AppContent.java // public class AppContent { // private int content_id; // private ArrayList<Content> contents; // private String icon_id; // private String name; // private int position; // // public AppContent(int content_id) { // this.content_id = content_id; // } // // public AppContent(int content_id, int position, String name, String icon_id, ArrayList<Content> contents) { // this.content_id = content_id; // this.position = position; // this.name = name; // this.icon_id = icon_id; // this.contents = contents; // } // // public int getContent_id() { // return this.content_id; // } // // public void setContent_id(int content_id) { // this.content_id = content_id; // } // // public int getPosition() { // return this.position; // } // // public void setPosition(int position) { // this.position = position; // } // // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // public String getIcon_id() { // return this.icon_id; // } // // public void setIcon_id(String icon_id) { // this.icon_id = icon_id; // } // // public ArrayList<Content> getContents() { // return this.contents; // } // // public void setContents(ArrayList<Content> contents) { // this.contents = contents; // } // // public boolean equals(Object o) { // return !(o == null || !(o instanceof AppContent)) && ((AppContent) o).getContent_id() == getContent_id(); // } // } // // Path: app/src/main/java/com/appmatic/baseapp/api/models/ExtraInfo.java // public class ExtraInfo { // public static final String TYPE_CONTACT_ITEM = "TYPE_CONTACT_ITEM"; // public static final String TYPE_GALLERY_ITEM = "TYPE_GALLERY_ITEM"; // // private boolean navigation_bar_colored; // private String android_drawer_header_color; // private String android_drawer_header_main_text; // private String android_drawer_header_sub_text; // private ArrayList<String> extra_items; // // public ExtraInfo() { // } // // public ExtraInfo(boolean navigation_bar_colored, String android_drawer_header_color, // String android_drawer_header_main_text, String android_drawer_header_sub_text, ArrayList<String> extra_items) { // this.navigation_bar_colored = navigation_bar_colored; // this.android_drawer_header_color = android_drawer_header_color; // this.android_drawer_header_main_text = android_drawer_header_main_text; // this.android_drawer_header_sub_text = android_drawer_header_sub_text; // this.extra_items = extra_items; // } // // public static String getTagByItemName(String itemName) { // switch (itemName) { // case TYPE_CONTACT_ITEM: // return ContactFragment.class.toString(); // default: // return ""; // } // } // // public ArrayList<String> getExtra_items() { // return extra_items; // } // // public void setExtra_items(ArrayList<String> extra_items) { // this.extra_items = extra_items; // } // // public boolean isNavigation_bar_colored() { // return navigation_bar_colored; // } // // public void setNavigation_bar_colored(boolean navigation_bar_colored) { // this.navigation_bar_colored = navigation_bar_colored; // } // // public String getAndroid_drawer_header_color() { // return android_drawer_header_color; // } // // public void setAndroid_drawer_header_color(String android_drawer_header_color) { // this.android_drawer_header_color = android_drawer_header_color; // } // // public String getAndroid_drawer_header_main_text() { // return android_drawer_header_main_text; // } // // public void setAndroid_drawer_header_main_text(String android_drawer_header_main_text) { // this.android_drawer_header_main_text = android_drawer_header_main_text; // } // // public String getAndroid_drawer_header_sub_text() { // return android_drawer_header_sub_text; // } // // public void setAndroid_drawer_header_sub_text(String android_drawer_header_sub_text) { // this.android_drawer_header_sub_text = android_drawer_header_sub_text; // } // }
import android.content.Context; import com.appmatic.baseapp.api.models.AppContent; import com.appmatic.baseapp.api.models.ExtraInfo; import java.util.ArrayList;
package com.appmatic.baseapp.main; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ class MainPresenterImpl implements MainPresenter, MainInteractorImpl.OnDataRetrievedListener, MainInteractor.OnExtraInfoListener { private MainView mainView; private MainInteractor mainInteractor; MainPresenterImpl(MainView mainView) { this.mainView = mainView; mainInteractor = new MainInteractorImpl(); } @Override public void setUpDataFromServer() { mainInteractor.getData((Context) mainView, this); } @Override public void onDestroy() { mainView = null; } @Override public void populateApp() { setUpDataFromServer(); } @Override public void getExtraItems() { mainInteractor.getExtraInfo((Context) mainView, this); } @Override
// Path: app/src/main/java/com/appmatic/baseapp/api/models/AppContent.java // public class AppContent { // private int content_id; // private ArrayList<Content> contents; // private String icon_id; // private String name; // private int position; // // public AppContent(int content_id) { // this.content_id = content_id; // } // // public AppContent(int content_id, int position, String name, String icon_id, ArrayList<Content> contents) { // this.content_id = content_id; // this.position = position; // this.name = name; // this.icon_id = icon_id; // this.contents = contents; // } // // public int getContent_id() { // return this.content_id; // } // // public void setContent_id(int content_id) { // this.content_id = content_id; // } // // public int getPosition() { // return this.position; // } // // public void setPosition(int position) { // this.position = position; // } // // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // public String getIcon_id() { // return this.icon_id; // } // // public void setIcon_id(String icon_id) { // this.icon_id = icon_id; // } // // public ArrayList<Content> getContents() { // return this.contents; // } // // public void setContents(ArrayList<Content> contents) { // this.contents = contents; // } // // public boolean equals(Object o) { // return !(o == null || !(o instanceof AppContent)) && ((AppContent) o).getContent_id() == getContent_id(); // } // } // // Path: app/src/main/java/com/appmatic/baseapp/api/models/ExtraInfo.java // public class ExtraInfo { // public static final String TYPE_CONTACT_ITEM = "TYPE_CONTACT_ITEM"; // public static final String TYPE_GALLERY_ITEM = "TYPE_GALLERY_ITEM"; // // private boolean navigation_bar_colored; // private String android_drawer_header_color; // private String android_drawer_header_main_text; // private String android_drawer_header_sub_text; // private ArrayList<String> extra_items; // // public ExtraInfo() { // } // // public ExtraInfo(boolean navigation_bar_colored, String android_drawer_header_color, // String android_drawer_header_main_text, String android_drawer_header_sub_text, ArrayList<String> extra_items) { // this.navigation_bar_colored = navigation_bar_colored; // this.android_drawer_header_color = android_drawer_header_color; // this.android_drawer_header_main_text = android_drawer_header_main_text; // this.android_drawer_header_sub_text = android_drawer_header_sub_text; // this.extra_items = extra_items; // } // // public static String getTagByItemName(String itemName) { // switch (itemName) { // case TYPE_CONTACT_ITEM: // return ContactFragment.class.toString(); // default: // return ""; // } // } // // public ArrayList<String> getExtra_items() { // return extra_items; // } // // public void setExtra_items(ArrayList<String> extra_items) { // this.extra_items = extra_items; // } // // public boolean isNavigation_bar_colored() { // return navigation_bar_colored; // } // // public void setNavigation_bar_colored(boolean navigation_bar_colored) { // this.navigation_bar_colored = navigation_bar_colored; // } // // public String getAndroid_drawer_header_color() { // return android_drawer_header_color; // } // // public void setAndroid_drawer_header_color(String android_drawer_header_color) { // this.android_drawer_header_color = android_drawer_header_color; // } // // public String getAndroid_drawer_header_main_text() { // return android_drawer_header_main_text; // } // // public void setAndroid_drawer_header_main_text(String android_drawer_header_main_text) { // this.android_drawer_header_main_text = android_drawer_header_main_text; // } // // public String getAndroid_drawer_header_sub_text() { // return android_drawer_header_sub_text; // } // // public void setAndroid_drawer_header_sub_text(String android_drawer_header_sub_text) { // this.android_drawer_header_sub_text = android_drawer_header_sub_text; // } // } // Path: app/src/main/java/com/appmatic/baseapp/main/MainPresenterImpl.java import android.content.Context; import com.appmatic.baseapp.api.models.AppContent; import com.appmatic.baseapp.api.models.ExtraInfo; import java.util.ArrayList; package com.appmatic.baseapp.main; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ class MainPresenterImpl implements MainPresenter, MainInteractorImpl.OnDataRetrievedListener, MainInteractor.OnExtraInfoListener { private MainView mainView; private MainInteractor mainInteractor; MainPresenterImpl(MainView mainView) { this.mainView = mainView; mainInteractor = new MainInteractorImpl(); } @Override public void setUpDataFromServer() { mainInteractor.getData((Context) mainView, this); } @Override public void onDestroy() { mainView = null; } @Override public void populateApp() { setUpDataFromServer(); } @Override public void getExtraItems() { mainInteractor.getExtraInfo((Context) mainView, this); } @Override
public void onDataReceived(ArrayList<AppContent> appContents) {
Nulltilus/Appmatic-Android
app/src/main/java/com/appmatic/baseapp/main/MainPresenterImpl.java
// Path: app/src/main/java/com/appmatic/baseapp/api/models/AppContent.java // public class AppContent { // private int content_id; // private ArrayList<Content> contents; // private String icon_id; // private String name; // private int position; // // public AppContent(int content_id) { // this.content_id = content_id; // } // // public AppContent(int content_id, int position, String name, String icon_id, ArrayList<Content> contents) { // this.content_id = content_id; // this.position = position; // this.name = name; // this.icon_id = icon_id; // this.contents = contents; // } // // public int getContent_id() { // return this.content_id; // } // // public void setContent_id(int content_id) { // this.content_id = content_id; // } // // public int getPosition() { // return this.position; // } // // public void setPosition(int position) { // this.position = position; // } // // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // public String getIcon_id() { // return this.icon_id; // } // // public void setIcon_id(String icon_id) { // this.icon_id = icon_id; // } // // public ArrayList<Content> getContents() { // return this.contents; // } // // public void setContents(ArrayList<Content> contents) { // this.contents = contents; // } // // public boolean equals(Object o) { // return !(o == null || !(o instanceof AppContent)) && ((AppContent) o).getContent_id() == getContent_id(); // } // } // // Path: app/src/main/java/com/appmatic/baseapp/api/models/ExtraInfo.java // public class ExtraInfo { // public static final String TYPE_CONTACT_ITEM = "TYPE_CONTACT_ITEM"; // public static final String TYPE_GALLERY_ITEM = "TYPE_GALLERY_ITEM"; // // private boolean navigation_bar_colored; // private String android_drawer_header_color; // private String android_drawer_header_main_text; // private String android_drawer_header_sub_text; // private ArrayList<String> extra_items; // // public ExtraInfo() { // } // // public ExtraInfo(boolean navigation_bar_colored, String android_drawer_header_color, // String android_drawer_header_main_text, String android_drawer_header_sub_text, ArrayList<String> extra_items) { // this.navigation_bar_colored = navigation_bar_colored; // this.android_drawer_header_color = android_drawer_header_color; // this.android_drawer_header_main_text = android_drawer_header_main_text; // this.android_drawer_header_sub_text = android_drawer_header_sub_text; // this.extra_items = extra_items; // } // // public static String getTagByItemName(String itemName) { // switch (itemName) { // case TYPE_CONTACT_ITEM: // return ContactFragment.class.toString(); // default: // return ""; // } // } // // public ArrayList<String> getExtra_items() { // return extra_items; // } // // public void setExtra_items(ArrayList<String> extra_items) { // this.extra_items = extra_items; // } // // public boolean isNavigation_bar_colored() { // return navigation_bar_colored; // } // // public void setNavigation_bar_colored(boolean navigation_bar_colored) { // this.navigation_bar_colored = navigation_bar_colored; // } // // public String getAndroid_drawer_header_color() { // return android_drawer_header_color; // } // // public void setAndroid_drawer_header_color(String android_drawer_header_color) { // this.android_drawer_header_color = android_drawer_header_color; // } // // public String getAndroid_drawer_header_main_text() { // return android_drawer_header_main_text; // } // // public void setAndroid_drawer_header_main_text(String android_drawer_header_main_text) { // this.android_drawer_header_main_text = android_drawer_header_main_text; // } // // public String getAndroid_drawer_header_sub_text() { // return android_drawer_header_sub_text; // } // // public void setAndroid_drawer_header_sub_text(String android_drawer_header_sub_text) { // this.android_drawer_header_sub_text = android_drawer_header_sub_text; // } // }
import android.content.Context; import com.appmatic.baseapp.api.models.AppContent; import com.appmatic.baseapp.api.models.ExtraInfo; import java.util.ArrayList;
@Override public void onDestroy() { mainView = null; } @Override public void populateApp() { setUpDataFromServer(); } @Override public void getExtraItems() { mainInteractor.getExtraInfo((Context) mainView, this); } @Override public void onDataReceived(ArrayList<AppContent> appContents) { if (mainView != null) { mainView.updateAllContent(appContents); } } @Override public void onDataReceivedError() { if (mainView != null) { mainView.handleInternetError(null); } } @Override
// Path: app/src/main/java/com/appmatic/baseapp/api/models/AppContent.java // public class AppContent { // private int content_id; // private ArrayList<Content> contents; // private String icon_id; // private String name; // private int position; // // public AppContent(int content_id) { // this.content_id = content_id; // } // // public AppContent(int content_id, int position, String name, String icon_id, ArrayList<Content> contents) { // this.content_id = content_id; // this.position = position; // this.name = name; // this.icon_id = icon_id; // this.contents = contents; // } // // public int getContent_id() { // return this.content_id; // } // // public void setContent_id(int content_id) { // this.content_id = content_id; // } // // public int getPosition() { // return this.position; // } // // public void setPosition(int position) { // this.position = position; // } // // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // public String getIcon_id() { // return this.icon_id; // } // // public void setIcon_id(String icon_id) { // this.icon_id = icon_id; // } // // public ArrayList<Content> getContents() { // return this.contents; // } // // public void setContents(ArrayList<Content> contents) { // this.contents = contents; // } // // public boolean equals(Object o) { // return !(o == null || !(o instanceof AppContent)) && ((AppContent) o).getContent_id() == getContent_id(); // } // } // // Path: app/src/main/java/com/appmatic/baseapp/api/models/ExtraInfo.java // public class ExtraInfo { // public static final String TYPE_CONTACT_ITEM = "TYPE_CONTACT_ITEM"; // public static final String TYPE_GALLERY_ITEM = "TYPE_GALLERY_ITEM"; // // private boolean navigation_bar_colored; // private String android_drawer_header_color; // private String android_drawer_header_main_text; // private String android_drawer_header_sub_text; // private ArrayList<String> extra_items; // // public ExtraInfo() { // } // // public ExtraInfo(boolean navigation_bar_colored, String android_drawer_header_color, // String android_drawer_header_main_text, String android_drawer_header_sub_text, ArrayList<String> extra_items) { // this.navigation_bar_colored = navigation_bar_colored; // this.android_drawer_header_color = android_drawer_header_color; // this.android_drawer_header_main_text = android_drawer_header_main_text; // this.android_drawer_header_sub_text = android_drawer_header_sub_text; // this.extra_items = extra_items; // } // // public static String getTagByItemName(String itemName) { // switch (itemName) { // case TYPE_CONTACT_ITEM: // return ContactFragment.class.toString(); // default: // return ""; // } // } // // public ArrayList<String> getExtra_items() { // return extra_items; // } // // public void setExtra_items(ArrayList<String> extra_items) { // this.extra_items = extra_items; // } // // public boolean isNavigation_bar_colored() { // return navigation_bar_colored; // } // // public void setNavigation_bar_colored(boolean navigation_bar_colored) { // this.navigation_bar_colored = navigation_bar_colored; // } // // public String getAndroid_drawer_header_color() { // return android_drawer_header_color; // } // // public void setAndroid_drawer_header_color(String android_drawer_header_color) { // this.android_drawer_header_color = android_drawer_header_color; // } // // public String getAndroid_drawer_header_main_text() { // return android_drawer_header_main_text; // } // // public void setAndroid_drawer_header_main_text(String android_drawer_header_main_text) { // this.android_drawer_header_main_text = android_drawer_header_main_text; // } // // public String getAndroid_drawer_header_sub_text() { // return android_drawer_header_sub_text; // } // // public void setAndroid_drawer_header_sub_text(String android_drawer_header_sub_text) { // this.android_drawer_header_sub_text = android_drawer_header_sub_text; // } // } // Path: app/src/main/java/com/appmatic/baseapp/main/MainPresenterImpl.java import android.content.Context; import com.appmatic.baseapp.api.models.AppContent; import com.appmatic.baseapp.api.models.ExtraInfo; import java.util.ArrayList; @Override public void onDestroy() { mainView = null; } @Override public void populateApp() { setUpDataFromServer(); } @Override public void getExtraItems() { mainInteractor.getExtraInfo((Context) mainView, this); } @Override public void onDataReceived(ArrayList<AppContent> appContents) { if (mainView != null) { mainView.updateAllContent(appContents); } } @Override public void onDataReceivedError() { if (mainView != null) { mainView.handleInternetError(null); } } @Override
public void onExtraInfoReceived(ExtraInfo extraInfo) {
Nulltilus/Appmatic-Android
app/src/main/java/com/appmatic/baseapp/contact/ContactView.java
// Path: app/src/main/java/com/appmatic/baseapp/api/models/Contact.java // public class Contact { // private String contact_email; // private float latitude; // private float longitude; // private String contact_address; // private String contact_name; // private String contact_phone; // private String contact_website; // // public Contact(String contact_name, String contact_email, String contact_phone, float latitude, float longitude, String contact_address, String contact_website) { // this.contact_name = contact_name; // this.contact_email = contact_email; // this.contact_phone = contact_phone; // this.contact_address = contact_address; // this.contact_website = contact_website; // this.latitude = latitude; // this.longitude = longitude; // } // // public float getLongitude() { // return this.longitude; // } // // public void setLongitude(float longitude) { // this.longitude = longitude; // } // // public float getLatitude() { // return this.latitude; // } // // public void setLatitude(float latitude) { // this.latitude = latitude; // } // // public String getContact_phone() { // return this.contact_phone; // } // // public void setContact_phone(String contact_phone) { // this.contact_phone = contact_phone; // } // // public String getContact_email() { // return this.contact_email; // } // // public void setContact_email(String contact_email) { // this.contact_email = contact_email; // } // // public String getName() { // return this.contact_name; // } // // public void setName(String name) { // this.contact_name = name; // } // // public String getContact_website() { // return contact_website; // } // // public void setContact_website(String contact_website) { // this.contact_website = contact_website; // } // // public String getContact_address() { // return contact_address; // } // // public void setContact_address(String contact_address) { // this.contact_address = contact_address; // } // }
import com.appmatic.baseapp.api.models.Contact; import com.google.android.gms.maps.model.CameraPosition;
package com.appmatic.baseapp.contact; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ interface ContactView { void showFullscreenMap(); void performPhoneCall(); void sendEmail(); void openWebsite();
// Path: app/src/main/java/com/appmatic/baseapp/api/models/Contact.java // public class Contact { // private String contact_email; // private float latitude; // private float longitude; // private String contact_address; // private String contact_name; // private String contact_phone; // private String contact_website; // // public Contact(String contact_name, String contact_email, String contact_phone, float latitude, float longitude, String contact_address, String contact_website) { // this.contact_name = contact_name; // this.contact_email = contact_email; // this.contact_phone = contact_phone; // this.contact_address = contact_address; // this.contact_website = contact_website; // this.latitude = latitude; // this.longitude = longitude; // } // // public float getLongitude() { // return this.longitude; // } // // public void setLongitude(float longitude) { // this.longitude = longitude; // } // // public float getLatitude() { // return this.latitude; // } // // public void setLatitude(float latitude) { // this.latitude = latitude; // } // // public String getContact_phone() { // return this.contact_phone; // } // // public void setContact_phone(String contact_phone) { // this.contact_phone = contact_phone; // } // // public String getContact_email() { // return this.contact_email; // } // // public void setContact_email(String contact_email) { // this.contact_email = contact_email; // } // // public String getName() { // return this.contact_name; // } // // public void setName(String name) { // this.contact_name = name; // } // // public String getContact_website() { // return contact_website; // } // // public void setContact_website(String contact_website) { // this.contact_website = contact_website; // } // // public String getContact_address() { // return contact_address; // } // // public void setContact_address(String contact_address) { // this.contact_address = contact_address; // } // } // Path: app/src/main/java/com/appmatic/baseapp/contact/ContactView.java import com.appmatic.baseapp.api.models.Contact; import com.google.android.gms.maps.model.CameraPosition; package com.appmatic.baseapp.contact; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ interface ContactView { void showFullscreenMap(); void performPhoneCall(); void sendEmail(); void openWebsite();
void populateContent(Contact contact);
Nulltilus/Appmatic-Android
app/src/main/java/com/appmatic/baseapp/utils/ViewParsingUtils.java
// Path: app/src/main/java/com/appmatic/baseapp/api/models/Content.java // public class Content { // public static final String TABLE_COLUMN_DIVIDER = ":::"; // public static final String TABLE_ROW_DIVIDER = ";;;"; // // public static final String TYPE_SEPARATOR = "TYPE_SEPARATOR"; // public static final String TYPE_IMAGE = "TYPE_IMAGE"; // public static final String TYPE_TABLE = "TYPE_TABLE"; // public static final String TYPE_TEXT = "TYPE_TEXT"; // public static final String TYPE_TITLE = "TYPE_TITLE"; // public static final String TYPE_YOUTUBE = "TYPE_YOUTUBE"; // // public static final String EXTRA_DELIMITER = "ǁ"; // public static final String EXTRA_HAS_STRIPES = "HAS_STRIPES"; // public static final String EXTRA_HAS_HEADER = "HAS_HEADER"; // // private String content; // private String extras; // private String type; // // public Content(String type, String extras, String content) { // this.type = type; // this.extras = extras; // this.content = content; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getExtras() { // return this.extras; // } // // public void setExtras(String extras) { // this.extras = extras; // } // // public String getContent() { // return this.content; // } // // public void setContent(String content) { // this.content = content; // } // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Typeface; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v4.view.GravityCompat; import android.text.method.LinkMovementMethod; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import com.appmatic.baseapp.R; import com.appmatic.baseapp.api.models.Content; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.google.android.youtube.player.YouTubeStandalonePlayer; import com.pixplicity.htmlcompat.HtmlCompat; import java.util.Arrays;
package com.appmatic.baseapp.utils; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ public class ViewParsingUtils { private static int halfMargin = -1; private static int defaultMargin = -1;
// Path: app/src/main/java/com/appmatic/baseapp/api/models/Content.java // public class Content { // public static final String TABLE_COLUMN_DIVIDER = ":::"; // public static final String TABLE_ROW_DIVIDER = ";;;"; // // public static final String TYPE_SEPARATOR = "TYPE_SEPARATOR"; // public static final String TYPE_IMAGE = "TYPE_IMAGE"; // public static final String TYPE_TABLE = "TYPE_TABLE"; // public static final String TYPE_TEXT = "TYPE_TEXT"; // public static final String TYPE_TITLE = "TYPE_TITLE"; // public static final String TYPE_YOUTUBE = "TYPE_YOUTUBE"; // // public static final String EXTRA_DELIMITER = "ǁ"; // public static final String EXTRA_HAS_STRIPES = "HAS_STRIPES"; // public static final String EXTRA_HAS_HEADER = "HAS_HEADER"; // // private String content; // private String extras; // private String type; // // public Content(String type, String extras, String content) { // this.type = type; // this.extras = extras; // this.content = content; // } // // public String getType() { // return this.type; // } // // public void setType(String type) { // this.type = type; // } // // public String getExtras() { // return this.extras; // } // // public void setExtras(String extras) { // this.extras = extras; // } // // public String getContent() { // return this.content; // } // // public void setContent(String content) { // this.content = content; // } // } // Path: app/src/main/java/com/appmatic/baseapp/utils/ViewParsingUtils.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Typeface; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v4.view.GravityCompat; import android.text.method.LinkMovementMethod; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import com.appmatic.baseapp.R; import com.appmatic.baseapp.api.models.Content; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.google.android.youtube.player.YouTubeStandalonePlayer; import com.pixplicity.htmlcompat.HtmlCompat; import java.util.Arrays; package com.appmatic.baseapp.utils; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ public class ViewParsingUtils { private static int halfMargin = -1; private static int defaultMargin = -1;
public static View parseContent(@NonNull final Context context, final Content content, boolean isFirstView,
Nulltilus/Appmatic-Android
app/src/main/java/com/appmatic/baseapp/gallery/GalleryPresenterImpl.java
// Path: app/src/main/java/com/appmatic/baseapp/api/models/GalleryGroup.java // public class GalleryGroup { // private String title; // private ArrayList<Image> images; // // public GalleryGroup() { // } // // public GalleryGroup(String title, ArrayList<Image> images) { // this.title = title; // this.images = images; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public ArrayList<Image> getImages() { // return images; // } // // public void setImages(ArrayList<Image> images) { // this.images = images; // } // // public static class Image implements Parcelable { // public static final Creator<Image> CREATOR = new Creator<Image>() { // @Override // public Image createFromParcel(Parcel in) { // return new Image(in); // } // // @Override // public Image[] newArray(int size) { // return new Image[size]; // } // }; // private String url; // // public Image() { // } // // public Image(String url) { // this.url = url; // } // // protected Image(Parcel in) { // url = in.readString(); // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel parcel, int i) { // parcel.writeString(url); // } // } // }
import com.appmatic.baseapp.api.models.GalleryGroup; import java.util.ArrayList;
package com.appmatic.baseapp.gallery; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ class GalleryPresenterImpl implements GalleryPresenter, GalleryInteractor.OnImagesReceivedListener { private GalleryView galleryView; private GalleryInteractor galleryInteractor; GalleryPresenterImpl(GalleryView galleryView) { this.galleryView = galleryView; galleryInteractor = new GalleryInteractorImpl(); } @Override public void getImages() { galleryInteractor.retrieveImages(((GalleryFragment) galleryView).getActivity(), this); } @Override public void onDestroy() { this.galleryView = null; } @Override
// Path: app/src/main/java/com/appmatic/baseapp/api/models/GalleryGroup.java // public class GalleryGroup { // private String title; // private ArrayList<Image> images; // // public GalleryGroup() { // } // // public GalleryGroup(String title, ArrayList<Image> images) { // this.title = title; // this.images = images; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public ArrayList<Image> getImages() { // return images; // } // // public void setImages(ArrayList<Image> images) { // this.images = images; // } // // public static class Image implements Parcelable { // public static final Creator<Image> CREATOR = new Creator<Image>() { // @Override // public Image createFromParcel(Parcel in) { // return new Image(in); // } // // @Override // public Image[] newArray(int size) { // return new Image[size]; // } // }; // private String url; // // public Image() { // } // // public Image(String url) { // this.url = url; // } // // protected Image(Parcel in) { // url = in.readString(); // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel parcel, int i) { // parcel.writeString(url); // } // } // } // Path: app/src/main/java/com/appmatic/baseapp/gallery/GalleryPresenterImpl.java import com.appmatic.baseapp.api.models.GalleryGroup; import java.util.ArrayList; package com.appmatic.baseapp.gallery; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ class GalleryPresenterImpl implements GalleryPresenter, GalleryInteractor.OnImagesReceivedListener { private GalleryView galleryView; private GalleryInteractor galleryInteractor; GalleryPresenterImpl(GalleryView galleryView) { this.galleryView = galleryView; galleryInteractor = new GalleryInteractorImpl(); } @Override public void getImages() { galleryInteractor.retrieveImages(((GalleryFragment) galleryView).getActivity(), this); } @Override public void onDestroy() { this.galleryView = null; } @Override
public void onImagesReceived(ArrayList<GalleryGroup> groups) {
Nulltilus/Appmatic-Android
app/src/main/java/com/appmatic/baseapp/api/WebService.java
// Path: app/src/main/java/com/appmatic/baseapp/utils/Constants.java // public class Constants { // public static final String APP_ID = "2"; // public static final String FCM_TOPIC = "TOPIC_" + APP_ID; // // public static final String BASE_URL = "https://cpanel.appmatic.nulltilus.com/"; // // public static final String BASE_URL = "http://cpanel.appmatic.sprueba.tk/"; // public static final String API_URL = BASE_URL + "api/"; // // public static final String APP_DATA_ENDPOINT = "get_app_content"; // public static final String APP_EXTRA_INFO_ENDPOINT = "get_extra_info"; // public static final String APP_EXTRA_CONTACT_ENDPOINT = "get_contact"; // public static final String APP_GALLERY_ENDPOINT = "get_gallery"; // // public static final String PREF_FIRST_BOOT = "preferences.first_boot"; // // // 0 to 127 (reserved for predefined views) // public static final int MENU_CONTACT_ID = 0; // public static final int MENU_GALLERY_ID = 1; // public static final String MENU_CONTACT_ICON = "ic_account_circle_black_48dp"; // public static final String MENU_GALLERY_ICON = "ic_collections_black_48dp"; // // } // // Path: app/src/main/java/com/appmatic/baseapp/utils/InternetUtils.java // public class InternetUtils { // public static boolean isInternetAvailable(@NonNull Context context) { // NetworkInfo ni = ((ConnectivityManager) context. // getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); // return ni != null && ni.isConnected() && ni.isAvailable(); // } // }
import android.content.Context; import android.support.annotation.NonNull; import com.appmatic.baseapp.utils.Constants; import com.appmatic.baseapp.utils.InternetUtils; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.CacheControl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory;
package com.appmatic.baseapp.api; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ public class WebService { private static final String CACHE_CONTROL = "Cache-Control"; private Retrofit retrofit; public WebService(@NonNull Context context) { this.retrofit = new Retrofit.Builder() .client(provideOkHttpClient(context))
// Path: app/src/main/java/com/appmatic/baseapp/utils/Constants.java // public class Constants { // public static final String APP_ID = "2"; // public static final String FCM_TOPIC = "TOPIC_" + APP_ID; // // public static final String BASE_URL = "https://cpanel.appmatic.nulltilus.com/"; // // public static final String BASE_URL = "http://cpanel.appmatic.sprueba.tk/"; // public static final String API_URL = BASE_URL + "api/"; // // public static final String APP_DATA_ENDPOINT = "get_app_content"; // public static final String APP_EXTRA_INFO_ENDPOINT = "get_extra_info"; // public static final String APP_EXTRA_CONTACT_ENDPOINT = "get_contact"; // public static final String APP_GALLERY_ENDPOINT = "get_gallery"; // // public static final String PREF_FIRST_BOOT = "preferences.first_boot"; // // // 0 to 127 (reserved for predefined views) // public static final int MENU_CONTACT_ID = 0; // public static final int MENU_GALLERY_ID = 1; // public static final String MENU_CONTACT_ICON = "ic_account_circle_black_48dp"; // public static final String MENU_GALLERY_ICON = "ic_collections_black_48dp"; // // } // // Path: app/src/main/java/com/appmatic/baseapp/utils/InternetUtils.java // public class InternetUtils { // public static boolean isInternetAvailable(@NonNull Context context) { // NetworkInfo ni = ((ConnectivityManager) context. // getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); // return ni != null && ni.isConnected() && ni.isAvailable(); // } // } // Path: app/src/main/java/com/appmatic/baseapp/api/WebService.java import android.content.Context; import android.support.annotation.NonNull; import com.appmatic.baseapp.utils.Constants; import com.appmatic.baseapp.utils.InternetUtils; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.CacheControl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; package com.appmatic.baseapp.api; /** * Appmatic * Copyright (C) 2016 - Nulltilus * * This file is part of Appmatic. * * Appmatic 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 * any later version. * * Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>. */ public class WebService { private static final String CACHE_CONTROL = "Cache-Control"; private Retrofit retrofit; public WebService(@NonNull Context context) { this.retrofit = new Retrofit.Builder() .client(provideOkHttpClient(context))
.baseUrl(Constants.API_URL)
Nulltilus/Appmatic-Android
app/src/main/java/com/appmatic/baseapp/api/WebService.java
// Path: app/src/main/java/com/appmatic/baseapp/utils/Constants.java // public class Constants { // public static final String APP_ID = "2"; // public static final String FCM_TOPIC = "TOPIC_" + APP_ID; // // public static final String BASE_URL = "https://cpanel.appmatic.nulltilus.com/"; // // public static final String BASE_URL = "http://cpanel.appmatic.sprueba.tk/"; // public static final String API_URL = BASE_URL + "api/"; // // public static final String APP_DATA_ENDPOINT = "get_app_content"; // public static final String APP_EXTRA_INFO_ENDPOINT = "get_extra_info"; // public static final String APP_EXTRA_CONTACT_ENDPOINT = "get_contact"; // public static final String APP_GALLERY_ENDPOINT = "get_gallery"; // // public static final String PREF_FIRST_BOOT = "preferences.first_boot"; // // // 0 to 127 (reserved for predefined views) // public static final int MENU_CONTACT_ID = 0; // public static final int MENU_GALLERY_ID = 1; // public static final String MENU_CONTACT_ICON = "ic_account_circle_black_48dp"; // public static final String MENU_GALLERY_ICON = "ic_collections_black_48dp"; // // } // // Path: app/src/main/java/com/appmatic/baseapp/utils/InternetUtils.java // public class InternetUtils { // public static boolean isInternetAvailable(@NonNull Context context) { // NetworkInfo ni = ((ConnectivityManager) context. // getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); // return ni != null && ni.isConnected() && ni.isAvailable(); // } // }
import android.content.Context; import android.support.annotation.NonNull; import com.appmatic.baseapp.utils.Constants; import com.appmatic.baseapp.utils.InternetUtils; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.CacheControl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory;
cache = new Cache(new File(context.getCacheDir(), "http-cache"), 10 * 1024 * 1024); // 10 MB } catch (Exception ignored) { } return cache; } private static Interceptor provideCacheInterceptor() { return new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Response response = chain.proceed(chain.request()); CacheControl cacheControl = new CacheControl.Builder() .maxAge(0, TimeUnit.SECONDS) .build(); return response.newBuilder() .header(CACHE_CONTROL, cacheControl.toString()) .build(); } }; } private static Interceptor provideOfflineCacheInterceptor(@NonNull final Context context) { return new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request();
// Path: app/src/main/java/com/appmatic/baseapp/utils/Constants.java // public class Constants { // public static final String APP_ID = "2"; // public static final String FCM_TOPIC = "TOPIC_" + APP_ID; // // public static final String BASE_URL = "https://cpanel.appmatic.nulltilus.com/"; // // public static final String BASE_URL = "http://cpanel.appmatic.sprueba.tk/"; // public static final String API_URL = BASE_URL + "api/"; // // public static final String APP_DATA_ENDPOINT = "get_app_content"; // public static final String APP_EXTRA_INFO_ENDPOINT = "get_extra_info"; // public static final String APP_EXTRA_CONTACT_ENDPOINT = "get_contact"; // public static final String APP_GALLERY_ENDPOINT = "get_gallery"; // // public static final String PREF_FIRST_BOOT = "preferences.first_boot"; // // // 0 to 127 (reserved for predefined views) // public static final int MENU_CONTACT_ID = 0; // public static final int MENU_GALLERY_ID = 1; // public static final String MENU_CONTACT_ICON = "ic_account_circle_black_48dp"; // public static final String MENU_GALLERY_ICON = "ic_collections_black_48dp"; // // } // // Path: app/src/main/java/com/appmatic/baseapp/utils/InternetUtils.java // public class InternetUtils { // public static boolean isInternetAvailable(@NonNull Context context) { // NetworkInfo ni = ((ConnectivityManager) context. // getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); // return ni != null && ni.isConnected() && ni.isAvailable(); // } // } // Path: app/src/main/java/com/appmatic/baseapp/api/WebService.java import android.content.Context; import android.support.annotation.NonNull; import com.appmatic.baseapp.utils.Constants; import com.appmatic.baseapp.utils.InternetUtils; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.CacheControl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; cache = new Cache(new File(context.getCacheDir(), "http-cache"), 10 * 1024 * 1024); // 10 MB } catch (Exception ignored) { } return cache; } private static Interceptor provideCacheInterceptor() { return new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Response response = chain.proceed(chain.request()); CacheControl cacheControl = new CacheControl.Builder() .maxAge(0, TimeUnit.SECONDS) .build(); return response.newBuilder() .header(CACHE_CONTROL, cacheControl.toString()) .build(); } }; } private static Interceptor provideOfflineCacheInterceptor(@NonNull final Context context) { return new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request();
if (!InternetUtils.isInternetAvailable(context)) {
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/machine/frier/ItemRendererFrier.java
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // }
import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import com.teammetallurgy.agriculture.BlockList; import cpw.mods.fml.client.FMLClientHandler;
package com.teammetallurgy.agriculture.machine.frier; public class ItemRendererFrier implements IItemRenderer { private ResourceLocation texture = new ResourceLocation("agriculture:textures/models/machines/frier.png"); private ModelFrier model = new ModelFrier(); @Override public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { if (itemStack == null || itemStack.getItem() == null) return false;
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // } // Path: src/main/java/com/teammetallurgy/agriculture/machine/frier/ItemRendererFrier.java import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import com.teammetallurgy.agriculture.BlockList; import cpw.mods.fml.client.FMLClientHandler; package com.teammetallurgy.agriculture.machine.frier; public class ItemRendererFrier implements IItemRenderer { private ResourceLocation texture = new ResourceLocation("agriculture:textures/models/machines/frier.png"); private ModelFrier model = new ModelFrier(); @Override public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { if (itemStack == null || itemStack.getItem() == null) return false;
if (BlockList.frier != Block.getBlockFromItem(itemStack.getItem())) return false;
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/block/BlockSalt.java
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java // public class ItemList // { // // private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>(); // // public static void preInit() // { // ItemList.initFoodList(); // } // // private static void initFoodList() // { // String[] sets = { "base" }; // // for (String set : sets) // { // // String path = "assets/agriculture/data/"; // // URL resource = Resources.getResource(path + set + ".json"); // // try // { // ItemList.injectMetalSet(set, resource.openStream()); // } // catch (IOException ignored) // { // } // } // } // // private static void injectMetalSet(String name, InputStream stream) // { // FoodSet foodSet = new FoodSet(name); // // foodSet.load(stream); // // ItemList.setList.put(name, foodSet); // } // // public static ItemStack getItemStack(String setName, String foodName) // { // FoodSet foodSet = setList.get(setName); // if (foodSet == null) return null; // // return foodSet.getItemStack(foodName); // } // // public static FoodSet getSet(String setName) // { // return setList.get(setName); // } // // public static String[] getSetNames() // { // return setList.keySet().toArray(new String[setList.size()]); // } // }
import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.ItemList;
package com.teammetallurgy.agriculture.block; public class BlockSalt extends Block { private Item saltItem; private int saltMeta; public BlockSalt() { super(Material.rock); this.setHardness(1.5F);
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java // public class ItemList // { // // private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>(); // // public static void preInit() // { // ItemList.initFoodList(); // } // // private static void initFoodList() // { // String[] sets = { "base" }; // // for (String set : sets) // { // // String path = "assets/agriculture/data/"; // // URL resource = Resources.getResource(path + set + ".json"); // // try // { // ItemList.injectMetalSet(set, resource.openStream()); // } // catch (IOException ignored) // { // } // } // } // // private static void injectMetalSet(String name, InputStream stream) // { // FoodSet foodSet = new FoodSet(name); // // foodSet.load(stream); // // ItemList.setList.put(name, foodSet); // } // // public static ItemStack getItemStack(String setName, String foodName) // { // FoodSet foodSet = setList.get(setName); // if (foodSet == null) return null; // // return foodSet.getItemStack(foodName); // } // // public static FoodSet getSet(String setName) // { // return setList.get(setName); // } // // public static String[] getSetNames() // { // return setList.keySet().toArray(new String[setList.size()]); // } // } // Path: src/main/java/com/teammetallurgy/agriculture/block/BlockSalt.java import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.ItemList; package com.teammetallurgy.agriculture.block; public class BlockSalt extends Block { private Item saltItem; private int saltMeta; public BlockSalt() { super(Material.rock); this.setHardness(1.5F);
this.setBlockName(Agriculture.MODID.toLowerCase() + ".salt");
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/block/BlockSalt.java
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java // public class ItemList // { // // private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>(); // // public static void preInit() // { // ItemList.initFoodList(); // } // // private static void initFoodList() // { // String[] sets = { "base" }; // // for (String set : sets) // { // // String path = "assets/agriculture/data/"; // // URL resource = Resources.getResource(path + set + ".json"); // // try // { // ItemList.injectMetalSet(set, resource.openStream()); // } // catch (IOException ignored) // { // } // } // } // // private static void injectMetalSet(String name, InputStream stream) // { // FoodSet foodSet = new FoodSet(name); // // foodSet.load(stream); // // ItemList.setList.put(name, foodSet); // } // // public static ItemStack getItemStack(String setName, String foodName) // { // FoodSet foodSet = setList.get(setName); // if (foodSet == null) return null; // // return foodSet.getItemStack(foodName); // } // // public static FoodSet getSet(String setName) // { // return setList.get(setName); // } // // public static String[] getSetNames() // { // return setList.keySet().toArray(new String[setList.size()]); // } // }
import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.ItemList;
package com.teammetallurgy.agriculture.block; public class BlockSalt extends Block { private Item saltItem; private int saltMeta; public BlockSalt() { super(Material.rock); this.setHardness(1.5F); this.setBlockName(Agriculture.MODID.toLowerCase() + ".salt"); this.setBlockTextureName(Agriculture.MODID.toLowerCase() + ":Salt"); this.setCreativeTab(Agriculture.instance.creativeTabBlock); setSalt(); } private void setSalt() {
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java // public class ItemList // { // // private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>(); // // public static void preInit() // { // ItemList.initFoodList(); // } // // private static void initFoodList() // { // String[] sets = { "base" }; // // for (String set : sets) // { // // String path = "assets/agriculture/data/"; // // URL resource = Resources.getResource(path + set + ".json"); // // try // { // ItemList.injectMetalSet(set, resource.openStream()); // } // catch (IOException ignored) // { // } // } // } // // private static void injectMetalSet(String name, InputStream stream) // { // FoodSet foodSet = new FoodSet(name); // // foodSet.load(stream); // // ItemList.setList.put(name, foodSet); // } // // public static ItemStack getItemStack(String setName, String foodName) // { // FoodSet foodSet = setList.get(setName); // if (foodSet == null) return null; // // return foodSet.getItemStack(foodName); // } // // public static FoodSet getSet(String setName) // { // return setList.get(setName); // } // // public static String[] getSetNames() // { // return setList.keySet().toArray(new String[setList.size()]); // } // } // Path: src/main/java/com/teammetallurgy/agriculture/block/BlockSalt.java import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.ItemList; package com.teammetallurgy.agriculture.block; public class BlockSalt extends Block { private Item saltItem; private int saltMeta; public BlockSalt() { super(Material.rock); this.setHardness(1.5F); this.setBlockName(Agriculture.MODID.toLowerCase() + ".salt"); this.setBlockTextureName(Agriculture.MODID.toLowerCase() + ":Salt"); this.setCreativeTab(Agriculture.instance.creativeTabBlock); setSalt(); } private void setSalt() {
ItemStack saltStack = ItemList.getItemStack("base", "Salt");
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/block/plant/BlockStrawberry.java
// Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java // public class ItemList // { // // private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>(); // // public static void preInit() // { // ItemList.initFoodList(); // } // // private static void initFoodList() // { // String[] sets = { "base" }; // // for (String set : sets) // { // // String path = "assets/agriculture/data/"; // // URL resource = Resources.getResource(path + set + ".json"); // // try // { // ItemList.injectMetalSet(set, resource.openStream()); // } // catch (IOException ignored) // { // } // } // } // // private static void injectMetalSet(String name, InputStream stream) // { // FoodSet foodSet = new FoodSet(name); // // foodSet.load(stream); // // ItemList.setList.put(name, foodSet); // } // // public static ItemStack getItemStack(String setName, String foodName) // { // FoodSet foodSet = setList.get(setName); // if (foodSet == null) return null; // // return foodSet.getItemStack(foodName); // } // // public static FoodSet getSet(String setName) // { // return setList.get(setName); // } // // public static String[] getSetNames() // { // return setList.keySet().toArray(new String[setList.size()]); // } // }
import com.teammetallurgy.agriculture.ItemList;
package com.teammetallurgy.agriculture.block.plant; public class BlockStrawberry extends BlockPlant { public BlockStrawberry() { this.setBlockTextureName("agriculture:strawberry"); this.setBlockName("agriculture.strawberry");
// Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java // public class ItemList // { // // private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>(); // // public static void preInit() // { // ItemList.initFoodList(); // } // // private static void initFoodList() // { // String[] sets = { "base" }; // // for (String set : sets) // { // // String path = "assets/agriculture/data/"; // // URL resource = Resources.getResource(path + set + ".json"); // // try // { // ItemList.injectMetalSet(set, resource.openStream()); // } // catch (IOException ignored) // { // } // } // } // // private static void injectMetalSet(String name, InputStream stream) // { // FoodSet foodSet = new FoodSet(name); // // foodSet.load(stream); // // ItemList.setList.put(name, foodSet); // } // // public static ItemStack getItemStack(String setName, String foodName) // { // FoodSet foodSet = setList.get(setName); // if (foodSet == null) return null; // // return foodSet.getItemStack(foodName); // } // // public static FoodSet getSet(String setName) // { // return setList.get(setName); // } // // public static String[] getSetNames() // { // return setList.keySet().toArray(new String[setList.size()]); // } // } // Path: src/main/java/com/teammetallurgy/agriculture/block/plant/BlockStrawberry.java import com.teammetallurgy.agriculture.ItemList; package com.teammetallurgy.agriculture.block.plant; public class BlockStrawberry extends BlockPlant { public BlockStrawberry() { this.setBlockTextureName("agriculture:strawberry"); this.setBlockName("agriculture.strawberry");
harvestItemStack = ItemList.getItemStack("base", "Strawberry");
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/machine/brewer/ModelBrewer.java
// Path: src/main/java/com/teammetallurgy/agriculture/machine/ModelSimpleBox.java // public class ModelSimpleBox { // public String field_78247_g; // // private final IIcon icon; // // /** X vertex coordinate of lower box corner */ // public final float posX1; // // /** X vertex coordinate of upper box corner */ // public final float posX2; // // /** Y vertex coordinate of lower box corner */ // public final float posY1; // // /** Y vertex coordinate of upper box corner */ // public final float posY2; // // /** Z vertex coordinate of lower box corner */ // public final float posZ1; // // /** Z vertex coordinate of upper box corner */ // public final float posZ2; // /** An array of 6 TexturedQuads, one for each face of a cube */ // private final TexturedQuadIcon[] quadList; // // /** // * The (x,y,z) vertex positions and (u,v) texture coordinates for each of // * the 8 points on a cube // */ // private final PositionTextureVertex[] vertexPositions; // // public ModelSimpleBox(final int textureWidth, final int textureHeight, final int textureX, final int textureZ, float posX, float posY, float posZ, final int width, final int height, final int width2, final int par10, final IIcon liquidIcon) // { // icon = liquidIcon; // posX1 = posX; // posY1 = posY; // posZ1 = posZ; // posX2 = posX + width; // posY2 = posY + height; // posZ2 = posZ + width2; // vertexPositions = new PositionTextureVertex[8]; // quadList = new TexturedQuadIcon[6]; // float f4 = posX + width; // float f5 = posY + height; // float f6 = posZ + width2; // posX -= par10; // posY -= par10; // posZ -= par10; // f4 += par10; // f5 += par10; // f6 += par10; // // final PositionTextureVertex positiontexturevertex = new PositionTextureVertex(posX, posY, posZ, 0.0F, 0.0F); // final PositionTextureVertex positiontexturevertex1 = new PositionTextureVertex(f4, posY, posZ, 0.0F, 8.0F); // final PositionTextureVertex positiontexturevertex2 = new PositionTextureVertex(f4, f5, posZ, 8.0F, 8.0F); // final PositionTextureVertex positiontexturevertex3 = new PositionTextureVertex(posX, f5, posZ, 8.0F, 0.0F); // final PositionTextureVertex positiontexturevertex4 = new PositionTextureVertex(posX, posY, f6, 0.0F, 0.0F); // final PositionTextureVertex positiontexturevertex5 = new PositionTextureVertex(f4, posY, f6, 0.0F, 8.0F); // final PositionTextureVertex positiontexturevertex6 = new PositionTextureVertex(f4, f5, f6, 8.0F, 8.0F); // final PositionTextureVertex positiontexturevertex7 = new PositionTextureVertex(posX, f5, f6, 8.0F, 0.0F); // vertexPositions[0] = positiontexturevertex; // vertexPositions[1] = positiontexturevertex1; // vertexPositions[2] = positiontexturevertex2; // vertexPositions[3] = positiontexturevertex3; // vertexPositions[4] = positiontexturevertex4; // vertexPositions[5] = positiontexturevertex5; // vertexPositions[6] = positiontexturevertex6; // vertexPositions[7] = positiontexturevertex7; // quadList[0] = new TexturedQuadIcon(new PositionTextureVertex[] { positiontexturevertex5, positiontexturevertex1, positiontexturevertex2, positiontexturevertex6 }, textureX + width2 + width, textureZ + width2, textureX + width2 + width + width2, textureZ + width2 + height, textureWidth, textureHeight); // quadList[1] = new TexturedQuadIcon(new PositionTextureVertex[] { positiontexturevertex, positiontexturevertex4, positiontexturevertex7, positiontexturevertex3 }, textureX, textureZ + width2, textureX + width2, textureZ + width2 + height, textureWidth, textureHeight); // quadList[2] = new TexturedQuadIcon(new PositionTextureVertex[] { positiontexturevertex5, positiontexturevertex4, positiontexturevertex, positiontexturevertex1 }, textureX + width2, textureZ, textureX + width2 + width, textureZ + width2, textureWidth, textureHeight); // quadList[3] = new TexturedQuadIcon(new PositionTextureVertex[] { positiontexturevertex2, positiontexturevertex3, positiontexturevertex7, positiontexturevertex6 }, textureX + width2 + width, textureZ + width2, textureX + width2 + width + width, textureZ, textureWidth, textureHeight); // quadList[4] = new TexturedQuadIcon(new PositionTextureVertex[] { positiontexturevertex1, positiontexturevertex, positiontexturevertex3, positiontexturevertex2 }, textureX + width2, textureZ + width2, textureX + width2 + width, textureZ + width2 + height, textureWidth, textureHeight); // quadList[5] = new TexturedQuadIcon(new PositionTextureVertex[] { positiontexturevertex4, positiontexturevertex5, positiontexturevertex6, positiontexturevertex7 }, textureX + width2 + width + width2, textureZ + width2, textureX + width2 + width + width2 + width, textureZ + width2 + height, textureWidth, textureHeight); // } // // public ModelSimpleBox func_78244_a(final String par1Str) // { // field_78247_g = par1Str; // return this; // } // // /** // * Draw the six sided box defined by this ModelBox // */ // @SideOnly(Side.CLIENT) // public void render(final Tessellator par1Tessellator, final float par2) // { // for (final TexturedQuadIcon element : quadList) // { // element.draw(par1Tessellator, par2, icon); // } // } // }
import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; import net.minecraft.util.IIcon; import net.minecraftforge.fluids.FluidStack; import com.teammetallurgy.agriculture.machine.ModelSimpleBox;
package com.teammetallurgy.agriculture.machine.brewer; public class ModelBrewer extends ModelBase { // fields ModelRenderer base; ModelRenderer base2;
// Path: src/main/java/com/teammetallurgy/agriculture/machine/ModelSimpleBox.java // public class ModelSimpleBox { // public String field_78247_g; // // private final IIcon icon; // // /** X vertex coordinate of lower box corner */ // public final float posX1; // // /** X vertex coordinate of upper box corner */ // public final float posX2; // // /** Y vertex coordinate of lower box corner */ // public final float posY1; // // /** Y vertex coordinate of upper box corner */ // public final float posY2; // // /** Z vertex coordinate of lower box corner */ // public final float posZ1; // // /** Z vertex coordinate of upper box corner */ // public final float posZ2; // /** An array of 6 TexturedQuads, one for each face of a cube */ // private final TexturedQuadIcon[] quadList; // // /** // * The (x,y,z) vertex positions and (u,v) texture coordinates for each of // * the 8 points on a cube // */ // private final PositionTextureVertex[] vertexPositions; // // public ModelSimpleBox(final int textureWidth, final int textureHeight, final int textureX, final int textureZ, float posX, float posY, float posZ, final int width, final int height, final int width2, final int par10, final IIcon liquidIcon) // { // icon = liquidIcon; // posX1 = posX; // posY1 = posY; // posZ1 = posZ; // posX2 = posX + width; // posY2 = posY + height; // posZ2 = posZ + width2; // vertexPositions = new PositionTextureVertex[8]; // quadList = new TexturedQuadIcon[6]; // float f4 = posX + width; // float f5 = posY + height; // float f6 = posZ + width2; // posX -= par10; // posY -= par10; // posZ -= par10; // f4 += par10; // f5 += par10; // f6 += par10; // // final PositionTextureVertex positiontexturevertex = new PositionTextureVertex(posX, posY, posZ, 0.0F, 0.0F); // final PositionTextureVertex positiontexturevertex1 = new PositionTextureVertex(f4, posY, posZ, 0.0F, 8.0F); // final PositionTextureVertex positiontexturevertex2 = new PositionTextureVertex(f4, f5, posZ, 8.0F, 8.0F); // final PositionTextureVertex positiontexturevertex3 = new PositionTextureVertex(posX, f5, posZ, 8.0F, 0.0F); // final PositionTextureVertex positiontexturevertex4 = new PositionTextureVertex(posX, posY, f6, 0.0F, 0.0F); // final PositionTextureVertex positiontexturevertex5 = new PositionTextureVertex(f4, posY, f6, 0.0F, 8.0F); // final PositionTextureVertex positiontexturevertex6 = new PositionTextureVertex(f4, f5, f6, 8.0F, 8.0F); // final PositionTextureVertex positiontexturevertex7 = new PositionTextureVertex(posX, f5, f6, 8.0F, 0.0F); // vertexPositions[0] = positiontexturevertex; // vertexPositions[1] = positiontexturevertex1; // vertexPositions[2] = positiontexturevertex2; // vertexPositions[3] = positiontexturevertex3; // vertexPositions[4] = positiontexturevertex4; // vertexPositions[5] = positiontexturevertex5; // vertexPositions[6] = positiontexturevertex6; // vertexPositions[7] = positiontexturevertex7; // quadList[0] = new TexturedQuadIcon(new PositionTextureVertex[] { positiontexturevertex5, positiontexturevertex1, positiontexturevertex2, positiontexturevertex6 }, textureX + width2 + width, textureZ + width2, textureX + width2 + width + width2, textureZ + width2 + height, textureWidth, textureHeight); // quadList[1] = new TexturedQuadIcon(new PositionTextureVertex[] { positiontexturevertex, positiontexturevertex4, positiontexturevertex7, positiontexturevertex3 }, textureX, textureZ + width2, textureX + width2, textureZ + width2 + height, textureWidth, textureHeight); // quadList[2] = new TexturedQuadIcon(new PositionTextureVertex[] { positiontexturevertex5, positiontexturevertex4, positiontexturevertex, positiontexturevertex1 }, textureX + width2, textureZ, textureX + width2 + width, textureZ + width2, textureWidth, textureHeight); // quadList[3] = new TexturedQuadIcon(new PositionTextureVertex[] { positiontexturevertex2, positiontexturevertex3, positiontexturevertex7, positiontexturevertex6 }, textureX + width2 + width, textureZ + width2, textureX + width2 + width + width, textureZ, textureWidth, textureHeight); // quadList[4] = new TexturedQuadIcon(new PositionTextureVertex[] { positiontexturevertex1, positiontexturevertex, positiontexturevertex3, positiontexturevertex2 }, textureX + width2, textureZ + width2, textureX + width2 + width, textureZ + width2 + height, textureWidth, textureHeight); // quadList[5] = new TexturedQuadIcon(new PositionTextureVertex[] { positiontexturevertex4, positiontexturevertex5, positiontexturevertex6, positiontexturevertex7 }, textureX + width2 + width + width2, textureZ + width2, textureX + width2 + width + width2 + width, textureZ + width2 + height, textureWidth, textureHeight); // } // // public ModelSimpleBox func_78244_a(final String par1Str) // { // field_78247_g = par1Str; // return this; // } // // /** // * Draw the six sided box defined by this ModelBox // */ // @SideOnly(Side.CLIENT) // public void render(final Tessellator par1Tessellator, final float par2) // { // for (final TexturedQuadIcon element : quadList) // { // element.draw(par1Tessellator, par2, icon); // } // } // } // Path: src/main/java/com/teammetallurgy/agriculture/machine/brewer/ModelBrewer.java import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; import net.minecraft.util.IIcon; import net.minecraftforge.fluids.FluidStack; import com.teammetallurgy.agriculture.machine.ModelSimpleBox; package com.teammetallurgy.agriculture.machine.brewer; public class ModelBrewer extends ModelBase { // fields ModelRenderer base; ModelRenderer base2;
ModelSimpleBox filling;
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/machine/icebox/ItemRendererIcebox.java
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // }
import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import com.teammetallurgy.agriculture.BlockList; import cpw.mods.fml.client.FMLClientHandler;
package com.teammetallurgy.agriculture.machine.icebox; public class ItemRendererIcebox implements IItemRenderer { private ResourceLocation texture = new ResourceLocation("agriculture:textures/models/machines/icebox.png"); private ModelIcebox model = new ModelIcebox(); @Override public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { if (itemStack == null || itemStack.getItem() == null) return false;
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // } // Path: src/main/java/com/teammetallurgy/agriculture/machine/icebox/ItemRendererIcebox.java import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import com.teammetallurgy.agriculture.BlockList; import cpw.mods.fml.client.FMLClientHandler; package com.teammetallurgy.agriculture.machine.icebox; public class ItemRendererIcebox implements IItemRenderer { private ResourceLocation texture = new ResourceLocation("agriculture:textures/models/machines/icebox.png"); private ModelIcebox model = new ModelIcebox(); @Override public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { if (itemStack == null || itemStack.getItem() == null) return false;
if (BlockList.icebox != Block.getBlockFromItem(itemStack.getItem())) return false;
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/handler/MissingMapHandler.java
// Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java // public class ItemList // { // // private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>(); // // public static void preInit() // { // ItemList.initFoodList(); // } // // private static void initFoodList() // { // String[] sets = { "base" }; // // for (String set : sets) // { // // String path = "assets/agriculture/data/"; // // URL resource = Resources.getResource(path + set + ".json"); // // try // { // ItemList.injectMetalSet(set, resource.openStream()); // } // catch (IOException ignored) // { // } // } // } // // private static void injectMetalSet(String name, InputStream stream) // { // FoodSet foodSet = new FoodSet(name); // // foodSet.load(stream); // // ItemList.setList.put(name, foodSet); // } // // public static ItemStack getItemStack(String setName, String foodName) // { // FoodSet foodSet = setList.get(setName); // if (foodSet == null) return null; // // return foodSet.getItemStack(foodName); // } // // public static FoodSet getSet(String setName) // { // return setList.get(setName); // } // // public static String[] getSetNames() // { // return setList.keySet().toArray(new String[setList.size()]); // } // }
import java.util.List; import net.minecraft.item.ItemStack; import com.teammetallurgy.agriculture.ItemList; import cpw.mods.fml.common.event.FMLMissingMappingsEvent; import cpw.mods.fml.common.event.FMLMissingMappingsEvent.MissingMapping;
package com.teammetallurgy.agriculture.handler; public class MissingMapHandler { public static void processingMissingMap(FMLMissingMappingsEvent event) { List<MissingMapping> missingMappings = event.get(); for (MissingMapping map : missingMappings) { if (map.name.equals("Agriculture:base.crop")) {
// Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java // public class ItemList // { // // private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>(); // // public static void preInit() // { // ItemList.initFoodList(); // } // // private static void initFoodList() // { // String[] sets = { "base" }; // // for (String set : sets) // { // // String path = "assets/agriculture/data/"; // // URL resource = Resources.getResource(path + set + ".json"); // // try // { // ItemList.injectMetalSet(set, resource.openStream()); // } // catch (IOException ignored) // { // } // } // } // // private static void injectMetalSet(String name, InputStream stream) // { // FoodSet foodSet = new FoodSet(name); // // foodSet.load(stream); // // ItemList.setList.put(name, foodSet); // } // // public static ItemStack getItemStack(String setName, String foodName) // { // FoodSet foodSet = setList.get(setName); // if (foodSet == null) return null; // // return foodSet.getItemStack(foodName); // } // // public static FoodSet getSet(String setName) // { // return setList.get(setName); // } // // public static String[] getSetNames() // { // return setList.keySet().toArray(new String[setList.size()]); // } // } // Path: src/main/java/com/teammetallurgy/agriculture/handler/MissingMapHandler.java import java.util.List; import net.minecraft.item.ItemStack; import com.teammetallurgy.agriculture.ItemList; import cpw.mods.fml.common.event.FMLMissingMappingsEvent; import cpw.mods.fml.common.event.FMLMissingMappingsEvent.MissingMapping; package com.teammetallurgy.agriculture.handler; public class MissingMapHandler { public static void processingMissingMap(FMLMissingMappingsEvent event) { List<MissingMapping> missingMappings = event.get(); for (MissingMapping map : missingMappings) { if (map.name.equals("Agriculture:base.crop")) {
ItemStack stack = ItemList.getItemStack("base", "Dough");
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/block/plant/BlockPeanut.java
// Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java // public class ItemList // { // // private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>(); // // public static void preInit() // { // ItemList.initFoodList(); // } // // private static void initFoodList() // { // String[] sets = { "base" }; // // for (String set : sets) // { // // String path = "assets/agriculture/data/"; // // URL resource = Resources.getResource(path + set + ".json"); // // try // { // ItemList.injectMetalSet(set, resource.openStream()); // } // catch (IOException ignored) // { // } // } // } // // private static void injectMetalSet(String name, InputStream stream) // { // FoodSet foodSet = new FoodSet(name); // // foodSet.load(stream); // // ItemList.setList.put(name, foodSet); // } // // public static ItemStack getItemStack(String setName, String foodName) // { // FoodSet foodSet = setList.get(setName); // if (foodSet == null) return null; // // return foodSet.getItemStack(foodName); // } // // public static FoodSet getSet(String setName) // { // return setList.get(setName); // } // // public static String[] getSetNames() // { // return setList.keySet().toArray(new String[setList.size()]); // } // }
import com.teammetallurgy.agriculture.ItemList;
package com.teammetallurgy.agriculture.block.plant; public class BlockPeanut extends BlockPlant { public BlockPeanut() { this.setBlockTextureName("agriculture:peanut"); this.setBlockName("agriculture.peanut");
// Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java // public class ItemList // { // // private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>(); // // public static void preInit() // { // ItemList.initFoodList(); // } // // private static void initFoodList() // { // String[] sets = { "base" }; // // for (String set : sets) // { // // String path = "assets/agriculture/data/"; // // URL resource = Resources.getResource(path + set + ".json"); // // try // { // ItemList.injectMetalSet(set, resource.openStream()); // } // catch (IOException ignored) // { // } // } // } // // private static void injectMetalSet(String name, InputStream stream) // { // FoodSet foodSet = new FoodSet(name); // // foodSet.load(stream); // // ItemList.setList.put(name, foodSet); // } // // public static ItemStack getItemStack(String setName, String foodName) // { // FoodSet foodSet = setList.get(setName); // if (foodSet == null) return null; // // return foodSet.getItemStack(foodName); // } // // public static FoodSet getSet(String setName) // { // return setList.get(setName); // } // // public static String[] getSetNames() // { // return setList.keySet().toArray(new String[setList.size()]); // } // } // Path: src/main/java/com/teammetallurgy/agriculture/block/plant/BlockPeanut.java import com.teammetallurgy.agriculture.ItemList; package com.teammetallurgy.agriculture.block.plant; public class BlockPeanut extends BlockPlant { public BlockPeanut() { this.setBlockTextureName("agriculture:peanut"); this.setBlockName("agriculture.peanut");
harvestItemStack = ItemList.getItemStack("base", "Peanuts");
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/food/FoodSet.java
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum FoodType // { // base, crop, edible // } // // Path: src/main/java/com/teammetallurgy/agriculture/handler/AgricultureLogHandler.java // public class AgricultureLogHandler // { // private static Logger LOGGER; // // public static void setLogger(Logger log) // { // LOGGER = log; // } // // public static void info(String message) // { // LOGGER.info(message); // } // // public static void trace(String message) // { // LOGGER.trace(message); // } // // public static void warn(String message) // { // LOGGER.warn(message); // } // // }
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import com.google.gson.Gson; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.food.Food.FoodType; import com.teammetallurgy.agriculture.handler.AgricultureLogHandler; import cpw.mods.fml.common.registry.GameRegistry;
package com.teammetallurgy.agriculture.food; public class FoodSet { private final String name; private final String setTag; private Food[] foods; private HashMap<String, ItemStack> itemStacks = new HashMap<String, ItemStack>(); private FoodItem defaultItem; public FoodSet(String setName) { this.name = setName; this.setTag = this.name.substring(0, 1).toUpperCase() + this.name.substring(1); this.initDefaults(); } private void initDefaults() { String postfix = this.name.toLowerCase(); postfix = postfix.replace(" ", "."); this.defaultItem = new FoodItem(postfix, 2); GameRegistry.registerItem(defaultItem, this.name + ".item"); } public void load(InputStream inputStream) { Reader reader = null; try { reader = new InputStreamReader(inputStream, "UTF-8"); } catch (IOException e) {
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum FoodType // { // base, crop, edible // } // // Path: src/main/java/com/teammetallurgy/agriculture/handler/AgricultureLogHandler.java // public class AgricultureLogHandler // { // private static Logger LOGGER; // // public static void setLogger(Logger log) // { // LOGGER = log; // } // // public static void info(String message) // { // LOGGER.info(message); // } // // public static void trace(String message) // { // LOGGER.trace(message); // } // // public static void warn(String message) // { // LOGGER.warn(message); // } // // } // Path: src/main/java/com/teammetallurgy/agriculture/food/FoodSet.java import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import com.google.gson.Gson; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.food.Food.FoodType; import com.teammetallurgy.agriculture.handler.AgricultureLogHandler; import cpw.mods.fml.common.registry.GameRegistry; package com.teammetallurgy.agriculture.food; public class FoodSet { private final String name; private final String setTag; private Food[] foods; private HashMap<String, ItemStack> itemStacks = new HashMap<String, ItemStack>(); private FoodItem defaultItem; public FoodSet(String setName) { this.name = setName; this.setTag = this.name.substring(0, 1).toUpperCase() + this.name.substring(1); this.initDefaults(); } private void initDefaults() { String postfix = this.name.toLowerCase(); postfix = postfix.replace(" ", "."); this.defaultItem = new FoodItem(postfix, 2); GameRegistry.registerItem(defaultItem, this.name + ".item"); } public void load(InputStream inputStream) { Reader reader = null; try { reader = new InputStreamReader(inputStream, "UTF-8"); } catch (IOException e) {
AgricultureLogHandler.warn(e.getLocalizedMessage());
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/food/FoodSet.java
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum FoodType // { // base, crop, edible // } // // Path: src/main/java/com/teammetallurgy/agriculture/handler/AgricultureLogHandler.java // public class AgricultureLogHandler // { // private static Logger LOGGER; // // public static void setLogger(Logger log) // { // LOGGER = log; // } // // public static void info(String message) // { // LOGGER.info(message); // } // // public static void trace(String message) // { // LOGGER.trace(message); // } // // public static void warn(String message) // { // LOGGER.warn(message); // } // // }
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import com.google.gson.Gson; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.food.Food.FoodType; import com.teammetallurgy.agriculture.handler.AgricultureLogHandler; import cpw.mods.fml.common.registry.GameRegistry;
private void initDefaults() { String postfix = this.name.toLowerCase(); postfix = postfix.replace(" ", "."); this.defaultItem = new FoodItem(postfix, 2); GameRegistry.registerItem(defaultItem, this.name + ".item"); } public void load(InputStream inputStream) { Reader reader = null; try { reader = new InputStreamReader(inputStream, "UTF-8"); } catch (IOException e) { AgricultureLogHandler.warn(e.getLocalizedMessage()); } this.foods = new Gson().fromJson(reader, Food[].class); int meta; for (meta = 0; meta < this.foods.length; meta++) { Food food = foods[meta]; String texture = food.getName().replace(" ", "_");
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum FoodType // { // base, crop, edible // } // // Path: src/main/java/com/teammetallurgy/agriculture/handler/AgricultureLogHandler.java // public class AgricultureLogHandler // { // private static Logger LOGGER; // // public static void setLogger(Logger log) // { // LOGGER = log; // } // // public static void info(String message) // { // LOGGER.info(message); // } // // public static void trace(String message) // { // LOGGER.trace(message); // } // // public static void warn(String message) // { // LOGGER.warn(message); // } // // } // Path: src/main/java/com/teammetallurgy/agriculture/food/FoodSet.java import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import com.google.gson.Gson; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.food.Food.FoodType; import com.teammetallurgy.agriculture.handler.AgricultureLogHandler; import cpw.mods.fml.common.registry.GameRegistry; private void initDefaults() { String postfix = this.name.toLowerCase(); postfix = postfix.replace(" ", "."); this.defaultItem = new FoodItem(postfix, 2); GameRegistry.registerItem(defaultItem, this.name + ".item"); } public void load(InputStream inputStream) { Reader reader = null; try { reader = new InputStreamReader(inputStream, "UTF-8"); } catch (IOException e) { AgricultureLogHandler.warn(e.getLocalizedMessage()); } this.foods = new Gson().fromJson(reader, Food[].class); int meta; for (meta = 0; meta < this.foods.length; meta++) { Food food = foods[meta]; String texture = food.getName().replace(" ", "_");
texture = Agriculture.MODID + ":" + this.name + "/" + texture.toLowerCase();
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/food/FoodSet.java
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum FoodType // { // base, crop, edible // } // // Path: src/main/java/com/teammetallurgy/agriculture/handler/AgricultureLogHandler.java // public class AgricultureLogHandler // { // private static Logger LOGGER; // // public static void setLogger(Logger log) // { // LOGGER = log; // } // // public static void info(String message) // { // LOGGER.info(message); // } // // public static void trace(String message) // { // LOGGER.trace(message); // } // // public static void warn(String message) // { // LOGGER.warn(message); // } // // }
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import com.google.gson.Gson; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.food.Food.FoodType; import com.teammetallurgy.agriculture.handler.AgricultureLogHandler; import cpw.mods.fml.common.registry.GameRegistry;
GameRegistry.registerItem(defaultItem, this.name + ".item"); } public void load(InputStream inputStream) { Reader reader = null; try { reader = new InputStreamReader(inputStream, "UTF-8"); } catch (IOException e) { AgricultureLogHandler.warn(e.getLocalizedMessage()); } this.foods = new Gson().fromJson(reader, Food[].class); int meta; for (meta = 0; meta < this.foods.length; meta++) { Food food = foods[meta]; String texture = food.getName().replace(" ", "_"); texture = Agriculture.MODID + ":" + this.name + "/" + texture.toLowerCase(); String tag = food.getName().replace(" ", ""); String oreDicPrefix = "crop";
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum FoodType // { // base, crop, edible // } // // Path: src/main/java/com/teammetallurgy/agriculture/handler/AgricultureLogHandler.java // public class AgricultureLogHandler // { // private static Logger LOGGER; // // public static void setLogger(Logger log) // { // LOGGER = log; // } // // public static void info(String message) // { // LOGGER.info(message); // } // // public static void trace(String message) // { // LOGGER.trace(message); // } // // public static void warn(String message) // { // LOGGER.warn(message); // } // // } // Path: src/main/java/com/teammetallurgy/agriculture/food/FoodSet.java import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import com.google.gson.Gson; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.food.Food.FoodType; import com.teammetallurgy.agriculture.handler.AgricultureLogHandler; import cpw.mods.fml.common.registry.GameRegistry; GameRegistry.registerItem(defaultItem, this.name + ".item"); } public void load(InputStream inputStream) { Reader reader = null; try { reader = new InputStreamReader(inputStream, "UTF-8"); } catch (IOException e) { AgricultureLogHandler.warn(e.getLocalizedMessage()); } this.foods = new Gson().fromJson(reader, Food[].class); int meta; for (meta = 0; meta < this.foods.length; meta++) { Food food = foods[meta]; String texture = food.getName().replace(" ", "_"); texture = Agriculture.MODID + ":" + this.name + "/" + texture.toLowerCase(); String tag = food.getName().replace(" ", ""); String oreDicPrefix = "crop";
if (food.type == FoodType.base || food.type == FoodType.edible)
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/block/plant/BlockPlant.java
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // }
import java.util.Random; import vazkii.botania.api.item.IHornHarvestable; import net.minecraft.block.BlockCrops; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; import com.teammetallurgy.agriculture.Agriculture; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
package com.teammetallurgy.agriculture.block.plant; public class BlockPlant extends BlockCrops implements IHornHarvestable { protected ItemStack harvestItemStack; private IIcon plantIcons[]; public BlockPlant() {
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // Path: src/main/java/com/teammetallurgy/agriculture/block/plant/BlockPlant.java import java.util.Random; import vazkii.botania.api.item.IHornHarvestable; import net.minecraft.block.BlockCrops; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; import com.teammetallurgy.agriculture.Agriculture; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; package com.teammetallurgy.agriculture.block.plant; public class BlockPlant extends BlockCrops implements IHornHarvestable { protected ItemStack harvestItemStack; private IIcon plantIcons[]; public BlockPlant() {
this.setCreativeTab(Agriculture.instance.creativeTabBlock);
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/food/FoodItem.java
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum FoodType // { // base, crop, edible // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum Methods // { // process(2), bake(3), prepare(1), brew(2), fry(3), freeze(3); // // private int hungerBonus; // // private Methods(int bonus) // { // hungerBonus = bonus; // } // // public int getHungerBonus() // { // return hungerBonus; // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.Item; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.food.Food.FoodType; import com.teammetallurgy.agriculture.food.Food.Methods; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
package com.teammetallurgy.agriculture.food; public class FoodItem extends ItemFood { private HashMap<Integer, String> names = new HashMap<Integer, String>();
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum FoodType // { // base, crop, edible // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum Methods // { // process(2), bake(3), prepare(1), brew(2), fry(3), freeze(3); // // private int hungerBonus; // // private Methods(int bonus) // { // hungerBonus = bonus; // } // // public int getHungerBonus() // { // return hungerBonus; // } // } // Path: src/main/java/com/teammetallurgy/agriculture/food/FoodItem.java import java.util.HashMap; import java.util.List; import java.util.Map; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.Item; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.food.Food.FoodType; import com.teammetallurgy.agriculture.food.Food.Methods; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; package com.teammetallurgy.agriculture.food; public class FoodItem extends ItemFood { private HashMap<Integer, String> names = new HashMap<Integer, String>();
private HashMap<Integer, FoodType> itemTypes = new HashMap<Integer, FoodType>();
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/food/FoodItem.java
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum FoodType // { // base, crop, edible // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum Methods // { // process(2), bake(3), prepare(1), brew(2), fry(3), freeze(3); // // private int hungerBonus; // // private Methods(int bonus) // { // hungerBonus = bonus; // } // // public int getHungerBonus() // { // return hungerBonus; // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.Item; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.food.Food.FoodType; import com.teammetallurgy.agriculture.food.Food.Methods; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
package com.teammetallurgy.agriculture.food; public class FoodItem extends ItemFood { private HashMap<Integer, String> names = new HashMap<Integer, String>(); private HashMap<Integer, FoodType> itemTypes = new HashMap<Integer, FoodType>(); private HashMap<Integer, String> textures = new HashMap<Integer, String>(); private HashMap<Integer, IIcon> icons = new HashMap<Integer, IIcon>(); private HashMap<Integer, Integer> healAmounts = new HashMap<Integer, Integer>();
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum FoodType // { // base, crop, edible // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum Methods // { // process(2), bake(3), prepare(1), brew(2), fry(3), freeze(3); // // private int hungerBonus; // // private Methods(int bonus) // { // hungerBonus = bonus; // } // // public int getHungerBonus() // { // return hungerBonus; // } // } // Path: src/main/java/com/teammetallurgy/agriculture/food/FoodItem.java import java.util.HashMap; import java.util.List; import java.util.Map; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.Item; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.food.Food.FoodType; import com.teammetallurgy.agriculture.food.Food.Methods; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; package com.teammetallurgy.agriculture.food; public class FoodItem extends ItemFood { private HashMap<Integer, String> names = new HashMap<Integer, String>(); private HashMap<Integer, FoodType> itemTypes = new HashMap<Integer, FoodType>(); private HashMap<Integer, String> textures = new HashMap<Integer, String>(); private HashMap<Integer, IIcon> icons = new HashMap<Integer, IIcon>(); private HashMap<Integer, Integer> healAmounts = new HashMap<Integer, Integer>();
private HashMap<Integer, Food.Methods> methods = new HashMap<Integer, Food.Methods>();
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/food/FoodItem.java
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum FoodType // { // base, crop, edible // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum Methods // { // process(2), bake(3), prepare(1), brew(2), fry(3), freeze(3); // // private int hungerBonus; // // private Methods(int bonus) // { // hungerBonus = bonus; // } // // public int getHungerBonus() // { // return hungerBonus; // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.Item; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.food.Food.FoodType; import com.teammetallurgy.agriculture.food.Food.Methods; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
package com.teammetallurgy.agriculture.food; public class FoodItem extends ItemFood { private HashMap<Integer, String> names = new HashMap<Integer, String>(); private HashMap<Integer, FoodType> itemTypes = new HashMap<Integer, FoodType>(); private HashMap<Integer, String> textures = new HashMap<Integer, String>(); private HashMap<Integer, IIcon> icons = new HashMap<Integer, IIcon>(); private HashMap<Integer, Integer> healAmounts = new HashMap<Integer, Integer>(); private HashMap<Integer, Food.Methods> methods = new HashMap<Integer, Food.Methods>(); public FoodItem(String postfix, int health) { super(health, false); this.healAmounts.put(0, 2);
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum FoodType // { // base, crop, edible // } // // Path: src/main/java/com/teammetallurgy/agriculture/food/Food.java // public static enum Methods // { // process(2), bake(3), prepare(1), brew(2), fry(3), freeze(3); // // private int hungerBonus; // // private Methods(int bonus) // { // hungerBonus = bonus; // } // // public int getHungerBonus() // { // return hungerBonus; // } // } // Path: src/main/java/com/teammetallurgy/agriculture/food/FoodItem.java import java.util.HashMap; import java.util.List; import java.util.Map; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.Item; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import com.teammetallurgy.agriculture.Agriculture; import com.teammetallurgy.agriculture.food.Food.FoodType; import com.teammetallurgy.agriculture.food.Food.Methods; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; package com.teammetallurgy.agriculture.food; public class FoodItem extends ItemFood { private HashMap<Integer, String> names = new HashMap<Integer, String>(); private HashMap<Integer, FoodType> itemTypes = new HashMap<Integer, FoodType>(); private HashMap<Integer, String> textures = new HashMap<Integer, String>(); private HashMap<Integer, IIcon> icons = new HashMap<Integer, IIcon>(); private HashMap<Integer, Integer> healAmounts = new HashMap<Integer, Integer>(); private HashMap<Integer, Food.Methods> methods = new HashMap<Integer, Food.Methods>(); public FoodItem(String postfix, int health) { super(health, false); this.healAmounts.put(0, 2);
this.setTextureName(Agriculture.MODID + ":food_item_default");
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/worldgen/WorldGenSalt.java
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // }
import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import com.teammetallurgy.agriculture.BlockList; import cpw.mods.fml.common.IWorldGenerator;
package com.teammetallurgy.agriculture.worldgen; public class WorldGenSalt implements IWorldGenerator { private int saltPerChunk = 1; private Block saltBlock; private static int saltSeed = "saltBlock".hashCode(); public WorldGenSalt() {
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // } // Path: src/main/java/com/teammetallurgy/agriculture/worldgen/WorldGenSalt.java import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import com.teammetallurgy.agriculture.BlockList; import cpw.mods.fml.common.IWorldGenerator; package com.teammetallurgy.agriculture.worldgen; public class WorldGenSalt implements IWorldGenerator { private int saltPerChunk = 1; private Block saltBlock; private static int saltSeed = "saltBlock".hashCode(); public WorldGenSalt() {
saltBlock = BlockList.salt;
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/machine/counter/ContainerCounter.java
// Path: src/main/java/com/teammetallurgy/agriculture/machine/TileEntityBaseMachine.java // public abstract class TileEntityBaseMachine extends TileEntity implements ISidedInventory // { // protected byte facing = 0; // protected ItemStack[] inventory; // // public TileEntityBaseMachine(int inventorySize) // { // inventory = new ItemStack[inventorySize]; // } // // @Override // abstract public int getInventoryStackLimit(); // // @Override // abstract public String getInventoryName(); // // public void setFacing(byte direction) // { // facing = direction; // } // // public byte getFacing() // { // return facing; // } // // @Override // public void writeToNBT(NBTTagCompound compound) // { // super.writeToNBT(compound); // writeInventoryToNBT(compound); // compound.setByte("facing", facing); // // } // // protected void writeInventoryToNBT(NBTTagCompound compound) // { // NBTTagList inventoryNBT = new NBTTagList(); // // for (int i = 0; i < inventory.length; i++) // { // if (inventory[i] != null) // { // NBTTagCompound slotCompound = new NBTTagCompound(); // slotCompound.setByte("Slot", (byte) i); // inventory[i].writeToNBT(slotCompound); // // inventoryNBT.appendTag(slotCompound); // } // } // // compound.setTag("Items", inventoryNBT); // } // // @Override // public void readFromNBT(NBTTagCompound compound) // { // super.readFromNBT(compound); // readInventoryFromNBT(compound); // facing = compound.getByte("facing"); // // } // // protected void readInventoryFromNBT(NBTTagCompound compound) // { // NBTTagList inventoryNBT = compound.getTagList("Items", 10); // // for (int i = 0; i < inventoryNBT.tagCount(); i++) // { // NBTTagCompound slotCompound = inventoryNBT.getCompoundTagAt(i); // byte slotId = slotCompound.getByte("Slot"); // // if (slotId >= 0 && slotId < inventory.length) // { // inventory[slotId] = ItemStack.loadItemStackFromNBT(slotCompound); // } // } // } // // @Override // public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) // { // NBTTagCompound nbtCompound = pkt.func_148857_g(); // if (nbtCompound == null) return; // // readFromNBT(nbtCompound); // } // // @Override // public Packet getDescriptionPacket() // { // NBTTagCompound nbtCompound = new NBTTagCompound(); // // writeToNBT(nbtCompound); // // S35PacketUpdateTileEntity packet = new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, nbtCompound); // return packet; // } // // @Override // public int getSizeInventory() // { // return inventory.length; // } // // @Override // public ItemStack getStackInSlot(int slotId) // { // if (slotId >= 0 && slotId < inventory.length) { return inventory[slotId]; } // // return null; // } // // @Override // public ItemStack decrStackSize(int slotId, int amount) // { // if (inventory[slotId] == null) { return null; } // // ItemStack requestedStack = null; // // if (inventory[slotId].stackSize <= amount) // { // requestedStack = inventory[slotId]; // inventory[slotId] = null; // return requestedStack; // } // // requestedStack = inventory[slotId].splitStack(amount); // // if (inventory[slotId].stackSize == 0) // { // inventory[slotId] = null; // } // // return requestedStack; // } // // @Override // public ItemStack getStackInSlotOnClosing(int slotId) // { // if (inventory[slotId] == null) { return null; } // // ItemStack slotStack = inventory[slotId]; // inventory[slotId] = null; // return slotStack; // } // // @Override // public void setInventorySlotContents(int slotId, ItemStack itemStack) // { // inventory[slotId] = itemStack; // // if (itemStack != null && itemStack.stackSize > getInventoryStackLimit()) // { // inventory[slotId].stackSize = getInventoryStackLimit(); // } // } // // @Override // public boolean hasCustomInventoryName() // { // return false; // } // // @Override // public boolean isUseableByPlayer(EntityPlayer player) // { // return player.getDistanceSq(xCoord, yCoord, zCoord) <= 64; // } // // @Override // public void openInventory() // { // // not in use // } // // @Override // public void closeInventory() // { // // not in use // } // // @Override // abstract public boolean isItemValidForSlot(int slotId, ItemStack itemStack); // // @Override // abstract public int[] getAccessibleSlotsFromSide(int side); // // @Override // abstract public boolean canInsertItem(int slotId, ItemStack itemStack, int side); // // @Override // abstract public boolean canExtractItem(int slotId, ItemStack itemStack, int side); // // }
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import com.teammetallurgy.agriculture.machine.TileEntityBaseMachine;
package com.teammetallurgy.agriculture.machine.counter; public class ContainerCounter extends Container {
// Path: src/main/java/com/teammetallurgy/agriculture/machine/TileEntityBaseMachine.java // public abstract class TileEntityBaseMachine extends TileEntity implements ISidedInventory // { // protected byte facing = 0; // protected ItemStack[] inventory; // // public TileEntityBaseMachine(int inventorySize) // { // inventory = new ItemStack[inventorySize]; // } // // @Override // abstract public int getInventoryStackLimit(); // // @Override // abstract public String getInventoryName(); // // public void setFacing(byte direction) // { // facing = direction; // } // // public byte getFacing() // { // return facing; // } // // @Override // public void writeToNBT(NBTTagCompound compound) // { // super.writeToNBT(compound); // writeInventoryToNBT(compound); // compound.setByte("facing", facing); // // } // // protected void writeInventoryToNBT(NBTTagCompound compound) // { // NBTTagList inventoryNBT = new NBTTagList(); // // for (int i = 0; i < inventory.length; i++) // { // if (inventory[i] != null) // { // NBTTagCompound slotCompound = new NBTTagCompound(); // slotCompound.setByte("Slot", (byte) i); // inventory[i].writeToNBT(slotCompound); // // inventoryNBT.appendTag(slotCompound); // } // } // // compound.setTag("Items", inventoryNBT); // } // // @Override // public void readFromNBT(NBTTagCompound compound) // { // super.readFromNBT(compound); // readInventoryFromNBT(compound); // facing = compound.getByte("facing"); // // } // // protected void readInventoryFromNBT(NBTTagCompound compound) // { // NBTTagList inventoryNBT = compound.getTagList("Items", 10); // // for (int i = 0; i < inventoryNBT.tagCount(); i++) // { // NBTTagCompound slotCompound = inventoryNBT.getCompoundTagAt(i); // byte slotId = slotCompound.getByte("Slot"); // // if (slotId >= 0 && slotId < inventory.length) // { // inventory[slotId] = ItemStack.loadItemStackFromNBT(slotCompound); // } // } // } // // @Override // public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) // { // NBTTagCompound nbtCompound = pkt.func_148857_g(); // if (nbtCompound == null) return; // // readFromNBT(nbtCompound); // } // // @Override // public Packet getDescriptionPacket() // { // NBTTagCompound nbtCompound = new NBTTagCompound(); // // writeToNBT(nbtCompound); // // S35PacketUpdateTileEntity packet = new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, nbtCompound); // return packet; // } // // @Override // public int getSizeInventory() // { // return inventory.length; // } // // @Override // public ItemStack getStackInSlot(int slotId) // { // if (slotId >= 0 && slotId < inventory.length) { return inventory[slotId]; } // // return null; // } // // @Override // public ItemStack decrStackSize(int slotId, int amount) // { // if (inventory[slotId] == null) { return null; } // // ItemStack requestedStack = null; // // if (inventory[slotId].stackSize <= amount) // { // requestedStack = inventory[slotId]; // inventory[slotId] = null; // return requestedStack; // } // // requestedStack = inventory[slotId].splitStack(amount); // // if (inventory[slotId].stackSize == 0) // { // inventory[slotId] = null; // } // // return requestedStack; // } // // @Override // public ItemStack getStackInSlotOnClosing(int slotId) // { // if (inventory[slotId] == null) { return null; } // // ItemStack slotStack = inventory[slotId]; // inventory[slotId] = null; // return slotStack; // } // // @Override // public void setInventorySlotContents(int slotId, ItemStack itemStack) // { // inventory[slotId] = itemStack; // // if (itemStack != null && itemStack.stackSize > getInventoryStackLimit()) // { // inventory[slotId].stackSize = getInventoryStackLimit(); // } // } // // @Override // public boolean hasCustomInventoryName() // { // return false; // } // // @Override // public boolean isUseableByPlayer(EntityPlayer player) // { // return player.getDistanceSq(xCoord, yCoord, zCoord) <= 64; // } // // @Override // public void openInventory() // { // // not in use // } // // @Override // public void closeInventory() // { // // not in use // } // // @Override // abstract public boolean isItemValidForSlot(int slotId, ItemStack itemStack); // // @Override // abstract public int[] getAccessibleSlotsFromSide(int side); // // @Override // abstract public boolean canInsertItem(int slotId, ItemStack itemStack, int side); // // @Override // abstract public boolean canExtractItem(int slotId, ItemStack itemStack, int side); // // } // Path: src/main/java/com/teammetallurgy/agriculture/machine/counter/ContainerCounter.java import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import com.teammetallurgy.agriculture.machine.TileEntityBaseMachine; package com.teammetallurgy.agriculture.machine.counter; public class ContainerCounter extends Container {
private TileEntityBaseMachine machine;
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/machine/BlockBaseMachine.java
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // }
import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import com.teammetallurgy.agriculture.Agriculture;
package com.teammetallurgy.agriculture.machine; public abstract class BlockBaseMachine extends BlockContainer { Random random = new Random(); public BlockBaseMachine() { super(Material.rock); this.setBlockTextureName("minecraft:brick"); this.setHardness(3F);
// Path: src/main/java/com/teammetallurgy/agriculture/Agriculture.java // @Mod(name = Agriculture.MODNAME, modid = Agriculture.MODID, version = Agriculture.VERSION, useMetadata = true) // public class Agriculture // { // public static final String MODNAME = "Agriculture"; // public static final String MODID = "Agriculture"; // public static final String VERSION = "2.0"; // // @Mod.Instance(Agriculture.MODID) // public static Agriculture instance; // // @SidedProxy(clientSide = "com.teammetallurgy.agriculture.networking.ClientProxy", serverSide = "com.teammetallurgy.agriculture.networking.CommonProxy") // public static CommonProxy proxy; // // // public AgricultureCreativeTab creativeTabFood = new AgricultureCreativeTab(Agriculture.MODID + ".Food"); // public AgricultureCreativeTab creativeTabBlock = new AgricultureCreativeTab(Agriculture.MODID + ".blocks"); // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // AgricultureLogHandler.setLogger(event.getModLog()); // AgricultureConfigHandler.setFile(event.getSuggestedConfigurationFile()); // // ItemList.preInit(); // // BlockList.preInit(); // // setCreativeTabsIcons(); // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // NetworkRegistry.INSTANCE.registerGuiHandler(Agriculture.instance, new GuiHandler()); // GameRegistry.registerWorldGenerator(new WorldGenSalt(), 0); // GameRegistry.registerWorldGenerator(new WorldGenPlants(), 0); // proxy.initRenderers(); // MinecraftForge.EVENT_BUS.register(new AgricultureEventHandler()); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // Recipes.create(); // Hunger.init(); // } // // @EventHandler // public void missingMapping(FMLMissingMappingsEvent event) // { // MissingMapHandler.processingMissingMap(event); // } // // private void setCreativeTabsIcons() // { // // creativeTabFood.setItemStack(ItemList.getItemStack("base", "Caramel Apple With Nuts")); // creativeTabBlock.setItem(BlockList.counter); // } // } // Path: src/main/java/com/teammetallurgy/agriculture/machine/BlockBaseMachine.java import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import com.teammetallurgy.agriculture.Agriculture; package com.teammetallurgy.agriculture.machine; public abstract class BlockBaseMachine extends BlockContainer { Random random = new Random(); public BlockBaseMachine() { super(Material.rock); this.setBlockTextureName("minecraft:brick"); this.setHardness(3F);
this.setCreativeTab(Agriculture.instance.creativeTabBlock);
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/machine/counter/ItemRendererCounter.java
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // }
import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import com.teammetallurgy.agriculture.BlockList; import cpw.mods.fml.client.FMLClientHandler;
package com.teammetallurgy.agriculture.machine.counter; public class ItemRendererCounter implements IItemRenderer { private ResourceLocation texture = new ResourceLocation("agriculture:textures/models/machines/counter.png"); private ModelCounter model = new ModelCounter(); @Override public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { if (itemStack == null || itemStack.getItem() == null) return false;
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // } // Path: src/main/java/com/teammetallurgy/agriculture/machine/counter/ItemRendererCounter.java import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import com.teammetallurgy.agriculture.BlockList; import cpw.mods.fml.client.FMLClientHandler; package com.teammetallurgy.agriculture.machine.counter; public class ItemRendererCounter implements IItemRenderer { private ResourceLocation texture = new ResourceLocation("agriculture:textures/models/machines/counter.png"); private ModelCounter model = new ModelCounter(); @Override public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { if (itemStack == null || itemStack.getItem() == null) return false;
if (BlockList.counter != Block.getBlockFromItem(itemStack.getItem())) return false;
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/ItemList.java
// Path: src/main/java/com/teammetallurgy/agriculture/food/FoodSet.java // public class FoodSet // { // private final String name; // private final String setTag; // private Food[] foods; // // private HashMap<String, ItemStack> itemStacks = new HashMap<String, ItemStack>(); // // private FoodItem defaultItem; // // public FoodSet(String setName) // { // this.name = setName; // this.setTag = this.name.substring(0, 1).toUpperCase() + this.name.substring(1); // this.initDefaults(); // } // // private void initDefaults() // { // String postfix = this.name.toLowerCase(); // postfix = postfix.replace(" ", "."); // // this.defaultItem = new FoodItem(postfix, 2); // GameRegistry.registerItem(defaultItem, this.name + ".item"); // } // // public void load(InputStream inputStream) // { // Reader reader = null; // try // { // reader = new InputStreamReader(inputStream, "UTF-8"); // // } // catch (IOException e) // { // AgricultureLogHandler.warn(e.getLocalizedMessage()); // } // // this.foods = new Gson().fromJson(reader, Food[].class); // // int meta; // for (meta = 0; meta < this.foods.length; meta++) // { // // Food food = foods[meta]; // String texture = food.getName().replace(" ", "_"); // texture = Agriculture.MODID + ":" + this.name + "/" + texture.toLowerCase(); // // String tag = food.getName().replace(" ", ""); // // String oreDicPrefix = "crop"; // // if (food.type == FoodType.base || food.type == FoodType.edible) // { // oreDicPrefix = "food"; // } // // defaultItem.addSubItem(meta, food.getName(), food.type, texture, food.method); // ItemStack stack = new ItemStack(defaultItem, 1, meta); // // OreDictionary.registerOre(oreDicPrefix + tag, stack); // // this.itemStacks.put(food.getName(), stack); // } // } // // public ItemStack getItemStack(String food) // { // return this.itemStacks.get(food); // } // // public Food[] getFoods() // { // return this.foods; // } // // public Food getFoodInfo(String name) // { // Food food = null; // for (int i = 0; i < foods.length; i++) // { // if (name.equals(foods[i].getName())) // { // food = foods[i]; // break; // } // } // return food; // } // // }
import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import net.minecraft.item.ItemStack; import com.google.common.io.Resources; import com.teammetallurgy.agriculture.food.FoodSet;
package com.teammetallurgy.agriculture; public class ItemList {
// Path: src/main/java/com/teammetallurgy/agriculture/food/FoodSet.java // public class FoodSet // { // private final String name; // private final String setTag; // private Food[] foods; // // private HashMap<String, ItemStack> itemStacks = new HashMap<String, ItemStack>(); // // private FoodItem defaultItem; // // public FoodSet(String setName) // { // this.name = setName; // this.setTag = this.name.substring(0, 1).toUpperCase() + this.name.substring(1); // this.initDefaults(); // } // // private void initDefaults() // { // String postfix = this.name.toLowerCase(); // postfix = postfix.replace(" ", "."); // // this.defaultItem = new FoodItem(postfix, 2); // GameRegistry.registerItem(defaultItem, this.name + ".item"); // } // // public void load(InputStream inputStream) // { // Reader reader = null; // try // { // reader = new InputStreamReader(inputStream, "UTF-8"); // // } // catch (IOException e) // { // AgricultureLogHandler.warn(e.getLocalizedMessage()); // } // // this.foods = new Gson().fromJson(reader, Food[].class); // // int meta; // for (meta = 0; meta < this.foods.length; meta++) // { // // Food food = foods[meta]; // String texture = food.getName().replace(" ", "_"); // texture = Agriculture.MODID + ":" + this.name + "/" + texture.toLowerCase(); // // String tag = food.getName().replace(" ", ""); // // String oreDicPrefix = "crop"; // // if (food.type == FoodType.base || food.type == FoodType.edible) // { // oreDicPrefix = "food"; // } // // defaultItem.addSubItem(meta, food.getName(), food.type, texture, food.method); // ItemStack stack = new ItemStack(defaultItem, 1, meta); // // OreDictionary.registerOre(oreDicPrefix + tag, stack); // // this.itemStacks.put(food.getName(), stack); // } // } // // public ItemStack getItemStack(String food) // { // return this.itemStacks.get(food); // } // // public Food[] getFoods() // { // return this.foods; // } // // public Food getFoodInfo(String name) // { // Food food = null; // for (int i = 0; i < foods.length; i++) // { // if (name.equals(foods[i].getName())) // { // food = foods[i]; // break; // } // } // return food; // } // // } // Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import net.minecraft.item.ItemStack; import com.google.common.io.Resources; import com.teammetallurgy.agriculture.food.FoodSet; package com.teammetallurgy.agriculture; public class ItemList {
private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>();
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/worldgen/WorldGenPlants.java
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // }
import java.util.Random; import com.teammetallurgy.agriculture.BlockList; import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import cpw.mods.fml.common.IWorldGenerator;
package com.teammetallurgy.agriculture.worldgen; public class WorldGenPlants implements IWorldGenerator { private Block plants[]; private static long plantGenerationSeed; public WorldGenPlants() { plantGenerationSeed = "agriculture.plants".hashCode();
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // } // Path: src/main/java/com/teammetallurgy/agriculture/worldgen/WorldGenPlants.java import java.util.Random; import com.teammetallurgy.agriculture.BlockList; import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import cpw.mods.fml.common.IWorldGenerator; package com.teammetallurgy.agriculture.worldgen; public class WorldGenPlants implements IWorldGenerator { private Block plants[]; private static long plantGenerationSeed; public WorldGenPlants() { plantGenerationSeed = "agriculture.plants".hashCode();
plants = new Block[] { BlockList.cinnamon, BlockList.peanut, BlockList.strawberry, BlockList.vanilla };
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/block/plant/BlockCinnamon.java
// Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java // public class ItemList // { // // private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>(); // // public static void preInit() // { // ItemList.initFoodList(); // } // // private static void initFoodList() // { // String[] sets = { "base" }; // // for (String set : sets) // { // // String path = "assets/agriculture/data/"; // // URL resource = Resources.getResource(path + set + ".json"); // // try // { // ItemList.injectMetalSet(set, resource.openStream()); // } // catch (IOException ignored) // { // } // } // } // // private static void injectMetalSet(String name, InputStream stream) // { // FoodSet foodSet = new FoodSet(name); // // foodSet.load(stream); // // ItemList.setList.put(name, foodSet); // } // // public static ItemStack getItemStack(String setName, String foodName) // { // FoodSet foodSet = setList.get(setName); // if (foodSet == null) return null; // // return foodSet.getItemStack(foodName); // } // // public static FoodSet getSet(String setName) // { // return setList.get(setName); // } // // public static String[] getSetNames() // { // return setList.keySet().toArray(new String[setList.size()]); // } // }
import com.teammetallurgy.agriculture.ItemList;
package com.teammetallurgy.agriculture.block.plant; public class BlockCinnamon extends BlockPlant { public BlockCinnamon() { this.setBlockTextureName("agriculture:cinnamon"); this.setBlockName("agriculture.cinnamon");
// Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java // public class ItemList // { // // private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>(); // // public static void preInit() // { // ItemList.initFoodList(); // } // // private static void initFoodList() // { // String[] sets = { "base" }; // // for (String set : sets) // { // // String path = "assets/agriculture/data/"; // // URL resource = Resources.getResource(path + set + ".json"); // // try // { // ItemList.injectMetalSet(set, resource.openStream()); // } // catch (IOException ignored) // { // } // } // } // // private static void injectMetalSet(String name, InputStream stream) // { // FoodSet foodSet = new FoodSet(name); // // foodSet.load(stream); // // ItemList.setList.put(name, foodSet); // } // // public static ItemStack getItemStack(String setName, String foodName) // { // FoodSet foodSet = setList.get(setName); // if (foodSet == null) return null; // // return foodSet.getItemStack(foodName); // } // // public static FoodSet getSet(String setName) // { // return setList.get(setName); // } // // public static String[] getSetNames() // { // return setList.keySet().toArray(new String[setList.size()]); // } // } // Path: src/main/java/com/teammetallurgy/agriculture/block/plant/BlockCinnamon.java import com.teammetallurgy.agriculture.ItemList; package com.teammetallurgy.agriculture.block.plant; public class BlockCinnamon extends BlockPlant { public BlockCinnamon() { this.setBlockTextureName("agriculture:cinnamon"); this.setBlockName("agriculture.cinnamon");
harvestItemStack = ItemList.getItemStack("base", "Cinnamon");
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/machine/processor/ItemRendererProcessor.java
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // }
import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import com.teammetallurgy.agriculture.BlockList; import cpw.mods.fml.client.FMLClientHandler;
package com.teammetallurgy.agriculture.machine.processor; public class ItemRendererProcessor implements IItemRenderer { private ResourceLocation texture = new ResourceLocation("agriculture:textures/models/machines/processor.png"); private ModelProcessor model = new ModelProcessor(); @Override public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { if (itemStack == null || itemStack.getItem() == null) return false;
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // } // Path: src/main/java/com/teammetallurgy/agriculture/machine/processor/ItemRendererProcessor.java import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import com.teammetallurgy.agriculture.BlockList; import cpw.mods.fml.client.FMLClientHandler; package com.teammetallurgy.agriculture.machine.processor; public class ItemRendererProcessor implements IItemRenderer { private ResourceLocation texture = new ResourceLocation("agriculture:textures/models/machines/processor.png"); private ModelProcessor model = new ModelProcessor(); @Override public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { if (itemStack == null || itemStack.getItem() == null) return false;
if (BlockList.processor != Block.getBlockFromItem(itemStack.getItem())) return false;
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/block/plant/BlockVanilla.java
// Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java // public class ItemList // { // // private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>(); // // public static void preInit() // { // ItemList.initFoodList(); // } // // private static void initFoodList() // { // String[] sets = { "base" }; // // for (String set : sets) // { // // String path = "assets/agriculture/data/"; // // URL resource = Resources.getResource(path + set + ".json"); // // try // { // ItemList.injectMetalSet(set, resource.openStream()); // } // catch (IOException ignored) // { // } // } // } // // private static void injectMetalSet(String name, InputStream stream) // { // FoodSet foodSet = new FoodSet(name); // // foodSet.load(stream); // // ItemList.setList.put(name, foodSet); // } // // public static ItemStack getItemStack(String setName, String foodName) // { // FoodSet foodSet = setList.get(setName); // if (foodSet == null) return null; // // return foodSet.getItemStack(foodName); // } // // public static FoodSet getSet(String setName) // { // return setList.get(setName); // } // // public static String[] getSetNames() // { // return setList.keySet().toArray(new String[setList.size()]); // } // }
import com.teammetallurgy.agriculture.ItemList;
package com.teammetallurgy.agriculture.block.plant; public class BlockVanilla extends BlockPlant { public BlockVanilla() { this.setBlockTextureName("agriculture:vanilla"); this.setBlockName("agriculture.vanilla");
// Path: src/main/java/com/teammetallurgy/agriculture/ItemList.java // public class ItemList // { // // private static HashMap<String, FoodSet> setList = new HashMap<String, FoodSet>(); // // public static void preInit() // { // ItemList.initFoodList(); // } // // private static void initFoodList() // { // String[] sets = { "base" }; // // for (String set : sets) // { // // String path = "assets/agriculture/data/"; // // URL resource = Resources.getResource(path + set + ".json"); // // try // { // ItemList.injectMetalSet(set, resource.openStream()); // } // catch (IOException ignored) // { // } // } // } // // private static void injectMetalSet(String name, InputStream stream) // { // FoodSet foodSet = new FoodSet(name); // // foodSet.load(stream); // // ItemList.setList.put(name, foodSet); // } // // public static ItemStack getItemStack(String setName, String foodName) // { // FoodSet foodSet = setList.get(setName); // if (foodSet == null) return null; // // return foodSet.getItemStack(foodName); // } // // public static FoodSet getSet(String setName) // { // return setList.get(setName); // } // // public static String[] getSetNames() // { // return setList.keySet().toArray(new String[setList.size()]); // } // } // Path: src/main/java/com/teammetallurgy/agriculture/block/plant/BlockVanilla.java import com.teammetallurgy.agriculture.ItemList; package com.teammetallurgy.agriculture.block.plant; public class BlockVanilla extends BlockPlant { public BlockVanilla() { this.setBlockTextureName("agriculture:vanilla"); this.setBlockName("agriculture.vanilla");
harvestItemStack = ItemList.getItemStack("base", "Vanilla");
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/machine/brewer/ItemRendererBrewer.java
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // }
import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import com.teammetallurgy.agriculture.BlockList; import cpw.mods.fml.client.FMLClientHandler;
package com.teammetallurgy.agriculture.machine.brewer; public class ItemRendererBrewer implements IItemRenderer { private ResourceLocation texture = new ResourceLocation("agriculture:textures/models/machines/brewer.png"); private ModelBrewer model = new ModelBrewer(); @Override public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { if (itemStack == null || itemStack.getItem() == null) return false;
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // } // Path: src/main/java/com/teammetallurgy/agriculture/machine/brewer/ItemRendererBrewer.java import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import com.teammetallurgy.agriculture.BlockList; import cpw.mods.fml.client.FMLClientHandler; package com.teammetallurgy.agriculture.machine.brewer; public class ItemRendererBrewer implements IItemRenderer { private ResourceLocation texture = new ResourceLocation("agriculture:textures/models/machines/brewer.png"); private ModelBrewer model = new ModelBrewer(); @Override public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { if (itemStack == null || itemStack.getItem() == null) return false;
if (BlockList.brewer != Block.getBlockFromItem(itemStack.getItem())) return false;
TeamMetallurgy/Agriculture2
src/main/java/com/teammetallurgy/agriculture/machine/oven/ItemRendererOven.java
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // }
import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import com.teammetallurgy.agriculture.BlockList; import cpw.mods.fml.client.FMLClientHandler;
package com.teammetallurgy.agriculture.machine.oven; public class ItemRendererOven implements IItemRenderer { private ResourceLocation texture = new ResourceLocation("agriculture:textures/models/machines/oven.png"); private ModelOven model = new ModelOven(); @Override public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { if (itemStack == null || itemStack.getItem() == null) return false;
// Path: src/main/java/com/teammetallurgy/agriculture/BlockList.java // public class BlockList // { // // public static Block brewer; // public static Block counter; // public static Block frier; // public static Block icebox; // public static Block oven; // public static Block processor; // public static Block salt; // // public static Block cinnamon; // public static Block peanut; // public static Block strawberry; // public static Block vanilla; // // public static void preInit() // { // String modID = Agriculture.MODID.toLowerCase(); // // // Machines // // String blockName = "brewer"; // brewer = new BlockBrewer().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(brewer, blockName); // GameRegistry.registerTileEntity(TileEntityBrewer.class, blockName); // // blockName = "counter"; // counter = new BlockCounter().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(counter, blockName); // GameRegistry.registerTileEntity(TileEntityCounter.class, blockName); // // blockName = "frier"; // frier = new BlockFrier().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(frier, blockName); // GameRegistry.registerTileEntity(TileEntityFrier.class, blockName); // // blockName = "icebox"; // icebox = new BlockIcebox().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(icebox, blockName); // GameRegistry.registerTileEntity(TileEntityIcebox.class, blockName); // // blockName = "oven"; // oven = new BlockOven().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(oven, blockName); // GameRegistry.registerTileEntity(TileEntityOven.class, blockName); // // blockName = "processor"; // processor = new BlockProcessor().setBlockName(modID + "." + blockName); // GameRegistry.registerBlock(processor, blockName); // GameRegistry.registerTileEntity(TileEntityProcessor.class, blockName); // // blockName = "salt"; // salt = new BlockSalt(); // GameRegistry.registerBlock(salt, blockName); // // // Plants // blockName = "cinnamon"; // cinnamon = new BlockCinnamon(); // GameRegistry.registerBlock(cinnamon, blockName); // // blockName = "peanut"; // peanut = new BlockPeanut(); // GameRegistry.registerBlock(peanut, blockName); // // blockName = "strawberry"; // strawberry = new BlockStrawberry(); // GameRegistry.registerBlock(strawberry, blockName); // // blockName = "vanilla"; // vanilla = new BlockVanilla(); // GameRegistry.registerBlock(vanilla, blockName); // // } // // } // Path: src/main/java/com/teammetallurgy/agriculture/machine/oven/ItemRendererOven.java import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import com.teammetallurgy.agriculture.BlockList; import cpw.mods.fml.client.FMLClientHandler; package com.teammetallurgy.agriculture.machine.oven; public class ItemRendererOven implements IItemRenderer { private ResourceLocation texture = new ResourceLocation("agriculture:textures/models/machines/oven.png"); private ModelOven model = new ModelOven(); @Override public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { if (itemStack == null || itemStack.getItem() == null) return false;
if (BlockList.oven != Block.getBlockFromItem(itemStack.getItem())) return false;
gustav9797/PowerfulPerms
PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/common/PowerfulGroup.java
// Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Group.java // public interface Group { // // public int getId(); // // public String getName(); // // public List<Group> getParents(); // // public String getPrefix(String server); // // public String getSuffix(String server); // // public HashMap<String, String> getPrefixes(); // // public HashMap<String, String> getSuffixes(); // // public List<Permission> getOwnPermissions(); // // public List<Permission> getPermissions(); // // public String getLadder(); // // public int getRank(); // // public void setParents(List<Integer> parents); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Permission.java // public interface Permission { // // /** // * Returns the ID of this permission as it is stored in the database. // */ // public int getId(); // // /** // * Returns the permission string. // */ // public String getPermissionString(); // // /** // * Returns the name of the world the permission applies to. // */ // public String getWorld(); // // /** // * Returns the name of the server the permission applies to. If empty or "all", applies to all servers. // */ // public String getServer(); // // /** // * Returns the date when this permission expires. If no expiration date, it is null. // */ // public Date getExpirationDate(); // // /* // * Returns true if this is a timed permission. // */ // public boolean willExpire(); // // /* // * Returns true if this is a timed permission and has expired. // */ // public boolean hasExpired(); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/PowerfulPermsPlugin.java // public interface PowerfulPermsPlugin { // // public PermissionManager getPermissionManager(); // // public Logger getLogger(); // // public void runTaskAsynchronously(Runnable runnable); // // public void runTaskLater(Runnable runnable, int delay); // // public boolean isDebug(); // // public ServerMode getServerMode(); // // public boolean isPlayerOnline(UUID uuid); // // public boolean isPlayerOnline(String name); // // public UUID getPlayerUUID(String name); // // public String getPlayerName(UUID uuid); // // public Map<UUID, String> getOnlinePlayers(); // // public void sendPlayerMessage(String name, String message); // // public void debug(String message); // // public int getOldVersion(); // // public String getVersion(); // // public void loadConfig(); // // public boolean isBungeeCord(); // }
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.TreeMap; import com.github.gustav9797.PowerfulPermsAPI.Group; import com.github.gustav9797.PowerfulPermsAPI.Permission; import com.github.gustav9797.PowerfulPermsAPI.PowerfulPermsPlugin;
package com.github.gustav9797.PowerfulPerms.common; public class PowerfulGroup implements Group { private int id; private String name; private List<PowerfulPermission> permissions = new ArrayList<>(); private List<Integer> parents; private String ladder; private int rank;
// Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Group.java // public interface Group { // // public int getId(); // // public String getName(); // // public List<Group> getParents(); // // public String getPrefix(String server); // // public String getSuffix(String server); // // public HashMap<String, String> getPrefixes(); // // public HashMap<String, String> getSuffixes(); // // public List<Permission> getOwnPermissions(); // // public List<Permission> getPermissions(); // // public String getLadder(); // // public int getRank(); // // public void setParents(List<Integer> parents); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Permission.java // public interface Permission { // // /** // * Returns the ID of this permission as it is stored in the database. // */ // public int getId(); // // /** // * Returns the permission string. // */ // public String getPermissionString(); // // /** // * Returns the name of the world the permission applies to. // */ // public String getWorld(); // // /** // * Returns the name of the server the permission applies to. If empty or "all", applies to all servers. // */ // public String getServer(); // // /** // * Returns the date when this permission expires. If no expiration date, it is null. // */ // public Date getExpirationDate(); // // /* // * Returns true if this is a timed permission. // */ // public boolean willExpire(); // // /* // * Returns true if this is a timed permission and has expired. // */ // public boolean hasExpired(); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/PowerfulPermsPlugin.java // public interface PowerfulPermsPlugin { // // public PermissionManager getPermissionManager(); // // public Logger getLogger(); // // public void runTaskAsynchronously(Runnable runnable); // // public void runTaskLater(Runnable runnable, int delay); // // public boolean isDebug(); // // public ServerMode getServerMode(); // // public boolean isPlayerOnline(UUID uuid); // // public boolean isPlayerOnline(String name); // // public UUID getPlayerUUID(String name); // // public String getPlayerName(UUID uuid); // // public Map<UUID, String> getOnlinePlayers(); // // public void sendPlayerMessage(String name, String message); // // public void debug(String message); // // public int getOldVersion(); // // public String getVersion(); // // public void loadConfig(); // // public boolean isBungeeCord(); // } // Path: PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/common/PowerfulGroup.java import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.TreeMap; import com.github.gustav9797.PowerfulPermsAPI.Group; import com.github.gustav9797.PowerfulPermsAPI.Permission; import com.github.gustav9797.PowerfulPermsAPI.PowerfulPermsPlugin; package com.github.gustav9797.PowerfulPerms.common; public class PowerfulGroup implements Group { private int id; private String name; private List<PowerfulPermission> permissions = new ArrayList<>(); private List<Integer> parents; private String ladder; private int rank;
private PowerfulPermsPlugin plugin;
gustav9797/PowerfulPerms
PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/common/PowerfulGroup.java
// Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Group.java // public interface Group { // // public int getId(); // // public String getName(); // // public List<Group> getParents(); // // public String getPrefix(String server); // // public String getSuffix(String server); // // public HashMap<String, String> getPrefixes(); // // public HashMap<String, String> getSuffixes(); // // public List<Permission> getOwnPermissions(); // // public List<Permission> getPermissions(); // // public String getLadder(); // // public int getRank(); // // public void setParents(List<Integer> parents); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Permission.java // public interface Permission { // // /** // * Returns the ID of this permission as it is stored in the database. // */ // public int getId(); // // /** // * Returns the permission string. // */ // public String getPermissionString(); // // /** // * Returns the name of the world the permission applies to. // */ // public String getWorld(); // // /** // * Returns the name of the server the permission applies to. If empty or "all", applies to all servers. // */ // public String getServer(); // // /** // * Returns the date when this permission expires. If no expiration date, it is null. // */ // public Date getExpirationDate(); // // /* // * Returns true if this is a timed permission. // */ // public boolean willExpire(); // // /* // * Returns true if this is a timed permission and has expired. // */ // public boolean hasExpired(); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/PowerfulPermsPlugin.java // public interface PowerfulPermsPlugin { // // public PermissionManager getPermissionManager(); // // public Logger getLogger(); // // public void runTaskAsynchronously(Runnable runnable); // // public void runTaskLater(Runnable runnable, int delay); // // public boolean isDebug(); // // public ServerMode getServerMode(); // // public boolean isPlayerOnline(UUID uuid); // // public boolean isPlayerOnline(String name); // // public UUID getPlayerUUID(String name); // // public String getPlayerName(UUID uuid); // // public Map<UUID, String> getOnlinePlayers(); // // public void sendPlayerMessage(String name, String message); // // public void debug(String message); // // public int getOldVersion(); // // public String getVersion(); // // public void loadConfig(); // // public boolean isBungeeCord(); // }
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.TreeMap; import com.github.gustav9797.PowerfulPermsAPI.Group; import com.github.gustav9797.PowerfulPermsAPI.Permission; import com.github.gustav9797.PowerfulPermsAPI.PowerfulPermsPlugin;
@Override public String getPrefix(String server) { String prefix = serverPrefix.get(server); if (prefix != null) return prefix; prefix = serverPrefix.get(""); return (prefix != null ? prefix : ""); } @Override public String getSuffix(String server) { String suffix = serverSuffix.get(server); if (suffix != null) return suffix; suffix = serverSuffix.get(""); return (suffix != null ? suffix : ""); } @Override public HashMap<String, String> getPrefixes() { return this.serverPrefix; } @Override public HashMap<String, String> getSuffixes() { return this.serverSuffix; } @Override
// Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Group.java // public interface Group { // // public int getId(); // // public String getName(); // // public List<Group> getParents(); // // public String getPrefix(String server); // // public String getSuffix(String server); // // public HashMap<String, String> getPrefixes(); // // public HashMap<String, String> getSuffixes(); // // public List<Permission> getOwnPermissions(); // // public List<Permission> getPermissions(); // // public String getLadder(); // // public int getRank(); // // public void setParents(List<Integer> parents); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Permission.java // public interface Permission { // // /** // * Returns the ID of this permission as it is stored in the database. // */ // public int getId(); // // /** // * Returns the permission string. // */ // public String getPermissionString(); // // /** // * Returns the name of the world the permission applies to. // */ // public String getWorld(); // // /** // * Returns the name of the server the permission applies to. If empty or "all", applies to all servers. // */ // public String getServer(); // // /** // * Returns the date when this permission expires. If no expiration date, it is null. // */ // public Date getExpirationDate(); // // /* // * Returns true if this is a timed permission. // */ // public boolean willExpire(); // // /* // * Returns true if this is a timed permission and has expired. // */ // public boolean hasExpired(); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/PowerfulPermsPlugin.java // public interface PowerfulPermsPlugin { // // public PermissionManager getPermissionManager(); // // public Logger getLogger(); // // public void runTaskAsynchronously(Runnable runnable); // // public void runTaskLater(Runnable runnable, int delay); // // public boolean isDebug(); // // public ServerMode getServerMode(); // // public boolean isPlayerOnline(UUID uuid); // // public boolean isPlayerOnline(String name); // // public UUID getPlayerUUID(String name); // // public String getPlayerName(UUID uuid); // // public Map<UUID, String> getOnlinePlayers(); // // public void sendPlayerMessage(String name, String message); // // public void debug(String message); // // public int getOldVersion(); // // public String getVersion(); // // public void loadConfig(); // // public boolean isBungeeCord(); // } // Path: PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/common/PowerfulGroup.java import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.TreeMap; import com.github.gustav9797.PowerfulPermsAPI.Group; import com.github.gustav9797.PowerfulPermsAPI.Permission; import com.github.gustav9797.PowerfulPermsAPI.PowerfulPermsPlugin; @Override public String getPrefix(String server) { String prefix = serverPrefix.get(server); if (prefix != null) return prefix; prefix = serverPrefix.get(""); return (prefix != null ? prefix : ""); } @Override public String getSuffix(String server) { String suffix = serverSuffix.get(server); if (suffix != null) return suffix; suffix = serverSuffix.get(""); return (suffix != null ? suffix : ""); } @Override public HashMap<String, String> getPrefixes() { return this.serverPrefix; } @Override public HashMap<String, String> getSuffixes() { return this.serverSuffix; } @Override
public ArrayList<Permission> getOwnPermissions() {
gustav9797/PowerfulPerms
PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/common/event/PowerfulEventHandler.java
// Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/PowerfulPermsListener.java // public interface PowerfulPermsListener { // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Event.java // public class Event { // protected String name; // // public String getEventName() { // if (name == null) { // name = getClass().getSimpleName(); // } // return name; // } // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/EventHandler.java // public interface EventHandler { // // public void registerListener(PowerfulPermsListener listener); // // public void unregisterListener(PowerfulPermsListener listener); // // public void fireEvent(Event event); // // }
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import com.github.gustav9797.PowerfulPermsAPI.PowerfulPermsListener; import com.github.gustav9797.PowerfulPermsAPI.Event; import com.github.gustav9797.PowerfulPermsAPI.EventHandler; import com.github.gustav9797.PowerfulPermsAPI.PowerfulEvent;
package com.github.gustav9797.PowerfulPerms.common.event; public class PowerfulEventHandler implements EventHandler { private List<PowerfulPermsListener> listeners; public PowerfulEventHandler() { listeners = new ArrayList<>(); } public void registerListener(PowerfulPermsListener listener) { listeners.add(listener); } public void unregisterListener(PowerfulPermsListener listener) { listeners.remove(listener); }
// Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/PowerfulPermsListener.java // public interface PowerfulPermsListener { // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Event.java // public class Event { // protected String name; // // public String getEventName() { // if (name == null) { // name = getClass().getSimpleName(); // } // return name; // } // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/EventHandler.java // public interface EventHandler { // // public void registerListener(PowerfulPermsListener listener); // // public void unregisterListener(PowerfulPermsListener listener); // // public void fireEvent(Event event); // // } // Path: PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/common/event/PowerfulEventHandler.java import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import com.github.gustav9797.PowerfulPermsAPI.PowerfulPermsListener; import com.github.gustav9797.PowerfulPermsAPI.Event; import com.github.gustav9797.PowerfulPermsAPI.EventHandler; import com.github.gustav9797.PowerfulPermsAPI.PowerfulEvent; package com.github.gustav9797.PowerfulPerms.common.event; public class PowerfulEventHandler implements EventHandler { private List<PowerfulPermsListener> listeners; public PowerfulEventHandler() { listeners = new ArrayList<>(); } public void registerListener(PowerfulPermsListener listener) { listeners.add(listener); } public void unregisterListener(PowerfulPermsListener listener) { listeners.remove(listener); }
public void fireEvent(Event event) {
gustav9797/PowerfulPerms
PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/common/PermissionPlayerBase.java
// Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/CachedGroup.java // public class CachedGroup { // private int id; // private int groupId; // private boolean negated; // private Date expires; // private int expireTaskId = -1; // // public CachedGroup(int id, int groupId, boolean negated, Date expires) { // this.id = id; // this.groupId = groupId; // this.negated = negated; // this.expires = expires; // } // // public int getId() { // return this.id; // } // // public int getGroupId() { // return this.groupId; // } // // public boolean isNegated() { // return this.negated; // } // // public Date getExpirationDate() { // return expires; // } // // public boolean willExpire() { // return expires != null; // } // // public boolean hasExpired() { // return willExpire() && getExpirationDate().before(new Date()); // } // // public int getExpireTaskId() { // return expireTaskId; // } // // public void setExpireTaskId(int taskId) { // this.expireTaskId = taskId; // } // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Group.java // public interface Group { // // public int getId(); // // public String getName(); // // public List<Group> getParents(); // // public String getPrefix(String server); // // public String getSuffix(String server); // // public HashMap<String, String> getPrefixes(); // // public HashMap<String, String> getSuffixes(); // // public List<Permission> getOwnPermissions(); // // public List<Permission> getPermissions(); // // public String getLadder(); // // public int getRank(); // // public void setParents(List<Integer> parents); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Permission.java // public interface Permission { // // /** // * Returns the ID of this permission as it is stored in the database. // */ // public int getId(); // // /** // * Returns the permission string. // */ // public String getPermissionString(); // // /** // * Returns the name of the world the permission applies to. // */ // public String getWorld(); // // /** // * Returns the name of the server the permission applies to. If empty or "all", applies to all servers. // */ // public String getServer(); // // /** // * Returns the date when this permission expires. If no expiration date, it is null. // */ // public Date getExpirationDate(); // // /* // * Returns true if this is a timed permission. // */ // public boolean willExpire(); // // /* // * Returns true if this is a timed permission and has expired. // */ // public boolean hasExpired(); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/PermissionPlayer.java // public interface PermissionPlayer { // // public LinkedHashMap<String, List<CachedGroup>> getCachedGroups(); // // public List<CachedGroup> getCachedGroups(String server); // // public List<Group> getGroups(String server); // // public List<Group> getGroups(); // // public List<Permission> getPermissions(); // // public List<String> getPermissionsInEffect(); // // public List<Permission> getAllPermissions(); // // public Boolean hasPermission(String permission); // // public boolean isPermissionSet(String permission); // // public Group getGroup(String ladder); // // public Group getPrimaryGroup(); // // public String getPrefix(String ladder); // // public String getSuffix(String ladder); // // public String getPrefix(); // // public String getSuffix(); // // public String getOwnPrefix(); // // public String getOwnSuffix(); // // public boolean isDefault(); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/PowerfulPermsPlugin.java // public interface PowerfulPermsPlugin { // // public PermissionManager getPermissionManager(); // // public Logger getLogger(); // // public void runTaskAsynchronously(Runnable runnable); // // public void runTaskLater(Runnable runnable, int delay); // // public boolean isDebug(); // // public ServerMode getServerMode(); // // public boolean isPlayerOnline(UUID uuid); // // public boolean isPlayerOnline(String name); // // public UUID getPlayerUUID(String name); // // public String getPlayerName(UUID uuid); // // public Map<UUID, String> getOnlinePlayers(); // // public void sendPlayerMessage(String name, String message); // // public void debug(String message); // // public int getOldVersion(); // // public String getVersion(); // // public void loadConfig(); // // public boolean isBungeeCord(); // }
import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import java.util.TreeMap; import java.util.concurrent.locks.ReentrantLock; import com.github.gustav9797.PowerfulPermsAPI.CachedGroup; import com.github.gustav9797.PowerfulPermsAPI.Group; import com.github.gustav9797.PowerfulPermsAPI.Permission; import com.github.gustav9797.PowerfulPermsAPI.PermissionPlayer; import com.github.gustav9797.PowerfulPermsAPI.PowerfulPermsPlugin;
package com.github.gustav9797.PowerfulPerms.common; public class PermissionPlayerBase extends PermissionContainer implements PermissionPlayer { protected LinkedHashMap<String, List<CachedGroup>> groups = new LinkedHashMap<>(); // Contains -all- groups for this player.
// Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/CachedGroup.java // public class CachedGroup { // private int id; // private int groupId; // private boolean negated; // private Date expires; // private int expireTaskId = -1; // // public CachedGroup(int id, int groupId, boolean negated, Date expires) { // this.id = id; // this.groupId = groupId; // this.negated = negated; // this.expires = expires; // } // // public int getId() { // return this.id; // } // // public int getGroupId() { // return this.groupId; // } // // public boolean isNegated() { // return this.negated; // } // // public Date getExpirationDate() { // return expires; // } // // public boolean willExpire() { // return expires != null; // } // // public boolean hasExpired() { // return willExpire() && getExpirationDate().before(new Date()); // } // // public int getExpireTaskId() { // return expireTaskId; // } // // public void setExpireTaskId(int taskId) { // this.expireTaskId = taskId; // } // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Group.java // public interface Group { // // public int getId(); // // public String getName(); // // public List<Group> getParents(); // // public String getPrefix(String server); // // public String getSuffix(String server); // // public HashMap<String, String> getPrefixes(); // // public HashMap<String, String> getSuffixes(); // // public List<Permission> getOwnPermissions(); // // public List<Permission> getPermissions(); // // public String getLadder(); // // public int getRank(); // // public void setParents(List<Integer> parents); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Permission.java // public interface Permission { // // /** // * Returns the ID of this permission as it is stored in the database. // */ // public int getId(); // // /** // * Returns the permission string. // */ // public String getPermissionString(); // // /** // * Returns the name of the world the permission applies to. // */ // public String getWorld(); // // /** // * Returns the name of the server the permission applies to. If empty or "all", applies to all servers. // */ // public String getServer(); // // /** // * Returns the date when this permission expires. If no expiration date, it is null. // */ // public Date getExpirationDate(); // // /* // * Returns true if this is a timed permission. // */ // public boolean willExpire(); // // /* // * Returns true if this is a timed permission and has expired. // */ // public boolean hasExpired(); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/PermissionPlayer.java // public interface PermissionPlayer { // // public LinkedHashMap<String, List<CachedGroup>> getCachedGroups(); // // public List<CachedGroup> getCachedGroups(String server); // // public List<Group> getGroups(String server); // // public List<Group> getGroups(); // // public List<Permission> getPermissions(); // // public List<String> getPermissionsInEffect(); // // public List<Permission> getAllPermissions(); // // public Boolean hasPermission(String permission); // // public boolean isPermissionSet(String permission); // // public Group getGroup(String ladder); // // public Group getPrimaryGroup(); // // public String getPrefix(String ladder); // // public String getSuffix(String ladder); // // public String getPrefix(); // // public String getSuffix(); // // public String getOwnPrefix(); // // public String getOwnSuffix(); // // public boolean isDefault(); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/PowerfulPermsPlugin.java // public interface PowerfulPermsPlugin { // // public PermissionManager getPermissionManager(); // // public Logger getLogger(); // // public void runTaskAsynchronously(Runnable runnable); // // public void runTaskLater(Runnable runnable, int delay); // // public boolean isDebug(); // // public ServerMode getServerMode(); // // public boolean isPlayerOnline(UUID uuid); // // public boolean isPlayerOnline(String name); // // public UUID getPlayerUUID(String name); // // public String getPlayerName(UUID uuid); // // public Map<UUID, String> getOnlinePlayers(); // // public void sendPlayerMessage(String name, String message); // // public void debug(String message); // // public int getOldVersion(); // // public String getVersion(); // // public void loadConfig(); // // public boolean isBungeeCord(); // } // Path: PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/common/PermissionPlayerBase.java import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import java.util.TreeMap; import java.util.concurrent.locks.ReentrantLock; import com.github.gustav9797.PowerfulPermsAPI.CachedGroup; import com.github.gustav9797.PowerfulPermsAPI.Group; import com.github.gustav9797.PowerfulPermsAPI.Permission; import com.github.gustav9797.PowerfulPermsAPI.PermissionPlayer; import com.github.gustav9797.PowerfulPermsAPI.PowerfulPermsPlugin; package com.github.gustav9797.PowerfulPerms.common; public class PermissionPlayerBase extends PermissionContainer implements PermissionPlayer { protected LinkedHashMap<String, List<CachedGroup>> groups = new LinkedHashMap<>(); // Contains -all- groups for this player.
protected List<Group> currentGroups = new ArrayList<>();
gustav9797/PowerfulPerms
PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/common/PermissionPlayerBase.java
// Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/CachedGroup.java // public class CachedGroup { // private int id; // private int groupId; // private boolean negated; // private Date expires; // private int expireTaskId = -1; // // public CachedGroup(int id, int groupId, boolean negated, Date expires) { // this.id = id; // this.groupId = groupId; // this.negated = negated; // this.expires = expires; // } // // public int getId() { // return this.id; // } // // public int getGroupId() { // return this.groupId; // } // // public boolean isNegated() { // return this.negated; // } // // public Date getExpirationDate() { // return expires; // } // // public boolean willExpire() { // return expires != null; // } // // public boolean hasExpired() { // return willExpire() && getExpirationDate().before(new Date()); // } // // public int getExpireTaskId() { // return expireTaskId; // } // // public void setExpireTaskId(int taskId) { // this.expireTaskId = taskId; // } // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Group.java // public interface Group { // // public int getId(); // // public String getName(); // // public List<Group> getParents(); // // public String getPrefix(String server); // // public String getSuffix(String server); // // public HashMap<String, String> getPrefixes(); // // public HashMap<String, String> getSuffixes(); // // public List<Permission> getOwnPermissions(); // // public List<Permission> getPermissions(); // // public String getLadder(); // // public int getRank(); // // public void setParents(List<Integer> parents); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Permission.java // public interface Permission { // // /** // * Returns the ID of this permission as it is stored in the database. // */ // public int getId(); // // /** // * Returns the permission string. // */ // public String getPermissionString(); // // /** // * Returns the name of the world the permission applies to. // */ // public String getWorld(); // // /** // * Returns the name of the server the permission applies to. If empty or "all", applies to all servers. // */ // public String getServer(); // // /** // * Returns the date when this permission expires. If no expiration date, it is null. // */ // public Date getExpirationDate(); // // /* // * Returns true if this is a timed permission. // */ // public boolean willExpire(); // // /* // * Returns true if this is a timed permission and has expired. // */ // public boolean hasExpired(); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/PermissionPlayer.java // public interface PermissionPlayer { // // public LinkedHashMap<String, List<CachedGroup>> getCachedGroups(); // // public List<CachedGroup> getCachedGroups(String server); // // public List<Group> getGroups(String server); // // public List<Group> getGroups(); // // public List<Permission> getPermissions(); // // public List<String> getPermissionsInEffect(); // // public List<Permission> getAllPermissions(); // // public Boolean hasPermission(String permission); // // public boolean isPermissionSet(String permission); // // public Group getGroup(String ladder); // // public Group getPrimaryGroup(); // // public String getPrefix(String ladder); // // public String getSuffix(String ladder); // // public String getPrefix(); // // public String getSuffix(); // // public String getOwnPrefix(); // // public String getOwnSuffix(); // // public boolean isDefault(); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/PowerfulPermsPlugin.java // public interface PowerfulPermsPlugin { // // public PermissionManager getPermissionManager(); // // public Logger getLogger(); // // public void runTaskAsynchronously(Runnable runnable); // // public void runTaskLater(Runnable runnable, int delay); // // public boolean isDebug(); // // public ServerMode getServerMode(); // // public boolean isPlayerOnline(UUID uuid); // // public boolean isPlayerOnline(String name); // // public UUID getPlayerUUID(String name); // // public String getPlayerName(UUID uuid); // // public Map<UUID, String> getOnlinePlayers(); // // public void sendPlayerMessage(String name, String message); // // public void debug(String message); // // public int getOldVersion(); // // public String getVersion(); // // public void loadConfig(); // // public boolean isBungeeCord(); // }
import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import java.util.TreeMap; import java.util.concurrent.locks.ReentrantLock; import com.github.gustav9797.PowerfulPermsAPI.CachedGroup; import com.github.gustav9797.PowerfulPermsAPI.Group; import com.github.gustav9797.PowerfulPermsAPI.Permission; import com.github.gustav9797.PowerfulPermsAPI.PermissionPlayer; import com.github.gustav9797.PowerfulPermsAPI.PowerfulPermsPlugin;
package com.github.gustav9797.PowerfulPerms.common; public class PermissionPlayerBase extends PermissionContainer implements PermissionPlayer { protected LinkedHashMap<String, List<CachedGroup>> groups = new LinkedHashMap<>(); // Contains -all- groups for this player. protected List<Group> currentGroups = new ArrayList<>(); protected String prefix = ""; protected String suffix = "";
// Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/CachedGroup.java // public class CachedGroup { // private int id; // private int groupId; // private boolean negated; // private Date expires; // private int expireTaskId = -1; // // public CachedGroup(int id, int groupId, boolean negated, Date expires) { // this.id = id; // this.groupId = groupId; // this.negated = negated; // this.expires = expires; // } // // public int getId() { // return this.id; // } // // public int getGroupId() { // return this.groupId; // } // // public boolean isNegated() { // return this.negated; // } // // public Date getExpirationDate() { // return expires; // } // // public boolean willExpire() { // return expires != null; // } // // public boolean hasExpired() { // return willExpire() && getExpirationDate().before(new Date()); // } // // public int getExpireTaskId() { // return expireTaskId; // } // // public void setExpireTaskId(int taskId) { // this.expireTaskId = taskId; // } // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Group.java // public interface Group { // // public int getId(); // // public String getName(); // // public List<Group> getParents(); // // public String getPrefix(String server); // // public String getSuffix(String server); // // public HashMap<String, String> getPrefixes(); // // public HashMap<String, String> getSuffixes(); // // public List<Permission> getOwnPermissions(); // // public List<Permission> getPermissions(); // // public String getLadder(); // // public int getRank(); // // public void setParents(List<Integer> parents); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Permission.java // public interface Permission { // // /** // * Returns the ID of this permission as it is stored in the database. // */ // public int getId(); // // /** // * Returns the permission string. // */ // public String getPermissionString(); // // /** // * Returns the name of the world the permission applies to. // */ // public String getWorld(); // // /** // * Returns the name of the server the permission applies to. If empty or "all", applies to all servers. // */ // public String getServer(); // // /** // * Returns the date when this permission expires. If no expiration date, it is null. // */ // public Date getExpirationDate(); // // /* // * Returns true if this is a timed permission. // */ // public boolean willExpire(); // // /* // * Returns true if this is a timed permission and has expired. // */ // public boolean hasExpired(); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/PermissionPlayer.java // public interface PermissionPlayer { // // public LinkedHashMap<String, List<CachedGroup>> getCachedGroups(); // // public List<CachedGroup> getCachedGroups(String server); // // public List<Group> getGroups(String server); // // public List<Group> getGroups(); // // public List<Permission> getPermissions(); // // public List<String> getPermissionsInEffect(); // // public List<Permission> getAllPermissions(); // // public Boolean hasPermission(String permission); // // public boolean isPermissionSet(String permission); // // public Group getGroup(String ladder); // // public Group getPrimaryGroup(); // // public String getPrefix(String ladder); // // public String getSuffix(String ladder); // // public String getPrefix(); // // public String getSuffix(); // // public String getOwnPrefix(); // // public String getOwnSuffix(); // // public boolean isDefault(); // // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/PowerfulPermsPlugin.java // public interface PowerfulPermsPlugin { // // public PermissionManager getPermissionManager(); // // public Logger getLogger(); // // public void runTaskAsynchronously(Runnable runnable); // // public void runTaskLater(Runnable runnable, int delay); // // public boolean isDebug(); // // public ServerMode getServerMode(); // // public boolean isPlayerOnline(UUID uuid); // // public boolean isPlayerOnline(String name); // // public UUID getPlayerUUID(String name); // // public String getPlayerName(UUID uuid); // // public Map<UUID, String> getOnlinePlayers(); // // public void sendPlayerMessage(String name, String message); // // public void debug(String message); // // public int getOldVersion(); // // public String getVersion(); // // public void loadConfig(); // // public boolean isBungeeCord(); // } // Path: PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/common/PermissionPlayerBase.java import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import java.util.TreeMap; import java.util.concurrent.locks.ReentrantLock; import com.github.gustav9797.PowerfulPermsAPI.CachedGroup; import com.github.gustav9797.PowerfulPermsAPI.Group; import com.github.gustav9797.PowerfulPermsAPI.Permission; import com.github.gustav9797.PowerfulPermsAPI.PermissionPlayer; import com.github.gustav9797.PowerfulPermsAPI.PowerfulPermsPlugin; package com.github.gustav9797.PowerfulPerms.common; public class PermissionPlayerBase extends PermissionContainer implements PermissionPlayer { protected LinkedHashMap<String, List<CachedGroup>> groups = new LinkedHashMap<>(); // Contains -all- groups for this player. protected List<Group> currentGroups = new ArrayList<>(); protected String prefix = ""; protected String suffix = "";
protected static PowerfulPermsPlugin plugin;
gustav9797/PowerfulPerms
PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/common/CachedPlayer.java
// Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/CachedGroup.java // public class CachedGroup { // private int id; // private int groupId; // private boolean negated; // private Date expires; // private int expireTaskId = -1; // // public CachedGroup(int id, int groupId, boolean negated, Date expires) { // this.id = id; // this.groupId = groupId; // this.negated = negated; // this.expires = expires; // } // // public int getId() { // return this.id; // } // // public int getGroupId() { // return this.groupId; // } // // public boolean isNegated() { // return this.negated; // } // // public Date getExpirationDate() { // return expires; // } // // public boolean willExpire() { // return expires != null; // } // // public boolean hasExpired() { // return willExpire() && getExpirationDate().before(new Date()); // } // // public int getExpireTaskId() { // return expireTaskId; // } // // public void setExpireTaskId(int taskId) { // this.expireTaskId = taskId; // } // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Permission.java // public interface Permission { // // /** // * Returns the ID of this permission as it is stored in the database. // */ // public int getId(); // // /** // * Returns the permission string. // */ // public String getPermissionString(); // // /** // * Returns the name of the world the permission applies to. // */ // public String getWorld(); // // /** // * Returns the name of the server the permission applies to. If empty or "all", applies to all servers. // */ // public String getServer(); // // /** // * Returns the date when this permission expires. If no expiration date, it is null. // */ // public Date getExpirationDate(); // // /* // * Returns true if this is a timed permission. // */ // public boolean willExpire(); // // /* // * Returns true if this is a timed permission and has expired. // */ // public boolean hasExpired(); // // }
import java.util.LinkedHashMap; import java.util.List; import com.github.gustav9797.PowerfulPermsAPI.CachedGroup; import com.github.gustav9797.PowerfulPermsAPI.Permission;
package com.github.gustav9797.PowerfulPerms.common; public class CachedPlayer { private LinkedHashMap<String, List<CachedGroup>> groups; private String prefix; private String suffix;
// Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/CachedGroup.java // public class CachedGroup { // private int id; // private int groupId; // private boolean negated; // private Date expires; // private int expireTaskId = -1; // // public CachedGroup(int id, int groupId, boolean negated, Date expires) { // this.id = id; // this.groupId = groupId; // this.negated = negated; // this.expires = expires; // } // // public int getId() { // return this.id; // } // // public int getGroupId() { // return this.groupId; // } // // public boolean isNegated() { // return this.negated; // } // // public Date getExpirationDate() { // return expires; // } // // public boolean willExpire() { // return expires != null; // } // // public boolean hasExpired() { // return willExpire() && getExpirationDate().before(new Date()); // } // // public int getExpireTaskId() { // return expireTaskId; // } // // public void setExpireTaskId(int taskId) { // this.expireTaskId = taskId; // } // } // // Path: PowerfulPermsAPI/src/main/java/com/github/gustav9797/PowerfulPermsAPI/Permission.java // public interface Permission { // // /** // * Returns the ID of this permission as it is stored in the database. // */ // public int getId(); // // /** // * Returns the permission string. // */ // public String getPermissionString(); // // /** // * Returns the name of the world the permission applies to. // */ // public String getWorld(); // // /** // * Returns the name of the server the permission applies to. If empty or "all", applies to all servers. // */ // public String getServer(); // // /** // * Returns the date when this permission expires. If no expiration date, it is null. // */ // public Date getExpirationDate(); // // /* // * Returns true if this is a timed permission. // */ // public boolean willExpire(); // // /* // * Returns true if this is a timed permission and has expired. // */ // public boolean hasExpired(); // // } // Path: PowerfulPerms/src/main/java/com/github/gustav9797/PowerfulPerms/common/CachedPlayer.java import java.util.LinkedHashMap; import java.util.List; import com.github.gustav9797.PowerfulPermsAPI.CachedGroup; import com.github.gustav9797.PowerfulPermsAPI.Permission; package com.github.gustav9797.PowerfulPerms.common; public class CachedPlayer { private LinkedHashMap<String, List<CachedGroup>> groups; private String prefix; private String suffix;
private List<Permission> perms;
xwz/iview-android-tv
iview/src/main/java/io/github/xwz/iview/activities/BootActivity.java
// Path: iview/src/main/java/io/github/xwz/iview/content/RecommendationsService.java // public class RecommendationsService extends IntentService { // private static final String TAG = "UpdateRecommendations"; // // private static final String RECOMMENDATION_TAG = "io.github.xwz.iview.RECOMMENDATION_TAG"; // private static final String BACKGROUND_URI_PREFIX = "content://io.github.xwz.iview.recommendation/"; // // public RecommendationsService() { // super("RecommendationService"); // } // // @Override // protected void onHandleIntent(Intent intent) { // Log.d(TAG, "Updating recommendation cards"); // EpisodeModel episode = (EpisodeModel) intent.getSerializableExtra(ContentManager.CONTENT_ID); // int id = intent.getIntExtra(ContentManager.CONTENT_TAG, 0); // if (episode != null) { // try { // Log.d(TAG, "Will recommend: " + episode); // buildNotification(episode, id); // } catch (IOException e) { // Log.e(TAG, "Error:" + e.getMessage()); // } // } // } // // private void buildNotification(EpisodeModel ep, final int id) throws IOException { // Point size = new Point(getResources().getDimensionPixelSize(R.dimen.card_width), // getResources().getDimensionPixelSize(R.dimen.card_height)); // Bitmap image = Picasso.with(this).load(ep.getThumbnail()).resize(size.x, size.y).get(); // Bitmap background = Picasso.with(this).load(ep.getThumbnail()).get(); // // final RecommendationBuilder builder = new RecommendationBuilder(this, id); // builder.setBackgroundPrefix(BACKGROUND_URI_PREFIX); // final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Notification notification = builder // .setBackgroundPrefix(BACKGROUND_URI_PREFIX) // .setIcon(R.mipmap.icon) // .setColor(getResources().getColor(R.color.brand_color)) // .setTitle(ep.getSeriesTitle()) // .setDescription(ep.getTitle()) // .setImage(image) // .setBackground(background) // .setPendingIntent(buildPendingIntent(ep)) // .build(); // manager.notify(RECOMMENDATION_TAG, id, notification); // Log.d(TAG, "Recommending: " + ep); // } // // private PendingIntent buildPendingIntent(EpisodeModel ep) { // Intent intent = new Intent(this, DetailsActivity.class); // intent.putExtra(ContentManager.CONTENT_ID, ep); // // TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // stackBuilder.addParentStack(DetailsActivity.class); // stackBuilder.addNextIntent(intent); // intent.setAction(ep.getHref()); // // return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); // } // }
import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import io.github.xwz.iview.content.RecommendationsService;
package io.github.xwz.iview.activities; public class BootActivity extends BroadcastReceiver { private static final String TAG = "BootActivity"; private static final long INITIAL_DELAY = 5000; @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "BootActivity initiated"); if (intent.getAction().endsWith(Intent.ACTION_BOOT_COMPLETED)) { scheduleRecommendationUpdate(context); } } private void scheduleRecommendationUpdate(Context context) { Log.d(TAG, "Scheduling recommendations update"); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// Path: iview/src/main/java/io/github/xwz/iview/content/RecommendationsService.java // public class RecommendationsService extends IntentService { // private static final String TAG = "UpdateRecommendations"; // // private static final String RECOMMENDATION_TAG = "io.github.xwz.iview.RECOMMENDATION_TAG"; // private static final String BACKGROUND_URI_PREFIX = "content://io.github.xwz.iview.recommendation/"; // // public RecommendationsService() { // super("RecommendationService"); // } // // @Override // protected void onHandleIntent(Intent intent) { // Log.d(TAG, "Updating recommendation cards"); // EpisodeModel episode = (EpisodeModel) intent.getSerializableExtra(ContentManager.CONTENT_ID); // int id = intent.getIntExtra(ContentManager.CONTENT_TAG, 0); // if (episode != null) { // try { // Log.d(TAG, "Will recommend: " + episode); // buildNotification(episode, id); // } catch (IOException e) { // Log.e(TAG, "Error:" + e.getMessage()); // } // } // } // // private void buildNotification(EpisodeModel ep, final int id) throws IOException { // Point size = new Point(getResources().getDimensionPixelSize(R.dimen.card_width), // getResources().getDimensionPixelSize(R.dimen.card_height)); // Bitmap image = Picasso.with(this).load(ep.getThumbnail()).resize(size.x, size.y).get(); // Bitmap background = Picasso.with(this).load(ep.getThumbnail()).get(); // // final RecommendationBuilder builder = new RecommendationBuilder(this, id); // builder.setBackgroundPrefix(BACKGROUND_URI_PREFIX); // final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Notification notification = builder // .setBackgroundPrefix(BACKGROUND_URI_PREFIX) // .setIcon(R.mipmap.icon) // .setColor(getResources().getColor(R.color.brand_color)) // .setTitle(ep.getSeriesTitle()) // .setDescription(ep.getTitle()) // .setImage(image) // .setBackground(background) // .setPendingIntent(buildPendingIntent(ep)) // .build(); // manager.notify(RECOMMENDATION_TAG, id, notification); // Log.d(TAG, "Recommending: " + ep); // } // // private PendingIntent buildPendingIntent(EpisodeModel ep) { // Intent intent = new Intent(this, DetailsActivity.class); // intent.putExtra(ContentManager.CONTENT_ID, ep); // // TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // stackBuilder.addParentStack(DetailsActivity.class); // stackBuilder.addNextIntent(intent); // intent.setAction(ep.getHref()); // // return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); // } // } // Path: iview/src/main/java/io/github/xwz/iview/activities/BootActivity.java import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import io.github.xwz.iview.content.RecommendationsService; package io.github.xwz.iview.activities; public class BootActivity extends BroadcastReceiver { private static final String TAG = "BootActivity"; private static final long INITIAL_DELAY = 5000; @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "BootActivity initiated"); if (intent.getAction().endsWith(Intent.ACTION_BOOT_COMPLETED)) { scheduleRecommendationUpdate(context); } } private void scheduleRecommendationUpdate(Context context) { Log.d(TAG, "Scheduling recommendations update"); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent recommendationIntent = new Intent(context, RecommendationsService.class);
xwz/iview-android-tv
base/src/main/java/io/github/xwz/base/adapters/FilmPresenter.java
// Path: base/src/main/java/io/github/xwz/base/IApplication.java // public interface IApplication { // int getImageCardViewContentTextResId(); // int getImageCardViewInfoFieldResId(); // int getImageCardViewTitleTextResId(); // } // // Path: base/src/main/java/io/github/xwz/base/views/EpisodeCardView.java // public class EpisodeCardView extends Presenter.ViewHolder { // private static final String TAG = "EpisodeCardView"; // // private final ImageCardView card; // private final Context mContext; // private final Point size; // private boolean canShowCover; // private ProgressBar progress; // // public EpisodeCardView(Context context, ImageCardView view, Point s, boolean showCover) { // super(view); // mContext = context; // card = view; // size = s; // canShowCover = showCover; // addProgressBar(context, view); // } // // private void addProgressBar(Context context, View card) { // if (context.getApplicationContext() instanceof IApplication) { // IApplication app = (IApplication) context.getApplicationContext(); // View info = card.findViewById(app.getImageCardViewInfoFieldResId()); // if (info instanceof RelativeLayout) { // RelativeLayout frame = (RelativeLayout) info; // frame.setClipToPadding(false); // LayoutInflater inflater = LayoutInflater.from(context); // View v = inflater.inflate(R.layout.progress, frame); // if (v != null) { // progress = (ProgressBar) v.findViewById(R.id.progress); // } // } // } // } // // public void setEpisode(EpisodeBaseModel ep) { // String series = ep.getSeriesTitle(); // String title = ep.getTitle(); // if (series == null || series.length() == 0) { // series = title; // } // card.setTitleText(series); // card.setContentText(title); // if (sameTitles(series, title)) { // card.setContentText(""); // } // if (progress != null) { // if (ep.isRecent()) { // progress.setVisibility(View.VISIBLE); // progress.setProgress(ep.getProgress()); // } else { // progress.setVisibility(View.GONE); // } // card.requestLayout(); // } // // if (ep.getEpisodeCount() > 0) { // TextDrawable badge = new TextDrawable(mContext); // badge.setText("" + ep.getEpisodeCount()); // card.setBadgeImage(badge); // } else { // card.setBadgeImage(null); // } // String image = ep.getThumbnail(); // if (canShowCover && ep.hasCover()) { // image = ep.getCover(); // } // Picasso.with(mContext) // .load(image) // .resize(size.x, size.y) // .into(card.getMainImageView()); // } // // private boolean sameTitles(String a, String b) { // if (a != null && b != null) { // return a.toLowerCase().equals(b.toLowerCase()); // } // return false; // } // // public ImageCardView getImageCardView() { // return card; // } // }
import android.content.Context; import android.graphics.Point; import android.support.v17.leanback.widget.BaseCardView; import android.support.v17.leanback.widget.ImageCardView; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import io.github.xwz.base.IApplication; import io.github.xwz.base.R; import io.github.xwz.base.views.EpisodeCardView;
package io.github.xwz.base.adapters; public class FilmPresenter extends EpisodePresenter { private boolean large = false; public FilmPresenter() { } public FilmPresenter(boolean details) { large = details; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent) { Context context = parent.getContext();
// Path: base/src/main/java/io/github/xwz/base/IApplication.java // public interface IApplication { // int getImageCardViewContentTextResId(); // int getImageCardViewInfoFieldResId(); // int getImageCardViewTitleTextResId(); // } // // Path: base/src/main/java/io/github/xwz/base/views/EpisodeCardView.java // public class EpisodeCardView extends Presenter.ViewHolder { // private static final String TAG = "EpisodeCardView"; // // private final ImageCardView card; // private final Context mContext; // private final Point size; // private boolean canShowCover; // private ProgressBar progress; // // public EpisodeCardView(Context context, ImageCardView view, Point s, boolean showCover) { // super(view); // mContext = context; // card = view; // size = s; // canShowCover = showCover; // addProgressBar(context, view); // } // // private void addProgressBar(Context context, View card) { // if (context.getApplicationContext() instanceof IApplication) { // IApplication app = (IApplication) context.getApplicationContext(); // View info = card.findViewById(app.getImageCardViewInfoFieldResId()); // if (info instanceof RelativeLayout) { // RelativeLayout frame = (RelativeLayout) info; // frame.setClipToPadding(false); // LayoutInflater inflater = LayoutInflater.from(context); // View v = inflater.inflate(R.layout.progress, frame); // if (v != null) { // progress = (ProgressBar) v.findViewById(R.id.progress); // } // } // } // } // // public void setEpisode(EpisodeBaseModel ep) { // String series = ep.getSeriesTitle(); // String title = ep.getTitle(); // if (series == null || series.length() == 0) { // series = title; // } // card.setTitleText(series); // card.setContentText(title); // if (sameTitles(series, title)) { // card.setContentText(""); // } // if (progress != null) { // if (ep.isRecent()) { // progress.setVisibility(View.VISIBLE); // progress.setProgress(ep.getProgress()); // } else { // progress.setVisibility(View.GONE); // } // card.requestLayout(); // } // // if (ep.getEpisodeCount() > 0) { // TextDrawable badge = new TextDrawable(mContext); // badge.setText("" + ep.getEpisodeCount()); // card.setBadgeImage(badge); // } else { // card.setBadgeImage(null); // } // String image = ep.getThumbnail(); // if (canShowCover && ep.hasCover()) { // image = ep.getCover(); // } // Picasso.with(mContext) // .load(image) // .resize(size.x, size.y) // .into(card.getMainImageView()); // } // // private boolean sameTitles(String a, String b) { // if (a != null && b != null) { // return a.toLowerCase().equals(b.toLowerCase()); // } // return false; // } // // public ImageCardView getImageCardView() { // return card; // } // } // Path: base/src/main/java/io/github/xwz/base/adapters/FilmPresenter.java import android.content.Context; import android.graphics.Point; import android.support.v17.leanback.widget.BaseCardView; import android.support.v17.leanback.widget.ImageCardView; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import io.github.xwz.base.IApplication; import io.github.xwz.base.R; import io.github.xwz.base.views.EpisodeCardView; package io.github.xwz.base.adapters; public class FilmPresenter extends EpisodePresenter { private boolean large = false; public FilmPresenter() { } public FilmPresenter(boolean details) { large = details; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent) { Context context = parent.getContext();
return new EpisodeCardView(context, getCardView(context), getCardSize(context), true);
xwz/iview-android-tv
base/src/main/java/io/github/xwz/base/adapters/FilmPresenter.java
// Path: base/src/main/java/io/github/xwz/base/IApplication.java // public interface IApplication { // int getImageCardViewContentTextResId(); // int getImageCardViewInfoFieldResId(); // int getImageCardViewTitleTextResId(); // } // // Path: base/src/main/java/io/github/xwz/base/views/EpisodeCardView.java // public class EpisodeCardView extends Presenter.ViewHolder { // private static final String TAG = "EpisodeCardView"; // // private final ImageCardView card; // private final Context mContext; // private final Point size; // private boolean canShowCover; // private ProgressBar progress; // // public EpisodeCardView(Context context, ImageCardView view, Point s, boolean showCover) { // super(view); // mContext = context; // card = view; // size = s; // canShowCover = showCover; // addProgressBar(context, view); // } // // private void addProgressBar(Context context, View card) { // if (context.getApplicationContext() instanceof IApplication) { // IApplication app = (IApplication) context.getApplicationContext(); // View info = card.findViewById(app.getImageCardViewInfoFieldResId()); // if (info instanceof RelativeLayout) { // RelativeLayout frame = (RelativeLayout) info; // frame.setClipToPadding(false); // LayoutInflater inflater = LayoutInflater.from(context); // View v = inflater.inflate(R.layout.progress, frame); // if (v != null) { // progress = (ProgressBar) v.findViewById(R.id.progress); // } // } // } // } // // public void setEpisode(EpisodeBaseModel ep) { // String series = ep.getSeriesTitle(); // String title = ep.getTitle(); // if (series == null || series.length() == 0) { // series = title; // } // card.setTitleText(series); // card.setContentText(title); // if (sameTitles(series, title)) { // card.setContentText(""); // } // if (progress != null) { // if (ep.isRecent()) { // progress.setVisibility(View.VISIBLE); // progress.setProgress(ep.getProgress()); // } else { // progress.setVisibility(View.GONE); // } // card.requestLayout(); // } // // if (ep.getEpisodeCount() > 0) { // TextDrawable badge = new TextDrawable(mContext); // badge.setText("" + ep.getEpisodeCount()); // card.setBadgeImage(badge); // } else { // card.setBadgeImage(null); // } // String image = ep.getThumbnail(); // if (canShowCover && ep.hasCover()) { // image = ep.getCover(); // } // Picasso.with(mContext) // .load(image) // .resize(size.x, size.y) // .into(card.getMainImageView()); // } // // private boolean sameTitles(String a, String b) { // if (a != null && b != null) { // return a.toLowerCase().equals(b.toLowerCase()); // } // return false; // } // // public ImageCardView getImageCardView() { // return card; // } // }
import android.content.Context; import android.graphics.Point; import android.support.v17.leanback.widget.BaseCardView; import android.support.v17.leanback.widget.ImageCardView; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import io.github.xwz.base.IApplication; import io.github.xwz.base.R; import io.github.xwz.base.views.EpisodeCardView;
package io.github.xwz.base.adapters; public class FilmPresenter extends EpisodePresenter { private boolean large = false; public FilmPresenter() { } public FilmPresenter(boolean details) { large = details; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent) { Context context = parent.getContext(); return new EpisodeCardView(context, getCardView(context), getCardSize(context), true); } @Override protected Point getCardSize(Context context) { if (large) { return new Point(context.getResources().getDimensionPixelSize(R.dimen.poster_width_large), context.getResources().getDimensionPixelSize(R.dimen.poster_height_large)); } else { return new Point(context.getResources().getDimensionPixelSize(R.dimen.poster_width), context.getResources().getDimensionPixelSize(R.dimen.poster_height)); } } @Override protected ImageCardView getCardView(Context context) { ImageCardView card = super.getCardView(context); // nasty hack to hide content text view
// Path: base/src/main/java/io/github/xwz/base/IApplication.java // public interface IApplication { // int getImageCardViewContentTextResId(); // int getImageCardViewInfoFieldResId(); // int getImageCardViewTitleTextResId(); // } // // Path: base/src/main/java/io/github/xwz/base/views/EpisodeCardView.java // public class EpisodeCardView extends Presenter.ViewHolder { // private static final String TAG = "EpisodeCardView"; // // private final ImageCardView card; // private final Context mContext; // private final Point size; // private boolean canShowCover; // private ProgressBar progress; // // public EpisodeCardView(Context context, ImageCardView view, Point s, boolean showCover) { // super(view); // mContext = context; // card = view; // size = s; // canShowCover = showCover; // addProgressBar(context, view); // } // // private void addProgressBar(Context context, View card) { // if (context.getApplicationContext() instanceof IApplication) { // IApplication app = (IApplication) context.getApplicationContext(); // View info = card.findViewById(app.getImageCardViewInfoFieldResId()); // if (info instanceof RelativeLayout) { // RelativeLayout frame = (RelativeLayout) info; // frame.setClipToPadding(false); // LayoutInflater inflater = LayoutInflater.from(context); // View v = inflater.inflate(R.layout.progress, frame); // if (v != null) { // progress = (ProgressBar) v.findViewById(R.id.progress); // } // } // } // } // // public void setEpisode(EpisodeBaseModel ep) { // String series = ep.getSeriesTitle(); // String title = ep.getTitle(); // if (series == null || series.length() == 0) { // series = title; // } // card.setTitleText(series); // card.setContentText(title); // if (sameTitles(series, title)) { // card.setContentText(""); // } // if (progress != null) { // if (ep.isRecent()) { // progress.setVisibility(View.VISIBLE); // progress.setProgress(ep.getProgress()); // } else { // progress.setVisibility(View.GONE); // } // card.requestLayout(); // } // // if (ep.getEpisodeCount() > 0) { // TextDrawable badge = new TextDrawable(mContext); // badge.setText("" + ep.getEpisodeCount()); // card.setBadgeImage(badge); // } else { // card.setBadgeImage(null); // } // String image = ep.getThumbnail(); // if (canShowCover && ep.hasCover()) { // image = ep.getCover(); // } // Picasso.with(mContext) // .load(image) // .resize(size.x, size.y) // .into(card.getMainImageView()); // } // // private boolean sameTitles(String a, String b) { // if (a != null && b != null) { // return a.toLowerCase().equals(b.toLowerCase()); // } // return false; // } // // public ImageCardView getImageCardView() { // return card; // } // } // Path: base/src/main/java/io/github/xwz/base/adapters/FilmPresenter.java import android.content.Context; import android.graphics.Point; import android.support.v17.leanback.widget.BaseCardView; import android.support.v17.leanback.widget.ImageCardView; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import io.github.xwz.base.IApplication; import io.github.xwz.base.R; import io.github.xwz.base.views.EpisodeCardView; package io.github.xwz.base.adapters; public class FilmPresenter extends EpisodePresenter { private boolean large = false; public FilmPresenter() { } public FilmPresenter(boolean details) { large = details; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent) { Context context = parent.getContext(); return new EpisodeCardView(context, getCardView(context), getCardSize(context), true); } @Override protected Point getCardSize(Context context) { if (large) { return new Point(context.getResources().getDimensionPixelSize(R.dimen.poster_width_large), context.getResources().getDimensionPixelSize(R.dimen.poster_height_large)); } else { return new Point(context.getResources().getDimensionPixelSize(R.dimen.poster_width), context.getResources().getDimensionPixelSize(R.dimen.poster_height)); } } @Override protected ImageCardView getCardView(Context context) { ImageCardView card = super.getCardView(context); // nasty hack to hide content text view
if (context.getApplicationContext() instanceof IApplication) {
xwz/iview-android-tv
sbs/src/main/java/io/github/xwz/sbs/MainApplication.java
// Path: base/src/main/java/io/github/xwz/base/IApplication.java // public interface IApplication { // int getImageCardViewContentTextResId(); // int getImageCardViewInfoFieldResId(); // int getImageCardViewTitleTextResId(); // } // // Path: sbs/src/main/java/io/github/xwz/sbs/content/ContentManager.java // public class ContentManager extends ContentManagerBase { // // private static final String TAG = "ContentManager"; // // private SBSApi fetchShows; // // private long lastFetchList = 0; // // public ContentManager(Context context) { // super(context); // } // // @Override // public void fetchShowList(boolean force) { // long now = (new Date()).getTime(); // boolean shouldFetch = force || now - lastFetchList > 1800000; // Log.d(TAG, "diff:" + (now - lastFetchList)); // if (shouldFetch && (fetchShows == null || fetchShows.getStatus() == AsyncTask.Status.FINISHED)) { // cache().broadcastChange(CONTENT_SHOW_LIST_FETCHING); // fetchShows = new SBSApi(getContext()); // fetchShows.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); // lastFetchList = now; // } // } // // @Override // public void fetchEpisode(EpisodeBaseModel episode) { // broadcastChange(CONTENT_EPISODE_FETCHING, episode.getHref()); // EpisodeModel existing = (EpisodeModel) cache().getEpisode(episode.getHref()); // if (existing != null && existing.hasExtras() && existing.hasOtherEpisodes()) { // cache().broadcastChangeDelayed(100, CONTENT_EPISODE_DONE, episode.getHref(), null); // } else { // new SBSRelatedApi(getContext(), episode.getHref()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, episode.getHref()); // } // } // // @Override // public void fetchAuthToken(EpisodeBaseModel episode) { // Log.d(TAG, "fetchAuthToken"); // cache().broadcastChange(CONTENT_AUTH_FETCHING, episode.getHref()); // new SBSAuthApi(getContext(), episode.getHref()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, episode.getHref()); // } // // @Override // public List<EpisodeBaseModel> getRecommendations() { // List<EpisodeBaseModel> all = getAllShows(); // if (all.size() > 40) { // return getAllShows().subList(30, 32); // } // return new ArrayList<>(); // } // // @Override // public Class getRecommendationServiceClass() { // return RecommendationsService.class; // } // }
import android.app.Application; import com.raizlabs.android.dbflow.config.FlowManager; import io.github.xwz.base.IApplication; import io.github.xwz.sbs.content.ContentManager;
package io.github.xwz.sbs; public class MainApplication extends Application implements IApplication { private static final String TAG = "MainApplication"; @Override public void onCreate() { super.onCreate();
// Path: base/src/main/java/io/github/xwz/base/IApplication.java // public interface IApplication { // int getImageCardViewContentTextResId(); // int getImageCardViewInfoFieldResId(); // int getImageCardViewTitleTextResId(); // } // // Path: sbs/src/main/java/io/github/xwz/sbs/content/ContentManager.java // public class ContentManager extends ContentManagerBase { // // private static final String TAG = "ContentManager"; // // private SBSApi fetchShows; // // private long lastFetchList = 0; // // public ContentManager(Context context) { // super(context); // } // // @Override // public void fetchShowList(boolean force) { // long now = (new Date()).getTime(); // boolean shouldFetch = force || now - lastFetchList > 1800000; // Log.d(TAG, "diff:" + (now - lastFetchList)); // if (shouldFetch && (fetchShows == null || fetchShows.getStatus() == AsyncTask.Status.FINISHED)) { // cache().broadcastChange(CONTENT_SHOW_LIST_FETCHING); // fetchShows = new SBSApi(getContext()); // fetchShows.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); // lastFetchList = now; // } // } // // @Override // public void fetchEpisode(EpisodeBaseModel episode) { // broadcastChange(CONTENT_EPISODE_FETCHING, episode.getHref()); // EpisodeModel existing = (EpisodeModel) cache().getEpisode(episode.getHref()); // if (existing != null && existing.hasExtras() && existing.hasOtherEpisodes()) { // cache().broadcastChangeDelayed(100, CONTENT_EPISODE_DONE, episode.getHref(), null); // } else { // new SBSRelatedApi(getContext(), episode.getHref()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, episode.getHref()); // } // } // // @Override // public void fetchAuthToken(EpisodeBaseModel episode) { // Log.d(TAG, "fetchAuthToken"); // cache().broadcastChange(CONTENT_AUTH_FETCHING, episode.getHref()); // new SBSAuthApi(getContext(), episode.getHref()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, episode.getHref()); // } // // @Override // public List<EpisodeBaseModel> getRecommendations() { // List<EpisodeBaseModel> all = getAllShows(); // if (all.size() > 40) { // return getAllShows().subList(30, 32); // } // return new ArrayList<>(); // } // // @Override // public Class getRecommendationServiceClass() { // return RecommendationsService.class; // } // } // Path: sbs/src/main/java/io/github/xwz/sbs/MainApplication.java import android.app.Application; import com.raizlabs.android.dbflow.config.FlowManager; import io.github.xwz.base.IApplication; import io.github.xwz.sbs.content.ContentManager; package io.github.xwz.sbs; public class MainApplication extends Application implements IApplication { private static final String TAG = "MainApplication"; @Override public void onCreate() { super.onCreate();
new ContentManager(this).fetchShowList(true);
xwz/iview-android-tv
iview/src/main/java/io/github/xwz/iview/api/AuthApi.java
// Path: iview/src/main/java/io/github/xwz/iview/content/ContentManager.java // public class ContentManager extends ContentManagerBase { // // public static final Map<String, String> CATEGORIES = ImmutableMap.of( // "arts", "Arts & Culture", // "comedy", "Comedy", // "docs", "Documentary", // "drama", "Drama", // "education", "Education", // "lifestyle", "Lifestyle", // "news", "News & Current Affairs", // "panel", "Panel & Discussion", // "sport", "Sport" // ); // // private static final Map<String, String> CHANNELS = ImmutableMap.of( // "abc1", "ABC1", // "abc2", "ABC2", // "abc3", "ABC3", // "abc4kids", "ABC4Kids", // "iview", "iView Exclusives" // ); // // public ContentManager(Context context) { // super(context); // } // // private TvShowListApi fetchShows; // private long lastFetchList = 0; // // @Override // public void fetchShowList(boolean force) { // long now = (new Date()).getTime(); // boolean shouldFetch = force || now - lastFetchList > 1800000; // if (shouldFetch && (fetchShows == null || fetchShows.getStatus() == AsyncTask.Status.FINISHED)) { // broadcastChange(CONTENT_SHOW_LIST_FETCHING); // fetchShows = new TvShowListApi(getContext()); // fetchShows.execute(); // lastFetchList = now; // } // } // // @Override // public void fetchAuthToken(EpisodeBaseModel episode) { // EpisodeModel ep = (EpisodeModel)episode; // cache().broadcastChange(CONTENT_AUTH_FETCHING, ep.getHref()); // new AuthApi(getContext(), episode.getHref()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ep.getStream()); // } // // @Override // public void fetchEpisode(EpisodeBaseModel episode) { // broadcastChange(CONTENT_EPISODE_FETCHING, episode.getHref()); // EpisodeModel existing = (EpisodeModel)getEpisode(episode.getHref()); // if (existing != null && existing.hasExtras() && existing.hasOtherEpisodes()) { // cache().broadcastChangeDelayed(100, CONTENT_EPISODE_DONE, episode.getHref(), null); // } else { // new EpisodeDetailsApi(getContext(), episode.getHref()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, episode.getHref()); // } // } // // @Override // public LinkedHashMap<String, List<EpisodeBaseModel>> getAllShowsByCategories() { // LinkedHashMap<String, List<EpisodeBaseModel>> all = super.getAllShowsByCategories(); // List<EpisodeBaseModel> shows = getAllShows(); // for (Map.Entry<String, String> channel : CHANNELS.entrySet()) { // List<EpisodeBaseModel> episodes = new ArrayList<>(); // for (EpisodeBaseModel show : shows) { // if (channel.getKey().equals(show.getChannel())) { // episodes.add(show); // } // } // all.put(channel.getValue(), episodes); // } // for (Map.Entry<String, String> cat : CATEGORIES.entrySet()) { // List<EpisodeBaseModel> episodes = new ArrayList<>(); // for (EpisodeBaseModel show : shows) { // if (show.getCategories().contains(cat.getKey())) { // episodes.add(show); // } // } // all.put(cat.getValue(), episodes); // } // return all; // } // // @Override // public List<EpisodeBaseModel> getRecommendations() { // List<EpisodeBaseModel> all = getAllShows(); // if (all.size() > 40) { // return getAllShows().subList(30, 32); // } // return new ArrayList<>(); // } // // @Override // public Class getRecommendationServiceClass() { // return RecommendationsService.class; // } // }
import android.content.Context; import android.net.Uri; import android.util.Log; import android.util.Pair; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.github.xwz.iview.BuildConfig; import io.github.xwz.iview.content.ContentManager;
private static final Pattern TOKEN_PATTERN = Pattern.compile("<tokenhd>([^<]+)</tokenhd>"); private static final Pattern SERVER_PATTERN = Pattern.compile("<server>([^<]+)</server>"); private static final Pattern HOST_PATTERN = Pattern.compile("^(https?://)([^/]+)(/?.*)$"); public AuthApi(Context context, String id) { super(context); setEnableCache(false); this.id = id; } @Override protected Void doInBackground(String... urls) { if (urls.length > 0) { buildAuth(urls[0]); } return null; } private void buildAuth(String stream) { if (stream == null) { stream = updateEpisodeDetails(id); } if (stream != null) { Pair<String, String> auth = getAuthToken(); if (auth != null) { Uri.Builder builder = Uri.parse(stream).buildUpon(); builder.authority(auth.first).appendQueryParameter("hdnea", auth.second); Uri url = builder.build(); Log.d(TAG, "Stream URL:" + url);
// Path: iview/src/main/java/io/github/xwz/iview/content/ContentManager.java // public class ContentManager extends ContentManagerBase { // // public static final Map<String, String> CATEGORIES = ImmutableMap.of( // "arts", "Arts & Culture", // "comedy", "Comedy", // "docs", "Documentary", // "drama", "Drama", // "education", "Education", // "lifestyle", "Lifestyle", // "news", "News & Current Affairs", // "panel", "Panel & Discussion", // "sport", "Sport" // ); // // private static final Map<String, String> CHANNELS = ImmutableMap.of( // "abc1", "ABC1", // "abc2", "ABC2", // "abc3", "ABC3", // "abc4kids", "ABC4Kids", // "iview", "iView Exclusives" // ); // // public ContentManager(Context context) { // super(context); // } // // private TvShowListApi fetchShows; // private long lastFetchList = 0; // // @Override // public void fetchShowList(boolean force) { // long now = (new Date()).getTime(); // boolean shouldFetch = force || now - lastFetchList > 1800000; // if (shouldFetch && (fetchShows == null || fetchShows.getStatus() == AsyncTask.Status.FINISHED)) { // broadcastChange(CONTENT_SHOW_LIST_FETCHING); // fetchShows = new TvShowListApi(getContext()); // fetchShows.execute(); // lastFetchList = now; // } // } // // @Override // public void fetchAuthToken(EpisodeBaseModel episode) { // EpisodeModel ep = (EpisodeModel)episode; // cache().broadcastChange(CONTENT_AUTH_FETCHING, ep.getHref()); // new AuthApi(getContext(), episode.getHref()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ep.getStream()); // } // // @Override // public void fetchEpisode(EpisodeBaseModel episode) { // broadcastChange(CONTENT_EPISODE_FETCHING, episode.getHref()); // EpisodeModel existing = (EpisodeModel)getEpisode(episode.getHref()); // if (existing != null && existing.hasExtras() && existing.hasOtherEpisodes()) { // cache().broadcastChangeDelayed(100, CONTENT_EPISODE_DONE, episode.getHref(), null); // } else { // new EpisodeDetailsApi(getContext(), episode.getHref()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, episode.getHref()); // } // } // // @Override // public LinkedHashMap<String, List<EpisodeBaseModel>> getAllShowsByCategories() { // LinkedHashMap<String, List<EpisodeBaseModel>> all = super.getAllShowsByCategories(); // List<EpisodeBaseModel> shows = getAllShows(); // for (Map.Entry<String, String> channel : CHANNELS.entrySet()) { // List<EpisodeBaseModel> episodes = new ArrayList<>(); // for (EpisodeBaseModel show : shows) { // if (channel.getKey().equals(show.getChannel())) { // episodes.add(show); // } // } // all.put(channel.getValue(), episodes); // } // for (Map.Entry<String, String> cat : CATEGORIES.entrySet()) { // List<EpisodeBaseModel> episodes = new ArrayList<>(); // for (EpisodeBaseModel show : shows) { // if (show.getCategories().contains(cat.getKey())) { // episodes.add(show); // } // } // all.put(cat.getValue(), episodes); // } // return all; // } // // @Override // public List<EpisodeBaseModel> getRecommendations() { // List<EpisodeBaseModel> all = getAllShows(); // if (all.size() > 40) { // return getAllShows().subList(30, 32); // } // return new ArrayList<>(); // } // // @Override // public Class getRecommendationServiceClass() { // return RecommendationsService.class; // } // } // Path: iview/src/main/java/io/github/xwz/iview/api/AuthApi.java import android.content.Context; import android.net.Uri; import android.util.Log; import android.util.Pair; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.github.xwz.iview.BuildConfig; import io.github.xwz.iview.content.ContentManager; private static final Pattern TOKEN_PATTERN = Pattern.compile("<tokenhd>([^<]+)</tokenhd>"); private static final Pattern SERVER_PATTERN = Pattern.compile("<server>([^<]+)</server>"); private static final Pattern HOST_PATTERN = Pattern.compile("^(https?://)([^/]+)(/?.*)$"); public AuthApi(Context context, String id) { super(context); setEnableCache(false); this.id = id; } @Override protected Void doInBackground(String... urls) { if (urls.length > 0) { buildAuth(urls[0]); } return null; } private void buildAuth(String stream) { if (stream == null) { stream = updateEpisodeDetails(id); } if (stream != null) { Pair<String, String> auth = getAuthToken(); if (auth != null) { Uri.Builder builder = Uri.parse(stream).buildUpon(); builder.authority(auth.first).appendQueryParameter("hdnea", auth.second); Uri url = builder.build(); Log.d(TAG, "Stream URL:" + url);
ContentManager.cache().putStreamUrl(id, url);
xwz/iview-android-tv
sbs/src/main/java/io/github/xwz/sbs/activities/BootActivity.java
// Path: sbs/src/main/java/io/github/xwz/sbs/content/RecommendationsService.java // public class RecommendationsService extends IntentService { // private static final String TAG = "UpdateRecommendations"; // // private static final String RECOMMENDATION_TAG = "io.github.xwz.sbs.RECOMMENDATION_TAG"; // private static final String BACKGROUND_URI_PREFIX = "content://io.github.xwz.sbs.recommendation/"; // // public RecommendationsService() { // super("RecommendationService"); // } // // @Override // protected void onHandleIntent(Intent intent) { // Log.d(TAG, "Updating recommendation cards"); // EpisodeModel episode = (EpisodeModel) intent.getSerializableExtra(ContentManager.CONTENT_ID); // int id = intent.getIntExtra(ContentManager.CONTENT_TAG, 0); // if (episode != null) { // try { // Log.d(TAG, "Will recommend: " + episode); // buildNotification(episode, id); // } catch (IOException e) { // Log.e(TAG, "Error:" + e.getMessage()); // } // } // } // // private void buildNotification(EpisodeModel ep, final int id) throws IOException { // Point size = new Point(getResources().getDimensionPixelSize(R.dimen.card_width), // getResources().getDimensionPixelSize(R.dimen.card_height)); // Bitmap image = Picasso.with(this).load(ep.getThumbnail()).resize(size.x, size.y).get(); // Bitmap background = Picasso.with(this).load(ep.getThumbnail()).get(); // // final RecommendationBuilder builder = new RecommendationBuilder(this, id); // builder.setBackgroundPrefix(BACKGROUND_URI_PREFIX); // final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Notification notification = builder // .setBackgroundPrefix(BACKGROUND_URI_PREFIX) // .setIcon(R.mipmap.icon) // .setColor(getResources().getColor(R.color.brand_color_dark)) // .setTitle(ep.getSeriesTitle()) // .setDescription(ep.getTitle()) // .setImage(image) // .setBackground(background) // .setPendingIntent(buildPendingIntent(ep)) // .build(); // manager.notify(RECOMMENDATION_TAG, id, notification); // Log.d(TAG, "Recommending: " + ep); // } // // private PendingIntent buildPendingIntent(EpisodeModel ep) { // Intent intent = new Intent(this, DetailsActivity.class); // intent.putExtra(ContentManager.CONTENT_ID, ep); // // TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // stackBuilder.addParentStack(DetailsActivity.class); // stackBuilder.addNextIntent(intent); // intent.setAction(ep.getHref()); // // return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); // } // }
import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import io.github.xwz.sbs.content.RecommendationsService;
package io.github.xwz.sbs.activities; public class BootActivity extends BroadcastReceiver { private static final String TAG = "BootActivity"; private static final long INITIAL_DELAY = 5000; @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "BootActivity initiated"); if (intent.getAction().endsWith(Intent.ACTION_BOOT_COMPLETED)) { scheduleRecommendationUpdate(context); } } private void scheduleRecommendationUpdate(Context context) { Log.d(TAG, "Scheduling recommendations update"); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// Path: sbs/src/main/java/io/github/xwz/sbs/content/RecommendationsService.java // public class RecommendationsService extends IntentService { // private static final String TAG = "UpdateRecommendations"; // // private static final String RECOMMENDATION_TAG = "io.github.xwz.sbs.RECOMMENDATION_TAG"; // private static final String BACKGROUND_URI_PREFIX = "content://io.github.xwz.sbs.recommendation/"; // // public RecommendationsService() { // super("RecommendationService"); // } // // @Override // protected void onHandleIntent(Intent intent) { // Log.d(TAG, "Updating recommendation cards"); // EpisodeModel episode = (EpisodeModel) intent.getSerializableExtra(ContentManager.CONTENT_ID); // int id = intent.getIntExtra(ContentManager.CONTENT_TAG, 0); // if (episode != null) { // try { // Log.d(TAG, "Will recommend: " + episode); // buildNotification(episode, id); // } catch (IOException e) { // Log.e(TAG, "Error:" + e.getMessage()); // } // } // } // // private void buildNotification(EpisodeModel ep, final int id) throws IOException { // Point size = new Point(getResources().getDimensionPixelSize(R.dimen.card_width), // getResources().getDimensionPixelSize(R.dimen.card_height)); // Bitmap image = Picasso.with(this).load(ep.getThumbnail()).resize(size.x, size.y).get(); // Bitmap background = Picasso.with(this).load(ep.getThumbnail()).get(); // // final RecommendationBuilder builder = new RecommendationBuilder(this, id); // builder.setBackgroundPrefix(BACKGROUND_URI_PREFIX); // final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Notification notification = builder // .setBackgroundPrefix(BACKGROUND_URI_PREFIX) // .setIcon(R.mipmap.icon) // .setColor(getResources().getColor(R.color.brand_color_dark)) // .setTitle(ep.getSeriesTitle()) // .setDescription(ep.getTitle()) // .setImage(image) // .setBackground(background) // .setPendingIntent(buildPendingIntent(ep)) // .build(); // manager.notify(RECOMMENDATION_TAG, id, notification); // Log.d(TAG, "Recommending: " + ep); // } // // private PendingIntent buildPendingIntent(EpisodeModel ep) { // Intent intent = new Intent(this, DetailsActivity.class); // intent.putExtra(ContentManager.CONTENT_ID, ep); // // TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // stackBuilder.addParentStack(DetailsActivity.class); // stackBuilder.addNextIntent(intent); // intent.setAction(ep.getHref()); // // return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); // } // } // Path: sbs/src/main/java/io/github/xwz/sbs/activities/BootActivity.java import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import io.github.xwz.sbs.content.RecommendationsService; package io.github.xwz.sbs.activities; public class BootActivity extends BroadcastReceiver { private static final String TAG = "BootActivity"; private static final long INITIAL_DELAY = 5000; @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "BootActivity initiated"); if (intent.getAction().endsWith(Intent.ACTION_BOOT_COMPLETED)) { scheduleRecommendationUpdate(context); } } private void scheduleRecommendationUpdate(Context context) { Log.d(TAG, "Scheduling recommendations update"); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent recommendationIntent = new Intent(context, RecommendationsService.class);
xwz/iview-android-tv
sbs/src/main/java/io/github/xwz/sbs/api/SBSAuthApi.java
// Path: sbs/src/main/java/io/github/xwz/sbs/content/ContentManager.java // public class ContentManager extends ContentManagerBase { // // private static final String TAG = "ContentManager"; // // private SBSApi fetchShows; // // private long lastFetchList = 0; // // public ContentManager(Context context) { // super(context); // } // // @Override // public void fetchShowList(boolean force) { // long now = (new Date()).getTime(); // boolean shouldFetch = force || now - lastFetchList > 1800000; // Log.d(TAG, "diff:" + (now - lastFetchList)); // if (shouldFetch && (fetchShows == null || fetchShows.getStatus() == AsyncTask.Status.FINISHED)) { // cache().broadcastChange(CONTENT_SHOW_LIST_FETCHING); // fetchShows = new SBSApi(getContext()); // fetchShows.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); // lastFetchList = now; // } // } // // @Override // public void fetchEpisode(EpisodeBaseModel episode) { // broadcastChange(CONTENT_EPISODE_FETCHING, episode.getHref()); // EpisodeModel existing = (EpisodeModel) cache().getEpisode(episode.getHref()); // if (existing != null && existing.hasExtras() && existing.hasOtherEpisodes()) { // cache().broadcastChangeDelayed(100, CONTENT_EPISODE_DONE, episode.getHref(), null); // } else { // new SBSRelatedApi(getContext(), episode.getHref()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, episode.getHref()); // } // } // // @Override // public void fetchAuthToken(EpisodeBaseModel episode) { // Log.d(TAG, "fetchAuthToken"); // cache().broadcastChange(CONTENT_AUTH_FETCHING, episode.getHref()); // new SBSAuthApi(getContext(), episode.getHref()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, episode.getHref()); // } // // @Override // public List<EpisodeBaseModel> getRecommendations() { // List<EpisodeBaseModel> all = getAllShows(); // if (all.size() > 40) { // return getAllShows().subList(30, 32); // } // return new ArrayList<>(); // } // // @Override // public Class getRecommendationServiceClass() { // return RecommendationsService.class; // } // }
import android.content.Context; import android.net.Uri; import android.util.Log; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.github.xwz.sbs.content.ContentManager;
package io.github.xwz.sbs.api; public class SBSAuthApi extends SBSApiBase { private static final String TAG = "SBSAuthApi"; private final String id; private static final Pattern SRC_PATTERN = Pattern.compile("<video src=\"([^\"]+)\""); public SBSAuthApi(Context context, String id) { super(context); setEnableCache(false); this.id = id; } @Override protected Void doInBackground(String... urls) { Log.d(TAG, "Doing AUTH"); if (urls.length > 0) { buildAuth(urls[0]); } return null; } private void buildAuth(String href) { Uri url = createStreamUrl(href); if (url != null) { String content = fetchUrlSkipLocalCache(url, 0); if (content != null) { parseContent(content); } else {
// Path: sbs/src/main/java/io/github/xwz/sbs/content/ContentManager.java // public class ContentManager extends ContentManagerBase { // // private static final String TAG = "ContentManager"; // // private SBSApi fetchShows; // // private long lastFetchList = 0; // // public ContentManager(Context context) { // super(context); // } // // @Override // public void fetchShowList(boolean force) { // long now = (new Date()).getTime(); // boolean shouldFetch = force || now - lastFetchList > 1800000; // Log.d(TAG, "diff:" + (now - lastFetchList)); // if (shouldFetch && (fetchShows == null || fetchShows.getStatus() == AsyncTask.Status.FINISHED)) { // cache().broadcastChange(CONTENT_SHOW_LIST_FETCHING); // fetchShows = new SBSApi(getContext()); // fetchShows.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); // lastFetchList = now; // } // } // // @Override // public void fetchEpisode(EpisodeBaseModel episode) { // broadcastChange(CONTENT_EPISODE_FETCHING, episode.getHref()); // EpisodeModel existing = (EpisodeModel) cache().getEpisode(episode.getHref()); // if (existing != null && existing.hasExtras() && existing.hasOtherEpisodes()) { // cache().broadcastChangeDelayed(100, CONTENT_EPISODE_DONE, episode.getHref(), null); // } else { // new SBSRelatedApi(getContext(), episode.getHref()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, episode.getHref()); // } // } // // @Override // public void fetchAuthToken(EpisodeBaseModel episode) { // Log.d(TAG, "fetchAuthToken"); // cache().broadcastChange(CONTENT_AUTH_FETCHING, episode.getHref()); // new SBSAuthApi(getContext(), episode.getHref()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, episode.getHref()); // } // // @Override // public List<EpisodeBaseModel> getRecommendations() { // List<EpisodeBaseModel> all = getAllShows(); // if (all.size() > 40) { // return getAllShows().subList(30, 32); // } // return new ArrayList<>(); // } // // @Override // public Class getRecommendationServiceClass() { // return RecommendationsService.class; // } // } // Path: sbs/src/main/java/io/github/xwz/sbs/api/SBSAuthApi.java import android.content.Context; import android.net.Uri; import android.util.Log; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.github.xwz.sbs.content.ContentManager; package io.github.xwz.sbs.api; public class SBSAuthApi extends SBSApiBase { private static final String TAG = "SBSAuthApi"; private final String id; private static final Pattern SRC_PATTERN = Pattern.compile("<video src=\"([^\"]+)\""); public SBSAuthApi(Context context, String id) { super(context); setEnableCache(false); this.id = id; } @Override protected Void doInBackground(String... urls) { Log.d(TAG, "Doing AUTH"); if (urls.length > 0) { buildAuth(urls[0]); } return null; } private void buildAuth(String href) { Uri url = createStreamUrl(href); if (url != null) { String content = fetchUrlSkipLocalCache(url, 0); if (content != null) { parseContent(content); } else {
ContentManager.getInstance().broadcastChange(ContentManager.CONTENT_AUTH_ERROR, ContentManager.AUTH_FAILED_NETWORK, id);
linhongseba/Temporal-Network-Embedding
source_code/document2vector/src/process/ReadTopwords.java
// Path: source_code/document2vector/src/util/WordPair.java // public class WordPair extends Pair implements Comparable{ // // public WordPair(double key, int value) { // // key: the weight of words // // value: the idx of words // super(key, value); // } // // public void setKey(double key) { // super.setKey(key); // } // public void setValue(int value){ // super.setValue(value); // } // public double getWeight() { // return ((Double)super.getKey()).doubleValue(); // } // public int getIdx(){ // return ((Integer)super.getValue()).intValue(); // } // @Override // public int compareTo(Object o) { // return compareTo((WordPair)o); // } // public int compareTo(WordPair o){ // return Double.compare(getWeight(),o.getWeight()); // } // }
import util.WordPair; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Scanner;
package process; /** * Created by linhong on 11/7/2016. */ public class ReadTopwords { int dimension; int dnum; int K;
// Path: source_code/document2vector/src/util/WordPair.java // public class WordPair extends Pair implements Comparable{ // // public WordPair(double key, int value) { // // key: the weight of words // // value: the idx of words // super(key, value); // } // // public void setKey(double key) { // super.setKey(key); // } // public void setValue(int value){ // super.setValue(value); // } // public double getWeight() { // return ((Double)super.getKey()).doubleValue(); // } // public int getIdx(){ // return ((Integer)super.getValue()).intValue(); // } // @Override // public int compareTo(Object o) { // return compareTo((WordPair)o); // } // public int compareTo(WordPair o){ // return Double.compare(getWeight(),o.getWeight()); // } // } // Path: source_code/document2vector/src/process/ReadTopwords.java import util.WordPair; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Scanner; package process; /** * Created by linhong on 11/7/2016. */ public class ReadTopwords { int dimension; int dnum; int K;
PriorityQueue<WordPair> []Q;
neo4j-contrib/neo4j-jdbc
neo4j-jdbc-http/src/main/java/org/neo4j/jdbc/http/driver/CypherExecutor.java
// Path: neo4j-jdbc/src/main/java/org/neo4j/jdbc/Neo4jDatabaseMetaData.java // public static final String GET_DBMS_FUNCTIONS = "CALL dbms.functions() YIELD name RETURN name ORDER BY name ASC";
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthState; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HttpContext; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.logging.Logger; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; import static org.neo4j.jdbc.Neo4jDatabaseMetaData.GET_DBMS_FUNCTIONS;
String user = properties.getProperty("user", properties.getProperty("username", "neo4j")); CredentialsProvider credsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, properties.getProperty("password")); credsProvider.setCredentials(new AuthScope(host, port), credentials); return credsProvider; } return null; } /** * Execute a list of cypher queries. * * @param queries List of cypher query object * @return the response for these queries * @throws SQLException sqlexception */ public Neo4jResponse executeQueries(List<Neo4jStatement> queries) throws SQLException { // Prepare the headers query HttpPost request = new HttpPost(currentTransactionUrl); // Prepare body request StringEntity requestEntity = new StringEntity(Neo4jStatement.toJson(queries, mapper), ContentType.APPLICATION_JSON); request.setEntity(requestEntity); // Make the request return this.executeHttpRequest(request); } public List<String> callDbmsFunctions() { try {
// Path: neo4j-jdbc/src/main/java/org/neo4j/jdbc/Neo4jDatabaseMetaData.java // public static final String GET_DBMS_FUNCTIONS = "CALL dbms.functions() YIELD name RETURN name ORDER BY name ASC"; // Path: neo4j-jdbc-http/src/main/java/org/neo4j/jdbc/http/driver/CypherExecutor.java import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthState; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HttpContext; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.logging.Logger; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; import static org.neo4j.jdbc.Neo4jDatabaseMetaData.GET_DBMS_FUNCTIONS; String user = properties.getProperty("user", properties.getProperty("username", "neo4j")); CredentialsProvider credsProvider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, properties.getProperty("password")); credsProvider.setCredentials(new AuthScope(host, port), credentials); return credsProvider; } return null; } /** * Execute a list of cypher queries. * * @param queries List of cypher query object * @return the response for these queries * @throws SQLException sqlexception */ public Neo4jResponse executeQueries(List<Neo4jStatement> queries) throws SQLException { // Prepare the headers query HttpPost request = new HttpPost(currentTransactionUrl); // Prepare body request StringEntity requestEntity = new StringEntity(Neo4jStatement.toJson(queries, mapper), ContentType.APPLICATION_JSON); request.setEntity(requestEntity); // Make the request return this.executeHttpRequest(request); } public List<String> callDbmsFunctions() { try {
Neo4jResponse response = this.executeQuery(new Neo4jStatement(GET_DBMS_FUNCTIONS, Collections.emptyMap(), false));
neo4j-contrib/neo4j-jdbc
neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/BoltNeo4jAuthenticationIT.java
// Path: neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/utils/Neo4jContainerUtils.java // public static GenericContainer<?> createNeo4jContainerWithDefaultPassword() { // return new GenericContainer<>(neo4jImageCoordinates()) // .withExposedPorts(7687) // .withEnv("NEO4J_ACCEPT_LICENSE_AGREEMENT", "yes") // .waitingFor(boltStart()); // }
import java.sql.Statement; import static org.hamcrest.CoreMatchers.isA; import static org.neo4j.jdbc.bolt.utils.Neo4jContainerUtils.createNeo4jContainerWithDefaultPassword; import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.neo4j.driver.exceptions.ClientException; import org.testcontainers.containers.GenericContainer; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;
/* * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> * Created on 23/03/16 */ package org.neo4j.jdbc.bolt; /** * @author AgileLARUS * @since 3.0.0 */ public class BoltNeo4jAuthenticationIT { @ClassRule
// Path: neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/utils/Neo4jContainerUtils.java // public static GenericContainer<?> createNeo4jContainerWithDefaultPassword() { // return new GenericContainer<>(neo4jImageCoordinates()) // .withExposedPorts(7687) // .withEnv("NEO4J_ACCEPT_LICENSE_AGREEMENT", "yes") // .waitingFor(boltStart()); // } // Path: neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/BoltNeo4jAuthenticationIT.java import java.sql.Statement; import static org.hamcrest.CoreMatchers.isA; import static org.neo4j.jdbc.bolt.utils.Neo4jContainerUtils.createNeo4jContainerWithDefaultPassword; import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.neo4j.driver.exceptions.ClientException; import org.testcontainers.containers.GenericContainer; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /* * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> * Created on 23/03/16 */ package org.neo4j.jdbc.bolt; /** * @author AgileLARUS * @since 3.0.0 */ public class BoltNeo4jAuthenticationIT { @ClassRule
public static final GenericContainer<?> neo4j = createNeo4jContainerWithDefaultPassword();
neo4j-contrib/neo4j-jdbc
neo4j-jdbc/src/main/java/org/neo4j/jdbc/Neo4jPreparedStatement.java
// Path: neo4j-jdbc/src/main/java/org/neo4j/jdbc/utils/PreparedStatementBuilder.java // public class PreparedStatementBuilder { // // private PreparedStatementBuilder() {} // // /** // * This method return a String that is the original raw string with all valid placeholders replaced with neo4j curly brackets notation for parameters. // * <br> // * i.e. MATCH n RETURN n WHERE n.name = ? is transformed in MATCH n RETURN n WHERE n.name = {1} // * // * @param raw The string to be translated. // * @return The string with the placeholders replaced. // */ // public static String replacePlaceholders(String raw) { // int index = 1; // String digested = raw; // // String regex = "\\?(?=[^\"]*(?:\"[^\"]*\"[^\"]*)*$)"; // Matcher matcher = Pattern.compile(regex).matcher(digested); // // while (matcher.find()) { // digested = digested.replaceFirst(regex, "\\$" + index); // index++; // } // // return digested; // } // // /** // * Given a string (statement) it counts all valid placeholders // * // * @param raw The string of the statement // * @return The number of all valid placeholders // */ // public static int namedParameterCount(String raw) { // int max = 0; // String regex = "\\$\\s*`?\\s*(\\d+)\\s*`?\\s*(?=[^\"]*(\"[^\"]*\"[^\"]*)*$)"; // Matcher matcher = Pattern.compile(regex).matcher(raw); // while (matcher.find()) { // max = Math.max(Integer.parseInt(matcher.group(1)),max); // } // return max; // } // // }
import static java.sql.Types.*; import org.neo4j.jdbc.utils.ExceptionBuilder; import org.neo4j.jdbc.utils.PreparedStatementBuilder; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.*; import java.sql.Date; import java.sql.ResultSet; import java.util.*;
/* * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> * Created on 03/02/16 */ package org.neo4j.jdbc; /** * Don't forget to close some attribute (like currentResultSet and currentUpdateCount) or your implementation. * * @author AgileLARUS * @since 3.0.0 */ public abstract class Neo4jPreparedStatement extends Neo4jStatement implements PreparedStatement { protected String statement; protected HashMap<String, Object> parameters; protected List<Map<String, Object>> batchParameters; protected int parametersNumber; private static final List<Integer> UNSUPPORTED_TYPES = Collections .unmodifiableList( Arrays.asList( ARRAY, BLOB, CLOB, DATALINK, JAVA_OBJECT, NCHAR, NCLOB, NVARCHAR, LONGNVARCHAR, REF, ROWID, SQLXML, STRUCT ) ); /** * Default constructor with connection and statement. * * @param connection The JDBC connection * @param rawStatement The prepared statement */ protected Neo4jPreparedStatement(Neo4jConnection connection, String rawStatement) { super(connection);
// Path: neo4j-jdbc/src/main/java/org/neo4j/jdbc/utils/PreparedStatementBuilder.java // public class PreparedStatementBuilder { // // private PreparedStatementBuilder() {} // // /** // * This method return a String that is the original raw string with all valid placeholders replaced with neo4j curly brackets notation for parameters. // * <br> // * i.e. MATCH n RETURN n WHERE n.name = ? is transformed in MATCH n RETURN n WHERE n.name = {1} // * // * @param raw The string to be translated. // * @return The string with the placeholders replaced. // */ // public static String replacePlaceholders(String raw) { // int index = 1; // String digested = raw; // // String regex = "\\?(?=[^\"]*(?:\"[^\"]*\"[^\"]*)*$)"; // Matcher matcher = Pattern.compile(regex).matcher(digested); // // while (matcher.find()) { // digested = digested.replaceFirst(regex, "\\$" + index); // index++; // } // // return digested; // } // // /** // * Given a string (statement) it counts all valid placeholders // * // * @param raw The string of the statement // * @return The number of all valid placeholders // */ // public static int namedParameterCount(String raw) { // int max = 0; // String regex = "\\$\\s*`?\\s*(\\d+)\\s*`?\\s*(?=[^\"]*(\"[^\"]*\"[^\"]*)*$)"; // Matcher matcher = Pattern.compile(regex).matcher(raw); // while (matcher.find()) { // max = Math.max(Integer.parseInt(matcher.group(1)),max); // } // return max; // } // // } // Path: neo4j-jdbc/src/main/java/org/neo4j/jdbc/Neo4jPreparedStatement.java import static java.sql.Types.*; import org.neo4j.jdbc.utils.ExceptionBuilder; import org.neo4j.jdbc.utils.PreparedStatementBuilder; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.*; import java.sql.Date; import java.sql.ResultSet; import java.util.*; /* * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> * Created on 03/02/16 */ package org.neo4j.jdbc; /** * Don't forget to close some attribute (like currentResultSet and currentUpdateCount) or your implementation. * * @author AgileLARUS * @since 3.0.0 */ public abstract class Neo4jPreparedStatement extends Neo4jStatement implements PreparedStatement { protected String statement; protected HashMap<String, Object> parameters; protected List<Map<String, Object>> batchParameters; protected int parametersNumber; private static final List<Integer> UNSUPPORTED_TYPES = Collections .unmodifiableList( Arrays.asList( ARRAY, BLOB, CLOB, DATALINK, JAVA_OBJECT, NCHAR, NCLOB, NVARCHAR, LONGNVARCHAR, REF, ROWID, SQLXML, STRUCT ) ); /** * Default constructor with connection and statement. * * @param connection The JDBC connection * @param rawStatement The prepared statement */ protected Neo4jPreparedStatement(Neo4jConnection connection, String rawStatement) { super(connection);
this.statement = PreparedStatementBuilder.replacePlaceholders(rawStatement);
neo4j-contrib/neo4j-jdbc
neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/NodeSerializer.java
// Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/DataConverterUtils.java // public static Map<String, Object> nodeToMap(Node value) { // Map<String, Object> nodeMap = new LinkedHashMap<>(); // nodeMap.put("_id", value.id()); // nodeMap.put("_labels", value.labels()); // nodeMap.putAll(convertFields(value.asMap())); // return nodeMap; // }
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.neo4j.driver.types.Node; import java.io.IOException; import java.util.Map; import static org.neo4j.jdbc.utils.DataConverterUtils.nodeToMap;
package org.neo4j.jdbc.utils; public class NodeSerializer extends JsonSerializer<Node> { @Override public void serialize(Node value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
// Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/DataConverterUtils.java // public static Map<String, Object> nodeToMap(Node value) { // Map<String, Object> nodeMap = new LinkedHashMap<>(); // nodeMap.put("_id", value.id()); // nodeMap.put("_labels", value.labels()); // nodeMap.putAll(convertFields(value.asMap())); // return nodeMap; // } // Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/NodeSerializer.java import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.neo4j.driver.types.Node; import java.io.IOException; import java.util.Map; import static org.neo4j.jdbc.utils.DataConverterUtils.nodeToMap; package org.neo4j.jdbc.utils; public class NodeSerializer extends JsonSerializer<Node> { @Override public void serialize(Node value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
Map<String, Object> nodeMap = nodeToMap(value);
neo4j-contrib/neo4j-jdbc
neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/RelationshipSerializer.java
// Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/DataConverterUtils.java // public static Map<String, Object> relationshipToMap(Relationship value) { // Map<String, Object> relMap = new LinkedHashMap<>(); // relMap.put("_id", value.id()); // relMap.put("_type", value.type()); // relMap.put("_startId", value.startNodeId()); // relMap.put("_endId", value.endNodeId()); // relMap.putAll(convertFields(value.asMap())); // return relMap; // }
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.neo4j.driver.types.Relationship; import java.io.IOException; import java.util.Map; import static org.neo4j.jdbc.utils.DataConverterUtils.relationshipToMap;
package org.neo4j.jdbc.utils; public class RelationshipSerializer extends JsonSerializer<Relationship> { @Override public void serialize(Relationship value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
// Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/DataConverterUtils.java // public static Map<String, Object> relationshipToMap(Relationship value) { // Map<String, Object> relMap = new LinkedHashMap<>(); // relMap.put("_id", value.id()); // relMap.put("_type", value.type()); // relMap.put("_startId", value.startNodeId()); // relMap.put("_endId", value.endNodeId()); // relMap.putAll(convertFields(value.asMap())); // return relMap; // } // Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/RelationshipSerializer.java import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.neo4j.driver.types.Relationship; import java.io.IOException; import java.util.Map; import static org.neo4j.jdbc.utils.DataConverterUtils.relationshipToMap; package org.neo4j.jdbc.utils; public class RelationshipSerializer extends JsonSerializer<Relationship> { @Override public void serialize(Relationship value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
Map<String, Object> relMap = relationshipToMap(value);
neo4j-contrib/neo4j-jdbc
neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/boltrouting/BoltRoutingNeo4jDriverTest.java
// Path: neo4j-jdbc/src/main/java/org/neo4j/jdbc/Neo4jDriver.java // public abstract class Neo4jDriver implements java.sql.Driver { // // /** // * JDBC prefix for the connection url. // */ // protected static final String JDBC_PREFIX = "jdbc:neo4j:"; // // /** // * Driver prefix for the connection url. // */ // private final String driverPrefix; // // /** // * Constructor for extended class. // * // * @param prefix Prefix of the driver for the connection url. // */ // protected Neo4jDriver(String prefix) { // this.driverPrefix = prefix; // } // // @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { // return new DriverPropertyInfo[0]; // } // // @Override public int getMajorVersion() { // return 3; // } // // @Override public int getMinorVersion() { // return 4; // } // // @Override public boolean jdbcCompliant() { // return false; // } // // @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { // throw ExceptionBuilder.buildUnsupportedOperationException(); // } // // @Override public boolean acceptsURL(String url) throws SQLException { // if (url == null) { // throw new SQLException("null is not a valid url"); // } // String[] pieces = url.split(":"); // if (pieces.length > 3 && url.startsWith(JDBC_PREFIX)) { // if (driverPrefix != null) { // return pieces[2].matches(driverPrefix); // } // return true; // } // return false; // } // // protected String getPrefix() { // return this.driverPrefix; // } // // /** // * Parse the url string and construct a properties object. // * // * @param url The url to parse // * @param params The properties // * @return the properties // */ // protected Properties parseUrlProperties(String url, Properties params) { // Properties properties = new Properties(); // if(params != null) { // for (Map.Entry<Object, Object> entry : params.entrySet()) { // properties.put(entry.getKey().toString().toLowerCase(),entry.getValue()); // } // } // if (url.contains("?")) { // String urlProps = url.substring(url.indexOf('?') + 1); // String[] props = urlProps.split("[,&]"); // for (String prop : props) { // prop = decodeUrlComponent(prop); // int idx1 = prop.indexOf('='); // int idx2 = prop.indexOf(':'); // int idx = (idx1 != -1 && idx2 != -1) ? Math.min(idx1, idx2) : Math.max(idx1, idx2); // if (idx != -1) { // String key = prop.substring(0, idx); // String value = prop.substring(idx + 1); // if (properties.containsKey(key.toLowerCase())) { // properties.put(key.toLowerCase(), Arrays.asList(properties.getProperty(key.toLowerCase()), value)); // } else { // properties.put(key.toLowerCase(), value); // } // } else { // properties.put(prop.toLowerCase(), "true"); // } // } // } // // return properties; // } // // private String decodeUrlComponent(String urlProps) { // try { // return URLDecoder.decode(urlProps, "UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new Neo4jJdbcRuntimeException(e); // } // } // // }
import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.neo4j.jdbc.Neo4jDriver; import java.sql.SQLException; import static junit.framework.TestCase.assertFalse;
/* * Copyright (c) 2018 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> */ package org.neo4j.jdbc.boltrouting; /** * @author AgileLARUS * @since 3.3.1 */ public class BoltRoutingNeo4jDriverTest { @Rule public ExpectedException expectedEx = ExpectedException.none(); @Test public void shoulNotAcceptURL() throws SQLException {
// Path: neo4j-jdbc/src/main/java/org/neo4j/jdbc/Neo4jDriver.java // public abstract class Neo4jDriver implements java.sql.Driver { // // /** // * JDBC prefix for the connection url. // */ // protected static final String JDBC_PREFIX = "jdbc:neo4j:"; // // /** // * Driver prefix for the connection url. // */ // private final String driverPrefix; // // /** // * Constructor for extended class. // * // * @param prefix Prefix of the driver for the connection url. // */ // protected Neo4jDriver(String prefix) { // this.driverPrefix = prefix; // } // // @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { // return new DriverPropertyInfo[0]; // } // // @Override public int getMajorVersion() { // return 3; // } // // @Override public int getMinorVersion() { // return 4; // } // // @Override public boolean jdbcCompliant() { // return false; // } // // @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { // throw ExceptionBuilder.buildUnsupportedOperationException(); // } // // @Override public boolean acceptsURL(String url) throws SQLException { // if (url == null) { // throw new SQLException("null is not a valid url"); // } // String[] pieces = url.split(":"); // if (pieces.length > 3 && url.startsWith(JDBC_PREFIX)) { // if (driverPrefix != null) { // return pieces[2].matches(driverPrefix); // } // return true; // } // return false; // } // // protected String getPrefix() { // return this.driverPrefix; // } // // /** // * Parse the url string and construct a properties object. // * // * @param url The url to parse // * @param params The properties // * @return the properties // */ // protected Properties parseUrlProperties(String url, Properties params) { // Properties properties = new Properties(); // if(params != null) { // for (Map.Entry<Object, Object> entry : params.entrySet()) { // properties.put(entry.getKey().toString().toLowerCase(),entry.getValue()); // } // } // if (url.contains("?")) { // String urlProps = url.substring(url.indexOf('?') + 1); // String[] props = urlProps.split("[,&]"); // for (String prop : props) { // prop = decodeUrlComponent(prop); // int idx1 = prop.indexOf('='); // int idx2 = prop.indexOf(':'); // int idx = (idx1 != -1 && idx2 != -1) ? Math.min(idx1, idx2) : Math.max(idx1, idx2); // if (idx != -1) { // String key = prop.substring(0, idx); // String value = prop.substring(idx + 1); // if (properties.containsKey(key.toLowerCase())) { // properties.put(key.toLowerCase(), Arrays.asList(properties.getProperty(key.toLowerCase()), value)); // } else { // properties.put(key.toLowerCase(), value); // } // } else { // properties.put(prop.toLowerCase(), "true"); // } // } // } // // return properties; // } // // private String decodeUrlComponent(String urlProps) { // try { // return URLDecoder.decode(urlProps, "UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new Neo4jJdbcRuntimeException(e); // } // } // // } // Path: neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/boltrouting/BoltRoutingNeo4jDriverTest.java import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.neo4j.jdbc.Neo4jDriver; import java.sql.SQLException; import static junit.framework.TestCase.assertFalse; /* * Copyright (c) 2018 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> */ package org.neo4j.jdbc.boltrouting; /** * @author AgileLARUS * @since 3.3.1 */ public class BoltRoutingNeo4jDriverTest { @Rule public ExpectedException expectedEx = ExpectedException.none(); @Test public void shoulNotAcceptURL() throws SQLException {
Neo4jDriver driver = new BoltRoutingNeo4jDriver();
neo4j-contrib/neo4j-jdbc
neo4j-jdbc-http/src/test/java/org/neo4j/jdbc/http/test/Neo4jHttpUnitTestUtil.java
// Path: neo4j-jdbc-http/src/main/java/org/neo4j/jdbc/http/driver/Neo4jStatement.java // public class Neo4jStatement { // // /** // * Cypher query. // */ // public final String statement; // // /** // * Params of the cypher query. // */ // public final Map<String, Object> parameters; // // /** // * Do we need to include stats with the query ? // */ // public final Boolean includeStats; // // /** // * Default constructor. // * // * @param statement Cypher query // * @param parameters List of named params for the cypher query // * @param includeStats Do we need to include stats // * @throws SQLException sqlexception // */ // public Neo4jStatement(String statement, Map<String, Object> parameters, Boolean includeStats) throws SQLException { // if (statement != null && !"".equals(statement)) { // this.statement = statement; // } else { // throw new SQLException("Creating a NULL query"); // } // if (parameters != null) { // this.parameters = parameters; // } else { // this.parameters = new HashMap<>(); // } // if (includeStats != null) { // this.includeStats = includeStats; // } else { // this.includeStats = Boolean.FALSE; // } // } // // /** // * Convert the list of query to a JSON compatible with Neo4j endpoint. // * // * @param queries List of cypher queries. // * @param mapper mapper // * @return The JSON string that correspond to the body of the API call // * @throws SQLException sqlexception // */ // public static String toJson(List<Neo4jStatement> queries, ObjectMapper mapper) throws SQLException { // StringBuilder sb = new StringBuilder(); // try { // sb.append("{\"statements\":"); // sb.append(mapper.writeValueAsString(queries)); // sb.append("}"); // // } catch (JsonProcessingException e) { // throw new SQLException("Can't convert Cypher statement(s) into JSON", e); // } // return sb.toString(); // } // // /** // * Getter for Statements. // * We escape the string for the API. // * // * @return the statement // */ // public String getStatement() { // return statement; // } // // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.opencsv.CSVParserBuilder; import com.opencsv.CSVReader; import com.opencsv.CSVReaderBuilder; import org.junit.Assert; import org.junit.Rule; import org.junit.rules.ExpectedException; import org.neo4j.jdbc.http.driver.Neo4jStatement; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.stream.Collectors;
/* * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> * Created on 15/4/2016 */ package org.neo4j.jdbc.http.test; public class Neo4jHttpUnitTestUtil { @Rule public ExpectedException expectedEx = ExpectedException.none(); private final static int CSV_STATEMENT = 0; private final static int CSV_PARAMETERS = 1; private final static int CSV_INCLUDESTATS = 2; /** * Retrieve some random queries from a csv file. * We return a map with the CSV source into the kye <code>source</code> and its object Neo4jStatement into key <code>object</code>. * * @param filename The filename that contains queries * @param nbElement The number element to return * @return * @throws Exception */ protected Map<String, List> getRandomNeo4jStatementFromCSV(String filename, int nbElement) throws Exception {
// Path: neo4j-jdbc-http/src/main/java/org/neo4j/jdbc/http/driver/Neo4jStatement.java // public class Neo4jStatement { // // /** // * Cypher query. // */ // public final String statement; // // /** // * Params of the cypher query. // */ // public final Map<String, Object> parameters; // // /** // * Do we need to include stats with the query ? // */ // public final Boolean includeStats; // // /** // * Default constructor. // * // * @param statement Cypher query // * @param parameters List of named params for the cypher query // * @param includeStats Do we need to include stats // * @throws SQLException sqlexception // */ // public Neo4jStatement(String statement, Map<String, Object> parameters, Boolean includeStats) throws SQLException { // if (statement != null && !"".equals(statement)) { // this.statement = statement; // } else { // throw new SQLException("Creating a NULL query"); // } // if (parameters != null) { // this.parameters = parameters; // } else { // this.parameters = new HashMap<>(); // } // if (includeStats != null) { // this.includeStats = includeStats; // } else { // this.includeStats = Boolean.FALSE; // } // } // // /** // * Convert the list of query to a JSON compatible with Neo4j endpoint. // * // * @param queries List of cypher queries. // * @param mapper mapper // * @return The JSON string that correspond to the body of the API call // * @throws SQLException sqlexception // */ // public static String toJson(List<Neo4jStatement> queries, ObjectMapper mapper) throws SQLException { // StringBuilder sb = new StringBuilder(); // try { // sb.append("{\"statements\":"); // sb.append(mapper.writeValueAsString(queries)); // sb.append("}"); // // } catch (JsonProcessingException e) { // throw new SQLException("Can't convert Cypher statement(s) into JSON", e); // } // return sb.toString(); // } // // /** // * Getter for Statements. // * We escape the string for the API. // * // * @return the statement // */ // public String getStatement() { // return statement; // } // // } // Path: neo4j-jdbc-http/src/test/java/org/neo4j/jdbc/http/test/Neo4jHttpUnitTestUtil.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.opencsv.CSVParserBuilder; import com.opencsv.CSVReader; import com.opencsv.CSVReaderBuilder; import org.junit.Assert; import org.junit.Rule; import org.junit.rules.ExpectedException; import org.neo4j.jdbc.http.driver.Neo4jStatement; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.stream.Collectors; /* * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> * Created on 15/4/2016 */ package org.neo4j.jdbc.http.test; public class Neo4jHttpUnitTestUtil { @Rule public ExpectedException expectedEx = ExpectedException.none(); private final static int CSV_STATEMENT = 0; private final static int CSV_PARAMETERS = 1; private final static int CSV_INCLUDESTATS = 2; /** * Retrieve some random queries from a csv file. * We return a map with the CSV source into the kye <code>source</code> and its object Neo4jStatement into key <code>object</code>. * * @param filename The filename that contains queries * @param nbElement The number element to return * @return * @throws Exception */ protected Map<String, List> getRandomNeo4jStatementFromCSV(String filename, int nbElement) throws Exception {
List<Neo4jStatement> queriesObj = new ArrayList<>();
neo4j-contrib/neo4j-jdbc
neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/PointSerializer.java
// Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/DataConverterUtils.java // public static Map<String, Object> pointToMap(Point point) { // Map<String, Object> map = new HashMap<>(); // map.put("srid",point.srid()); // map.put("x", point.x()); // map.put("y", point.y()); // // switch(point.srid()){ // case 7203: // map.put("crs","cartesian"); // break; // case 9157: // map.put("crs","cartesian-3d"); // map.put("z", point.z()); // break; // case 4326: // map.put("crs","wgs-84"); // map.put("longitude", point.x()); // map.put("latitude", point.y()); // break; // case 4979: // map.put("crs","wgs-84-3d"); // map.put("longitude", point.x()); // map.put("latitude", point.y()); // map.put("height",point.z()); // map.put("z", point.z()); // break; // } // // return map; // }
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.neo4j.driver.types.Point; import java.io.IOException; import java.util.Map; import static org.neo4j.jdbc.utils.DataConverterUtils.pointToMap;
package org.neo4j.jdbc.utils; public class PointSerializer extends JsonSerializer<Point> { @Override public void serialize(Point value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
// Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/DataConverterUtils.java // public static Map<String, Object> pointToMap(Point point) { // Map<String, Object> map = new HashMap<>(); // map.put("srid",point.srid()); // map.put("x", point.x()); // map.put("y", point.y()); // // switch(point.srid()){ // case 7203: // map.put("crs","cartesian"); // break; // case 9157: // map.put("crs","cartesian-3d"); // map.put("z", point.z()); // break; // case 4326: // map.put("crs","wgs-84"); // map.put("longitude", point.x()); // map.put("latitude", point.y()); // break; // case 4979: // map.put("crs","wgs-84-3d"); // map.put("longitude", point.x()); // map.put("latitude", point.y()); // map.put("height",point.z()); // map.put("z", point.z()); // break; // } // // return map; // } // Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/PointSerializer.java import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.neo4j.driver.types.Point; import java.io.IOException; import java.util.Map; import static org.neo4j.jdbc.utils.DataConverterUtils.pointToMap; package org.neo4j.jdbc.utils; public class PointSerializer extends JsonSerializer<Point> { @Override public void serialize(Point value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
Map<String, Object> point = pointToMap(value);
neo4j-contrib/neo4j-jdbc
neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/SamplePT.java
// Path: neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/data/PerformanceTestData.java // public class PerformanceTestData { // // public static final String NEO_URL = "jdbc:neo4j:bolt://localhost:7687?user=neo4j,password=test"; // // /** // * Get a new connection to the external database // * @return // * @throws SQLException // */ // public static Connection getConnection() throws SQLException { // return DriverManager.getConnection(NEO_URL); // } // // /** // * Fill, if needed, the test random data. // * (:A)-[:X]->(:B)-[:Y]->(:C) // * @return true if the DB was empty and the load run // * @throws SQLException // */ // public static boolean loadABCXYData() throws SQLException { // Connection conn = getConnection(); // Statement stmt = conn.createStatement(); // ResultSet rs = stmt.executeQuery("MATCH (n) RETURN n LIMIT 1"); // boolean hasDataLoaded = rs.next(); // rs.close(); // if(hasDataLoaded){ // Statement stmtCheck = conn.createStatement(); // ResultSet checkRs = stmtCheck.executeQuery("MATCH (x:PerformanceTestData) RETURN x LIMIT 1"); // boolean hasTestDataLoaded = checkRs.next(); // if(!hasTestDataLoaded){ // throw new IllegalStateException("The database is loaded without test data. Make sure you are using the correct db at "+NEO_URL); // } // stmtCheck.close(); // } else{ // for (int i = 0; i < 100; i++) { // stmt.executeQuery("CREATE (:A {prop:" + (int) (Math.random() * 100) + "})" + (Math.random() * 10 > 5 ? // "-[:X]->(:B {prop:'" + (int) (Math.random() * 100) + "'})" : // "")); // } // stmt.executeQuery("CREATE (:C)"); // stmt.executeQuery("MATCH (b:B), (c:C) MERGE (c)<-[:Y]-(b)"); // stmt.executeQuery("CREATE (x:PerformanceTestData {when: timestamp()})"); // stmt.close(); // conn.close(); // } // // return !hasDataLoaded; // } // }
import org.junit.Test; import org.mockito.Mockito; import org.neo4j.driver.AuthTokens; import org.neo4j.driver.GraphDatabase; import org.neo4j.driver.Session; import org.neo4j.jdbc.bolt.data.PerformanceTestData; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; import java.io.IOException; import java.io.PrintStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.concurrent.TimeUnit;
/* * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> * Created on 14/03/16 */ package org.neo4j.jdbc.bolt; /** * @author AgileLARUS * @since 3.0.0 */ public class SamplePT { @Test public void launchBenchmark() throws Exception {
// Path: neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/data/PerformanceTestData.java // public class PerformanceTestData { // // public static final String NEO_URL = "jdbc:neo4j:bolt://localhost:7687?user=neo4j,password=test"; // // /** // * Get a new connection to the external database // * @return // * @throws SQLException // */ // public static Connection getConnection() throws SQLException { // return DriverManager.getConnection(NEO_URL); // } // // /** // * Fill, if needed, the test random data. // * (:A)-[:X]->(:B)-[:Y]->(:C) // * @return true if the DB was empty and the load run // * @throws SQLException // */ // public static boolean loadABCXYData() throws SQLException { // Connection conn = getConnection(); // Statement stmt = conn.createStatement(); // ResultSet rs = stmt.executeQuery("MATCH (n) RETURN n LIMIT 1"); // boolean hasDataLoaded = rs.next(); // rs.close(); // if(hasDataLoaded){ // Statement stmtCheck = conn.createStatement(); // ResultSet checkRs = stmtCheck.executeQuery("MATCH (x:PerformanceTestData) RETURN x LIMIT 1"); // boolean hasTestDataLoaded = checkRs.next(); // if(!hasTestDataLoaded){ // throw new IllegalStateException("The database is loaded without test data. Make sure you are using the correct db at "+NEO_URL); // } // stmtCheck.close(); // } else{ // for (int i = 0; i < 100; i++) { // stmt.executeQuery("CREATE (:A {prop:" + (int) (Math.random() * 100) + "})" + (Math.random() * 10 > 5 ? // "-[:X]->(:B {prop:'" + (int) (Math.random() * 100) + "'})" : // "")); // } // stmt.executeQuery("CREATE (:C)"); // stmt.executeQuery("MATCH (b:B), (c:C) MERGE (c)<-[:Y]-(b)"); // stmt.executeQuery("CREATE (x:PerformanceTestData {when: timestamp()})"); // stmt.close(); // conn.close(); // } // // return !hasDataLoaded; // } // } // Path: neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/SamplePT.java import org.junit.Test; import org.mockito.Mockito; import org.neo4j.driver.AuthTokens; import org.neo4j.driver.GraphDatabase; import org.neo4j.driver.Session; import org.neo4j.jdbc.bolt.data.PerformanceTestData; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; import java.io.IOException; import java.io.PrintStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.concurrent.TimeUnit; /* * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> * Created on 14/03/16 */ package org.neo4j.jdbc.bolt; /** * @author AgileLARUS * @since 3.0.0 */ public class SamplePT { @Test public void launchBenchmark() throws Exception {
PerformanceTestData.loadABCXYData();
neo4j-contrib/neo4j-jdbc
neo4j-jdbc/src/test/java/org/neo4j/jdbc/utils/Neo4jPreparedStatementBuilderTest.java
// Path: neo4j-jdbc/src/main/java/org/neo4j/jdbc/utils/PreparedStatementBuilder.java // public static String replacePlaceholders(String raw) { // int index = 1; // String digested = raw; // // String regex = "\\?(?=[^\"]*(?:\"[^\"]*\"[^\"]*)*$)"; // Matcher matcher = Pattern.compile(regex).matcher(digested); // // while (matcher.find()) { // digested = digested.replaceFirst(regex, "\\$" + index); // index++; // } // // return digested; // }
import static org.junit.Assert.assertEquals; import org.junit.Test; import static org.neo4j.jdbc.utils.PreparedStatementBuilder.replacePlaceholders;
/* * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> * Created on 25/03/16 */ package org.neo4j.jdbc.utils; /** * @author AgileLARUS * @since 3.0.0 */ public class Neo4jPreparedStatementBuilderTest { @Test public void replacePlaceholderShouldReturnSameStatementIfNoPlaceholders() { String raw = "MATCH statement RETURN same WHERE thereAreNoPlaceholders";
// Path: neo4j-jdbc/src/main/java/org/neo4j/jdbc/utils/PreparedStatementBuilder.java // public static String replacePlaceholders(String raw) { // int index = 1; // String digested = raw; // // String regex = "\\?(?=[^\"]*(?:\"[^\"]*\"[^\"]*)*$)"; // Matcher matcher = Pattern.compile(regex).matcher(digested); // // while (matcher.find()) { // digested = digested.replaceFirst(regex, "\\$" + index); // index++; // } // // return digested; // } // Path: neo4j-jdbc/src/test/java/org/neo4j/jdbc/utils/Neo4jPreparedStatementBuilderTest.java import static org.junit.Assert.assertEquals; import org.junit.Test; import static org.neo4j.jdbc.utils.PreparedStatementBuilder.replacePlaceholders; /* * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> * Created on 25/03/16 */ package org.neo4j.jdbc.utils; /** * @author AgileLARUS * @since 3.0.0 */ public class Neo4jPreparedStatementBuilderTest { @Test public void replacePlaceholderShouldReturnSameStatementIfNoPlaceholders() { String raw = "MATCH statement RETURN same WHERE thereAreNoPlaceholders";
assertEquals(raw, replacePlaceholders(raw));
neo4j-contrib/neo4j-jdbc
neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/ExecutePT.java
// Path: neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/data/PerformanceTestData.java // public class PerformanceTestData { // // public static final String NEO_URL = "jdbc:neo4j:bolt://localhost:7687?user=neo4j,password=test"; // // /** // * Get a new connection to the external database // * @return // * @throws SQLException // */ // public static Connection getConnection() throws SQLException { // return DriverManager.getConnection(NEO_URL); // } // // /** // * Fill, if needed, the test random data. // * (:A)-[:X]->(:B)-[:Y]->(:C) // * @return true if the DB was empty and the load run // * @throws SQLException // */ // public static boolean loadABCXYData() throws SQLException { // Connection conn = getConnection(); // Statement stmt = conn.createStatement(); // ResultSet rs = stmt.executeQuery("MATCH (n) RETURN n LIMIT 1"); // boolean hasDataLoaded = rs.next(); // rs.close(); // if(hasDataLoaded){ // Statement stmtCheck = conn.createStatement(); // ResultSet checkRs = stmtCheck.executeQuery("MATCH (x:PerformanceTestData) RETURN x LIMIT 1"); // boolean hasTestDataLoaded = checkRs.next(); // if(!hasTestDataLoaded){ // throw new IllegalStateException("The database is loaded without test data. Make sure you are using the correct db at "+NEO_URL); // } // stmtCheck.close(); // } else{ // for (int i = 0; i < 100; i++) { // stmt.executeQuery("CREATE (:A {prop:" + (int) (Math.random() * 100) + "})" + (Math.random() * 10 > 5 ? // "-[:X]->(:B {prop:'" + (int) (Math.random() * 100) + "'})" : // "")); // } // stmt.executeQuery("CREATE (:C)"); // stmt.executeQuery("MATCH (b:B), (c:C) MERGE (c)<-[:Y]-(b)"); // stmt.executeQuery("CREATE (x:PerformanceTestData {when: timestamp()})"); // stmt.close(); // conn.close(); // } // // return !hasDataLoaded; // } // }
import java.util.concurrent.TimeUnit; import org.junit.Test; import org.neo4j.jdbc.bolt.data.PerformanceTestData; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; import java.io.IOException; import java.sql.*;
/* * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> * Created on 14/03/16 */ package org.neo4j.jdbc.bolt; /** * @author AgileLARUS * @since 3.3 * Created by the issue #141 */ public class ExecutePT { @Test public void launchBenchmark() throws Exception {
// Path: neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/data/PerformanceTestData.java // public class PerformanceTestData { // // public static final String NEO_URL = "jdbc:neo4j:bolt://localhost:7687?user=neo4j,password=test"; // // /** // * Get a new connection to the external database // * @return // * @throws SQLException // */ // public static Connection getConnection() throws SQLException { // return DriverManager.getConnection(NEO_URL); // } // // /** // * Fill, if needed, the test random data. // * (:A)-[:X]->(:B)-[:Y]->(:C) // * @return true if the DB was empty and the load run // * @throws SQLException // */ // public static boolean loadABCXYData() throws SQLException { // Connection conn = getConnection(); // Statement stmt = conn.createStatement(); // ResultSet rs = stmt.executeQuery("MATCH (n) RETURN n LIMIT 1"); // boolean hasDataLoaded = rs.next(); // rs.close(); // if(hasDataLoaded){ // Statement stmtCheck = conn.createStatement(); // ResultSet checkRs = stmtCheck.executeQuery("MATCH (x:PerformanceTestData) RETURN x LIMIT 1"); // boolean hasTestDataLoaded = checkRs.next(); // if(!hasTestDataLoaded){ // throw new IllegalStateException("The database is loaded without test data. Make sure you are using the correct db at "+NEO_URL); // } // stmtCheck.close(); // } else{ // for (int i = 0; i < 100; i++) { // stmt.executeQuery("CREATE (:A {prop:" + (int) (Math.random() * 100) + "})" + (Math.random() * 10 > 5 ? // "-[:X]->(:B {prop:'" + (int) (Math.random() * 100) + "'})" : // "")); // } // stmt.executeQuery("CREATE (:C)"); // stmt.executeQuery("MATCH (b:B), (c:C) MERGE (c)<-[:Y]-(b)"); // stmt.executeQuery("CREATE (x:PerformanceTestData {when: timestamp()})"); // stmt.close(); // conn.close(); // } // // return !hasDataLoaded; // } // } // Path: neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/ExecutePT.java import java.util.concurrent.TimeUnit; import org.junit.Test; import org.neo4j.jdbc.bolt.data.PerformanceTestData; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; import java.io.IOException; import java.sql.*; /* * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> * Created on 14/03/16 */ package org.neo4j.jdbc.bolt; /** * @author AgileLARUS * @since 3.3 * Created by the issue #141 */ public class ExecutePT { @Test public void launchBenchmark() throws Exception {
PerformanceTestData.loadABCXYData();
neo4j-contrib/neo4j-jdbc
neo4j-jdbc-bolt/src/test/java/org/neo4j/TestcontainersCausalCluster.java
// Path: neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/utils/Neo4jContainerUtils.java // public static Neo4jContainer<?> createNeo4jContainer() { // return new Neo4jContainer<>(neo4jImageCoordinates()).withEnv("NEO4J_ACCEPT_LICENSE_AGREEMENT", "yes") // .waitingFor(boltStart()) // .withAdminPassword(null); // }
import org.neo4j.driver.AuthTokens; import org.neo4j.driver.Driver; import org.neo4j.driver.GraphDatabase; import org.neo4j.driver.Session; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Neo4jContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy; import org.testcontainers.containers.wait.strategy.WaitStrategy; import java.net.URI; import java.net.URISyntaxException; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.function.Function; import java.util.function.IntFunction; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static org.neo4j.jdbc.bolt.utils.Neo4jContainerUtils.createNeo4jContainer;
Function<GenericContainer<?>, String> getProxyUrl = instance -> String.format("%s:%d", instance.getContainerIpAddress(), instance.getMappedPort(DEFAULT_BOLT_PORT)); return iterateMembers(numberOfCoreMembers, instanceType) .map(name -> getNeo4jContainer(waitForBolt, network, initialDiscoveryMembers, sidecars, getProxyUrl, instanceType, neo4jConfig, name)) .collect(toList()); } private static Map<String, GenericContainer<?>> createSidecars(int numOfMembers, Network network, ClusterInstanceType instanceType) { return iterateMembers(numOfMembers, instanceType) .collect(toMap( Function.identity(), name -> new GenericContainer<>("alpine/socat") .withNetwork(network) .withLabel("memberType", instanceType.toString()) // Expose the default bolt port on the sidecar .withExposedPorts(DEFAULT_BOLT_PORT) // And redirect that port to the corresponding Neo4j instance .withCommand(String .format("tcp-listen:%d,fork,reuseaddr tcp-connect:%s:%1$d", DEFAULT_BOLT_PORT, name)) )); } private static Neo4jContainer<?> getNeo4jContainer(WaitStrategy waitForBolt, Network network, String initialDiscoveryMembers, Map<String, GenericContainer<?>> sidecars, Function<GenericContainer<?>, String> getProxyUrl, ClusterInstanceType instanceType, Map<String, Object> neo4jConfig, String name) {
// Path: neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/utils/Neo4jContainerUtils.java // public static Neo4jContainer<?> createNeo4jContainer() { // return new Neo4jContainer<>(neo4jImageCoordinates()).withEnv("NEO4J_ACCEPT_LICENSE_AGREEMENT", "yes") // .waitingFor(boltStart()) // .withAdminPassword(null); // } // Path: neo4j-jdbc-bolt/src/test/java/org/neo4j/TestcontainersCausalCluster.java import org.neo4j.driver.AuthTokens; import org.neo4j.driver.Driver; import org.neo4j.driver.GraphDatabase; import org.neo4j.driver.Session; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Neo4jContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy; import org.testcontainers.containers.wait.strategy.WaitStrategy; import java.net.URI; import java.net.URISyntaxException; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.function.Function; import java.util.function.IntFunction; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static org.neo4j.jdbc.bolt.utils.Neo4jContainerUtils.createNeo4jContainer; Function<GenericContainer<?>, String> getProxyUrl = instance -> String.format("%s:%d", instance.getContainerIpAddress(), instance.getMappedPort(DEFAULT_BOLT_PORT)); return iterateMembers(numberOfCoreMembers, instanceType) .map(name -> getNeo4jContainer(waitForBolt, network, initialDiscoveryMembers, sidecars, getProxyUrl, instanceType, neo4jConfig, name)) .collect(toList()); } private static Map<String, GenericContainer<?>> createSidecars(int numOfMembers, Network network, ClusterInstanceType instanceType) { return iterateMembers(numOfMembers, instanceType) .collect(toMap( Function.identity(), name -> new GenericContainer<>("alpine/socat") .withNetwork(network) .withLabel("memberType", instanceType.toString()) // Expose the default bolt port on the sidecar .withExposedPorts(DEFAULT_BOLT_PORT) // And redirect that port to the corresponding Neo4j instance .withCommand(String .format("tcp-listen:%d,fork,reuseaddr tcp-connect:%s:%1$d", DEFAULT_BOLT_PORT, name)) )); } private static Neo4jContainer<?> getNeo4jContainer(WaitStrategy waitForBolt, Network network, String initialDiscoveryMembers, Map<String, GenericContainer<?>> sidecars, Function<GenericContainer<?>, String> getProxyUrl, ClusterInstanceType instanceType, Map<String, Object> neo4jConfig, String name) {
Neo4jContainer<?> container = createNeo4jContainer()
neo4j-contrib/neo4j-jdbc
neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/PathSerializer.java
// Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/DataConverterUtils.java // public static Map<String, Object> nodeToMap(Node value) { // Map<String, Object> nodeMap = new LinkedHashMap<>(); // nodeMap.put("_id", value.id()); // nodeMap.put("_labels", value.labels()); // nodeMap.putAll(convertFields(value.asMap())); // return nodeMap; // } // // Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/DataConverterUtils.java // public static Map<String, Object> relationshipToMap(Relationship value) { // Map<String, Object> relMap = new LinkedHashMap<>(); // relMap.put("_id", value.id()); // relMap.put("_type", value.type()); // relMap.put("_startId", value.startNodeId()); // relMap.put("_endId", value.endNodeId()); // relMap.putAll(convertFields(value.asMap())); // return relMap; // }
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.neo4j.driver.types.Path; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.neo4j.jdbc.utils.DataConverterUtils.nodeToMap; import static org.neo4j.jdbc.utils.DataConverterUtils.relationshipToMap;
package org.neo4j.jdbc.utils; public class PathSerializer extends JsonSerializer<Path> { @Override public void serialize(Path value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException { List<Map<String, Object>> list = toPath(value); jsonGenerator.writeObject(list); } public static List<Map<String, Object>> toPath(Path value) { List<Map<String, Object>> list = new ArrayList<>();
// Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/DataConverterUtils.java // public static Map<String, Object> nodeToMap(Node value) { // Map<String, Object> nodeMap = new LinkedHashMap<>(); // nodeMap.put("_id", value.id()); // nodeMap.put("_labels", value.labels()); // nodeMap.putAll(convertFields(value.asMap())); // return nodeMap; // } // // Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/DataConverterUtils.java // public static Map<String, Object> relationshipToMap(Relationship value) { // Map<String, Object> relMap = new LinkedHashMap<>(); // relMap.put("_id", value.id()); // relMap.put("_type", value.type()); // relMap.put("_startId", value.startNodeId()); // relMap.put("_endId", value.endNodeId()); // relMap.putAll(convertFields(value.asMap())); // return relMap; // } // Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/PathSerializer.java import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.neo4j.driver.types.Path; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.neo4j.jdbc.utils.DataConverterUtils.nodeToMap; import static org.neo4j.jdbc.utils.DataConverterUtils.relationshipToMap; package org.neo4j.jdbc.utils; public class PathSerializer extends JsonSerializer<Path> { @Override public void serialize(Path value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException { List<Map<String, Object>> list = toPath(value); jsonGenerator.writeObject(list); } public static List<Map<String, Object>> toPath(Path value) { List<Map<String, Object>> list = new ArrayList<>();
list.add(nodeToMap(value.start()));
neo4j-contrib/neo4j-jdbc
neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/PathSerializer.java
// Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/DataConverterUtils.java // public static Map<String, Object> nodeToMap(Node value) { // Map<String, Object> nodeMap = new LinkedHashMap<>(); // nodeMap.put("_id", value.id()); // nodeMap.put("_labels", value.labels()); // nodeMap.putAll(convertFields(value.asMap())); // return nodeMap; // } // // Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/DataConverterUtils.java // public static Map<String, Object> relationshipToMap(Relationship value) { // Map<String, Object> relMap = new LinkedHashMap<>(); // relMap.put("_id", value.id()); // relMap.put("_type", value.type()); // relMap.put("_startId", value.startNodeId()); // relMap.put("_endId", value.endNodeId()); // relMap.putAll(convertFields(value.asMap())); // return relMap; // }
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.neo4j.driver.types.Path; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.neo4j.jdbc.utils.DataConverterUtils.nodeToMap; import static org.neo4j.jdbc.utils.DataConverterUtils.relationshipToMap;
package org.neo4j.jdbc.utils; public class PathSerializer extends JsonSerializer<Path> { @Override public void serialize(Path value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException { List<Map<String, Object>> list = toPath(value); jsonGenerator.writeObject(list); } public static List<Map<String, Object>> toPath(Path value) { List<Map<String, Object>> list = new ArrayList<>(); list.add(nodeToMap(value.start())); for (Path.Segment s : value) {
// Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/DataConverterUtils.java // public static Map<String, Object> nodeToMap(Node value) { // Map<String, Object> nodeMap = new LinkedHashMap<>(); // nodeMap.put("_id", value.id()); // nodeMap.put("_labels", value.labels()); // nodeMap.putAll(convertFields(value.asMap())); // return nodeMap; // } // // Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/DataConverterUtils.java // public static Map<String, Object> relationshipToMap(Relationship value) { // Map<String, Object> relMap = new LinkedHashMap<>(); // relMap.put("_id", value.id()); // relMap.put("_type", value.type()); // relMap.put("_startId", value.startNodeId()); // relMap.put("_endId", value.endNodeId()); // relMap.putAll(convertFields(value.asMap())); // return relMap; // } // Path: neo4j-jdbc-bolt/src/main/java/org/neo4j/jdbc/utils/PathSerializer.java import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.neo4j.driver.types.Path; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.neo4j.jdbc.utils.DataConverterUtils.nodeToMap; import static org.neo4j.jdbc.utils.DataConverterUtils.relationshipToMap; package org.neo4j.jdbc.utils; public class PathSerializer extends JsonSerializer<Path> { @Override public void serialize(Path value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException { List<Map<String, Object>> list = toPath(value); jsonGenerator.writeObject(list); } public static List<Map<String, Object>> toPath(Path value) { List<Map<String, Object>> list = new ArrayList<>(); list.add(nodeToMap(value.start())); for (Path.Segment s : value) {
list.add(relationshipToMap(s.relationship()));
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/session/handlers/PlatformVersionHandler.java
// Path: src/main/java/org/continuousassurance/swamp/api/Platform.java // public class Platform extends SwampThing { // public Platform(Session session) { // super(session); // } // public Platform(Session session, Map map) { // super(session, map); // } // // @Override // protected SwampThing getNewInstance() { // return new Platform(getSession()); // } // // @Override // public String getIDKey() {return PLATFORM_UUID_KEY;} // public String getName(){return getString(NAME_KEY);} // public void setName(String name){put(NAME_KEY,name);} // public String getPlatformSharingStatus(){return getString(PLATFORM_SHARING_STATUS_KEY);} // public void setPlatformSharingStatus(String sharingStatus){put(PLATFORM_SHARING_STATUS_KEY, sharingStatus);} // public Date getCreateDate(){return getDate(CREATE_DATE_KEY);} // public void setCreateDate(Date createDate){put(CREATE_DATE_KEY, createDate);} // public String getDescription(){return getString(DESCRIPTION_KEY);} // public List<String> getVersions(){return getAsArray(VERSION_STRINGS_KEY);} // /* // public Date getUpdateDate(){return getDate(UPDATE_DATE_KEY);} // public void setUpdateDate(Date updateDate){put(UPDATE_DATE_KEY,updateDate);} // */ // // @Override // public String toString() { // return "Platform[uuid=" + getIdentifier() + ", name=" + getName() + ", create date=" + getCreateDate() + "]"; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // }
import org.continuousassurance.swamp.api.Platform; import org.continuousassurance.swamp.api.PlatformVersion; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import edu.uiuc.ncsa.security.core.exceptions.NotImplementedException; import net.sf.json.JSONObject; import java.util.ArrayList; import java.util.List;
package org.continuousassurance.swamp.session.handlers; /** * <p>Created by Jeff Gaynor<br> * on 12/10/14 at 2:18 PM */ public class PlatformVersionHandler<T extends PlatformVersion> extends AbstractHandler<T> { public PlatformVersionHandler(Session session) { super(session); } @Override public List<T> getAll() { throw new NotImplementedException(); }
// Path: src/main/java/org/continuousassurance/swamp/api/Platform.java // public class Platform extends SwampThing { // public Platform(Session session) { // super(session); // } // public Platform(Session session, Map map) { // super(session, map); // } // // @Override // protected SwampThing getNewInstance() { // return new Platform(getSession()); // } // // @Override // public String getIDKey() {return PLATFORM_UUID_KEY;} // public String getName(){return getString(NAME_KEY);} // public void setName(String name){put(NAME_KEY,name);} // public String getPlatformSharingStatus(){return getString(PLATFORM_SHARING_STATUS_KEY);} // public void setPlatformSharingStatus(String sharingStatus){put(PLATFORM_SHARING_STATUS_KEY, sharingStatus);} // public Date getCreateDate(){return getDate(CREATE_DATE_KEY);} // public void setCreateDate(Date createDate){put(CREATE_DATE_KEY, createDate);} // public String getDescription(){return getString(DESCRIPTION_KEY);} // public List<String> getVersions(){return getAsArray(VERSION_STRINGS_KEY);} // /* // public Date getUpdateDate(){return getDate(UPDATE_DATE_KEY);} // public void setUpdateDate(Date updateDate){put(UPDATE_DATE_KEY,updateDate);} // */ // // @Override // public String toString() { // return "Platform[uuid=" + getIdentifier() + ", name=" + getName() + ", create date=" + getCreateDate() + "]"; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // Path: src/main/java/org/continuousassurance/swamp/session/handlers/PlatformVersionHandler.java import org.continuousassurance.swamp.api.Platform; import org.continuousassurance.swamp.api.PlatformVersion; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import edu.uiuc.ncsa.security.core.exceptions.NotImplementedException; import net.sf.json.JSONObject; import java.util.ArrayList; import java.util.List; package org.continuousassurance.swamp.session.handlers; /** * <p>Created by Jeff Gaynor<br> * on 12/10/14 at 2:18 PM */ public class PlatformVersionHandler<T extends PlatformVersion> extends AbstractHandler<T> { public PlatformVersionHandler(Session session) { super(session); } @Override public List<T> getAll() { throw new NotImplementedException(); }
public List<T> getAll(Platform platform) {
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/session/handlers/PlatformVersionHandler.java
// Path: src/main/java/org/continuousassurance/swamp/api/Platform.java // public class Platform extends SwampThing { // public Platform(Session session) { // super(session); // } // public Platform(Session session, Map map) { // super(session, map); // } // // @Override // protected SwampThing getNewInstance() { // return new Platform(getSession()); // } // // @Override // public String getIDKey() {return PLATFORM_UUID_KEY;} // public String getName(){return getString(NAME_KEY);} // public void setName(String name){put(NAME_KEY,name);} // public String getPlatformSharingStatus(){return getString(PLATFORM_SHARING_STATUS_KEY);} // public void setPlatformSharingStatus(String sharingStatus){put(PLATFORM_SHARING_STATUS_KEY, sharingStatus);} // public Date getCreateDate(){return getDate(CREATE_DATE_KEY);} // public void setCreateDate(Date createDate){put(CREATE_DATE_KEY, createDate);} // public String getDescription(){return getString(DESCRIPTION_KEY);} // public List<String> getVersions(){return getAsArray(VERSION_STRINGS_KEY);} // /* // public Date getUpdateDate(){return getDate(UPDATE_DATE_KEY);} // public void setUpdateDate(Date updateDate){put(UPDATE_DATE_KEY,updateDate);} // */ // // @Override // public String toString() { // return "Platform[uuid=" + getIdentifier() + ", name=" + getName() + ", create date=" + getCreateDate() + "]"; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // }
import org.continuousassurance.swamp.api.Platform; import org.continuousassurance.swamp.api.PlatformVersion; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import edu.uiuc.ncsa.security.core.exceptions.NotImplementedException; import net.sf.json.JSONObject; import java.util.ArrayList; import java.util.List;
package org.continuousassurance.swamp.session.handlers; /** * <p>Created by Jeff Gaynor<br> * on 12/10/14 at 2:18 PM */ public class PlatformVersionHandler<T extends PlatformVersion> extends AbstractHandler<T> { public PlatformVersionHandler(Session session) { super(session); } @Override public List<T> getAll() { throw new NotImplementedException(); } public List<T> getAll(Platform platform) { String url = createURL("platforms/" + platform.getIdentifierString() + "/versions");
// Path: src/main/java/org/continuousassurance/swamp/api/Platform.java // public class Platform extends SwampThing { // public Platform(Session session) { // super(session); // } // public Platform(Session session, Map map) { // super(session, map); // } // // @Override // protected SwampThing getNewInstance() { // return new Platform(getSession()); // } // // @Override // public String getIDKey() {return PLATFORM_UUID_KEY;} // public String getName(){return getString(NAME_KEY);} // public void setName(String name){put(NAME_KEY,name);} // public String getPlatformSharingStatus(){return getString(PLATFORM_SHARING_STATUS_KEY);} // public void setPlatformSharingStatus(String sharingStatus){put(PLATFORM_SHARING_STATUS_KEY, sharingStatus);} // public Date getCreateDate(){return getDate(CREATE_DATE_KEY);} // public void setCreateDate(Date createDate){put(CREATE_DATE_KEY, createDate);} // public String getDescription(){return getString(DESCRIPTION_KEY);} // public List<String> getVersions(){return getAsArray(VERSION_STRINGS_KEY);} // /* // public Date getUpdateDate(){return getDate(UPDATE_DATE_KEY);} // public void setUpdateDate(Date updateDate){put(UPDATE_DATE_KEY,updateDate);} // */ // // @Override // public String toString() { // return "Platform[uuid=" + getIdentifier() + ", name=" + getName() + ", create date=" + getCreateDate() + "]"; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // Path: src/main/java/org/continuousassurance/swamp/session/handlers/PlatformVersionHandler.java import org.continuousassurance.swamp.api.Platform; import org.continuousassurance.swamp.api.PlatformVersion; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import edu.uiuc.ncsa.security.core.exceptions.NotImplementedException; import net.sf.json.JSONObject; import java.util.ArrayList; import java.util.List; package org.continuousassurance.swamp.session.handlers; /** * <p>Created by Jeff Gaynor<br> * on 12/10/14 at 2:18 PM */ public class PlatformVersionHandler<T extends PlatformVersion> extends AbstractHandler<T> { public PlatformVersionHandler(Session session) { super(session); } @Override public List<T> getAll() { throw new NotImplementedException(); } public List<T> getAll(Platform platform) { String url = createURL("platforms/" + platform.getIdentifierString() + "/versions");
MyResponse mr = getClient().rawGet(url, null);
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/api/SwampThing.java
// Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/SWAMPIdentifiers.java // public class SWAMPIdentifiers { // public static String IDENTIFIER_CAPUT = "urn:uuid:"; // // public static Identifier toIdentifier(String x) { // return BasicIdentifier.newID(x); // } // // // public static String fromIdentifier(Identifier identifier) { // if (identifier == null) return null; // String x = identifier.toString(); // return x; // } // }
import edu.uiuc.ncsa.security.core.Identifiable; import edu.uiuc.ncsa.security.core.Identifier; import net.sf.json.JSONArray; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.handlers.PackageVersionHandler; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import org.continuousassurance.swamp.session.util.SWAMPIdentifiers; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Map;
* method below. Any extensions to this class require you to set this flag if there are changes to the data * or they might not be persisted. * * @return */ public boolean isChanged() { return changed; } public void setChanged(boolean changed) { this.changed = changed; } boolean changed = false; @Override public String getIdentifierString() { if (getIdentifier() == null) return null; return getIdentifier().toString(); } /** * Convenience to recover the UUID, such as it is, from the identifier. Note that since the "uuid" is * in general not a valid {@link java.util.UUID}, this is simply a string. * * @return */ public String getUUIDString() { if (getIdentifier() == null) return null;
// Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/SWAMPIdentifiers.java // public class SWAMPIdentifiers { // public static String IDENTIFIER_CAPUT = "urn:uuid:"; // // public static Identifier toIdentifier(String x) { // return BasicIdentifier.newID(x); // } // // // public static String fromIdentifier(Identifier identifier) { // if (identifier == null) return null; // String x = identifier.toString(); // return x; // } // } // Path: src/main/java/org/continuousassurance/swamp/api/SwampThing.java import edu.uiuc.ncsa.security.core.Identifiable; import edu.uiuc.ncsa.security.core.Identifier; import net.sf.json.JSONArray; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.handlers.PackageVersionHandler; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import org.continuousassurance.swamp.session.util.SWAMPIdentifiers; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Map; * method below. Any extensions to this class require you to set this flag if there are changes to the data * or they might not be persisted. * * @return */ public boolean isChanged() { return changed; } public void setChanged(boolean changed) { this.changed = changed; } boolean changed = false; @Override public String getIdentifierString() { if (getIdentifier() == null) return null; return getIdentifier().toString(); } /** * Convenience to recover the UUID, such as it is, from the identifier. Note that since the "uuid" is * in general not a valid {@link java.util.UUID}, this is simply a string. * * @return */ public String getUUIDString() { if (getIdentifier() == null) return null;
return SWAMPIdentifiers.fromIdentifier(getIdentifier());
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/api/SwampThing.java
// Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/SWAMPIdentifiers.java // public class SWAMPIdentifiers { // public static String IDENTIFIER_CAPUT = "urn:uuid:"; // // public static Identifier toIdentifier(String x) { // return BasicIdentifier.newID(x); // } // // // public static String fromIdentifier(Identifier identifier) { // if (identifier == null) return null; // String x = identifier.toString(); // return x; // } // }
import edu.uiuc.ncsa.security.core.Identifiable; import edu.uiuc.ncsa.security.core.Identifier; import net.sf.json.JSONArray; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.handlers.PackageVersionHandler; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import org.continuousassurance.swamp.session.util.SWAMPIdentifiers; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Map;
} /** * Convenience to recover the UUID, such as it is, from the identifier. Note that since the "uuid" is * in general not a valid {@link java.util.UUID}, this is simply a string. * * @return */ public String getUUIDString() { if (getIdentifier() == null) return null; return SWAMPIdentifiers.fromIdentifier(getIdentifier()); } public String getFilename() { return getConversionMap().getString(PackageVersionHandler.FILENAME); } public void setFilename(String filename) { getConversionMap().put(PackageVersionHandler.FILENAME, filename); } /** * An internally used map to manage values and convert between them when they are marshalled or unmarshalled. * This method is public because of Java requirements on visibility to utilities in other packages. Generally * you should not need to access properties for this object through this map. * * @return */
// Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/SWAMPIdentifiers.java // public class SWAMPIdentifiers { // public static String IDENTIFIER_CAPUT = "urn:uuid:"; // // public static Identifier toIdentifier(String x) { // return BasicIdentifier.newID(x); // } // // // public static String fromIdentifier(Identifier identifier) { // if (identifier == null) return null; // String x = identifier.toString(); // return x; // } // } // Path: src/main/java/org/continuousassurance/swamp/api/SwampThing.java import edu.uiuc.ncsa.security.core.Identifiable; import edu.uiuc.ncsa.security.core.Identifier; import net.sf.json.JSONArray; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.handlers.PackageVersionHandler; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import org.continuousassurance.swamp.session.util.SWAMPIdentifiers; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Map; } /** * Convenience to recover the UUID, such as it is, from the identifier. Note that since the "uuid" is * in general not a valid {@link java.util.UUID}, this is simply a string. * * @return */ public String getUUIDString() { if (getIdentifier() == null) return null; return SWAMPIdentifiers.fromIdentifier(getIdentifier()); } public String getFilename() { return getConversionMap().getString(PackageVersionHandler.FILENAME); } public void setFilename(String filename) { getConversionMap().put(PackageVersionHandler.FILENAME, filename); } /** * An internally used map to manage values and convert between them when they are marshalled or unmarshalled. * This method is public because of Java requirements on visibility to utilities in other packages. Generally * you should not need to access properties for this object through this map. * * @return */
public ConversionMapImpl getConversionMap() {
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/session/handlers/PlatformHandler.java
// Path: src/main/java/org/continuousassurance/swamp/api/Platform.java // public class Platform extends SwampThing { // public Platform(Session session) { // super(session); // } // public Platform(Session session, Map map) { // super(session, map); // } // // @Override // protected SwampThing getNewInstance() { // return new Platform(getSession()); // } // // @Override // public String getIDKey() {return PLATFORM_UUID_KEY;} // public String getName(){return getString(NAME_KEY);} // public void setName(String name){put(NAME_KEY,name);} // public String getPlatformSharingStatus(){return getString(PLATFORM_SHARING_STATUS_KEY);} // public void setPlatformSharingStatus(String sharingStatus){put(PLATFORM_SHARING_STATUS_KEY, sharingStatus);} // public Date getCreateDate(){return getDate(CREATE_DATE_KEY);} // public void setCreateDate(Date createDate){put(CREATE_DATE_KEY, createDate);} // public String getDescription(){return getString(DESCRIPTION_KEY);} // public List<String> getVersions(){return getAsArray(VERSION_STRINGS_KEY);} // /* // public Date getUpdateDate(){return getDate(UPDATE_DATE_KEY);} // public void setUpdateDate(Date updateDate){put(UPDATE_DATE_KEY,updateDate);} // */ // // @Override // public String toString() { // return "Platform[uuid=" + getIdentifier() + ", name=" + getName() + ", create date=" + getCreateDate() + "]"; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // }
import net.sf.json.JSONObject; import org.continuousassurance.swamp.api.Platform; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import java.util.ArrayList; import java.util.List;
package org.continuousassurance.swamp.session.handlers; /** * <p>Created by Jeff Gaynor<br> * on 12/10/14 at 2:18 PM */ public class PlatformHandler<T extends Platform> extends AbstractHandler<T> { public PlatformHandler(Session session) { super(session); } public static final String PLATFORM_UUID_KEY = "platform_uuid"; public static final String NAME_KEY = "name"; public static final String DESCRIPTION_KEY = "description"; public static final String VERSION_STRINGS_KEY = "version_strings"; public static final String PLATFORM_SHARING_STATUS_KEY = "platform_sharing_status"; public static final String CREATE_DATE_KEY = "create_date"; public static final String UPDATE_DATE_KEY = "update_date"; @Override public List<T> getAll() { String url = createURL("platforms/public");
// Path: src/main/java/org/continuousassurance/swamp/api/Platform.java // public class Platform extends SwampThing { // public Platform(Session session) { // super(session); // } // public Platform(Session session, Map map) { // super(session, map); // } // // @Override // protected SwampThing getNewInstance() { // return new Platform(getSession()); // } // // @Override // public String getIDKey() {return PLATFORM_UUID_KEY;} // public String getName(){return getString(NAME_KEY);} // public void setName(String name){put(NAME_KEY,name);} // public String getPlatformSharingStatus(){return getString(PLATFORM_SHARING_STATUS_KEY);} // public void setPlatformSharingStatus(String sharingStatus){put(PLATFORM_SHARING_STATUS_KEY, sharingStatus);} // public Date getCreateDate(){return getDate(CREATE_DATE_KEY);} // public void setCreateDate(Date createDate){put(CREATE_DATE_KEY, createDate);} // public String getDescription(){return getString(DESCRIPTION_KEY);} // public List<String> getVersions(){return getAsArray(VERSION_STRINGS_KEY);} // /* // public Date getUpdateDate(){return getDate(UPDATE_DATE_KEY);} // public void setUpdateDate(Date updateDate){put(UPDATE_DATE_KEY,updateDate);} // */ // // @Override // public String toString() { // return "Platform[uuid=" + getIdentifier() + ", name=" + getName() + ", create date=" + getCreateDate() + "]"; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // Path: src/main/java/org/continuousassurance/swamp/session/handlers/PlatformHandler.java import net.sf.json.JSONObject; import org.continuousassurance.swamp.api.Platform; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import java.util.ArrayList; import java.util.List; package org.continuousassurance.swamp.session.handlers; /** * <p>Created by Jeff Gaynor<br> * on 12/10/14 at 2:18 PM */ public class PlatformHandler<T extends Platform> extends AbstractHandler<T> { public PlatformHandler(Session session) { super(session); } public static final String PLATFORM_UUID_KEY = "platform_uuid"; public static final String NAME_KEY = "name"; public static final String DESCRIPTION_KEY = "description"; public static final String VERSION_STRINGS_KEY = "version_strings"; public static final String PLATFORM_SHARING_STATUS_KEY = "platform_sharing_status"; public static final String CREATE_DATE_KEY = "create_date"; public static final String UPDATE_DATE_KEY = "update_date"; @Override public List<T> getAll() { String url = createURL("platforms/public");
MyResponse mr = getClient().rawGet(url, null);
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/session/handlers/PlatformHandler.java
// Path: src/main/java/org/continuousassurance/swamp/api/Platform.java // public class Platform extends SwampThing { // public Platform(Session session) { // super(session); // } // public Platform(Session session, Map map) { // super(session, map); // } // // @Override // protected SwampThing getNewInstance() { // return new Platform(getSession()); // } // // @Override // public String getIDKey() {return PLATFORM_UUID_KEY;} // public String getName(){return getString(NAME_KEY);} // public void setName(String name){put(NAME_KEY,name);} // public String getPlatformSharingStatus(){return getString(PLATFORM_SHARING_STATUS_KEY);} // public void setPlatformSharingStatus(String sharingStatus){put(PLATFORM_SHARING_STATUS_KEY, sharingStatus);} // public Date getCreateDate(){return getDate(CREATE_DATE_KEY);} // public void setCreateDate(Date createDate){put(CREATE_DATE_KEY, createDate);} // public String getDescription(){return getString(DESCRIPTION_KEY);} // public List<String> getVersions(){return getAsArray(VERSION_STRINGS_KEY);} // /* // public Date getUpdateDate(){return getDate(UPDATE_DATE_KEY);} // public void setUpdateDate(Date updateDate){put(UPDATE_DATE_KEY,updateDate);} // */ // // @Override // public String toString() { // return "Platform[uuid=" + getIdentifier() + ", name=" + getName() + ", create date=" + getCreateDate() + "]"; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // }
import net.sf.json.JSONObject; import org.continuousassurance.swamp.api.Platform; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import java.util.ArrayList; import java.util.List;
package org.continuousassurance.swamp.session.handlers; /** * <p>Created by Jeff Gaynor<br> * on 12/10/14 at 2:18 PM */ public class PlatformHandler<T extends Platform> extends AbstractHandler<T> { public PlatformHandler(Session session) { super(session); } public static final String PLATFORM_UUID_KEY = "platform_uuid"; public static final String NAME_KEY = "name"; public static final String DESCRIPTION_KEY = "description"; public static final String VERSION_STRINGS_KEY = "version_strings"; public static final String PLATFORM_SHARING_STATUS_KEY = "platform_sharing_status"; public static final String CREATE_DATE_KEY = "create_date"; public static final String UPDATE_DATE_KEY = "update_date"; @Override public List<T> getAll() { String url = createURL("platforms/public"); MyResponse mr = getClient().rawGet(url, null); ArrayList<T> platforms = new ArrayList<>(); for (int i = 0; i < mr.jsonArray.size(); i++) { JSONObject json = mr.jsonArray.getJSONObject(i); platforms.add(fromJSON(json)); } return platforms; } protected T fromJSON(JSONObject json) { T platform = (T) new Platform(getSession());
// Path: src/main/java/org/continuousassurance/swamp/api/Platform.java // public class Platform extends SwampThing { // public Platform(Session session) { // super(session); // } // public Platform(Session session, Map map) { // super(session, map); // } // // @Override // protected SwampThing getNewInstance() { // return new Platform(getSession()); // } // // @Override // public String getIDKey() {return PLATFORM_UUID_KEY;} // public String getName(){return getString(NAME_KEY);} // public void setName(String name){put(NAME_KEY,name);} // public String getPlatformSharingStatus(){return getString(PLATFORM_SHARING_STATUS_KEY);} // public void setPlatformSharingStatus(String sharingStatus){put(PLATFORM_SHARING_STATUS_KEY, sharingStatus);} // public Date getCreateDate(){return getDate(CREATE_DATE_KEY);} // public void setCreateDate(Date createDate){put(CREATE_DATE_KEY, createDate);} // public String getDescription(){return getString(DESCRIPTION_KEY);} // public List<String> getVersions(){return getAsArray(VERSION_STRINGS_KEY);} // /* // public Date getUpdateDate(){return getDate(UPDATE_DATE_KEY);} // public void setUpdateDate(Date updateDate){put(UPDATE_DATE_KEY,updateDate);} // */ // // @Override // public String toString() { // return "Platform[uuid=" + getIdentifier() + ", name=" + getName() + ", create date=" + getCreateDate() + "]"; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // Path: src/main/java/org/continuousassurance/swamp/session/handlers/PlatformHandler.java import net.sf.json.JSONObject; import org.continuousassurance.swamp.api.Platform; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import java.util.ArrayList; import java.util.List; package org.continuousassurance.swamp.session.handlers; /** * <p>Created by Jeff Gaynor<br> * on 12/10/14 at 2:18 PM */ public class PlatformHandler<T extends Platform> extends AbstractHandler<T> { public PlatformHandler(Session session) { super(session); } public static final String PLATFORM_UUID_KEY = "platform_uuid"; public static final String NAME_KEY = "name"; public static final String DESCRIPTION_KEY = "description"; public static final String VERSION_STRINGS_KEY = "version_strings"; public static final String PLATFORM_SHARING_STATUS_KEY = "platform_sharing_status"; public static final String CREATE_DATE_KEY = "create_date"; public static final String UPDATE_DATE_KEY = "update_date"; @Override public List<T> getAll() { String url = createURL("platforms/public"); MyResponse mr = getClient().rawGet(url, null); ArrayList<T> platforms = new ArrayList<>(); for (int i = 0; i < mr.jsonArray.size(); i++) { JSONObject json = mr.jsonArray.getJSONObject(i); platforms.add(fromJSON(json)); } return platforms; } protected T fromJSON(JSONObject json) { T platform = (T) new Platform(getSession());
ConversionMapImpl map = new ConversionMapImpl();
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/api/Project.java
// Path: src/main/java/org/continuousassurance/swamp/session/handlers/UserHandler.java // public static final String USER_UID_KEY = "user_uid";
import org.continuousassurance.swamp.session.Session; import java.util.Date; import java.util.Map; import static org.continuousassurance.swamp.session.handlers.ProjectHandler.*; import static org.continuousassurance.swamp.session.handlers.UserHandler.USER_UID_KEY;
public void setAffiliation(String affiliation) { put(AFFILIATION_KEY, affiliation); } public Date getCreateDate() { return getDate(CREATE_DATE_KEY); } public void setCreateDate(Date createDate) { put(CREATE_DATE_KEY, createDate); } public Date getDenialDate() { return getDate(DENIAL_DATE_KEY); } public void setDenialDate(Date denialDate) { put(DENIAL_DATE_KEY, denialDate); } public Date getDeactivationDate() { return getDate((DEACTIVATION_DATE_KEY)); } public void setDeactivationDate(Date deactivationDate) { put(DEACTIVATION_DATE_KEY, deactivationDate); } public String getOwnerUUID() {
// Path: src/main/java/org/continuousassurance/swamp/session/handlers/UserHandler.java // public static final String USER_UID_KEY = "user_uid"; // Path: src/main/java/org/continuousassurance/swamp/api/Project.java import org.continuousassurance.swamp.session.Session; import java.util.Date; import java.util.Map; import static org.continuousassurance.swamp.session.handlers.ProjectHandler.*; import static org.continuousassurance.swamp.session.handlers.UserHandler.USER_UID_KEY; public void setAffiliation(String affiliation) { put(AFFILIATION_KEY, affiliation); } public Date getCreateDate() { return getDate(CREATE_DATE_KEY); } public void setCreateDate(Date createDate) { put(CREATE_DATE_KEY, createDate); } public Date getDenialDate() { return getDate(DENIAL_DATE_KEY); } public void setDenialDate(Date denialDate) { put(DENIAL_DATE_KEY, denialDate); } public Date getDeactivationDate() { return getDate((DEACTIVATION_DATE_KEY)); } public void setDeactivationDate(Date deactivationDate) { put(DEACTIVATION_DATE_KEY, deactivationDate); } public String getOwnerUUID() {
return getString(USER_UID_KEY);
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/session/handlers/AssessmentRunHandler.java
// Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/SWAMPIdentifiers.java // public class SWAMPIdentifiers { // public static String IDENTIFIER_CAPUT = "urn:uuid:"; // // public static Identifier toIdentifier(String x) { // return BasicIdentifier.newID(x); // } // // // public static String fromIdentifier(Identifier identifier) { // if (identifier == null) return null; // String x = identifier.toString(); // return x; // } // }
import edu.uiuc.ncsa.security.core.Identifier; import org.continuousassurance.swamp.api.*; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import org.continuousassurance.swamp.session.util.SWAMPIdentifiers; import net.sf.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
public void setProjectHandler(ProjectHandler<? extends Project> projectHandler) { this.projectHandler = projectHandler; } ProjectHandler<? extends Project> projectHandler; /** * Caution: This gets every assessment for every project that the current user has. It is more * efficient to get assessments per project by using {@link #getAllAssessments(Project)}. * * @return */ @Override public List<T> getAll() { List<? extends Project> projects = getProjectHandler().getAll(); List<T> assessments = new ArrayList<>(); for (Project project : projects) { assessments.addAll(getAllAssessments(project)); } return assessments; } public AssessmentRun create(Project project, PackageThing pkg, Platform platform, Tool tool) { String url = createURL("assessment_runs"); HashMap<String, Object> parameters = new HashMap<>(); parameters.put("project_uuid", project.getUUIDString()); parameters.put(PackageHandler.PACKAGE_UUID_KEY, pkg.getUUIDString()); parameters.put(PlatformHandler.PLATFORM_UUID_KEY, platform.getUUIDString()); parameters.put(ToolHandler.TOOL_UUID_KEY, tool.getUUIDString());
// Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/SWAMPIdentifiers.java // public class SWAMPIdentifiers { // public static String IDENTIFIER_CAPUT = "urn:uuid:"; // // public static Identifier toIdentifier(String x) { // return BasicIdentifier.newID(x); // } // // // public static String fromIdentifier(Identifier identifier) { // if (identifier == null) return null; // String x = identifier.toString(); // return x; // } // } // Path: src/main/java/org/continuousassurance/swamp/session/handlers/AssessmentRunHandler.java import edu.uiuc.ncsa.security.core.Identifier; import org.continuousassurance.swamp.api.*; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import org.continuousassurance.swamp.session.util.SWAMPIdentifiers; import net.sf.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public void setProjectHandler(ProjectHandler<? extends Project> projectHandler) { this.projectHandler = projectHandler; } ProjectHandler<? extends Project> projectHandler; /** * Caution: This gets every assessment for every project that the current user has. It is more * efficient to get assessments per project by using {@link #getAllAssessments(Project)}. * * @return */ @Override public List<T> getAll() { List<? extends Project> projects = getProjectHandler().getAll(); List<T> assessments = new ArrayList<>(); for (Project project : projects) { assessments.addAll(getAllAssessments(project)); } return assessments; } public AssessmentRun create(Project project, PackageThing pkg, Platform platform, Tool tool) { String url = createURL("assessment_runs"); HashMap<String, Object> parameters = new HashMap<>(); parameters.put("project_uuid", project.getUUIDString()); parameters.put(PackageHandler.PACKAGE_UUID_KEY, pkg.getUUIDString()); parameters.put(PlatformHandler.PLATFORM_UUID_KEY, platform.getUUIDString()); parameters.put(ToolHandler.TOOL_UUID_KEY, tool.getUUIDString());
MyResponse myResponse = getClient().rawPost(url, parameters);
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/session/handlers/AssessmentRunHandler.java
// Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/SWAMPIdentifiers.java // public class SWAMPIdentifiers { // public static String IDENTIFIER_CAPUT = "urn:uuid:"; // // public static Identifier toIdentifier(String x) { // return BasicIdentifier.newID(x); // } // // // public static String fromIdentifier(Identifier identifier) { // if (identifier == null) return null; // String x = identifier.toString(); // return x; // } // }
import edu.uiuc.ncsa.security.core.Identifier; import org.continuousassurance.swamp.api.*; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import org.continuousassurance.swamp.session.util.SWAMPIdentifiers; import net.sf.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
result.setPkg(pkg_ver.getPackageThing()); result.setPlatform(platform_version.getPlatform()); result.setPlatformVersion(platform_version); result.setTool(tool); return result; } public AssessmentRun create(Project project, PackageVersion pkg_ver, PlatformVersion platform_version, ToolVersion tool_version) { String url = createURL("assessment_runs"); HashMap<String, Object> parameters = new HashMap<>(); parameters.put("project_uuid", project.getUUIDString()); parameters.put("package_version_uuid", pkg_ver.getUUIDString()); parameters.put(PackageHandler.PACKAGE_UUID_KEY, pkg_ver.getPackageThing().getUUIDString()); //parameters.put(PLATFORM_UUID_KEY, platform_version.getUUIDString()); parameters.put(PlatformVersion.PLATFORM_UUID_KEY, platform_version.getPlatform().getUUIDString()); parameters.put(PlatformVersion.PLATFORM_VERSION_UUID_KEY, platform_version.getUUIDString()); parameters.put(ToolHandler.TOOL_UUID_KEY, tool_version.getTool().getUUIDString()); parameters.put(TOOL_VERSION_UUID, tool_version.getUUIDString()); MyResponse myResponse = getClient().rawPost(url, parameters); AssessmentRun result = fromJSON(myResponse.json); result.setProject(project); result.setPkg(pkg_ver.getPackageThing()); result.setPlatform(platform_version.getPlatform()); result.setPlatformVersion(platform_version); result.setTool(tool_version.getTool()); return result; } public T get(Identifier identifier) {
// Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/SWAMPIdentifiers.java // public class SWAMPIdentifiers { // public static String IDENTIFIER_CAPUT = "urn:uuid:"; // // public static Identifier toIdentifier(String x) { // return BasicIdentifier.newID(x); // } // // // public static String fromIdentifier(Identifier identifier) { // if (identifier == null) return null; // String x = identifier.toString(); // return x; // } // } // Path: src/main/java/org/continuousassurance/swamp/session/handlers/AssessmentRunHandler.java import edu.uiuc.ncsa.security.core.Identifier; import org.continuousassurance.swamp.api.*; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import org.continuousassurance.swamp.session.util.SWAMPIdentifiers; import net.sf.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; result.setPkg(pkg_ver.getPackageThing()); result.setPlatform(platform_version.getPlatform()); result.setPlatformVersion(platform_version); result.setTool(tool); return result; } public AssessmentRun create(Project project, PackageVersion pkg_ver, PlatformVersion platform_version, ToolVersion tool_version) { String url = createURL("assessment_runs"); HashMap<String, Object> parameters = new HashMap<>(); parameters.put("project_uuid", project.getUUIDString()); parameters.put("package_version_uuid", pkg_ver.getUUIDString()); parameters.put(PackageHandler.PACKAGE_UUID_KEY, pkg_ver.getPackageThing().getUUIDString()); //parameters.put(PLATFORM_UUID_KEY, platform_version.getUUIDString()); parameters.put(PlatformVersion.PLATFORM_UUID_KEY, platform_version.getPlatform().getUUIDString()); parameters.put(PlatformVersion.PLATFORM_VERSION_UUID_KEY, platform_version.getUUIDString()); parameters.put(ToolHandler.TOOL_UUID_KEY, tool_version.getTool().getUUIDString()); parameters.put(TOOL_VERSION_UUID, tool_version.getUUIDString()); MyResponse myResponse = getClient().rawPost(url, parameters); AssessmentRun result = fromJSON(myResponse.json); result.setProject(project); result.setPkg(pkg_ver.getPackageThing()); result.setPlatform(platform_version.getPlatform()); result.setPlatformVersion(platform_version); result.setTool(tool_version.getTool()); return result; } public T get(Identifier identifier) {
String url = createURL("assessment_runs/" + SWAMPIdentifiers.fromIdentifier(identifier));
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/session/handlers/AssessmentRunHandler.java
// Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/SWAMPIdentifiers.java // public class SWAMPIdentifiers { // public static String IDENTIFIER_CAPUT = "urn:uuid:"; // // public static Identifier toIdentifier(String x) { // return BasicIdentifier.newID(x); // } // // // public static String fromIdentifier(Identifier identifier) { // if (identifier == null) return null; // String x = identifier.toString(); // return x; // } // }
import edu.uiuc.ncsa.security.core.Identifier; import org.continuousassurance.swamp.api.*; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import org.continuousassurance.swamp.session.util.SWAMPIdentifiers; import net.sf.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
MyResponse mr = getClient().rawGet(url, null); ArrayList<T> assessments = new ArrayList<>(); for (int i = 0; i < mr.jsonArray.size(); i++) { JSONObject jo = mr.jsonArray.getJSONObject(i); T a = fromJSON(jo); //(T) new AssessmentRun(getSession()); Object v = jo.get(ASSESSMENT_RUN_UUID); // this is actually the uuid of the assessment run. a.setIdentifier(SWAMPIdentifiers.toIdentifier(v.toString())); a.setProject(project); assessments.add(a); } return assessments; } public List<? extends AssessmentRun> getAssessments(Project project) { String pUrl = createURL("projects/" + project.getUUIDString() + "/assessment_runs"); // need to get this from the same server that has the assessments, not the projects server. MyResponse mr0 = getClient().rawGet(pUrl, null); ArrayList<T> list = new ArrayList<>(); for(int i = 0; i < mr0.jsonArray.size(); i++){ T a = fromJSON((JSONObject) mr0.jsonArray.get(i)); list.add(a); } return list; } @Override protected T fromJSON(JSONObject json) { T a = (T) new AssessmentRun(getSession());
// Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/SWAMPIdentifiers.java // public class SWAMPIdentifiers { // public static String IDENTIFIER_CAPUT = "urn:uuid:"; // // public static Identifier toIdentifier(String x) { // return BasicIdentifier.newID(x); // } // // // public static String fromIdentifier(Identifier identifier) { // if (identifier == null) return null; // String x = identifier.toString(); // return x; // } // } // Path: src/main/java/org/continuousassurance/swamp/session/handlers/AssessmentRunHandler.java import edu.uiuc.ncsa.security.core.Identifier; import org.continuousassurance.swamp.api.*; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import org.continuousassurance.swamp.session.util.SWAMPIdentifiers; import net.sf.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; MyResponse mr = getClient().rawGet(url, null); ArrayList<T> assessments = new ArrayList<>(); for (int i = 0; i < mr.jsonArray.size(); i++) { JSONObject jo = mr.jsonArray.getJSONObject(i); T a = fromJSON(jo); //(T) new AssessmentRun(getSession()); Object v = jo.get(ASSESSMENT_RUN_UUID); // this is actually the uuid of the assessment run. a.setIdentifier(SWAMPIdentifiers.toIdentifier(v.toString())); a.setProject(project); assessments.add(a); } return assessments; } public List<? extends AssessmentRun> getAssessments(Project project) { String pUrl = createURL("projects/" + project.getUUIDString() + "/assessment_runs"); // need to get this from the same server that has the assessments, not the projects server. MyResponse mr0 = getClient().rawGet(pUrl, null); ArrayList<T> list = new ArrayList<>(); for(int i = 0; i < mr0.jsonArray.size(); i++){ T a = fromJSON((JSONObject) mr0.jsonArray.get(i)); list.add(a); } return list; } @Override protected T fromJSON(JSONObject json) { T a = (T) new AssessmentRun(getSession());
ConversionMapImpl map = new ConversionMapImpl();
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/client/commands/ProjectCommands.java
// Path: src/main/java/org/continuousassurance/swamp/api/Project.java // public class Project extends SwampThing { // // // @Override // protected SwampThing getNewInstance() { // return new Project(getSession()); // } // // @Override // public String getIDKey() { // return PROJECT_UID_KEY; // } // // // public Project(Session session) { // super(session); // } // public Project(Session session, Map map) { // super(session, map); // } // // // public String getDescription() { // return getString(DESCRIPTION_KEY); // } // // public void setDescription(String description) { // put(DESCRIPTION_KEY, description); // } // // public String getFullName() { // return getString(FULL_NAME_KEY); // } // // public void setFullName(String fullName) { // put(FULL_NAME_KEY, fullName); // } // // // public String getShortName() { // return getString(SHORT_NAME_KEY); // } // // public void setShortName(String shortName) { // put(SHORT_NAME_KEY, shortName); // } // // public String getAffiliation() { // return getString(AFFILIATION_KEY); // } // // public void setAffiliation(String affiliation) { // put(AFFILIATION_KEY, affiliation); // } // // public Date getCreateDate() { // return getDate(CREATE_DATE_KEY); // } // // public void setCreateDate(Date createDate) { // put(CREATE_DATE_KEY, createDate); // } // // public Date getDenialDate() { // return getDate(DENIAL_DATE_KEY); // } // // public void setDenialDate(Date denialDate) { // put(DENIAL_DATE_KEY, denialDate); // } // // public Date getDeactivationDate() { // return getDate((DEACTIVATION_DATE_KEY)); // } // // public void setDeactivationDate(Date deactivationDate) { // put(DEACTIVATION_DATE_KEY, deactivationDate); // } // // public String getOwnerUUID() { // return getString(USER_UID_KEY); // } // // public void setOwnerUUID(String ownerUUID) { // put(USER_UID_KEY, ownerUUID); // } // // public boolean isTrialProjectFlag() { // return getBoolean(TRIAL_PROJECT_FLAG_KEY); // } // // public void setTrialProjectFlag(boolean trialProjectFlag) { // put(TRIAL_PROJECT_FLAG_KEY, trialProjectFlag); // } // // @Override // public String toString() { // return "Project[name=" + getFullName() + ",description=" + getDescription() + ", owner id=" + getOwnerUUID() + // ", create date=" + getCreateDate() + ", uuid=" + getIdentifier() + "]"; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/storage/ProjectStore.java // public class ProjectStore<V extends Project> extends AbstractStore<V> { // ProjectHandler<V> projectHandler; // // public ProjectStore(ProjectHandler<V> projectHandler) { // super(projectHandler); // } // // @Override // public V create() { // //return null; // return (V) new Project(projectHandler.getSession()); // // } // }
import edu.uiuc.ncsa.security.core.Identifiable; import edu.uiuc.ncsa.security.core.Store; import edu.uiuc.ncsa.security.core.util.Iso8601; import edu.uiuc.ncsa.security.core.util.MyLoggingFacade; import org.continuousassurance.swamp.api.Project; import org.continuousassurance.swamp.session.storage.ProjectStore;
package org.continuousassurance.swamp.client.commands; /** * <p>Created by Jeff Gaynor<br> * on 4/11/16 at 2:55 PM */ public class ProjectCommands extends SWAMPStoreCommands { public ProjectCommands(MyLoggingFacade logger, String defaultIndent, Store store) { super(logger, defaultIndent, store); } public ProjectCommands(MyLoggingFacade logger, Store store) { super(logger, store); }
// Path: src/main/java/org/continuousassurance/swamp/api/Project.java // public class Project extends SwampThing { // // // @Override // protected SwampThing getNewInstance() { // return new Project(getSession()); // } // // @Override // public String getIDKey() { // return PROJECT_UID_KEY; // } // // // public Project(Session session) { // super(session); // } // public Project(Session session, Map map) { // super(session, map); // } // // // public String getDescription() { // return getString(DESCRIPTION_KEY); // } // // public void setDescription(String description) { // put(DESCRIPTION_KEY, description); // } // // public String getFullName() { // return getString(FULL_NAME_KEY); // } // // public void setFullName(String fullName) { // put(FULL_NAME_KEY, fullName); // } // // // public String getShortName() { // return getString(SHORT_NAME_KEY); // } // // public void setShortName(String shortName) { // put(SHORT_NAME_KEY, shortName); // } // // public String getAffiliation() { // return getString(AFFILIATION_KEY); // } // // public void setAffiliation(String affiliation) { // put(AFFILIATION_KEY, affiliation); // } // // public Date getCreateDate() { // return getDate(CREATE_DATE_KEY); // } // // public void setCreateDate(Date createDate) { // put(CREATE_DATE_KEY, createDate); // } // // public Date getDenialDate() { // return getDate(DENIAL_DATE_KEY); // } // // public void setDenialDate(Date denialDate) { // put(DENIAL_DATE_KEY, denialDate); // } // // public Date getDeactivationDate() { // return getDate((DEACTIVATION_DATE_KEY)); // } // // public void setDeactivationDate(Date deactivationDate) { // put(DEACTIVATION_DATE_KEY, deactivationDate); // } // // public String getOwnerUUID() { // return getString(USER_UID_KEY); // } // // public void setOwnerUUID(String ownerUUID) { // put(USER_UID_KEY, ownerUUID); // } // // public boolean isTrialProjectFlag() { // return getBoolean(TRIAL_PROJECT_FLAG_KEY); // } // // public void setTrialProjectFlag(boolean trialProjectFlag) { // put(TRIAL_PROJECT_FLAG_KEY, trialProjectFlag); // } // // @Override // public String toString() { // return "Project[name=" + getFullName() + ",description=" + getDescription() + ", owner id=" + getOwnerUUID() + // ", create date=" + getCreateDate() + ", uuid=" + getIdentifier() + "]"; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/storage/ProjectStore.java // public class ProjectStore<V extends Project> extends AbstractStore<V> { // ProjectHandler<V> projectHandler; // // public ProjectStore(ProjectHandler<V> projectHandler) { // super(projectHandler); // } // // @Override // public V create() { // //return null; // return (V) new Project(projectHandler.getSession()); // // } // } // Path: src/main/java/org/continuousassurance/swamp/client/commands/ProjectCommands.java import edu.uiuc.ncsa.security.core.Identifiable; import edu.uiuc.ncsa.security.core.Store; import edu.uiuc.ncsa.security.core.util.Iso8601; import edu.uiuc.ncsa.security.core.util.MyLoggingFacade; import org.continuousassurance.swamp.api.Project; import org.continuousassurance.swamp.session.storage.ProjectStore; package org.continuousassurance.swamp.client.commands; /** * <p>Created by Jeff Gaynor<br> * on 4/11/16 at 2:55 PM */ public class ProjectCommands extends SWAMPStoreCommands { public ProjectCommands(MyLoggingFacade logger, String defaultIndent, Store store) { super(logger, defaultIndent, store); } public ProjectCommands(MyLoggingFacade logger, Store store) { super(logger, store); }
protected ProjectStore getProjectStore(){
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/client/commands/ProjectCommands.java
// Path: src/main/java/org/continuousassurance/swamp/api/Project.java // public class Project extends SwampThing { // // // @Override // protected SwampThing getNewInstance() { // return new Project(getSession()); // } // // @Override // public String getIDKey() { // return PROJECT_UID_KEY; // } // // // public Project(Session session) { // super(session); // } // public Project(Session session, Map map) { // super(session, map); // } // // // public String getDescription() { // return getString(DESCRIPTION_KEY); // } // // public void setDescription(String description) { // put(DESCRIPTION_KEY, description); // } // // public String getFullName() { // return getString(FULL_NAME_KEY); // } // // public void setFullName(String fullName) { // put(FULL_NAME_KEY, fullName); // } // // // public String getShortName() { // return getString(SHORT_NAME_KEY); // } // // public void setShortName(String shortName) { // put(SHORT_NAME_KEY, shortName); // } // // public String getAffiliation() { // return getString(AFFILIATION_KEY); // } // // public void setAffiliation(String affiliation) { // put(AFFILIATION_KEY, affiliation); // } // // public Date getCreateDate() { // return getDate(CREATE_DATE_KEY); // } // // public void setCreateDate(Date createDate) { // put(CREATE_DATE_KEY, createDate); // } // // public Date getDenialDate() { // return getDate(DENIAL_DATE_KEY); // } // // public void setDenialDate(Date denialDate) { // put(DENIAL_DATE_KEY, denialDate); // } // // public Date getDeactivationDate() { // return getDate((DEACTIVATION_DATE_KEY)); // } // // public void setDeactivationDate(Date deactivationDate) { // put(DEACTIVATION_DATE_KEY, deactivationDate); // } // // public String getOwnerUUID() { // return getString(USER_UID_KEY); // } // // public void setOwnerUUID(String ownerUUID) { // put(USER_UID_KEY, ownerUUID); // } // // public boolean isTrialProjectFlag() { // return getBoolean(TRIAL_PROJECT_FLAG_KEY); // } // // public void setTrialProjectFlag(boolean trialProjectFlag) { // put(TRIAL_PROJECT_FLAG_KEY, trialProjectFlag); // } // // @Override // public String toString() { // return "Project[name=" + getFullName() + ",description=" + getDescription() + ", owner id=" + getOwnerUUID() + // ", create date=" + getCreateDate() + ", uuid=" + getIdentifier() + "]"; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/storage/ProjectStore.java // public class ProjectStore<V extends Project> extends AbstractStore<V> { // ProjectHandler<V> projectHandler; // // public ProjectStore(ProjectHandler<V> projectHandler) { // super(projectHandler); // } // // @Override // public V create() { // //return null; // return (V) new Project(projectHandler.getSession()); // // } // }
import edu.uiuc.ncsa.security.core.Identifiable; import edu.uiuc.ncsa.security.core.Store; import edu.uiuc.ncsa.security.core.util.Iso8601; import edu.uiuc.ncsa.security.core.util.MyLoggingFacade; import org.continuousassurance.swamp.api.Project; import org.continuousassurance.swamp.session.storage.ProjectStore;
package org.continuousassurance.swamp.client.commands; /** * <p>Created by Jeff Gaynor<br> * on 4/11/16 at 2:55 PM */ public class ProjectCommands extends SWAMPStoreCommands { public ProjectCommands(MyLoggingFacade logger, String defaultIndent, Store store) { super(logger, defaultIndent, store); } public ProjectCommands(MyLoggingFacade logger, Store store) { super(logger, store); } protected ProjectStore getProjectStore(){ return (ProjectStore)getStore(); } @Override public String getPrompt() { return "projects>"; } @Override public void extraUpdates(Identifiable identifiable) { } /* protected void showResultsHelp() { say("Shows the assessment results for this package."); say("Syntax is "); say("results index|uid"); say(""); } public void results(InputLine inputLine) { if (showHelp(inputLine)) { showResultsHelp(); return; } Project p = null; if (inputLine.size() == 1) { say("You must supply the index or id of the item to update"); return; } Identifiable identifiable = findItem(inputLine); if (identifiable != null) { p = (Project) identifiable; List<AssessmentResults> ars = getProjectStore().getAssessmentResults(p); say(" There are " + ars.size() + " assessment results."); for(AssessmentResults ar : ars){ // ar. } } else { say("Sorry, project not found"); } }*/ @Override public String getName() { return defaultIndent + "projects"; } @Override public boolean update(Identifiable identifiable) {
// Path: src/main/java/org/continuousassurance/swamp/api/Project.java // public class Project extends SwampThing { // // // @Override // protected SwampThing getNewInstance() { // return new Project(getSession()); // } // // @Override // public String getIDKey() { // return PROJECT_UID_KEY; // } // // // public Project(Session session) { // super(session); // } // public Project(Session session, Map map) { // super(session, map); // } // // // public String getDescription() { // return getString(DESCRIPTION_KEY); // } // // public void setDescription(String description) { // put(DESCRIPTION_KEY, description); // } // // public String getFullName() { // return getString(FULL_NAME_KEY); // } // // public void setFullName(String fullName) { // put(FULL_NAME_KEY, fullName); // } // // // public String getShortName() { // return getString(SHORT_NAME_KEY); // } // // public void setShortName(String shortName) { // put(SHORT_NAME_KEY, shortName); // } // // public String getAffiliation() { // return getString(AFFILIATION_KEY); // } // // public void setAffiliation(String affiliation) { // put(AFFILIATION_KEY, affiliation); // } // // public Date getCreateDate() { // return getDate(CREATE_DATE_KEY); // } // // public void setCreateDate(Date createDate) { // put(CREATE_DATE_KEY, createDate); // } // // public Date getDenialDate() { // return getDate(DENIAL_DATE_KEY); // } // // public void setDenialDate(Date denialDate) { // put(DENIAL_DATE_KEY, denialDate); // } // // public Date getDeactivationDate() { // return getDate((DEACTIVATION_DATE_KEY)); // } // // public void setDeactivationDate(Date deactivationDate) { // put(DEACTIVATION_DATE_KEY, deactivationDate); // } // // public String getOwnerUUID() { // return getString(USER_UID_KEY); // } // // public void setOwnerUUID(String ownerUUID) { // put(USER_UID_KEY, ownerUUID); // } // // public boolean isTrialProjectFlag() { // return getBoolean(TRIAL_PROJECT_FLAG_KEY); // } // // public void setTrialProjectFlag(boolean trialProjectFlag) { // put(TRIAL_PROJECT_FLAG_KEY, trialProjectFlag); // } // // @Override // public String toString() { // return "Project[name=" + getFullName() + ",description=" + getDescription() + ", owner id=" + getOwnerUUID() + // ", create date=" + getCreateDate() + ", uuid=" + getIdentifier() + "]"; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/storage/ProjectStore.java // public class ProjectStore<V extends Project> extends AbstractStore<V> { // ProjectHandler<V> projectHandler; // // public ProjectStore(ProjectHandler<V> projectHandler) { // super(projectHandler); // } // // @Override // public V create() { // //return null; // return (V) new Project(projectHandler.getSession()); // // } // } // Path: src/main/java/org/continuousassurance/swamp/client/commands/ProjectCommands.java import edu.uiuc.ncsa.security.core.Identifiable; import edu.uiuc.ncsa.security.core.Store; import edu.uiuc.ncsa.security.core.util.Iso8601; import edu.uiuc.ncsa.security.core.util.MyLoggingFacade; import org.continuousassurance.swamp.api.Project; import org.continuousassurance.swamp.session.storage.ProjectStore; package org.continuousassurance.swamp.client.commands; /** * <p>Created by Jeff Gaynor<br> * on 4/11/16 at 2:55 PM */ public class ProjectCommands extends SWAMPStoreCommands { public ProjectCommands(MyLoggingFacade logger, String defaultIndent, Store store) { super(logger, defaultIndent, store); } public ProjectCommands(MyLoggingFacade logger, Store store) { super(logger, store); } protected ProjectStore getProjectStore(){ return (ProjectStore)getStore(); } @Override public String getPrompt() { return "projects>"; } @Override public void extraUpdates(Identifiable identifiable) { } /* protected void showResultsHelp() { say("Shows the assessment results for this package."); say("Syntax is "); say("results index|uid"); say(""); } public void results(InputLine inputLine) { if (showHelp(inputLine)) { showResultsHelp(); return; } Project p = null; if (inputLine.size() == 1) { say("You must supply the index or id of the item to update"); return; } Identifiable identifiable = findItem(inputLine); if (identifiable != null) { p = (Project) identifiable; List<AssessmentResults> ars = getProjectStore().getAssessmentResults(p); say(" There are " + ars.size() + " assessment results."); for(AssessmentResults ar : ars){ // ar. } } else { say("Sorry, project not found"); } }*/ @Override public String getName() { return defaultIndent + "projects"; } @Override public boolean update(Identifiable identifiable) {
Project p = (Project) identifiable;
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/api/RunRequest.java
// Path: src/main/java/org/continuousassurance/swamp/session/handlers/RunRequestHandler.java // public class RunRequestHandler<T extends RunRequest> extends AbstractHandler<RunRequest> { // public static final String RUN_REQUEST_UUID_KEY = "run_request_uuid"; // public static final String RUN_REQUEST_NAME_KEY = "name"; // public static final String RUN_REQUEST_DESCRIPTION_KEY = "description"; // public static final String RUN_REQUEST_PROJECT_UUID_KEY = "project_uuid"; // different than used by project itself. // // public RunRequestHandler(Session session) { // super(session); // } // // ProjectHandler projectHandler; // // public ProjectHandler getProjectHandler() { // return projectHandler; // } // // public void setProjectHandler(ProjectHandler projectHandler) { // this.projectHandler = projectHandler; // } // // @Override // protected RunRequest fromJSON(JSONObject json) { // RunRequest rr = new RunRequest(getSession()); // // Project project = (Project) getProjectHandler().get(SWAMPIdentifiers.toIdentifier(json.getString(RUN_REQUEST_PROJECT_UUID_KEY))); // // rr.setProject(project); // ConversionMapImpl map = new ConversionMapImpl(); // // String[] uAttrib = {RUN_REQUEST_UUID_KEY}; // String[] sAttrib = {RUN_REQUEST_NAME_KEY, RUN_REQUEST_DESCRIPTION_KEY}; // setAttributes(map, uAttrib, json, DATA_TYPE_IDENTIFIER); // setAttributes(map, sAttrib, json, DATA_TYPE_STRING); // rr.setConversionMap(map); // return rr; // } // // @Override // public List<RunRequest> getAll() { // return null; // } // // @Override // public String getURL() { // return createURL("run_requests"); // } // public RunRequest create(Project project, String name, String description){ // ConversionMapImpl map = new ConversionMapImpl(); // map.put(RUN_REQUEST_PROJECT_UUID_KEY, project.getUUIDString() ); // map.put(RUN_REQUEST_NAME_KEY, name); // map.put(RUN_REQUEST_DESCRIPTION_KEY, description); // RunRequest rr = (RunRequest) super.create(map); // rr.setProject(project); // return rr; // } // public boolean submitOneTimeRequest(Collection<AssessmentRun> aRuns, boolean notifyWhenDone){ // String url = createURL("run_requests/one-time"); // ConversionMapImpl parameters = new ConversionMapImpl(); // if(notifyWhenDone) { // parameters.put("notify-when-done", "true"); // } // // JSONArray uuids = new JSONArray(); // for(AssessmentRun arun : aRuns){ // uuids.add(arun.getUUIDString()); // } // parameters.put("assessment-run-uuids", uuids); // // MyResponse myResponse = getClient().rawPost(url, mapToJSON(parameters)); // // if (myResponse.jsonArray != null){ // return true; // }else { // return false; // } // // } // public boolean submitOneTimeRequest(AssessmentRun aRun, boolean notifyWhenDone){ // String url = createURL("run_requests/one-time"); // HashMap<String, Object> parameters = new HashMap<>(); // if(notifyWhenDone) { // parameters.put("notify-when-done", "true"); // } // parameters.put("assessment-run-uuids[]", aRun.getUUIDString()); // MyResponse myResponse = getClient().rawPost(url, parameters); // // //System.out.println(myResponse); // // if (myResponse.jsonArray != null){ // return true; // }else { // return false; // } // /* // parameters.put(PACKAGE_UUID_KEY, pkg.getUUIDString()); // parameters.put(PLATFORM_UUID_KEY, platform.getUUIDString()); // parameters.put(TOOL_UUID_KEY, tool.getUUIDString()); // AssessmentRun result = fromJSON(myResponse.json); // result.setProject(project); // result.setPkg(pkg); // result.setPlatform(platform); // result.setTool(tool); // */ // } // }
import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.handlers.RunRequestHandler; import java.util.Map;
package org.continuousassurance.swamp.api; /** * This models a run request. Properties supported are * <ul> * <li>Description</li> * <li>Name</li> * <li>Project</li> * </ul> * <p>Created by Jeff Gaynor<br> * on 12/22/14 at 11:37 AM */ public class RunRequest extends SwampThing{ public RunRequest(Session session) { super(session); } public RunRequest(Session session, Map map) { super(session, map); } @Override protected SwampThing getNewInstance() { return new RunRequest(getSession()); } @Override public String getIDKey() {
// Path: src/main/java/org/continuousassurance/swamp/session/handlers/RunRequestHandler.java // public class RunRequestHandler<T extends RunRequest> extends AbstractHandler<RunRequest> { // public static final String RUN_REQUEST_UUID_KEY = "run_request_uuid"; // public static final String RUN_REQUEST_NAME_KEY = "name"; // public static final String RUN_REQUEST_DESCRIPTION_KEY = "description"; // public static final String RUN_REQUEST_PROJECT_UUID_KEY = "project_uuid"; // different than used by project itself. // // public RunRequestHandler(Session session) { // super(session); // } // // ProjectHandler projectHandler; // // public ProjectHandler getProjectHandler() { // return projectHandler; // } // // public void setProjectHandler(ProjectHandler projectHandler) { // this.projectHandler = projectHandler; // } // // @Override // protected RunRequest fromJSON(JSONObject json) { // RunRequest rr = new RunRequest(getSession()); // // Project project = (Project) getProjectHandler().get(SWAMPIdentifiers.toIdentifier(json.getString(RUN_REQUEST_PROJECT_UUID_KEY))); // // rr.setProject(project); // ConversionMapImpl map = new ConversionMapImpl(); // // String[] uAttrib = {RUN_REQUEST_UUID_KEY}; // String[] sAttrib = {RUN_REQUEST_NAME_KEY, RUN_REQUEST_DESCRIPTION_KEY}; // setAttributes(map, uAttrib, json, DATA_TYPE_IDENTIFIER); // setAttributes(map, sAttrib, json, DATA_TYPE_STRING); // rr.setConversionMap(map); // return rr; // } // // @Override // public List<RunRequest> getAll() { // return null; // } // // @Override // public String getURL() { // return createURL("run_requests"); // } // public RunRequest create(Project project, String name, String description){ // ConversionMapImpl map = new ConversionMapImpl(); // map.put(RUN_REQUEST_PROJECT_UUID_KEY, project.getUUIDString() ); // map.put(RUN_REQUEST_NAME_KEY, name); // map.put(RUN_REQUEST_DESCRIPTION_KEY, description); // RunRequest rr = (RunRequest) super.create(map); // rr.setProject(project); // return rr; // } // public boolean submitOneTimeRequest(Collection<AssessmentRun> aRuns, boolean notifyWhenDone){ // String url = createURL("run_requests/one-time"); // ConversionMapImpl parameters = new ConversionMapImpl(); // if(notifyWhenDone) { // parameters.put("notify-when-done", "true"); // } // // JSONArray uuids = new JSONArray(); // for(AssessmentRun arun : aRuns){ // uuids.add(arun.getUUIDString()); // } // parameters.put("assessment-run-uuids", uuids); // // MyResponse myResponse = getClient().rawPost(url, mapToJSON(parameters)); // // if (myResponse.jsonArray != null){ // return true; // }else { // return false; // } // // } // public boolean submitOneTimeRequest(AssessmentRun aRun, boolean notifyWhenDone){ // String url = createURL("run_requests/one-time"); // HashMap<String, Object> parameters = new HashMap<>(); // if(notifyWhenDone) { // parameters.put("notify-when-done", "true"); // } // parameters.put("assessment-run-uuids[]", aRun.getUUIDString()); // MyResponse myResponse = getClient().rawPost(url, parameters); // // //System.out.println(myResponse); // // if (myResponse.jsonArray != null){ // return true; // }else { // return false; // } // /* // parameters.put(PACKAGE_UUID_KEY, pkg.getUUIDString()); // parameters.put(PLATFORM_UUID_KEY, platform.getUUIDString()); // parameters.put(TOOL_UUID_KEY, tool.getUUIDString()); // AssessmentRun result = fromJSON(myResponse.json); // result.setProject(project); // result.setPkg(pkg); // result.setPlatform(platform); // result.setTool(tool); // */ // } // } // Path: src/main/java/org/continuousassurance/swamp/api/RunRequest.java import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.handlers.RunRequestHandler; import java.util.Map; package org.continuousassurance.swamp.api; /** * This models a run request. Properties supported are * <ul> * <li>Description</li> * <li>Name</li> * <li>Project</li> * </ul> * <p>Created by Jeff Gaynor<br> * on 12/22/14 at 11:37 AM */ public class RunRequest extends SwampThing{ public RunRequest(Session session) { super(session); } public RunRequest(Session session, Map map) { super(session, map); } @Override protected SwampThing getNewInstance() { return new RunRequest(getSession()); } @Override public String getIDKey() {
return RunRequestHandler.RUN_REQUEST_UUID_KEY;
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/session/handlers/UserHandler.java
// Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // }
import org.continuousassurance.swamp.api.User; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import net.sf.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
package org.continuousassurance.swamp.session.handlers; /** * <p>Created by Jeff Gaynor<br> * on 11/20/14 at 10:08 AM */ public class UserHandler<T extends User> extends AbstractHandler<T> { public static final String USER_UID_KEY = "user_uid"; public static final String FIRST_NAME_KEY = "first_name"; public static final String LAST_NAME_KEY = "last_name"; public static final String PREFERRED_NAME_KEY = "preferred_name"; public static final String USERNAME_KEY = "username"; public static final String EMAIL_KEY = "email"; public static final String ADDRESS_KEY = "address"; public static final String PHONE_KEY = "phone"; public static final String AFFILIATION_KEY = "affiliation"; public static final String EMAIL_VERIFIED_KEY = "email_verified_flag"; public static final String ACCOUNT_ENABLED_KEY = "enabled_flag"; public static final String OWNER_KEY = "owner_flag"; public static final String SSH_ACCESS_KEY = "ssh_access_flag"; public static final String ADMIN_ACCESS_KEY = "admin_flag"; public static final String LAST_URL_KEY = "last_url"; public static final String CREATE_DATE_KEY = "create_date"; public static final String UPDATE_DATE_KEY = "update_date"; public static final String USERS_CURRENT = "users/current"; public static final String OLD_PASSWORD_KEY = "old_password"; public static final String NEW_PASSWORD_KEY = "new_password"; public UserHandler(Session session) { super(session); } public void changePassword(String oldPassword, String newPassword) throws UnsupportedEncodingException { HashMap<String, Object> map = new HashMap<String, Object>(); map.put(OLD_PASSWORD_KEY, oldPassword); map.put(NEW_PASSWORD_KEY, newPassword);
// Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // Path: src/main/java/org/continuousassurance/swamp/session/handlers/UserHandler.java import org.continuousassurance.swamp.api.User; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import net.sf.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; package org.continuousassurance.swamp.session.handlers; /** * <p>Created by Jeff Gaynor<br> * on 11/20/14 at 10:08 AM */ public class UserHandler<T extends User> extends AbstractHandler<T> { public static final String USER_UID_KEY = "user_uid"; public static final String FIRST_NAME_KEY = "first_name"; public static final String LAST_NAME_KEY = "last_name"; public static final String PREFERRED_NAME_KEY = "preferred_name"; public static final String USERNAME_KEY = "username"; public static final String EMAIL_KEY = "email"; public static final String ADDRESS_KEY = "address"; public static final String PHONE_KEY = "phone"; public static final String AFFILIATION_KEY = "affiliation"; public static final String EMAIL_VERIFIED_KEY = "email_verified_flag"; public static final String ACCOUNT_ENABLED_KEY = "enabled_flag"; public static final String OWNER_KEY = "owner_flag"; public static final String SSH_ACCESS_KEY = "ssh_access_flag"; public static final String ADMIN_ACCESS_KEY = "admin_flag"; public static final String LAST_URL_KEY = "last_url"; public static final String CREATE_DATE_KEY = "create_date"; public static final String UPDATE_DATE_KEY = "update_date"; public static final String USERS_CURRENT = "users/current"; public static final String OLD_PASSWORD_KEY = "old_password"; public static final String NEW_PASSWORD_KEY = "new_password"; public UserHandler(Session session) { super(session); } public void changePassword(String oldPassword, String newPassword) throws UnsupportedEncodingException { HashMap<String, Object> map = new HashMap<String, Object>(); map.put(OLD_PASSWORD_KEY, oldPassword); map.put(NEW_PASSWORD_KEY, newPassword);
MyResponse myResponse = getClient().rawPut(createURL("users/" + getSession().getUserUID() + "/change-password"), map);
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/session/handlers/UserHandler.java
// Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // }
import org.continuousassurance.swamp.api.User; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import net.sf.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
map.put(NEW_PASSWORD_KEY, newPassword); MyResponse myResponse = getClient().rawPut(createURL("users/" + getSession().getUserUID() + "/change-password"), map); } public User getCurrentUser() { if (getSession() == null || getSession().getUserUID() == null) { throw new IllegalStateException("Error: There is no current session or user."); } MyResponse myResponse = getClient().rawGet(createURL(USERS_CURRENT), null); int code = myResponse.getHttpResponseCode(); /* 2xx series codes indicate OK */ /* could be more selective, MIR team indicates all 2xx OK */ if (code >= 200 && code <= 299) { return fromJSON(myResponse.json); } else { return null; } } @Override public List<T> getAll() { return new ArrayList<T>(); } @Override protected T fromJSON(JSONObject json) {
// Path: src/main/java/org/continuousassurance/swamp/session/MyResponse.java // public class MyResponse { // public JSONObject json; // public JSONArray jsonArray; // public List<Cookie> cookies; // public OutputStream outputStream; // // public boolean hasJSON(){return json != null;} // // public int getHttpResponseCode() { // return httpResponseCode; // } // // public void setHttpResponseCode(int httpResponseCode) { // this.httpResponseCode = httpResponseCode; // } // // int httpResponseCode = 0; // // public MyResponse(OutputStream outputStream, List<Cookie> cookies) { // this.outputStream = outputStream; // this.cookies = cookies; // } // // boolean streamable = false; // /** // * Returns if this response should be interpreted as a stream rather than a JSON object. // * @return // */ // public boolean isStreamable(){return streamable;} // public void setStreamable(boolean streamable){this.streamable = streamable;} // public OutputStream getOutputStream(){return outputStream;} // // public MyResponse(JSON json, List<Cookie> cookies) { // this.cookies = cookies; // if(json == null) return; // if (json.isArray()) { // jsonArray = (JSONArray) json; // } // if (json instanceof JSONObject) { // this.json = (JSONObject) json; // } // } // // public void setOutputStream(OutputStream outputStream) { // this.outputStream = outputStream; // } // } // // Path: src/main/java/org/continuousassurance/swamp/session/util/ConversionMapImpl.java // public class ConversionMapImpl extends HashMap<String, Object> implements ConversionMap<String, Object> { // public static final boolean BOOLEAN_DEFAULT = false; // public static final long LONG_DEFAULT = 0L; // // // @Override // public Date getDate(java.lang.String key) { // return (Date) get(key); // } // // @Override // public boolean getBoolean(java.lang.String key) { // Object x = get(key); // if(x == null) return BOOLEAN_DEFAULT; // return (boolean) x; // } // // @Override // public long getLong(java.lang.String key) { // if(get(key) == null) return LONG_DEFAULT; // return (long) get(key); // } // // @Override // public java.lang.String getString(String key) { // Object x = get(key); // if (x == null) return null; // return x.toString(); // } // // // @Override // public Identifier getIdentifier(String key) { // return (Identifier) get(key); // } // // // @Override // public URI getURI(java.lang.String key) { // Object x = get(key); // if (x == null) return null; // return URI.create(x.toString()); // } // // @Override // public byte[] getBytes(java.lang.String key) { // Object x = get(key); // if (x.getClass().isArray()) { // // try to return it... // return (byte[]) x; // } // return null; // } // } // Path: src/main/java/org/continuousassurance/swamp/session/handlers/UserHandler.java import org.continuousassurance.swamp.api.User; import org.continuousassurance.swamp.session.MyResponse; import org.continuousassurance.swamp.session.Session; import org.continuousassurance.swamp.session.util.ConversionMapImpl; import net.sf.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; map.put(NEW_PASSWORD_KEY, newPassword); MyResponse myResponse = getClient().rawPut(createURL("users/" + getSession().getUserUID() + "/change-password"), map); } public User getCurrentUser() { if (getSession() == null || getSession().getUserUID() == null) { throw new IllegalStateException("Error: There is no current session or user."); } MyResponse myResponse = getClient().rawGet(createURL(USERS_CURRENT), null); int code = myResponse.getHttpResponseCode(); /* 2xx series codes indicate OK */ /* could be more selective, MIR team indicates all 2xx OK */ if (code >= 200 && code <= 299) { return fromJSON(myResponse.json); } else { return null; } } @Override public List<T> getAll() { return new ArrayList<T>(); } @Override protected T fromJSON(JSONObject json) {
ConversionMapImpl map = new ConversionMapImpl();
mirswamp/java-cli
src/main/java/org/continuousassurance/swamp/api/RunRequestSchedule.java
// Path: src/main/java/org/continuousassurance/swamp/session/handlers/RunRequestScheduleHandler.java // public static String RUN_REQUEST_SCHEDULE_UUID = "run_request_schedule_uuid";
import org.continuousassurance.swamp.session.Session; import java.util.Map; import static org.continuousassurance.swamp.session.handlers.RunRequestScheduleHandler.RUN_REQUEST_SCHEDULE_UUID;
package org.continuousassurance.swamp.api; /** * This models the schedule for an assessment run. Properties are * <ul> * <li>{@link RunRequest} this schedule refers to</li> * <li>Recurrence type</li> * <li>Recurrence day</li> * <li>Recurrence time of day - the time of day this should run.</li> * </ul> * <p>Created by Jeff Gaynor<br> * on 12/22/14 at 3:35 PM */ public class RunRequestSchedule extends SwampThing{ public RunRequestSchedule(Session session) { super(session); } public RunRequestSchedule(Session session, Map map) { super(session, map); } @Override protected SwampThing getNewInstance() { return new RunRequestSchedule(getSession()); } @Override public String getIDKey() {
// Path: src/main/java/org/continuousassurance/swamp/session/handlers/RunRequestScheduleHandler.java // public static String RUN_REQUEST_SCHEDULE_UUID = "run_request_schedule_uuid"; // Path: src/main/java/org/continuousassurance/swamp/api/RunRequestSchedule.java import org.continuousassurance.swamp.session.Session; import java.util.Map; import static org.continuousassurance.swamp.session.handlers.RunRequestScheduleHandler.RUN_REQUEST_SCHEDULE_UUID; package org.continuousassurance.swamp.api; /** * This models the schedule for an assessment run. Properties are * <ul> * <li>{@link RunRequest} this schedule refers to</li> * <li>Recurrence type</li> * <li>Recurrence day</li> * <li>Recurrence time of day - the time of day this should run.</li> * </ul> * <p>Created by Jeff Gaynor<br> * on 12/22/14 at 3:35 PM */ public class RunRequestSchedule extends SwampThing{ public RunRequestSchedule(Session session) { super(session); } public RunRequestSchedule(Session session, Map map) { super(session, map); } @Override protected SwampThing getNewInstance() { return new RunRequestSchedule(getSession()); } @Override public String getIDKey() {
return RUN_REQUEST_SCHEDULE_UUID;
unofficial/npr-android-app
src/org/npr/api/Podcast.java
// Path: src/org/npr/android/util/NodeUtils.java // public class NodeUtils { // public static final String LOG_TAG = NodeUtils.class.getName(); // private static boolean getTextContentAvailable = true; // private static Method getTextContentMethod = null; // // private final static int MAX_RECURSION_DEPTH = 10; // // /** // * Node#getTextContent() is only available in Froyo and later. // * Call getTextContent if it exists else use local implementation // * @param node // * @return text content of this node and its descendant // */ // public static String getTextContent(Node node) { // if (getTextContentAvailable && getTextContentMethod == null) { // try { // getTextContentMethod = Node.class.getMethod( // "getTextContent", (Class[]) null ); // } catch (NoSuchMethodException nsme) { // // failure, must be older device // getTextContentAvailable = false; // } // } // // if (getTextContentAvailable) { // try { // String value = (String) getTextContentMethod.invoke(node); // return value; // } catch (IllegalArgumentException e1) { // getTextContentAvailable = false; // } catch (IllegalAccessException e1) { // getTextContentAvailable = false; // } catch (InvocationTargetException e1) { // getTextContentAvailable = false; // } // } // // // getTextContent doesn't exist. // return getTextContentImpl(node, 0); // } // // /** // * implementation based on Javadoc description of getTextContent // * @param node // * @return text content of this node and its descendant // */ // private static String getTextContentImpl(Node node, int recursionDepth) { // // should never happen but don't allow too much recursion // if (recursionDepth > MAX_RECURSION_DEPTH) { // Log.d(LOG_TAG, "too much recursion!"); // return ""; // } // // switch (node.getNodeType()) { // case Node.TEXT_NODE: // case Node.CDATA_SECTION_NODE: // case Node.COMMENT_NODE: // case Node.PROCESSING_INSTRUCTION_NODE: // return node.getNodeValue(); // // case Node.ELEMENT_NODE: // case Node.ATTRIBUTE_NODE: // case Node.ENTITY_NODE: // case Node.ENTITY_REFERENCE_NODE: // case Node.DOCUMENT_FRAGMENT_NODE: // StringBuffer value = new StringBuffer(); // for (Node childNode: new IterableNodeList(node.getChildNodes())) { // int childNodeType = childNode.getNodeType(); // if (childNodeType != Node.COMMENT_NODE // && childNodeType != Node.PROCESSING_INSTRUCTION_NODE) { // value.append(getTextContentImpl(childNode, recursionDepth + 1)); // } // } // return value.toString(); // } // // Log.d(LOG_TAG, "unexpected node type: " + node.getNodeType()); // return null; // } // }
import android.util.Log; import org.apache.http.client.ClientProtocolException; import org.npr.android.util.NodeUtils; import org.w3c.dom.Attr; import org.w3c.dom.Node; import org.xml.sax.SAXException; import java.io.IOException; import java.util.LinkedList; import java.util.List; import javax.xml.parsers.ParserConfigurationException;
public Podcast build() { return new Podcast(title, summary, link, items); } } public static class PodcastFactory { private static final String LOG_TAG = PodcastFactory.class.getName(); private static Podcast parsePodcast(Node rootNode) { if (!rootNode.getNodeName().equals("rss") || !rootNode.hasChildNodes()) { return null; } PodcastBuilder pb = new PodcastBuilder(); // Presumes one channel Node channel = null; for (Node n : new IterableNodeList(rootNode.getChildNodes())) { String nodeName = n.getNodeName(); if (nodeName.equals("channel")) { channel = n; break; } } if (channel == null) { return null; } for (Node n : new IterableNodeList(channel.getChildNodes())) { String nodeName = n.getNodeName(); Node nodeChild = n.getChildNodes().item(0); if (nodeName.equals("title")) {
// Path: src/org/npr/android/util/NodeUtils.java // public class NodeUtils { // public static final String LOG_TAG = NodeUtils.class.getName(); // private static boolean getTextContentAvailable = true; // private static Method getTextContentMethod = null; // // private final static int MAX_RECURSION_DEPTH = 10; // // /** // * Node#getTextContent() is only available in Froyo and later. // * Call getTextContent if it exists else use local implementation // * @param node // * @return text content of this node and its descendant // */ // public static String getTextContent(Node node) { // if (getTextContentAvailable && getTextContentMethod == null) { // try { // getTextContentMethod = Node.class.getMethod( // "getTextContent", (Class[]) null ); // } catch (NoSuchMethodException nsme) { // // failure, must be older device // getTextContentAvailable = false; // } // } // // if (getTextContentAvailable) { // try { // String value = (String) getTextContentMethod.invoke(node); // return value; // } catch (IllegalArgumentException e1) { // getTextContentAvailable = false; // } catch (IllegalAccessException e1) { // getTextContentAvailable = false; // } catch (InvocationTargetException e1) { // getTextContentAvailable = false; // } // } // // // getTextContent doesn't exist. // return getTextContentImpl(node, 0); // } // // /** // * implementation based on Javadoc description of getTextContent // * @param node // * @return text content of this node and its descendant // */ // private static String getTextContentImpl(Node node, int recursionDepth) { // // should never happen but don't allow too much recursion // if (recursionDepth > MAX_RECURSION_DEPTH) { // Log.d(LOG_TAG, "too much recursion!"); // return ""; // } // // switch (node.getNodeType()) { // case Node.TEXT_NODE: // case Node.CDATA_SECTION_NODE: // case Node.COMMENT_NODE: // case Node.PROCESSING_INSTRUCTION_NODE: // return node.getNodeValue(); // // case Node.ELEMENT_NODE: // case Node.ATTRIBUTE_NODE: // case Node.ENTITY_NODE: // case Node.ENTITY_REFERENCE_NODE: // case Node.DOCUMENT_FRAGMENT_NODE: // StringBuffer value = new StringBuffer(); // for (Node childNode: new IterableNodeList(node.getChildNodes())) { // int childNodeType = childNode.getNodeType(); // if (childNodeType != Node.COMMENT_NODE // && childNodeType != Node.PROCESSING_INSTRUCTION_NODE) { // value.append(getTextContentImpl(childNode, recursionDepth + 1)); // } // } // return value.toString(); // } // // Log.d(LOG_TAG, "unexpected node type: " + node.getNodeType()); // return null; // } // } // Path: src/org/npr/api/Podcast.java import android.util.Log; import org.apache.http.client.ClientProtocolException; import org.npr.android.util.NodeUtils; import org.w3c.dom.Attr; import org.w3c.dom.Node; import org.xml.sax.SAXException; import java.io.IOException; import java.util.LinkedList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; public Podcast build() { return new Podcast(title, summary, link, items); } } public static class PodcastFactory { private static final String LOG_TAG = PodcastFactory.class.getName(); private static Podcast parsePodcast(Node rootNode) { if (!rootNode.getNodeName().equals("rss") || !rootNode.hasChildNodes()) { return null; } PodcastBuilder pb = new PodcastBuilder(); // Presumes one channel Node channel = null; for (Node n : new IterableNodeList(rootNode.getChildNodes())) { String nodeName = n.getNodeName(); if (nodeName.equals("channel")) { channel = n; break; } } if (channel == null) { return null; } for (Node n : new IterableNodeList(channel.getChildNodes())) { String nodeName = n.getNodeName(); Node nodeChild = n.getChildNodes().item(0); if (nodeName.equals("title")) {
pb.withTitle(NodeUtils.getTextContent(n));
unofficial/npr-android-app
src/org/npr/android/news/PlayerActivity.java
// Path: src/org/npr/android/util/PlaylistEntry.java // public class PlaylistEntry { // public long id; // public final String url; // public final String title; // public final boolean isStream; // public int order; // public final String storyID; // // public PlaylistEntry(long id, String url, String title, boolean isStream, // int order) { // this(id, url, title, isStream, order, null); // } // // public PlaylistEntry(long id, String url, String title, boolean isStream, // int order, String storyID) { // this.id = id; // this.url = url; // this.title = title; // this.isStream = isStream; // this.order = order; // this.storyID = storyID; // } // }
import android.app.Activity; import android.app.ActivityGroup; import android.content.Intent; import android.media.AudioManager; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.TextView; import org.npr.android.util.PlaylistEntry; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;
} private enum MenuId { ABOUT, REFRESH } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, MenuId.ABOUT.ordinal(), Menu.NONE, R.string.msg_main_menu_about) .setIcon(android.R.drawable.ic_menu_help).setAlphabeticShortcut('a'); if (this.isRefreshable()) { menu.add(Menu.NONE, MenuId.REFRESH.ordinal(), Menu.NONE, R.string.msg_refresh).setAlphabeticShortcut('r'); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == MenuId.ABOUT.ordinal()) { startActivity(new Intent(this, AboutActivity.class)); return true; } else if (item.getItemId() == MenuId.REFRESH.ordinal()) { this.refresh(); } return super.onOptionsItemSelected(item); }
// Path: src/org/npr/android/util/PlaylistEntry.java // public class PlaylistEntry { // public long id; // public final String url; // public final String title; // public final boolean isStream; // public int order; // public final String storyID; // // public PlaylistEntry(long id, String url, String title, boolean isStream, // int order) { // this(id, url, title, isStream, order, null); // } // // public PlaylistEntry(long id, String url, String title, boolean isStream, // int order, String storyID) { // this.id = id; // this.url = url; // this.title = title; // this.isStream = isStream; // this.order = order; // this.storyID = storyID; // } // } // Path: src/org/npr/android/news/PlayerActivity.java import android.app.Activity; import android.app.ActivityGroup; import android.content.Intent; import android.media.AudioManager; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.TextView; import org.npr.android.util.PlaylistEntry; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; } private enum MenuId { ABOUT, REFRESH } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, MenuId.ABOUT.ordinal(), Menu.NONE, R.string.msg_main_menu_about) .setIcon(android.R.drawable.ic_menu_help).setAlphabeticShortcut('a'); if (this.isRefreshable()) { menu.add(Menu.NONE, MenuId.REFRESH.ordinal(), Menu.NONE, R.string.msg_refresh).setAlphabeticShortcut('r'); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == MenuId.ABOUT.ordinal()) { startActivity(new Intent(this, AboutActivity.class)); return true; } else if (item.getItemId() == MenuId.REFRESH.ordinal()) { this.refresh(); } return super.onOptionsItemSelected(item); }
protected void listen(PlaylistEntry entry) {
unofficial/npr-android-app
src/org/npr/api/Story.java
// Path: src/org/npr/android/util/NodeUtils.java // public class NodeUtils { // public static final String LOG_TAG = NodeUtils.class.getName(); // private static boolean getTextContentAvailable = true; // private static Method getTextContentMethod = null; // // private final static int MAX_RECURSION_DEPTH = 10; // // /** // * Node#getTextContent() is only available in Froyo and later. // * Call getTextContent if it exists else use local implementation // * @param node // * @return text content of this node and its descendant // */ // public static String getTextContent(Node node) { // if (getTextContentAvailable && getTextContentMethod == null) { // try { // getTextContentMethod = Node.class.getMethod( // "getTextContent", (Class[]) null ); // } catch (NoSuchMethodException nsme) { // // failure, must be older device // getTextContentAvailable = false; // } // } // // if (getTextContentAvailable) { // try { // String value = (String) getTextContentMethod.invoke(node); // return value; // } catch (IllegalArgumentException e1) { // getTextContentAvailable = false; // } catch (IllegalAccessException e1) { // getTextContentAvailable = false; // } catch (InvocationTargetException e1) { // getTextContentAvailable = false; // } // } // // // getTextContent doesn't exist. // return getTextContentImpl(node, 0); // } // // /** // * implementation based on Javadoc description of getTextContent // * @param node // * @return text content of this node and its descendant // */ // private static String getTextContentImpl(Node node, int recursionDepth) { // // should never happen but don't allow too much recursion // if (recursionDepth > MAX_RECURSION_DEPTH) { // Log.d(LOG_TAG, "too much recursion!"); // return ""; // } // // switch (node.getNodeType()) { // case Node.TEXT_NODE: // case Node.CDATA_SECTION_NODE: // case Node.COMMENT_NODE: // case Node.PROCESSING_INSTRUCTION_NODE: // return node.getNodeValue(); // // case Node.ELEMENT_NODE: // case Node.ATTRIBUTE_NODE: // case Node.ENTITY_NODE: // case Node.ENTITY_REFERENCE_NODE: // case Node.DOCUMENT_FRAGMENT_NODE: // StringBuffer value = new StringBuffer(); // for (Node childNode: new IterableNodeList(node.getChildNodes())) { // int childNodeType = childNode.getNodeType(); // if (childNodeType != Node.COMMENT_NODE // && childNodeType != Node.PROCESSING_INSTRUCTION_NODE) { // value.append(getTextContentImpl(childNode, recursionDepth + 1)); // } // } // return value.toString(); // } // // Log.d(LOG_TAG, "unexpected node type: " + node.getNodeType()); // return null; // } // }
import java.util.TreeMap; import java.util.Map.Entry; import javax.xml.parsers.ParserConfigurationException; import android.util.Log; import org.apache.http.client.ClientProtocolException; import org.npr.android.util.NodeUtils; import org.w3c.dom.Attr; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.SortedMap;
for (Node node : new IterableNodeList(childNodes)) { if (node.getNodeName().equals("list")) { for (Node storyNode : new IterableNodeList(node.getChildNodes())) { Story story = createStory(storyNode); if (story != null) { result.add(story); } } } } return result; } private static Story createStory(Node node) { if (!node.getNodeName().equals("story") || !node.hasChildNodes()) { return null; } StoryBuilder sb = new StoryBuilder(node.getAttributes().getNamedItem( "id").getNodeValue()); try { Log.d(LOG_TAG, "parsing story " + sb.id); for (Node n : new IterableNodeList(node.getChildNodes())) { String nodeName = n.getNodeName(); Node nodeChild = n.getChildNodes().item(0); if (nodeChild == null) { continue; } if (nodeName.equals("title")) {
// Path: src/org/npr/android/util/NodeUtils.java // public class NodeUtils { // public static final String LOG_TAG = NodeUtils.class.getName(); // private static boolean getTextContentAvailable = true; // private static Method getTextContentMethod = null; // // private final static int MAX_RECURSION_DEPTH = 10; // // /** // * Node#getTextContent() is only available in Froyo and later. // * Call getTextContent if it exists else use local implementation // * @param node // * @return text content of this node and its descendant // */ // public static String getTextContent(Node node) { // if (getTextContentAvailable && getTextContentMethod == null) { // try { // getTextContentMethod = Node.class.getMethod( // "getTextContent", (Class[]) null ); // } catch (NoSuchMethodException nsme) { // // failure, must be older device // getTextContentAvailable = false; // } // } // // if (getTextContentAvailable) { // try { // String value = (String) getTextContentMethod.invoke(node); // return value; // } catch (IllegalArgumentException e1) { // getTextContentAvailable = false; // } catch (IllegalAccessException e1) { // getTextContentAvailable = false; // } catch (InvocationTargetException e1) { // getTextContentAvailable = false; // } // } // // // getTextContent doesn't exist. // return getTextContentImpl(node, 0); // } // // /** // * implementation based on Javadoc description of getTextContent // * @param node // * @return text content of this node and its descendant // */ // private static String getTextContentImpl(Node node, int recursionDepth) { // // should never happen but don't allow too much recursion // if (recursionDepth > MAX_RECURSION_DEPTH) { // Log.d(LOG_TAG, "too much recursion!"); // return ""; // } // // switch (node.getNodeType()) { // case Node.TEXT_NODE: // case Node.CDATA_SECTION_NODE: // case Node.COMMENT_NODE: // case Node.PROCESSING_INSTRUCTION_NODE: // return node.getNodeValue(); // // case Node.ELEMENT_NODE: // case Node.ATTRIBUTE_NODE: // case Node.ENTITY_NODE: // case Node.ENTITY_REFERENCE_NODE: // case Node.DOCUMENT_FRAGMENT_NODE: // StringBuffer value = new StringBuffer(); // for (Node childNode: new IterableNodeList(node.getChildNodes())) { // int childNodeType = childNode.getNodeType(); // if (childNodeType != Node.COMMENT_NODE // && childNodeType != Node.PROCESSING_INSTRUCTION_NODE) { // value.append(getTextContentImpl(childNode, recursionDepth + 1)); // } // } // return value.toString(); // } // // Log.d(LOG_TAG, "unexpected node type: " + node.getNodeType()); // return null; // } // } // Path: src/org/npr/api/Story.java import java.util.TreeMap; import java.util.Map.Entry; import javax.xml.parsers.ParserConfigurationException; import android.util.Log; import org.apache.http.client.ClientProtocolException; import org.npr.android.util.NodeUtils; import org.w3c.dom.Attr; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.SortedMap; for (Node node : new IterableNodeList(childNodes)) { if (node.getNodeName().equals("list")) { for (Node storyNode : new IterableNodeList(node.getChildNodes())) { Story story = createStory(storyNode); if (story != null) { result.add(story); } } } } return result; } private static Story createStory(Node node) { if (!node.getNodeName().equals("story") || !node.hasChildNodes()) { return null; } StoryBuilder sb = new StoryBuilder(node.getAttributes().getNamedItem( "id").getNodeValue()); try { Log.d(LOG_TAG, "parsing story " + sb.id); for (Node n : new IterableNodeList(node.getChildNodes())) { String nodeName = n.getNodeName(); Node nodeChild = n.getChildNodes().item(0); if (nodeChild == null) { continue; } if (nodeName.equals("title")) {
sb.withTitle(NodeUtils.getTextContent(n));
unofficial/npr-android-app
src/org/npr/android/news/AboutActivity.java
// Path: src/org/npr/android/util/FileUtils.java // public class FileUtils { // public static CharSequence readFile(Activity activity, int id) { // BufferedReader in = null; // try { // in = // new BufferedReader(new InputStreamReader(activity.getResources() // .openRawResource(id))); // String line; // StringBuilder buffer = new StringBuilder(); // while ((line = in.readLine()) != null) { // buffer.append(line).append('\n'); // } // // Chomp the last newline // buffer.deleteCharAt(buffer.length() - 1); // return buffer; // } catch (IOException e) { // return ""; // } finally { // closeStream(in); // } // } // // /** // * Closes the specified stream. // * // * @param stream The stream to close. // */ // private static void closeStream(Closeable stream) { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // // Ignore // } // } // } // }
import java.util.Map; import java.util.Map.Entry; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.text.Html; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import org.npr.android.util.FileUtils; import java.util.LinkedHashMap;
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.npr.android.news; public class AboutActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); TextView tv = (TextView) findViewById(R.id.AboutText); Map<String, String> map = new LinkedHashMap<String, String>(); map.put(getString(R.string.msg_about_developer), getString(R.string.msg_about_developer_value)); map.put(getString(R.string.msg_about_contact), getString(R.string.msg_about_contact_value)); map.put(getString(R.string.msg_about_version_name), getVersionName()); map.put(getString(R.string.msg_about_version_code), "" + getVersionCode()); populateField(map, tv); Button terms = (Button) findViewById(R.id.TermsButton); terms.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final AlertDialog.Builder builder = new AlertDialog.Builder(AboutActivity.this); builder.setTitle(R.string.msg_about_terms);
// Path: src/org/npr/android/util/FileUtils.java // public class FileUtils { // public static CharSequence readFile(Activity activity, int id) { // BufferedReader in = null; // try { // in = // new BufferedReader(new InputStreamReader(activity.getResources() // .openRawResource(id))); // String line; // StringBuilder buffer = new StringBuilder(); // while ((line = in.readLine()) != null) { // buffer.append(line).append('\n'); // } // // Chomp the last newline // buffer.deleteCharAt(buffer.length() - 1); // return buffer; // } catch (IOException e) { // return ""; // } finally { // closeStream(in); // } // } // // /** // * Closes the specified stream. // * // * @param stream The stream to close. // */ // private static void closeStream(Closeable stream) { // if (stream != null) { // try { // stream.close(); // } catch (IOException e) { // // Ignore // } // } // } // } // Path: src/org/npr/android/news/AboutActivity.java import java.util.Map; import java.util.Map.Entry; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.text.Html; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import org.npr.android.util.FileUtils; import java.util.LinkedHashMap; // Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.npr.android.news; public class AboutActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); TextView tv = (TextView) findViewById(R.id.AboutText); Map<String, String> map = new LinkedHashMap<String, String>(); map.put(getString(R.string.msg_about_developer), getString(R.string.msg_about_developer_value)); map.put(getString(R.string.msg_about_contact), getString(R.string.msg_about_contact_value)); map.put(getString(R.string.msg_about_version_name), getVersionName()); map.put(getString(R.string.msg_about_version_code), "" + getVersionCode()); populateField(map, tv); Button terms = (Button) findViewById(R.id.TermsButton); terms.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final AlertDialog.Builder builder = new AlertDialog.Builder(AboutActivity.this); builder.setTitle(R.string.msg_about_terms);
builder.setMessage(FileUtils.readFile(AboutActivity.this, R.raw.terms));
unofficial/npr-android-app
src/org/npr/api/StoryGrouping.java
// Path: src/org/npr/android/util/NodeUtils.java // public class NodeUtils { // public static final String LOG_TAG = NodeUtils.class.getName(); // private static boolean getTextContentAvailable = true; // private static Method getTextContentMethod = null; // // private final static int MAX_RECURSION_DEPTH = 10; // // /** // * Node#getTextContent() is only available in Froyo and later. // * Call getTextContent if it exists else use local implementation // * @param node // * @return text content of this node and its descendant // */ // public static String getTextContent(Node node) { // if (getTextContentAvailable && getTextContentMethod == null) { // try { // getTextContentMethod = Node.class.getMethod( // "getTextContent", (Class[]) null ); // } catch (NoSuchMethodException nsme) { // // failure, must be older device // getTextContentAvailable = false; // } // } // // if (getTextContentAvailable) { // try { // String value = (String) getTextContentMethod.invoke(node); // return value; // } catch (IllegalArgumentException e1) { // getTextContentAvailable = false; // } catch (IllegalAccessException e1) { // getTextContentAvailable = false; // } catch (InvocationTargetException e1) { // getTextContentAvailable = false; // } // } // // // getTextContent doesn't exist. // return getTextContentImpl(node, 0); // } // // /** // * implementation based on Javadoc description of getTextContent // * @param node // * @return text content of this node and its descendant // */ // private static String getTextContentImpl(Node node, int recursionDepth) { // // should never happen but don't allow too much recursion // if (recursionDepth > MAX_RECURSION_DEPTH) { // Log.d(LOG_TAG, "too much recursion!"); // return ""; // } // // switch (node.getNodeType()) { // case Node.TEXT_NODE: // case Node.CDATA_SECTION_NODE: // case Node.COMMENT_NODE: // case Node.PROCESSING_INSTRUCTION_NODE: // return node.getNodeValue(); // // case Node.ELEMENT_NODE: // case Node.ATTRIBUTE_NODE: // case Node.ENTITY_NODE: // case Node.ENTITY_REFERENCE_NODE: // case Node.DOCUMENT_FRAGMENT_NODE: // StringBuffer value = new StringBuffer(); // for (Node childNode: new IterableNodeList(node.getChildNodes())) { // int childNodeType = childNode.getNodeType(); // if (childNodeType != Node.COMMENT_NODE // && childNodeType != Node.PROCESSING_INSTRUCTION_NODE) { // value.append(getTextContentImpl(childNode, recursionDepth + 1)); // } // } // return value.toString(); // } // // Log.d(LOG_TAG, "unexpected node type: " + node.getNodeType()); // return null; // } // }
import android.util.Log; import org.apache.http.client.ClientProtocolException; import org.npr.android.util.NodeUtils; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeSet; import javax.xml.parsers.ParserConfigurationException;
resultSet.add(p); } } for (T p : resultSet) { result.add(p); } return result; } @SuppressWarnings("unchecked") private T createStoryGrouping(Class<T> c, Node node) { if (!node.getNodeName().equals("item") || !node.hasChildNodes()) { return null; } String id; int storycounttoday, storycountmonth, storycountall; id = node.getAttributes().getNamedItem("id").getNodeValue(); storycountall = Integer.parseInt(node.getAttributes().getNamedItem( "storycountall").getNodeValue()); storycountmonth = Integer.parseInt(node.getAttributes().getNamedItem( "storycountmonth").getNodeValue()); storycounttoday = Integer.parseInt(node.getAttributes().getNamedItem( "storycounttoday").getNodeValue()); StoryGroupingBuilder<? extends StoryGrouping> sb = new StoryGroupingBuilder<T>(c, id, storycounttoday, storycountmonth, storycountall); for (Node n : new IterableNodeList(node.getChildNodes())) { String nodeName = n.getNodeName(); if (nodeName.equals("title")) {
// Path: src/org/npr/android/util/NodeUtils.java // public class NodeUtils { // public static final String LOG_TAG = NodeUtils.class.getName(); // private static boolean getTextContentAvailable = true; // private static Method getTextContentMethod = null; // // private final static int MAX_RECURSION_DEPTH = 10; // // /** // * Node#getTextContent() is only available in Froyo and later. // * Call getTextContent if it exists else use local implementation // * @param node // * @return text content of this node and its descendant // */ // public static String getTextContent(Node node) { // if (getTextContentAvailable && getTextContentMethod == null) { // try { // getTextContentMethod = Node.class.getMethod( // "getTextContent", (Class[]) null ); // } catch (NoSuchMethodException nsme) { // // failure, must be older device // getTextContentAvailable = false; // } // } // // if (getTextContentAvailable) { // try { // String value = (String) getTextContentMethod.invoke(node); // return value; // } catch (IllegalArgumentException e1) { // getTextContentAvailable = false; // } catch (IllegalAccessException e1) { // getTextContentAvailable = false; // } catch (InvocationTargetException e1) { // getTextContentAvailable = false; // } // } // // // getTextContent doesn't exist. // return getTextContentImpl(node, 0); // } // // /** // * implementation based on Javadoc description of getTextContent // * @param node // * @return text content of this node and its descendant // */ // private static String getTextContentImpl(Node node, int recursionDepth) { // // should never happen but don't allow too much recursion // if (recursionDepth > MAX_RECURSION_DEPTH) { // Log.d(LOG_TAG, "too much recursion!"); // return ""; // } // // switch (node.getNodeType()) { // case Node.TEXT_NODE: // case Node.CDATA_SECTION_NODE: // case Node.COMMENT_NODE: // case Node.PROCESSING_INSTRUCTION_NODE: // return node.getNodeValue(); // // case Node.ELEMENT_NODE: // case Node.ATTRIBUTE_NODE: // case Node.ENTITY_NODE: // case Node.ENTITY_REFERENCE_NODE: // case Node.DOCUMENT_FRAGMENT_NODE: // StringBuffer value = new StringBuffer(); // for (Node childNode: new IterableNodeList(node.getChildNodes())) { // int childNodeType = childNode.getNodeType(); // if (childNodeType != Node.COMMENT_NODE // && childNodeType != Node.PROCESSING_INSTRUCTION_NODE) { // value.append(getTextContentImpl(childNode, recursionDepth + 1)); // } // } // return value.toString(); // } // // Log.d(LOG_TAG, "unexpected node type: " + node.getNodeType()); // return null; // } // } // Path: src/org/npr/api/StoryGrouping.java import android.util.Log; import org.apache.http.client.ClientProtocolException; import org.npr.android.util.NodeUtils; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeSet; import javax.xml.parsers.ParserConfigurationException; resultSet.add(p); } } for (T p : resultSet) { result.add(p); } return result; } @SuppressWarnings("unchecked") private T createStoryGrouping(Class<T> c, Node node) { if (!node.getNodeName().equals("item") || !node.hasChildNodes()) { return null; } String id; int storycounttoday, storycountmonth, storycountall; id = node.getAttributes().getNamedItem("id").getNodeValue(); storycountall = Integer.parseInt(node.getAttributes().getNamedItem( "storycountall").getNodeValue()); storycountmonth = Integer.parseInt(node.getAttributes().getNamedItem( "storycountmonth").getNodeValue()); storycounttoday = Integer.parseInt(node.getAttributes().getNamedItem( "storycounttoday").getNodeValue()); StoryGroupingBuilder<? extends StoryGrouping> sb = new StoryGroupingBuilder<T>(c, id, storycounttoday, storycountmonth, storycountall); for (Node n : new IterableNodeList(node.getChildNodes())) { String nodeName = n.getNodeName(); if (nodeName.equals("title")) {
sb.withTitle(NodeUtils.getTextContent(n));
unofficial/npr-android-app
src/org/npr/android/news/ListenView.java
// Path: src/org/npr/android/util/PlaylistEntry.java // public class PlaylistEntry { // public long id; // public final String url; // public final String title; // public final boolean isStream; // public int order; // public final String storyID; // // public PlaylistEntry(long id, String url, String title, boolean isStream, // int order) { // this(id, url, title, isStream, order, null); // } // // public PlaylistEntry(long id, String url, String title, boolean isStream, // int order, String storyID) { // this.id = id; // this.url = url; // this.title = title; // this.isStream = isStream; // this.order = order; // this.storyID = storyID; // } // }
import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.IBinder; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.SlidingDrawer; import android.widget.TextView; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.SlidingDrawer.OnDrawerCloseListener; import android.widget.SlidingDrawer.OnDrawerOpenListener; import org.npr.android.util.PlaylistEntry; import java.io.IOException;
playButtonisPause = false; } else { player.play(); playButton.setImageResource(android.R.drawable.ic_media_pause); playButtonisPause = true; } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.StreamPlayButton: togglePlay(); break; case R.id.StreamPlaylistButton: getContext().startActivity( new Intent(getContext(), PlaylistActivity.class)); break; case R.id.StreamShareButton: Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); // shareIntent.putExtra(Intent.EXTRA_SUBJECT, current.title); // shareIntent.putExtra(Intent.EXTRA_TEXT, String.format("%s: %s", // current.title, current.url)); shareIntent.setType("text/plain"); getContext().startActivity(Intent.createChooser(shareIntent, getContext().getString(R.string.msg_share_story))); break; } }
// Path: src/org/npr/android/util/PlaylistEntry.java // public class PlaylistEntry { // public long id; // public final String url; // public final String title; // public final boolean isStream; // public int order; // public final String storyID; // // public PlaylistEntry(long id, String url, String title, boolean isStream, // int order) { // this(id, url, title, isStream, order, null); // } // // public PlaylistEntry(long id, String url, String title, boolean isStream, // int order, String storyID) { // this.id = id; // this.url = url; // this.title = title; // this.isStream = isStream; // this.order = order; // this.storyID = storyID; // } // } // Path: src/org/npr/android/news/ListenView.java import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.IBinder; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.SlidingDrawer; import android.widget.TextView; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.SlidingDrawer.OnDrawerCloseListener; import android.widget.SlidingDrawer.OnDrawerOpenListener; import org.npr.android.util.PlaylistEntry; import java.io.IOException; playButtonisPause = false; } else { player.play(); playButton.setImageResource(android.R.drawable.ic_media_pause); playButtonisPause = true; } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.StreamPlayButton: togglePlay(); break; case R.id.StreamPlaylistButton: getContext().startActivity( new Intent(getContext(), PlaylistActivity.class)); break; case R.id.StreamShareButton: Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); // shareIntent.putExtra(Intent.EXTRA_SUBJECT, current.title); // shareIntent.putExtra(Intent.EXTRA_TEXT, String.format("%s: %s", // current.title, current.url)); shareIntent.setType("text/plain"); getContext().startActivity(Intent.createChooser(shareIntent, getContext().getString(R.string.msg_share_story))); break; } }
protected void listen(PlaylistEntry entry) {
unofficial/npr-android-app
src/org/npr/api/Station.java
// Path: src/org/npr/android/util/NodeUtils.java // public class NodeUtils { // public static final String LOG_TAG = NodeUtils.class.getName(); // private static boolean getTextContentAvailable = true; // private static Method getTextContentMethod = null; // // private final static int MAX_RECURSION_DEPTH = 10; // // /** // * Node#getTextContent() is only available in Froyo and later. // * Call getTextContent if it exists else use local implementation // * @param node // * @return text content of this node and its descendant // */ // public static String getTextContent(Node node) { // if (getTextContentAvailable && getTextContentMethod == null) { // try { // getTextContentMethod = Node.class.getMethod( // "getTextContent", (Class[]) null ); // } catch (NoSuchMethodException nsme) { // // failure, must be older device // getTextContentAvailable = false; // } // } // // if (getTextContentAvailable) { // try { // String value = (String) getTextContentMethod.invoke(node); // return value; // } catch (IllegalArgumentException e1) { // getTextContentAvailable = false; // } catch (IllegalAccessException e1) { // getTextContentAvailable = false; // } catch (InvocationTargetException e1) { // getTextContentAvailable = false; // } // } // // // getTextContent doesn't exist. // return getTextContentImpl(node, 0); // } // // /** // * implementation based on Javadoc description of getTextContent // * @param node // * @return text content of this node and its descendant // */ // private static String getTextContentImpl(Node node, int recursionDepth) { // // should never happen but don't allow too much recursion // if (recursionDepth > MAX_RECURSION_DEPTH) { // Log.d(LOG_TAG, "too much recursion!"); // return ""; // } // // switch (node.getNodeType()) { // case Node.TEXT_NODE: // case Node.CDATA_SECTION_NODE: // case Node.COMMENT_NODE: // case Node.PROCESSING_INSTRUCTION_NODE: // return node.getNodeValue(); // // case Node.ELEMENT_NODE: // case Node.ATTRIBUTE_NODE: // case Node.ENTITY_NODE: // case Node.ENTITY_REFERENCE_NODE: // case Node.DOCUMENT_FRAGMENT_NODE: // StringBuffer value = new StringBuffer(); // for (Node childNode: new IterableNodeList(node.getChildNodes())) { // int childNodeType = childNode.getNodeType(); // if (childNodeType != Node.COMMENT_NODE // && childNodeType != Node.PROCESSING_INSTRUCTION_NODE) { // value.append(getTextContentImpl(childNode, recursionDepth + 1)); // } // } // return value.toString(); // } // // Log.d(LOG_TAG, "unexpected node type: " + node.getNodeType()); // return null; // } // }
import javax.xml.parsers.ParserConfigurationException; import android.util.Log; import org.apache.http.client.ClientProtocolException; import org.npr.android.util.NodeUtils; import org.w3c.dom.Attr; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map;
podcasts, tagline, image); } } public static class StationFactory { public static List<Station> parseStations(Node rootNode) { List<Station> result = new ArrayList<Station>(); NodeList stationList = rootNode.getChildNodes(); for (Node stationNode : new IterableNodeList(stationList)) { Station station = createStation(stationNode); if (station != null) { result.add(station); } } return result; } private static Station createStation(Node node) { if (!node.getNodeName().equals("station") || !node.hasChildNodes()) { return null; } StationBuilder sb = new StationBuilder(node.getAttributes().getNamedItem( "id").getNodeValue()); List<AudioStream> streams = new LinkedList<AudioStream>(); List<Podcast> podcasts = new LinkedList<Podcast>(); for (Node n : new IterableNodeList(node.getChildNodes())) { String nodeName = n.getNodeName(); Node nodeChild = n.getChildNodes().item(0); if (nodeName.equals("name")) {
// Path: src/org/npr/android/util/NodeUtils.java // public class NodeUtils { // public static final String LOG_TAG = NodeUtils.class.getName(); // private static boolean getTextContentAvailable = true; // private static Method getTextContentMethod = null; // // private final static int MAX_RECURSION_DEPTH = 10; // // /** // * Node#getTextContent() is only available in Froyo and later. // * Call getTextContent if it exists else use local implementation // * @param node // * @return text content of this node and its descendant // */ // public static String getTextContent(Node node) { // if (getTextContentAvailable && getTextContentMethod == null) { // try { // getTextContentMethod = Node.class.getMethod( // "getTextContent", (Class[]) null ); // } catch (NoSuchMethodException nsme) { // // failure, must be older device // getTextContentAvailable = false; // } // } // // if (getTextContentAvailable) { // try { // String value = (String) getTextContentMethod.invoke(node); // return value; // } catch (IllegalArgumentException e1) { // getTextContentAvailable = false; // } catch (IllegalAccessException e1) { // getTextContentAvailable = false; // } catch (InvocationTargetException e1) { // getTextContentAvailable = false; // } // } // // // getTextContent doesn't exist. // return getTextContentImpl(node, 0); // } // // /** // * implementation based on Javadoc description of getTextContent // * @param node // * @return text content of this node and its descendant // */ // private static String getTextContentImpl(Node node, int recursionDepth) { // // should never happen but don't allow too much recursion // if (recursionDepth > MAX_RECURSION_DEPTH) { // Log.d(LOG_TAG, "too much recursion!"); // return ""; // } // // switch (node.getNodeType()) { // case Node.TEXT_NODE: // case Node.CDATA_SECTION_NODE: // case Node.COMMENT_NODE: // case Node.PROCESSING_INSTRUCTION_NODE: // return node.getNodeValue(); // // case Node.ELEMENT_NODE: // case Node.ATTRIBUTE_NODE: // case Node.ENTITY_NODE: // case Node.ENTITY_REFERENCE_NODE: // case Node.DOCUMENT_FRAGMENT_NODE: // StringBuffer value = new StringBuffer(); // for (Node childNode: new IterableNodeList(node.getChildNodes())) { // int childNodeType = childNode.getNodeType(); // if (childNodeType != Node.COMMENT_NODE // && childNodeType != Node.PROCESSING_INSTRUCTION_NODE) { // value.append(getTextContentImpl(childNode, recursionDepth + 1)); // } // } // return value.toString(); // } // // Log.d(LOG_TAG, "unexpected node type: " + node.getNodeType()); // return null; // } // } // Path: src/org/npr/api/Station.java import javax.xml.parsers.ParserConfigurationException; import android.util.Log; import org.apache.http.client.ClientProtocolException; import org.npr.android.util.NodeUtils; import org.w3c.dom.Attr; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; podcasts, tagline, image); } } public static class StationFactory { public static List<Station> parseStations(Node rootNode) { List<Station> result = new ArrayList<Station>(); NodeList stationList = rootNode.getChildNodes(); for (Node stationNode : new IterableNodeList(stationList)) { Station station = createStation(stationNode); if (station != null) { result.add(station); } } return result; } private static Station createStation(Node node) { if (!node.getNodeName().equals("station") || !node.hasChildNodes()) { return null; } StationBuilder sb = new StationBuilder(node.getAttributes().getNamedItem( "id").getNodeValue()); List<AudioStream> streams = new LinkedList<AudioStream>(); List<Podcast> podcasts = new LinkedList<Podcast>(); for (Node n : new IterableNodeList(node.getChildNodes())) { String nodeName = n.getNodeName(); Node nodeChild = n.getChildNodes().item(0); if (nodeName.equals("name")) {
sb.withName(NodeUtils.getTextContent(n));
unofficial/npr-android-app
src/org/npr/android/util/NodeUtils.java
// Path: src/org/npr/api/IterableNodeList.java // public class IterableNodeList implements Iterable<Node>, Iterator<Node> { // private final NodeList nodeList; // int index = 0; // // public IterableNodeList(NodeList nodeList) { // this.nodeList = nodeList; // } // // @Override // public Iterator<Node> iterator() { // return this; // } // // @Override // public boolean hasNext() { // return index < nodeList.getLength(); // } // // @Override // public Node next() { // Node item = nodeList.item(index++); // return item; // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // }
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.npr.api.IterableNodeList; import org.w3c.dom.Node; import android.util.Log;
// getTextContent doesn't exist. return getTextContentImpl(node, 0); } /** * implementation based on Javadoc description of getTextContent * @param node * @return text content of this node and its descendant */ private static String getTextContentImpl(Node node, int recursionDepth) { // should never happen but don't allow too much recursion if (recursionDepth > MAX_RECURSION_DEPTH) { Log.d(LOG_TAG, "too much recursion!"); return ""; } switch (node.getNodeType()) { case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: return node.getNodeValue(); case Node.ELEMENT_NODE: case Node.ATTRIBUTE_NODE: case Node.ENTITY_NODE: case Node.ENTITY_REFERENCE_NODE: case Node.DOCUMENT_FRAGMENT_NODE: StringBuffer value = new StringBuffer();
// Path: src/org/npr/api/IterableNodeList.java // public class IterableNodeList implements Iterable<Node>, Iterator<Node> { // private final NodeList nodeList; // int index = 0; // // public IterableNodeList(NodeList nodeList) { // this.nodeList = nodeList; // } // // @Override // public Iterator<Node> iterator() { // return this; // } // // @Override // public boolean hasNext() { // return index < nodeList.getLength(); // } // // @Override // public Node next() { // Node item = nodeList.item(index++); // return item; // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // } // Path: src/org/npr/android/util/NodeUtils.java import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.npr.api.IterableNodeList; import org.w3c.dom.Node; import android.util.Log; // getTextContent doesn't exist. return getTextContentImpl(node, 0); } /** * implementation based on Javadoc description of getTextContent * @param node * @return text content of this node and its descendant */ private static String getTextContentImpl(Node node, int recursionDepth) { // should never happen but don't allow too much recursion if (recursionDepth > MAX_RECURSION_DEPTH) { Log.d(LOG_TAG, "too much recursion!"); return ""; } switch (node.getNodeType()) { case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: return node.getNodeValue(); case Node.ELEMENT_NODE: case Node.ATTRIBUTE_NODE: case Node.ENTITY_NODE: case Node.ENTITY_REFERENCE_NODE: case Node.DOCUMENT_FRAGMENT_NODE: StringBuffer value = new StringBuffer();
for (Node childNode: new IterableNodeList(node.getChildNodes())) {
forax/jsjs
src/com/github/forax/jsjs/RT.java
// Path: src/com/github/forax/jsjs/JSObject.java // static void setPrototypeOf(JSObject object, JSObject proto) { // if (object.proto != null) { // throw new Error("prototype already set"); // } // object.hiddenClass = object.hiddenClass.forwardProto(); // object.proto = proto; // object.invalidate(); // } // // Path: src/com/github/forax/jsjs/JSObject.java // static final class HiddenClass { // final HashMap<String, Integer> slotMap; // final HashMap<String, HiddenClass> forwardMap = new HashMap<>(); // // HiddenClass(HashMap<String, Integer> slotMap) { // this.slotMap = slotMap; // } // // Integer slot(String key) { // return slotMap.get(key); // } // // HiddenClass forward(String key) { // return forwardMap.computeIfAbsent(key, k -> { // HashMap<String, Integer> slotMap = new HashMap<>(); // slotMap.putAll(this.slotMap); // slotMap.put(k, slotMap.size()); // return new HiddenClass(slotMap); // }); // } // HiddenClass forwardProto() { // return forwardMap.computeIfAbsent(PROTO_KEY, k -> new HiddenClass(slotMap)); // } // // @Override // public String toString() { // DEBUG // return slotMap.keySet().stream().map(Object::toString).collect(java.util.stream.Collectors.joining(", ", "[", "]")); // } // }
import static com.github.forax.jsjs.JSObject.setPrototypeOf; import static java.lang.invoke.MethodHandles.constant; import static java.lang.invoke.MethodHandles.dropArguments; import static java.lang.invoke.MethodHandles.exactInvoker; import static java.lang.invoke.MethodHandles.filterReturnValue; import static java.lang.invoke.MethodHandles.foldArguments; import static java.lang.invoke.MethodHandles.guardWithTest; import static java.lang.invoke.MethodHandles.identity; import static java.lang.invoke.MethodHandles.insertArguments; import static java.lang.invoke.MethodHandles.lookup; import static java.lang.invoke.MethodHandles.publicLookup; import static java.lang.invoke.MethodType.genericMethodType; import static java.lang.invoke.MethodType.methodType; import java.lang.invoke.CallSite; import java.lang.invoke.ConstantCallSite; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodType; import java.lang.invoke.MutableCallSite; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; import com.github.forax.jsjs.JSObject.HiddenClass;
metadata.set(field.getName(), field.get(null)); } catch (IllegalArgumentException | IllegalAccessException e) { throw new AssertionError(e); } } } static final ClassValue<JSFunction> JAVA_TYPE_MAP = classValue(type -> { JSObject prototype = new JSObject(); populateWithMethods(prototype, type, selectInstanceMethod(true), UnaryOperator.identity()); JSFunction function = createJavaType(type); //setPrototypeOf(function, prototype); // FIXME function.set(JSObject.PROTOTYPE_KEY, prototype); populateWithStaticFields(function, type); populateWithMethods(function, type, selectInstanceMethod(false), mh -> dropArguments(mh, 0, Object.class)); function.set("class", type); // interrop with Java return function; }); private static final ThreadLocal<JSObject> GLOBAL_MAP_TL_INIT = new ThreadLocal<>(); static final ClassValue<JSObject> GLOBAL_MAP = classValue(type -> { if (type.getName().equals("boot.boot")) { return GLOBAL_MAP_TL_INIT.get(); // ugly hack, global is already initialized, just return it } JSObject global = new JSObject(); global.set("global", global); JSFunction builtins = JAVA_TYPE_MAP.get(Builtins.class);
// Path: src/com/github/forax/jsjs/JSObject.java // static void setPrototypeOf(JSObject object, JSObject proto) { // if (object.proto != null) { // throw new Error("prototype already set"); // } // object.hiddenClass = object.hiddenClass.forwardProto(); // object.proto = proto; // object.invalidate(); // } // // Path: src/com/github/forax/jsjs/JSObject.java // static final class HiddenClass { // final HashMap<String, Integer> slotMap; // final HashMap<String, HiddenClass> forwardMap = new HashMap<>(); // // HiddenClass(HashMap<String, Integer> slotMap) { // this.slotMap = slotMap; // } // // Integer slot(String key) { // return slotMap.get(key); // } // // HiddenClass forward(String key) { // return forwardMap.computeIfAbsent(key, k -> { // HashMap<String, Integer> slotMap = new HashMap<>(); // slotMap.putAll(this.slotMap); // slotMap.put(k, slotMap.size()); // return new HiddenClass(slotMap); // }); // } // HiddenClass forwardProto() { // return forwardMap.computeIfAbsent(PROTO_KEY, k -> new HiddenClass(slotMap)); // } // // @Override // public String toString() { // DEBUG // return slotMap.keySet().stream().map(Object::toString).collect(java.util.stream.Collectors.joining(", ", "[", "]")); // } // } // Path: src/com/github/forax/jsjs/RT.java import static com.github.forax.jsjs.JSObject.setPrototypeOf; import static java.lang.invoke.MethodHandles.constant; import static java.lang.invoke.MethodHandles.dropArguments; import static java.lang.invoke.MethodHandles.exactInvoker; import static java.lang.invoke.MethodHandles.filterReturnValue; import static java.lang.invoke.MethodHandles.foldArguments; import static java.lang.invoke.MethodHandles.guardWithTest; import static java.lang.invoke.MethodHandles.identity; import static java.lang.invoke.MethodHandles.insertArguments; import static java.lang.invoke.MethodHandles.lookup; import static java.lang.invoke.MethodHandles.publicLookup; import static java.lang.invoke.MethodType.genericMethodType; import static java.lang.invoke.MethodType.methodType; import java.lang.invoke.CallSite; import java.lang.invoke.ConstantCallSite; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodType; import java.lang.invoke.MutableCallSite; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; import com.github.forax.jsjs.JSObject.HiddenClass; metadata.set(field.getName(), field.get(null)); } catch (IllegalArgumentException | IllegalAccessException e) { throw new AssertionError(e); } } } static final ClassValue<JSFunction> JAVA_TYPE_MAP = classValue(type -> { JSObject prototype = new JSObject(); populateWithMethods(prototype, type, selectInstanceMethod(true), UnaryOperator.identity()); JSFunction function = createJavaType(type); //setPrototypeOf(function, prototype); // FIXME function.set(JSObject.PROTOTYPE_KEY, prototype); populateWithStaticFields(function, type); populateWithMethods(function, type, selectInstanceMethod(false), mh -> dropArguments(mh, 0, Object.class)); function.set("class", type); // interrop with Java return function; }); private static final ThreadLocal<JSObject> GLOBAL_MAP_TL_INIT = new ThreadLocal<>(); static final ClassValue<JSObject> GLOBAL_MAP = classValue(type -> { if (type.getName().equals("boot.boot")) { return GLOBAL_MAP_TL_INIT.get(); // ugly hack, global is already initialized, just return it } JSObject global = new JSObject(); global.set("global", global); JSFunction builtins = JAVA_TYPE_MAP.get(Builtins.class);
setPrototypeOf(global, builtins);
forax/jsjs
src/com/github/forax/jsjs/RT.java
// Path: src/com/github/forax/jsjs/JSObject.java // static void setPrototypeOf(JSObject object, JSObject proto) { // if (object.proto != null) { // throw new Error("prototype already set"); // } // object.hiddenClass = object.hiddenClass.forwardProto(); // object.proto = proto; // object.invalidate(); // } // // Path: src/com/github/forax/jsjs/JSObject.java // static final class HiddenClass { // final HashMap<String, Integer> slotMap; // final HashMap<String, HiddenClass> forwardMap = new HashMap<>(); // // HiddenClass(HashMap<String, Integer> slotMap) { // this.slotMap = slotMap; // } // // Integer slot(String key) { // return slotMap.get(key); // } // // HiddenClass forward(String key) { // return forwardMap.computeIfAbsent(key, k -> { // HashMap<String, Integer> slotMap = new HashMap<>(); // slotMap.putAll(this.slotMap); // slotMap.put(k, slotMap.size()); // return new HiddenClass(slotMap); // }); // } // HiddenClass forwardProto() { // return forwardMap.computeIfAbsent(PROTO_KEY, k -> new HiddenClass(slotMap)); // } // // @Override // public String toString() { // DEBUG // return slotMap.keySet().stream().map(Object::toString).collect(java.util.stream.Collectors.joining(", ", "[", "]")); // } // }
import static com.github.forax.jsjs.JSObject.setPrototypeOf; import static java.lang.invoke.MethodHandles.constant; import static java.lang.invoke.MethodHandles.dropArguments; import static java.lang.invoke.MethodHandles.exactInvoker; import static java.lang.invoke.MethodHandles.filterReturnValue; import static java.lang.invoke.MethodHandles.foldArguments; import static java.lang.invoke.MethodHandles.guardWithTest; import static java.lang.invoke.MethodHandles.identity; import static java.lang.invoke.MethodHandles.insertArguments; import static java.lang.invoke.MethodHandles.lookup; import static java.lang.invoke.MethodHandles.publicLookup; import static java.lang.invoke.MethodType.genericMethodType; import static java.lang.invoke.MethodType.methodType; import java.lang.invoke.CallSite; import java.lang.invoke.ConstantCallSite; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodType; import java.lang.invoke.MutableCallSite; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; import com.github.forax.jsjs.JSObject.HiddenClass;
methodType(MethodHandle.class, PolymorphicInliningCacheCallSite.class, Object.class)); } private static boolean typeCheck(Class<?> type, Object receiver) { return receiver.getClass() == type; } private static boolean pointerCheck(Object instance, Object receiver) { return instance == receiver; } interface MHFactory<T> { MethodHandle create(Lookup lookup, Class<?> declaringClass, String name, T type) throws NoSuchMethodException, NoSuchFieldException, IllegalAccessException; } static <T> MethodHandle mh(Lookup lookup, MHFactory<T> factory, Class<?> declaringClass, String name, T type) { try { return factory.create(lookup, declaringClass, name, type); } catch (NoSuchMethodException | NoSuchFieldException | IllegalAccessException e) { throw new AssertionError(e); } } private static final MethodHandle JSOBJECT_NEW, DEF; static final MethodHandle TYPE_CHECK, POINTER_CHECK, SET_TARGET, NEW_OBJECT_ARRAY, JSOBJECT_LITERAL_NEW; static { Lookup lookup = MethodHandles.lookup(); MHFactory<MethodType> findStatic = Lookup::findStatic; JSOBJECT_NEW = mh(lookup, findStatic, JSObject.class, "newJSObject", methodType(JSObject.class, JSObject.class)); NEW_OBJECT_ARRAY = mh(lookup, findStatic, RT.class, "newObjectArray", methodType(Object[].class, int.class));
// Path: src/com/github/forax/jsjs/JSObject.java // static void setPrototypeOf(JSObject object, JSObject proto) { // if (object.proto != null) { // throw new Error("prototype already set"); // } // object.hiddenClass = object.hiddenClass.forwardProto(); // object.proto = proto; // object.invalidate(); // } // // Path: src/com/github/forax/jsjs/JSObject.java // static final class HiddenClass { // final HashMap<String, Integer> slotMap; // final HashMap<String, HiddenClass> forwardMap = new HashMap<>(); // // HiddenClass(HashMap<String, Integer> slotMap) { // this.slotMap = slotMap; // } // // Integer slot(String key) { // return slotMap.get(key); // } // // HiddenClass forward(String key) { // return forwardMap.computeIfAbsent(key, k -> { // HashMap<String, Integer> slotMap = new HashMap<>(); // slotMap.putAll(this.slotMap); // slotMap.put(k, slotMap.size()); // return new HiddenClass(slotMap); // }); // } // HiddenClass forwardProto() { // return forwardMap.computeIfAbsent(PROTO_KEY, k -> new HiddenClass(slotMap)); // } // // @Override // public String toString() { // DEBUG // return slotMap.keySet().stream().map(Object::toString).collect(java.util.stream.Collectors.joining(", ", "[", "]")); // } // } // Path: src/com/github/forax/jsjs/RT.java import static com.github.forax.jsjs.JSObject.setPrototypeOf; import static java.lang.invoke.MethodHandles.constant; import static java.lang.invoke.MethodHandles.dropArguments; import static java.lang.invoke.MethodHandles.exactInvoker; import static java.lang.invoke.MethodHandles.filterReturnValue; import static java.lang.invoke.MethodHandles.foldArguments; import static java.lang.invoke.MethodHandles.guardWithTest; import static java.lang.invoke.MethodHandles.identity; import static java.lang.invoke.MethodHandles.insertArguments; import static java.lang.invoke.MethodHandles.lookup; import static java.lang.invoke.MethodHandles.publicLookup; import static java.lang.invoke.MethodType.genericMethodType; import static java.lang.invoke.MethodType.methodType; import java.lang.invoke.CallSite; import java.lang.invoke.ConstantCallSite; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.invoke.MethodType; import java.lang.invoke.MutableCallSite; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; import com.github.forax.jsjs.JSObject.HiddenClass; methodType(MethodHandle.class, PolymorphicInliningCacheCallSite.class, Object.class)); } private static boolean typeCheck(Class<?> type, Object receiver) { return receiver.getClass() == type; } private static boolean pointerCheck(Object instance, Object receiver) { return instance == receiver; } interface MHFactory<T> { MethodHandle create(Lookup lookup, Class<?> declaringClass, String name, T type) throws NoSuchMethodException, NoSuchFieldException, IllegalAccessException; } static <T> MethodHandle mh(Lookup lookup, MHFactory<T> factory, Class<?> declaringClass, String name, T type) { try { return factory.create(lookup, declaringClass, name, type); } catch (NoSuchMethodException | NoSuchFieldException | IllegalAccessException e) { throw new AssertionError(e); } } private static final MethodHandle JSOBJECT_NEW, DEF; static final MethodHandle TYPE_CHECK, POINTER_CHECK, SET_TARGET, NEW_OBJECT_ARRAY, JSOBJECT_LITERAL_NEW; static { Lookup lookup = MethodHandles.lookup(); MHFactory<MethodType> findStatic = Lookup::findStatic; JSOBJECT_NEW = mh(lookup, findStatic, JSObject.class, "newJSObject", methodType(JSObject.class, JSObject.class)); NEW_OBJECT_ARRAY = mh(lookup, findStatic, RT.class, "newObjectArray", methodType(Object[].class, int.class));
JSOBJECT_LITERAL_NEW = mh(lookup, findStatic, JSObject.class, "newJSLiteralObject", methodType(JSObject.class, HiddenClass.class, JSObject.class, Object[].class));
forax/jsjs
src/com/github/forax/jsjs/JSFunction.java
// Path: src/com/github/forax/jsjs/RT.java // static interface MOP { // MethodType type(); // int counter(); // MethodHandle invalidate(MethodHandle target); // // default MOP withType(MethodType methodType) { // return new MOP() { // @Override // public MethodType type() { // return methodType; // } // @Override // public int counter() { // return MOP.this.counter(); // } // @Override // public MethodHandle invalidate(MethodHandle target) { // return MOP.this.invalidate(target); // } // }; // } // }
import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.util.function.BiFunction; import java.util.function.Function; import com.github.forax.jsjs.RT.MOP;
package com.github.forax.jsjs; public final class JSFunction extends JSObject { private final String name; private final Function<MethodType, MethodHandle> functionFactory;
// Path: src/com/github/forax/jsjs/RT.java // static interface MOP { // MethodType type(); // int counter(); // MethodHandle invalidate(MethodHandle target); // // default MOP withType(MethodType methodType) { // return new MOP() { // @Override // public MethodType type() { // return methodType; // } // @Override // public int counter() { // return MOP.this.counter(); // } // @Override // public MethodHandle invalidate(MethodHandle target) { // return MOP.this.invalidate(target); // } // }; // } // } // Path: src/com/github/forax/jsjs/JSFunction.java import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.util.function.BiFunction; import java.util.function.Function; import com.github.forax.jsjs.RT.MOP; package com.github.forax.jsjs; public final class JSFunction extends JSObject { private final String name; private final Function<MethodType, MethodHandle> functionFactory;
private final BiFunction<JSFunction, MOP, MethodHandle> constructorFactory;
forax/jsjs
src/com/github/forax/jsjs/JSArray.java
// Path: src/com/github/forax/jsjs/RT.java // static <T> MethodHandle mh(Lookup lookup, MHFactory<T> factory, Class<?> declaringClass, String name, T type) { // try { // return factory.create(lookup, declaringClass, name, type); // } catch (NoSuchMethodException | NoSuchFieldException | IllegalAccessException e) { // throw new AssertionError(e); // } // }
import static com.github.forax.jsjs.RT.mh; import static java.lang.invoke.MethodHandles.lookup; import static java.lang.invoke.MethodType.methodType; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles.Lookup; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects;
} @Override public Object next() { try { return array[i++]; } catch(ArrayIndexOutOfBoundsException e) { throw new NoSuchElementException(); } } }; } final void sort() { Arrays.sort(array); } @Override final MethodHandle getArrayGetter() { return GET_INDEX.asType(methodType(Object.class, JSObject.class, Object.class)); } @Override final MethodHandle getArraySetter() { return SET_INDEX.asType(methodType(void.class, JSObject.class, Object.class, Object.class)); } private static final String LENGTH_KEY = "length"; private static final MethodHandle GET_INDEX, SET_INDEX; static { Lookup lookup = lookup();
// Path: src/com/github/forax/jsjs/RT.java // static <T> MethodHandle mh(Lookup lookup, MHFactory<T> factory, Class<?> declaringClass, String name, T type) { // try { // return factory.create(lookup, declaringClass, name, type); // } catch (NoSuchMethodException | NoSuchFieldException | IllegalAccessException e) { // throw new AssertionError(e); // } // } // Path: src/com/github/forax/jsjs/JSArray.java import static com.github.forax.jsjs.RT.mh; import static java.lang.invoke.MethodHandles.lookup; import static java.lang.invoke.MethodType.methodType; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles.Lookup; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; } @Override public Object next() { try { return array[i++]; } catch(ArrayIndexOutOfBoundsException e) { throw new NoSuchElementException(); } } }; } final void sort() { Arrays.sort(array); } @Override final MethodHandle getArrayGetter() { return GET_INDEX.asType(methodType(Object.class, JSObject.class, Object.class)); } @Override final MethodHandle getArraySetter() { return SET_INDEX.asType(methodType(void.class, JSObject.class, Object.class, Object.class)); } private static final String LENGTH_KEY = "length"; private static final MethodHandle GET_INDEX, SET_INDEX; static { Lookup lookup = lookup();
GET_INDEX = mh(lookup, Lookup::findVirtual, JSArray.class, "get", methodType(Object.class, int.class));
EManual/EManual-Android
app/src/main/java/io/github/emanual/app/ui/event/InterviewDownloadEndEvent.java
// Path: app/src/main/java/io/github/emanual/app/entity/FeedsItemEntity.java // public class FeedsItemEntity extends BaseEntity implements Serializable{ // private String name; // private String name_cn; // private String md5; // private String icon_url; // private String url; // private String author; // private String homepage; // // /** // * 获取book的下载url // * NOTE: // * 在url上加上`?v=xxxx` // * @return // */ // public String getDownloadUrl(){ // return String.format("%s?v=%s", getUrl(), getMd5()); // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getHomepage() { // return homepage; // } // // public void setHomepage(String homepage) { // this.homepage = homepage; // } // // public String getIcon_url() { // return icon_url; // } // // public void setIcon_url(String icon_url) { // this.icon_url = icon_url; // } // // public String getMd5() { // return md5; // } // // public void setMd5(String md5) { // this.md5 = md5; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getName_cn() { // return name_cn; // } // // public void setName_cn(String name_cn) { // this.name_cn = name_cn; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // @Override public String toString() { // return "FeedsItemEntity{" + // "author='" + author + '\'' + // ", name='" + name + '\'' + // ", name_cn='" + name_cn + '\'' + // ", md5='" + md5 + '\'' + // ", icon_url='" + icon_url + '\'' + // ", url='" + url + '\'' + // ", homepage='" + homepage + '\'' + // '}'; // } // }
import java.io.File; import io.github.emanual.app.entity.FeedsItemEntity;
package io.github.emanual.app.ui.event; /** * Author: jayin * Date: 2/23/16 */ public class InterviewDownloadEndEvent extends BaseEvent { private File file;
// Path: app/src/main/java/io/github/emanual/app/entity/FeedsItemEntity.java // public class FeedsItemEntity extends BaseEntity implements Serializable{ // private String name; // private String name_cn; // private String md5; // private String icon_url; // private String url; // private String author; // private String homepage; // // /** // * 获取book的下载url // * NOTE: // * 在url上加上`?v=xxxx` // * @return // */ // public String getDownloadUrl(){ // return String.format("%s?v=%s", getUrl(), getMd5()); // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getHomepage() { // return homepage; // } // // public void setHomepage(String homepage) { // this.homepage = homepage; // } // // public String getIcon_url() { // return icon_url; // } // // public void setIcon_url(String icon_url) { // this.icon_url = icon_url; // } // // public String getMd5() { // return md5; // } // // public void setMd5(String md5) { // this.md5 = md5; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getName_cn() { // return name_cn; // } // // public void setName_cn(String name_cn) { // this.name_cn = name_cn; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // @Override public String toString() { // return "FeedsItemEntity{" + // "author='" + author + '\'' + // ", name='" + name + '\'' + // ", name_cn='" + name_cn + '\'' + // ", md5='" + md5 + '\'' + // ", icon_url='" + icon_url + '\'' + // ", url='" + url + '\'' + // ", homepage='" + homepage + '\'' + // '}'; // } // } // Path: app/src/main/java/io/github/emanual/app/ui/event/InterviewDownloadEndEvent.java import java.io.File; import io.github.emanual.app.entity.FeedsItemEntity; package io.github.emanual.app.ui.event; /** * Author: jayin * Date: 2/23/16 */ public class InterviewDownloadEndEvent extends BaseEvent { private File file;
private FeedsItemEntity feedsItemEntity;
EManual/EManual-Android
app/src/main/java/io/github/emanual/app/ui/QuestionDetailActivity.java
// Path: app/src/main/java/io/github/emanual/app/entity/QuestionEntity.java // public class QuestionEntity extends BaseEntity { // /** // * 回答 // */ // private final static String TYPE_REPLY = "reply"; // /** // * 选择 // */ // private final static String TYPE_CHOICE = "choice"; // /** // * 判断 // */ // private final static String TYPE_JUDGMENT = "judgment"; // private String type; // private String tag; // private int difficulty; // private String from; // private String description; // private String answer; // private List<String> options; // // public String getAnswer() { // return answer; // } // // public void setAnswer(String answer) { // this.answer = answer; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public int getDifficulty() { // return difficulty; // } // // public void setDifficulty(int difficulty) { // this.difficulty = difficulty; // } // // public String getFrom() { // return from; // } // // public void setFrom(String from) { // this.from = from; // } // // public List<String> getOptions() { // return options; // } // // public void setOptions(List<String> options) { // this.options = options; // } // // public String getTag() { // return tag; // } // // public void setTag(String tag) { // this.tag = tag; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // @Override public String toString() { // return "QuestionEntity{" + // "answer='" + answer + '\'' + // ", type='" + type + '\'' + // ", tag='" + tag + '\'' + // ", difficulty=" + difficulty + // ", from='" + from + '\'' + // ", description='" + description + '\'' + // ", options=" + options + // '}'; // } // } // // Path: app/src/main/java/io/github/emanual/app/ui/base/activity/SwipeBackActivity.java // public abstract class SwipeBackActivity extends BaseActivity { // @Bind(R.id.swipBackLayout) SwipeBackLayout mSwipeBackLayout; // // @Override protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // mSwipeBackLayout.setCallBack(new SwipeBackLayout.CallBack() { // @Override // public void onFinish() { // finish(); // } // }); // } // // public SwipeBackLayout getSwipeBackLayout() { // return mSwipeBackLayout; // } // } // // Path: app/src/main/java/io/github/emanual/app/ui/event/QuestionUpdateEvent.java // public class QuestionUpdateEvent extends BaseEvent{ // private QuestionEntity questionEntity; // // public QuestionUpdateEvent(QuestionEntity questionEntity){ // this.questionEntity = questionEntity; // } // // public QuestionEntity getQuestionEntity() { // return questionEntity; // } // // public void setQuestionEntity(QuestionEntity questionEntity) { // this.questionEntity = questionEntity; // } // } // // Path: app/src/main/java/io/github/emanual/app/widget/DefaultWebView.java // public class DefaultWebView extends WebView{ // // // public DefaultWebView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(); // } // // public DefaultWebView(Context context, AttributeSet attrs) { // super(context, attrs); // init(); // } // // public DefaultWebView(Context context) { // super(context); // init(); // } // // private void init() { // this.getSettings().setJavaScriptEnabled(true); // this.getSettings().setDomStorageEnabled(true); // this.getSettings().setAppCacheEnabled(true); // this.getSettings().setDatabaseEnabled(true); // this.getSettings().setGeolocationEnabled(true); // this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); // } // }
import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.webkit.ConsoleMessage; import android.webkit.JsPromptResult; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.Toast; import com.google.gson.Gson; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import butterknife.Bind; import de.greenrobot.event.Subscribe; import de.greenrobot.event.ThreadMode; import io.github.emanual.app.R; import io.github.emanual.app.entity.QuestionEntity; import io.github.emanual.app.ui.base.activity.SwipeBackActivity; import io.github.emanual.app.ui.event.QuestionUpdateEvent; import io.github.emanual.app.widget.DefaultWebView; import timber.log.Timber;
package io.github.emanual.app.ui; public class QuestionDetailActivity extends SwipeBackActivity { @Bind(R.id.webview) DefaultWebView webView; public static final String EXTRA_INTERVIEW = "EXTRA_QUESTION"; private static final String CALL_BY_NATIVE = "javascript:(function(){ Bridge.callByNative(%s) })()"; Map<String, Handler.Callback> callbacks = new HashMap<String, Handler.Callback>(); int guid = 0;
// Path: app/src/main/java/io/github/emanual/app/entity/QuestionEntity.java // public class QuestionEntity extends BaseEntity { // /** // * 回答 // */ // private final static String TYPE_REPLY = "reply"; // /** // * 选择 // */ // private final static String TYPE_CHOICE = "choice"; // /** // * 判断 // */ // private final static String TYPE_JUDGMENT = "judgment"; // private String type; // private String tag; // private int difficulty; // private String from; // private String description; // private String answer; // private List<String> options; // // public String getAnswer() { // return answer; // } // // public void setAnswer(String answer) { // this.answer = answer; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public int getDifficulty() { // return difficulty; // } // // public void setDifficulty(int difficulty) { // this.difficulty = difficulty; // } // // public String getFrom() { // return from; // } // // public void setFrom(String from) { // this.from = from; // } // // public List<String> getOptions() { // return options; // } // // public void setOptions(List<String> options) { // this.options = options; // } // // public String getTag() { // return tag; // } // // public void setTag(String tag) { // this.tag = tag; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // @Override public String toString() { // return "QuestionEntity{" + // "answer='" + answer + '\'' + // ", type='" + type + '\'' + // ", tag='" + tag + '\'' + // ", difficulty=" + difficulty + // ", from='" + from + '\'' + // ", description='" + description + '\'' + // ", options=" + options + // '}'; // } // } // // Path: app/src/main/java/io/github/emanual/app/ui/base/activity/SwipeBackActivity.java // public abstract class SwipeBackActivity extends BaseActivity { // @Bind(R.id.swipBackLayout) SwipeBackLayout mSwipeBackLayout; // // @Override protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // mSwipeBackLayout.setCallBack(new SwipeBackLayout.CallBack() { // @Override // public void onFinish() { // finish(); // } // }); // } // // public SwipeBackLayout getSwipeBackLayout() { // return mSwipeBackLayout; // } // } // // Path: app/src/main/java/io/github/emanual/app/ui/event/QuestionUpdateEvent.java // public class QuestionUpdateEvent extends BaseEvent{ // private QuestionEntity questionEntity; // // public QuestionUpdateEvent(QuestionEntity questionEntity){ // this.questionEntity = questionEntity; // } // // public QuestionEntity getQuestionEntity() { // return questionEntity; // } // // public void setQuestionEntity(QuestionEntity questionEntity) { // this.questionEntity = questionEntity; // } // } // // Path: app/src/main/java/io/github/emanual/app/widget/DefaultWebView.java // public class DefaultWebView extends WebView{ // // // public DefaultWebView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(); // } // // public DefaultWebView(Context context, AttributeSet attrs) { // super(context, attrs); // init(); // } // // public DefaultWebView(Context context) { // super(context); // init(); // } // // private void init() { // this.getSettings().setJavaScriptEnabled(true); // this.getSettings().setDomStorageEnabled(true); // this.getSettings().setAppCacheEnabled(true); // this.getSettings().setDatabaseEnabled(true); // this.getSettings().setGeolocationEnabled(true); // this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); // } // } // Path: app/src/main/java/io/github/emanual/app/ui/QuestionDetailActivity.java import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.webkit.ConsoleMessage; import android.webkit.JsPromptResult; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.Toast; import com.google.gson.Gson; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import butterknife.Bind; import de.greenrobot.event.Subscribe; import de.greenrobot.event.ThreadMode; import io.github.emanual.app.R; import io.github.emanual.app.entity.QuestionEntity; import io.github.emanual.app.ui.base.activity.SwipeBackActivity; import io.github.emanual.app.ui.event.QuestionUpdateEvent; import io.github.emanual.app.widget.DefaultWebView; import timber.log.Timber; package io.github.emanual.app.ui; public class QuestionDetailActivity extends SwipeBackActivity { @Bind(R.id.webview) DefaultWebView webView; public static final String EXTRA_INTERVIEW = "EXTRA_QUESTION"; private static final String CALL_BY_NATIVE = "javascript:(function(){ Bridge.callByNative(%s) })()"; Map<String, Handler.Callback> callbacks = new HashMap<String, Handler.Callback>(); int guid = 0;
QuestionEntity questionEntity;
EManual/EManual-Android
app/src/main/java/io/github/emanual/app/ui/QuestionDetailActivity.java
// Path: app/src/main/java/io/github/emanual/app/entity/QuestionEntity.java // public class QuestionEntity extends BaseEntity { // /** // * 回答 // */ // private final static String TYPE_REPLY = "reply"; // /** // * 选择 // */ // private final static String TYPE_CHOICE = "choice"; // /** // * 判断 // */ // private final static String TYPE_JUDGMENT = "judgment"; // private String type; // private String tag; // private int difficulty; // private String from; // private String description; // private String answer; // private List<String> options; // // public String getAnswer() { // return answer; // } // // public void setAnswer(String answer) { // this.answer = answer; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public int getDifficulty() { // return difficulty; // } // // public void setDifficulty(int difficulty) { // this.difficulty = difficulty; // } // // public String getFrom() { // return from; // } // // public void setFrom(String from) { // this.from = from; // } // // public List<String> getOptions() { // return options; // } // // public void setOptions(List<String> options) { // this.options = options; // } // // public String getTag() { // return tag; // } // // public void setTag(String tag) { // this.tag = tag; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // @Override public String toString() { // return "QuestionEntity{" + // "answer='" + answer + '\'' + // ", type='" + type + '\'' + // ", tag='" + tag + '\'' + // ", difficulty=" + difficulty + // ", from='" + from + '\'' + // ", description='" + description + '\'' + // ", options=" + options + // '}'; // } // } // // Path: app/src/main/java/io/github/emanual/app/ui/base/activity/SwipeBackActivity.java // public abstract class SwipeBackActivity extends BaseActivity { // @Bind(R.id.swipBackLayout) SwipeBackLayout mSwipeBackLayout; // // @Override protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // mSwipeBackLayout.setCallBack(new SwipeBackLayout.CallBack() { // @Override // public void onFinish() { // finish(); // } // }); // } // // public SwipeBackLayout getSwipeBackLayout() { // return mSwipeBackLayout; // } // } // // Path: app/src/main/java/io/github/emanual/app/ui/event/QuestionUpdateEvent.java // public class QuestionUpdateEvent extends BaseEvent{ // private QuestionEntity questionEntity; // // public QuestionUpdateEvent(QuestionEntity questionEntity){ // this.questionEntity = questionEntity; // } // // public QuestionEntity getQuestionEntity() { // return questionEntity; // } // // public void setQuestionEntity(QuestionEntity questionEntity) { // this.questionEntity = questionEntity; // } // } // // Path: app/src/main/java/io/github/emanual/app/widget/DefaultWebView.java // public class DefaultWebView extends WebView{ // // // public DefaultWebView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(); // } // // public DefaultWebView(Context context, AttributeSet attrs) { // super(context, attrs); // init(); // } // // public DefaultWebView(Context context) { // super(context); // init(); // } // // private void init() { // this.getSettings().setJavaScriptEnabled(true); // this.getSettings().setDomStorageEnabled(true); // this.getSettings().setAppCacheEnabled(true); // this.getSettings().setDatabaseEnabled(true); // this.getSettings().setGeolocationEnabled(true); // this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); // } // }
import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.webkit.ConsoleMessage; import android.webkit.JsPromptResult; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.Toast; import com.google.gson.Gson; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import butterknife.Bind; import de.greenrobot.event.Subscribe; import de.greenrobot.event.ThreadMode; import io.github.emanual.app.R; import io.github.emanual.app.entity.QuestionEntity; import io.github.emanual.app.ui.base.activity.SwipeBackActivity; import io.github.emanual.app.ui.event.QuestionUpdateEvent; import io.github.emanual.app.widget.DefaultWebView; import timber.log.Timber;
webView.setWebChromeClient(new MyWebChromeClient()); webView.loadUrl("file:///android_asset/preview-question/index.html"); Timber.d("question json:"); Timber.d(new Gson().toJson(questionEntity)); } @Override protected int getContentViewId() { return R.layout.acty_question_detail; } @Override public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_question_detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.action_show_answer: Toast.makeText(getContext(), "action_show_answer", Toast.LENGTH_SHORT).show(); return true; } return super.onOptionsItemSelected(item); } @Subscribe(threadMode = ThreadMode.MainThread)
// Path: app/src/main/java/io/github/emanual/app/entity/QuestionEntity.java // public class QuestionEntity extends BaseEntity { // /** // * 回答 // */ // private final static String TYPE_REPLY = "reply"; // /** // * 选择 // */ // private final static String TYPE_CHOICE = "choice"; // /** // * 判断 // */ // private final static String TYPE_JUDGMENT = "judgment"; // private String type; // private String tag; // private int difficulty; // private String from; // private String description; // private String answer; // private List<String> options; // // public String getAnswer() { // return answer; // } // // public void setAnswer(String answer) { // this.answer = answer; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public int getDifficulty() { // return difficulty; // } // // public void setDifficulty(int difficulty) { // this.difficulty = difficulty; // } // // public String getFrom() { // return from; // } // // public void setFrom(String from) { // this.from = from; // } // // public List<String> getOptions() { // return options; // } // // public void setOptions(List<String> options) { // this.options = options; // } // // public String getTag() { // return tag; // } // // public void setTag(String tag) { // this.tag = tag; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // @Override public String toString() { // return "QuestionEntity{" + // "answer='" + answer + '\'' + // ", type='" + type + '\'' + // ", tag='" + tag + '\'' + // ", difficulty=" + difficulty + // ", from='" + from + '\'' + // ", description='" + description + '\'' + // ", options=" + options + // '}'; // } // } // // Path: app/src/main/java/io/github/emanual/app/ui/base/activity/SwipeBackActivity.java // public abstract class SwipeBackActivity extends BaseActivity { // @Bind(R.id.swipBackLayout) SwipeBackLayout mSwipeBackLayout; // // @Override protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // mSwipeBackLayout.setCallBack(new SwipeBackLayout.CallBack() { // @Override // public void onFinish() { // finish(); // } // }); // } // // public SwipeBackLayout getSwipeBackLayout() { // return mSwipeBackLayout; // } // } // // Path: app/src/main/java/io/github/emanual/app/ui/event/QuestionUpdateEvent.java // public class QuestionUpdateEvent extends BaseEvent{ // private QuestionEntity questionEntity; // // public QuestionUpdateEvent(QuestionEntity questionEntity){ // this.questionEntity = questionEntity; // } // // public QuestionEntity getQuestionEntity() { // return questionEntity; // } // // public void setQuestionEntity(QuestionEntity questionEntity) { // this.questionEntity = questionEntity; // } // } // // Path: app/src/main/java/io/github/emanual/app/widget/DefaultWebView.java // public class DefaultWebView extends WebView{ // // // public DefaultWebView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(); // } // // public DefaultWebView(Context context, AttributeSet attrs) { // super(context, attrs); // init(); // } // // public DefaultWebView(Context context) { // super(context); // init(); // } // // private void init() { // this.getSettings().setJavaScriptEnabled(true); // this.getSettings().setDomStorageEnabled(true); // this.getSettings().setAppCacheEnabled(true); // this.getSettings().setDatabaseEnabled(true); // this.getSettings().setGeolocationEnabled(true); // this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); // } // } // Path: app/src/main/java/io/github/emanual/app/ui/QuestionDetailActivity.java import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.webkit.ConsoleMessage; import android.webkit.JsPromptResult; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.Toast; import com.google.gson.Gson; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import butterknife.Bind; import de.greenrobot.event.Subscribe; import de.greenrobot.event.ThreadMode; import io.github.emanual.app.R; import io.github.emanual.app.entity.QuestionEntity; import io.github.emanual.app.ui.base.activity.SwipeBackActivity; import io.github.emanual.app.ui.event.QuestionUpdateEvent; import io.github.emanual.app.widget.DefaultWebView; import timber.log.Timber; webView.setWebChromeClient(new MyWebChromeClient()); webView.loadUrl("file:///android_asset/preview-question/index.html"); Timber.d("question json:"); Timber.d(new Gson().toJson(questionEntity)); } @Override protected int getContentViewId() { return R.layout.acty_question_detail; } @Override public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_question_detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.action_show_answer: Toast.makeText(getContext(), "action_show_answer", Toast.LENGTH_SHORT).show(); return true; } return super.onOptionsItemSelected(item); } @Subscribe(threadMode = ThreadMode.MainThread)
public void onFinishLoadQuestionList(QuestionUpdateEvent event){
EManual/EManual-Android
app/src/main/java/io/github/emanual/app/ui/fragment/InterviewDetailFragment.java
// Path: app/src/main/java/io/github/emanual/app/entity/InterviewJSONEntity.java // public class InterviewJSONEntity extends BaseEntity { // // private String title; // private InterviewInfoEntity info; // // public InterviewInfoEntity getInfo() { // return info; // } // // public void setInfo(InterviewInfoEntity info) { // this.info = info; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // @Override public String toString() { // return "InterviewJSONEntity{" + // "info=" + info + // ", title='" + title + '\'' + // '}'; // } // } // // Path: app/src/main/java/io/github/emanual/app/ui/base/fragment/BaseFragment.java // public abstract class BaseFragment extends Fragment { // // /** // * EventBus 3必须要有一个@Subscribe // */ // @Subscribe // public void onEmpty(EmptyEvent event){ // // } // // protected abstract void initData(Bundle savedInstanceState); // protected abstract void initLayout(Bundle savedInstanceState); // protected abstract int getContentViewId(); // // @Override public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // if(!EventBus.getDefault().isRegistered(this)){ // EventBus.getDefault().register(this); // } // } // // @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = inflater.from(getActivity()).inflate(getContentViewId(), container, false); // ButterKnife.bind(this, view); // initData(savedInstanceState); // initLayout(savedInstanceState); // return view; // } // // @Override public void onDestroy() { // super.onDestroy(); // if(EventBus.getDefault().isRegistered(this)){ // EventBus.getDefault().unregister(this); // } // } // // public void toast(String content) { // if (getActivity() != null) { // try{ // Snackbar.make(getActivity().findViewById(R.id.layout_container), content, Snackbar.LENGTH_LONG).show(); // }catch(Exception e){ // Toast.makeText(getActivity(), content, Toast.LENGTH_LONG).show(); // } // // } // } // }
import android.os.Bundle; import io.github.emanual.app.R; import io.github.emanual.app.entity.InterviewJSONEntity; import io.github.emanual.app.ui.base.fragment.BaseFragment;
package io.github.emanual.app.ui.fragment; /** * A placeholder fragment containing a simple view. */ public class InterviewDetailFragment extends BaseFragment { public static final String EXTRA_INTERVIEW = "EXTRA_INTERVIEW"; public static final String EXTRA_INDEX_PAGE = "INDEX_PAGE";
// Path: app/src/main/java/io/github/emanual/app/entity/InterviewJSONEntity.java // public class InterviewJSONEntity extends BaseEntity { // // private String title; // private InterviewInfoEntity info; // // public InterviewInfoEntity getInfo() { // return info; // } // // public void setInfo(InterviewInfoEntity info) { // this.info = info; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // @Override public String toString() { // return "InterviewJSONEntity{" + // "info=" + info + // ", title='" + title + '\'' + // '}'; // } // } // // Path: app/src/main/java/io/github/emanual/app/ui/base/fragment/BaseFragment.java // public abstract class BaseFragment extends Fragment { // // /** // * EventBus 3必须要有一个@Subscribe // */ // @Subscribe // public void onEmpty(EmptyEvent event){ // // } // // protected abstract void initData(Bundle savedInstanceState); // protected abstract void initLayout(Bundle savedInstanceState); // protected abstract int getContentViewId(); // // @Override public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // if(!EventBus.getDefault().isRegistered(this)){ // EventBus.getDefault().register(this); // } // } // // @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = inflater.from(getActivity()).inflate(getContentViewId(), container, false); // ButterKnife.bind(this, view); // initData(savedInstanceState); // initLayout(savedInstanceState); // return view; // } // // @Override public void onDestroy() { // super.onDestroy(); // if(EventBus.getDefault().isRegistered(this)){ // EventBus.getDefault().unregister(this); // } // } // // public void toast(String content) { // if (getActivity() != null) { // try{ // Snackbar.make(getActivity().findViewById(R.id.layout_container), content, Snackbar.LENGTH_LONG).show(); // }catch(Exception e){ // Toast.makeText(getActivity(), content, Toast.LENGTH_LONG).show(); // } // // } // } // } // Path: app/src/main/java/io/github/emanual/app/ui/fragment/InterviewDetailFragment.java import android.os.Bundle; import io.github.emanual.app.R; import io.github.emanual.app.entity.InterviewJSONEntity; import io.github.emanual.app.ui.base.fragment.BaseFragment; package io.github.emanual.app.ui.fragment; /** * A placeholder fragment containing a simple view. */ public class InterviewDetailFragment extends BaseFragment { public static final String EXTRA_INTERVIEW = "EXTRA_INTERVIEW"; public static final String EXTRA_INDEX_PAGE = "INDEX_PAGE";
InterviewJSONEntity interviewJSONEntity;
EManual/EManual-Android
app/src/main/java/io/github/emanual/app/utils/ParseUtils.java
// Path: app/src/main/java/io/github/emanual/app/api/RestClient.java // public class RestClient { // //http://localhost:63342/examples/EManual // // public static final String BASE_URL = "http://192.168.0.105:8080"; // main // // public static final String BASE_URL ="http://192.168.199.221:8081"; // //http://jayin.github.io/EManual // public static final String BASE_URL = "http://emanual.github.io"; // public static final String URL_Preview = BASE_URL + "/assets/preview.html"; // public static final String URL_NewsFeeds = BASE_URL + "/md-newsfeeds/dist/%s"; // public static final String URL_Java = BASE_URL + "/java"; // public static final String URL_FEEDS = " http://emanualresource.github.io"; // private static int HTTP_Timeout = 12 * 1000; // public static Context context; // // private static AsyncHttpClient client; // // public static AsyncHttpClient getHttpClient() { // if (client == null) { // client = new AsyncHttpClient(); // } // return client; // } // // /** // * 初始化:如果需要调用登录验证记录session的函数前,必须调用这个方法,否则请求失败 // * // * @param context Activity or Application context // */ // public static void init(Context context) { // RestClient.context = context; // client = getHttpClient(); // } // // /** // * get method // * // * @param url 相对的url // * @param params // * @param responseHandler // */ // public static void get(String url, RequestParams params, // AsyncHttpResponseHandler responseHandler) { // get(BASE_URL, url, params, responseHandler); // } // // public static void get(String baseUrl, String url, RequestParams params, // AsyncHttpResponseHandler responseHandler) { // initClient(); // client.get(baseUrl + url, params, responseHandler); // } // // /** // * post method // * // * @param url // * @param params // * @param responseHandler // */ // public static void post(String url, RequestParams params, // AsyncHttpResponseHandler responseHandler) { // initClient(); // client.post(getAbsoluteUrl(url), params, responseHandler); // // } // // /** // * 请求前初始化<br> // * 必须在请求之前初始化,不然cookie失效<br> // * context不为空时带着cookie去访问<br> // */ // private static void initClient() { // if (context != null) // client.setCookieStore(new PersistentCookieStore(context)); // client.setTimeout(HTTP_Timeout); // client.setEnableRedirects(true); // } // // /** // * 获得绝对url // * // * @param relativeUrl // * @return // */ // private static String getAbsoluteUrl(String relativeUrl) { // return BASE_URL + relativeUrl; // } // }
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import android.util.Log; import io.github.emanual.app.api.RestClient;
package io.github.emanual.app.utils; public class ParseUtils { public static int getArticleId(String filename) { return Integer.parseInt(filename.split("-")[0]); } // [(2013-1-1,0010)]title].md public static String getArticleName(String filename) { String[] s = filename.replaceAll("\\.[Mm]{1}[Dd]{1}", "").split("-"); //这是日期开头 if (_.isNumber(s[0]) && _.isNumber(s[1]) && _.isNumber(s[2])) { return s[3]; } else { //这是文章编号 return s[1]; } } // http:xxxxx/assets/preview.html?path=/a/b/[(2013-1-1,0010)]title].md // public static String getArticleNameByUrl(String url) { // String[] s = url.split("=")[1].split("/"); // return getArticleName(s[s.length - 1]); // } // http:xxxxx/a/b/[(2013-1-1,0010)]title].md public static String getArticleNameByUrl(String url) { String[] s = url.split("/"); return getArticleName(s[s.length - 1]); } public static String encodeArticleURL(String url) { try {
// Path: app/src/main/java/io/github/emanual/app/api/RestClient.java // public class RestClient { // //http://localhost:63342/examples/EManual // // public static final String BASE_URL = "http://192.168.0.105:8080"; // main // // public static final String BASE_URL ="http://192.168.199.221:8081"; // //http://jayin.github.io/EManual // public static final String BASE_URL = "http://emanual.github.io"; // public static final String URL_Preview = BASE_URL + "/assets/preview.html"; // public static final String URL_NewsFeeds = BASE_URL + "/md-newsfeeds/dist/%s"; // public static final String URL_Java = BASE_URL + "/java"; // public static final String URL_FEEDS = " http://emanualresource.github.io"; // private static int HTTP_Timeout = 12 * 1000; // public static Context context; // // private static AsyncHttpClient client; // // public static AsyncHttpClient getHttpClient() { // if (client == null) { // client = new AsyncHttpClient(); // } // return client; // } // // /** // * 初始化:如果需要调用登录验证记录session的函数前,必须调用这个方法,否则请求失败 // * // * @param context Activity or Application context // */ // public static void init(Context context) { // RestClient.context = context; // client = getHttpClient(); // } // // /** // * get method // * // * @param url 相对的url // * @param params // * @param responseHandler // */ // public static void get(String url, RequestParams params, // AsyncHttpResponseHandler responseHandler) { // get(BASE_URL, url, params, responseHandler); // } // // public static void get(String baseUrl, String url, RequestParams params, // AsyncHttpResponseHandler responseHandler) { // initClient(); // client.get(baseUrl + url, params, responseHandler); // } // // /** // * post method // * // * @param url // * @param params // * @param responseHandler // */ // public static void post(String url, RequestParams params, // AsyncHttpResponseHandler responseHandler) { // initClient(); // client.post(getAbsoluteUrl(url), params, responseHandler); // // } // // /** // * 请求前初始化<br> // * 必须在请求之前初始化,不然cookie失效<br> // * context不为空时带着cookie去访问<br> // */ // private static void initClient() { // if (context != null) // client.setCookieStore(new PersistentCookieStore(context)); // client.setTimeout(HTTP_Timeout); // client.setEnableRedirects(true); // } // // /** // * 获得绝对url // * // * @param relativeUrl // * @return // */ // private static String getAbsoluteUrl(String relativeUrl) { // return BASE_URL + relativeUrl; // } // } // Path: app/src/main/java/io/github/emanual/app/utils/ParseUtils.java import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import android.util.Log; import io.github.emanual.app.api.RestClient; package io.github.emanual.app.utils; public class ParseUtils { public static int getArticleId(String filename) { return Integer.parseInt(filename.split("-")[0]); } // [(2013-1-1,0010)]title].md public static String getArticleName(String filename) { String[] s = filename.replaceAll("\\.[Mm]{1}[Dd]{1}", "").split("-"); //这是日期开头 if (_.isNumber(s[0]) && _.isNumber(s[1]) && _.isNumber(s[2])) { return s[3]; } else { //这是文章编号 return s[1]; } } // http:xxxxx/assets/preview.html?path=/a/b/[(2013-1-1,0010)]title].md // public static String getArticleNameByUrl(String url) { // String[] s = url.split("=")[1].split("/"); // return getArticleName(s[s.length - 1]); // } // http:xxxxx/a/b/[(2013-1-1,0010)]title].md public static String getArticleNameByUrl(String url) { String[] s = url.split("/"); return getArticleName(s[s.length - 1]); } public static String encodeArticleURL(String url) { try {
StringBuilder sb = new StringBuilder(RestClient.URL_Preview
EManual/EManual-Android
app/src/main/java/io/github/emanual/app/ui/event/BookDownloadEndEvent.java
// Path: app/src/main/java/io/github/emanual/app/entity/FeedsItemEntity.java // public class FeedsItemEntity extends BaseEntity implements Serializable{ // private String name; // private String name_cn; // private String md5; // private String icon_url; // private String url; // private String author; // private String homepage; // // /** // * 获取book的下载url // * NOTE: // * 在url上加上`?v=xxxx` // * @return // */ // public String getDownloadUrl(){ // return String.format("%s?v=%s", getUrl(), getMd5()); // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getHomepage() { // return homepage; // } // // public void setHomepage(String homepage) { // this.homepage = homepage; // } // // public String getIcon_url() { // return icon_url; // } // // public void setIcon_url(String icon_url) { // this.icon_url = icon_url; // } // // public String getMd5() { // return md5; // } // // public void setMd5(String md5) { // this.md5 = md5; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getName_cn() { // return name_cn; // } // // public void setName_cn(String name_cn) { // this.name_cn = name_cn; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // @Override public String toString() { // return "FeedsItemEntity{" + // "author='" + author + '\'' + // ", name='" + name + '\'' + // ", name_cn='" + name_cn + '\'' + // ", md5='" + md5 + '\'' + // ", icon_url='" + icon_url + '\'' + // ", url='" + url + '\'' + // ", homepage='" + homepage + '\'' + // '}'; // } // }
import java.io.File; import io.github.emanual.app.entity.FeedsItemEntity;
package io.github.emanual.app.ui.event; /** * 书下载完毕事件 * Author: jayin * Date: 1/22/16 */ public class BookDownloadEndEvent extends BaseEvent{ private File file;
// Path: app/src/main/java/io/github/emanual/app/entity/FeedsItemEntity.java // public class FeedsItemEntity extends BaseEntity implements Serializable{ // private String name; // private String name_cn; // private String md5; // private String icon_url; // private String url; // private String author; // private String homepage; // // /** // * 获取book的下载url // * NOTE: // * 在url上加上`?v=xxxx` // * @return // */ // public String getDownloadUrl(){ // return String.format("%s?v=%s", getUrl(), getMd5()); // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getHomepage() { // return homepage; // } // // public void setHomepage(String homepage) { // this.homepage = homepage; // } // // public String getIcon_url() { // return icon_url; // } // // public void setIcon_url(String icon_url) { // this.icon_url = icon_url; // } // // public String getMd5() { // return md5; // } // // public void setMd5(String md5) { // this.md5 = md5; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getName_cn() { // return name_cn; // } // // public void setName_cn(String name_cn) { // this.name_cn = name_cn; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // @Override public String toString() { // return "FeedsItemEntity{" + // "author='" + author + '\'' + // ", name='" + name + '\'' + // ", name_cn='" + name_cn + '\'' + // ", md5='" + md5 + '\'' + // ", icon_url='" + icon_url + '\'' + // ", url='" + url + '\'' + // ", homepage='" + homepage + '\'' + // '}'; // } // } // Path: app/src/main/java/io/github/emanual/app/ui/event/BookDownloadEndEvent.java import java.io.File; import io.github.emanual.app.entity.FeedsItemEntity; package io.github.emanual.app.ui.event; /** * 书下载完毕事件 * Author: jayin * Date: 1/22/16 */ public class BookDownloadEndEvent extends BaseEvent{ private File file;
private FeedsItemEntity feedsItemEntity;
EManual/EManual-Android
app/src/main/java/io/github/emanual/app/ui/adapter/InterviewListAdapter.java
// Path: app/src/main/java/io/github/emanual/app/entity/InterviewJSONEntity.java // public class InterviewJSONEntity extends BaseEntity { // // private String title; // private InterviewInfoEntity info; // // public InterviewInfoEntity getInfo() { // return info; // } // // public void setInfo(InterviewInfoEntity info) { // this.info = info; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // @Override public String toString() { // return "InterviewJSONEntity{" + // "info=" + info + // ", title='" + title + '\'' + // '}'; // } // } // // Path: app/src/main/java/io/github/emanual/app/ui/QuestionListActivity.java // public class QuestionListActivity extends SwipeBackActivity { // public static final String EXTRA_INTERVIEW = "EXTRA_INTERVIEW"; // public static final String EXTRA_INDEX_PAGE = "INDEX_PAGE"; // // InterviewJSONEntity interviewJSONEntity; // ProgressDialog mProgressDialog; // @Bind(R.id.recyclerView) RecyclerView recyclerView; // // @Override protected void initData(Bundle savedInstanceState) { // interviewJSONEntity = (InterviewJSONEntity)getIntent().getSerializableExtra(EXTRA_INTERVIEW); // if(interviewJSONEntity == null){ // finish(); // } // } // // @Override protected void initLayout(Bundle savedInstanceState) { // if(isFinishing()){ // return; // } // // setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // getSupportActionBar().setTitle(R.string.acty_question_list); // // mProgressDialog = new ProgressDialog(getContext()); // mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // // recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); // // EventBus.getDefault().post(new GetQuestionListEvent(interviewJSONEntity.getInfo().getName())); // } // // @Override protected int getContentViewId() { // return R.layout.acty_question_list; // } // // @Subscribe(threadMode = ThreadMode.Async) // public void onGetQuestionsList(GetQuestionListEvent event){ // List<QuestionEntity> data = InterviewResource.getQuestionList(getContext(), event.getInterviewName()); // EventBus.getDefault().post(new FinishLoadQuestionListEvent(data)); // } // // @Subscribe(threadMode = ThreadMode.MainThread) // public void onFinishLoadQuestionList(FinishLoadQuestionListEvent event){ // recyclerView.setAdapter(new QuestionListAdapter(getContext(), event.getQuestionEntityList())); // } // }
import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import io.github.emanual.app.R; import io.github.emanual.app.entity.InterviewJSONEntity; import io.github.emanual.app.ui.QuestionListActivity;
package io.github.emanual.app.ui.adapter; /** * Author: jayin * Date: 2/25/16 */ public class InterviewListAdapter extends RecyclerView.Adapter<InterviewListAdapter.ViewHolder>{ Context context;
// Path: app/src/main/java/io/github/emanual/app/entity/InterviewJSONEntity.java // public class InterviewJSONEntity extends BaseEntity { // // private String title; // private InterviewInfoEntity info; // // public InterviewInfoEntity getInfo() { // return info; // } // // public void setInfo(InterviewInfoEntity info) { // this.info = info; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // @Override public String toString() { // return "InterviewJSONEntity{" + // "info=" + info + // ", title='" + title + '\'' + // '}'; // } // } // // Path: app/src/main/java/io/github/emanual/app/ui/QuestionListActivity.java // public class QuestionListActivity extends SwipeBackActivity { // public static final String EXTRA_INTERVIEW = "EXTRA_INTERVIEW"; // public static final String EXTRA_INDEX_PAGE = "INDEX_PAGE"; // // InterviewJSONEntity interviewJSONEntity; // ProgressDialog mProgressDialog; // @Bind(R.id.recyclerView) RecyclerView recyclerView; // // @Override protected void initData(Bundle savedInstanceState) { // interviewJSONEntity = (InterviewJSONEntity)getIntent().getSerializableExtra(EXTRA_INTERVIEW); // if(interviewJSONEntity == null){ // finish(); // } // } // // @Override protected void initLayout(Bundle savedInstanceState) { // if(isFinishing()){ // return; // } // // setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // getSupportActionBar().setTitle(R.string.acty_question_list); // // mProgressDialog = new ProgressDialog(getContext()); // mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // // recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); // // EventBus.getDefault().post(new GetQuestionListEvent(interviewJSONEntity.getInfo().getName())); // } // // @Override protected int getContentViewId() { // return R.layout.acty_question_list; // } // // @Subscribe(threadMode = ThreadMode.Async) // public void onGetQuestionsList(GetQuestionListEvent event){ // List<QuestionEntity> data = InterviewResource.getQuestionList(getContext(), event.getInterviewName()); // EventBus.getDefault().post(new FinishLoadQuestionListEvent(data)); // } // // @Subscribe(threadMode = ThreadMode.MainThread) // public void onFinishLoadQuestionList(FinishLoadQuestionListEvent event){ // recyclerView.setAdapter(new QuestionListAdapter(getContext(), event.getQuestionEntityList())); // } // } // Path: app/src/main/java/io/github/emanual/app/ui/adapter/InterviewListAdapter.java import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import io.github.emanual.app.R; import io.github.emanual.app.entity.InterviewJSONEntity; import io.github.emanual.app.ui.QuestionListActivity; package io.github.emanual.app.ui.adapter; /** * Author: jayin * Date: 2/25/16 */ public class InterviewListAdapter extends RecyclerView.Adapter<InterviewListAdapter.ViewHolder>{ Context context;
List<InterviewJSONEntity> data;