text
stringlengths
10
2.72M
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package test; /** * * @author elshan.abdullayev */ import java.io.FileInputStream; import org.xml.sax.SAXException; import javax.xml.XMLConstants; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import static test.ValidateXmlXsd.xsdInput; /** * custom error handler while validating xml against xsd */ public class ValidateXmlXsd { public static InputStream xsdInput; public static InputStream xmlInput; public static String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<course id=\"1-ID\">\n" + " <name>JAX-B</name>\n" + " <description>Validate XML against XSD Schema</description>\n" + "</course>"; public static void main(String... args) { try { xsdInput = new FileInputStream("src/XSD/CCreditInfo2.xsd"); //xmlInput = new FileInputStream("D:\\For_Parsing\\New_pars\\First_Check.xml"); xmlInput = new FileInputStream("D:\\For_Parsing\\New_pars\\070616.xml"); //System.out.println("Custom Error Handler while Validating XML against XSD"); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); //Schema schema = factory.newSchema(ValidateXmlXsd.class.getResource("schema.xsd")); Schema schema = factory.newSchema(new StreamSource(xsdInput)); Validator validator = schema.newValidator(); validator.setErrorHandler(new XsdErrorHandler() {}); //validator.validate(new StreamSource(new StringReader(xml))); validator.validate(new StreamSource(xmlInput)); System.out.println("Validation is successful"); } catch (IOException e) { // handle exception while reading source } catch (SAXException e) { //System.out.println("Custom Error Handler while Validating XML against XSD"); System.out.println("Message: " + e.getMessage()); } } }
package core.dao.api; import domain.api.Item; public interface ItemDao extends GenericDao<Item, Long> { }
package com.box.androidsdk.content.models; import android.text.TextUtils; import com.box.androidsdk.content.BoxConstants; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import java.util.ArrayList; import java.util.Date; import java.util.EnumSet; import java.util.List; import java.util.Locale; /** * Abstract class that represents a BoxItem which is the super class of BoxFolder, BoxFile, and BoxBookmark. */ public abstract class BoxItem extends BoxEntity { private static final long serialVersionUID = 4876182952337609430L; public static final String FIELD_NAME = "name"; public static final String FIELD_SEQUENCE_ID = "sequence_id"; public static final String FIELD_ETAG = "etag"; public static final String FIELD_CREATED_AT = "created_at"; public static final String FIELD_MODIFIED_AT = "modified_at"; public static final String FIELD_DESCRIPTION = "description"; public static final String FIELD_PATH_COLLECTION = "path_collection"; public static final String FIELD_CREATED_BY = "created_by"; public static final String FIELD_MODIFIED_BY = "modified_by"; public static final String FIELD_TRASHED_AT = "trashed_at"; public static final String FIELD_PURGED_AT = "purged_at"; public static final String FIELD_OWNED_BY = "owned_by"; public static final String FIELD_SHARED_LINK = "shared_link"; public static final String FIELD_PARENT = "parent"; public static final String FIELD_ITEM_STATUS = "item_status"; public static final String FIELD_PERMISSIONS = "permissions"; public static final String FIELD_SYNCED = "synced"; public static final String FIELD_ALLOWED_SHARED_LINK_ACCESS_LEVELS = "allowed_shared_link_access_levels"; public static final String FIELD_TAGS = "tags"; public static final String FIELD_COLLECTIONS = "collections"; public static final String FIELD_CLASSIFICATION = "classification"; protected transient EnumSet<Permission> mPermissions = null; /** * Constructs an empty BoxItem object. */ public BoxItem() { super(); } /** * Constructs a BoxItem with the provided map values. * * @param object JsonObject representing this class */ public BoxItem(JsonObject object) { super(object); } /** * Gets a unique string identifying the version of the item. * * @return a unique string identifying the version of the item. */ public String getEtag() { return getPropertyAsString(FIELD_ETAG); } /** * Gets the name of the item. * * @return the name of the item. */ public String getName() { return getPropertyAsString(FIELD_NAME); } /** * Gets the time the item was created. * * @return the time the item was created. */ public Date getCreatedAt() { return getPropertyAsDate(FIELD_CREATED_AT); } /** * Gets the time the item was last modified. * * @return the time the item was last modified. */ public Date getModifiedAt() { return getPropertyAsDate(FIELD_MODIFIED_AT); } /** * Gets the description of the item. * * @return the description of the item. */ public String getDescription() { return getPropertyAsString(FIELD_DESCRIPTION); } /** * Gets the size of the item in bytes. * * @return the size of the item in bytes. */ public Long getSize() { return getPropertyAsLong(BoxConstants.FIELD_SIZE); } /** * Gets the path of folders to the item, starting at the root. * * @return the path of folders to the item. */ public BoxIterator<BoxFolder> getPathCollection() { return (BoxIterator<BoxFolder>)getPropertyAsJsonObject(BoxJsonObject.getBoxJsonObjectCreator(BoxIteratorBoxEntity.class),FIELD_PATH_COLLECTION); } /** * Gets info about the user who created the item. * * @return info about the user who created the item. */ public BoxUser getCreatedBy() { return getPropertyAsJsonObject(BoxEntity.getBoxJsonObjectCreator(BoxUser.class), FIELD_CREATED_BY); } /** * Gets info about the user who last modified the item. * * @return info about the user who last modified the item. */ public BoxUser getModifiedBy() { return getPropertyAsJsonObject(BoxEntity.getBoxJsonObjectCreator(BoxUser.class), FIELD_MODIFIED_BY); } /** * Gets the time that the item was trashed. * * @return the time that the item was trashed. */ public Date getTrashedAt() { return getPropertyAsDate(FIELD_TRASHED_AT); } /** * Gets the time that the item was purged from the trash. * * @return the time that the item was purged from the trash. */ public Date getPurgedAt() { return getPropertyAsDate(FIELD_PURGED_AT); } /** * Gets the time that the item was created according to the uploader. * * @return the time that the item was created according to the uploader. */ protected Date getContentCreatedAt() { return getPropertyAsDate(BoxConstants.FIELD_CONTENT_CREATED_AT); } /** * Gets the time that the item was last modified according to the uploader. * * @return the time that the item was last modified according to the uploader. */ protected Date getContentModifiedAt() { return getPropertyAsDate(BoxConstants.FIELD_CONTENT_MODIFIED_AT); } /** * Gets info about the user who owns the item. * * @return info about the user who owns the item. */ public BoxUser getOwnedBy() { return getPropertyAsJsonObject(BoxEntity.getBoxJsonObjectCreator(BoxUser.class), FIELD_OWNED_BY); } /** * Gets the shared link for the item. * * @return the shared link for the item. */ public BoxSharedLink getSharedLink() { return getPropertyAsJsonObject(BoxEntity.getBoxJsonObjectCreator(BoxSharedLink.class), FIELD_SHARED_LINK); } /** * Gets a unique ID for use with the EventStreams. * * @return a unique ID for use with the EventStream. */ public String getSequenceID() { return getPropertyAsString(FIELD_SEQUENCE_ID); } /** * Access level settings for shared links set by administrator. Can be collaborators, open, or company. * * @return possible access level settings for this item. */ public ArrayList<BoxSharedLink.Access> getAllowedSharedLinkAccessLevels() { ArrayList<String> accessStrList = getPropertyAsStringArray(FIELD_ALLOWED_SHARED_LINK_ACCESS_LEVELS); if (accessStrList == null){ return null; } ArrayList<BoxSharedLink.Access> accessList = new ArrayList<BoxSharedLink.Access>(accessStrList.size()); for (String str: accessStrList) { accessList.add(BoxSharedLink.Access.fromString(str)); } return accessList; } /** * Gets info about the parent folder of the item. * * @return info about the parent folder of the item. */ public BoxFolder getParent() { return getPropertyAsJsonObject(BoxEntity.getBoxJsonObjectCreator(BoxFolder.class), FIELD_PARENT); } /** * Gets the status of the item. * * @return the status of the item. */ public String getItemStatus() { return getPropertyAsString(FIELD_ITEM_STATUS); } /** * Gets whether or not this item is synced. * * @return true if this item is synced, false otherwise. */ public Boolean getIsSynced() { return getPropertyAsBoolean(FIELD_SYNCED); } /** * Gets the array of tags for this item * * @return tags of item */ public List<String> getTags() { return getPropertyAsStringArray(FIELD_TAGS); } /** * Gets the collections that this item is a part of * * @return list of collections the item belongs to */ public List<BoxCollection> getCollections() { return getPropertyAsJsonObjectArray(BoxEntity.getBoxJsonObjectCreator(BoxCollection.class), FIELD_COLLECTIONS); } /** * Gets the classification of the item. * @return the classification of the item. */ public BoxClassification getClassification() { return getPropertyAsJsonObject(BoxJsonObject.getBoxJsonObjectCreator(BoxClassification.class), FIELD_CLASSIFICATION); } public boolean hasRequestedClassification() { return hasRequestedField(FIELD_CLASSIFICATION); } /** * Gets the number of comments on the item. * * @return the number of comments on the item. */ protected Long getCommentCount() { return getPropertyAsLong(BoxConstants.FIELD_COMMENT_COUNT); } private List<BoxFolder> parsePathCollection(JsonObject jsonObject) { int count = jsonObject.get("total_count").asInt(); List<BoxFolder> pathCollection = new ArrayList<BoxFolder>(count); JsonArray entries = jsonObject.get("entries").asArray(); for (JsonValue value : entries) { JsonObject entry = value.asObject(); BoxFolder folder = new BoxFolder(); folder.createFromJson(entry); pathCollection.add(folder); } return pathCollection; } private BoxUser parseUserInfo(JsonObject jsonObject) { BoxUser user = new BoxUser(); user.createFromJson(jsonObject); return user; } private List<String> parseTags(JsonArray jsonArray) { List<String> tags = new ArrayList<String>(); for (JsonValue value : jsonArray) { tags.add(value.asString()); } return tags; } /** * Deprecated use BoxEntity.createEntityFromJson. FromCreates a BoxItem object from a JSON string. * * @param json JSON string to convert to a BoxItem. * @return BoxItem object representing information in the JSON string. */ @Deprecated public static BoxItem createBoxItemFromJson(final String json) { BoxEntity createdByEntity = new BoxEntity(); createdByEntity.createFromJson(json); if (createdByEntity.getType().equals(BoxFile.TYPE)) { BoxFile file = new BoxFile(); file.createFromJson(json); return file; } else if (createdByEntity.getType().equals(BoxBookmark.TYPE)) { BoxBookmark bookmark = new BoxBookmark(); bookmark.createFromJson(json); return bookmark; } else if (createdByEntity.getType().equals(BoxFolder.TYPE)) { BoxFolder folder = new BoxFolder(); folder.createFromJson(json); return folder; } return null; } /** * Deprecated use BoxEntity.createEntityFromJson. Creates a BoxItem object from a JsonObject. * * @param json JsonObject to convert to a BoxItem. * @return BoxItem object representing information in the JsonObject. */ @Deprecated public static BoxItem createBoxItemFromJson(final JsonObject json) { BoxEntity createdByEntity = new BoxEntity(); createdByEntity.createFromJson(json); if (createdByEntity.getType().equals(BoxFile.TYPE)) { BoxFile file = new BoxFile(); file.createFromJson(json); return file; } else if (createdByEntity.getType().equals(BoxBookmark.TYPE)) { BoxBookmark bookmark = new BoxBookmark(); bookmark.createFromJson(json); return bookmark; } else if (createdByEntity.getType().equals(BoxFolder.TYPE)) { BoxFolder folder = new BoxFolder(); folder.createFromJson(json); return folder; } return null; } /** * Gets the permissions that the current user has on the bookmark. * * @return the permissions that the current user has on the bookmark. */ public EnumSet<Permission> getPermissions() { if (mPermissions == null) { parsePermissions(); } return mPermissions; } protected EnumSet<Permission> parsePermissions() { BoxPermission permission = getPropertyAsJsonObject(BoxEntity.getBoxJsonObjectCreator(BoxPermission.class), FIELD_PERMISSIONS); if (permission == null) return null; mPermissions = permission.getPermissions(); return mPermissions; } /** * Enumerates the possible permissions that a user can have on a file. */ public enum Permission { /** * The user can preview the item. */ CAN_PREVIEW("can_preview"), /** * The user can download the item. */ CAN_DOWNLOAD("can_download"), /** * The user can upload to the item. */ CAN_UPLOAD("can_upload"), /** * The user can invite collaborators to the item. */ CAN_INVITE_COLLABORATOR("can_invite_collaborator"), /** * The user can rename the item. */ CAN_RENAME("can_rename"), /** * The user can delete the item. */ CAN_DELETE("can_delete"), /** * The user can share the item. */ CAN_SHARE("can_share"), /** * The user can set the access level for shared links to the item. */ CAN_SET_SHARE_ACCESS("can_set_share_access"), /** * The user can comment on the item. */ CAN_COMMENT("can_comment"); private final String value; private Permission(String value) { this.value = value; } public static Permission fromString(String text) { if (!TextUtils.isEmpty(text)) { for (Permission a : Permission.values()) { if (text.equalsIgnoreCase(a.name())) { return a; } } } throw new IllegalArgumentException(String.format(Locale.ENGLISH, "No enum with text %s found", text)); } @Override public String toString() { return this.value; } } }
package com.twoyears44.myadapter; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.GridView; import android.widget.TextView; import com.twoyears44.myclass.BCAlbumManager; import com.twoyears44.tripgif.R; import java.util.ArrayList; import java.util.HashMap; /** * Created by twoyears44 on 16/3/29. */ public class PhotoListAdapter extends BaseAdapter { Context context; ArrayList<ArrayList<HashMap<String,String>>> listItems; ArrayList<ArrayList<Integer>> indexPath; public PhotoListAdapter(Context context, ArrayList<ArrayList<HashMap<String,String>>> listItems) { this.context = context; this.listItems = listItems; indexPath = new ArrayList<>(listItems.size()); for (int i = 0; i < listItems.size(); i ++) { ArrayList<Integer> arrayList = new ArrayList<>(); indexPath.add(arrayList); } } @Override public int getCount() { return listItems.size(); } @Override public Object getItem(int position) { return listItems.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); convertView = layoutInflater.inflate(R.layout.item_photo_list, null); TextView dateTextView = (TextView)convertView.findViewById(R.id.textView); CheckBox checkBox = (CheckBox)convertView.findViewById(R.id.checkBox); GridView gridView = (GridView)convertView.findViewById(R.id.gridView); gridView.setNumColumns(3); gridView.setVerticalSpacing(20); ArrayList<HashMap<String,String>> listItem = listItems.get(position); PhotoGridInListAdapter gridInListAdapter = new PhotoGridInListAdapter(context, position,listItem); gridView.setAdapter(gridInListAdapter); HashMap<String,String> item0 = listItem.get(0); String date = item0.get("dateTaken"); String dateString = BCAlbumManager.getDate(Long.valueOf(date), "yyyy/MM/dd"); dateTextView.setText(dateString); return convertView; } }
/* 1: */ package com.kaldin.setting.forgotpassword.dao.impl; /* 2: */ /* 3: */ import com.kaldin.setting.forgotpassword.dao.ForgotPasswordInterface; /* 4: */ import com.kaldin.setting.forgotpassword.dto.forgotPasswordDTO; /* 5: */ import com.kaldin.setting.forgotpassword.hibernate.ForgotPassHibernate; /* 6: */ /* 7: */ public class ForgotPasswordImpl /* 8: */ implements ForgotPasswordInterface /* 9: */ { /* 10:13 */ ForgotPassHibernate hiber = new ForgotPassHibernate(); /* 11: */ /* 12: */ public String forgotUserPassword(forgotPasswordDTO forgotpassObj) /* 13: */ { /* 14:20 */ return this.hiber.forgotUserPassword(forgotpassObj); /* 15: */ } /* 16: */ /* 17: */ public int getUserId(String email) /* 18: */ { /* 19:23 */ return this.hiber.getUserId(email); /* 20: */ } /* 21: */ /* 22: */ public int getCompanyId(String email) /* 23: */ { /* 24:27 */ return this.hiber.getCompanyId(email); /* 25: */ } /* 26: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.setting.forgotpassword.dao.impl.ForgotPasswordImpl * JD-Core Version: 0.7.0.1 */
package com.aplicacion.guiaplayasgalicia.listaplayas; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Set; import android.app.ProgressDialog; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.ExpandableListView; import android.widget.ExpandableListView.OnChildClickListener; import android.widget.Toast; import com.aplicacion.guiaplayasgalicia.CustomBaseActivity; import com.aplicacion.guiaplayasgalicia.R; import com.aplicacion.guiaplayasgalicia.gestionbd.DataBaseHelper; import com.aplicacion.guiaplayasgalicia.objetos.Beach; import com.aplicacion.guiaplayasgalicia.utils.ListDialogFragment; import com.aplicacion.guiaplayasgalicia.utils.ListDialogFragment.ClickItemDialogListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; public class BeachesListProvinceFragment extends Fragment implements ClickItemDialogListener { DataBaseHelper dataBaseHelper = null; BeachesListProvinceAdapter listBeachesAdapter = null; ExpandableListView expandableListView = null; private Integer groupPositionClicked = -1; private Integer childPositionClicked = -1; ActionBarDrawerToggle actionBarDrawerToggle = null; DrawerLayout drawerLayoutBeachList = null; String[] drawerListElements = null; String sectionTitle = null; SearchView searchView = null; // Variables to save the scroll position private int expandableListViewPosition = 0; private int expandableListViewItemPosition = 0; // Declare references to stateful objects when configuration changes (orientation changes) public Integer getGroupPositionClicked() { return groupPositionClicked; } public void setGroupPositionClicked(Integer groupPositionClicked) { this.groupPositionClicked = groupPositionClicked; } public Integer getChildPositionClicked() { return childPositionClicked; } public void setChildPositionClicked(Integer childPositionClicked) { this.childPositionClicked = childPositionClicked; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.beach_list_provinces, null); final List<Beach> beachesArrayList = this.getBeachesList(); HashMap<String, List<Beach>> provinceBeachesHashMap = this.listToHashMap(beachesArrayList); List<String> provinceNamesList = this.stringSetToStringList(provinceBeachesHashMap.keySet()); // Set to visible the drawer indicator icon and enable the navigation drawer swipe CustomBaseActivity.drawerToggle.setDrawerIndicatorEnabled(true); CustomBaseActivity.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); // Modify the title of the Action Bar ((ActionBarActivity)getActivity()).getSupportActionBar().setTitle(getResources().getString(R.string.beachesProvince)); expandableListView = (ExpandableListView) view.findViewById(R.id.list); // Set the adapter listBeachesAdapter = new BeachesListProvinceAdapter(getActivity(), provinceNamesList, provinceBeachesHashMap); expandableListView.setAdapter(listBeachesAdapter); // Set the behaviour of clicking a child in the list expandableListView.setOnChildClickListener(new OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { groupPositionClicked = groupPosition; childPositionClicked = childPosition; // Set the array of options to be shown in the dialog String[] optionsArray = new String[4]; optionsArray[0] = getResources().getString(R.string.seeCharacteristics); optionsArray[1] = getResources().getString(R.string.seeWeather); optionsArray[2] = getResources().getString(R.string.seeMap); // Check if the beach is marked as favourite. // If true, the option remove from favourites will be shown. Otherwise the option shown will be add to favourites. boolean isFavouriteBeach = false; try { if (dataBaseHelper == null) { dataBaseHelper = new DataBaseHelper(getActivity()); } dataBaseHelper.createDataBase(); dataBaseHelper.openDataBase(SQLiteDatabase.OPEN_READONLY); isFavouriteBeach = dataBaseHelper.isFavouriteBeach(Integer.valueOf(Long.valueOf(id).toString())); } catch (SQLiteException e) { // CustomToast.showCustomToast(getActivity(), getResources().getString(R.string.databaseErrorUpdateBeach)); Toast.makeText(getActivity(), getResources().getString(R.string.databaseErrorUpdateBeach), Toast.LENGTH_LONG).show(); getActivity().finish(); } catch (IOException e) { // CustomToast.showCustomToast(getActivity(), getResources().getString(R.string.databaseErrorUpdateBeach)); Toast.makeText(getActivity(), getResources().getString(R.string.databaseErrorUpdateBeach), Toast.LENGTH_LONG).show(); getActivity().finish(); } if (isFavouriteBeach) { optionsArray[3] = getResources().getString(R.string.removeFromFavourites); } else { optionsArray[3] = getResources().getString(R.string.addToFavourites); } // Hide the soft keyboard at pushing the button InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(searchView.getWindowToken(), 0); // Get the selected beach Beach selectedBeach = (Beach) listBeachesAdapter.getChild(groupPosition, childPosition); // Create the dialog and show it DialogFragment dialogFragment = ListDialogFragment.newInstance(selectedBeach, getResources().getString(R.string.tituloAlertDialog), optionsArray); dialogFragment.setTargetFragment(BeachesListProvinceFragment.this, 0); dialogFragment.show(getActivity().getSupportFragmentManager(), "dialog"); return true; } }); // Expand all the groups for (int i=0; i<expandableListView.getExpandableListAdapter().getGroupCount(); i++) { expandableListView.expandGroup(i); } // Allow the fragment to manage the action bar setHasOptionsMenu(true); // Retain this fragment (orientation changes) setRetainInstance(true); // Show the advertisement AdView adView = (AdView) view.findViewById(R.id.adViewListBeaches); AdRequest adRequest = new AdRequest.Builder().build(); adView.loadAd(adRequest); return view; } @Override public void onStop() { super.onStop(); if (dataBaseHelper != null) { dataBaseHelper.close(); Log.i(this.getClass().toString(), "Database closed"); } } @Override public void onResume() { super.onResume(); // Set the position of the scroll expandableListView.setSelectionFromTop(expandableListViewPosition, expandableListViewItemPosition); } @Override public void onPause() { super.onPause(); // Save position of first visible item and the scroll position of item expandableListViewPosition = expandableListView.getFirstVisiblePosition(); View itemView = expandableListView.getChildAt(0); expandableListViewItemPosition = itemView == null ? 0 : itemView.getTop(); } @Override // Manage the items of the activity action bar public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); // Get the search item of the action bar of its activity and set its functionality when the user writes MenuItem searchMenuItem = menu.findItem(R.id.actionSearchId); searchMenuItem.setVisible(true); searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextChange(String text) { listBeachesAdapter.resetData(); listBeachesAdapter.getFilter().filter(text.toString()); return false; } @Override public boolean onQueryTextSubmit(String text) { return false; } }); } private HashMap<String, List<Beach>> listToHashMap(List<Beach> beachesArrayList) { HashMap<String, List<Beach>> beachesHashMap = new HashMap<String, List<Beach>>(); for (Beach beach : beachesArrayList) { List<Beach> beachesList = null; if (beachesHashMap.keySet().contains(beach.getProvince())) { beachesList = beachesHashMap.get(beach.getProvince()); } else { beachesList = new ArrayList<Beach>(); } beachesList.add(beach); beachesHashMap.put(beach.getProvince(), beachesList); } // Alphabetically order the lists for (String province : beachesHashMap.keySet()) { Collections.sort(beachesHashMap.get(province)); } return beachesHashMap; } private List<String> stringSetToStringList(Set<String> provinceSet) { List<String> provincesList = new ArrayList<String>(); for (String provinceName : provinceSet) { provincesList.add(provinceName); } Collections.sort(provincesList); return provincesList; } /** * Method that retrieves a list of beaches from the database * @return List of Beach objects */ private List<Beach> getBeachesList() { ProgressDialog progressDialog = ProgressDialog.show(getActivity(), "", ""); List<Beach> beachesList = null; try { if (dataBaseHelper == null) { dataBaseHelper = new DataBaseHelper(getActivity()); } dataBaseHelper.createDataBase(); dataBaseHelper.openDataBase(SQLiteDatabase.OPEN_READONLY); beachesList = dataBaseHelper.getBeachesList(); } catch (SQLiteException e) { // CustomToast.showCustomToast(getActivity(), getResources().getString(R.string.databaseError)); Toast.makeText(getActivity(), getResources().getString(R.string.databaseError), Toast.LENGTH_LONG).show(); getActivity().finish(); } catch (IOException e) { // CustomToast.showCustomToast(getActivity(), getResources().getString(R.string.databaseError)); Toast.makeText(getActivity(), getResources().getString(R.string.databaseError), Toast.LENGTH_LONG).show(); getActivity().finish(); } progressDialog.dismiss(); return beachesList; } @Override public void onClickItemDialog() { Beach beach = (Beach) listBeachesAdapter.getChild(groupPositionClicked, childPositionClicked); if (beach.isFavourite()) { beach.setFavourite(false); } else { beach.setFavourite(true); } listBeachesAdapter.notifyDataSetChanged(); } }
package liquibase.database.structure; import liquibase.database.Database; import liquibase.util.StringUtils; public class Schema extends DatabaseObjectImpl { public static final String DEFAULT_NAME = "!DEFAULT_SCHEMA!"; public static final Schema DEFAULT = new Schema(Catalog.DEFAULT, DEFAULT_NAME); protected Catalog catalog; protected String name; public DatabaseObject[] getContainingObjects() { return null; } public Schema(String catalog, String schemaName) { catalog = StringUtils.trimToNull(catalog); schemaName = StringUtils.trimToNull(schemaName); if (catalog == null && schemaName == null) { catalog = Catalog.DEFAULT_NAME; schemaName = Schema.DEFAULT_NAME; } else if (schemaName != null && catalog == null) { if (schemaName.equals(Schema.DEFAULT_NAME)) { catalog = Catalog.DEFAULT_NAME; } else { catalog = Catalog.DEFAULT_NAME; } } else if (catalog != null && schemaName == null) { if (catalog.equals(Catalog.DEFAULT_NAME)) { schemaName = Schema.DEFAULT_NAME; } else { schemaName = catalog; } } this.name = schemaName; this.catalog = new Catalog(catalog); } public Schema(Catalog catalog, String name) { this(catalog.getName(), name); } public String getName() { return name; } public Schema getSchema() { return this; } public Catalog getCatalog() { return catalog; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Schema schema = (Schema) o; if (catalog != null ? !catalog.equals(schema.catalog) : schema.catalog != null) return false; if (name != null ? !name.equals(schema.name) : schema.name != null) return false; return true; } @Override public int hashCode() { int result = catalog != null ? catalog.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); return result; } public String getCatalogName() { return catalog.getName(); } @Override public String toString() { return catalog.getName()+"."+name; } public static class DatabaseSpecific extends Schema { private Database database; public DatabaseSpecific(String catalog, String schemaName, Database database) { super(catalog, schemaName); this.database = database; if (catalog == null) { this.catalog = new Catalog.DatabaseSpecific(null, database); } if (schemaName == null) { this.name = null; } } public DatabaseSpecific(Catalog catalog, String name) { super(catalog, name); if (catalog == null) { this.catalog = new Catalog.DatabaseSpecific(null, database); } if (name == null) { this.name = null; } } public Database getDatabase() { return database; } } }
package khmil.java8.Lambda; interface DoSmth { int execute(int x, int y); } public class LambdaAsReult { public static void main(String[] args) { int c = action(1).execute(6,7); System.out.println(c); } private static DoSmth action(int number) { switch (number) { case 1: return ((x, y) -> x + y); case 2: return ((x, y) -> x - y); case 3: return ((x, y) -> x * y); default: return ((x, y) -> x / y); } } }
package com.espendwise.manta.model.entity; // Generated by Hibernate Tools import com.espendwise.manta.model.ValueObject; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * UserStoreListEntity generated by hbm2java */ @Entity @Table(name="CLW_USER_ASSOC") public class UserStoreListEntity extends ValueObject implements java.io.Serializable { private static final long serialVersionUID = -1; public static final String USER_ASSOC_ID = "userAssocId"; public static final String USER_ID = "userId"; public static final String USER_ASSOC_CD = "userAssocCd"; public static final String STORES = "stores"; private Long userAssocId; private Long userId; private String userAssocCd; private StoreListEntity stores; public UserStoreListEntity() { } public UserStoreListEntity(Long userAssocId) { this.setUserAssocId(userAssocId); } public UserStoreListEntity(Long userAssocId, Long userId, String userAssocCd, StoreListEntity stores) { this.setUserAssocId(userAssocId); this.setUserId(userId); this.setUserAssocCd(userAssocCd); this.setStores(stores); } @Id @Column(name="USER_ASSOC_ID", nullable=false) public Long getUserAssocId() { return this.userAssocId; } public void setUserAssocId(Long userAssocId) { this.userAssocId = userAssocId; setDirty(true); } @Column(name="USER_ID", unique=true) public Long getUserId() { return this.userId; } public void setUserId(Long userId) { this.userId = userId; setDirty(true); } @Column(name="USER_ASSOC_CD") public String getUserAssocCd() { return this.userAssocCd; } public void setUserAssocCd(String userAssocCd) { this.userAssocCd = userAssocCd; setDirty(true); } @ManyToOne(fetch=FetchType.EAGER) @JoinColumn(name="BUS_ENTITY_ID") public StoreListEntity getStores() { return this.stores; } public void setStores(StoreListEntity stores) { this.stores = stores; setDirty(true); } }
package com.youthchina.service.community; import com.youthchina.dao.jinhao.CommunityInvitationMapper; import com.youthchina.domain.jinhao.property.Invitable; import com.youthchina.exception.zhongyang.exception.NotFoundException; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class InvitationServiceImpl implements InvitationService { @Resource CommunityInvitationMapper communityInvitationMapper; @Override public void add(Invitable entity, Integer userId, Integer invitedUserId) throws NotFoundException{ Integer type = entity.getInviteTargetType(); Integer id = entity.getId(); Integer invitId = communityInvitationMapper.checkIfInvitationExist(type,id,userId,invitedUserId); if(invitId != null){ throw new NotFoundException(4040,404,"you have invited this user");//todo } communityInvitationMapper.add(type,id,userId,invitedUserId); } @Override public void accept(Invitable entity, Integer userId, Integer invitedUserId)throws NotFoundException { Integer type = entity.getInviteTargetType(); Integer id = entity.getId(); Integer invitId = communityInvitationMapper.checkIfInvitationExist(type,id,userId,invitedUserId); if(invitId == null){ throw new NotFoundException(4040,404,"没有找到这个邀请");//todo } communityInvitationMapper.update(invitId); } }
package design.mode.factory.abstractFactory; import design.mode.factory.Milk; public abstract class AbstractMilkFactory { public abstract Milk getTeLunSuMilk(); public abstract Milk getYiLiMilk(); }
/* ThreadTest.java Author: Ketan Pandya Illustrates use of wait() and notify/notifyAll to do blocking of a thread. */ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; // // Main class which creates threads and objects. // public class ThreadTest { public static void main(String s[]) { Account acnt = new Account(); PhoneBill pb = new PhoneBill(acnt); TvBill tvb = new TvBill(acnt); Payroll pr = new Payroll(acnt); ExecutorService ex = Executors.newCachedThreadPool(); ex.execute(pb); ex.execute(pr); ex.execute(tvb); ex.shutdown(); } } // // Account - a class which holds the balance amount and method to // debit from and credit to the account. When a thread enters either // debit or credit, the object of this class will be locked and no // other thread will be able to access it. class Account { private int balance = 0; // Synchronized, so only one thread will enter the method. synchronized void debit(int amnt) { // if money is there then deduct it. if (balance >= amnt) { balance = balance - amnt; System.out.println("After debit balance = " + balance); } else // if money is not available then block i.e wait { balance = 0; System.out.println("After debit balance = " + balance); System.out.println("Waiting.."); try { wait(); } catch (Exception e) { e.printStackTrace(); } } } // Synchronized, so only one thread will enter the method. // Add money to the balance. synchronized void credit(int amnt) { balance = balance + amnt; System.out.println("After credit balance = " + balance); notifyAll(); // Make all waiting threads ready. } } // // PhoneBill - thread will attempts to debit the account every 200 ms. // class PhoneBill implements Runnable { private Account accnt; PhoneBill(Account a) { accnt = a; } public void run() { while (true) { try { Thread.sleep(200); } catch (Exception e) { e.printStackTrace(); } accnt.debit(25); } } } // // Payroll - thread which adds money to the account every 8000 ms. // class Payroll implements Runnable { private Account accnt; Payroll(Account a) { accnt = a; } public void run() { while (true) { try { Thread.sleep(8000); } catch (Exception e) { e.printStackTrace(); } accnt.credit(400); } } } // // TvBill - thread which deduct money of the account every 200 ms. // class TvBill implements Runnable { private Account accnt; TvBill(Account a) { accnt = a; } public void run() { while (true) { try { Thread.sleep(200); } catch (Exception e) { e.printStackTrace(); } accnt.debit(10); } } }
public enum SizesSML { S, M, L }
package com.tencent.mm.plugin.voiceprint.model; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.plugin.voiceprint.model.g.1; import com.tencent.mm.sdk.platformtools.x; class g$1$1 implements e { final /* synthetic */ 1 oFe; g$1$1(1 1) { this.oFe = 1; } public final void a(int i, int i2, String str, l lVar) { x.d("MicroMsg.NetSceneRsaGetVoicePrintResource", "summerauth dkcert getcert type:%d ret [%d,%d]", new Object[]{Integer.valueOf(lVar.getType()), Integer.valueOf(i), Integer.valueOf(i2)}); if (i == 0 && i2 == 0) { this.oFe.oFd.a(this.oFe.oFd.dIX, this.oFe.oFd.diJ); } else { this.oFe.oFd.diJ.a(i, i2, "", this.oFe.oFd); } } }
package com.base.adev.fragment; import android.support.annotation.LayoutRes; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.View; import com.base.adev.R; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView; import java.util.ArrayList; import java.util.List; public abstract class BaseRecyclerFragment<T> extends BaseFragment { private static final String TAG = "BaseRecyclerFragment"; protected SwipeRefreshLayout mSwipeRefreshLayout; protected SwipeMenuRecyclerView mSwipeMenuRecyclerView; protected RvAdapter mAdapter; /** * list 布局 */ protected static final int LINEAR_LAYOUT_MANAGER = 0; /** * grid 布局 */ protected static final int GRID_LAYOUT_MANAGER = 1; /** * 瀑布流布局 */ protected static final int STAGGERED_GRID_LAYOUT_MANAGER = 2; /** * 默认为 0 单行布局 */ private int mListType = 0; /** * 排列方式默认垂直 */ private boolean mIsVertical = true; /** * grid 布局与瀑布流布局默认单行数量 */ private int mSpanCount = 1; /** * 子布局 id */ private int layoutResId = -1; /** * 是否可刷新,默认不可以 */ private boolean mCanRefresh = false; /** * 刷新监听 */ private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = null; @Override protected void initView(View view) { initItemLayout(); mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.base_swipe_refresh_lay); mSwipeMenuRecyclerView = (SwipeMenuRecyclerView) view.findViewById(R.id.base_rv_list); setRefreshEnable(mCanRefresh, mOnRefreshListener); chooseListType(mListType, mIsVertical); if (-1 == layoutResId) { throw new RuntimeException("layoutResId is null!"); } mAdapter = new RvAdapter(layoutResId, new ArrayList<T>()); mSwipeMenuRecyclerView.setAdapter(mAdapter); } /** * 设置子布局 layout * * @param layoutResId 子布局 layout */ public void setLayoutResId(@LayoutRes int layoutResId) { this.layoutResId = layoutResId; } /** * 初始化子布局 */ protected abstract void initItemLayout(); /** * 设置下拉刷新 * * @param canRefresh 下拉刷新功能是否可用,true:允许,false:禁止。 * @param onRefreshListener 刷新监听 */ protected void setRefreshEnable(boolean canRefresh, SwipeRefreshLayout.OnRefreshListener onRefreshListener) { if (canRefresh) { mSwipeRefreshLayout.setEnabled(true); mSwipeRefreshLayout.setOnRefreshListener(onRefreshListener); } else { mSwipeRefreshLayout.setEnabled(false); } } /** * 设置加载更多 * * @param mOnScrollListener 滚动监听 */ protected void setLoadMoreEnable(RecyclerView.OnScrollListener mOnScrollListener) { // 添加滚动监听 mSwipeMenuRecyclerView.addOnScrollListener(mOnScrollListener); } /** * 设置布局类型 * * @param type 布局管理 type * @param isVertical 是否为垂直布局,true:垂直布局,false:横向布局 * @param canRefresh 是否可刷新 * @param onRefreshListener 刷新监听,如果 canRefresh 为 true,必须传 onRefreshListener,若为 false,传 null */ protected void setListType(int type, boolean isVertical, boolean canRefresh, SwipeRefreshLayout.OnRefreshListener onRefreshListener) { mListType = type; mIsVertical = isVertical; mCanRefresh = canRefresh; mOnRefreshListener = onRefreshListener; } /** * 设置 grid 样式和瀑布流横向或纵向数量 * * @param spanCount 数量 */ protected void setSpanCount(int spanCount) { if (spanCount > 0) mSpanCount = spanCount; } /** * 设置布局管理器 * * @param listType 布局类型 * @param isVertical 是否为垂直布局 */ private void chooseListType(int listType, boolean isVertical) { switch (listType) { case LINEAR_LAYOUT_MANAGER: LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); linearLayoutManager.setOrientation(isVertical ? LinearLayoutManager.VERTICAL : LinearLayoutManager.HORIZONTAL); mSwipeMenuRecyclerView.setLayoutManager(linearLayoutManager); break; case GRID_LAYOUT_MANAGER: GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), mSpanCount); gridLayoutManager.setOrientation(isVertical ? GridLayoutManager.VERTICAL : GridLayoutManager.HORIZONTAL); mSwipeMenuRecyclerView.setLayoutManager(gridLayoutManager); break; case STAGGERED_GRID_LAYOUT_MANAGER: StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager (mSpanCount, isVertical ? StaggeredGridLayoutManager.VERTICAL : StaggeredGridLayoutManager.HORIZONTAL); mSwipeMenuRecyclerView.setLayoutManager(staggeredGridLayoutManager); break; default: LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); layoutManager.setOrientation(isVertical ? LinearLayoutManager.VERTICAL : LinearLayoutManager.HORIZONTAL); mSwipeMenuRecyclerView.setLayoutManager(layoutManager); break; } } /** * adapter 内的处理 * * @param baseViewHolder BaseViewHolder * @param t 泛型 T */ protected abstract void MyHolder(BaseViewHolder baseViewHolder, T t); public class RvAdapter extends BaseQuickAdapter<T, BaseViewHolder> { public RvAdapter(int layoutResId, List<T> data) { super(layoutResId, data); } @Override protected void convert(BaseViewHolder baseViewHolder, T t) { MyHolder(baseViewHolder, t); } } }
package com.beiyelin.generator; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STErrorListener; import org.stringtemplate.v4.STGroup; import org.stringtemplate.v4.STGroupDir; import org.stringtemplate.v4.misc.STMessage; import java.io.File; import java.util.Date; import java.util.Map; /** * @Author: newmann hu * @Date: created $time$ $date$ * @Description: **/ @Data @Slf4j public class Generator { private String modulePath; private String packageName; private String packagePath; private STGroup group; public static final String TEMPLATE_PATH = "template\\curd"; public void genCode(Map<String, EntityTypeEnum> entityList) { group = new STGroupDir(TEMPLATE_PATH); entityList.forEach((entityName,entityType)->{ genRepository(entityName,entityType); genService(entityName,entityType); genController(entityName,entityType); }); // Files.write(repositoryFile,stRepository.render(),charset); // System.out.println(stRepository.render()); // stRepository.inspect(); } public void genRepository(String entityName, EntityTypeEnum entityType){ ST stRepository = group.getInstanceOf("repository"); stRepository.add("packageName",packageName.concat(".repository")); stRepository.add("entityName",entityName); stRepository.add("idType","String"); stRepository.add("entityPackage", packageName.concat(".entity.Account")); stRepository.add("createTime",(new Date()).toString()); String repositoryPathStr = modulePath.concat("\\") .concat(packagePath).concat("\\") .concat("repository"); System.out.println(repositoryPathStr); File repositoryPath = new File(repositoryPathStr); if (!repositoryPath.exists()) { if (repositoryPath.mkdirs()) { System.out.println("创建".concat(repositoryPathStr).concat("成功")); } else{ System.out.println("创建".concat(repositoryPathStr).concat("失败。。。")); }; } // Path repositoryPath = Paths.get(repositoryPathStr); // Files.createDirectory(repositoryPath); String repositoryFileName = repositoryPathStr.concat("\\").concat(entityName).concat("Repository").concat(".java"); System.out.println(repositoryFileName); File repositoryFile = new File(repositoryFileName); if (!repositoryFile.exists()) { try { repositoryFile.createNewFile(); }catch (Exception e){ log.error(e.getMessage()); return; } } // Charset charset = Charset.forName("UTF-8"); STErrorListener listener = new STErrorListener() { @Override public void compileTimeError(STMessage msg) { System.out.println(msg.toString()); } @Override public void runTimeError(STMessage msg) { System.out.println(msg.toString()); } @Override public void IOError(STMessage msg) { System.out.println(msg.toString()); } @Override public void internalError(STMessage msg) { System.out.println(msg.toString()); } }; try { stRepository.write(repositoryFile, listener); }catch (Exception e){ log.error(e.getMessage()); } } public void genService(String entityName, EntityTypeEnum entityType) { } public void genController(String entityName, EntityTypeEnum entityType){} }
package lesson36.Ex3; public class InvalidWagesException extends Exception { private long invalidWages; public InvalidWagesException(long invalidWages) { this.invalidWages = invalidWages; } public InvalidWagesException(String message, long invalidWages) { super(message); this.invalidWages = invalidWages; } public long getInvalidWages() { return invalidWages; } public void setInvalidWages(long invalidWages) { this.invalidWages = invalidWages; } }
package pl.edu.wat.wcy.pz.project.server.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import pl.edu.wat.wcy.pz.project.server.entity.EmailVerificationToken; import java.util.Optional; @Repository public interface EmailVerificationTokenRepository extends JpaRepository<EmailVerificationToken, Long> { Optional<EmailVerificationToken> findFirstByToken(String token); }
package kh.picsell.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import kh.picsell.dao.HonorDAO; import kh.picsell.dto.HonorDTO; import kh.picsell.dto.HonorListDTO; import kh.picsell.dto.MemberDTO; import kh.picsell.dto.WriterImageUpDTO; @Service public class HonorService { @Autowired private HonorDAO dao; public int insert(HonorDTO dto)throws Exception { return dao.insert(dto); } public List<HonorDTO> honorlist() throws Exception{ return dao.honorlist(); } public int like(String nickname) throws Exception{ return dao.like(nickname); } public int voteinsert(String nickname) throws Exception{ return dao.voteinsert(nickname); } public int delete()throws Exception{ return dao.delete(); } public List<WriterImageUpDTO> showlike(WriterImageUpDTO imgdto) throws Exception{ return dao.showlike(imgdto); } public List<WriterImageUpDTO> showview(WriterImageUpDTO imgdto) throws Exception{ return dao.showview(imgdto); } public List<WriterImageUpDTO> showdownload(WriterImageUpDTO imgdto) throws Exception{ return dao.showdownload(imgdto); } public int insertcheck(String nickname) throws Exception{ return dao.insertcheck(nickname); } public int votecheck(String nick) throws Exception{ return dao.votecheck(nick); } public int votedelete() throws Exception{ return dao.deletevote(); } public List<MemberDTO> manlike(MemberDTO dto){ return dao.manlike(dto); } public List<WriterImageUpDTO> manpic(String nickname){ return dao.manpic(nickname); } public List<MemberDTO> first(MemberDTO dto){ return dao.first(dto); } public List<MemberDTO> second(MemberDTO dto){ return dao.second(dto); } public List<MemberDTO> third(MemberDTO dto){ return dao.third(dto); } public MemberDTO dfirst(){ return dao.dfirst(); } public MemberDTO dsecond(){ return dao.dsecond(); } public MemberDTO dthird(){ return dao.dthird(); } public List<HonorDTO> hfirst() { return dao.hfirst(); } public List<HonorDTO> hsecond() { return dao.hsecond(); } public List<HonorDTO> hthird() { return dao.hthird(); } public List<HonorDTO> list(HonorDTO dto)throws Exception{ return dao.list(dto); } public int man(String nickname) throws Exception{ return dao.man(nickname); } public List<HonorDTO> honormember() throws Exception{ return dao.honormember(); } public int enter(String nickname, int honorpoint) throws Exception { return dao.enter(nickname, honorpoint); } public List<HonorListDTO> enterhonorlist() throws Exception{ return dao.enterhonorlist(); } public HonorDTO top() throws Exception { return dao.top(); } public MemberDTO getpicture(String nickname) throws Exception{ return dao.getpicture(nickname); } public HonorListDTO newhonor() throws Exception { return dao.newhonor(); } }
package primary.coursethree.selfcode; import javax.print.DocFlavor; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; //如何仅用队列结构实现栈结构? 如何仅用栈结构实现队列结构 public class StackAndQueueConvert { public static class TwoStackToQueue{ private Stack<Integer> pushStack; private Stack<Integer> popStack; public TwoStackToQueue(){ pushStack = new Stack<>(); popStack = new Stack<>(); } public void push(Integer num){ this.pushStack.push(num); } public Integer poll(){ if(this.pushStack.isEmpty() && this.popStack.isEmpty()){ throw new ArrayIndexOutOfBoundsException("The Queue is empty"); }else if(this.popStack.isEmpty()){ while(!this.pushStack.isEmpty()){ this.popStack.push(this.pushStack.pop()); } } return popStack.pop(); } public Integer peek(){ if(this.pushStack.isEmpty() && this.popStack.isEmpty()){ return null; }else if(this.popStack.isEmpty()){ while(!this.pushStack.isEmpty()){ this.popStack.push(this.pushStack.pop()); } } return popStack.peek(); } } public static class TwoQueueToStack{ private Queue<Integer> queue; private Queue<Integer> help; public TwoQueueToStack(){ // queue = new Queue<Integer>(); queue = new LinkedList<>(); //注意这里用的是LinkedList help = new LinkedList<>(); } public void push(Integer num){ queue.add(num); } public Integer pop(){ if(this.queue.isEmpty()){ throw new ArrayIndexOutOfBoundsException("The Stack is empty"); } while(queue.size()!=1){ this.help.add(this.queue.poll()); } int value = queue.poll(); swap(); return value; } public Integer peek(){ if(this.queue.isEmpty()){ return null; } while(queue.size()!=1){ this.help.add(this.queue.poll()); } int value = queue.poll(); this.help.add(value); swap(); return value; } public void swap(){ Queue<Integer> tmp = new LinkedList<>(); tmp = this.queue; this.queue = this.help; this.help = tmp; } } public static void main(String[] args) { TwoStackToQueue queue = new TwoStackToQueue(); queue.push(3); queue.push(6); queue.push(9); System.out.println(queue.peek()); // 3 queue.poll(); System.out.println(queue.peek()); // 6 System.out.println("=========================="); // Queue<Integer> que = new LinkedList<>(); // que.add(1); // System.out.println(que); // [1] // Queue<Integer> tmp = que; // System.out.println(tmp); TwoQueueToStack stack = new TwoQueueToStack(); stack.push(3); stack.push(5); stack.push(7); // System.out.println(stack); // //primary.coursethree.selfcode.StackAndQueueConvert$TwoQueueToStack@2f4d3709 System.out.println(stack.peek()); // 7 stack.pop(); System.out.println(stack.peek()); // 5 } }
package com.tencent.mm.pluginsdk.g.a.a; import com.tencent.mm.a.g; import com.tencent.mm.pluginsdk.g.a.a.b.b; import com.tencent.mm.pluginsdk.g.a.a.b.c; import com.tencent.mm.pluginsdk.g.a.c.q; import com.tencent.mm.pluginsdk.g.a.c.q.a; import com.tencent.mm.pluginsdk.g.a.c.s; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; final class h implements com.tencent.mm.pluginsdk.g.a.c.h { h() { } public final void a(s sVar, int i) { if (sVar.field_expireTime != 0 && sVar.field_expireTime <= bi.VE()) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "urlKey(%s) exceed expire time(%d), delete", new Object[]{sVar.field_urlKey, Long.valueOf(sVar.field_expireTime)}); q ccH = a.ccH(); String str = sVar.field_urlKey; if (ccH.fAQ) { ccH.qDu.jy(str); } com.tencent.mm.pluginsdk.g.a.d.a.Tr(sVar.field_filePath); com.tencent.mm.pluginsdk.g.a.d.a.Tr(sVar.field_filePath + ".decompressed"); com.tencent.mm.pluginsdk.g.a.d.a.Tr(sVar.field_filePath + ".decrypted"); a.ccH().Tp(sVar.field_urlKey); } else if (i == 0) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "network unavailable, skip"); } else if (2 == i && 1 == sVar.field_networkType) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "network type = gprs, record network type = wifi, skip this "); } else if (sVar.field_deleted) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "record(%s), should have been deleted", new Object[]{sVar.field_urlKey}); com.tencent.mm.pluginsdk.g.a.d.a.Tr(sVar.field_filePath); com.tencent.mm.pluginsdk.g.a.d.a.Tr(sVar.field_filePath + ".decompressed"); com.tencent.mm.pluginsdk.g.a.d.a.Tr(sVar.field_filePath + ".decrypted"); } else if (!sVar.field_needRetry) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "no need retry, resType %d, subType %d, version %s", new Object[]{Integer.valueOf(sVar.field_resType), Integer.valueOf(sVar.field_subType), sVar.field_fileVersion}); } else if (sVar.field_status == 2) { long Io = com.tencent.mm.pluginsdk.g.a.d.a.Io(sVar.field_filePath); if (sVar.field_contentLength > Io) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "content-length > fileSize, resume download"); if (0 == Io) { if (!sVar.field_needRetry) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "no need retry, resType %d, subType %d, version %s", new Object[]{Integer.valueOf(sVar.field_resType), Integer.valueOf(sVar.field_subType), sVar.field_fileVersion}); return; } else if (1 != i) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "fileSize = 0, completed file may be deleted by user, skip this because it's not wifi"); return; } else { for (b bVar : c.ccr().ccp()) { int i2 = sVar.field_resType; i2 = sVar.field_subType; bi.getInt(sVar.field_fileVersion, 0); if (bVar.ccq()) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "filterNotRetry by %s, resType %d, subType %d, version %s", new Object[]{bVar.getClass().getName(), Integer.valueOf(sVar.field_resType), Integer.valueOf(sVar.field_subType), sVar.field_fileVersion}); return; } } sVar.field_fileUpdated = true; c.ccr().f(sVar.field_resType, sVar.field_subType, 0, bi.oV(sVar.field_groupId2).equals("NewXml")); a.ccH().g(sVar); } } a.ccH().d(c.c(sVar)); } else if (d(sVar)) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "md5 check ok, file download complete, throw event to do decrypt"); e(sVar); } else { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "file invalid, re-download"); a(sVar, 1 == i); } } else if (sVar.field_status == 1 || sVar.field_status == 0) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "db status: downloading or waiting, db content-length %d", new Object[]{Long.valueOf(sVar.field_contentLength)}); if (a.ccH().To(sVar.field_urlKey)) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "request already in downloading queue"); return; } x.d("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "check md5"); if (d(sVar)) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "md5 match, request complete, throw event to do decrypt"); sVar.field_status = 2; sVar.field_contentLength = com.tencent.mm.pluginsdk.g.a.d.a.Io(sVar.field_filePath); a.ccH().g(sVar); e(sVar); return; } if (0 == com.tencent.mm.pluginsdk.g.a.d.a.Io(sVar.field_filePath)) { sVar.field_fileUpdated = true; a.ccH().g(sVar); c.ccr().f(sVar.field_resType, sVar.field_subType, 0, bi.oV(sVar.field_groupId2).equals("NewXml")); } x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "md5 not match, download"); a.ccH().d(c.c(sVar)); } else if (sVar.field_status == 4 || sVar.field_status == 3) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "file invalid, re-download"); sVar.field_status = 0; a(sVar, true); } } private static boolean d(s sVar) { return bi.oV(g.cu(sVar.field_filePath)).equals(sVar.field_md5); } private static void a(s sVar, boolean z) { a.ccH().Tp(sVar.field_urlKey); com.tencent.mm.pluginsdk.g.a.d.a.Tr(sVar.field_filePath); com.tencent.mm.pluginsdk.g.a.d.a.Tr(sVar.field_filePath + ".decompressed"); com.tencent.mm.pluginsdk.g.a.d.a.Tr(sVar.field_filePath + ".decrypted"); if (2 == sVar.field_status && !z) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "delete completed but invalid file, but forceDL = false, skip this downloading"); } else if (sVar.field_maxRetryTimes <= 0 || sVar.field_retryTimes > 0) { sVar.field_retryTimes--; sVar.field_fileUpdated = true; a.ccH().g(sVar); j.n(sVar.field_reportId, 12); x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "post network task"); c c = c.c(sVar); c.pON = false; a.ccH().d(c); } else { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "record_maxRetryTimes = %d, record_retryTimes = %d, retry times out, skip ", new Object[]{Integer.valueOf(sVar.field_maxRetryTimes), Integer.valueOf(sVar.field_retryTimes)}); } } private static void e(s sVar) { if (sVar.field_fileCompress || sVar.field_fileEncrypt) { x.i("MicroMsg.ResDownloader.CheckResUpdateResumeRecordHandler", "send query and decrypt request"); c.ccr().b(sVar); return; } c.ccr().d(sVar.field_resType, sVar.field_subType, sVar.field_filePath, bi.getInt(sVar.field_fileVersion, 0)); } }
package com.cz.android.sample.listview.list2.decoration; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.view.View; import com.cz.android.sample.R; import com.cz.android.sample.listview.list2.SimpleNestedListView; /** * @author Created by cz * @date 2020/7/9 5:41 PM * @email bingo110@126.com */ public class DividerItemDecoration extends SimpleNestedListView.ItemDecoration { private final Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG); public DividerItemDecoration(Context context) { paint.setColor(Color.GRAY); paint.setStrokeWidth(context.getResources().getDimension(R.dimen.sample_divide)); } @Override public void onDraw(Canvas c, SimpleNestedListView parent) { super.onDraw(c, parent); int childCount = parent.getChildCount(); int orientation = parent.getOrientation(); for(int i=0;i<childCount;i++){ View childView = parent.getChildAt(i); Rect outRect = parent.getDecoratedInsets(childView); if(SimpleNestedListView.HORIZONTAL==orientation){ int paddingTop = parent.getPaddingTop(); int paddingBottom = parent.getPaddingBottom(); int height = parent.getHeight(); int right = childView.getRight(); int strokeWidth = outRect.right; paint.setStrokeWidth(strokeWidth); c.drawLine(right+strokeWidth/2,paddingTop,right+strokeWidth/2,height+paddingBottom/2,paint); } else if(SimpleNestedListView.VERTICAL==orientation){ int paddingLeft = parent.getPaddingLeft(); int paddingRight = parent.getPaddingRight(); int width = parent.getWidth(); int bottom = childView.getBottom(); int strokeWidth = outRect.bottom; paint.setStrokeWidth(outRect.bottom); c.drawLine(paddingLeft,bottom+strokeWidth/2,width-paddingRight,bottom+strokeWidth/2,paint); } } } @Override public void onDrawOver(Canvas c, SimpleNestedListView parent) { super.onDrawOver(c, parent); } @Override public void getItemOffsets(Rect outRect, int itemPosition, SimpleNestedListView parent) { super.getItemOffsets(outRect,itemPosition, parent); int orientation = parent.getOrientation(); int strokeWidth = (int) paint.getStrokeWidth(); if(SimpleNestedListView.HORIZONTAL==orientation){ outRect.set(0,0,strokeWidth,0); } else if(SimpleNestedListView.VERTICAL==orientation){ outRect.set(0,0,0,strokeWidth); } } }
package org.denevell.natch.jsp.thread.add; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.PageContext; import org.denevell.natch.io.posts.AddPostResourceReturnData; import org.denevell.natch.jsp.ForumDao; import org.denevell.natch.jsp.ForumDao.ObjectOrStatusCode; import org.denevell.natch.utils.Forwards; import org.denevell.natch.utils.SessionUtils; import org.denevell.natch.utils.Strings; import org.denevell.natch.utils.simpletags.ComponentTag; import org.denevell.natch.utils.simpletags.PostResponse; public class AddThreadPOST implements PostResponse { private ForumDao mDao; public void setDao(ForumDao mDao) { this.mDao = mDao; } private SessionUtils mSessionUtils = new SessionUtils(); public void setSessionUtils(SessionUtils mSessionUtils) { this.mSessionUtils = mSessionUtils; } @Override public String process( HttpServletRequest req, HttpServletResponse res, PageContext pageContext, Object input) { AddThreadJspInput in = (AddThreadJspInput) input; if(mDao==null) mDao = ForumDao.getInstance(req.getServletContext()); // Can be non null in testing String authKey = mSessionUtils.getAuthKey(req); ObjectOrStatusCode<AddPostResourceReturnData> ret = mDao.addThread( in.getSubject(), in.getContent(), in.getTagArray(), null, authKey); if(ret.object!=null && ret.object.isSuccessful()) { Forwards.sendToListPosts(req, res, ret.object.getThread().getId(), "1"); return ComponentTag.FORWARDING; } else if(ret.statusCode==400){ return Strings.getPostFieldsCannotBeBlank(); } else { String error = (ret==null || ret.object==null || ret.object.getError()==null) ? "Unknown error" : ret.object.getError(); return "Error adding thread: " + error; } } }
package com.cse308.sbuify.common; import com.cse308.sbuify.image.Image; import com.cse308.sbuify.image.ImageI; import com.cse308.sbuify.user.User; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.IndexedEmbedded; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.time.LocalDateTime; import static org.hibernate.search.annotations.IndexedEmbedded.DEFAULT_NULL_TOKEN; @MappedSuperclass public abstract class CatalogItem implements Serializable, Cloneable { @Id @GeneratedValue private Integer id; @NotNull @NotEmpty @Field private String name; @NotNull @JsonSerialize(using = LocalDateTimeSerializer.class) @JsonDeserialize(using = LocalDateTimeDeserializer.class) private LocalDateTime createdDate; @NotNull private Boolean active = true; @OneToOne @IndexedEmbedded(includeEmbeddedObjectId = true, indexNullAs = DEFAULT_NULL_TOKEN) @JsonIgnoreProperties("password") private User owner; @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, targetEntity = Image.class) private ImageI image; public CatalogItem() { } public CatalogItem(@NotEmpty String name, User owner, ImageI image) { this.name = name; this.owner = owner; this.image = image; } /** * Set date created when catalog item is first persisted. */ @PrePersist private void onPrePersist() { this.createdDate = LocalDateTime.now(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public LocalDateTime getCreatedDate() { return createdDate; } public void setCreatedDate(LocalDateTime createdDate) { this.createdDate = createdDate; } public Boolean isActive() { return active; } public void setActive(Boolean active) { this.active = active; } public User getOwner() { return owner; } public void setOwner(User owner) { this.owner = owner; } public ImageI getImage() { return image; } public void setImage(ImageI image) { this.image = image; } @Override public String toString() { ObjectMapper mapper = new ObjectMapper(); String jsonString = ""; try { mapper.enable(SerializationFeature.INDENT_OUTPUT); jsonString = mapper.writeValueAsString(this); } catch (JsonProcessingException e) { e.printStackTrace(); } return jsonString; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CatalogItem that = (CatalogItem) o; return id.equals(that.id); } @Override public int hashCode() { return id.hashCode(); } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
package graphics; import java.awt.*; import javax.swing.*; // Header data import java.util.*; import game.Game; import player.Player; import card.Card; import card.CityCard; public class Footer extends graphics.Box { int p_flag_width = 5; int p_info_width; int p_highlight = 2; int p_cont_gap = 2 + p_highlight; Hashtable<String, Box> player_tabs; // Useful to identify specific player tabs in the footer so they can be updated // individually Game g; Renderer r; int p_tab_height; int p_n_lines = 3; int p_line_height; Font tab_font_name; Font tab_font_data; // Constructors public Footer(int width, int height, Game g, Renderer r, int p_tab_height) { super(width, height, null); player_tabs = new Hashtable<String, Box>(); this.p_tab_height = p_tab_height; this.g = g; this.r = r; // RAWR - rethink gaps this.p_info_width = width - this.p_flag_width - 2 * this.p_cont_gap; this.p_line_height = (int) ((float) p_tab_height / this.p_n_lines) - 2 * this.p_cont_gap; this.tab_font_name = new Font("TimesRoman", Font.BOLD, this.p_line_height); this.tab_font_data = new Font("TimesRoman", Font.PLAIN, this.p_line_height - 2); // Creates table contents of footers Collection<Player> players = g.players.values(); Table player_hud = new Table(width, players.size(), p_tab_height); Box container = new Box(width, players.size() * p_tab_height, null); // Creates scrollable container JScrollPane scrollable = new JScrollPane(); scrollable.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scrollable.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); scrollable.setViewportView(container); // Creates an info object per player containing its relevant info for (Player p : players) { Box p_tab = new Box(width, p_tab_height, new FlowLayout(FlowLayout.LEFT, p_cont_gap, p_cont_gap)); parsePlayerInfo(p_tab, p); // Appends main data container to general player list player_hud.add(p_tab); // Adds resulting object to a hashtable, so it can be easily refreshed later player_tabs.put(p.alias, p_tab); } // Appends list to main container and binds scrollable object to footer container.add(player_hud); this.add(scrollable); // this.add(new JLabel("[Footer] - Should show current turn data...")); // this.add(new JLabel("[Footer] - Second line...")); } // Refresh a set of player info blocks public void refresh(ArrayList<String> players) { // Refreshes blocks for (String p : players) { Box container = player_tabs.get(p); // Removes all its contents container.removeAll(); // Generates player info contents parsePlayerInfo(container, this.g.players.get(p)); // Refresh interface container.revalidate(); container.repaint(); } } // Given a Box object and a player, builds the dataobject public void parsePlayerInfo(Box container, Player p) { // Player info main containers Box p_flag = new Box(this.p_flag_width, this.p_tab_height, null); Box p_info = new Box(this.p_info_width, this.p_tab_height, null); // Highlights current playing player if (p.turn) { p_info.setBorder(BorderFactory.createLineBorder(Color.blue, p_highlight)); } // Sets flag p_flag.setBackground(this.r.color_players.get(p.alias)); // Builds info Table p_data = new Table(this.p_info_width, p_n_lines, this.p_line_height); JLabel p_name = new JLabel(p.alias); Box p_city = new Box(this.p_info_width, this.p_line_height, null); JLabel p_city_l1 = new JLabel("In: "); JLabel p_city_l2 = new JLabel(p.city.name + "(" + p.city.local_disease.name + ")"); p_city_l2.setOpaque(true); p_city_l2.setBackground(this.r.color_diseases.get(p.city.local_disease.alias)); p_city_l1.setFont(this.tab_font_data); p_city_l2.setFont(this.tab_font_data); p_city.add(p_city_l1); p_city.add(p_city_l2); // Player hand Box p_hand = new Box(this.p_info_width, this.p_line_height, null); JLabel p_hand_l1 = new JLabel("Hand: "); p_hand_l1.setFont(this.tab_font_data); p_hand.add(p_hand_l1); for (CityCard c : p.hand.values()) { JLabel p_hand_l = new JLabel(c.city.alias); p_hand_l.setOpaque(true); p_hand_l.setBackground(this.r.color_diseases.get(c.city.local_disease.alias)); p_hand_l.setFont(this.tab_font_data); // Border p_hand_l.setBorder(BorderFactory.createLineBorder(Color.black)); p_hand.add(p_hand_l); } // Sets appropriate font p_name.setFont(this.tab_font_name); p_hand.setFont(this.tab_font_data); // Appends tab contents to table p_data.add(p_name); p_data.add(p_city); p_data.add(p_hand); // Appends table to info container p_info.add(p_data); // Appends flag & tab to main player data container container.add(p_flag); container.add(p_info); } }
package task82; import common.Utils; import java.io.IOException; import java.util.List; /** * @author Igor */ public class Main1 { public static void main(String[] args) throws IOException { int size = 80; int[][] matrix = new int[size][size]; int[][] best = new int[size][size]; matrix = getMatrix(Utils.readFile("../50_99/src/task82/matrix.txt")); // Dynamic Programming - initialization for (int i = 0; i < size; i++) { best[i][0] = matrix[i][0]; } // Dynamic Programming - going // right in the matrix column by column for (int j = 1; j < size; j++) { for (int row = 0; row < size; row++) { int s = best[row][j - 1]; int t = row; while (t >= 0) { s += matrix[t][j]; if (best[t][j] == 0 || best[t][j] > s) { best[t][j] = s; } t--; } s = best[row][j - 1]; t = row; while (t < size) { s += matrix[t][j]; if (best[t][j] == 0 || best[t][j] > s) { best[t][j] = s; } t++; } } } // Finding the minimal // value in the last column int min = Integer.MAX_VALUE; for (int j = 0; j < size; j++) { if (best[j][size - 1] < min) { min = best[j][size - 1]; } } System.out.println(min); } private static int[][] getMatrix(List<String> lines) { int size = lines.size(); int[][] matrix = new int[size][size]; for (int i = 0; i < size; i++) { String[] numbers = lines.get(i).split(","); int[] row = new int[size]; for (int j = 0; j < size; j++) { row[j] = Integer.parseInt(numbers[j]); } matrix[i] = row; } return matrix; } }
package com.enat.sharemanagement.security.role; import com.enat.sharemanagement.exceptions.EntityNotFoundException; import com.enat.sharemanagement.security.privilage.Privilege; import com.enat.sharemanagement.security.privilage.PrivilegeRepository; import com.enat.sharemanagement.utils.Common; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import javax.persistence.EntityExistsException; import java.time.LocalDateTime; import java.util.HashSet; import java.util.List; import java.util.Set; @Service @RequiredArgsConstructor public class RoleService implements Common<Role, Role,Long> { private final RoleRepository roleRepository; private final PrivilegeRepository privilegeRepository; @Override public Role store(Role role) { if (roleRepository.findByName(role.getName()).isPresent()) { throw new EntityExistsException("Role with name '" + role.getName() + "' already exists"); } getRolePrivileges(role, role); return roleRepository.save(role); } @Override public Iterable<Role> store(List<Role> t) { return null; } @Override public Role show(Long id) { return roleRepository.findById(id).orElseThrow(() -> new EntityNotFoundException(Role.class, " id ", String.valueOf(id))); } @Override public Role update(Long id, Role role) { Role r = show(id); if (role.getPrivileges() != null && role.getPrivileges().size() != 0) { getRolePrivileges(role, r); } return roleRepository.save(r); } private void getRolePrivileges(Role role, Role r) { Set<Privilege> privileges = new HashSet<>(); for (Privilege privilege : role.getPrivileges()) { Privilege byName = privilegeRepository.findByName(privilege.getName()) .orElseThrow(() -> new EntityNotFoundException(Privilege.class, " name ", privilege.getName())); privileges.add(byName); } r.setPrivileges(privileges); } @Override public boolean delete(Long id) { Role role = roleRepository.findById(id).orElseThrow(() -> new EntityNotFoundException(Role.class, " id ", String.valueOf(id))); role.setDeletedAt(LocalDateTime.now()); roleRepository.save(role); return true; } @Override public Page<Role> getAll(Pageable pageable) { return roleRepository.findAllByDeletedAtIsNull(pageable); } public Role getRoleByName(String name) { return roleRepository.findByName(name) .orElseThrow(()-> new EntityNotFoundException(Role.class,"Name",name)); } }
package com.hawk.application.repository.springdatajpa; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import com.hawk.application.model.User; public interface UserRepository extends CrudRepository<User, Integer> { User findByEmail(String email); @Modifying @Query("UPDATE User u SET u.password = :newPassword WHERE u.id = :id") void updatePassword(@Param("id") Integer id, @Param("newPassword") String newPassword); }
package com.xj.base.controller.admin.system; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.xj.base.common.JsonResult; import com.xj.base.controller.BaseController; import com.xj.base.controller.admin.LoginController; import com.xj.base.entity.Classes; import com.xj.base.entity.Course; import com.xj.base.entity.Student; import com.xj.base.entity.User; import com.xj.base.entity.Dormitory; import com.xj.base.entity.Role; import com.xj.base.service.IClassesService; import com.xj.base.service.ICourseService; import com.xj.base.service.IDormitoryService; import com.xj.base.service.IStudentService; import com.xj.base.service.specification.SimpleSpecificationBuilder; import com.xj.base.service.specification.SpecificationOperator.Operator; @Controller @RequestMapping("/admin/student") public class StudentController extends BaseController { @Autowired private IStudentService studentService; @Autowired private IDormitoryService dormitoryService; @Autowired private ICourseService courseService; @Autowired private IClassesService classesService; @RequestMapping(value = { "/", "/index" }) public String index() { return "admin/student/index"; } @RequestMapping(value = { "/list" }) @ResponseBody public Page<Student> list() { SimpleSpecificationBuilder<Student> builder = new SimpleSpecificationBuilder<Student>(); String searchText = request.getParameter("searchText"); if(StringUtils.isNotBlank(searchText)){ builder.addOr("name", Operator.likeAll.name(), searchText); builder.addOr("address", Operator.likeAll.name(), searchText); } Page<Student> page = studentService.findAll(builder.generateSpecification(), getPageRequest()); for (Student student : page) { String name = studentService.findDormitoryNameById(student.getId()); student.setDormName(name); student.setClassName(studentService.findClassNameById(student.getClassedId())); // student.setDormitory(null); // student.setCourses(null); } return page; } @RequestMapping(value = "/add", method = RequestMethod.GET) public String add(ModelMap map) { Map<String, String> map2 = new HashMap<String, String>(); List<Course> list = courseService.findAll(); // List<Dormitory> dormitorys = dormitoryService.findAll(); // map.put("dormitorys", dormitorys); map.put("add", "add"); List<Classes> classes = classesService.findAll(); map.put("classes", classes); List<Dormitory> dormitorys = dormitoryService.findAll(); map.put("dormitorys", dormitorys); return "admin/student/form"; } @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET) public String edit(@PathVariable Integer id,ModelMap map) { Student student = studentService.find(id); map.put("student", student); List<Dormitory> dormitorys = dormitoryService.findAll(); map.put("dormitorys", dormitorys); List<Classes> classes = classesService.findAll(); map.put("classes", classes); return "admin/student/form"; } @RequestMapping(value= {"/edit"} ,method = RequestMethod.POST) @ResponseBody public JsonResult edit(Student student,ModelMap map, Integer dormid){ try { if (null != dormid) { Dormitory dormitory = dormitoryService.find(dormid); student.setDormitory(dormitory); } studentService.saveOrUpdate(student); // studentService.update(student); } catch (Exception e) { return JsonResult.failure(e.getMessage()); } return JsonResult.success(); } @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public JsonResult delete(@PathVariable Integer id,ModelMap map) { try { studentService.delete(id); } catch (Exception e) { e.printStackTrace(); return JsonResult.failure(e.getMessage()); } return JsonResult.success(); } @RequestMapping(value = "/grant/{id}", method = RequestMethod.GET) public String grant(@PathVariable Integer id, ModelMap map) { Student student = studentService.find(id); map.put("student", student); Set<Course> set = student.getCourses(); List<Integer> courseIds = new ArrayList<Integer>(); for (Course course : set) { courseIds.add(course.getId()); } map.put("courseIds", courseIds); List<Course> courses = courseService.findAll(); map.put("courses", courses); return "admin/student/grant"; } @ResponseBody @RequestMapping(value = "/grant/{id}", method = RequestMethod.POST) public JsonResult grant(@PathVariable Integer id,String[] roleIds, ModelMap map) { try { studentService.grant(id,roleIds); } catch (Exception e) { e.printStackTrace(); return JsonResult.failure(e.getMessage()); } return JsonResult.success(); } }
package rest; import dao.DAOLog; import entities.User; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import rest.security.AuthToken; import rest.security.Authentication; import entities.Credentials; import entities.Log; import javax.ejb.Stateless; import javax.ws.rs.GET; import javax.ws.rs.PathParam; import javax.ws.rs.core.Context; import org.apache.cxf.jaxrs.ext.MessageContext; import rest.security.PasswordHasher; import rest.security.RightsChecker; @Stateless @Path("auth") @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces(MediaType.TEXT_PLAIN) public class AuthenticationEndpoint { @PersistenceContext(unitName = "IUFPU") private EntityManager em; public AuthenticationEndpoint() { } /** * Endpoint qui authentifie un utilisateur sur base de ses credentials (login, mot de passe) et lui renvoie un token * signé pour ses requêtes suivantes afin de pouvoir s'authentifier rapidement. * @param credentials entité qui contient le login et le mot de passe de l'utilisateur à authentifier * @return Token d'authentification pour l'utilisateur */ @POST public Response authenticateUser(Credentials credentials) { AuthToken token = authenticate(credentials); new DAOLog(em).log(new User(token.getUserId()), Log.Type.AUTH_USER, "'" + credentials.getLogin() + "' s'est connecté"); return Response.ok(token.toJsonString()).build(); } /** * Endpoint qui permet à un superadmin de récupérer un token qui lui permet d'utiliser le compte d'un autre utilisateur. * @param jaxrsContext Contexte de la requête, utilisé pour l'authentification * @param login Le login du compte qu'on veut utiliser * @return Token qui permet de se faire passer pour l'utisateur correspondant au login. */ @GET @Path("adminLoginAs/{login}") public Response authenticateAsUser(@Context MessageContext jaxrsContext, @PathParam("login") String login) { AuthToken token = Authentication.validate(jaxrsContext); User superadmin = RightsChecker.getInstance(em).validate(token, User.Roles.SUPERADMIN); TypedQuery<User> userQuery = em.createNamedQuery("User.getByLogin", User.class); userQuery.setParameter("login", login); User user; try { user = userQuery.getSingleResult(); } catch(Exception e) { throw new WebApplicationException(Response.Status.NOT_FOUND); } if(user.hasRole(User.Roles.SUPERADMIN)) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } AuthToken userToken = Authentication.issueToken(user.getId(), user.getRole(), 60 * 60, AuthToken.AUTH_KEY); new DAOLog(em).log(superadmin, Log.Type.AUTH_AS, "'" + superadmin.getLogin() + "' s'est connecté en tant que '" + login + "'", user); return Response.ok(userToken.toJsonString()).build(); } private AuthToken authenticate(Credentials credentials) { TypedQuery<User> authQuery = em.createNamedQuery("User.getByloginWithCredentialsForAuth", User.class); authQuery.setParameter("login", credentials.getLogin()); List<User> users = authQuery.getResultList(); // si on a un et un seul résultat (login est unique) c'est bon, sinon : if(users == null || users.isEmpty() || users.size() > 1) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } // check pw User user = users.get(0); PasswordHasher ph = new PasswordHasher(credentials.getPassword(), user.getCredentials().getSalt(), user.getCredentials().getIteration()); if(! ph.hash().equals(user.getCredentials().getPassword())) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } // génération du token en fonction du l'utilisateur return Authentication.issueToken(user.getId(), user.getRole(), 60 * 60, AuthToken.AUTH_KEY); // token valable pendant 1h = 60 * 60 = 3600 sec } }
package fr.fares.zoo; import java.util.ArrayList; import java.util.List; public class Habitat { private final Environnement environnement; private List<Animal> animaux = new ArrayList<>(); public Habitat(Environnement environnement) { this.environnement = environnement; } public boolean ajouterUnAnimal(Animal animal) { for (Animal a: animaux) { if (a.isSolo() != animal.isSolo()) return false; if (animal.isSolo() && !animal.equals(a)) { return false; } } if (getPlacesRestantes() > 0 && animal.getEnvironnement().equals(this.environnement)) { return this.animaux.add(animal); } return false; } public List<Animal> getAnimaux() { return animaux; } public int getPlacesPrises() { return animaux.size(); } public int getPlacesTotal() { return environnement.getPlace(); } public int getPlacesRestantes() { return environnement.getPlace() - animaux.size(); } public String getAnimauxDescription() { String retour = ""; for (Animal animal: animaux) { retour += animal.getDescription() + "; "; } return retour; } public Environnement getEnvironnement() { return environnement; } public String getDescription() { return this.environnement.getDescription() + "\nplaces restantes='" + getPlacesRestantes() + "'\nanimaux={ " + getAnimauxDescription() + "}"; } public void deplacerAnimalVers(Habitat habitat, Animal animal) { if (!animaux.contains(animal)) return; for (Animal a: animaux) { if (animal.equals(a)) { habitat.ajouterUnAnimal(a); animaux.remove(a); break; } } } @Override public String toString() { return environnement.getNom(); // return "Habitat{" + // "environnement=" + environnement + // ", animaux=" + animaux + // '}'; } }
/** * Copyright (c) 2016, 润柒 All Rights Reserved. * */ package com.richer.jsms.thread.middle.io.b102; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * * 自定义线程池 * * @author <a href="mailto:sunline360@sina.com">润柒</a> * @since JDK 1.7 * @version 0.0.1 */ public class HandlerExecutorPool { private ExecutorService executor; public HandlerExecutorPool(int maxPoolSize,int queueSize){ this.executor = new ThreadPoolExecutor( //当前机器最大线程数 Runtime.getRuntime().availableProcessors(), maxPoolSize, 120L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize)); } public void execute(Runnable task){ this.executor.execute(task); } }
package br.com.helpdev.quaklog.configuration.converter; import org.junit.jupiter.api.Test; import java.time.LocalDate; import static org.junit.jupiter.api.Assertions.*; class LocalDateToStringConverterTest { private final LocalDateToStringConverter converter = new LocalDateToStringConverter(); @Test void shouldNotThrowExceptionWhenConvertingNullParameter() { final String convert = converter.convert(null); assertNull(convert); } @Test void shouldThrowDateTimeParseExceptionWhenTryingToConvertInvalidDate() { final String convert = converter.convert(LocalDate.of(2010, 10, 10)); assertEquals("2010-10-10", convert); } }
package claseResurse; import java.util.Date; public class Notare { private int id_notare; private Date data; private int student_numar_matricol; private int profesor_marca; private int disciplina_id_disciplina; private int nota; public int getId_notare() { return id_notare; } public void setId_notare(int id_notare) { this.id_notare = id_notare; } public Date getData() { return data; } public void setData(Date data) { this.data = data; } public int getStudent_numar_matricol() { return student_numar_matricol; } public void setStudent_numar_matricol(int student_numar_matricol) { this.student_numar_matricol = student_numar_matricol; } public int getProfesor_marca() { return profesor_marca; } public void setProfesor_marca(int profesor_marca) { this.profesor_marca = profesor_marca; } public int getDisciplina_id_disciplina() { return disciplina_id_disciplina; } public void setDisciplina_id_disciplina(int disciplina_id_disciplina) { this.disciplina_id_disciplina = disciplina_id_disciplina; } public int getNota() { return nota; } public void setNota(int nota) { this.nota = nota; } }
package com.zjm.design.d15_observer; public class MySubject extends AbstractSubject{ @Override public void opration() { System.out.println("update myself"); notifyObserver(); } }
package com.leysoft.app.controller; import java.net.URI; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.leysoft.app.assembler.LibroResourceAssembler; import com.leysoft.app.entity.Libro; import com.leysoft.app.exception.NotFoundException; import com.leysoft.app.resource.LibroResource; import com.leysoft.app.service.inter.LibroService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; @Api @RestController public class ApiLibroController { @Autowired private LibroService libroService; @Autowired private LibroResourceAssembler assembler; @GetMapping(value = {"/libro"}) @ApiOperation(value = "get-libros", nickname = "get-libros") @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 500, message = "Failure")}) public ResponseEntity<List<LibroResource>> list() { List<LibroResource> resources = assembler.toResources(libroService.findAll()); return new ResponseEntity<List<LibroResource>>(resources, HttpStatus.OK); } @GetMapping(value = {"/libro/search"}) @ApiOperation(value = "search-libros", nickname = "search-libros") @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 500, message = "Failure")}) public ResponseEntity<List<LibroResource>> search(@RequestParam("titulo") String titulo) { List<LibroResource> resources = assembler.toResources(libroService.findByTituloContainingIgnoreCase(titulo)); return new ResponseEntity<List<LibroResource>>(resources, HttpStatus.OK); } @GetMapping(value = {"/libro/{id}"}) @ApiOperation(value = "get-libro", nickname = "get-libro") @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Failure")}) public ResponseEntity<LibroResource> detail(@PathVariable("id") Long id) { Libro libro = libroService.findById(id); if(libro == null) { throw new NotFoundException("id - " + id); } LibroResource resource = assembler.toResource(libro); return new ResponseEntity<LibroResource>(resource, HttpStatus.OK); } @PostMapping(value = {"/libro"}) @ApiOperation(value = "save-libro", nickname = "save-libro") @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 500, message = "Failure")}) public ResponseEntity<Void> create(@Valid @RequestBody Libro libro) { Libro currentLibro = libroService.save(libro); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}").buildAndExpand(currentLibro.getId()).toUri(); return ResponseEntity.created(location).build(); } @ApiOperation(value = "update-libro", nickname = "update-libro") @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Failure")}) @PutMapping(value = {"/libro/{id}"}) public ResponseEntity<Void> update(@Valid @RequestBody Libro libro, @PathVariable("id") Long id) { Libro currentLibro = libroService.findById(id); if(currentLibro == null) { throw new NotFoundException("id - " + id); } currentLibro.setTitulo(libro.getTitulo()); currentLibro.setFechaPublicacion(libro.getFechaPublicacion()); currentLibro.setAutor(libro.getAutor()); libroService.update(currentLibro); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}").buildAndExpand(currentLibro.getId()).toUri(); return ResponseEntity.created(location).build(); } @ResponseStatus(value = HttpStatus.NO_CONTENT) @DeleteMapping(value = {"/libro/{id}"}) @ApiOperation(value = "delete-libro", nickname = "delete-libro") @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Failure")}) public void delete(@PathVariable("id") Long id) { Libro libro = libroService.findById(id); if(libro == null) { throw new NotFoundException("id - " + id); } libroService.delete(id); } }
package mensaje; import javax.swing.JFrame; import entornoGrafico.JSala; public class MsjAvisarNuevoClienteEnSala extends Mensaje { private static final long serialVersionUID = 1L; private String userNuevo; // nuevo en la sala public MsjAvisarNuevoClienteEnSala(String userNuevo) { this.userNuevo = userNuevo; this.clase = this.getClass().getSimpleName(); } @Override public void ejecutar() { JFrame ventanaActual = listenerClient.getCliente().getVentanaActual(); ((JSala) ventanaActual).agregarAlaSala(userNuevo); } public String getUserNuevo() { return userNuevo; } public void setUserNuevo(String userNuevo) { this.userNuevo = userNuevo; } }
import java.util.ArrayList; /** * Provides useful methods for manipulating an * ArrayList of words. * * @author Ben Godfrey * @version 05 FEB 2018 */ public class WordList { /** Stores the list of words. */ private ArrayList<String> myList; /** * Creates a new WordList given an ArrayList of words. * * @param myList An ArrayList of strings; the words to be manipulated. */ public WordList(ArrayList<String> myList) { this.myList = myList; } /** * Counts the number of words in the list that are a given length. * * @param len The length to search for. * @return The number of words that are len length. */ public int numWordsOfLength(int len) { int counter = 0; for (String s: myList) { if (s.length() == len) counter++; } return counter; } /** * Removes words from the list that are a given length. * * @param len The exact length of words to be removed. */ public void removeWordsOfLength(int len) { for (int i=0; i<myList.size(); i++) { if (myList.get(i).length() == len) { myList.remove(i); i--; } } } /** * Returns a String representation of this object. * * @return A String representation of this object. */ public String toString() { return myList.toString(); } }
package campus; import java.util.Scanner; /** * @author kangkang lou */ public class Main_1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { String s = in.next(); int a = 0; int b = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if ((i + 1) % 2 == 0) { if (c != 'W') { a++; } if (c != 'B') { b++; } } else { if (c != 'B') { a++; } if (c != 'W') { b++; } } } System.out.println(Math.min(a, b)); } } }
/* * This software is licensed under the MIT License * https://github.com/GStefanowich/MC-Server-Protection * * Copyright (c) 2019 Gregory Stefanowich * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.theelm.sewingmachine.interfaces; import com.mojang.authlib.GameProfile; import net.minecraft.block.entity.BlockEntity; import net.minecraft.block.entity.SignText; import net.minecraft.item.SmithingTemplateItem; import net.minecraft.server.MinecraftServer; import net.minecraft.sound.SoundEvents; import net.minecraft.text.LiteralTextContent; import net.minecraft.util.ActionResult; import net.minecraft.util.DyeColor; import net.minecraft.util.Hand; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.world.World; import net.theelm.sewingmachine.base.CoreMod; import net.theelm.sewingmachine.base.mixins.Interfaces.SmithingTemplateItemAccessor; import net.theelm.sewingmachine.base.objects.ShopSign; import net.theelm.sewingmachine.enums.Test; import net.theelm.sewingmachine.utilities.DevUtils; import net.theelm.sewingmachine.utilities.TitleUtils; import net.theelm.sewingmachine.utilities.mod.Sew; import net.theelm.sewingmachine.utilities.nbt.NbtUtils; import net.theelm.sewingmachine.utilities.text.MessageUtils; import net.theelm.sewingmachine.utilities.text.StyleApplicator; import net.minecraft.block.entity.LootableContainerBlockEntity; import net.minecraft.block.entity.SignBlockEntity; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.inventory.Inventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.recipe.Recipe; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvent; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import net.minecraft.util.Formatting; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; import net.theelm.sewingmachine.utilities.text.TextUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; public interface ShopSignData { @NotNull StyleApplicator APPLICATOR_GREEN = new StyleApplicator("#32CD32"); @NotNull StyleApplicator APPLICATOR_RED = new StyleApplicator("#B22222"); /** * Get the attached container Entity for the Sign * @return The attached container, or NULL if none found */ @Nullable LootableContainerBlockEntity getContainer(); /** * Get the Signs Entity * @return The Signs Entity */ @NotNull SignBlockEntity getSign(); /** * Find the attached inventory for the Sign (The inventory of the container) * @return The attached inventory, or NULL if none found */ @Nullable Inventory getInventory(); /** * Get the text present on a specified line of the sign * @return */ @Nullable Text getSignLine(int line); /** * Set the signs front-side text * @return */ boolean setSign(@NotNull SignText text); /** * Set the signs front-side text with the applied first-line preformatting * @return */ default boolean setSign(@NotNull Text[] text) { Text[] render = new Text[4]; ShopSign shop = this.getShopType(); // Set line 1 to the shop type render[0] = MutableText.of(new LiteralTextContent("[" + shop.name + "]" )).styled(shop.getApplicator()); // Set lines 2, 3, and 4 to the provided Text for (int i = 0; i < 3; i++) render[i + 1] = i >= text.length ? TextUtils.literal() : text[i]; return this.setSign(new SignText(render, render, DyeColor.BLACK, false)); } void setShopOwner(@Nullable UUID uuid); @Nullable UUID getShopOwner(); default @NotNull Optional<GameProfile> getShopOwnerProfile() { UUID uuid = this.getShopOwner(); if (uuid == null) return Optional.empty(); if (Objects.equals(uuid, CoreMod.SPAWN_ID)) return Optional.of(new GameProfile(uuid, "Server")); return Sew.tryGetServer() .map(MinecraftServer::getUserCache) .flatMap(cache -> cache.getByUuid(uuid)); } @Nullable Item getShopItem(); @Nullable Identifier getShopItemIdentifier(); default @NotNull String getShopItemTranslationKey() { Item item = this.getShopItem(); return (item == null ? Items.AIR : item).getTranslationKey(); } default @Nullable Map<Enchantment, Integer> getShopItemEnchantments() { return new HashMap<>(); } default @Nullable Text getShopItemDisplay() { Item item = this.getShopItem(); if (item == null) return Text.literal(""); return Text.translatable(item.getTranslationKey()); } @Nullable List<? extends Recipe<?>> getShopItemRecipes(); @Nullable Integer getShopItemCount(); @Nullable Integer getShopItemPrice(); boolean setItem(@NotNull ItemStack stack); @Nullable BlockPos getFirstPos(); @Nullable BlockPos getSecondPos(); @Nullable ShopSign getShopType(); /** * Check if item-transfer can be ignored * @return If infinite */ default boolean isInfinite() { return Objects.equals(CoreMod.SPAWN_ID, this.getShopOwner()); } /** * Read the Item from the Sign and return the Formatting of the item * @return The formatted item name */ default @NotNull MutableText textParseItem() { Integer itemSize = this.getShopItemCount(); Item tradeItem = this.getShopItem(); Map<Enchantment, Integer> enchantments = this.getShopItemEnchantments(); if (itemSize == null || tradeItem == null || enchantments == null) return TextUtils.literal(); MutableText baseText = Text.translatable(itemSize == 1 ? "" : (itemSize + " ")); MutableText translatable = Text.translatable(tradeItem.getTranslationKey()); if (Items.ENCHANTED_BOOK.equals(tradeItem) && enchantments.size() == 1) { Optional<MutableText> optional = enchantments.entrySet() .stream() .findAny() .map(MessageUtils::enchantmentToText); if (optional.isPresent()) translatable = optional.get(); } else if (tradeItem instanceof SmithingTemplateItem templateItem) { translatable = ((SmithingTemplateItemAccessor) templateItem).getTitle() .copyContentOnly(); } return baseText.formatted(Formatting.BLACK) .append(translatable.formatted(Formatting.DARK_AQUA)); } /** * Read the shop owner from the Sign and return the Formatted name * @return The formatted owners name */ default MutableText textParseOwner() { Optional<GameProfile> lookup = this.getShopOwnerProfile(); return lookup.map(profile -> Objects.equals(CoreMod.SPAWN_ID, profile.getId()) ? null : Text.literal(profile.getName())) .orElseGet(() -> Text.literal("Nobody")); } /** * Rerun the sign formatter. Updates the owners name (If changed) and any formatting * @return If the sign was successfully rendered */ default boolean renderSign() { ShopSign type = this.getShopType(); return type != null && type.renderSign(this); } /** * Set the position that any sounds will come from * @param pos The sound source */ default void setSoundSourcePosition(@Nullable BlockPos pos) { } /** * Get the position that sounds should be played from * @return The sound source */ default @Nullable BlockPos getSoundSourcePosition() { return null; } /** * Play a sound for interacting with the sign * @param player The player to play the sound for (Will play for everyone nearby if the sign has set a SoundSourcePosition) * @param event The sound to play * @param category The category to use for the sounds volume */ default void playSound(@NotNull ServerPlayerEntity player, @NotNull SoundEvent event, @NotNull SoundCategory category) { ServerWorld world = player.getServerWorld(); BlockPos source; if (world == null || (source = this.getSoundSourcePosition()) == null) player.playSound(event, category, 1.0f, 1.0f); else world.playSound(null, source, event, category, 1.0f, 1.0f); } /** * Test if an ItemStack matches the Item exactly for this sign * @param stack The ItemStack to check * @return If the ItemStack matches the Item and Enchantments of this sign */ default boolean itemMatchPredicate(@NotNull ItemStack stack) { // Items must be equals if (!Objects.equals(this.getShopItem(), stack.getItem())) return false; // Don't accept damaged goods if (stack.isDamaged()) return false; // Make sure the enchantments match Map<Enchantment, Integer> enchantments = this.getShopItemEnchantments(); return enchantments == null || NbtUtils.enchantsEquals(enchantments, EnchantmentHelper.get(stack)); } /** * Item Spawner if this Sign is Infinite * @param count The stack count to create * @return An ItemStack */ default @NotNull ItemStack createItemStack(int count) { Item item = this.getShopItem(); if (item == null) item = Items.AIR; ItemStack stack = new ItemStack(item, Math.min(count, item.getMaxCount())); // Apply enchantments to the stack Map<Enchantment, Integer> enchantments = this.getShopItemEnchantments(); if (enchantments != null && !enchantments.isEmpty()) EnchantmentHelper.set(enchantments, stack); return stack; } static Test onSignInteract(@NotNull ServerPlayerEntity player, @NotNull World world, Hand hand, @NotNull ItemStack itemStack, @NotNull BlockHitResult blockHitResult) { BlockPos blockPos = blockHitResult.getBlockPos(); final BlockEntity blockEntity = world.getBlockEntity(blockPos); // Check if the block interacted with is a sign (For shop signs) if (blockEntity instanceof ShopSignData shopSign && blockEntity instanceof SignBlockEntity) { ShopSign shopSignType; // Interact with the sign if ((shopSign.getShopOwner() != null) && ((shopSignType = shopSign.getShopType()) != null)) { shopSignType.onInteract(world.getServer(), player, blockPos, shopSign) // Literal Text (Error) .ifLeft((text) -> { shopSign.playSound(player, SoundEvents.ENTITY_VILLAGER_NO, SoundCategory.NEUTRAL); TitleUtils.showPlayerAlert(player, Formatting.RED, text); }) // Boolean if success/fail .ifRight((bool) -> { if (!bool) shopSign.playSound(player, SoundEvents.ENTITY_VILLAGER_NO, SoundCategory.NEUTRAL); else if (shopSign.getSoundSourcePosition() != null && world.random.nextInt(12) == 0) shopSign.playSound(player, SoundEvents.ENTITY_VILLAGER_YES, SoundCategory.NEUTRAL); }); return Test.SUCCESS; } else if (DevUtils.isDebugging()) { CoreMod.logInfo("[DEBUG] Interacted with non-shop sign"); } } return Test.CONTINUE; } }
package br.org.catolicasc.salamandrium.dao; import br.org.catolicasc.salamandrium.entity.Expedidor; public class ExpedidorDao extends JpaDaoBase<Expedidor> { }
/** * Copyright (C) 2015 Zalando SE (http://tech.zalando.com) * * 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.zalando.zmon.actuator; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.util.StopWatch; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.UrlPathHelper; import org.zalando.zmon.actuator.metrics.MetricsWrapper; /** * Absolute the same as in the original. But instead of using CounterService and GaugeService a Timer fom Codahale is * used. * * @author jbellmann */ @Order(Ordered.HIGHEST_PRECEDENCE) public class ZmonMetricsFilter extends OncePerRequestFilter { private static final int UNDEFINED_HTTP_STATUS = 999; private final MetricsWrapper metricsWrapper; public ZmonMetricsFilter(final MetricsWrapper metricsWrapper) { this.metricsWrapper = metricsWrapper; } @Override protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws ServletException, IOException { StopWatch stopWatch = new StopWatch(); stopWatch.start(); String path = new UrlPathHelper().getPathWithinApplication(request); int status = HttpStatus.INTERNAL_SERVER_ERROR.value(); try { chain.doFilter(request, response); status = getStatus(response); } finally { stopWatch.stop(); metricsWrapper.recordClientRequestMetrics(request, path, status, stopWatch.getTotalTimeMillis()); } } private int getStatus(final HttpServletResponse response) { try { return response.getStatus(); } catch (Exception ex) { return UNDEFINED_HTTP_STATUS; } } }
package com.ren.bridge.inter; public interface DrawAPI { public void drawCircle(int radius, int x, int y); public void drawRect(int width, int high); }
package com.example.ecommerce.Admin; import android.Manifest; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.graphics.pdf.PdfDocument; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.ecommerce.Delivery.DelivererUserProductsActivity; import com.example.ecommerce.Delivery.DeliveryMansProfileActivity; import com.example.ecommerce.Model.AdminOrders; import com.example.ecommerce.Model.Balance; import com.example.ecommerce.Model.DelivererBalance; import com.example.ecommerce.Model.Invoice; import com.example.ecommerce.R; import com.example.ecommerce.ViewHolder.AdminOrdersViewHolder; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.karumi.dexter.Dexter; import com.karumi.dexter.PermissionToken; import com.karumi.dexter.listener.PermissionDeniedResponse; import com.karumi.dexter.listener.PermissionGrantedResponse; import com.karumi.dexter.listener.PermissionRequest; import com.karumi.dexter.listener.single.PermissionListener; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Objects; import java.util.Random; import static android.app.Activity.RESULT_OK; public class AdminNewOrdersFragment extends Fragment { private RecyclerView ordersList; private DatabaseReference ordersRef; private DecimalFormat formatter; private Bitmap bmp, scaledbmp; private int pageHeight = 2010; private int pagewidth = 1200; private ArrayList<String> addAllProductDetails=new ArrayList<>(); private String uID,invoiceNumber; private Uri FilePathUri; private StorageReference pdfFileStorageRef,deletePDFfileRef; private DatabaseReference pdfDatabaseRef; private String downloadPDFUrl; public AdminNewOrdersFragment() { // Required empty public constructor (25-08-2021 eCommerce) see this folder to get Activity } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v=inflater.inflate(R.layout.fragment_admin_new_orders, container, false); pdfFileStorageRef = FirebaseStorage.getInstance().getReference().child("Customers all invoice pdf"); pdfDatabaseRef = FirebaseDatabase.getInstance().getReference().child("Invoices"); ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PackageManager.PERMISSION_GRANTED); ordersRef = FirebaseDatabase.getInstance().getReference().child("Orders"); formatter = new DecimalFormat("#,###"); ordersList = v.findViewById(R.id.orders_list_fragment); ordersList.setLayoutManager(new LinearLayoutManager(v.getContext())); return v; } @Override public void onStart() { super.onStart(); FirebaseRecyclerOptions<AdminOrders> options = new FirebaseRecyclerOptions.Builder<AdminOrders>() .setQuery(ordersRef, AdminOrders.class) .build(); FirebaseRecyclerAdapter<AdminOrders, AdminOrdersViewHolder> adapter =new FirebaseRecyclerAdapter<AdminOrders, AdminOrdersViewHolder>(options) { @Override protected void onBindViewHolder(@NonNull @NotNull AdminOrdersViewHolder holder, int position, @NonNull @NotNull AdminOrders model) { holder.userName.setText("Name: " + model.getName()); holder.userPhoneNumber.setText("Phone: " + model.getPhone()); holder.userTotalPrice.setText("Total Amount = Tk " + formatter.format(Integer.valueOf(model.getTotalAmount())));//formatter.format(Integer.valueOf(model.getTotalAmount())) holder.userDateTime.setText("Order at: " + model.getDate() + " " + model.getTime()); holder.userShippingAddress.setText("Shipping Address: " + model.getAddress() + ", " + model.getCity()); if(model.getDeliveryMansUserId().equals("anyone")){ holder.SeeProfileOfTheDeliveryManBtn.setText("Nobody Picked This Order"); holder.SeeProfileOfTheDeliveryManBtn.setTextColor(Color.parseColor("#FFCC0000")); holder.SeeProfileOfTheDeliveryManBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(v.getContext(), "Nobody Picked This Order", Toast.LENGTH_SHORT).show(); } }); }else{ holder.SeeProfileOfTheDeliveryManBtn.setText("See Profile Of The Delivery Man"); holder.SeeProfileOfTheDeliveryManBtn.setTextColor(Color.parseColor("#1C8051")); holder.SeeProfileOfTheDeliveryManBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(v.getContext(), DeliveryMansProfileActivity.class); intent.putExtra("DeliveryMansUserId",model.getDeliveryMansUserId()); startActivity(intent); } }); } FirebaseDatabase.getInstance().getReference() .child("Cart List").child("Admin View").child(Objects.requireNonNull(getRef(holder.getAdapterPosition()).getKey())).child("Products") .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) { boolean x=true; for (DataSnapshot ds: snapshot.getChildren()){ if(ds.child("confirmationOfSellers").getValue().toString().equals("not confirm")){ x=false; break; } } if(!x){ holder.deliveredSignal.setTextColor(Color.parseColor("#FFCC0000")); }else{ if(!(model.getDelivered().equals("delivered") || model.getDelivered().equals("not delivered"))){ holder.deliveredSignal.setTextColor(Color.parseColor("#1C8051")); } } } @Override public void onCancelled(@NonNull @NotNull DatabaseError error) { } }); if(model.getDelivered().equals("delivered")){ holder.deliveredSignal.setText("Delivered"); holder.deliveredSignal.setTextColor(Color.parseColor("#1C8051")); }else if(model.getDelivered().equals("not delivered")){ holder.deliveredSignal.setText("Not Delivered"); holder.deliveredSignal.setTextColor(Color.parseColor("#FFCC0000")); }else if(model.getDelivered().equals("not confirmed")){ holder.deliveredSignal.setText("Confirmed order"); //holder.deliveredSignal.setTextColor(Color.parseColor("#FFCC0000")); holder.deliveredSignal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FirebaseDatabase.getInstance().getReference() .child("Cart List").child("Admin View").child(Objects.requireNonNull(getRef(holder.getAdapterPosition()).getKey())).child("Products") .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) { boolean x=true; for (DataSnapshot ds: snapshot.getChildren()){ if(ds.child("confirmationOfSellers").getValue().toString().equals("not confirm")){ x=false; break; } } if(!x){ Toast.makeText(v.getContext(), "Some products are not confirmed", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(v.getContext(), "All products are confirmed", Toast.LENGTH_SHORT).show(); ordersRef.child(Objects.requireNonNull(getRef(holder.getAdapterPosition()).getKey())) .child("delivered").setValue("not delivered"); } } @Override public void onCancelled(@NonNull @NotNull DatabaseError error) { } }); } }); } holder.ShowOrdersBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String uID = getRef(position).getKey(); //Intent intent = new Intent(v.getContext(), AdminUserProductsActivity.class); Intent intent = new Intent(v.getContext(), DelivererUserProductsActivity.class); intent.putExtra("uid", uID); startActivity(intent); } }); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CharSequence options[] = new CharSequence[] { "Delete", "Reset", "Give money to specific sellers and Deliverers", "Upload PDF", "View uploaded PDF", "No" }; AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext()); builder.setTitle("Have you delete/reset this order products ?"); builder.setCancelable(false); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { invoiceNumber=model.getInvoiceNumber(); if (i == 0) { uID = getRef(holder.getAdapterPosition()).getKey(); RemoverOrder(uID); }else if(i==1){ uID = getRef(position).getKey(); ChangeOrderStatesSecurityCode(uID); ChangeOrderStateIntoNotShipped(uID); ChangeOrderStateIntoNotConfirmed(uID); ChangeDeliveryMansCurrentPick(model.getDeliveryMansUserId()); ChangeOrderStateIntoAnyoneDeliveryMan(uID); ChangeFilenameFileurl(uID,model.getInvoiceFileUrl()); }else if(i==2){ uID = getRef(position).getKey(); GiveMoneyToSpecificSellersAndDeliverers(uID,model.getDeliveryMansUserId()); }else if(i==3){ uID = getRef(position).getKey(); ordersRef.child(uID).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) { if(snapshot.exists()){ String filename=snapshot.child("invoiceFileName").getValue().toString(); String fileurl=snapshot.child("invoiceFileUrl").getValue().toString(); if(!filename.equals("") && !fileurl.equals("")){ Toast.makeText(v.getContext(), "Invoice pdf file already uploaded..!", Toast.LENGTH_SHORT).show(); }else { bmp = BitmapFactory.decodeResource(getResources(), R.drawable.invoice_header); scaledbmp = Bitmap.createScaledBitmap(bmp, 1200, 580, false); generatePDF(model.getName(),model.getPhone(),model.getTotalAmount()); ChooseInvoicePDF(); Toast.makeText(v.getContext(), "Select "+invoiceNumber+".pdf file", Toast.LENGTH_LONG).show(); } }else{ Toast.makeText(v.getContext(), "Error", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(@NonNull @NotNull DatabaseError error) { } }); }else if(i==4){ uID = getRef(position).getKey(); ViewUploadPDF(uID); } else{ dialogInterface.cancel(); // finish(); } } }); builder.show(); } }); } @NonNull @NotNull @Override public AdminOrdersViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.orders_layout, parent, false); return new AdminOrdersViewHolder(view); } }; ordersList.setAdapter(adapter); adapter.startListening(); } private void ChangeDeliveryMansCurrentPick(String deliveryMansUserId) { if(!deliveryMansUserId.equals("anyone")){ FirebaseDatabase.getInstance().getReference().child("Deliverers") .child(deliveryMansUserId).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) { int currentPick=Integer.valueOf(snapshot.child("currentpick").getValue().toString()); currentPick=currentPick-1; if(!(currentPick<0)){ FirebaseDatabase.getInstance().getReference().child("Deliverers") .child(deliveryMansUserId) .child("currentpick").setValue(String.valueOf(currentPick)); } } @Override public void onCancelled(@NonNull @NotNull DatabaseError error) { } }); } } private void ViewUploadPDF(String uID) { ordersRef.child(uID).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) { if(snapshot.exists()){ String filename=snapshot.child("invoiceFileName").getValue().toString(); String fileurl=snapshot.child("invoiceFileUrl").getValue().toString(); if(!filename.equals("") && !fileurl.equals("")){ Intent intent=new Intent(getContext(), AdminViewPDFActivity.class); intent.putExtra("filename",filename); intent.putExtra("fileurl",fileurl); startActivity(intent); }else { Toast.makeText(getContext(), "First upload invoice pdf file", Toast.LENGTH_SHORT).show(); } }else{ Toast.makeText(getContext(), "Error", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(@NonNull @NotNull DatabaseError error) { } }); } private void ChooseInvoicePDF() { Dexter.withContext(getContext()) .withPermission(Manifest.permission.READ_EXTERNAL_STORAGE) .withListener(new PermissionListener() { @Override public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) { Intent intent=new Intent(); intent.setType("application/pdf"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent,"Select Pdf Files"),101); } @Override public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) { } @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) { permissionToken.continuePermissionRequest(); } }).check(); } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==101 && resultCode==RESULT_OK) { FilePathUri=data.getData(); processupload(FilePathUri); } } public void processupload(Uri filepath) { final ProgressDialog pd=new ProgressDialog(getContext()); pd.setTitle("File Uploading....!!!"); pd.show(); final StorageReference reference=pdfFileStorageRef.child(invoiceNumber+".pdf"); reference.putFile(filepath) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Task<Uri> urlTask = taskSnapshot.getMetadata().getReference().getDownloadUrl(); while (!urlTask.isSuccessful()); downloadPDFUrl = urlTask.getResult().toString(); Calendar calendar = Calendar.getInstance(); SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy"); String saveCurrentDate = currentDate.format(calendar.getTime()); SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a"); String saveCurrentTime = currentTime.format(calendar.getTime()); String CurrentDateCurrentTime = saveCurrentDate +" "+ saveCurrentTime; Invoice obj=new Invoice(invoiceNumber+".pdf",downloadPDFUrl, "Admin",CurrentDateCurrentTime,uID); pdfDatabaseRef.child(CurrentDateCurrentTime).setValue(obj); ordersRef.child(uID).child("invoiceFileUrl").setValue(downloadPDFUrl); ordersRef.child(uID).child("invoiceFileName").setValue(invoiceNumber+".pdf"); pd.dismiss(); Toast.makeText(getContext(),"File Uploaded",Toast.LENGTH_LONG).show(); } }) .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { float percent=(100*taskSnapshot.getBytesTransferred())/taskSnapshot.getTotalByteCount(); pd.setMessage("Uploaded :"+(int)percent+"%"); } }); } private void GiveMoneyToTheDeliverer(String deliveryMansUserId) { if(!deliveryMansUserId.equals("anyone")){ DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("BalanceHistoryForDeliverer"); Calendar calendar = Calendar.getInstance(); SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy"); String saveCurrentDate = currentDate.format(calendar.getTime()); SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a"); String saveCurrentTime = currentTime.format(calendar.getTime()); String CurrentDateCurrentTime = saveCurrentDate +" "+ saveCurrentTime; DelivererBalance obj =new DelivererBalance(deliveryMansUserId,CurrentDateCurrentTime,"100",invoiceNumber); databaseReference.push().setValue(obj); FirebaseDatabase.getInstance().getReference().child("Deliverers") .child(deliveryMansUserId).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) { if(snapshot.exists()){ int balance=Integer.valueOf(snapshot.child("balance").getValue().toString()); balance=balance+100; FirebaseDatabase.getInstance().getReference().child("Deliverers") .child(deliveryMansUserId).child("balance") .setValue(String.valueOf(balance)).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull @NotNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(getContext(), "Your money is added to your respective account. Please check for make sure.", Toast.LENGTH_SHORT).show(); } } }); } } @Override public void onCancelled(@NonNull @NotNull DatabaseError error) { } }); } } private void GiveMoneyToSpecificSellersAndDeliverers(String uID, String DeliveryMansUserId) { GiveMoneyToTheDeliverer(DeliveryMansUserId); DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("BalanceHistoryForSellerAndAdmin"); Calendar calendar = Calendar.getInstance(); SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy"); String saveCurrentDate = currentDate.format(calendar.getTime()); SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a"); String saveCurrentTime = currentTime.format(calendar.getTime()); String CurrentDateCurrentTime = saveCurrentDate +" "+ saveCurrentTime; sellerListArray.clear(); readDataForStoreSeller(new FirebaseCallbackForStoreSeller() { @Override public void onCallbackForStoreSeller(ArrayList<String> list) { for (int i = 0; i < list.size(); i++) { String eachSeller=list.get(i); String[] arr = eachSeller.split("\\s+"); GiveMoneyToTheSellers(arr[0],arr[1]); Balance obj =new Balance(arr[0],CurrentDateCurrentTime,arr[1],invoiceNumber,arr[2]); databaseReference.push().setValue(obj); } } }); } private void GiveMoneyToTheSellers(String sid, String price) { if(!sid.equals("Admin")){ FirebaseDatabase.getInstance().getReference().child("Sellers").child(sid) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot Sellersnapshot) { if(Sellersnapshot.exists()){ int balance=Integer.valueOf(Sellersnapshot.child("balance").getValue().toString()); balance=balance+Integer.valueOf(price); FirebaseDatabase.getInstance().getReference().child("Sellers").child(sid).child("balance") .setValue(String.valueOf(balance)).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull @NotNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(getContext(), "Send money to specific sellers successfully.", Toast.LENGTH_SHORT).show(); } } }); } } @Override public void onCancelled(@NonNull @NotNull DatabaseError error) { } }); }else { FirebaseDatabase.getInstance().getReference().child("Admins").child("01760091552").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot Adminsnapshot) { if(Adminsnapshot.exists()){ int balance=Integer.valueOf(Adminsnapshot.child("balance").getValue().toString()); balance=balance+Integer.valueOf(price); FirebaseDatabase.getInstance().getReference().child("Admins").child("01760091552").child("balance") .setValue(String.valueOf(balance)).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull @NotNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(getContext(), "Send money to specific Admins successfully.", Toast.LENGTH_SHORT).show(); } } }); } } @Override public void onCancelled(@NonNull @NotNull DatabaseError error) { } }); } } private void ChangeFilenameFileurl(String uID,String fileUrl){ if(!fileUrl.equals("")){ deletePDFfileRef=FirebaseStorage.getInstance().getReferenceFromUrl(fileUrl); deletePDFfileRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void unused) { ordersRef.child(uID).child("invoiceFileUrl").setValue(""); ordersRef.child(uID).child("invoiceFileName").setValue(""); FirebaseDatabase.getInstance().getReference().child("Invoices").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) { for (DataSnapshot ds: snapshot.getChildren()) { String fileurl=ds.child("fileurl").getValue().toString(); if(fileUrl.equals(fileurl)){ FirebaseDatabase.getInstance().getReference().child("Invoices").child(ds.child("currentDateCurrentTime").getValue().toString()).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull @NotNull Task<Void> task) { Toast.makeText(getContext(), "PDF also successfully deleted", Toast.LENGTH_SHORT).show(); } }); return; } } } @Override public void onCancelled(@NonNull @NotNull DatabaseError error) { } }); } }); } } private void ChangeOrderStatesSecurityCode(String uID) { Random rand=new Random(); int securityCode=rand.nextInt(90000000)+10000000; ordersRef.child(uID).child("securitycode").setValue(String.valueOf(securityCode)).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull @NotNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(getContext(), "The ordered state is now changed SecurityCode.", Toast.LENGTH_SHORT).show(); } } }); } private void ChangeOrderStateIntoAnyoneDeliveryMan(String uID) { ordersRef.child(uID).child("deliveryMansUserId").setValue("anyone").addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull @NotNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(getContext(), "The ordered state is now anyone deliveryman.", Toast.LENGTH_SHORT).show(); } } }); } private void ChangeOrderStateIntoNotConfirmed(String uID) { ordersRef.child(uID).child("delivered").setValue("not confirmed").addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull @NotNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(getContext(), "The ordered state is now not delivered.", Toast.LENGTH_SHORT).show(); } } }); } private void ChangeOrderStateIntoNotShipped(String uID) { ordersRef.child(uID).child("state").setValue("not shipped").addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull @NotNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(getContext(), "The ordered state is not shipped now.", Toast.LENGTH_SHORT).show(); } } }); } private void RemoverOrder(String uID) { //ordersRef.child(uID).removeValue(); ordersRef.child(uID).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull @NotNull Task<Void> task) { if(task.isSuccessful()){ FirebaseDatabase.getInstance().getReference() .child("Cart List") .child("Admin View") .child(uID) .removeValue() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(getContext(), "order has been deleted successfully.", Toast.LENGTH_SHORT).show(); } } }); } } }); } private void generatePDF(String name, String phone, String TotalPriceOfProducts) { addAllProductDetails.clear(); readData(new FirebaseCallback() { @Override public void onCallback(ArrayList<String> list) { if(list.size()>6){ pageHeight=pageHeight+500; } String saveCurrentDate, saveCurrentTime; Calendar calForDate = Calendar.getInstance(); SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy"); saveCurrentDate = currentDate.format(calForDate.getTime()); SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a"); saveCurrentTime = currentTime.format(calForDate.getTime()); PdfDocument pdfDocument = new PdfDocument(); Paint paint = new Paint(); Paint title = new Paint(); PdfDocument.PageInfo mypageInfo = new PdfDocument.PageInfo.Builder(pagewidth, pageHeight, 1).create(); PdfDocument.Page myPage = pdfDocument.startPage(mypageInfo); Canvas canvas = myPage.getCanvas(); canvas.drawBitmap(scaledbmp, 0, 0, paint); title.setTextAlign(Paint.Align.CENTER); title.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD)); title.setTextSize(70); title.setColor(ContextCompat.getColor(getContext(), R.color.white)); canvas.drawText("A portal for IT professionals.", pagewidth/2, 250, title); paint.setTextAlign(Paint.Align.RIGHT); paint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD)); paint.setTextSize(30f); paint.setColor(ContextCompat.getColor(getContext(), R.color.white)); canvas.drawText("Cell: +8801760091552", 1160, 40, paint); canvas.drawText(" +8801760000000", 1160, 80, paint); title.setTextAlign(Paint.Align.CENTER); title.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD_ITALIC)); title.setTextSize(70); title.setColor(ContextCompat.getColor(getContext(), R.color.design_default_color_error)); canvas.drawText("Invoice", pagewidth/2, 500, title); paint.setTextAlign(Paint.Align.LEFT); paint.setTextSize(35f); paint.setColor(ContextCompat.getColor(getContext(), R.color.design_default_color_error)); canvas.drawText("Customer name: "+name, 20, 590, paint); canvas.drawText("Contact no: "+phone, 20, 640, paint); paint.setTextAlign(Paint.Align.RIGHT); canvas.drawText("Invoice no: "+invoiceNumber, pagewidth-20, 590, paint); canvas.drawText("Date: "+saveCurrentDate, pagewidth-20, 640, paint); canvas.drawText("Time: "+saveCurrentTime, pagewidth-20, 690, paint); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(2); canvas.drawRect(20,780,pagewidth-20,860,paint); paint.setTextAlign(Paint.Align.LEFT); paint.setStyle(Paint.Style.FILL); canvas.drawText("Si. No.", 40, 830, paint); canvas.drawText("Item Description", 200, 830, paint); canvas.drawText("Price", 700, 830, paint); canvas.drawText("Qty", 900, 830, paint); canvas.drawText("Total", 1050, 830, paint); canvas.drawLine(180,790,180,840,paint); canvas.drawLine(680,790,680,840,paint); canvas.drawLine(880,790,880,840,paint); canvas.drawLine(1030,790,1030,840,paint); int yAxis=950; for (int i = 0; i < list.size(); i++) { String eachProduct=list.get(i); String[] arr = eachProduct.trim().split("\\s+"); canvas.drawText(String.valueOf(i+1)+".",40,yAxis,paint); canvas.drawText(arr[0].replace("#"," "),200,yAxis,paint); canvas.drawText(arr[1],700,yAxis,paint); canvas.drawText(arr[2],900,yAxis,paint); paint.setTextAlign(Paint.Align.RIGHT); canvas.drawText(arr[3],pagewidth-40,yAxis,paint); paint.setTextAlign(Paint.Align.LEFT); yAxis=yAxis+100; } int subTotalLine=1200; if(list.size()>3){ //Math.ceil() for (double i = 1; ; i++) { if(Math.ceil(list.size()/3.0)==i){ break; }else { subTotalLine=subTotalLine+300; } } } canvas.drawLine(680,subTotalLine,pagewidth-20,subTotalLine,paint); canvas.drawText("Sub total",700,subTotalLine+50,paint); canvas.drawText(":",900,subTotalLine+50,paint); paint.setTextAlign(Paint.Align.RIGHT); canvas.drawText(TotalPriceOfProducts,pagewidth-40,subTotalLine+50,paint); paint.setTextAlign(Paint.Align.LEFT); canvas.drawText("Tax (0%)",700,subTotalLine+100,paint); canvas.drawText(":",900,subTotalLine+100,paint); paint.setTextAlign(Paint.Align.RIGHT); canvas.drawText("0",pagewidth-40,subTotalLine+100,paint); paint.setTextAlign(Paint.Align.LEFT); paint.setColor(Color.rgb(247,147,30)); canvas.drawRect(680,subTotalLine+150,pagewidth-20,subTotalLine+250,paint); paint.setColor(Color.BLACK); paint.setTextSize(50f); paint.setTextAlign(Paint.Align.LEFT); canvas.drawText("Total",700,subTotalLine+215,paint); paint.setTextAlign(Paint.Align.RIGHT); canvas.drawText(TotalPriceOfProducts,pagewidth-40,subTotalLine+215,paint); pdfDocument.finishPage(myPage); //String myFilePath=Environment.getExternalStorageDirectory().getPath()+"/Nasim2.pdf"; // File file = new File(myFilePath); try { String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Dir"; File dir = new File(path); if(!dir.exists()) dir.mkdirs(); File file = new File(dir, invoiceNumber+".pdf"); pdfDocument.writeTo(new FileOutputStream(file)); Toast.makeText(getContext(), "PDF file generated successfully.", Toast.LENGTH_SHORT).show(); }catch (IOException e) { e.printStackTrace(); } pdfDocument.close(); // Toast.makeText(AdminNewOrdersActivity.this, list.toString(), Toast.LENGTH_SHORT).show(); } }); } private void readData(FirebaseCallback firebaseCallback){ FirebaseDatabase.getInstance().getReference().child("Orders").child(uID).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) { if(snapshot.exists()){ int numberOfProducts=Integer.valueOf(snapshot.child("numberOfProducts").getValue().toString()); for (int i = 0; i < numberOfProducts; i++) { String pid=snapshot.child("productDetails"+String.valueOf(i)).getValue().toString(); addAllProductDetails.add(pid); } } firebaseCallback.onCallback(addAllProductDetails); } @Override public void onCancelled(@NonNull @NotNull DatabaseError error) { } }); } private interface FirebaseCallback{ void onCallback(ArrayList<String> list); } private ArrayList<String> sellerListArray=new ArrayList<>(); private void readDataForStoreSeller(FirebaseCallbackForStoreSeller firebaseCallbackForStoreSeller){ FirebaseDatabase.getInstance().getReference().child("Orders").child(uID).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) { if(snapshot.exists()){ int numberOfSellers=Integer.valueOf(snapshot.child("numberOfSellers").getValue().toString()); for (int i = 0; i < numberOfSellers; i++) { String sid=snapshot.child("seller"+String.valueOf(i)).getValue().toString(); sellerListArray.add(sid); } } firebaseCallbackForStoreSeller.onCallbackForStoreSeller(sellerListArray); } @Override public void onCancelled(@NonNull @NotNull DatabaseError error) { } }); } private interface FirebaseCallbackForStoreSeller{ void onCallbackForStoreSeller(ArrayList<String> list); } }
package com.shopify.common.file; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.shopify.admin.statis.AdminStatisService; import com.shopify.mapper.ExcelMapper; @Service @Transactional public class ExcelService { @Autowired private ExcelMapper excelMapper; private Logger LOGGER = LoggerFactory.getLogger(ExcelService.class); @Autowired private AdminStatisService adminStatisService; /** * 부피중량 엑셀 파일 업로드 * @param destFile * @param filePath */ public List<Map<String, String>> volumeWeightUpload(String destFile, String filePath) { ExcelReadOption excelReadOption = new ExcelReadOption(); LOGGER.debug("ExcelService!!!!!!!!!!!"); List<Map<String, String>> excelContent = new ArrayList<Map<String, String>>(); //파일경로 추가 excelReadOption.setFilePath(filePath); //시작 행 excelReadOption.setStartRow(1); try { excelContent = ExcelRead.readVolumeWeight(excelReadOption); // ********************************************************** Iterator rootItr = excelContent.iterator(); while (rootItr.hasNext()) { Map tmpMap = (Map) rootItr.next(); LOGGER.debug(">>>tmpMap>>> : " + tmpMap.toString()); adminStatisService.updateVolumeWeightData(tmpMap); } }catch (Exception e) { LOGGER.debug("ExcelService Exception : " + e.toString()); } return excelContent; } /** * 요금매핑 가격 업로드 * @param destFile * @param filePath * @param shipCompany * @param deliveryService * @param startDate * @return */ public int feesPriceExcelUpload(String destFile, String filePath, String shipCompany, String deliveryService, String startDate) { ExcelReadOption excelReadOption = new ExcelReadOption(); LOGGER.debug("ExcelService!!!!!!!!!!!"); //파일경로 추가 excelReadOption.setFilePath(filePath); //시작 행 excelReadOption.setStartRow(1); try { List<Map<String, String>>excelContent = ExcelRead.read(excelReadOption); Map<String, Object> paramMap = new HashMap<String, Object>(); Map<String, Object> updateMap = new HashMap<String, Object>(); updateMap.put("shipCompany", shipCompany); updateMap.put("deliveryService", deliveryService); updateMap.put("startDate", startDate); //기존에 있던 data를 useYn N 처리 , endDate 현재일자 -1로 수정, where : id, code,useYn,endDate int updateFees = excelMapper.updateFeesData(updateMap); LOGGER.debug("feesPriceExcelUpload [ updateFees ]: " + updateFees); Iterator rootItr = excelContent.iterator(); while (rootItr.hasNext()) { Map tmpMap = (Map) rootItr.next(); tmpMap.put("shipCompany",shipCompany); tmpMap.put("deliveryService",deliveryService); tmpMap.put("startDate",startDate); String courierId = excelMapper.selectCourierId(tmpMap); tmpMap.put("courierId", courierId); LOGGER.debug("feesPriceExcelUpload : " + tmpMap.toString()); excelMapper.insertFeesData(tmpMap); } } catch (Exception e) { LOGGER.debug("ExcelService Exception : " + e.toString()); return 0; } return 1; } public int salePriceExcelUpload(String destFile, String filePath, String shipCompany, String deliveryService, String startDate) { //LOGGER.debug("salePriceExcelUpload : [Start]"); ExcelReadOption excelReadOption = new ExcelReadOption(); //파일경로 추가 excelReadOption.setFilePath(filePath); //시작 행 excelReadOption.setStartRow(1); try { List<Map<String, String>>excelContent = ExcelRead.read(excelReadOption); //LOGGER.debug("salePriceExcelUpload [excelContent] : " + excelContent.toString()); Map<String, Object> paramMap = new HashMap<String, Object>(); Map<String, Object> updateMap = new HashMap<String, Object>(); updateMap.put("shipCompany", shipCompany); updateMap.put("deliveryService", deliveryService); updateMap.put("startDate", startDate); //기존에 있던 data를 useYn N 처리 , endDate 현재일자로 수정, where : id, code,useYn,endDate int updateFees = excelMapper.updateSaleData(updateMap); Iterator rootItr = excelContent.iterator(); while (rootItr.hasNext()) { Map tmpMap = (Map) rootItr.next(); tmpMap.put("shipCompany",shipCompany); tmpMap.put("deliveryService",deliveryService); tmpMap.put("startDate",startDate); //LOGGER.debug("salePriceExcelUpload : " + tmpMap.toString()); excelMapper.insertSaleData(tmpMap); } } catch (Exception e) { // TODO Auto-generated catch block return 0; } return 1; } }
package io.github.zkhan93.alarmandplayer.data; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import com.google.firebase.firestore.Exclude; import com.google.firebase.firestore.IgnoreExtraProperties; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.TimeZone; public class Alarm implements Parcelable { @Exclude public static final String TAG = Alarm.class.getSimpleName(); @Exclude public String key; public boolean enabled; public int hour; public int minute; public List<Integer> repeat; @Exclude public long milliSecBeforeSetOff() { //Todo: consider repeat and enabled TimeZone IST = TimeZone.getTimeZone("Asia/Kolkata"); Calendar cal = Calendar.getInstance(IST); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, minute); if (Calendar.getInstance(IST).getTime().after(cal.getTime())) { cal.add(Calendar.HOUR, 24); } long now = Calendar.getInstance(IST).getTimeInMillis(); return cal.getTimeInMillis() - now; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.key); dest.writeByte(this.enabled ? (byte) 1 : (byte) 0); dest.writeInt(this.hour); dest.writeInt(this.minute); dest.writeList(this.repeat); } public Alarm() { } protected Alarm(Parcel in) { this.key = in.readString(); this.enabled = in.readByte() != 0; this.hour = in.readInt(); this.minute = in.readInt(); this.repeat = new ArrayList<Integer>(); in.readList(this.repeat, Integer.class.getClassLoader()); } public static final Parcelable.Creator<Alarm> CREATOR = new Parcelable.Creator<Alarm>() { @Override public Alarm createFromParcel(Parcel source) { return new Alarm(source); } @Override public Alarm[] newArray(int size) { return new Alarm[size]; } }; }
package com.yesilfil.qrgenc; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import android.Manifest; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; public class MainActivity extends AppCompatActivity { ImageButton tara; TextView lokasyonn; String urunID = "0"; double Longitude = 0, Latitude = 0; private LocationManager locationManager; private LocationListener listener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tara = (ImageButton) findViewById(R.id.tarabutton); lokasyonn = (TextView) findViewById(R.id.lokasyon); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); listener = new LocationListener() { @Override public void onLocationChanged(Location location) { Longitude = location.getLongitude(); Latitude = location.getLatitude(); /*Toast.makeText(MainActivity.this, "Long :"+location.getLongitude()+" "+"Loc :" + location.getLatitude() , Toast.LENGTH_SHORT).show();*/ } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(i); } }; configure_button(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == 0) { TextView tvlink = (TextView) findViewById(R.id.linktext); if (resultCode == RESULT_OK) { tvlink.setText(intent.getStringExtra("SCAN_RESULT")); urunID = intent.getStringExtra("SCAN_RESULT"); String tokenid = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID); String url = "http://jsonbulut.com/json/likeManagement.php?ref=7b7392076900968d8e4ad78351ad55d3&productId=" + urunID + "&vote=3&customerId=5&long=" + Longitude + "&lat=" + Latitude + "&tokenID=" + tokenid; Log.d("url :", url); Toast.makeText(this, "URL : "+ url, Toast.LENGTH_SHORT).show(); lokasyonn.setText("Long :" + Longitude + " " + "Loc :" + Latitude); new urunKontrol(url, this).execute(); } else if (resultCode == RESULT_CANCELED) { tvlink.setText("Taramadan Vazgeçildi"); } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case 10: configure_button(); break; default: break; } } void configure_button() { // first check for permissions if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET} , 10); } return; } // this code won't execute IF permissions are not allowed, because in the line above there is return statement. tara.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, 0); //Barcode Scanner to scan for us locationManager.requestLocationUpdates("gps", 900000000, 0, listener); Thread th = new Thread() { @Override public void run() { try { Thread.sleep(5000); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } } catch (Exception ex) { } finally { } } }; th.start(); } }); } class urunKontrol extends AsyncTask<Void, Void, Void> { private ProgressDialog pro; String data = ""; String url = ""; public urunKontrol(String url, Activity ac) { this.url = url; pro = new ProgressDialog(ac); pro.setMessage("Lütfen Bekleyiniz ..."); pro.show(); } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... param) { try { data = Jsoup.connect(url).ignoreContentType(true).execute().body(); } catch (Exception ex) { Log.d("Json hatası : ", ex.toString()); } finally { pro.dismiss(); } return null; } @Override protected void onPostExecute(Void o) { super.onPostExecute(o); // data çözümleme try { JSONObject obj = new JSONObject(data); JSONArray arr = obj.getJSONArray("votes"); JSONObject oj = arr.getJSONObject(0); //denetim yapılıyor if (oj.getBoolean("durum")) { Toast.makeText(getApplication(), oj.getString("mesaj"), Toast.LENGTH_SHORT).show(); //giriş başarılı aşağıdaki işlemleri yap } else { Toast.makeText(getApplication(), oj.getString("mesaj"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { Log.d("Giriş hatası : ", e.toString()); } Log.d("Gelen Data : ", data); } } }
package com.yoeki.kalpnay.hrporatal.Notification; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.yoeki.kalpnay.hrporatal.Login.Api; import com.yoeki.kalpnay.hrporatal.Login.ApiInterface; import com.yoeki.kalpnay.hrporatal.R; import com.yoeki.kalpnay.hrporatal.setting.preferance; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class CircularFragment extends Fragment { private RecyclerView ryc_circular; List<CircularModel.ListCircular> arraycircularlist; ApiInterface apiInterface; public static CircularFragment newInstance() { CircularFragment fragment = new CircularFragment(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_circular, container, false); ryc_circular=view.findViewById(R.id.ryc_circular); arraycircularlist=new ArrayList<>(); String user_id=null; user_id = preferance.getInstance(getActivity()).getUserId(); findcircular(user_id); return view; } public void findcircular(String UserId){ arraycircularlist.clear(); final ProgressDialog progressDialog = new ProgressDialog(getActivity()); progressDialog.setCancelable(false); // set cancelable to false progressDialog.setMessage("Please Wait"); // set message progressDialog.show(); // show progress dialogTitle apiInterface= Api.getClient().create(ApiInterface.class); CircularModel user = new CircularModel(UserId); Call<CircularModel> call1 = apiInterface.notificationcircular(user); call1.enqueue(new Callback<CircularModel>() { @Override public void onResponse(Call<CircularModel> call, Response<CircularModel> response) { CircularModel user1 = response.body(); progressDialog.dismiss(); String str=user1.getMessage(); String status=user1.getStatus(); arraycircularlist=user1.getListCircular(); if (status.equals("Success")){ ryc_circular.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); // rec_leavereqattachment.setLayoutManager(new Hori); ryc_circular.setItemAnimator(new DefaultItemAnimator()); CircularAdapter adapter=new CircularAdapter(getActivity(),arraycircularlist); ryc_circular.setAdapter(adapter); }else{ Toast.makeText(getActivity(), "Data not found", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<CircularModel> call, Throwable t) { call.cancel(); Toast.makeText(getActivity(), "somthing went wrong", Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } }); } }
package tests_dominio; import dominio.Alianza; import dominio.Asesino; import dominio.Guerrero; import dominio.Humano; import dominio.MyRandomStub; import dominio.Personaje; import java.util.LinkedList; import org.junit.Assert; import org.junit.Test; public class TestAliarCombatir { @Test public void testCrearAlianza() { Humano h = new Humano("Nicolas", new Guerrero(), 1); Humano h2 = new Humano("Lautaro", new Guerrero(), 1); Assert.assertNull(h.getClan()); Assert.assertNull(h2.getClan()); h.aliar(h2); Assert.assertNotNull(h.getClan()); Assert.assertNotNull(h2.getClan()); } @Test public void testDanar() { Humano h = new Humano("Nicolas", new Guerrero(), 1); Humano h2 = new Humano("Lautaro", new Asesino(), 1); Assert.assertEquals(h2.getSalud(), 105); if (h.atacar(h2, new MyRandomStub(0)) != 0) { Assert.assertTrue(h2.getSalud() < 105); } else { Assert.assertEquals(h2.getSalud(), 105); } } @Test public void testAliar() { Humano h = new Humano("Nicolas", new Guerrero(), 1); Humano h2 = new Humano("Lautaro", new Guerrero(), 1); Alianza a1 = new Alianza("Los CacheFC"); Assert.assertNull(h2.getClan()); Assert.assertNull(h.getClan()); h.setClan(a1); Assert.assertNotNull(h.getClan()); h.aliar(h2); Assert.assertEquals(h.getClan(), h2.getClan()); h.salirDeAlianza(); Assert.assertEquals(h.getClan(), null); LinkedList<Personaje> listap = a1.obtenerAliados(); Assert.assertEquals(listap.size(), 1); Assert.assertEquals(h.aliar(h2), false); } }
package eu.lsem.bakalarka.webfrontend.action.secure.superuser.categories; import eu.lsem.bakalarka.dao.categories.CategoryDao; import eu.lsem.bakalarka.model.Category; import eu.lsem.bakalarka.webfrontend.action.BaseActionBean; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.RedirectResolution; import net.sourceforge.stripes.action.Resolution; import net.sourceforge.stripes.validation.Validate; import net.sourceforge.stripes.validation.SimpleError; import java.util.List; import org.springframework.dao.DataIntegrityViolationException; public abstract class CategoriesBaseActionBean extends BaseActionBean { protected final String LIST_JSP = "/WEB-INF/pages/secure/superuser/categories/categories.jsp"; @Validate(encrypted = true) private Integer id; protected CategoryDao categoryDao; public void setId(Integer id) { this.id = id; } public List<Category> getCategories() { return categoryDao.getCategories(); } @DefaultHandler public Resolution list() { return new ForwardResolution(LIST_JSP); } public Resolution delete() { try { categoryDao.deleteCategory(id); } catch (DataIntegrityViolationException e) { getContext().getValidationErrors().addGlobalError(new SimpleError("Tuto kategorii nelze smazat, protože jsou k ní přiřazeny práce")); return getContext().getSourcePageResolution(); } return new RedirectResolution(this.getClass()); } public abstract Class getFormClass(); protected abstract void setCategoryDao(CategoryDao dao); }
package com.globomantics.test.base; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver;//execute program on VM or remotely import java.net.MalformedURLException; import com.generic.utilities.Logg; import com.generic.utilities.Utilities; public class TestBase { protected static final Logger LOGG = Logg.createLogger(); public static Properties prop; private static final Logger LOGGER = Logg.createLogger(); public static long Page_Load_time = 160; public static long Implicit_wait_time = 200; protected ThreadLocal<WebDriver> driver1 = new ThreadLocal<>(); public WebDriver driver; // public WebDriver driver; public TestBase() { try { File src = new File( System.getProperty("user.dir") + "/src/main/java/com/globomantics/test/config/config.properties");// location FileInputStream fs = new FileInputStream(src); prop = new Properties(); prop.load(fs); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public WebDriver initialization() { String browserName = prop.getProperty("browser"); LOGGER.info(Utilities.getCurrentThreadId() + "Instantiating/Launching the " + browserName + " Browser"); if (browserName.equals("chrome")) { // WebDriverManager.chromedriver().setup(); System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/resources/com/drivers/chromedriver.exe"); driver1.set(new ChromeDriver()); System.setProperty(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, "true"); } else if (browserName.equals("remotechrome")) { System.setProperty(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, "true"); DesiredCapabilities dc = new DesiredCapabilities(); dc.setBrowserName("chrome"); dc.setPlatform(Platform.LINUX); try { driver1.set(new RemoteWebDriver(new URL("http://35.232.146.10:4444/wd/hub"), dc));// http://34.70.254.170:4444 // http://34.77.44.43:4444 //http://35.193.91.97:4444/ } catch (MalformedURLException e) { System.out.println("Link error"); } } driver = driver1.get(); System.out.println("RUNNING TESTS IN REMOTE CHROME BROWSER"); LOGGER.info(Utilities.getCurrentThreadId() + "Maximize Windows of- " + browserName + " Browser"); driver.manage().window().maximize(); LOGGER.info(Utilities.getCurrentThreadId() + "Deleting all cookies- " + browserName + " Browser"); driver.manage().deleteAllCookies(); driver.manage().timeouts().pageLoadTimeout(Page_Load_time, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(Implicit_wait_time, TimeUnit.SECONDS); LOGGER.info(Utilities.getCurrentThreadId() + "Navigationg to " + prop.getProperty("url")); driver.get(prop.getProperty("url")); return driver; } }
package gui; import javafx.fxml.Initializable; import java.net.URL; import java.util.ArrayList; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import negocio.entidade.*; import gui.excecao.ServicoAConcluirNaoEncontradoException; import negocio.fachada.Fachada; public class ControleConcluirServico implements Initializable { private Fachada fachada; public ControleConcluirServico(){ fachada = fachada.getInstance(); } ObservableList<String> veiculosStatusList = FXCollections.observableArrayList(); @FXML private AnchorPane telaConcluirServico; @FXML private Label lb1; @FXML private Label lb2; @FXML private Button selecionar; @FXML private Button concluir; @FXML private ChoiceBox veiculosCbox; @FXML private ChoiceBox servicosCbox; private ArrayList<String> criarListaVeiculos(){ ArrayList<String> listaVeiculos = new ArrayList<String>(); if(fachada.getNegocioVeiculo().getRepositorio().getArray().size() != 0){ for(int i = 0; i < fachada.getNegocioVeiculo().getRepositorio().getArray().size(); i++){ listaVeiculos.add(fachada.getNegocioVeiculo().getRepositorio().getArray().get(i).getPlaca()); } } return listaVeiculos; } private ArrayList<String> criarListaServico(Veiculo veiculo){ ArrayList<String> listaServico = new ArrayList<String>(); if(fachada.getServicosNaoConcluidos(veiculo).size() != 0){ String aux; for(int i = 0; i < fachada.getServicosNaoConcluidos(veiculo).size(); i++){ aux = fachada.getServicosNaoConcluidos(veiculo).get(i).getProduto().getTipo() + "; " + fachada.getServicosNaoConcluidos(veiculo).get(i).getDescricao() + "; " + fachada.getServicosNaoConcluidos(veiculo).get(i).getTipoOperacao(); listaServico.add(aux); } } return listaServico; } @Override public void initialize(URL url, ResourceBundle rs){ if(criarListaVeiculos().size() != 0){ for(int i = 0; i < criarListaVeiculos().size(); i++){ veiculosStatusList.add(criarListaVeiculos().get(i)); } } veiculosCbox.setValue("Veiculos"); veiculosCbox.setItems(veiculosStatusList); } public void registrar(){ try{ ObservableList<String> servicosStatusList = FXCollections.observableArrayList(); veiculosCbox.setVisible(false); lb1.setVisible(false); selecionar.setVisible(false); String placa = (String)veiculosCbox.getSelectionModel().getSelectedItem(); Veiculo veiculo = null; if(fachada.getNegocioVeiculo().getRepositorio().getArray().size() != 0){ veiculo = fachada.getNegocioVeiculo().getRepositorio().procurarVeiculo(placa); } if(fachada.getServicosNaoConcluidos(veiculo).size() != 0){ if(criarListaServico(veiculo).size() != 0){ for(int i = 0; i < criarListaServico(veiculo).size(); i++){ servicosStatusList.add(criarListaServico(veiculo).get(i)); } } servicosCbox.setValue("Servicos"); servicosCbox.setItems(servicosStatusList); } lb2.setVisible(true); servicosCbox.setVisible(true); concluir.setVisible(true); } catch (Exception e){ Alert alerta = new Alert(Alert.AlertType.WARNING); alerta.setTitle("Erro"); alerta.setHeaderText("ERRO"); alerta.setContentText("Veiculo nao escolhido"); alerta.showAndWait(); } } public void concluir() { try { String listaServ[] = new String[3]; String servicos = (String) servicosCbox.getSelectionModel().getSelectedItem(); listaServ = servicos.split("; "); Veiculo veiculo = null; String placa = (String) veiculosCbox.getSelectionModel().getSelectedItem(); if (fachada.getNegocioVeiculo().getRepositorio().getArray().size() != 0) { veiculo = fachada.getNegocioVeiculo().getRepositorio().procurarVeiculo(placa); } if (veiculo != null) { if (fachada.getServicosNaoConcluidos(veiculo).size() != 0) { for (int i = 0; i < fachada.getServicosNaoConcluidos(veiculo).size(); i++) { if (fachada.getServicosNaoConcluidos(veiculo).get(i).getTipoOperacao().equals(listaServ[2]) && fachada.getServicosNaoConcluidos(veiculo).get(i).getDescricao().equals(listaServ[1]) && fachada.getServicosNaoConcluidos(veiculo).get(i).getProduto().getTipo().equals(listaServ[0])) { fachada.concluirServico(veiculo, fachada.getServicosNaoConcluidos(veiculo).get(i)); Alert alerta = new Alert(Alert.AlertType.INFORMATION); alerta.setTitle("Confirmacao"); alerta.setHeaderText("Conclusao efetuada"); alerta.setContentText("Servico foi concluido com sucesso"); alerta.showAndWait(); Stage telaConcluirServico = (Stage) this.telaConcluirServico.getScene().getWindow(); telaConcluirServico.close(); } } } } } catch (ServicoAConcluirNaoEncontradoException e) { Alert alerta = new Alert(Alert.AlertType.WARNING); alerta.setTitle("Erro"); alerta.setHeaderText("ERRO"); alerta.setContentText("Servico nao encontrado"); alerta.showAndWait(); } catch (Exception e){ Alert alerta = new Alert(Alert.AlertType.WARNING); alerta.setTitle("Erro"); alerta.setHeaderText("ERRO"); alerta.setContentText("Dados invalidos"); alerta.showAndWait(); } } }
package com.OovEver.easyCrawle.download; import com.OovEver.easyCrawle.response.Response; import com.OovEver.easyCrawle.scheduler.Scheduler; import com.Oovever.easyHttp.util.HttpUtil; import com.Oovever.esayTool.io.file.FileWriter; import com.sun.deploy.net.HttpUtils; import io.github.biezhi.request.Request; import lombok.extern.slf4j.Slf4j; import org.apache.http.client.methods.HttpRequestBase; import java.io.*; /** * 下载器线程 * @author OovEver * 2018/5/18 22:56 */ @Slf4j public class Downloader implements Runnable { private final Scheduler scheduler; private final com.OovEver.easyCrawle.request.Request request; public Downloader(Scheduler scheduler, com.OovEver.easyCrawle.request.Request request) { this.scheduler = scheduler; this.request = request; } @Override public void run() { log.debug("[{}] 开始请求", request.getUrl()); // 自己的http工具 InputStream crawleRelult = null; Request httpReq = null; if ("get".equalsIgnoreCase(request.getMethod())) { httpReq = Request.get(request.getUrl()); crawleRelult = HttpUtil.get(request.getUrl()).execute().getInputStream(); } if ("post".equalsIgnoreCase(request.getMethod())) { httpReq = Request.post(request.getUrl()); crawleRelult = HttpUtil.post(request.getUrl()).execute().getInputStream(); } // 使用别人的http工具 InputStream result = httpReq.contentType(request.getContentType()).headers(request.getHeaders()) .connectTimeout(request.getSpider().getConfig().getTimeout()) .readTimeout(request.getSpider().getConfig().getTimeout()) .stream(); log.debug("[{}] 下载完毕", request.getUrl()); Response response = new Response(request, result); scheduler.addResponse(response); } }
package com.demo.test.service; import com.demo.test.domain.Student; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.List; import java.util.Optional; /** * @author Jack * @date 2019/05/30 14:36 PM */ public interface UserService { Optional<Student> findById(Long id); Optional<Student> getUser(Long id); List<Student> findAll(); Page<Student> findByName(String name, Pageable pageable); String getMailByName(String names); List<Student> findByNameAndPassword(String name, String password); Page<Student> listByPage(Pageable pageable); void deleteById(Long id); void save(Student student); }
/*An integer has sequential digits if and only if each digit in the number is one more than the previous digit. Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits. Example 1: Input: low = 100, high = 300 Output: [123,234] Example 2: Input: low = 1000, high = 13000 Output: [1234,2345,3456,4567,5678,6789,12345] Constraints: 10 <= low <= high <= 10^9*/ class Solution { public List<Integer> sequentialDigits(int low, int high) { List<Integer> res = new ArrayList<>(); String s = "123456789"; int llength = String.valueOf(low).length(); int hlength = String.valueOf(high).length(); for(int i = llength; i <= hlength; i++) { for(int j = 0; j < 10-i; j++) { int num = Integer.parseInt(s.substring(j, j+i)); if(num >= low && num <= high) res.add(num); } } return res; } }
/* * Copyright 2011 frdfsnlght <frdfsnlght@gmail.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.frdfsnlght.transporter.net; import java.io.ByteArrayOutputStream; import java.security.Key; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * * @author frdfsnlght <frdfsnlght@gmail.com> */ public final class Cipher { /** * used to indicate encryption mode */ public static final int Encrypt = 1; /** * used to indicate decryption mode */ public static final int Decrypt = 2; private static final int None = 0; private static final long randomP1 = 16807; private static final long randomP2 = 0; private static final long randomN = Integer.MAX_VALUE; // The randomSeed value was arbitrarily choosen, but shouldn't be // changed if you ever expect to decrypt something you've already // encrypted before the value was changed! private static long randomSeed = 4587243876L; private static final List<Byte> scramble; static { List<Byte> seed = new ArrayList<Byte>(256); scramble = new ArrayList<Byte>(256); for (int i = 0; i < 256; i++) seed.add((byte)(i + Byte.MIN_VALUE)); while (seed.size() > 0) //scramble.add(seed.remove(random(seed.size()))); scramble.add(seed.remove(0)); } // Use a custom random number generator because we can't rely on the // JRE generator producing the same result given the same seed under // different implementations of the runtime. // I don't think we need a cryptographically strong generator since we're // just randomizing an array of of lookup values. private static int random(int range) { randomSeed = ((randomP1 * randomSeed) + randomP2) % randomN; return (int)(((double)randomSeed / (double)randomN) * (double)range); } private ByteArrayOutputStream buffer; private int padSize; private int mode; private byte[] key; private int keyIndex; private int factor1; private int factor2; /** * Creates a new instance of Cipher. */ public Cipher() { this(0); } /** * Creates a new instance of Cipher with the specified pad size. */ public Cipher(int padSize) { mode = None; setPadSize(padSize); reset(); } /** * Returns the current pad size. * @return the current pad size */ public int getPadSize() { return padSize; } /** * Sets the current pad size. * <p> * The specified pad size must be greater than or equal to 0. * </p> * <p> * If the pad size is zero and you encrypt some data, the resulting cipher * data will be exactly the same length as the input data. This can make * cracking the encryption easier. Setting the pad size to any value * larger than zero will mean the cipher data length will be a multiple * of the pad size and least as long as the pad size. * This makes cracking the encryption a bit more difficult * because of the extra "garbage" in the cipher data and the fact the cracker * now doesn't know the length of the original data. Pad sizes greater than 1 * are recommended and larger values offer more protection (e.g., 1024, 8096, * or even larger). * </p> * @param padSize the new pad size */ public void setPadSize(int padSize) { if (padSize < 0) throw new IllegalArgumentException("padSize must be >= 0"); this.padSize = padSize; } /** * Initializes the cipher in the specified mode with the specified key data. * <p> * The key data is used to de/encrypt the data. The longer and more random * the key is, the better the encryption. To decrypt the data later, you * must use the same key. * </p> * <p> * Usually, the key data is obtained from the * {@link java.security.Key#getEncoded} method. * </p> * @param mode the mode the cipher will be used in * @param key the key data used during de/encryption */ public void init(int mode, byte[] key) { if ((mode != Encrypt) && (mode != Decrypt)) throw new IllegalArgumentException("mode is invalid"); reset(); this.mode = mode; this.key = key; } /** * Initializes the cipher in the specified mode with the specified key. * <p> * This method is the equivalent of: * <pre> * cipher.init(mode, Key.getEncoded()); * </pre> * </p> * @param mode the mode the cipher will be used in * @param key the key used during de/encryption */ public void init(int mode, Key key) { init(mode, key.getEncoded()); } /** * Initializes the cipher for encryption with the specified key data. * @param key the key data used during encryption */ public void initEncrypt(byte[] key) { init(Encrypt, key); } /** * Initializes the cipher for encryption with the specified key. * @param key the key used during encryption */ public void initEncrypt(Key key) { init(Encrypt, key); } /** * Initializes the cipher for decryption with the specified key data. * @param key the key data used during decryption */ public void initDecrypt(byte[] key) { init(Decrypt, key); } /** * Initializes the cipher for decryption with the specified key. * @param key the key used during decryption */ public void initDecrypt(Key key) { init(Decrypt, key); } /** * Resets the cipher, canceling any de/encryption currently in progress. */ public void reset() { buffer = new ByteArrayOutputStream(); keyIndex = 0; factor1 = factor2 = 0; mode = None; } /** * Returns the specified plain text data encrypted with the specified key. * @param key the key data used during encryption * @param plainText the plaintext data to encrypt * @return the encrypted, or cipher text, data */ public byte[] encrypt(byte[] key, byte[] plainText) { init(Encrypt, key); return doFinal(plainText); } /** * Returns the specified cipher text data decrypted with the specified key. * @param key the key data used during decryption * @param cipherText the encrypted data to decrypt * @return the decrypted, or plain text, data */ public byte[] decrypt(byte[] key, byte[] cipherText) { init(Decrypt, key); return doFinal(cipherText); } /** * Updates the cipher stream with a single byte of data. * @param data the byte of data */ public void update(byte data) { if (mode == None) throw new IllegalStateException("encrypt/decrypt mode not set"); int posIn = scramble.indexOf(data); int adj = scramble.indexOf(key[keyIndex++]); if (keyIndex >= key.length) keyIndex = 0; factor1 = factor2 + adj; int posOut; if (mode == Encrypt) posOut = posIn + factor1; else posOut = posIn - factor1; posOut = (posOut % scramble.size()); if (posOut < 0) posOut += scramble.size(); if (mode == Encrypt) factor2 = factor1 + posOut; else factor2 = factor1 + posIn; buffer.write(scramble.get(posOut)); } /** * Updates the cipher stream with an array of data. * @param data an array of data */ public void update(byte[] data) { if (data == null) return; for (byte b : data) update(b); } /** * Updates the cipher stream with a portion of the data in an array. * @param data the array containing the data * @param offset the offset within the array where the data to read is located * @param length the length of the data in the array to read */ public void update(byte[] data, int offset, int length) { if (data == null) return; for (int i = offset; i < (i + length); i++) update(data[i]); } /** * Completes the de/encryption cycle, resets the cipher instance, * and returns the de/encrypted (cipher) data. * @return the de/encrypted (cipher) data */ public byte[] doFinal() { if (mode == None) throw new IllegalStateException("encrypt/decrypt mode not set"); try { if (padSize > 0) { if (mode == Encrypt) { int extraBytes = padSize - ((buffer.size() + 4) % padSize); if (extraBytes == padSize) extraBytes = 0; Random r = new Random(); for (int i = 0; i < extraBytes; i++) update((byte)(r.nextInt(256) + Byte.MIN_VALUE)); update((byte)((extraBytes >> 24) & 0x000000ff)); update((byte)((extraBytes >> 16) & 0x000000ff)); update((byte)((extraBytes >> 8) & 0x000000ff)); update((byte)(extraBytes & 0x000000ff)); return buffer.toByteArray(); } else { byte[] tmp = buffer.toByteArray(); if ((tmp.length % padSize) != 0) { // decryption failed return new byte[0]; } int extraBytes = ((int)tmp[tmp.length - 1] & 0x000000ff) | (((int)tmp[tmp.length - 2] << 8) & 0x0000ff00) | (((int)tmp[tmp.length - 3] << 16) & 0x00ff0000) | (((int)tmp[tmp.length - 4] << 24) & 0xff000000); if ((extraBytes >= padSize) || (extraBytes < 0)) { // something went wrong return new byte[0]; } byte[] data = new byte[tmp.length - 4 - extraBytes]; System.arraycopy(tmp, 0, data, 0, data.length); return data; } } else return buffer.toByteArray(); } finally { reset(); } } /** * Completes the de/encryption cycle, resets the cipher instance, * and returns the de/encrypted (cipher) data. * <p> * This method is the equivalent of: * <pre> * cipher.update(data); * cipher.doFinal(); * </pre> * </p> * @param data the final array of data update the cipher stream with * @return the de/encrypted (cipher) data */ public byte[] doFinal(byte[] data) { update(data); return doFinal(); } }
package org.browsexml.timesheetjob.service; import java.util.List; import org.browsexml.timesheetjob.model.Awards; public interface AwardsManager { public List<Awards> getAwards(); public void save(Awards award, boolean isInsert); public void remove(String code); public Awards getAward(String code); }
package net.sssanma.mc.callbacks; public class SiteParseException extends Exception { private static final long serialVersionUID = 1L; public SiteParseException(String arg0) { super(arg0); } }
package com.xunfang.service; import com.xunfang.pojo.OrderDetail; import com.xunfang.pojo.OrderInfo; import com.xunfang.pojo.Pager; import com.xunfang.pojo.ProductInfo; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; import java.util.List; import java.util.Map; public interface OrderInfoService { // 添加订单 public int saveOrder(OrderInfo orderInfo); // 添加订单详情 public int saveOrderDetail(OrderDetail orderDetail); // 分页 public List<OrderInfo> selectByPage(Pager pager, OrderInfo orderInfo); // 总数 public Integer count(Map<String,Object> params); // 根据订单id 获取 订单明细 public List<OrderDetail> getDetailByOrderId(int oid); // 通过 id 获取 订单信息 public OrderInfo getOrderInfoById(int id); // 删除 订单 和 订单明细 public int delete(String ids); }
package it.test.strutturali; import static org.junit.Assert.*; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; import it.cinema.multisala.Film; import it.cinema.multisala.Recensione; public class FilmTest { Film f; Recensione r; Recensione r_1; LocalTime durata; LocalTime durata_1; LocalDateTime dataUscita; LocalDateTime dataUscita_1; LocalDateTime dataRimozione; LocalDateTime dataRimozione_1; ArrayList<Recensione> recensioni; @Before public void setUp() throws Exception { durata = LocalTime.of(1 , 57); dataUscita = LocalDateTime.of(1982, Month.JUNE, 25, 00, 00, 00); dataRimozione = LocalDateTime.of(1982, Month.SEPTEMBER, 25, 00, 00, 00); f = new Film(1, "Blade Runner", "fatascienza", "Deckard è costretto...", 4.8, 5.50, durata, dataUscita, dataRimozione); r = new Recensione(1, 4, "bello...", "Luigi"); r_1 = new Recensione(2, 2, "brutto...", "Mario"); recensioni = new ArrayList<Recensione>(); recensioni.add(r); recensioni.add(r_1); } @Test public void testFilm() { assertNotNull(f); assertEquals(1, f.getIdFilm()); assertEquals("Blade Runner", f.getTitolo()); assertEquals("fatascienza", f.getGenere()); assertEquals("Deckard è costretto...", f.getTrama()); assertEquals(4.8, f.getVotoMedio(), 0); assertEquals(durata, f.getDurata()); assertEquals(dataUscita, f.getDataUscita()); assertEquals(dataRimozione, f.getDataRimozione()); } @Test public void testGetIdFilm() { f.setIdFilm(2); assertEquals(2, f.getIdFilm()); } @Test public void testGetTitolo() { f.setTitolo("Il padrino"); assertEquals("Il padrino", f.getTitolo()); } @Test public void testGetGenere() { f.setGenere("drammatico"); assertEquals("drammatico", f.getGenere()); } @Test public void testGetTrama() { f.setTrama("New York, 1945. Vito..."); assertEquals("New York, 1945. Vito...", f.getTrama()); } @Test public void testGetVotoMedio() { f.setVotoMedio(4.9); assertEquals(4.9, f.getVotoMedio(), 0); } @Test public void testGetPrezzo() { f.setPrezzo(6.50); assertEquals(6.50, f.getPrezzo(), 0); } @Test public void testGetDurata() { durata_1 = LocalTime.of(2 , 05); f.setDurata(durata_1); assertEquals(durata_1, f.getDurata()); } @Test public void testGetDataUscita() { dataUscita_1 = LocalDateTime.of(1972, Month.SEPTEMBER, 21, 00, 00, 00); f.setDataUscita(dataUscita_1); assertEquals(dataUscita_1, f.getDataUscita()); } @Test public void testOttieniInfoFilm() { String[] info; f.setRecensione(recensioni); info = f.ottieniInfoFilm(); assertNotNull(info); assertEquals("titolo:Blade Runner", info[0]); assertEquals("genere:fatascienza", info[1]); assertEquals("trama:Deckard è costretto...", info[2]); assertEquals("voto medio:4.8", info[3]); assertEquals("prezzo:5.5", info[4]); assertEquals("data uscita:25-06-1982", info[5]); assertEquals("data rimozione:25-09-1982", info[6]); assertEquals("durata:01:57\n", info[7]); assertEquals("username:Luigi", info[8]); assertEquals("commento:bello...", info[9]); assertEquals("voto:4\n", info[10]); assertEquals("username:Mario", info[11]); assertEquals("commento:brutto...", info[12]); assertEquals("voto:2\n", info[13]); } @Test public void testAggiungiRecensione() { Recensione r_2; Recensione r_3; int size = f.getRecensione().size(); r_2 = new Recensione(3, 5, "bellissimo...", "Tony"); r_3 = new Recensione(4, 0, "bellissimo...", "Tony"); f.setVotoMedio(0); //recensione valida viene inserita tra quelle disponibili //viene aggionato anche il voto medio f.aggiungiRecensione(r_2); assertTrue(f.getRecensione().contains(r_2)); assertEquals(size + 1, f.getRecensione().size()); assertEquals(5, f.getVotoMedio(), 0); //recensione non valida non viene inserita tra le disponibili f.aggiungiRecensione(r_3); assertEquals(size + 1, f.getRecensione().size()); } @Test public void testRimuoviRecensione() { f.setVotoMedio(0); f.setRecensione(recensioni); //rimuovo la recensione e ricalcolo voto medio assertTrue(f.rimuoviRecensione(r_1)); assertFalse(f.getRecensione().contains(r_1)); assertEquals(4, f.getVotoMedio(), 0); //impossibile eliminare una recensione non presente assertFalse(f.rimuoviRecensione(r_1)); } @Test public void testPrintInfoFIlm() { f.setRecensione(recensioni); f.printInfoFIlm(); } }
package com.chilkens.timeset.controller; import com.chilkens.timeset.dto.HistoryResponse; import com.chilkens.timeset.domain.Timetable; import com.chilkens.timeset.service.HistoryService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @CrossOrigin(origins = "*") @Api(value = "HistoryFinResponse API", description = "시간 선택 완료된 타임테이블 찾기 API", basePath = "/api/v1/historyFin") @RestController @RequestMapping("/api/v1/historyFin") public class HistoryFinController { @Autowired HistoryService historyService; @ApiOperation(value = "findFinTimetable", notes = "모든사람이 시간 선택을 완료한 타임테이블을 반환해주는 API 입니다. 프런트에서 오는 kakaoId와 Timetable에 createdBy와 비교하여 같은 모든 테이블 중, 시간 선택이 완료된 타임테이블만 반환됩니다.") @RequestMapping(method = RequestMethod.GET) public List<HistoryResponse> findById(@RequestParam String kakaoId) { List<HistoryResponse> historyFin = new ArrayList<>(); List<Timetable> finTimetable = historyService.findFinInTimetable(kakaoId); List<String> pickName = new ArrayList<>(); return historyService.findHistory(finTimetable, pickName, historyFin); } }
package day30WrapperClassArrayList; public class methodsofWrapperclass2 { public static void main(String[] args) { /* useful methods of wrapper class; Max_Value: it returns the maximum value of the primitive Min_Valuereturns: the minimum value of primitive parse methods: converting a String value to Primitives,returns value as primitive, it is not case sensitive ValueOfmethods:used for converting string value to Wrapper class, */ //max_Value: it returns the maximum value of the primitive int maximum=Integer.MAX_VALUE; System.out.println(maximum); double maxidouble=Double.MAX_VALUE; System.out.println(maxidouble); byte maxibyte=Byte.MAX_VALUE; System.out.println(maxibyte); char maxiChar=Character.MAX_VALUE; System.out.println(maxiChar);//returns character //min_value; returns the minimum value of primitive int minimum=Integer.MIN_VALUE; System.out.println(minimum); byte minibyte=Byte.MIN_VALUE; System.out.println(minibyte); //parse Methods: converting a String value to Primitives,returns value as primitive //parseIn("strValue"):takes the string and converts the String to int primitive System.out.println("+++++++++++++++++++++"); Integer num1=Integer.parseInt("123");//auto boxing //wrapper class<====primitive//auto boxing System.out.println(num1); int num2=Integer.parseInt("125");//none //primitive primitive===>none //parseByte("strValue"); takes string and converts string to byte int num3= Byte.parseByte("19");//we can assign byte to int(size) System.out.println(num3+1); //byte num3= Byte.parseByte("198");//gives error out of range Byte num4=Byte.parseByte("19");//auto-boxing System.out.println(num4); //parseShort("StrValur"):takes string value and converts it to short value short snum=Short.parseShort("200");//none System.out.println(snum); Short num6=Short.parseShort("200");//auto-boxing System.out.println(num6+1); // paresLong("strValue"): takes a string value and converts it to a long primitive long num7=Long.parseLong("1222"); System.out.println(num7); int num8=(int)Long.parseLong("1222");//explicit casting System.out.println(num8); //parseFloat("strValue");takes string value and converts it float primitive float num9=Float.parseFloat("12.5"); System.out.println(num9+0.5); Float num10=Float.parseFloat("12.5f");//auto System.out.println(num10); //parseDouble(strValue):takes string value and converts it to double primitive int num11=(int)Double.parseDouble("12.65");//explicit casting System.out.println(num11); double num12=Double.parseDouble("12.65"); System.out.println(num12);//12.65 double num13=Double.parseDouble("12.65");//auto boxing System.out.println(num13); //parseBoolean("strValue");takes a string and converts it to a boolean primitive boolean A=Boolean.parseBoolean("true");//any string value other than True will return false System.out.println(A); boolean B=Boolean.parseBoolean("TRUE");//methods ignores the case sensitivity System.out.println(B); boolean C=Boolean.parseBoolean("10>9"); System.out.println(C);//false //====================================== System.out.println("+++++++++++++++++++++++++"); //we can assign int to bouble primitive int a=10; double b=a; // we can not assign int primitive to other type wrapper class //Double c=a;we can not assign int primitive to other type wrapper class int A1=Byte.parseByte("19"); //Integer A2=Byte.parseByte("19");//gives compile error needs to explicit Integer A2=(int)Byte.parseByte("19");// needs to explicit //exp // Short A3=(byte)Double.parseDouble("10.9"); gives compile error //needs to explicit to short Short A3=(short)Double.parseDouble("10.9"); // int A5=100; //Float A6=A5;//float wrapper class only for float primitive we need to cast iy Float A6=(float)A5; //ValueOf METHODS: used for converting string value to Wrapper class,returns wrapper class values int z=Integer.valueOf("1234");//unboxing Integer z1=Integer.valueOf("1234");//none Integer z2=Integer.valueOf("1234"+1);//auto boxing //(int)Integer.valueOf("1234");//turns wrapper class to primitive value System.out.println(z2+1); // exp boolean result=Boolean.valueOf("TrUe");//unboxing System.out.println(result); //valuOf the methods ignores the case sensitivity boolean result1=!Boolean.valueOf("TrUe");//false //converting other data types to string int totalNumber=100; String str3=""+totalNumber; } }
package lokinsky.dope.plugin.Logic; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.HashMap; public class PDO_MYSQL { private Connection connection; public HashMap<String, PreparedStatement> sql = new HashMap<>(); public PDO_MYSQL() { try{ Class.forName("org.gjt.mm.mysql.Driver").getDeclaredConstructor().newInstance(); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db", "root", ""); //String users = connection.nativeSQL(); initilize_prepared_queries(); System.out.println("Connection succesfull!"); } catch(Exception ex){ System.out.println("Connection failed..."); System.out.println(ex); } } private void initilize_prepared_queries() throws SQLException { sql.put("get_user", connection.prepareStatement("SELECT * FROM Users WHERE name = ?;")); } public String[] executePreparedSql(String name, String args[]) throws SQLException { int argcount = 1; String res[] = new String[args.length-1]; while(sql.get(name).getParameterMetaData().getParameterCount()>argcount) { argcount+=1; sql.get(name).setString(1, args[argcount]); } if(res[0]!=null) { return res; }else { return null; } } }
package com.example.ifpb.validar; import android.app.Activity; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import com.example.ifpb.validar.Listeners.OnClickData; import com.example.ifpb.validar.Listeners.ValidarEndTextWatcher; import com.example.ifpb.validar.Listeners.ValidarNomeTextWatcher; public class MainActivity extends Activity { private EditText nome; private EditText data; private EditText end; private Button enviar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); nome = (EditText) findViewById(R.id.nome); end = (EditText) findViewById(R.id.end); nome.addTextChangedListener(new ValidarNomeTextWatcher(this)); end.addTextChangedListener(new ValidarEndTextWatcher(this)); Button enviar = (Button) findViewById(R.id.enviar); } public void setEnviar(Button enviar){ this.enviar = enviar; } public Button getEnviar(){ return this.enviar; } public void setNome(EditText nome){ this.nome = nome; } public EditText getNome(){ return this.nome; } public void setData(int ano, int mes, int dia){ this.data.setText(dia+"/"+mes+"/"+ano); } public EditText getData(){ return this.data; } public void setEnd(EditText end){ this.end = end; } public EditText getEnd(){ return this.end; } public void setNomeColor (String c){ this.nome.setTextColor(Color.parseColor(c)); } }
package com.mygdx.game; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; public interface IRenderable { void render(SpriteBatch batch); void render(ShapeRenderer shapes); }
package com.tencent.mm.plugin.wallet_payu.remittance.a; import com.tencent.mm.wallet_core.e.a.a; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; public final class d extends a { public String bJg; public String bST; public double mBj; public int pFU; public String toUserName; public d(double d, String str, String str2, int i) { this.mBj = d; this.bJg = str; this.toUserName = str2; this.pFU = i; Map hashMap = new HashMap(); hashMap.put("total_fee", Math.round(100.0d * d)); hashMap.put("fee_type", str); hashMap.put("to_customer_name", str2); hashMap.put("transfer_type", String.valueOf(i)); F(hashMap); } public final int bOo() { return 13; } public final void a(int i, String str, JSONObject jSONObject) { this.bST = jSONObject.optString("PrepayId"); } }
package org.murinrad.android.musicmultiply.networking.qos; import android.util.Log; import org.murinrad.android.musicmultiply.MainActivity; import org.murinrad.android.musicmultiply.datamodel.device.IDevice; import org.murinrad.android.musicmultiply.devices.management.IDeviceManager; import org.murinrad.android.musicmultiply.networking.PacketConstructor; import org.murinrad.android.musicmultiply.tags.Constants; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Set; /** * Created by Radovan Murin on 19.4.2015. */ public class QoSMessageListener implements Runnable, IDeviceManager { private static int QoS_ACTION_INTERVAL = 5000; Thread runner; Set<QosMessageHandler> handlers = new HashSet<>(); HashMap<InetAddress, Integer> delaysAverages = new HashMap<>(); HashMap<InetAddress, Integer> packetLosses = new HashMap<>(); private long lastAction = 0; public QoSMessageListener() { } public void start() { runner = new Thread(this); runner.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { Log.e(MainActivity.APP_TAG, "QoS: Fatal uncaught exception", ex); } }); runner.start(); } public void stop() { runner.interrupt(); } public void addHandler(QosMessageHandler handler) { handlers.add(handler); } public void removeHandler(QosMessageHandler handler) { handlers.remove(handler); } @Override public void run() { DatagramSocket socket = null; try { socket = new DatagramSocket(Constants.QoS_PORT); byte[] buffer = new byte[9]; Log.i(MainActivity.APP_TAG, "QoS:QoSListener active...."); while (!Thread.interrupted()) { DatagramPacket packet = new DatagramPacket(buffer, buffer.length); try { socket.receive(packet); byte datagramType = packet.getData()[0]; Constants.QoS_PACKET_TYPE packetType = Constants.QoS_PACKET_TYPE.getDatagramType(datagramType); switch (packetType) { case PACKET_RESEND_REQUEST: processPacketResendReq(packet); break; case STATISTICS_REPORT: processStatistics(packet); break; } } catch (IOException e) { Log.i(MainActivity.APP_TAG, "QoS:Cannot receive packet"); } } } catch (Exception e) { Log.w(MainActivity.APP_TAG, "QoS:Problem in QoS listener", e); } finally { socket.close(); } Log.i(MainActivity.APP_TAG, "QoS:QoSListener shutdown...."); } private void processPacketResendReq(DatagramPacket packet) { int packetID = PacketConstructor.getPacketID(Arrays.copyOfRange(packet.getData(), 1, 5)); Log.i(MainActivity.APP_TAG, String.format("QoS: Packet resend request received from %s," + " requested packet was: %s", packet.getAddress().getHostAddress(), packetID)); for (QosMessageHandler handler : handlers) { handler.onPacketResentRequest(packet.getAddress(), packetID); } } private void processStatistics(DatagramPacket packet) { int delayAverage = ByteBuffer.wrap(Arrays.copyOfRange(packet.getData(), 1, 5)).getInt(); int packetLoss = ByteBuffer.wrap(Arrays.copyOfRange(packet.getData(), 5, 9)).getInt(); delaysAverages.put(packet.getAddress(), delayAverage); packetLosses.put(packet.getAddress(), packetLoss); Log.i(MainActivity.APP_TAG, String.format("QoS: New QoS report received from %s, " + "average delay: %s,packet loss: %s", packet.getAddress().getHostAddress(), delayAverage, packetLoss)); synchronized (this) { int delaySum = 0; for (int delay : delaysAverages.values()) { delaySum += delay; } int delayAverage1 = (int) Math.round((double) delaySum / delaysAverages.values().size()); if (lastAction == 0 || System.currentTimeMillis() - lastAction > QoS_ACTION_INTERVAL) { Log.i(MainActivity.APP_TAG, "QoS: Invoking handler actions on " + handlers.size() + "objects"); lastAction = System.currentTimeMillis(); for (QosMessageHandler handler : handlers) { // handler.onDelayRequest(delayAverage); } } } } @Override public void addDevice(IDevice dev) { } @Override public synchronized void removeDevice(IDevice dev) { packetLosses.remove(dev.getAddress()); delaysAverages.remove(dev.getAddress()); } @Override public synchronized void removeDevice(String UUID) { } public void reset() { packetLosses.clear(); delaysAverages.clear(); } @Override public synchronized void refreshDevices(IDevice[] devs) { Set<InetAddress> toRemove = packetLosses.keySet(); for (IDevice dev : devs) { toRemove.remove(dev.getAddress()); } for (InetAddress del : toRemove) { packetLosses.remove(del); delaysAverages.remove((del)); } } }
package fi.lassemaatta.temporaljooq.config.jooq; import org.jooq.SQLDialect; import org.jooq.conf.Settings; import org.jooq.impl.DataSourceConnectionProvider; import org.jooq.impl.DefaultConfiguration; import org.jooq.impl.DefaultDSLContext; import org.jooq.impl.DefaultExecuteListenerProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; @Configuration @PropertySource("classpath:configuration/jooq.properties") public class JOOQConfig { @Bean public JOOQToSpringExceptionTransformer jooqToSpringExceptionTransformer() { return new JOOQToSpringExceptionTransformer(); } @Bean public DefaultConfiguration configuration(final DataSourceConnectionProvider connectionProvider, final Environment env, final JOOQToSpringExceptionTransformer jooqToSpringExceptionTransformer) { final DefaultConfiguration jooqConfiguration = new DefaultConfiguration(); jooqConfiguration.set(connectionProvider); jooqConfiguration.set(new DefaultExecuteListenerProvider(jooqToSpringExceptionTransformer)); final Settings settings = jooqConfiguration.settings(); settings.withReturnAllOnUpdatableRecord(true); jooqConfiguration.setSettings(settings); final String sqlDialectName = env.getRequiredProperty("jooq.sql.dialect"); final SQLDialect dialect = SQLDialect.valueOf(sqlDialectName); jooqConfiguration.set(dialect); return jooqConfiguration; } @Bean public DefaultDSLContext dsl(final DefaultConfiguration configuration) { return new DefaultDSLContext(configuration); } }
package resources; import javafx.scene.image.Image; public final class Sprites { public static Image AttackShark = new Image(Sprites.class.getResourceAsStream("shark_attack.png")); public static Image AttackSharkUnderwater = new Image(Sprites.class.getResourceAsStream("shark_attack_underwater.png")); public static Image Shark = new Image(Sprites.class.getResourceAsStream("shark.png")); public static Image UtilityShark = new Image(Sprites.class.getResourceAsStream("shark_utility.png")); public static Image AltAttackShark = new Image(Sprites.class.getResourceAsStream("alt_shark_attack.png")); public static Image AltShark = new Image(Sprites.class.getResourceAsStream("alt_shark.png")); public static Image AltUtilityShark = new Image(Sprites.class.getResourceAsStream("alt_shark_utility.png")); public static Image AttackEagle = new Image(Sprites.class.getResourceAsStream("eagle_attack.png")); public static Image Eagle = new Image(Sprites.class.getResourceAsStream("eagle.png")); public static Image UtilityEagle = new Image(Sprites.class.getResourceAsStream("eagle_utility.png")); public static Image AltAttackEagle = new Image(Sprites.class.getResourceAsStream("alt_eagle_attack.png")); public static Image AltEagle = new Image(Sprites.class.getResourceAsStream("alt_eagle.png")); public static Image AltUtilityEagle = new Image(Sprites.class.getResourceAsStream("alt_eagle_utility.png")); public static Image Terrain = new Image(Sprites.class.getResourceAsStream("terrain.png")); }
package paskaita11; public class Egzotiniai extends Vaisiai { void kasAsEsu() { System.out.println("as esu vaisius"); } }
package MobileAutomationPrerequisite.desktop.step_definitions; import MobileAutomationPrerequisite.desktop.pages.Order_Deliver_Page; import cucumber.api.java.en.And; import cucumber.api.java.en.Then; import org.testng.Assert; import java.io.IOException; public class OrderDeliverSteps { Order_Deliver_Page orderDeliverPage = new Order_Deliver_Page(); @And("I select buy now button") public void iSelectBuyNowButton() { orderDeliverPage.selectBuyNowbutton(); } @And("I select google for signin") public void iSelectGoogleForSignin() { orderDeliverPage.selectGooglebutton(); } @And("I sign by providing buyer google account {string} email and {string} password") public void iSignByProvidingBuyerEmailAndForTheAccount(String emailAddress, String password) { orderDeliverPage.signinWithGoogle(emailAddress,password); } @And("I save the Order Number for {string} order and venture details") public void iSaveTheOrderNumberAndVentureDetails(String orderType) throws IOException { orderDeliverPage.saveTheOrderNumberAndVenture(orderType); } @And("I make the order RTS from seller center for {string} order") public void iMakeTheOrderRTSFromSellerCenterHavingAnAccountEmailAndPassword(String orderType) throws IOException { orderDeliverPage.goToSellerOrderManagement(orderType); } @And("I goto order push tool") public void iGotoOrderPushTool() throws IOException { orderDeliverPage.goToOrderPushTool(); } @And("I sign with my alibaba account {string} ID and {string} password") public void iSignWithMyAlibabaAccountIDAndPasswordPassword(String email, String password) { orderDeliverPage.loginUsingAliBabaAccount(email,password); } @And("I make the order status delivered for {string} order") public void iMakeTheOrderStatusDelivered(String orderType) throws IOException { orderDeliverPage.makeTheOrderDelivered(orderType); } @Then("I verify for the success message for order deliver") public void iVerifyForTheSuccessMessageForOrderDeliver() { Assert.assertTrue(orderDeliverPage.verifyForTheOrderSuccessStatus(),"Order is not successfully delivered!"); } @And("I save the delivered order number for {string} product in mobile automation project") public void iSaveTheDeliveredOrderNumberForProductInMobileAutomationProject(String productType) throws IOException { orderDeliverPage.saveDeliveredOrderedNumber(productType); } @And("I make a checkout for combo product") public void iMakeACheckoutForComboProduct() { orderDeliverPage.addComboToCart(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package algoritmosMemoria; import java.util.ArrayList; import modelo.Proceso; /** * * @author ser */ public class algoritmosMemoria { /*************************************************variables***************************************************/ private ArrayList<Proceso> procesos=new ArrayList<>(); private ArrayList<String> faltante=new ArrayList<>(); private ArrayList<String> memoria=new ArrayList<>(); private ArrayList<String> memoriaV=new ArrayList<>(); private ArrayList<String> tamañoS=new ArrayList<>(); private ArrayList<String> tamañoSV=new ArrayList<>(); private String tipo,tamañoP,tamañoF,tamañoM,tamañoVirtual; /***********************************************fin variable************************************************/ /** * * @param tipo * @param tamañoP //tamaño de frames * @param tamañoS * @param tamañoSV * @param tamañoF * @param tamañoM * @param tamañoVirtual * @param procesos */ public algoritmosMemoria(String tipo,String tamañoP,ArrayList<String> tamañoS,ArrayList<String> tamañoSV,String tamañoF, String tamañoM,String tamañoVirtual,ArrayList<Proceso> procesos) { this.procesos=procesos; this.tipo=tipo; this.tamañoP=tamañoP; this.tamañoS=tamañoS; this.tamañoSV=tamañoSV; this.tamañoF=tamañoF; this.tamañoM=tamañoM; this.tamañoVirtual=tamañoVirtual; crearMemoria(); seleccionAlgoritmo(); } /** * */ private void crearMemoria(){ for(int i=0;i<Integer.parseInt(tamañoM);i++){ memoria.add("Libre"); } for(int i=0;i<Integer.parseInt(tamañoVirtual);i++){ memoriaV.add("Libre"); } } /** * */ private void seleccionAlgoritmo(){ if(tipo.equals("Paginación")){ paginada(); } if(tipo.equals("Dinámica")){ dinamico(); } if(tipo.equals("Fija")){ fija(); } if(tipo.equals("Segmentación")){ segmentacion(); } } /** * */ private ArrayList fragmentacionProceso(Proceso pro){ ArrayList ListaRusltado = new ArrayList(); int tamañoFracmento=pro.getTamañoKB()/Integer.parseInt(tamañoP); int cont=0; for(int i=0;i<tamañoFracmento;i++){ ListaRusltado.add("Pagina-"+i); for(int j=0;j<Integer.parseInt(tamañoP);j++){ ListaRusltado.add("Proceso-"+pro.getNumeroProceso()); cont++; } } if(cont<pro.getTamañoKB()){ ListaRusltado.add("Pagina-"+tamañoFracmento); for(int j=0;j<Integer.parseInt(tamañoP);j++){ if(cont<pro.getTamañoKB()){ ListaRusltado.add("Proceso-"+pro.getNumeroProceso()); cont+=1; }else{ ListaRusltado.add("Libre"); } } } return ListaRusltado; } /** * */ public void paginada(){ // System.out.println("entra"); ArrayList procesosFracmentados=new ArrayList<>(); int CantidadFramesMemory=Integer.parseInt(tamañoM)/Integer.parseInt(tamañoP); int CantidadFramesMemoryV=Integer.parseInt(tamañoVirtual)/Integer.parseInt(tamañoP); int framesOcupados=0; int framesOcupadosV=0; int contPosM=0; int contPosV=0; for(Proceso pro :procesos ){ boolean bandera=true; procesosFracmentados=fragmentacionProceso(pro); framesOcupados+=procesosFracmentados.size(); // System.out.println("ocupados= "+framesOcupados); // System.out.println("disponibles= "+CantidadFramesMemory*Integer.parseInt(tamañoP)); if(framesOcupados<(CantidadFramesMemory*Integer.parseInt(tamañoP))){ bandera=false; pro.setEstado(1); for(int i=0;i<framesOcupados;i++){ memoria.add("Libre"); } for(int x=0;x<procesosFracmentados.size();x++){ memoria.set(contPosM,String.valueOf(procesosFracmentados.get(x))); contPosM+=1; } } else{ framesOcupados-=procesosFracmentados.size()/Integer.parseInt(tamañoP); framesOcupadosV+=procesosFracmentados.size()/Integer.parseInt(tamañoP); if(framesOcupadosV<CantidadFramesMemoryV && bandera){ pro.setEstado(1); for(int i=0;i<framesOcupadosV;i++){ memoriaV.add("Libre"); } for(int x=0;x<procesosFracmentados.size();x++){ memoriaV.set(contPosV,String.valueOf(procesosFracmentados.get(x))); contPosV+=1; } } else{ framesOcupadosV-=procesosFracmentados.size(); } } } } /** * */ public void dinamico(){ int tamaño=0; int tamannoV=0; int contPosM=0; int contPosV=0; for(Proceso pro : procesos){ tamaño+=pro.getTamañoKB(); if(tamaño<=Integer.parseInt(tamañoM)){ pro.setEstado(1); for(int x=0;x<pro.getTamañoKB();x++){ memoria.set(contPosM, "Proceso"+pro.getNumeroProceso()+"-"+x); contPosM+=1; } } else{ tamaño-=pro.getTamañoKB(); tamannoV+=pro.getTamañoKB(); if(tamannoV<=Integer.parseInt(tamañoVirtual)){ pro.setEstado(1); for(int x=0;x<pro.getTamañoKB();x++){ memoriaV.set(contPosV, "Proceso"+pro.getNumeroProceso()+"-"+x); contPosV+=1; } } } } } /** * */ public void fragmentarFija(){ int tamaño=Integer.parseInt(tamañoM)/Integer.parseInt(tamañoF); for(int x=0;x<tamaño;x++){ memoria.add("Libre"); } int posMemoria=0; for(int i=0; i<tamaño;i++){ memoria.set(posMemoria, "bloque"); posMemoria=posMemoria+1; for(int j=1;j<=Integer.parseInt(tamañoF);j++){ posMemoria++; if(posMemoria<memoria.size()){ memoria.set(posMemoria, "Libre"); } } } int tamañoV=Integer.parseInt(tamañoVirtual)/Integer.parseInt(tamañoF); for(int x=0;x<tamaño;x++){ memoriaV.add("Libre"); } int posMemoriaV=0; for(int i=0; i<tamañoV;i++){ // System.out.println(posMemoriaV); if(posMemoriaV<memoriaV.size()){ memoriaV.set(posMemoriaV, "bloque"); posMemoriaV=posMemoriaV+1; } for(int j=1;j<=Integer.parseInt(tamañoF);j++){ posMemoriaV++; if(posMemoriaV<memoriaV.size()){ memoriaV.set(posMemoriaV, "Libre"); } } } } /** * */ public void fija(){ fragmentarFija(); int posMemori=1; int posMemoriV=1; int suma=0; for(Proceso pro: procesos){ boolean bandera=true; int cantidad=0; while(posMemori<memoria.size()){ pro.setEstado(1); if(memoria.get(posMemori).equals("Libre")){ int diferencia=suma-posMemori; if(diferencia<pro.getTamañoKB()){ if(cantidad<pro.getTamañoKB()){ memoria.set(posMemori, "Proceso-"+pro.getNumeroProceso()); posMemori++; cantidad++; bandera=false; } else{ posMemori++; bandera=false; } } else{ posMemori++; memoria.set(posMemori, "Libre"); } } else if(memoria.get(posMemori).equals("bloque")){ if((pro.getTamañoKB()-Integer.parseInt(tamañoF))<0){ pro.setFaltante(0); }else{ pro.setFaltante(pro.getTamañoKB()-Integer.parseInt(tamañoF)); } posMemori++; suma+=Integer.parseInt(tamañoF); break; } } if(!bandera){ if((pro.getTamañoKB()-Integer.parseInt(tamañoF))<0){ pro.setFaltante(0); }else{ pro.setFaltante(pro.getTamañoKB()-Integer.parseInt(tamañoF)); } } while(posMemoriV<memoriaV.size() && bandera){ pro.setEstado(1); if(memoriaV.get(posMemoriV).equals("Libre")){ int diferencia=suma-posMemoriV; if(diferencia<pro.getTamañoKB()){ if(cantidad<pro.getTamañoKB()){ memoriaV.set(posMemoriV, "Proceso-"+pro.getNumeroProceso()); posMemoriV++; cantidad++; } else{ posMemoriV++; } } else{ posMemoriV++; memoriaV.set(posMemoriV, "Libre"); } } else if(memoriaV.get(posMemoriV).equals("bloque")){ if((pro.getTamañoKB()-Integer.parseInt(tamañoF))<0){ pro.setFaltante(0); }else{ pro.setFaltante(pro.getTamañoKB()-Integer.parseInt(tamañoF)); } posMemoriV++; break; } } } } /** * * @param pro * @param pos */ public void ingresarProceso(Proceso pro,int pos){ int inicio=0; pro.setEstado(1); for(int i=0;i<pos;i++){ inicio+=Integer.parseInt(tamañoS.get(i)); } memoria.set(inicio, "Segmento"); for(int i=0;i<pro.getTamañoKB();i++){ memoria.set(inicio+1, "Proceso-"+pro.getNumeroProceso()); inicio++; } }/** * * @param pro * @param pos */ public void ingresarProcesoV(Proceso pro,int pos){ int inicio=0; pro.setEstado(1); for(int i=0;i<pos;i++){ inicio+=Integer.parseInt(tamañoSV.get(i)); } memoriaV.set(inicio, "Segmento"); inicio=inicio+1; for(int i=0;i<=pro.getTamañoKB();i++){ memoriaV.set(inicio, "Proceso-"+pro.getNumeroProceso()); inicio++; } } /** * */ public void segmentacion(){ int tamaño=tamañoS.size(); for(int x=0;x<tamaño;x++){ memoria.add("Libre"); } int tamañoV=tamañoSV.size(); for(int x=0;x<tamañoV;x++){ memoriaV.add("Libre"); } int posMemoria=0; int posMemoriaV=0; for(Proceso pro : procesos){ boolean bandera=true; for(int i=0;i<tamañoS.size();i++){ if(pro.getTamañoKB()<= Integer.parseInt(tamañoS.get(i)) && posMemoria<tamañoS.size()){ ingresarProceso( pro, posMemoria); posMemoria+=1; bandera=false; break; } } for(int i=0;i<tamañoSV.size();i++){ if(pro.getTamañoKB()<= Integer.parseInt(tamañoSV.get(i))&& bandera && posMemoriaV<tamañoSV.size()){ ingresarProcesoV( pro, posMemoriaV); posMemoriaV+=1; break; } } } } public ArrayList<String> getMemoria() { return memoria; } public ArrayList<String> getMemoriaV() { return memoriaV; } public ArrayList<String> getFaltante() { return faltante; } }
package net.minecraft.client.gui.recipebook; public interface IRecipeShownListener { void func_192043_J_(); GuiRecipeBook func_194310_f(); } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\client\gui\recipebook\IRecipeShownListener.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package mobappdev.demo.finalexam.problem4; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.UUID; import mobappdev.demo.finalexam.R; public class ImageDownloaderActivity extends AppCompatActivity { private static final String TAG = "ImgDler"; private ImageView mDisplay; private DownloadImage mDownloadImageTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate called"); setContentView(R.layout.activity_image_downloader); mDisplay = (ImageView)findViewById(R.id.iv_image); mDownloadImageTask = new DownloadImage(); } public void downloadPressed(View view) { String url = "https://camo.derpicdn.net/409146886402e82218b6763062d5c3ddbd250db0?url=http%3A%2F%2Fimg04.deviantart.net%2F360e%2Fi%2F2015%2F300%2F9%2Fd%2Ftemmie_by_ilovegir64-d9elpal.png"; Log.d(TAG, "download initiated"); mDownloadImageTask.execute(url); mDownloadImageTask = new DownloadImage(); } // use this method to scale the image private Bitmap getScaledBitmap(String path) { Point size = new Point(); getWindowManager().getDefaultDisplay().getSize(size); return getScaledBitmap(path, size.x, size.y); } private static Bitmap getScaledBitmap(String path, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; Log.d(TAG, "requested width=" + width + "," + "requested height=" + height); Log.d(TAG, "srcWidth=" + srcWidth + "," + "srcHeight=" + srcHeight); int sampleSize = 1; if(srcHeight > height || srcWidth > width ) { if(srcWidth > srcHeight) { sampleSize = Math.round(srcHeight / height); } else { sampleSize = Math.round(srcWidth / width); } } Log.d(TAG, "sampleSize=" + sampleSize); BitmapFactory.Options scaledOptions = new BitmapFactory.Options(); scaledOptions.inSampleSize = sampleSize; //return BitmapFactory.decodeFile(path, scaledOptions); return BitmapFactory.decodeFile(path); } private class DownloadImage extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String filename = null; Bitmap image = null; try{ URL url = new URL(params[0]); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.connect(); image = BitmapFactory.decodeStream(connection.getInputStream()); } catch(IOException e){ Log.e(TAG, "IOException"); } //Save to file system filename = "IMG_" + UUID.randomUUID().toString() + ".jpg"; File file = new File(getApplicationContext().getFilesDir(), filename); FileOutputStream stream = null; try{ stream = new FileOutputStream(file); image.compress(Bitmap.CompressFormat.PNG, 100, stream); } catch(IOException e){ Log.d(TAG, "IOException"); } finally{ try{ stream.close(); } catch(IOException e){ Log.d(TAG, "IOException"); } } return file.getAbsolutePath(); } @Override protected void onPostExecute(String result){ //update imageview if(result != null) { Bitmap image = getScaledBitmap(result); mDisplay.setImageBitmap(image); } else{ Log.d(TAG, "image download failed"); } } } }
package com.mysql.cj.xdevapi; import java.util.Map; public interface Collection extends DatabaseObject { AddStatement add(Map<String, ?> paramMap); AddStatement add(String... paramVarArgs); AddStatement add(DbDoc paramDbDoc); AddStatement add(DbDoc... paramVarArgs); FindStatement find(); FindStatement find(String paramString); ModifyStatement modify(String paramString); RemoveStatement remove(String paramString); Result createIndex(String paramString, DbDoc paramDbDoc); Result createIndex(String paramString1, String paramString2); void dropIndex(String paramString); long count(); DbDoc newDoc(); Result replaceOne(String paramString, DbDoc paramDbDoc); Result replaceOne(String paramString1, String paramString2); Result addOrReplaceOne(String paramString, DbDoc paramDbDoc); Result addOrReplaceOne(String paramString1, String paramString2); DbDoc getOne(String paramString); Result removeOne(String paramString); } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\xdevapi\Collection.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package anonymous.blindeye.banmanagement; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; public class BMPlayer { private boolean muted; private boolean banned; private boolean frozen; private int warnings; private int mutes; private int bans; private int freezes; private int kicks; private int banTime; public int getBanTime() { return banTime; } public void setBanTime(int bantime) { banTime = bantime; } private String uuid; Player pplayer; BanManagement bm; public void runUpdateQuery(String s) { Connection conn = bm.getDatabaseConnection(); PreparedStatement statement; try { statement = conn.prepareStatement(s); statement.executeUpdate(s); conn.close(); } catch (SQLException e) { bm.sendToConsole(ChatColor.DARK_RED + "Error executing Query!"); bm.sendToConsole(e.getSQLState()); bm.sendToConsole(e.getMessage()); bm.sendToConsole("Error Code: " + e.getErrorCode()); } } public static String getUUIDFromPlayer(Player player) { String uuid = ""; try { URL url = new URL( "https://api.mojang.com/users/profiles/minecraft/" + player.getName()); BufferedReader in = new BufferedReader(new InputStreamReader( url.openStream())); String line; while ((line = in.readLine()) != null) { uuid += line; } in.close(); } catch (MalformedURLException e) { System.out.println("Malformed URL: " + e.getMessage()); } catch (IOException e) { System.out.println("I/O Error: " + e.getMessage()); } uuid = uuid .substring(uuid.indexOf("d\":\"") + 4, uuid.indexOf("\",\"")); String uuid2 = uuid; uuid2 = uuid2.substring(0, 8) + "-" + uuid2.substring(8, 12) + "-" + uuid2.substring(12, 16) + "-" + uuid2.substring(16, 20) + "-" + uuid2.substring(20, uuid2.length()); return uuid2; } public static String getUUIDFromPlayer(String name) { String uuid = ""; try { URL url = new URL( "https://api.mojang.com/users/profiles/minecraft/" + name); BufferedReader in = new BufferedReader(new InputStreamReader( url.openStream())); String line; while ((line = in.readLine()) != null) { uuid += line; } in.close(); } catch (MalformedURLException e) { System.out.println("Malformed URL: " + e.getMessage()); } catch (IOException e) { System.out.println("I/O Error: " + e.getMessage()); } uuid = uuid .substring(uuid.indexOf("d\":\"") + 4, uuid.indexOf("\",\"")); String uuid2 = uuid; uuid2 = uuid2.substring(0, 8) + "-" + uuid2.substring(8, 12) + "-" + uuid2.substring(12, 16) + "-" + uuid2.substring(16, 20) + "-" + uuid2.substring(20, uuid2.length()); return uuid2; } public BMPlayer(UUID uuid, BanManagement b) { this.bm = b; this.pplayer = Bukkit.getPlayer(uuid); Connection conn = bm.getDatabaseConnection(); Statement st = null; ResultSet rs = null; boolean alreadyExists = false; try { st = conn.createStatement(); rs = st.executeQuery("SELECT uuid FROM " + bm.getDatabaseName() + ".banmanagement WHERE uuid = \"" + uuid.toString().replaceAll("-", "") + "\";"); if (rs.next()) { alreadyExists = true; } st.close(); rs.close(); conn.close(); } catch (SQLException e) { bm.sendToConsole(ChatColor.DARK_RED + "Error executing Query!"); bm.sendToConsole(e.getSQLState()); bm.sendToConsole(e.getMessage()); bm.sendToConsole("Error Code: " + e.getErrorCode()); } if (!alreadyExists) { String sql = "INSERT INTO \"" + bm.getDatabaseName() + "\".\"banmanagement\" " + "values (\"" + uuid.toString().replaceAll("-", "") + "\", " + "0, " + "0, " + "0, " + "0, 0, " + "\"false\", " + "\"false\", " + "\"false\", 0" + ");"; runUpdateQuery(sql); } } public BMPlayer(Player player, BanManagement b) { this.bm = b; this.pplayer = player; String uuid = getUUIDFromPlayer(player); Connection conn = bm.getDatabaseConnection(); Statement st = null; ResultSet rs = null; boolean alreadyExists = false; try { st = conn.createStatement(); rs = st.executeQuery("SELECT uuid FROM " + bm.getDatabaseName() + ".banmanagement WHERE uuid = \"" + uuid.replaceAll("-", "") + "\";"); if (rs.next()) { alreadyExists = true; } st.close(); rs.close(); conn.close(); } catch (SQLException e) { bm.sendToConsole(ChatColor.DARK_RED + "Error executing Query!"); bm.sendToConsole(e.getSQLState()); bm.sendToConsole(e.getMessage()); bm.sendToConsole("Error Code: " + e.getErrorCode()); } if (!alreadyExists) { String sql = "INSERT INTO " + bm.getDatabaseName() + ".banmanagement " + "values (\"" + uuid.replaceAll("-", "") + "\", " + "0, " + "0, " + "0, " + "0, 0, " + "\"false\", " + "\"false\", " + "\"false\", 0" + ");"; runUpdateQuery(sql); } } public BMPlayer(String name, BanManagement b) { this.bm = b; this.pplayer = Bukkit.getPlayer(name); String uuid = getUUIDFromPlayer(name); Connection conn = bm.getDatabaseConnection(); Statement st = null; ResultSet rs = null; boolean alreadyExists = false; try { st = conn.createStatement(); rs = st.executeQuery("SELECT uuid FROM " + bm.getDatabaseName() + ".banmanagement WHERE uuid = \"" + uuid.replaceAll("-", "") + "\";"); if (rs.next()) { alreadyExists = true; } st.close(); rs.close(); conn.close(); } catch (SQLException e) { bm.sendToConsole(ChatColor.DARK_RED + "Error executing Query!"); bm.sendToConsole(e.getSQLState()); bm.sendToConsole(e.getMessage()); bm.sendToConsole("Error Code: " + e.getErrorCode()); } if (!alreadyExists) { String sql = "INSERT INTO " + bm.getDatabaseName() + ".banmanagement " + "values (\"" + uuid.replaceAll("-", "") + "\", " + "0, " + "0, " + "0, " + "0, 0, " + "\"false\", " + "\"false\", " + "\"false\", 0" + ");"; runUpdateQuery(sql); } } public String getUUIDAsString() { return uuid; } public int getKicks() { return kicks; } public void addKick(int i) { // runUpdateQuery(""); kicks += i; } public void addKick() { addKick(1); } public void kick(String reason) { pplayer.kickPlayer(reason); addKick(); } public void removeKick(int i) { if (kicks >= i) { kicks -= i; } } public void removeKick() { removeKick(1); } public void addFreeze(int i) { freezes += i; } public void addFreeze() { addFreeze(1); } public void removeFreeze(int i) { if (freezes >= i) { freezes -= i; } } public void removeFreeze() { removeFreeze(1); } public void addBan(int i) { bans += i; } public void addBan() { addBan(1); } public void removeBan(int i) { if (bans >= i) { bans -= i; } } public void removeBan() { removeBan(1); } public void addMute(int i) { mutes += i; } public void addMute() { addMute(1); } public void removeMute(int i) { if (mutes >= i) { mutes -= i; } } public void removeMute() { removeMute(1); } public int getMutes() { return mutes; } public int getBans() { return bans; } public int getFreezes() { return freezes; } public void setMuted(boolean mute) { if (mute) { addMute(); } else { removeMute(); } muted = mute; } public boolean isMuted() { return muted; } public void setBanned(boolean ban) { if (ban) { addBan(); } else { removeBan(); } banned = ban; } public boolean isBanned() { return banned; } public void setFrozen(boolean freeze) { if (freeze) { addFreeze(); } else { removeFreeze(); } frozen = freeze; } public boolean isFrozen() { return frozen; } public void addWarning(int i) { warnings += i; } public void addWarning() { addWarning(1); } public void removeWarning() { removeWarning(1); } public void removeWarning(int i) { if (warnings >= i) { warnings -= i; } } public int getWarnings() { return warnings; } }
package be.axxes.bookrental.config; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; public class MyCorsFilter extends CorsFilter { public MyCorsFilter() { super(createCconfiguration()); } private static CorsConfigurationSource createCconfiguration() { CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("http://domain1.com"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; } } //public class CorsConfig extends WebMvcConfigurerAdapter { // @Override // public void addCorsMappings(CorsRegistry corsRegistry) { // corsRegistry.addMapping("/**").allowedOrigins("*"); // } //}
package com.projet3.library_webapp.library_webapp_model.book; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Classe Java pour dateResponse complex type. * * <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe. * * <pre> * &lt;complexType name="dateResponse"> * &lt;complexContent> * &lt;extension base="{http://library_webservice_service.library_webservice.projet3.com/}genericResponse"> * &lt;sequence> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "dateResponse") public class DateResponse extends GenericResponse { }
package org.mitre.hapifhir.utils; import java.util.Date; import java.util.List; import java.util.UUID; import org.hl7.fhir.r4.model.BaseReference; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent; import org.hl7.fhir.r4.model.Bundle.BundleType; import org.hl7.fhir.r4.model.CanonicalType; import org.hl7.fhir.r4.model.CodeType; import org.hl7.fhir.r4.model.Meta; import org.hl7.fhir.r4.model.Parameters; import org.hl7.fhir.r4.model.Reference; import org.hl7.fhir.r4.model.Resource; import org.hl7.fhir.r4.model.Subscription; import org.mitre.hapifhir.model.SubscriptionTopic.NotificationType; public class CreateNotification { /** * Create an R5 Backport Notification. * * @param subscription - the subscription to notify * @param resources - list of resources to include (empty or null for empty notification) * @param baseUrl - the server base url * @param topicUrl - the canonical url of the topic * @param notificationType - R5 Subscription Notification Type Value Set * @return the notification Bundle */ public static Bundle createResourceNotification(Subscription subscription, List<Resource> resources, String baseUrl, String topicUrl, NotificationType notificationType) { Meta meta = new Meta(); meta.addProfile("http://hl7.org/fhir/uv/subscriptions-backport/StructureDefinition/backport-subscription-notification"); String subscriptionFullUrl = baseUrl + "/Subscription/" + subscription.getIdElement().getIdPart(); Parameters parameters = new Parameters(); String parametersId = UUID.randomUUID().toString(); parameters.setId(parametersId); BaseReference subscriptionReference = new Reference(subscriptionFullUrl); parameters.addParameter("subscription", subscriptionReference); parameters.addParameter("topic", new CanonicalType(topicUrl)); parameters.addParameter("status", new CodeType(subscription.getStatus().toCode())); parameters.addParameter("type", notificationType.toCoding().getCodeElement()); BundleEntryComponent subscriptionStatusComponent = new BundleEntryComponent(); subscriptionStatusComponent.setResource(parameters); subscriptionStatusComponent.setFullUrl("urn:uuid:" + parametersId); Bundle notificationBundle = new Bundle(); notificationBundle.setType(BundleType.HISTORY); notificationBundle.setMeta(meta); notificationBundle.setTimestamp(new Date()); notificationBundle.addEntry(subscriptionStatusComponent); // TODO: support id-only notifications if (resources != null && !resources.isEmpty()) { for (Resource r : resources) { BundleEntryComponent bec = new BundleEntryComponent(); bec.setResource(r); bec.setFullUrl(baseUrl + "/" + r.fhirType() + "/" + r.getId()); notificationBundle.addEntry(bec); } } return notificationBundle; } }
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.rack; import com.google.common.io.ByteStreams; import com.squareup.rack.io.ByteArrayBuffer; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; /** * <p>Adapts an {@link InputStream} to the required interface for {@code rack.input}.</p> * * <p>Speaks {@code byte[]}, not {@code String}, because {@code rack.input} is required to have * binary encoding.</p> */ public class RackInput implements Closeable { private static final int LINEFEED = 0xA; private static final int MAX_LINE_LENGTH = 1024 * 1024; private static final int READ_AHEAD_SUGGESTION = 1024 * 1024; private final InputStream stream; private final ByteArrayBuffer buffer = new ByteArrayBuffer(); private int bufferReadHead; /** * Creates a {@link RackInput} stream that draws from the given {@link InputStream}. * * @param inputStream the source stream. */ public RackInput(InputStream inputStream) { checkNotNull(inputStream); checkArgument(inputStream.markSupported(), "rack.input must be rewindable, but inputStream doesn't support mark."); stream = inputStream; stream.mark(READ_AHEAD_SUGGESTION); } /** * Reads the next line from the stream. * * @return the next line, or null at EOF. * @throws IOException */ public byte[] gets() throws IOException { return readToLinefeed(); } /** * Reads length bytes from the stream. Reads all the way to EOF when length is null. * * @param length the desired number of bytes, or null. * @return the bytes, or null at EOF when length is present. * @throws IOException */ public byte[] read(Integer length) throws IOException { if (length == null) { return readToEof(); } else { return readTo(length); } } /** * Resets the stream, so that it may be read again from the beginning. * * @throws IOException */ public void rewind() throws IOException { stream.reset(); buffer.reset(); bufferReadHead = 0; } /** * Closes the stream. * * @throws IOException */ @Override public void close() throws IOException { stream.close(); } private byte[] readToLinefeed() throws IOException { int startFrom = 0; do { int indexOfNewline = indexOfNextNewlineInBuffer(startFrom); if (indexOfNewline == -1) { int bytesPresent = bytesAvailableInBuffer(); if (bytesPresent > MAX_LINE_LENGTH) { throw new RuntimeException( "Really, you have a line longer than " + MAX_LINE_LENGTH + " bytes?"); } // next time through, start where we left off. startFrom = bytesPresent; int bytesRead = fillBuffer(8 * 1024); if (bytesRead == -1) { int bytesRemaining = bytesAvailableInBuffer(); return consumeBytesFromBuffer(bytesRemaining); } } else { int length = indexOfNewline - bufferReadHead + 1; return consumeBytesFromBuffer(length); } } while (true); } private byte[] readToEof() throws IOException { if (bufferReadHead > 0) { compactBuffer(true); } ByteStreams.copy(stream, buffer); int length = buffer.getLength(); if (length == 0) { return new byte[0]; } else { return consumeBytesFromBuffer(length); } } private byte[] readTo(int length) throws IOException { if (length == 0) { return new byte[0]; } if (bufferReadHead > 0) { compactBuffer(true); } int bytesStillNeeded = length - buffer.getLength(); if (bytesStillNeeded > 0) { fillBuffer(bytesStillNeeded); } return consumeBytesFromBuffer(length); } private int bytesAvailableInBuffer() { return buffer.getLength() - bufferReadHead; } private int indexOfNextNewlineInBuffer(int startFrom) { byte[] bytes = buffer.getBuffer(); int bufferLength = buffer.getLength(); for (int i = bufferReadHead + startFrom; i < bufferLength; i++) { if (bytes[i] == LINEFEED) { return i; } } return -1; } private int fillBuffer(int length) throws IOException { compactBuffer(false); byte[] readBuf = new byte[length]; int bytesRead = stream.read(readBuf); if (bytesRead > 0) { buffer.write(readBuf, 0, bytesRead); } return bytesRead; } private byte[] consumeBytesFromBuffer(int length) { int bytesAvailable = bytesAvailableInBuffer(); if (length > bytesAvailable) { length = bytesAvailable; } if (length == 0) { return null; } byte[] bytes = new byte[length]; byte[] bufferBytes = buffer.getBuffer(); System.arraycopy(bufferBytes, bufferReadHead, bytes, 0, length); bufferReadHead += length; return bytes; } private void compactBuffer(boolean force) { byte[] bufferBytes = buffer.getBuffer(); // normally, only compact if we're at least 1K in, and at least 3/4 of the way in if (force || (bufferReadHead > 1024 && bufferReadHead > (bufferBytes.length * 3 / 4))) { int remainingBytes = bytesAvailableInBuffer(); System.arraycopy(bufferBytes, bufferReadHead, bufferBytes, 0, remainingBytes); buffer.setLength(remainingBytes); bufferReadHead = 0; } } }
package it.polimi.se2019.model.server; import it.polimi.se2019.rmi.ServerLobbyInterface; import it.polimi.se2019.rmi.UserTimeoutException; import it.polimi.se2019.rmi.ViewFacadeInterfaceRMIClient; import it.polimi.se2019.model.map.UnknownMapTypeException; import it.polimi.se2019.view.player.PlayerViewOnServer; import java.io.Serializable; import java.net.InetAddress; import java.net.UnknownHostException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.server.ServerNotActiveException; import java.rmi.server.UnicastRemoteObject; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import static java.rmi.server.RemoteServer.getClientHost; /** * @author Fabio Mauri */ public class Server implements ServerLobbyInterface, Serializable { /** * Namespace this class logs to */ private static final String LOG_NAMESPACE = "Server"; /** * Contains the list of all lobbies active */ private transient List<ServerLobby> lobbyes = new LinkedList<>(); /** * Contains the mapping between an user id and a lobby an user should be * registered to */ private ConcurrentHashMap<String, ServerLobby> userLobbyMap = new ConcurrentHashMap<>(); /** * Timeout (in seconds) before starting games in ServerLobby */ private int lobbyTimeout; /** * Timeout (in seconds) before disconnecting an user */ private int disconnectionTimeout; /** * Creates a new Server * * @param host Hostname the registry is located to * @param lobbyTimeout Timeout (in seconds) before starting a game * @param disconnectionTimeout Timeout (in seconds) before starting a game * @throws RemoteException if there is an error in the RMI connection * @throws UnknownHostException if the hostname cannot be resolved */ public Server(String host, int lobbyTimeout, int disconnectionTimeout) throws RemoteException, UnknownHostException { System.setProperty( "java.rmi.server.hostname", InetAddress.getByName(host).getHostAddress() ); LocateRegistry.createRegistry(1099).rebind("server", UnicastRemoteObject.exportObject(this, 0) ); this.lobbyTimeout = lobbyTimeout; this.disconnectionTimeout = disconnectionTimeout; if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } } /** * Make the connection to the server * The server will lookup for an RMI registry on the ip the * client used to connect (see {@link #getIp()}), on the port * passed as parameter, at the reference passed as parameter. * * @param ref The reference the server should use to retrieve a view to * interact with. * @param port Port the registry is exposed on * * @throws RemoteException If something goes wrong with RMI */ @Override public void connect(String ref, int port) throws RemoteException { System.out.println("connect"); try { ViewFacadeInterfaceRMIClient userView = (ViewFacadeInterfaceRMIClient) LocateRegistry .getRegistry(getClientHost(),port) .lookup(ref); System.out.println("registering out"); this.registerPlayer(userView); } catch (ServerNotActiveException | NotBoundException | UserTimeoutException e){ Logger.getLogger(LOG_NAMESPACE).log( Level.WARNING, "Unable to initialize user", e ); } } /** * @return The ip (viewed by the server) of the connecting client. This * can then be used to properly create an RMI Registry. * Null if for some reason the ip can not retrieved * * @throws RemoteException If something goes wrong with RMI */ @Override public String getIp() throws RemoteException { try { return getClientHost(); } catch (ServerNotActiveException e){ Logger.getLogger(LOG_NAMESPACE).log( Level.WARNING, "The server is not active", e ); return null; } } /** * Register a new player to the server. * * If an open lobby is available, it is added to that lobby. * If there are no lobbies availables, a new lobby is created and the player * is added to the newly created lobby * * @param v VirtualView of the player to add to the lobby * * @throws UserTimeoutException if the user doesn't answer on time to a server * request. * If this exception is raised, the player is * not added to the lobby * @throws RemoteException If something goes wrong with RMI */ private void registerPlayer(ViewFacadeInterfaceRMIClient v) throws UserTimeoutException, RemoteException { System.out.println("Starting Registering"); if ( this.userLobbyMap.containsKey(v.getName()) && this.userLobbyMap.get(v.getName()).isGameRunning() ){ // Reconnecting user PlayerViewOnServer.registerPlayer(v.getName(), v); } else { // Creating a new user PlayerViewOnServer p = new PlayerViewOnServer(v, this.disconnectionTimeout); if (!this.lobbyes.isEmpty()){ this.userLobbyMap.put(v.getName(), this.lobbyes.get(0)); } while ( (this.lobbyes.isEmpty()) || !(this.lobbyes.get(0).addPlayer(p, p.getName(), p.getCharacter())) ) { Integer selectedMap = 0; try { selectedMap = p.chooseMap(); this.lobbyes.add(new ServerLobby(selectedMap, this.lobbyTimeout)); this.userLobbyMap.put(v.getName(), this.lobbyes.get(0)); } catch (UnknownMapTypeException e){ Logger.getLogger(LOG_NAMESPACE).log( Level.INFO, "User choose an unknown map type <{0}>", selectedMap ); } } } } }
package com.designpattern.behaviorpattern.strategy; import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer; public class ConcreteStrategyA extends Strategy { @Override void solveProblem(MyProblem problem) { System.out.println("通过A算法解决问题"+problem); } }
package demo.access.modifieres.mypack2; import demo.access.modifieres.mypack1.Student; public class PreKgStudent extends Student { public PreKgStudent() { super(); } }
package tw.org.iii.java; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; public class Brad52 extends JFrame { public Brad52() { MyMouseAdapter adapter = new MyMouseAdapter(); addMouseListener(adapter); addMouseMotionListener(adapter); setSize(640, 480); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } private class MyMouseAdapter extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { System.out.println("Click"); } @Override public void mouseMoved(MouseEvent e) { System.out.println("Move:" + e.getX() + ", " + e.getY()); } } public static void main(String[] args) { new Brad52(); } }
package com.travelportal.vm; import com.travelportal.domain.Currency; public class CurrencyExchangeVM { public Integer currencySelect; public Double curr_THB; public Double curr_SGD; public Double curr_MYR; public Double curr_INR; public Integer getCurrencySelect() { return currencySelect; } public void setCurrencySelect(Integer currencySelect) { this.currencySelect = currencySelect; } public Double getCurr_THB() { return curr_THB; } public void setCurr_THB(Double curr_THB) { this.curr_THB = curr_THB; } public Double getCurr_SGD() { return curr_SGD; } public void setCurr_SGD(Double curr_SGD) { this.curr_SGD = curr_SGD; } public Double getCurr_MYR() { return curr_MYR; } public void setCurr_MYR(Double curr_MYR) { this.curr_MYR = curr_MYR; } public Double getCurr_INR() { return curr_INR; } public void setCurr_INR(Double curr_INR) { this.curr_INR = curr_INR; } }
package com.tencent.mm.vending.base; final class Vending$i<_Struct, _Index> { byte[] dol = new byte[0]; boolean dsz = false; boolean gu = false; boolean uPP = false; _Index uQp; _Struct uQq; boolean uQr = false; boolean uQs = false; Vending$i() { } }
package com.linkan.githubtrendingrepos.base; public interface RetryNavigator { void onRetryClick(); }
package com.example.razor.huskid.adapter; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.razor.huskid.R; import com.example.razor.huskid.entity.Tile; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class TileAdapter extends ArrayAdapter<Tile> { private Context context; private ArrayList<Tile> tiles; public TileAdapter(@NonNull Context context, @NonNull ArrayList<Tile> objects) { super(context, R.layout.tile, objects); this.context = context; this.tiles = objects; } @Override public int getCount() { return super.getCount(); } @Nullable @Override public Tile getItem(int position) { return super.getItem(position); } @SuppressLint("SetTextI18n") @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.tile, parent, false); viewHolder = new ViewHolder(convertView); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } Tile tile = tiles.get(position); if (tile != null) { if (tile.getHorizontalNumber() > 0) { viewHolder.horizontalNumber.setText(Integer.toString(tile.getHorizontalNumber())); } if (tile.getVerticalNumber() > 0) { viewHolder.verticalNumber.setText(Integer.toString(tile.getVerticalNumber())); } if (tile.getVerticalNumber() > 0 && tile.getHorizontalNumber() > 0) { viewHolder.character.setBackgroundColor(Color.RED); } else if (tile.getHorizontalNumber() > 0 || tile.getVerticalNumber() > 0) { viewHolder.character.setBackgroundColor(Color.YELLOW); } else { viewHolder.character.setBackgroundColor(Color.GRAY); } if (tile.isSelected()) { viewHolder.character.setBackgroundColor(Color.CYAN); } if (tile.isShow()) { viewHolder.character.setText(tile.getCharacter().toString()); viewHolder.character.setBackgroundColor(Color.GREEN); } } return convertView; } static class ViewHolder { @BindView(R.id.character) TextView character; @BindView(R.id.horizontalNumber) TextView horizontalNumber; @BindView(R.id.verticalNumber) TextView verticalNumber; ViewHolder(View view) { ButterKnife.bind(this, view); } } }
package chat.signa.net.pingfang.logging.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; import chat.signa.net.pingfang.logging.R; import chat.signa.net.pingfang.logging.entity.LogInfo; /** * Created by Administrator on 2016/1/28. */ public class LogAdapter extends BaseAdapter { private List<LogInfo> lt; private Context context; public LogAdapter(List<LogInfo> lt, Context context) { this.lt = lt; this.context = context; } @Override public int getCount() { return lt.size(); } @Override public Object getItem(int i) { return lt.get(i); } @Override public long getItemId(int i) { return i; } static class ViewHolder{ private static TextView id,project,start,stop,message,remark; } @Override public View getView(int i, View view, ViewGroup viewGroup) { ViewHolder holder; LogInfo log=lt.get(i); if(view==null){ holder=new ViewHolder(); view= LayoutInflater.from(context).inflate(R.layout.item_layout,null); holder.id=(TextView)view.findViewById(R.id.logid); holder.project=(TextView)view.findViewById(R.id.logproject); holder.start=(TextView)view.findViewById(R.id.startime); holder.stop=(TextView)view.findViewById(R.id.stoptime); holder.message=(TextView)view.findViewById(R.id.logmessage); holder.remark=(TextView)view.findViewById(R.id.logremark); view.setTag(holder); }else{ holder=(ViewHolder)view.getTag(); } holder.id.setText(log.getId()); holder.project.setText(log.getProject()); holder.start.setText(log.getStartTime()); holder.stop.setText(log.getStopTime()); holder.message.setText(log.getLogMessage()); holder.remark.setText(log.getRemark()); return view; } }
package br.com.alura.java.io.teste; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; import br.com.bytebank.banco.modelo.Conta; import br.com.bytebank.banco.modelo.ContaCorrente; import br.com.bytebank.banco.modelo.ContaPoupanca; public class TesteInputEOutputStream{ public static void main(String[] args) throws Exception { InputStream entrada = new FileInputStream("Saldos.txt"); Reader isr = new InputStreamReader(entrada); BufferedReader br = new BufferedReader(isr); String linha = br.readLine(); List<Conta> listaConta = new ArrayList<>(); while (linha != null) { String[] coluna = linha.split(";"); int tipo = Integer.parseInt(coluna[8]); int agencia = Integer.parseInt(coluna[0]); int numero = Integer.parseInt(coluna[1]); double valorDeposito = Double.parseDouble(coluna[4]); Conta conta; if (tipo == 1) { conta = new ContaCorrente(agencia, numero); } else { conta = new ContaPoupanca(agencia, numero); } conta.deposita(valorDeposito); String[] nomeAbreviado = coluna[2].split(" "); conta.getTitular().setNome(nomeAbreviado[0]); listaConta.add(conta); linha = br.readLine(); } br.close(); listaConta.sort((c1, c2) -> c1.getTitular().getNome().compareToIgnoreCase(c2.getTitular().getNome())); OutputStream saida = new FileOutputStream("Saldos_Ordenado.txt"); Writer osw = new OutputStreamWriter(saida); BufferedWriter bw = new BufferedWriter(osw); bw.write("Relatório de Saldos Processados"); bw.newLine(); bw.write("--------------------------------------------------------"); for (Conta conta : listaConta) { bw.newLine(); String saldo = NumberFormat.getCurrencyInstance(new Locale("pt", "BR")).format(conta.getSaldo()); String nome = String.format("%-10s", conta.getTitular().getNome()); String texto = "Nome: " + nome + ", " + conta + ", Saldo: " + saldo; bw.write(texto); } bw.close(); } }
package jp.satoshun.chreco.feed.service; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndEntry; import jp.satoshun.chreco.libs.Logger; import jp.satoshun.chreco.service.IFeedObserver; import java.util.List; public class FeedServiceComponent { private IFeedRetrieverService feedRetrieverService; private List<String> feedUrlList; public FeedServiceComponent(final Activity context, List<String> feedUrlList) { bindService(context); this.feedUrlList = feedUrlList; } private ServiceConnection feedRetrieverConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { Logger.e(); feedRetrieverService = IFeedRetrieverService.Stub.asInterface(service); retriveSyndEntryList(feedUrlList); } @Override public void onServiceDisconnected(ComponentName name) { Logger.e(); feedRetrieverService = null; } }; public void bindService(final Activity context) { boolean result = context.bindService(new Intent(context, FeedRetrieverService.class), feedRetrieverConnection, Context.BIND_AUTO_CREATE); Logger.e(String.valueOf(result)); } public void unBindService(Activity context) { if (feedRetrieverService != null) { context.unbindService(feedRetrieverConnection); } } public void retriveSyndEntryList(List<String> feedUrlList) { try { if (feedRetrieverService != null) { Logger.e(); feedRetrieverService.retriveSyndEntryList(feedUrlList); } } catch (RemoteException e) { e.printStackTrace(); } } public List<SyndEntry> getEntryList() { return FeedRetrieverService.getEntryList(); } }
package de.jmda.app.uml.sampletypes; public interface InterfaceMiddle extends InterfaceTop1, InterfaceTop2 { }
package common.parser.implementations.map; import include.learning.perceptron.PackedScoreMap; @SuppressWarnings("serial") public final class IntMap extends PackedScoreMap<Integer> { public IntMap(String input_name, int table_size) { super(input_name, table_size); } @Override public Integer loadKeyFromString(String str) { return Integer.valueOf(str); } @Override public String generateStringFromKey(Integer key) { return key.toString(); } @Override public Integer allocate_key(Integer key) { return key; } }
/* * fra2015 * https://github.com/geosolutions-it/fra2015 * Copyright (C) 2007-2013 GeoSolutions S.A.S. * http://www.geo-solutions.it * * GPLv3 + Classpath exception * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package it.geosolutions.fra2015.mvc.controller.utils; import static it.geosolutions.fra2015.mvc.controller.utils.ControllerServices.FEEDBACK; import static it.geosolutions.fra2015.mvc.controller.utils.ControllerServices.SESSION_USER; import static it.geosolutions.fra2015.mvc.controller.utils.ControllerServices.SURVEY_INSTANCES; import it.geosolutions.fra2015.mvc.controller.utils.ControllerServices.Profile; import it.geosolutions.fra2015.server.model.survey.Entry; import it.geosolutions.fra2015.server.model.survey.Feedback; import it.geosolutions.fra2015.server.model.survey.Status; import it.geosolutions.fra2015.server.model.survey.SurveyInstance; import it.geosolutions.fra2015.server.model.user.User; import it.geosolutions.fra2015.services.FeedbackService; import it.geosolutions.fra2015.services.exception.BadRequestServiceEx; import it.geosolutions.fra2015.services.exception.NotFoundServiceEx; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Enumeration; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TimeZone; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.collections.list.UnmodifiableList; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.CharUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.jsoup.Jsoup; import org.springframework.beans.BeanUtils; import org.springframework.ui.Model; /** * Hold the feedback management: take as input the req and session objects, build a Feedback Instance and add to a feedback list * * @author DamianoG * @author Tobia Di Pisa at tobia.dipisa@geo-solutions.it * */ public class FeedbackHandler{ private static final Logger LOGGER = Logger.getLogger(FeedbackHandler.class); private static final String NO_COMMENT = "NO COMMENT PROVIDED..."; private ControllerServices controllerServiceUtils; private FeedbackService feedbackService; private List<Feedback> feedbackList; private List<Feedback> feedbackListToRemove; public FeedbackHandler(ControllerServices controllerServiceUtils, FeedbackService feedbackService){ this.controllerServiceUtils = controllerServiceUtils; this.feedbackService = feedbackService; this.feedbackList = new ArrayList<Feedback>(); this.feedbackListToRemove = new ArrayList<Feedback>(); } /** * @param country * @param question * @param session * @param su * @param harmonized * @return List<Feedback> * @throws BadRequestServiceEx * @throws NotFoundServiceEx */ public List<Feedback> retrieveFeedbacks(String country, Long question, HttpSession session, User su, Boolean harmonized) throws BadRequestServiceEx, NotFoundServiceEx { Map<String, SurveyInstance> surveyInstanceMap = (Map<String, SurveyInstance>) session .getAttribute(SURVEY_INSTANCES); SurveyInstance si = surveyInstanceMap.get(country); List<Feedback> feedbackList = null; List<Feedback> harmonizedFeedbackList = null; try { feedbackList = feedbackService.loadFeedback(su, si, question); harmonizedFeedbackList = feedbackService.loadHarmonizedfeedbacks(si, question); } catch (BadRequestServiceEx e) { throw new BadRequestServiceEx("Errors loading feedbacks..."); } feedbackList.addAll(harmonizedFeedbackList); return feedbackList; } /** * @param entry * @param si * @param user * @return Feedback */ private Feedback buildUnrevisionedFeedback(Entry entry, SurveyInstance si, User user){ Feedback feedback = new Feedback(); feedback.setEntry(entry); feedback.setFeedback(""); feedback.setFeedbackId(entry.getVariable()); feedback.setHarmonized(false); feedback.setStatus("notrevisioned"); feedback.setSurvey(si); feedback.setTimestamp(System.currentTimeMillis()); feedback.setUser(user); return feedback; } /** * @param session * @param feedbackList * @param country * @param question * @param si * @return List<Feedback> * @throws NotFoundServiceEx */ public List<Feedback> addUnrevisionedFeedbacks(HttpSession session, List<Feedback> feedbackList, String country, Long question) throws NotFoundServiceEx{ Map<String, SurveyInstance> surveyInstanceMap = (Map<String, SurveyInstance>) session .getAttribute(SURVEY_INSTANCES); SurveyInstance si = surveyInstanceMap.get(country); // ------------------------------- // // Find unrevisioned entries // // ------------------------------- // // List of question entries Collection<Entry> entries = this.controllerServiceUtils.getEntriesForQuestion(question); // /////////////////////////////////////// // List of submit users for the survey // /////////////////////////////////////// Status status = si.getStatus(); String reviewerSubmit = status.getReviewerSubmit(); String[] reviewers = (reviewerSubmit!=null)?reviewerSubmit.split(";"):new String[]{""}; List<User> reviewersForSurveyAndQuestion = null; if(question != null){ reviewersForSurveyAndQuestion = this.controllerServiceUtils.getReviewersForSurveyAndQuestion(country, question); } int size = reviewers.length; List<User> reviewersList = new ArrayList<User>(); for(int i=0; i<size; i++){ String reviewer = reviewers[i]; if(reviewer != null && !reviewer.isEmpty()){ User userReviewer = this.controllerServiceUtils.getUser(reviewer); boolean contians = reviewersForSurveyAndQuestion != null ? reviewersForSurveyAndQuestion.contains(userReviewer) : true; if(userReviewer != null && userReviewer.getRole().equals(Profile.REVIEWER.toString().toLowerCase()) && contians){ reviewersList.add(userReviewer); } } } // /////////////////////////////////////////////////////// // get the list of entries and users in feedback list // /////////////////////////////////////////////////////// List<Entry> feedbackEntryList = new ArrayList<Entry>(); List<User> feedbackUserList = new ArrayList<User>(); Iterator<Feedback> iterator = feedbackList.iterator(); while(iterator.hasNext()){ Feedback f = (Feedback)iterator.next(); Entry entry = f.getEntry(); User user = f.getUser(); if(entry != null){ feedbackEntryList.add(entry); feedbackUserList.add(user); } } Iterator<User> i = reviewersList.iterator(); while(i.hasNext()){ User user = (User)i.next(); if(!feedbackUserList.contains(user)){ // //////////////////////////////////////////// // The user have not revisioned any entry. // Creare the dummy feedback for each entry. // //////////////////////////////////////////// Iterator<Entry> iterEntry = entries.iterator(); while(iterEntry.hasNext()){ Entry entry = (Entry)iterEntry.next(); Feedback feedback = this.buildUnrevisionedFeedback(entry, si, user); feedbackList.add(feedback); } }else{ // //////////////////////////////////////////////////////////////// // The user have revisioned at least one entry. Determine which // he have not revisioned and create the dummies feedback for each // of these entries. // //////////////////////////////////////////////////////////////// Iterator<Entry> iterEntry = entries.iterator(); while(iterEntry.hasNext()){ Entry entry = (Entry)iterEntry.next(); iterator = feedbackList.iterator(); boolean exists = false; while(iterator.hasNext()){ Feedback f = (Feedback)iterator.next(); Entry e = f.getEntry(); User u = f.getUser(); boolean eb = e.equals(entry); boolean ub = u.equals(user); if(eb && ub){ exists = true; } } if(!exists){ // /////////////////////////////////////////////////////////// // Entry not revisioned. Add a dummy feedback for this. // /////////////////////////////////////////////////////////// Feedback feedback = this.buildUnrevisionedFeedback(entry, si, user); feedbackList.add(feedback); } } } } return feedbackList; } /** * @param country * @param session * @param su * @return List<Feedback> * @throws BadRequestServiceEx * @throws NotFoundServiceEx */ public List<Feedback> retrieveAllFeedbacks(String country, HttpSession session, User su) throws BadRequestServiceEx, NotFoundServiceEx { Map<String, SurveyInstance> surveyInstanceMap = (Map<String, SurveyInstance>) session .getAttribute(SURVEY_INSTANCES); SurveyInstance si = surveyInstanceMap.get(country); List<Feedback> feedbackList = null; List<Feedback> harmonizedFeedbackList = null; try { feedbackList = feedbackService.loadAllFeedback(su, si); harmonizedFeedbackList = feedbackService.loadAllHarmonizedfeedbacks(si); } catch (BadRequestServiceEx e) { throw new BadRequestServiceEx("Errors loading feedbacks..."); } feedbackList.addAll(harmonizedFeedbackList); return feedbackList; } public void storeFeedbacks() throws BadRequestServiceEx { if (this.feedbackList != null) { if (!this.feedbackList.isEmpty()) { feedbackService.storeFeedback(this.getFeedbackArray()); } } else { throw new BadRequestServiceEx("feedbackList equals to null"); } } /** * This method remove all the feedbacks that are in the feedbackListToRemove instance var * and empty the feedbackListToRemove var too. * * Usually It is used when a feedback come back to status "NOT revisioned": in that case the feedback should be removed by the DB. * * @throws BadRequestServiceEx */ public void removeFeedbacks() throws BadRequestServiceEx { if (this.feedbackListToRemove != null) { if (!this.feedbackListToRemove.isEmpty()) { feedbackService.removeFeedback(feedbackListToRemove); } } else { throw new BadRequestServiceEx("feedbackList equals to null"); } this.feedbackListToRemove = new ArrayList<Feedback>(); } /** * Create a feedback list to update the status on DB checking which feedback must be added, updated, deleted * * @param oldFeedbacks The list of the feedback before the current REVIEWER or REVIEWEREDITOR changes * @param deleteNotRevised a flag that indicate basically if the current user is a REVIEWER or REVIEWER EDITOR */ public void mergefeedbacks(List<Feedback> oldFeedbacks, boolean deleteNotRevised){ List<Feedback> feedbacksMerged = new ArrayList<Feedback>(); for(Feedback el : feedbackList){ clearFeedbackValue(el); int oldFbIndex = oldFeedbacks.indexOf(el); if(oldFbIndex >= 0){ // The feedback is present, so merge it Feedback oldFb = oldFeedbacks.get(oldFbIndex); oldFb.setStatus(el.getStatus()); String feedbackValue = (el.getStatus().equals("ok"))?"":el.getFeedback(); oldFb.setFeedback(feedbackValue); oldFb.setTimestamp(el.getTimestamp()); feedbacksMerged.add(oldFb); } // The feedback is not present, so check if must be added else if(checkIfMustBeAdded(el)){ feedbacksMerged.add(el); } } // This loop check if some feedback has been transitioned from state OK or KO to state NOT REVISED // In that case the feedback must be removed. This loop must be executed only if the user is REVIEWER // and not with REVIEWEREDITOR: with reved we delete all feedbacks for that questions! if(deleteNotRevised){ for(Feedback el : oldFeedbacks){ int oldFbIndex = feedbackList.indexOf(el); if(oldFbIndex < 0){ feedbackListToRemove.add(el); } } } feedbackList = feedbacksMerged; } public List<Feedback> packageFeedbacks(List<Feedback> feedbacks, boolean packageAlsoArmonized, Status status){ List<Feedback> packagedFeedbacks = new ArrayList<Feedback>(); Map<String, Feedback> packagedFeedbacksMap = new HashMap<String, Feedback>(); String recordKO = loadTemplatePackaged().get(0); String recordOK = loadTemplatePackaged().get(1); for(Feedback el : feedbacks){ Feedback f = new Feedback(); if(!el.getHarmonized()){ f = packagedFeedbacksMap.remove(el.getFeedbackId()); if(f == null){ f = new Feedback(); BeanUtils.copyProperties(el, f); f.setFeedback(""); } } String record = (el.getStatus().equals("ko")) ? recordKO : recordOK; String colorClass = ""; if(!StatusUtils.getReviewerSubmit(status).contains(el.getUser().getUsername())){ colorClass= "alert alert-warning"; } else { if (el.getStatus().equals("ok")) { colorClass = "alert alert-success"; }else if (el.getStatus().equals("ko")) { colorClass = "alert alert-error"; }else{ colorClass= "alert alert-warning"; } } if(f.getHarmonized() != null && !f.getHarmonized()){ StringBuilder sb = new StringBuilder(); Calendar cal = GregorianCalendar.getInstance(); cal.setTimeInMillis(el.getTimestamp()); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy.MM.dd 'at' hh:mm:ss a zzz"); dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); sb.append(f.getFeedback()); record = record.replace("%{colorClass}", colorClass); record = record.replace("%{date}", dateFormatter.format(cal.getTime())); record = record.replace("%{username}", el.getUser().getUsername()); record = record.replace("%{feedbackContent}", el.getFeedback()); record = record.replace("%{status}", el.getStatus()); sb.append(record); f.setFeedback(sb.toString()); packagedFeedbacksMap.put(f.getFeedbackId(), f); } else if(packageAlsoArmonized){ BeanUtils.copyProperties(el, f); packagedFeedbacksMap.put(f.getFeedbackId()+"_Ed", f); } } packagedFeedbacks = new ArrayList<Feedback>(packagedFeedbacksMap.values()); return packagedFeedbacks; } public void populateFeedbackList(HttpServletRequest request, HttpSession session, ControllerServices controllerServices, String countryIso3, Boolean harmonized){ User user = (User)session.getAttribute(SESSION_USER); Map<String, SurveyInstance> surveyInstanceMap = (Map<String, SurveyInstance>)session.getAttribute(SURVEY_INSTANCES); SurveyInstance si = surveyInstanceMap.get(countryIso3); Enumeration<String> paramsNames = request.getParameterNames(); while(paramsNames.hasMoreElements()){ String feedbackName = (String)paramsNames.nextElement(); if(feedbackName.startsWith(FEEDBACK)){ String feedback = (String)request.getParameter(feedbackName); String feedbackStatus = (String)request.getParameter("STATUS"+feedbackName); if(!harmonized && !checkIsOKorKO(feedbackStatus)){ continue; } feedbackStatus = (feedbackStatus != null)?feedbackStatus:""; String entryID = null; // This check is made in mergeFeedback now... // if(!StringUtils.isEmpty(feedback)){ entryID = VariableNameUtils.extractEntryIDfromFeedbackID(feedbackName); Entry entry = controllerServices.getEntry(entryID); addToFeedbackList(entry, si, user, feedback, entryID, feedbackStatus, harmonized); // } } } } public static void loadPreviousFeedbacks(Model model, FeedbackService feedbackService, HttpSession session, User su, Long question, String countryIso3){ Map<String, SurveyInstance> surveyInstanceMap = (Map<String, SurveyInstance>) session.getAttribute(SURVEY_INSTANCES); SurveyInstance si = surveyInstanceMap.get(countryIso3); List<Feedback> previousFB = new ArrayList<Feedback>(); try { previousFB = feedbackService.loadPreviousReviewFeedbacks(su, si, question); } catch (BadRequestServiceEx e1) { LOGGER.error(e1.getMessage(), e1); } for(Feedback el : previousFB){ model.addAttribute(VariableNameUtils.buildfeedbackIDfromEntryID(el.getFeedbackId()+"_old"), el.getFeedback()); } } public void prepareFeedbackModel(Model model, List<Feedback> feedbackList){ if(feedbackList != null){ for(Feedback el : feedbackList){ String feedbackId = el.getFeedbackId(); feedbackId = (el.getHarmonized())?feedbackId+"_Ed":feedbackId; model.addAttribute(VariableNameUtils.buildfeedbackIDfromEntryID(feedbackId), el.getFeedback()); model.addAttribute(VariableNameUtils.buildfeedbackStatusIDfromEntryID(feedbackId), el.getStatus()); } } } public List getFeedbackList(){ return UnmodifiableList.decorate(feedbackList); } public Feedback[] getFeedbackArray(){ if(feedbackList != null && !feedbackList.isEmpty()){ Feedback[] array = new Feedback[feedbackList.size()]; return feedbackList.toArray(array); } return null; } public void addToFeedbackList(Entry entry, SurveyInstance surveyInstance, User user, String feedback, String feedbackId, String status, Boolean harmonized){ final Feedback f = new Feedback(); f.setEntry(entry); feedback = (StringUtils.isBlank(feedback) && "ko".equals(status))?NO_COMMENT:feedback; f.setFeedback(feedback); f.setFeedbackId(feedbackId); f.setStatus(status); f.setSurvey(surveyInstance); f.setTimestamp(System.currentTimeMillis()); f.setUser(user); f.setHarmonized(harmonized); feedbackList.add(f); } public void addAllToFeedbackList(List<Feedback> list){ this.feedbackList.addAll(list); } private List<String> loadTemplatePackaged(){ InputStream tmpltStream = this.getClass().getResourceAsStream("/packagedFeedbacksTemplate.tmplt"); Reader r = new InputStreamReader(tmpltStream); List<String> templates = new ArrayList<String>(); templates.add("%{date} - %{username} - %{feedbackContent} - %{status}<br />"); templates.add("%{date} - %{username} - %{feedbackContent} - %{status}<br />"); try { templates = IOUtils.readLines(r); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } finally{ if(tmpltStream != null){ try { tmpltStream.close(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } if(r != null){ try { r.close(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } } return templates; } public int[] getFeedbackCounter(String country,HttpSession session,boolean harmonized){ Map<String, SurveyInstance> surveyInstanceMap = (Map<String, SurveyInstance>) session .getAttribute(SURVEY_INSTANCES); SurveyInstance si = surveyInstanceMap.get(country); // Update the status in surveyIstance si.setStatus(controllerServiceUtils.getStatusInstanceByCountry(country)); if(!harmonized){ Status s = si.getStatus(); StatusUtils.getReviewerSubmit(s); return feedbackService.getFeedbackCounter(si, harmonized,StatusUtils.getReviewerSubmit(s)); }else{ return feedbackService.getFeedbackCounter(si, harmonized); } } /** * This method basically check if the feedback is empty. * This check can't be done just with an isBlank method because some html tag can be present anyway, without any real content. (wrong Enter press, some button in ckeditor pressed) * So if no text is detected set the feedback value to "" * * @param f the feedback to analyze */ public static void clearFeedbackValue(Feedback f){ if(checkIsOKorNOT(f.getStatus()) || StringUtils.isBlank(f.getFeedback())){ return; } String s = f.getFeedback().replaceAll("\\s",""); if(StringUtils.isBlank(s)){ return; } s = Jsoup.parse(s).text(); if(StringUtils.isBlank(s)){ return; } for(int i=0; i<s.length(); i++){ if(CharUtils.isAsciiPrintable(s.charAt(i)) && s.charAt(i) != 0 && s.charAt(i) != 32){ return; } } if(f.getHarmonized()){ f.setFeedback(""); } else{ f.setFeedback(NO_COMMENT); } } public static boolean checkIfMustBeAdded(Feedback f){ boolean isBlank = StringUtils.isBlank(f.getFeedback()); boolean isOKorKO = checkIsOKorKO(f); return !isBlank || isOKorKO; } public static boolean checkIsOKorKO(Feedback f){ return (StringUtils.equals(f.getStatus(), "ok") || StringUtils.equals(f.getStatus(), "ko")); } public static boolean checkIsOKorKO(String status){ return (StringUtils.equals(status, "ok") || StringUtils.equals(status, "ko")); } public static boolean checkIsOKorNOT(String status){ return (StringUtils.equals(status, "ok") || StringUtils.equals(status, "not")); } }
package com.hxzy.service.impl; import com.hxzy.entity.GuestComment; import com.hxzy.mapper.GuestcommentMapper; import com.hxzy.service.GuestcommentService; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Transactional @Service public class GuestcommentServiceImpl implements GuestcommentService { @Autowired private GuestcommentMapper guestcommentMapper; @Override public boolean deleteByPrimaryKey(Integer id) { return this.guestcommentMapper.deleteByPrimaryKey(id)>0; } @Override public boolean insert(GuestComment record) { return this.guestcommentMapper.insert(record)>0; } @Transactional(propagation = Propagation.SUPPORTS) @Override public int selectByCount(int jobTableId) { return this.guestcommentMapper.selectByCount(jobTableId); } }
package com.blog.blog.pets.repositories; import com.blog.blog.pets.models.Pet; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface PetRepo extends CrudRepository<Pet, Long> { List<Pet> findAll(); }
package it.usi.xframe.xas.bfimpl.a2psms.providers.sendmail; import it.usi.xframe.xas.bfimpl.a2psms.configuration.CustomizationAbstract; import java.util.HashMap; public class Customization extends CustomizationAbstract { private HashMap mailMap = new HashMap(); public void add(String user, String address) { mailMap.put(user, address); } public String get(String user) { return (String) mailMap.get(user); } public boolean isSupportDeliveryReport() { return false; } public boolean isSupportMobileOriginated() { return false; } public boolean isSupportReplaceMap() { return false; } }
package org.graylog.outputs.hdfs; import com.google.inject.assistedinject.Assisted; import org.apache.commons.lang.text.StrSubstitutor; import org.apache.hadoop.fs.http.client.AuthenticationType; import org.apache.hadoop.fs.http.client.WebHDFSConnection; import org.apache.hadoop.security.authentication.client.AuthenticationException; import org.graylog2.plugin.Message; import org.graylog2.plugin.configuration.Configuration; import org.graylog2.plugin.configuration.ConfigurationRequest; import org.graylog2.plugin.configuration.fields.ConfigurationField; import org.graylog2.plugin.configuration.fields.NumberField; import org.graylog2.plugin.configuration.fields.TextField; import org.graylog2.plugin.outputs.MessageOutput; import org.graylog2.plugin.outputs.MessageOutputConfigurationException; import org.graylog2.plugin.streams.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; public class WebHDFSOutput implements MessageOutput { private static final Logger LOG = LoggerFactory.getLogger(WebHDFSOutput.class); private static final String CK_HDFS_HOST_NAME = "HDFS_HOST_NAME"; private static final String CK_HDFS_PORT = "HDFS_PORT"; private static final String CK_FILE = "FILE"; private static final String CK_MESSAGE_FORMAT = "MESSAGE_FORMAT"; private static final String CK_FLUSH_INTERVAL = "FLUSH_INTERVAL"; private static final String CK_CLOSE_INTERVAL = "CLOSE_INTERVAL"; private static final String CK_APPEND = "APPEND"; private static final String CK_REOPEN = "REOPEN"; private static final String CK_USERNAME = "USER_NAME"; private static final String FIELD_SEPARATOR = " | "; private Configuration configuration; private AtomicBoolean isRunning = new AtomicBoolean(false); private String fileToWrite; private String messageFormat; private long flushIntervalInMillis; //private boolean append; private Timer flushTimer; private TimerTask flushTask; private WebHDFSConnection hdfsConnection; private List<MessageData> messagesToWrite; @Inject public WebHDFSOutput(@Assisted Stream stream, @Assisted Configuration configuration) throws MessageOutputConfigurationException, IOException { this.configuration = configuration; LOG.info("WebHDFSOutput launching..."); String hostname = configuration.getString(CK_HDFS_HOST_NAME); int port = configuration.getInt(CK_HDFS_PORT); String username = configuration.getString(CK_USERNAME); hdfsConnection = new WebHDFSConnection("http://" + hostname + ":" + port, username, "anything", AuthenticationType.PSEUDO); messagesToWrite = new LinkedList<>(); fileToWrite = configuration.getString(CK_FILE); if(fileToWrite.contains("%")) { fileToWrite = fileToWrite.replaceAll("%","%1\\$t"); } messageFormat = configuration.getString(CK_MESSAGE_FORMAT); flushIntervalInMillis = configuration.getInt(CK_FLUSH_INTERVAL) * 1000; if(flushIntervalInMillis > 0) { flushTimer = new Timer("WebHDFS-Flush-Timer", true); flushTask = createFlushTask(); flushTimer.schedule(flushTask, flushIntervalInMillis, flushIntervalInMillis); } //append = configuration.getBoolean(CK_APPEND); isRunning.set(true); LOG.info("WebHDFSOutput launched"); } private TimerTask createFlushTask() { return new TimerTask() { @Override public void run() { try { writeToHdfs(); } catch (Exception e) { LOG.warn("Exception while writing to HDFS", e); } } }; } @Override public void stop() { LOG.info("Stopping WebHDFS output..."); if(flushTask != null) { flushTask.cancel(); } if(flushTimer != null) { flushTimer.cancel(); } isRunning.set(false); } @Override public boolean isRunning() { return isRunning.get(); } public void write(Message message) throws Exception { String path = getFormattedPath(message); String messageToWrite = getFormattedMessage(message); if (flushIntervalInMillis == 0) { writeToHdfs(path, messageToWrite); } else { synchronized (this) { messagesToWrite.add(new MessageData(path, messageToWrite)); } } } private synchronized void writeToHdfs() throws IOException, AuthenticationException { Map<String, StringBuilder> pathToDataMap = new HashMap<>(); for (MessageData message : messagesToWrite) { StringBuilder builder = pathToDataMap.get(message.getPath()); if (builder == null) { builder = new StringBuilder(); pathToDataMap.put(message.getPath(), builder); } builder.append(message.getMessage()); } for (Map.Entry<String, StringBuilder> entry : pathToDataMap.entrySet()) { writeToHdfs(entry.getKey(), entry.getValue().toString()); } messagesToWrite.clear(); } private void writeToHdfs(String path, String data) throws IOException, AuthenticationException { ByteArrayInputStream inputStream = new ByteArrayInputStream( data.getBytes()); try { hdfsConnection.append(path, inputStream); } catch (FileNotFoundException e) { hdfsConnection.create(path, inputStream); } } @Override public void write(List<Message> list) throws Exception { for (Message message : list) { write(message); } } private String getFormattedMessage(Message message) { String formattedMessage; if (messageFormat != null && messageFormat.length() > 0) { formattedMessage = StrSubstitutor.replace(messageFormat, message.getFields()); } else { formattedMessage = String.valueOf(message.getTimestamp()) + FIELD_SEPARATOR + message.getSource() + FIELD_SEPARATOR + message.getMessage(); } if (!formattedMessage.endsWith("\n")) { formattedMessage = formattedMessage.concat("\n"); } return formattedMessage; } private String getFormattedPath(Message message) { String formattedPath = fileToWrite; if (fileToWrite.contains("${")) { formattedPath = StrSubstitutor.replace(formattedPath, message.getFields()); } if(fileToWrite.contains("%")) { formattedPath = String.format(formattedPath, message.getTimestamp().toDate()); } return formattedPath; } public interface Factory extends MessageOutput.Factory<WebHDFSOutput> { @Override WebHDFSOutput create(Stream stream, Configuration configuration); @Override Config getConfig(); @Override Descriptor getDescriptor(); } public static class Config extends MessageOutput.Config { @Override public ConfigurationRequest getRequestedConfiguration() { final ConfigurationRequest configurationRequest = new ConfigurationRequest(); configurationRequest.addField(new TextField( CK_HDFS_HOST_NAME, "Host", "", "IP Address or hostname of HDFS server", ConfigurationField.Optional.NOT_OPTIONAL) ); configurationRequest.addField(new NumberField( CK_HDFS_PORT, "Port", 50070, "HDFS Web Port", ConfigurationField.Optional.NOT_OPTIONAL) ); configurationRequest.addField(new TextField( CK_USERNAME, "Username", "", "User name for WebHDFS connection", ConfigurationField.Optional.NOT_OPTIONAL) ); configurationRequest.addField(new TextField( CK_FILE, "File path", "", "Path of file to write messages." + "Accepts message fields like ${source} or date formats like %Y_%m_%d_%H_%M", ConfigurationField.Optional.NOT_OPTIONAL) ); configurationRequest.addField(new TextField( CK_MESSAGE_FORMAT, "Message Format", "${timestamp} | ${source} | ${message}", "Format of the message to be written. Use message fields to format", ConfigurationField.Optional.OPTIONAL) ); configurationRequest.addField(new NumberField( CK_FLUSH_INTERVAL, "Flush Interval", 0, "Flush interval in seconds. Recommended for high throughput outputs. 0 for immediate update", ConfigurationField.Optional.NOT_OPTIONAL) ); return configurationRequest; } } public static class Descriptor extends MessageOutput.Descriptor { public Descriptor() { super("WebHDFS Output", false, "", "Forwards messages to HDFS for storage"); } } private static class MessageData { private String path, message; public MessageData(String path, String messageToWrite) { this.path = path; this.message = messageToWrite; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } }
package api.longpoll.bots.model.objects.additional.buttons; import com.google.gson.JsonElement; import com.google.gson.annotations.SerializedName; /** * A button to open VK Pay window */ public class VKPayButton extends Button { public VKPayButton(Action action) { super(action); } /** * Describes action for button type of VK Pay. */ public static class Action extends Button.Action { /** * A string containing VK Pay payment parameters and the id of the app in the aid parameter, separated by &. * Example: action=transfer-to-group&group_id=1&aid=10 */ @SerializedName("hash") private String hash; public Action(String hash) { this(hash, null); } public Action(String hash, JsonElement payload) { super("vkpay", payload); this.hash = hash; } public String getHash() { return hash; } public void setHash(String hash) { this.hash = hash; } @Override public String toString() { return "Action{" + "hash='" + hash + '\'' + "} " + super.toString(); } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DatabaseAccessObjects; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.swing.JOptionPane; /** * * @author HACKER */ public class MedicalStaffDaos { public static final void registerMedicalStaff( String firstName ,String lastName, String role, String phone, String depertment, String employeeID) { try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/hospitalManagmentSystem","root","")) { PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO medicalStaff VALUES(?,?,?,?,?,?)"); preparedStatement.setString(1,firstName); preparedStatement.setString(2,lastName); preparedStatement.setString(3,role); preparedStatement.setString(4,phone); preparedStatement.setString(5,depertment); preparedStatement.setString(6,employeeID); preparedStatement.execute(); JOptionPane.showMessageDialog(null, "Staff Registration Succefull..."); } catch (SQLException ex) { ex.printStackTrace(); } } }