blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 131 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 32 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 313 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
41e7f8528875278ae4437c2b26203c710f843a6d | aae6fa589dd42c285d5fe645904f9d390972e01a | /upload/src/main/java/com/shiku/filter/RequestFilter.java | 271fd5e83e715844d55e93a72c85a9add21a6537 | [] | no_license | CNLzr/shikuim-main | 2e0ffa1b8b4d36b4caf29e482c1da7d3f7ded605 | af6857e77658d1b11ab2aca1071f856289559367 | refs/heads/main | 2023-09-02T01:54:51.031342 | 2021-11-12T00:44:26 | 2021-11-12T00:44:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,886 | java | package com.shiku.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebFilter(filterName = "requestFilter", urlPatterns = { "/*" }, initParams = {
@WebInitParam(name = "enable", value = "true") })
public class RequestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest)servletRequest;
//String origin = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", "*");
//response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
response.setHeader("Access-Control-Allow-Credentials", "true");
String method = request.getMethod();
if(method.equalsIgnoreCase("OPTIONS")){
servletResponse.getOutputStream().write("Success".getBytes("utf-8"));
}else{
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Override
public void destroy() {
}
}
| [
"65751313+SouthWind017@users.noreply.github.com"
] | 65751313+SouthWind017@users.noreply.github.com |
b1e86dd4728de5365e2d4e1599dbaab8e833ead3 | 0562cecc4dfbf5ea09480a52b69ad187443f69d4 | /src/main/java/edu/cmu/cs/stage3/alice/authoringtool/editors/responseeditor/CompositeComponentResponsePanel.java | 03cb5871745e452539c90c58040dfb322f76f90c | [
"BSD-2-Clause"
] | permissive | vorburger/Alice | 9f12b91200b53c12ee562aad88be4964c9911aa6 | af10b6edea7ecbf35bcba08d0853562fbe4a1837 | refs/heads/master | 2021-01-18T07:37:28.007447 | 2013-12-12T13:48:17 | 2013-12-12T13:48:17 | 3,757,745 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 33,470 | java | /*
* Copyright (c) 1999-2003, Carnegie Mellon University. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Products derived from the software may not be called "Alice",
* nor may "Alice" appear in their name, without prior written
* permission of Carnegie Mellon University.
*
* 4. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes software developed by Carnegie Mellon University"
*/
package edu.cmu.cs.stage3.alice.authoringtool.editors.responseeditor;
/**
* Title:
* Description:
* Copyright: Copyright (c) 2001
* Company:
* @author
* @version 1.0
*/
public class CompositeComponentResponsePanel extends edu.cmu.cs.stage3.alice.authoringtool.editors.compositeeditor.CompositeComponentElementPanel{
public CompositeComponentResponsePanel(){
super();
}
public void set(edu.cmu.cs.stage3.alice.core.property.ObjectArrayProperty elements, CompositeResponsePanel owner, edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool authoringToolIn) {
super.set(elements, owner, authoringToolIn);
}
protected java.awt.Component makeGUI(edu.cmu.cs.stage3.alice.core.Element currentElement){
javax.swing.JComponent toAdd = null;
if (currentElement instanceof edu.cmu.cs.stage3.alice.core.Response){
if (currentElement instanceof edu.cmu.cs.stage3.alice.core.response.CompositeResponse){
toAdd = edu.cmu.cs.stage3.alice.authoringtool.util.GUIFactory.getGUI(currentElement);
}
else{
if (currentElement != null){
toAdd = new ComponentResponsePanel();
((ComponentResponsePanel)toAdd).set(currentElement);
}
else{
return null;
}
}
return toAdd;
}
else{
return null;
}
}
public void dragOver( java.awt.dnd.DropTargetDragEvent dtde ) {
java.awt.Component sourceComponent = edu.cmu.cs.stage3.alice.authoringtool.util.DnDManager.getCurrentDragComponent();
int action = dtde.getDropAction();
boolean isCopy = ((action & java.awt.dnd.DnDConstants.ACTION_COPY) > 0);
boolean isMove = ((action & java.awt.dnd.DnDConstants.ACTION_MOVE) > 0);
if (!m_owner.isExpanded()){
if (m_owner.getParent() instanceof CompositeComponentResponsePanel){
((CompositeComponentResponsePanel)m_owner.getParent()).dragOver(dtde);
return;
}
}
if( edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(dtde, edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ElementReferenceTransferable.responseReferenceFlavor ) ) {
try{
java.awt.datatransfer.Transferable transferable = edu.cmu.cs.stage3.alice.authoringtool.util.DnDManager.getCurrentTransferable();
edu.cmu.cs.stage3.alice.core.Response response = (edu.cmu.cs.stage3.alice.core.Response)transferable.getTransferData( edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ElementReferenceTransferable.responseReferenceFlavor );
boolean isValid = checkLoop(response);
if (isValid){
if (isMove){
dtde.acceptDrag( java.awt.dnd.DnDConstants.ACTION_MOVE);
}
else if (isCopy){
dtde.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY );
}
insertDropPanel(dtde);
}
else{
dtde.rejectDrag();
}
} catch( java.awt.datatransfer.UnsupportedFlavorException e ) {
dtde.rejectDrag();
} catch( java.io.IOException e ) {
dtde.rejectDrag();
} catch( Throwable t ) {
dtde.rejectDrag();
}
}
else if (edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(dtde, edu.cmu.cs.stage3.alice.authoringtool.datatransfer.CopyFactoryTransferable.copyFactoryFlavor )){
try {
java.awt.datatransfer.Transferable transferable = edu.cmu.cs.stage3.alice.authoringtool.util.DnDManager.getCurrentTransferable();
edu.cmu.cs.stage3.alice.core.CopyFactory copyFactory = (edu.cmu.cs.stage3.alice.core.CopyFactory)transferable.getTransferData( edu.cmu.cs.stage3.alice.authoringtool.datatransfer.CopyFactoryTransferable.copyFactoryFlavor );
Class valueClass = copyFactory.getValueClass();
if (edu.cmu.cs.stage3.alice.core.Response.class.isAssignableFrom(valueClass)){
dtde.acceptDrag( java.awt.dnd.DnDConstants.ACTION_MOVE); //looks nicer
insertDropPanel(dtde);
}
else{
dtde.rejectDrag();
}
} catch( java.awt.datatransfer.UnsupportedFlavorException e ) {
dtde.rejectDrag();
} catch( java.io.IOException e ) {
dtde.rejectDrag();
} catch( Throwable t ) {
dtde.rejectDrag();
}
}else if( edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(dtde, edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ElementReferenceTransferable.questionReferenceFlavor )){
dtde.rejectDrag();
}
else if (edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(dtde, edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ElementReferenceTransferable.elementReferenceFlavor ) ) {
try {
java.awt.datatransfer.Transferable transferable = edu.cmu.cs.stage3.alice.authoringtool.util.DnDManager.getCurrentTransferable();
edu.cmu.cs.stage3.alice.core.Element element = (edu.cmu.cs.stage3.alice.core.Element)transferable.getTransferData( edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ElementReferenceTransferable.elementReferenceFlavor );
if (!((element instanceof edu.cmu.cs.stage3.alice.core.Behavior) || (element instanceof edu.cmu.cs.stage3.alice.core.World) || (element instanceof edu.cmu.cs.stage3.alice.core.TextureMap) || (element instanceof edu.cmu.cs.stage3.alice.core.Group))){
if (checkLoop(element)){
dtde.acceptDrag( java.awt.dnd.DnDConstants.ACTION_MOVE); //looks nicer
insertDropPanel(dtde);
}
else{
dtde.rejectDrag();
}
}
else{
dtde.rejectDrag();
}
} catch( java.awt.datatransfer.UnsupportedFlavorException e ) {
dtde.rejectDrag();
} catch( java.io.IOException e ) {
dtde.rejectDrag();
} catch( Throwable t ) {
dtde.rejectDrag();
}
}else if( edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(dtde, edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ResponsePrototypeReferenceTransferable.responsePrototypeReferenceFlavor )
|| edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(dtde, edu.cmu.cs.stage3.alice.authoringtool.datatransfer.PropertyReferenceTransferable.propertyReferenceFlavor )
|| edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(dtde, edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ElementReferenceTransferable.variableReferenceFlavor )){
if (isMove){
dtde.acceptDrag( java.awt.dnd.DnDConstants.ACTION_MOVE);
insertDropPanel(dtde);
}
else if (isCopy){
dtde.rejectDrag();
}
}else {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(dtde,edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.getReferenceFlavorForClass( edu.cmu.cs.stage3.alice.core.question.userdefined.CallToUserDefinedQuestion.class ));
dtde.rejectDrag();
return;
}
}
public void drop( final java.awt.dnd.DropTargetDropEvent dtde ) {
HACK_started = false;
boolean successful = true;
// java.awt.Component sourceComponent = edu.cmu.cs.stage3.alice.authoringtool.util.DnDManager.getCurrentDragComponent();
int action = dtde.getDropAction();
boolean isCopy = ((action & java.awt.dnd.DnDConstants.ACTION_COPY) > 0 );
boolean isMove = ((action & java.awt.dnd.DnDConstants.ACTION_MOVE) > 0);
if (!m_owner.isExpanded()){
if (m_owner.getParent() instanceof edu.cmu.cs.stage3.alice.authoringtool.editors.compositeeditor.CompositeComponentElementPanel){
((edu.cmu.cs.stage3.alice.authoringtool.editors.compositeeditor.CompositeComponentElementPanel)m_owner.getParent()).drop(dtde);
return;
}
}
java.awt.datatransfer.Transferable transferable = dtde.getTransferable();
// System.out.println("checking to see what kind of drop: "+System.currentTimeMillis());
if( edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(transferable, edu.cmu.cs.stage3.alice.authoringtool.datatransfer.CopyFactoryTransferable.copyFactoryFlavor ) ) {
try {
edu.cmu.cs.stage3.alice.core.CopyFactory copyFactory = (edu.cmu.cs.stage3.alice.core.CopyFactory)transferable.getTransferData( edu.cmu.cs.stage3.alice.authoringtool.datatransfer.CopyFactoryTransferable.copyFactoryFlavor );
Class valueClass = copyFactory.getValueClass();
if (edu.cmu.cs.stage3.alice.core.Response.class.isAssignableFrom(valueClass)){
dtde.acceptDrop( java.awt.dnd.DnDConstants.ACTION_COPY);
successful = true;
//edu.cmu.cs.stage3.alice.core.Response response = (edu.cmu.cs.stage3.alice.core.Response)copyFactory.manufactureCopy(m_owner.getElement().getRoot());
edu.cmu.cs.stage3.alice.core.Response response = (edu.cmu.cs.stage3.alice.core.Response)copyFactory.manufactureCopy(m_owner.getElement().getRoot(), null, null, m_owner.getElement() );
if (response != null){
performDrop(response, dtde);
}
}
else{
successful = false;
dtde.rejectDrop();
}
} catch( java.awt.datatransfer.UnsupportedFlavorException e ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed because of a bad flavor.", e );
successful = false;
} catch( java.io.IOException e ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed because of an IO error.", e );
successful = false;
} catch( Throwable t ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed.", t );
successful = false;
}
}else if( edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(transferable, edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ElementReferenceTransferable.responseReferenceFlavor ) ) {
try {
// System.out.println("getting response: "+System.currentTimeMillis());
edu.cmu.cs.stage3.alice.core.Response response = (edu.cmu.cs.stage3.alice.core.Response)transferable.getTransferData( edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ElementReferenceTransferable.responseReferenceFlavor );
if (response instanceof edu.cmu.cs.stage3.alice.core.response.CompositeResponse){
// System.out.println("checking valid drop: "+System.currentTimeMillis());
if (!isCopy && !isValidDrop( s_currentComponentPanel.getElement(), response)){
// System.err.println("Can't drop on self");
successful = false;
}
}
if (successful){
if (isMove){
dtde.acceptDrop( java.awt.dnd.DnDConstants.ACTION_MOVE );
}
else if (isCopy){
dtde.acceptDrop( java.awt.dnd.DnDConstants.ACTION_COPY);
}
performDrop(response, dtde);
successful = true;
}
} catch( java.awt.datatransfer.UnsupportedFlavorException e ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed because of a bad flavor.", e );
successful = false;
} catch( java.io.IOException e ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed because of an IO error.", e );
successful = false;
} catch( Throwable t ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed.", t );
successful = false;
}
}
else if( edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(dtde, edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ResponsePrototypeReferenceTransferable.responsePrototypeReferenceFlavor ) ) {
if (isMove){
dtde.acceptDrop( java.awt.dnd.DnDConstants.ACTION_MOVE );
successful = true;
}
else if (isCopy){
dtde.rejectDrop();
successful = false;
}
if (successful){
try {
edu.cmu.cs.stage3.alice.authoringtool.util.ResponsePrototype responsePrototype = (edu.cmu.cs.stage3.alice.authoringtool.util.ResponsePrototype)transferable.getTransferData( edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ResponsePrototypeReferenceTransferable.responsePrototypeReferenceFlavor );
if ((responsePrototype.getDesiredProperties() == null || responsePrototype.getDesiredProperties().length < 1) &&
!edu.cmu.cs.stage3.alice.core.response.Print.class.isAssignableFrom(responsePrototype.getResponseClass())){
performDrop(responsePrototype.createNewResponse(), dtde);
} else if (responsePrototype.getDesiredProperties().length > 3){ //Bypass the popup menu and just put in defaults if it wants more than 3 parameters
performDrop(responsePrototype.createNewResponse(), dtde);
}
else{
edu.cmu.cs.stage3.alice.authoringtool.util.PopupItemFactory factory = new edu.cmu.cs.stage3.alice.authoringtool.util.PopupItemFactory() {
public Object createItem( final Object object ) {
return new Runnable() {
public void run() {
if (object instanceof edu.cmu.cs.stage3.alice.authoringtool.util.ResponsePrototype){
performDrop(((edu.cmu.cs.stage3.alice.authoringtool.util.ResponsePrototype)object).createNewResponse(), dtde);
}
else if (object instanceof edu.cmu.cs.stage3.alice.authoringtool.util.ElementPrototype){
edu.cmu.cs.stage3.alice.core.Element newResponse = ((edu.cmu.cs.stage3.alice.authoringtool.util.ElementPrototype)object).createNewElement();
if (newResponse instanceof edu.cmu.cs.stage3.alice.core.Response){
performDrop(newResponse, dtde);
}
}
}
};
}
};
java.util.Vector structure = null;
if (edu.cmu.cs.stage3.alice.core.response.Print.class.isAssignableFrom(responsePrototype.getResponseClass())){
structure = edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.makeResponsePrintStructure(factory, componentElements.getOwner());
}
else{
structure= edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.makePrototypeStructure( responsePrototype, factory, componentElements.getOwner() );
}
javax.swing.JPopupMenu popup = edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.makePopupMenu( structure );
popup.addPopupMenuListener(this);
inserting = true;
popup.show( dtde.getDropTargetContext().getComponent(), (int)dtde.getLocation().getX(), (int)dtde.getLocation().getY() );
edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.ensurePopupIsOnScreen( popup );
}
} catch( java.awt.datatransfer.UnsupportedFlavorException e ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed because of a bad flavor.", e );
successful = false;
} catch( java.io.IOException e ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed because of an IO error.", e );
successful = false;
} catch( Throwable t ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed.", t );
successful = false;
}
}
}else if( edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(dtde, edu.cmu.cs.stage3.alice.authoringtool.datatransfer.PropertyReferenceTransferable.propertyReferenceFlavor ) ) {
if (isMove){
dtde.acceptDrop( java.awt.dnd.DnDConstants.ACTION_MOVE );
successful = true;
}
else if (isCopy){
dtde.rejectDrop();
successful = false;
}
if (successful){
try {
edu.cmu.cs.stage3.util.StringObjectPair[] known;
edu.cmu.cs.stage3.alice.core.response.PropertyAnimation animation;
Class animationClass;
edu.cmu.cs.stage3.alice.core.Property property = (edu.cmu.cs.stage3.alice.core.Property)transferable.getTransferData( edu.cmu.cs.stage3.alice.authoringtool.datatransfer.PropertyReferenceTransferable.propertyReferenceFlavor );
if (property instanceof edu.cmu.cs.stage3.alice.core.property.VehicleProperty){
//System.out.println("new vehicle animation");
edu.cmu.cs.stage3.util.StringObjectPair[] newKnown = {new edu.cmu.cs.stage3.util.StringObjectPair("element", property.getOwner()), new edu.cmu.cs.stage3.util.StringObjectPair("propertyName", property.getName()), new edu.cmu.cs.stage3.util.StringObjectPair("duration", new Double(0))};
known = newKnown;
animationClass = edu.cmu.cs.stage3.alice.core.response.VehiclePropertyAnimation.class;
}
else{
edu.cmu.cs.stage3.util.StringObjectPair[] newKnown = {new edu.cmu.cs.stage3.util.StringObjectPair("element", property.getOwner()), new edu.cmu.cs.stage3.util.StringObjectPair("propertyName", property.getName())};
known = newKnown;
animationClass = edu.cmu.cs.stage3.alice.core.response.PropertyAnimation.class;
}
edu.cmu.cs.stage3.alice.authoringtool.util.PopupItemFactory factory = new edu.cmu.cs.stage3.alice.authoringtool.util.PopupItemFactory() {
public Object createItem( final Object object ) {
return new Runnable() {
public void run() {
if (object instanceof edu.cmu.cs.stage3.alice.authoringtool.util.ResponsePrototype){
performDrop(((edu.cmu.cs.stage3.alice.authoringtool.util.ResponsePrototype)object).createNewResponse(), dtde);
}
else if (object instanceof edu.cmu.cs.stage3.alice.authoringtool.util.ElementPrototype){
edu.cmu.cs.stage3.alice.core.Element newResponse = ((edu.cmu.cs.stage3.alice.authoringtool.util.ElementPrototype)object).createNewElement();
if (newResponse instanceof edu.cmu.cs.stage3.alice.core.Response){
performDrop(newResponse, dtde);
}
}
}
};
}
};
String[] desired = {"value"};
// System.out.println("class: "+ animationClass +", known: "+known+", desired: "+desired);
edu.cmu.cs.stage3.alice.authoringtool.util.ResponsePrototype rp = new edu.cmu.cs.stage3.alice.authoringtool.util.ResponsePrototype(animationClass, known, desired);
java.util.Vector structure = edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.makePrototypeStructure( rp, factory, componentElements.getOwner() );
javax.swing.JPopupMenu popup = edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.makePopupMenu( structure );
popup.addPopupMenuListener(this);
inserting = true;
popup.show(dtde.getDropTargetContext().getComponent(), (int)dtde.getLocation().getX(), (int)dtde.getLocation().getY() );
edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.ensurePopupIsOnScreen( popup );
} catch( java.awt.datatransfer.UnsupportedFlavorException e ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed because of a bad flavor.", e );
successful = false;
} catch( java.io.IOException e ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed because of an IO error.", e );
successful = false;
} catch( Throwable t ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed.", t );
successful = false;
}
}
}else if( edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(dtde, edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ElementReferenceTransferable.variableReferenceFlavor ) ) {
if (isMove){
dtde.acceptDrop( java.awt.dnd.DnDConstants.ACTION_MOVE );
successful = true;
}
else if (isCopy){
dtde.rejectDrop();
successful = false;
}
if (successful){
try {
edu.cmu.cs.stage3.alice.core.Variable variable = (edu.cmu.cs.stage3.alice.core.Variable)transferable.getTransferData( edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ElementReferenceTransferable.variableReferenceFlavor );
if (!checkLoop(variable)){
dtde.rejectDrop();
successful = false;
}
else{
edu.cmu.cs.stage3.alice.authoringtool.util.PopupItemFactory factory = new edu.cmu.cs.stage3.alice.authoringtool.util.PopupItemFactory() {
public Object createItem( final Object object ) {
return new Runnable() {
public void run() {
if (object instanceof edu.cmu.cs.stage3.alice.authoringtool.util.ResponsePrototype){
performDrop(((edu.cmu.cs.stage3.alice.authoringtool.util.ResponsePrototype)object).createNewResponse(), dtde);
}
else if (object instanceof edu.cmu.cs.stage3.alice.authoringtool.util.ElementPrototype){
edu.cmu.cs.stage3.alice.core.Element newResponse = ((edu.cmu.cs.stage3.alice.authoringtool.util.ElementPrototype)object).createNewElement();
if (newResponse instanceof edu.cmu.cs.stage3.alice.core.Response){
performDrop(newResponse, dtde);
}
}
}
};
}
};
java.util.Vector structure = edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.makeExpressionResponseStructure( variable, factory, componentElements.getOwner() );
javax.swing.JPopupMenu popup = edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.makePopupMenu( structure );
popup.addPopupMenuListener(this);
inserting = true;
popup.show(dtde.getDropTargetContext().getComponent(), (int)dtde.getLocation().getX(), (int)dtde.getLocation().getY() );
edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.ensurePopupIsOnScreen( popup );
}
} catch( java.awt.datatransfer.UnsupportedFlavorException e ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed because of a bad flavor.", e );
successful = false;
} catch( java.io.IOException e ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed because of an IO error.", e );
successful = false;
} catch( Throwable t ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed.", t );
successful = false;
}
}
}
else if( edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(dtde, edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ElementReferenceTransferable.expressionReferenceFlavor ) ) {
//Don't handle expressions besides variables (which are handled above)
dtde.rejectDrop();
successful = false;
}else if( edu.cmu.cs.stage3.alice.authoringtool.AuthoringToolResources.safeIsDataFlavorSupported(dtde, edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ElementReferenceTransferable.elementReferenceFlavor ) ) {
try {
final edu.cmu.cs.stage3.alice.core.Element element = (edu.cmu.cs.stage3.alice.core.Element)transferable.getTransferData( edu.cmu.cs.stage3.alice.authoringtool.datatransfer.ElementReferenceTransferable.elementReferenceFlavor );
if ((element instanceof edu.cmu.cs.stage3.alice.core.Behavior) || (element instanceof edu.cmu.cs.stage3.alice.core.World) || (element instanceof edu.cmu.cs.stage3.alice.core.TextureMap)){
dtde.rejectDrop();
successful = false;
}
if (isMove){
dtde.acceptDrop( java.awt.dnd.DnDConstants.ACTION_MOVE );
successful = true;
}
else if (isCopy){
dtde.rejectDrop();
successful = false;
}
if (successful){
if (element instanceof edu.cmu.cs.stage3.alice.core.Sound){
edu.cmu.cs.stage3.alice.core.response.SoundResponse r = new edu.cmu.cs.stage3.alice.core.response.SoundResponse();
r.sound.set(element);
r.subject.set(element.getParent());
performDrop(r, dtde);
}
else if (element instanceof edu.cmu.cs.stage3.alice.core.Pose){
edu.cmu.cs.stage3.alice.core.response.PoseAnimation r = new edu.cmu.cs.stage3.alice.core.response.PoseAnimation();
r.pose.set(element);
r.subject.set(element.getParent());
performDrop(r, dtde);
}
else{
final edu.cmu.cs.stage3.alice.authoringtool.util.PopupItemFactory factory = new edu.cmu.cs.stage3.alice.authoringtool.util.PopupItemFactory() {
public Object createItem( final Object object ) {
return new Runnable() {
public void run() {
if (object instanceof edu.cmu.cs.stage3.alice.authoringtool.util.ResponsePrototype){
performDrop(((edu.cmu.cs.stage3.alice.authoringtool.util.ResponsePrototype)object).createNewResponse(), dtde);
}
else if (object instanceof edu.cmu.cs.stage3.alice.authoringtool.util.ElementPrototype){
edu.cmu.cs.stage3.alice.core.Element newResponse = ((edu.cmu.cs.stage3.alice.authoringtool.util.ElementPrototype)object).createNewElement();
if (newResponse instanceof edu.cmu.cs.stage3.alice.core.Response){
performDrop(newResponse, dtde);
}
}
}
};
}
};
java.util.Vector structure = edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.makeResponseStructure( element, factory, componentElements.getOwner() );
javax.swing.JPopupMenu popup = edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.makePopupMenu( structure );
popup.addPopupMenuListener(this);
inserting = true;
popup.show(dtde.getDropTargetContext().getComponent(), (int)dtde.getLocation().getX(), (int)dtde.getLocation().getY() );
edu.cmu.cs.stage3.alice.authoringtool.util.PopupMenuUtilities.ensurePopupIsOnScreen( popup );
}
}
} catch( java.awt.datatransfer.UnsupportedFlavorException e ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed because of a bad flavor.", e );
successful = false;
} catch( java.io.IOException e ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed because of an IO error.", e );
successful = false;
} catch( Throwable t ) {
edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool.showErrorDialog( "The drop failed.", t );
successful = false;
}
}else{
dtde.rejectDrop();
successful = false;
}
dtde.dropComplete(successful);
}
} | [
"zonedabone@gmail.com"
] | zonedabone@gmail.com |
154f524615ee97c80140711a4fe167a23506a97c | 2be554391414f7ba93f89061b9651ac6d91f73dd | /app/src/main/java/com/yueyue/glidedemo/base/Constant.java | 963ee4897a2e1ceae29ff54e1b2478ccb36ecd94 | [
"Apache-2.0"
] | permissive | simplebam/GlideDemo | 010676e43194a9e0aa50d75f949207a158705cac | 2a5768e8a95fa9873fdb5c03d7b410f16a90ae6b | refs/heads/master | 2020-03-12T04:00:14.306782 | 2018-05-27T07:57:58 | 2018-05-27T07:57:58 | 130,435,614 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 388 | java | package com.yueyue.glidedemo.base;
import com.yueyue.glidedemo.utils.FileUtil;
/**
* author : yueyue on 2018/4/18 10:44
* desc :
*/
public interface Constant {
// 网络数据缓存地址
String NET_CACHE = FileUtil.getDiskCacheDir(App.getContext(), "NetCache").getParent();
//http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1
String YING_FORMAT="js";
}
| [
"3421448373@qq.com"
] | 3421448373@qq.com |
703541b5c9311060769b69013c9d76d34754adbe | 419885fd3acceefabe7a4008ed081d6de63c785b | /app/src/main/java/com/example/flixster/MainActivity.java | 007ad36ad9d707b91d3f1fe4a35c7098e34c3bd7 | [] | no_license | LHern/FlixsterApp | 93ed04d196992ab443dae708163234700e10f747 | fe56d966636d2fed480b3a4cb2f95291a18e6b94 | refs/heads/master | 2023-07-14T21:27:12.221313 | 2021-09-08T03:20:56 | 2021-09-08T03:20:56 | 404,190,641 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,514 | java | package com.example.flixster;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import com.codepath.asynchttpclient.AsyncHttpClient;
import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler;
import com.example.flixster.adapters.MovieAdapter;
import com.example.flixster.models.Movie;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Headers;
public class MainActivity extends AppCompatActivity {
public static final String NOW_Playing_URL = "https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed";
public static final String TAG = "MainActivity";
List<Movie> movies;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView rvMovies = findViewById(R.id.rvMovies);
movies = new ArrayList<>();
//Create the adapter
MovieAdapter movieAdapter = new MovieAdapter(this, movies);
//Set the adapter on the recycler view
rvMovies.setAdapter(movieAdapter);
// Set a Layout Manger on the recyclerView
rvMovies.setLayoutManager(new LinearLayoutManager(this));
AsyncHttpClient client = new AsyncHttpClient();
client.get(NOW_Playing_URL, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Headers headers, JSON json) {
Log.d(TAG, "anSuccess");
JSONObject jsonObject = json.jsonObject;
try {
JSONArray results = jsonObject.getJSONArray("results");
Log.i(TAG,"Results: " + results.toString());
movies.addAll(Movie.fromJsonArray(results));
movieAdapter.notifyDataSetChanged();
Log.i(TAG,"Movies: " + movies.size());
} catch (JSONException e) {
Log.e(TAG, "Hit Json execption", e);
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) {
Log.d(TAG, "onFailure");
}
});
}
} | [
"86651985+LHern@users.noreply.github.com"
] | 86651985+LHern@users.noreply.github.com |
4b5b45ed7979e1d057b564d355a268a3d9c7cb5d | 2b9878f793ae7804124b0659ebce372bfb1fd1ad | /src/Model/Jurnal.java | 0c824722ff748d146b1cc747c9a323c32ed3518a | [] | no_license | jonathangabe/Tugas-Besar-IMPAL | 5a227bda4420336abc3196fb9a6c629c6c6de21c | cca7cf38e07901f9abc65c1c7352ffa109a5bcb4 | refs/heads/master | 2020-07-27T01:28:04.201155 | 2016-12-13T12:17:09 | 2016-12-13T12:17:09 | 73,706,752 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,406 | java | /*
* 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 Model;
import java.util.ArrayList;
/**
*
* @author UPC
*/
public class Jurnal {
private int idJurnal;
private float debit,kredit;
private String keterangan;
public Jurnal(float debit, float kredit, String keterangan) {
this.debit = debit;
this.kredit = kredit;
this.keterangan = keterangan;
}
public Jurnal(int idJurnal, float debit, float kredit, String keterangan) {
this.idJurnal = idJurnal;
this.debit = debit;
this.kredit = kredit;
this.keterangan = keterangan;
}
public int getIdJurnal() {
return idJurnal;
}
public void setIdJurnal(int idJurnal) {
this.idJurnal = idJurnal;
}
public float getDebit() {
return debit;
}
public void setDebit(float debit) {
this.debit = debit;
}
public float getKredit() {
return kredit;
}
public void setKredit(float kredit) {
this.kredit = kredit;
}
public String getKeterangan() {
return keterangan;
}
public void setKeterangan(String keterangan) {
this.keterangan = keterangan;
}
}
| [
"Gabe@Gabe-PC.local"
] | Gabe@Gabe-PC.local |
57813fcc69bcbdef105e28e02581cddde5fa7235 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/8/8_eb71c8999ff29f7dc3fe8dcdba81084f7f6a5fac/NanoHTTPD/8_eb71c8999ff29f7dc3fe8dcdba81084f7f6a5fac_NanoHTTPD_t.java | 4277ce7f7d9ffda887f131a1eddb7fab1a08c24b | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 50,640 | java | package fi.iki.elonen;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* A simple, tiny, nicely embeddable HTTP server in Java
* <p/>
* <p/>
* NanoHTTPD
* <p></p>Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen, 2010 by Konstantinos Togias</p>
* <p/>
* <p/>
* <b>Features + limitations: </b>
* <ul>
* <p/>
* <li>Only one Java file</li>
* <li>Java 5 compatible</li>
* <li>Released as open source, Modified BSD licence</li>
* <li>No fixed config files, logging, authorization etc. (Implement yourself if you need them.)</li>
* <li>Supports parameter parsing of GET and POST methods (+ rudimentary PUT support in 1.25)</li>
* <li>Supports both dynamic content and file serving</li>
* <li>Supports file upload (since version 1.2, 2010)</li>
* <li>Supports partial content (streaming)</li>
* <li>Supports ETags</li>
* <li>Never caches anything</li>
* <li>Doesn't limit bandwidth, request time or simultaneous connections</li>
* <li>Default code serves files and shows all HTTP parameters and headers</li>
* <li>File server supports directory listing, index.html and index.htm</li>
* <li>File server supports partial content (streaming)</li>
* <li>File server supports ETags</li>
* <li>File server does the 301 redirection trick for directories without '/'</li>
* <li>File server supports simple skipping for files (continue download)</li>
* <li>File server serves also very long files without memory overhead</li>
* <li>Contains a built-in list of most common mime types</li>
* <li>All header names are converted lowercase so they don't vary between browsers/clients</li>
* <p/>
* </ul>
* <p/>
* <p/>
* <b>How to use: </b>
* <ul>
* <p/>
* <li>Subclass and implement serve() and embed to your own program</li>
* <p/>
* </ul>
* <p/>
* See the separate "LICENSE.md" file for the distribution license (Modified BSD licence)
*/
public abstract class NanoHTTPD {
/**
* Maximum time to wait on Socket.getInputStream().read() (in milliseconds)
* This is required as the Keep-Alive HTTP connections would otherwise
* block the socket reading thread forever (or as long the browser is open).
*/
public static final int SOCKET_READ_TIMEOUT = 5000;
/**
* Common mime type for dynamic content: plain text
*/
public static final String MIME_PLAINTEXT = "text/plain";
/**
* Common mime type for dynamic content: html
*/
public static final String MIME_HTML = "text/html";
/**
* Pseudo-Parameter to use to store the actual query string in the parameters map for later re-processing.
*/
private static final String QUERY_STRING_PARAMETER = "NanoHttpd.QUERY_STRING";
private final String hostname;
private final int myPort;
private ServerSocket myServerSocket;
private Thread myThread;
/**
* Pluggable strategy for asynchronously executing requests.
*/
private AsyncRunner asyncRunner;
/**
* Pluggable strategy for creating and cleaning up temporary files.
*/
private TempFileManagerFactory tempFileManagerFactory;
/**
* Constructs an HTTP server on given port.
*/
public NanoHTTPD(int port) {
this(null, port);
}
/**
* Constructs an HTTP server on given hostname and port.
*/
public NanoHTTPD(String hostname, int port) {
this.hostname = hostname;
this.myPort = port;
setTempFileManagerFactory(new DefaultTempFileManagerFactory());
setAsyncRunner(new DefaultAsyncRunner());
}
private static final void safeClose(ServerSocket serverSocket) {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
}
}
}
private static final void safeClose(Socket socket) {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
private static final void safeClose(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
}
}
}
/**
* Start the server.
*
* @throws IOException if the socket is in use.
*/
public void start() throws IOException {
myServerSocket = new ServerSocket();
myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));
myThread = new Thread(new Runnable() {
@Override
public void run() {
do {
try {
final Socket finalAccept = myServerSocket.accept();
finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
final InputStream inputStream = finalAccept.getInputStream();
if (inputStream == null) {
safeClose(finalAccept);
} else {
asyncRunner.exec(new Runnable() {
@Override
public void run() {
OutputStream outputStream = null;
try {
outputStream = finalAccept.getOutputStream();
TempFileManager tempFileManager = tempFileManagerFactory.create();
HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream);
while (!finalAccept.isClosed()) {
session.execute();
}
} catch (Exception e) {
// When the socket is closed by the client, we throw our own SocketException
// to break the "keep alive" loop above.
if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) {
e.printStackTrace();
}
} finally {
safeClose(outputStream);
safeClose(inputStream);
safeClose(finalAccept);
}
}
});
}
} catch (IOException e) {
}
} while (!myServerSocket.isClosed());
}
});
myThread.setDaemon(true);
myThread.setName("NanoHttpd Main Listener");
myThread.start();
}
/**
* Stop the server.
*/
public void stop() {
try {
safeClose(myServerSocket);
myThread.join();
} catch (Exception e) {
e.printStackTrace();
}
}
public final int getListeningPort() {
return myServerSocket == null ? -1 : myServerSocket.getLocalPort();
}
public final boolean wasStarted() {
return myServerSocket != null && myThread != null;
}
public final boolean isAlive() {
return wasStarted() && !myServerSocket.isClosed() && myThread.isAlive();
}
/**
* Override this to customize the server.
* <p/>
* <p/>
* (By default, this delegates to serveFile() and allows directory listing.)
*
* @param uri Percent-decoded URI without parameters, for example "/index.cgi"
* @param method "GET", "POST" etc.
* @param parms Parsed, percent decoded parameters from URI and, in case of POST, data.
* @param headers Header entries, percent decoded
* @return HTTP response, see class Response for details
*/
@Deprecated
public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms,
Map<String, String> files) {
return new Response(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found");
}
/**
* Override this to customize the server.
* <p/>
* <p/>
* (By default, this delegates to serveFile() and allows directory listing.)
*
* @param session The HTTP session
* @return HTTP response, see class Response for details
*/
public Response serve(IHTTPSession session) {
Map<String, String> files = new HashMap<String, String>();
Method method = session.getMethod();
if (Method.PUT.equals(method) || Method.POST.equals(method)) {
try {
session.parseBody(files);
} catch (IOException ioe) {
return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
} catch (ResponseException re) {
return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
}
}
return serve(session.getUri(), method, session.getHeaders(), session.getParms(), files);
}
/**
* Decode percent encoded <code>String</code> values.
*
* @param str the percent encoded <code>String</code>
* @return expanded form of the input, for example "foo%20bar" becomes "foo bar"
*/
protected String decodePercent(String str) {
String decoded = null;
try {
decoded = URLDecoder.decode(str, "UTF8");
} catch (UnsupportedEncodingException ignored) {
}
return decoded;
}
/**
* Decode parameters from a URL, handing the case where a single parameter name might have been
* supplied several times, by return lists of values. In general these lists will contain a single
* element.
*
* @param parms original <b>NanoHttpd</b> parameters values, as passed to the <code>serve()</code> method.
* @return a map of <code>String</code> (parameter name) to <code>List<String></code> (a list of the values supplied).
*/
protected Map<String, List<String>> decodeParameters(Map<String, String> parms) {
return this.decodeParameters(parms.get(QUERY_STRING_PARAMETER));
}
/**
* Decode parameters from a URL, handing the case where a single parameter name might have been
* supplied several times, by return lists of values. In general these lists will contain a single
* element.
*
* @param queryString a query string pulled from the URL.
* @return a map of <code>String</code> (parameter name) to <code>List<String></code> (a list of the values supplied).
*/
protected Map<String, List<String>> decodeParameters(String queryString) {
Map<String, List<String>> parms = new HashMap<String, List<String>>();
if (queryString != null) {
StringTokenizer st = new StringTokenizer(queryString, "&");
while (st.hasMoreTokens()) {
String e = st.nextToken();
int sep = e.indexOf('=');
String propertyName = (sep >= 0) ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim();
if (!parms.containsKey(propertyName)) {
parms.put(propertyName, new ArrayList<String>());
}
String propertyValue = (sep >= 0) ? decodePercent(e.substring(sep + 1)) : null;
if (propertyValue != null) {
parms.get(propertyName).add(propertyValue);
}
}
}
return parms;
}
// ------------------------------------------------------------------------------- //
//
// Threading Strategy.
//
// ------------------------------------------------------------------------------- //
/**
* Pluggable strategy for asynchronously executing requests.
*
* @param asyncRunner new strategy for handling threads.
*/
public void setAsyncRunner(AsyncRunner asyncRunner) {
this.asyncRunner = asyncRunner;
}
// ------------------------------------------------------------------------------- //
//
// Temp file handling strategy.
//
// ------------------------------------------------------------------------------- //
/**
* Pluggable strategy for creating and cleaning up temporary files.
*
* @param tempFileManagerFactory new strategy for handling temp files.
*/
public void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) {
this.tempFileManagerFactory = tempFileManagerFactory;
}
/**
* HTTP Request methods, with the ability to decode a <code>String</code> back to its enum value.
*/
public enum Method {
GET, PUT, POST, DELETE, HEAD, OPTIONS;
static Method lookup(String method) {
for (Method m : Method.values()) {
if (m.toString().equalsIgnoreCase(method)) {
return m;
}
}
return null;
}
}
/**
* Pluggable strategy for asynchronously executing requests.
*/
public interface AsyncRunner {
void exec(Runnable code);
}
/**
* Factory to create temp file managers.
*/
public interface TempFileManagerFactory {
TempFileManager create();
}
// ------------------------------------------------------------------------------- //
/**
* Temp file manager.
* <p/>
* <p>Temp file managers are created 1-to-1 with incoming requests, to create and cleanup
* temporary files created as a result of handling the request.</p>
*/
public interface TempFileManager {
TempFile createTempFile() throws Exception;
void clear();
}
/**
* A temp file.
* <p/>
* <p>Temp files are responsible for managing the actual temporary storage and cleaning
* themselves up when no longer needed.</p>
*/
public interface TempFile {
OutputStream open() throws Exception;
void delete() throws Exception;
String getName();
}
/**
* Default threading strategy for NanoHttpd.
* <p/>
* <p>By default, the server spawns a new Thread for every incoming request. These are set
* to <i>daemon</i> status, and named according to the request number. The name is
* useful when profiling the application.</p>
*/
public static class DefaultAsyncRunner implements AsyncRunner {
private long requestCount;
@Override
public void exec(Runnable code) {
++requestCount;
Thread t = new Thread(code);
t.setDaemon(true);
t.setName("NanoHttpd Request Processor (#" + requestCount + ")");
t.start();
}
}
/**
* Default strategy for creating and cleaning up temporary files.
* <p/>
* <p></p>This class stores its files in the standard location (that is,
* wherever <code>java.io.tmpdir</code> points to). Files are added
* to an internal list, and deleted when no longer needed (that is,
* when <code>clear()</code> is invoked at the end of processing a
* request).</p>
*/
public static class DefaultTempFileManager implements TempFileManager {
private final String tmpdir;
private final List<TempFile> tempFiles;
public DefaultTempFileManager() {
tmpdir = System.getProperty("java.io.tmpdir");
tempFiles = new ArrayList<TempFile>();
}
@Override
public TempFile createTempFile() throws Exception {
DefaultTempFile tempFile = new DefaultTempFile(tmpdir);
tempFiles.add(tempFile);
return tempFile;
}
@Override
public void clear() {
for (TempFile file : tempFiles) {
try {
file.delete();
} catch (Exception ignored) {
}
}
tempFiles.clear();
}
}
/**
* Default strategy for creating and cleaning up temporary files.
* <p/>
* <p></p></[>By default, files are created by <code>File.createTempFile()</code> in
* the directory specified.</p>
*/
public static class DefaultTempFile implements TempFile {
private File file;
private OutputStream fstream;
public DefaultTempFile(String tempdir) throws IOException {
file = File.createTempFile("NanoHTTPD-", "", new File(tempdir));
fstream = new FileOutputStream(file);
}
@Override
public OutputStream open() throws Exception {
return fstream;
}
@Override
public void delete() throws Exception {
safeClose(fstream);
file.delete();
}
@Override
public String getName() {
return file.getAbsolutePath();
}
}
/**
* HTTP response. Return one of these from serve().
*/
public static class Response {
/**
* HTTP status code after processing, e.g. "200 OK", HTTP_OK
*/
private Status status;
/**
* MIME type of content, e.g. "text/html"
*/
private String mimeType;
/**
* Data of the response, may be null.
*/
private InputStream data;
/**
* Headers for the HTTP response. Use addHeader() to add lines.
*/
private Map<String, String> header = new HashMap<String, String>();
/**
* The request method that spawned this response.
*/
private Method requestMethod;
/**
* Use chunkedTransfer
*/
private boolean chunkedTransfer;
/**
* Default constructor: response = HTTP_OK, mime = MIME_HTML and your supplied message
*/
public Response(String msg) {
this(Status.OK, MIME_HTML, msg);
}
/**
* Basic constructor.
*/
public Response(Status status, String mimeType, InputStream data) {
this.status = status;
this.mimeType = mimeType;
this.data = data;
}
/**
* Convenience method that makes an InputStream out of given text.
*/
public Response(Status status, String mimeType, String txt) {
this.status = status;
this.mimeType = mimeType;
try {
this.data = txt != null ? new ByteArrayInputStream(txt.getBytes("UTF-8")) : null;
} catch (java.io.UnsupportedEncodingException uee) {
uee.printStackTrace();
}
}
/**
* Adds given line to the header.
*/
public void addHeader(String name, String value) {
header.put(name, value);
}
/**
* Sends given response to the socket.
*/
private void send(OutputStream outputStream) {
String mime = mimeType;
SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
if (status == null) {
throw new Error("sendResponse(): Status can't be null.");
}
PrintWriter pw = new PrintWriter(outputStream);
pw.print("HTTP/1.1 " + status.getDescription() + " \r\n");
if (mime != null) {
pw.print("Content-Type: " + mime + "\r\n");
}
if (header == null || header.get("Date") == null) {
pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n");
}
if (header != null) {
for (String key : header.keySet()) {
String value = header.get(key);
pw.print(key + ": " + value + "\r\n");
}
}
pw.print("Connection: keep-alive\r\n");
if (requestMethod != Method.HEAD && chunkedTransfer) {
sendAsChunked(outputStream, pw);
} else {
sendAsFixedLength(outputStream, pw);
}
outputStream.flush();
safeClose(data);
} catch (IOException ioe) {
// Couldn't write? No can do.
}
}
private void sendAsChunked(OutputStream outputStream, PrintWriter pw) throws IOException {
pw.print("Transfer-Encoding: chunked\r\n");
pw.print("\r\n");
pw.flush();
int BUFFER_SIZE = 16 * 1024;
byte[] CRLF = "\r\n".getBytes();
byte[] buff = new byte[BUFFER_SIZE];
int read;
while ((read = data.read(buff)) > 0) {
outputStream.write(String.format("%x\r\n", read).getBytes());
outputStream.write(buff, 0, read);
outputStream.write(CRLF);
}
outputStream.write(String.format("0\r\n\r\n").getBytes());
}
private void sendAsFixedLength(OutputStream outputStream, PrintWriter pw) throws IOException {
int pending = data != null ? data.available() : 0; // This is to support partial sends, see serveFile()
pw.print("Content-Length: "+pending+"\r\n");
pw.print("\r\n");
pw.flush();
if (requestMethod != Method.HEAD && data != null) {
int BUFFER_SIZE = 16 * 1024;
byte[] buff = new byte[BUFFER_SIZE];
while (pending > 0) {
int read = data.read(buff, 0, ((pending > BUFFER_SIZE) ? BUFFER_SIZE : pending));
if (read <= 0) {
break;
}
outputStream.write(buff, 0, read);
pending -= read;
}
}
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public InputStream getData() {
return data;
}
public void setData(InputStream data) {
this.data = data;
}
public Method getRequestMethod() {
return requestMethod;
}
public void setRequestMethod(Method requestMethod) {
this.requestMethod = requestMethod;
}
public void setChunkedTransfer(boolean chunkedTransfer) {
this.chunkedTransfer = chunkedTransfer;
}
/**
* Some HTTP response status codes
*/
public enum Status {
OK(200, "OK"), CREATED(201, "Created"), ACCEPTED(202, "Accepted"), NO_CONTENT(204, "No Content"), PARTIAL_CONTENT(206, "Partial Content"), REDIRECT(301,
"Moved Permanently"), NOT_MODIFIED(304, "Not Modified"), BAD_REQUEST(400, "Bad Request"), UNAUTHORIZED(401,
"Unauthorized"), FORBIDDEN(403, "Forbidden"), NOT_FOUND(404, "Not Found"), METHOD_NOT_ALLOWED(405, "Method Not Allowed"), RANGE_NOT_SATISFIABLE(416,
"Requested Range Not Satisfiable"), INTERNAL_ERROR(500, "Internal Server Error");
private final int requestStatus;
private final String description;
Status(int requestStatus, String description) {
this.requestStatus = requestStatus;
this.description = description;
}
public int getRequestStatus() {
return this.requestStatus;
}
public String getDescription() {
return "" + this.requestStatus + " " + description;
}
}
}
public static final class ResponseException extends Exception {
private final Response.Status status;
public ResponseException(Response.Status status, String message) {
super(message);
this.status = status;
}
public ResponseException(Response.Status status, String message, Exception e) {
super(message, e);
this.status = status;
}
public Response.Status getStatus() {
return status;
}
}
/**
* Default strategy for creating and cleaning up temporary files.
*/
private class DefaultTempFileManagerFactory implements TempFileManagerFactory {
@Override
public TempFileManager create() {
return new DefaultTempFileManager();
}
}
/**
* Handles one session, i.e. parses the HTTP request and returns the response.
*/
public interface IHTTPSession {
void execute() throws IOException;
Map<String, String> getParms();
Map<String, String> getHeaders();
/**
* @return the path part of the URL.
*/
String getUri();
Method getMethod();
InputStream getInputStream();
CookieHandler getCookies();
/**
* Adds the files in the request body to the files map.
* @arg files - map to modify
*/
void parseBody(Map<String, String> files) throws IOException, ResponseException;
}
protected class HTTPSession implements IHTTPSession {
public static final int BUFSIZE = 8192;
private final TempFileManager tempFileManager;
private final OutputStream outputStream;
private InputStream inputStream;
private int splitbyte;
private int rlen;
private String uri;
private Method method;
private Map<String, String> parms;
private Map<String, String> headers;
private CookieHandler cookies;
public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) {
this.tempFileManager = tempFileManager;
this.inputStream = inputStream;
this.outputStream = outputStream;
}
@Override
public void execute() throws IOException {
try {
// Read the first 8192 bytes.
// The full header should fit in here.
// Apache's default header limit is 8KB.
// Do NOT assume that a single read will get the entire header at once!
byte[] buf = new byte[BUFSIZE];
splitbyte = 0;
rlen = 0;
{
int read = inputStream.read(buf, 0, BUFSIZE);
if (read == -1) {
// socket was been closed
throw new SocketException("NanoHttpd Shutdown");
}
while (read > 0) {
rlen += read;
splitbyte = findHeaderEnd(buf, rlen);
if (splitbyte > 0)
break;
read = inputStream.read(buf, rlen, BUFSIZE - rlen);
}
}
if (splitbyte < rlen) {
ByteArrayInputStream splitInputStream = new ByteArrayInputStream(buf, splitbyte, rlen - splitbyte);
SequenceInputStream sequenceInputStream = new SequenceInputStream(splitInputStream, inputStream);
inputStream = sequenceInputStream;
}
parms = new HashMap<String, String>();
headers = new HashMap<String, String>();
// Create a BufferedReader for parsing the header.
BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, rlen)));
// Decode the header into parms and header java properties
Map<String, String> pre = new HashMap<String, String>();
decodeHeader(hin, pre, parms, headers);
method = Method.lookup(pre.get("method"));
if (method == null) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error.");
}
uri = pre.get("uri");
cookies = new CookieHandler(headers);
// Ok, now do the serve()
Response r = serve(this);
if (r == null) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response.");
} else {
cookies.unloadQueue(r);
r.setRequestMethod(method);
r.send(outputStream);
}
} catch (SocketException e) {
// throw it out to close socket object (finalAccept)
throw e;
} catch (IOException ioe) {
Response r = new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
r.send(outputStream);
safeClose(outputStream);
} catch (ResponseException re) {
Response r = new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
r.send(outputStream);
safeClose(outputStream);
} finally {
tempFileManager.clear();
}
}
@Override
public void parseBody(Map<String, String> files) throws IOException, ResponseException {
RandomAccessFile randomAccessFile = null;
BufferedReader in = null;
try {
randomAccessFile = getTmpBucket();
long size;
if (headers.containsKey("content-length")) {
size = Integer.parseInt(headers.get("content-length"));
} else if (splitbyte < rlen) {
size = rlen - splitbyte;
} else {
size = 0;
}
// Now read all the body and write it to f
byte[] buf = new byte[512];
while (rlen >= 0 && size > 0) {
rlen = inputStream.read(buf, 0, 512);
size -= rlen;
if (rlen > 0) {
randomAccessFile.write(buf, 0, rlen);
}
}
// Get the raw body as a byte []
ByteBuffer fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());
randomAccessFile.seek(0);
// Create a BufferedReader for easily reading it as string.
InputStream bin = new FileInputStream(randomAccessFile.getFD());
in = new BufferedReader(new InputStreamReader(bin));
// If the method is POST, there may be parameters
// in data section, too, read it:
if (Method.POST.equals(method)) {
String contentType = "";
String contentTypeHeader = headers.get("content-type");
StringTokenizer st = null;
if (contentTypeHeader != null) {
st = new StringTokenizer(contentTypeHeader, ",; ");
if (st.hasMoreTokens()) {
contentType = st.nextToken();
}
}
if ("multipart/form-data".equalsIgnoreCase(contentType)) {
// Handle multipart/form-data
if (!st.hasMoreTokens()) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html");
}
String boundaryStartString = "boundary=";
int boundaryContentStart = contentTypeHeader.indexOf(boundaryStartString) + boundaryStartString.length();
String boundary = contentTypeHeader.substring(boundaryContentStart, contentTypeHeader.length());
if (boundary.startsWith("\"") && boundary.endsWith("\"")) {
boundary = boundary.substring(1, boundary.length() - 1);
}
decodeMultipartData(boundary, fbuf, in, parms, files);
} else {
// Handle application/x-www-form-urlencoded
String postLine = "";
char pbuf[] = new char[512];
int read = in.read(pbuf);
while (read >= 0 && !postLine.endsWith("\r\n")) {
postLine += String.valueOf(pbuf, 0, read);
read = in.read(pbuf);
}
postLine = postLine.trim();
decodeParms(postLine, parms);
}
} else if (Method.PUT.equals(method)) {
files.put("content", saveTmpFile(fbuf, 0, fbuf.limit()));
}
} finally {
safeClose(randomAccessFile);
safeClose(in);
}
}
/**
* Decodes the sent headers and loads the data into Key/value pairs
*/
private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, String> parms, Map<String, String> headers)
throws ResponseException {
try {
// Read the request line
String inLine = in.readLine();
if (inLine == null) {
return;
}
StringTokenizer st = new StringTokenizer(inLine);
if (!st.hasMoreTokens()) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html");
}
pre.put("method", st.nextToken());
if (!st.hasMoreTokens()) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html");
}
String uri = st.nextToken();
// Decode parameters from the URI
int qmi = uri.indexOf('?');
if (qmi >= 0) {
decodeParms(uri.substring(qmi + 1), parms);
uri = decodePercent(uri.substring(0, qmi));
} else {
uri = decodePercent(uri);
}
// If there's another token, it's protocol version,
// followed by HTTP headers. Ignore version but parse headers.
// NOTE: this now forces header names lowercase since they are
// case insensitive and vary by client.
if (st.hasMoreTokens()) {
String line = in.readLine();
while (line != null && line.trim().length() > 0) {
int p = line.indexOf(':');
if (p >= 0)
headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim());
line = in.readLine();
}
}
pre.put("uri", uri);
} catch (IOException ioe) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
}
}
/**
* Decodes the Multipart Body data and put it into Key/Value pairs.
*/
private void decodeMultipartData(String boundary, ByteBuffer fbuf, BufferedReader in, Map<String, String> parms,
Map<String, String> files) throws ResponseException {
try {
int[] bpositions = getBoundaryPositions(fbuf, boundary.getBytes());
int boundarycount = 1;
String mpline = in.readLine();
while (mpline != null) {
if (!mpline.contains(boundary)) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html");
}
boundarycount++;
Map<String, String> item = new HashMap<String, String>();
mpline = in.readLine();
while (mpline != null && mpline.trim().length() > 0) {
int p = mpline.indexOf(':');
if (p != -1) {
item.put(mpline.substring(0, p).trim().toLowerCase(Locale.US), mpline.substring(p + 1).trim());
}
mpline = in.readLine();
}
if (mpline != null) {
String contentDisposition = item.get("content-disposition");
if (contentDisposition == null) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html");
}
StringTokenizer st = new StringTokenizer(contentDisposition, "; ");
Map<String, String> disposition = new HashMap<String, String>();
while (st.hasMoreTokens()) {
String token = st.nextToken();
int p = token.indexOf('=');
if (p != -1) {
disposition.put(token.substring(0, p).trim().toLowerCase(Locale.US), token.substring(p + 1).trim());
}
}
String pname = disposition.get("name");
pname = pname.substring(1, pname.length() - 1);
String value = "";
if (item.get("content-type") == null) {
while (mpline != null && !mpline.contains(boundary)) {
mpline = in.readLine();
if (mpline != null) {
int d = mpline.indexOf(boundary);
if (d == -1) {
value += mpline;
} else {
value += mpline.substring(0, d - 2);
}
}
}
} else {
if (boundarycount > bpositions.length) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "Error processing request");
}
int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]);
String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4);
files.put(pname, path);
value = disposition.get("filename");
value = value.substring(1, value.length() - 1);
do {
mpline = in.readLine();
} while (mpline != null && !mpline.contains(boundary));
}
parms.put(pname, value);
}
}
} catch (IOException ioe) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
}
}
/**
* Find byte index separating header from body. It must be the last byte of the first two sequential new lines.
*/
private int findHeaderEnd(final byte[] buf, int rlen) {
int splitbyte = 0;
while (splitbyte + 3 < rlen) {
if (buf[splitbyte] == '\r' && buf[splitbyte + 1] == '\n' && buf[splitbyte + 2] == '\r' && buf[splitbyte + 3] == '\n') {
return splitbyte + 4;
}
splitbyte++;
}
return 0;
}
/**
* Find the byte positions where multipart boundaries start.
*/
private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) {
int matchcount = 0;
int matchbyte = -1;
List<Integer> matchbytes = new ArrayList<Integer>();
for (int i = 0; i < b.limit(); i++) {
if (b.get(i) == boundary[matchcount]) {
if (matchcount == 0)
matchbyte = i;
matchcount++;
if (matchcount == boundary.length) {
matchbytes.add(matchbyte);
matchcount = 0;
matchbyte = -1;
}
} else {
i -= matchcount;
matchcount = 0;
matchbyte = -1;
}
}
int[] ret = new int[matchbytes.size()];
for (int i = 0; i < ret.length; i++) {
ret[i] = matchbytes.get(i);
}
return ret;
}
/**
* Retrieves the content of a sent file and saves it to a temporary file. The full path to the saved file is returned.
*/
private String saveTmpFile(ByteBuffer b, int offset, int len) {
String path = "";
if (len > 0) {
FileOutputStream fileOutputStream = null;
try {
TempFile tempFile = tempFileManager.createTempFile();
ByteBuffer src = b.duplicate();
fileOutputStream = new FileOutputStream(tempFile.getName());
FileChannel dest = fileOutputStream.getChannel();
src.position(offset).limit(offset + len);
dest.write(src.slice());
path = tempFile.getName();
} catch (Exception e) { // Catch exception if any
System.err.println("Error: " + e.getMessage());
} finally {
safeClose(fileOutputStream);
}
}
return path;
}
private RandomAccessFile getTmpBucket() {
try {
TempFile tempFile = tempFileManager.createTempFile();
return new RandomAccessFile(tempFile.getName(), "rw");
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
return null;
}
/**
* It returns the offset separating multipart file headers from the file's data.
*/
private int stripMultipartHeaders(ByteBuffer b, int offset) {
int i;
for (i = offset; i < b.limit(); i++) {
if (b.get(i) == '\r' && b.get(++i) == '\n' && b.get(++i) == '\r' && b.get(++i) == '\n') {
break;
}
}
return i + 1;
}
/**
* Decodes parameters in percent-encoded URI-format ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and
* adds them to given Map. NOTE: this doesn't support multiple identical keys due to the simplicity of Map.
*/
private void decodeParms(String parms, Map<String, String> p) {
if (parms == null) {
p.put(QUERY_STRING_PARAMETER, "");
return;
}
p.put(QUERY_STRING_PARAMETER, parms);
StringTokenizer st = new StringTokenizer(parms, "&");
while (st.hasMoreTokens()) {
String e = st.nextToken();
int sep = e.indexOf('=');
if (sep >= 0) {
p.put(decodePercent(e.substring(0, sep)).trim(),
decodePercent(e.substring(sep + 1)));
} else {
p.put(decodePercent(e).trim(), "");
}
}
}
@Override
public final Map<String, String> getParms() {
return parms;
}
@Override
public final Map<String, String> getHeaders() {
return headers;
}
@Override
public final String getUri() {
return uri;
}
@Override
public final Method getMethod() {
return method;
}
@Override
public final InputStream getInputStream() {
return inputStream;
}
@Override
public CookieHandler getCookies() {
return cookies;
}
}
public static class Cookie {
private String n, v, e;
public Cookie(String name, String value, String expires) {
n = name;
v = value;
e = expires;
}
public Cookie(String name, String value) {
this(name, value, 30);
}
public Cookie(String name, String value, int numDays) {
n = name;
v = value;
e = getHTTPTime(numDays);
}
public String getHTTPHeader() {
String fmt = "%s=%s; expires=%s";
return String.format(fmt, n, v, e);
}
public static String getHTTPTime(int days) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar.add(Calendar.DAY_OF_MONTH, days);
return dateFormat.format(calendar.getTime());
}
}
/**
* Provides rudimentary support for cookies.
* Doesn't support 'path', 'secure' nor 'httpOnly'.
* Feel free to improve it and/or add unsupported features.
*
* @author LordFokas
*/
public class CookieHandler implements Iterable<String> {
private HashMap<String, String> cookies = new HashMap<String, String>();
private ArrayList<Cookie> queue = new ArrayList<Cookie>();
public CookieHandler(Map<String, String> httpHeaders) {
String raw = httpHeaders.get("cookie");
if (raw != null) {
String[] tokens = raw.split(";");
for (String token : tokens) {
String[] data = token.trim().split("=");
if (data.length == 2) {
cookies.put(data[0], data[1]);
}
}
}
}
@Override public Iterator<String> iterator() {
return cookies.keySet().iterator();
}
/**
* Read a cookie from the HTTP Headers.
*
* @param name The cookie's name.
* @return The cookie's value if it exists, null otherwise.
*/
public String read(String name) {
return cookies.get(name);
}
/**
* Sets a cookie.
*
* @param name The cookie's name.
* @param value The cookie's value.
* @param expires How many days until the cookie expires.
*/
public void set(String name, String value, int expires) {
queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires)));
}
public void set(Cookie cookie) {
queue.add(cookie);
}
/**
* Set a cookie with an expiration date from a month ago, effectively deleting it on the client side.
*
* @param name The cookie name.
*/
public void delete(String name) {
set(name, "-delete-", -30);
}
/**
* Internally used by the webserver to add all queued cookies into the Response's HTTP Headers.
*
* @param response The Response object to which headers the queued cookies will be added.
*/
public void unloadQueue(Response response) {
for (Cookie cookie : queue) {
response.addHeader("Set-Cookie", cookie.getHTTPHeader());
}
}
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
5a158c1b8e891c2f008d7e17cc2aa0cdc57262ce | c7488ee14754450f0da3988a5aea6744df39dd57 | /app/src/main/java/ss/com/lbs/jingdong01/moudle/GetSouSuoShangPin.java | 892fd43c235559b62907b509e8ddd1477c0f682e | [] | no_license | afffa/jing | 6e8ac627588d43edac685518263393783bf1d9cd | c9fcfb4db7d1db1888d972f7d891181876060673 | refs/heads/master | 2020-03-11T03:22:02.517136 | 2018-04-16T12:40:43 | 2018-04-16T12:40:43 | 129,744,871 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 257 | java | package ss.com.lbs.jingdong01.moudle;
import ss.com.lbs.jingdong01.bean.SouSuoShangPinBean;
/**
* author:Created by WangZhiQiang on 2018/4/13.
*/
public interface GetSouSuoShangPin {
void getSouSuoShangPin(SouSuoShangPinBean souSuoShangPinBean);
}
| [
"1413137532@qq.com"
] | 1413137532@qq.com |
41d2b1b6721bf7d3253d03b88bd9be1669403c74 | 9b59189dba000dd6d4f30a45153c826e8b73e9a7 | /tastemap1-Jiyeong/src/main/java/com/daedong/tastemap/security/AuthenticationFacadeImpl.java | 0465c53b4021ebf972ffa490393779655bb3d4f3 | [] | no_license | TasteMap/tastemap1-Jiyeong | ff827ea5d3c15694b18f8f727d99387d3f685e09 | 039b9581fcf12aa1c4e3373c29ad236c9f924e51 | refs/heads/master | 2023-07-11T15:02:57.035016 | 2021-08-17T05:47:09 | 2021-08-17T05:47:09 | 394,112,289 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 890 | java | package com.daedong.tastemap.security;
import com.daedong.tastemap.security.model.CustomUserPrincipal;
import com.daedong.tastemap.user.model.UserEntity;
import org.springframework.stereotype.Component;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
@Component
public class AuthenticationFacadeImpl implements IAuthenticationFacade {
@Override
public UserEntity getLoginUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object result = auth.getPrincipal();
if(result instanceof String) {
return null;
}
CustomUserPrincipal userDetails= (CustomUserPrincipal) result;
return userDetails.getUser();
}
@Override
public int getLoginUserPk(){
return getLoginUser().getIuser();
}
}
| [
"81175088+Jiyeong-github@users.noreply.github.com"
] | 81175088+Jiyeong-github@users.noreply.github.com |
b79e1ece58a48d177bc918ca751283c494d4bb61 | 587e950234afaf8d296a6820063196eacd68348c | /swing1/MainFrame.java | dcd5a32058324400dfb5fcb21433260ef619cea2 | [] | no_license | kharekartik08/Application-form | ea1f3d6e3e6e802a89f15ac8fb02ff51453b2bdd | eec8562bd24140e05280aa8e311251e2c1aa8f1b | refs/heads/master | 2021-01-22T06:14:27.747863 | 2019-10-01T00:16:57 | 2019-10-01T00:16:57 | 102,287,608 | 0 | 1 | null | 2019-10-01T00:16:58 | 2017-09-03T19:04:40 | Java | UTF-8 | Java | false | false | 5,058 | java |
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import static java.awt.event.KeyEvent.VK_X;
import static java.util.Locale.filter;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileNameExtensionFilter;
@SuppressWarnings("serial")
public class MainFrame extends JFrame{
private JButton btn;
private TextPanel textPanel;
private Toolbar toolbar;
private FormPanel formPanel;
private JFileChooser fileChooser;
public MainFrame(){
super("Hello... Enter ur detail bitch");
btn = new JButton("Click Kar");
textPanel = new TextPanel();
toolbar= new Toolbar();
formPanel = new FormPanel();
fileChooser= new JFileChooser();
fileChooser.addChoosableFileFilter(new PersonFileFilter());
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF Documents", "pdf"));
fileChooser .addChoosableFileFilter(new FileNameExtensionFilter("MS Office Documents", "docx", "xlsx", "pptx"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));
setJMenuBar(createMenuBar());
toolbar.setTextPanel(textPanel);
setLayout(new BorderLayout());
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textPanel.appendText("Hello........\n");
}
});
formPanel.setFormListener(new FormListener(){
public void formEventOccurred (FormEvent e){
String name= e.getName();
String occupation=e.getOccupation();
int ageCat=e.getAgeCategory();
String empCat= e.getEmploymentCategory();
String tax=e.getTaxId();
boolean citizen= e.isIndianCitizen();
String gender=e.getGender();
char ch=e.getGender().charAt(0);
textPanel.appendText(name+" : "+occupation+" : "+ageCat+":"+empCat+":"+tax+":"+citizen+":"+ch+"\n");
}
});
add(toolbar,BorderLayout.NORTH);
add(btn,BorderLayout.SOUTH);
add(textPanel,BorderLayout.CENTER);
add(formPanel,BorderLayout.WEST);
setVisible(true);
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private JMenuBar createMenuBar(){
JMenuBar menuBar= new JMenuBar();
JMenu fileMenu= new JMenu("File");
JMenu windowMenu= new JMenu("Window");
JMenuItem exportDataItem= new JMenuItem("Export Data.");
JMenuItem importDataItem= new JMenuItem("Import Data.");
JMenuItem exitItem= new JMenuItem("Exit");
fileMenu.add(exportDataItem);
fileMenu.addSeparator();
fileMenu.add(importDataItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
importDataItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (fileChooser.showOpenDialog(MainFrame.this)==JFileChooser.APPROVE_OPTION){
System.out.println(fileChooser.getSelectedFile());
}
}
});
JMenu showMenu= new JMenu("Show");
JCheckBoxMenuItem showFormItem= new JCheckBoxMenuItem("Person From");
showFormItem.setSelected(true);
showMenu.add(showFormItem);
windowMenu.add(showMenu);
menuBar.add(fileMenu);
menuBar.add(windowMenu);
showFormItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem)ev.getSource();
formPanel.setVisible(menuItem.isSelected());
}
});
fileMenu.setMnemonic(KeyEvent.VK_F);
exitItem.setMnemonic(KeyEvent.VK_X);
exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,ActionEvent.CTRL_MASK));
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showInputDialog(MainFrame.this,"USER NAME MC","USERNAME POP_UP",JOptionPane.OK_OPTION|JOptionPane.INFORMATION_MESSAGE);
int action=JOptionPane.showConfirmDialog(MainFrame.this,"Bahar Jana Chahta h Kya Bhadwe??","Confirm Exit",JOptionPane.OK_CANCEL_OPTION);
if(action==JOptionPane.OK_OPTION)
System.exit(0);
}
});
return menuBar;
}
}
| [
"singhkartik098@gmail.com"
] | singhkartik098@gmail.com |
9423ee4d0b5901e06057c353db2ca67eb26c6cfb | 27c61b06d7c794e302d6ca53f9da7a4fd92cc287 | /app/src/main/java/com/dq/huibao/adapter/pintuan/PTChooseAdapter.java | f13f634dd34e420a60a6a98f2f2fb1817876488a | [] | no_license | jingangdan/DQHuiBao | 543c9c7754e81702ccee04245d1d47e84e124e1a | f26bd46bc98c5549e1ae5822c62760cddc61f4c7 | refs/heads/master | 2020-04-11T06:40:06.344733 | 2018-05-25T02:44:43 | 2018-05-25T02:44:43 | 107,844,464 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,021 | java | package com.dq.huibao.adapter.pintuan;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.dq.huibao.Interface.OnItemClickListener;
import com.dq.huibao.R;
import com.dq.huibao.bean.pintuan.PinTuanDetails;
import com.dq.huibao.utils.BaseRecyclerViewHolder;
import java.util.List;
//import com.dq.huibao.bean.goods.GoodsDetail;
//import com.dq.huibao.bean.goodsdetail.Items;
/**
* Description:
* Created by jingang on 2017/11/10.
*/
public class PTChooseAdapter extends RecyclerView.Adapter<PTChooseAdapter.MyViewHolder> {
private Context mContext;
private List<PinTuanDetails.DataBean.SpecBean.ItemsBean> itemList;
private OnItemClickListener mOnItemClickListener;
private int mSelect = -1;
public PTChooseAdapter(Context mContext, List<PinTuanDetails.DataBean.SpecBean.ItemsBean> itemList) {
this.mContext = mContext;
this.itemList = itemList;
}
public void setmOnItemClickListener(OnItemClickListener mOnItemClickListener) {
this.mOnItemClickListener = mOnItemClickListener;
}
/**
* 刷新方法
*
* @param positon
*/
public void changeSelected(int positon) {
if (positon != mSelect) {
mSelect = positon;
notifyDataSetChanged();
}
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder vh = new MyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_gd_choose, parent, false));
return vh;
}
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
if (mOnItemClickListener != null) {
//为ItemView设置监听器
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getLayoutPosition(); // 1
mOnItemClickListener.onItemClick(holder.itemView, position); // 2
}
});
}
//点击改变背景
if (mSelect == position) {
holder.name.setBackgroundResource(R.drawable.kuang_choose_red);
holder.name.setTextColor(Color.rgb(255, 255, 255));
} else {
holder.name.setBackgroundResource(R.drawable.kuang_choose_gary);
holder.name.setTextColor(Color.rgb(51, 51, 51));
}
holder.name.setText("" + itemList.get(position).getTitle());
}
@Override
public int getItemCount() {
return itemList.size();
}
public class MyViewHolder extends BaseRecyclerViewHolder {
private TextView name;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.tv_item_choose_name);
}
}
}
| [
"1290062806@qq.com"
] | 1290062806@qq.com |
b368cac604404c6b2ff81c127289ce994622eba5 | 0b949c5c930a97ec6b2d2ff4a8430cdc38401fba | /tags/SMSPopup v1.0.1/src/net/everythingandroid/smspopup/.svn/text-base/ManageNotification.java.svn-base | 6485f424c85efbf2cd0582df39c834d5e5909d37 | [] | no_license | KhalidElSayed/Android-smspopup | 4633176474643b6aa01f39f75993618f78d1ccf6 | 0f9e8070b27da1b9e5ec8a36d17e3b82eeaa341d | refs/heads/master | 2021-01-18T00:31:52.145270 | 2012-03-06T16:02:38 | 2012-03-06T16:02:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,567 | package net.everythingandroid.smspopup;
import java.util.ArrayList;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.StyleSpan;
/*
* This class handles the Notifications (sounds/vibrate/LED)
*/
public class ManageNotification {
public static final int NOTIFICATION_ALERT = 1337;
public static final int NOTIFICATION_TEST = 888;
public static final String defaultRingtone = Settings.System.DEFAULT_NOTIFICATION_URI.toString();
/*
* Show/play the notification given a SmsMmsMessage and a notification ID
* (really just NOTIFICATION_ALERT for the main alert and NOTIFICATION_TEST
* for the test notification from the preferences screen)
*/
public static void show(Context context, SmsMmsMessage message, int notif) {
notify(context, message, false, notif);
}
/*
* Default to NOTIFICATION_ALERT if notif is left out
*/
public static void show(Context context, SmsMmsMessage message) {
notify(context, message, false, NOTIFICATION_ALERT);
}
/*
* Only update the notification given the SmsMmsMessage (ie. do not play the
* vibrate/sound, just update the text).
*/
public static void update(Context context, SmsMmsMessage message) {
// TODO: can I just use Notification.setLatestEventInfo() to update instead?
if (message != null) {
if (message.getUnreadCount() > 0) {
notify(context, message, true, NOTIFICATION_ALERT);
return;
}
}
// TODO: Should reply flag be set to true?
ManageNotification.clearAll(context, true);
}
/*
* The main notify method, this thing is WAY too long. Needs to be broken up.
*/
private static void notify(Context context, SmsMmsMessage message, boolean onlyUpdate, int notif) {
ManagePreferences mPrefs = new ManagePreferences(context, message.getContactId());
AudioManager AM = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
// Fetch info from the message object
int unreadCount = message.getUnreadCount();
String messageBody = message.getMessageBody();
String contactName = message.getContactName();
long timestamp = message.getTimestamp();
// Check if there are unread messages and if notifications are enabled -
// if not, we're done :)
if (unreadCount > 0
&& mPrefs.getBoolean(R.string.pref_notif_enabled_key, R.string.pref_notif_enabled_default,
SmsPopupDbAdapter.KEY_ENABLED_NUM)) {
// Make sure the NotificationManager is created
// createNM(context);
NotificationManager myNM =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Get some preferences: vibrate and vibrate_pattern prefs
boolean vibrate =
mPrefs.getBoolean(R.string.pref_vibrate_key, R.string.pref_vibrate_default,
SmsPopupDbAdapter.KEY_VIBRATE_ENABLED_NUM);
String vibrate_pattern_raw =
mPrefs.getString(R.string.pref_vibrate_pattern_key,
R.string.pref_vibrate_pattern_default, SmsPopupDbAdapter.KEY_VIBRATE_PATTERN_NUM);
String vibrate_pattern_custom_raw =
mPrefs.getString(R.string.pref_vibrate_pattern_custom_key,
R.string.pref_vibrate_pattern_default,
SmsPopupDbAdapter.KEY_VIBRATE_PATTERN_CUSTOM_NUM);
// Get LED preferences
boolean flashLed =
mPrefs.getBoolean(R.string.pref_flashled_key, R.string.pref_flashled_default,
SmsPopupDbAdapter.KEY_LED_ENABLED_NUM);
String flashLedCol =
mPrefs.getString(R.string.pref_flashled_color_key, R.string.pref_flashled_color_default,
SmsPopupDbAdapter.KEY_LED_COLOR_NUM);
String flashLedColCustom =
mPrefs.getString(R.string.pref_flashled_color_custom_key,
R.string.pref_flashled_color_default, SmsPopupDbAdapter.KEY_LED_COLOR_NUM_CUSTOM);
String flashLedPattern =
mPrefs.getString(R.string.pref_flashled_pattern_key,
R.string.pref_flashled_pattern_default, SmsPopupDbAdapter.KEY_LED_PATTERN_NUM);
String flashLedPatternCustom =
mPrefs.getString(R.string.pref_flashled_pattern_custom_key,
R.string.pref_flashled_pattern_default, SmsPopupDbAdapter.KEY_LED_PATTERN_NUM_CUSTOM);
// The default system ringtone
// ("content://settings/system/notification_sound")
// String defaultRingtone =
// Settings.System.DEFAULT_NOTIFICATION_URI.toString();
// Try and parse the user ringtone, use the default if it fails
Uri alarmSoundURI =
Uri.parse(mPrefs.getString(R.string.pref_notif_sound_key, defaultRingtone,
SmsPopupDbAdapter.KEY_RINGTONE_NUM));
if (Log.DEBUG) Log.v("Sounds URI = " + alarmSoundURI.toString());
// The notification title, sub-text and text that will scroll
String contentTitle;
String contentText;
SpannableString scrollText;
// The default intent when the notification is clicked (Inbox)
Intent smsIntent = SmsPopupUtils.getSmsIntent();
// See if user wants some privacy
boolean privacyMode =
mPrefs.getBoolean(R.string.pref_privacy_key, R.string.pref_privacy_default);
// If we're updating the notification, do not set the ticker text
if (onlyUpdate) {
scrollText = null;
} else {
// If we're in privacy mode and the keyguard is on then just display
// the name of the person, otherwise scroll the name and message
if (privacyMode && ManageKeyguard.inKeyguardRestrictedInputMode()) {
scrollText =
new SpannableString(context.getString(R.string.notification_scroll_privacy,
contactName));
} else {
scrollText =
new SpannableString(context.getString(R.string.notification_scroll, contactName,
messageBody));
// Set contact name as bold
scrollText.setSpan(new StyleSpan(Typeface.BOLD), 0, contactName.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
// If more than one message waiting ...
if (unreadCount > 1) {
contentTitle = context.getString(R.string.notification_multiple_title);
contentText = context.getString(R.string.notification_multiple_text, unreadCount);
// smsIntent = SMSPopupUtils.getSmsIntent();
} else { // Else 1 message, set text and intent accordingly
contentTitle = contactName;
contentText = messageBody;
smsIntent = message.getReplyIntent();
}
/*
* Ok, let's create our Notification object and set up all its parameters.
*/
// Set the icon, scrolling text and timestamp
Notification notification =
new Notification(R.drawable.stat_notify_sms, scrollText, timestamp);
// Set auto-cancel flag
notification.flags = Notification.FLAG_AUTO_CANCEL;
// Set audio stream to ring
// notification.audioStreamType = AudioManager.STREAM_RING;
notification.audioStreamType = Notification.STREAM_DEFAULT;
/*
* If this is a new notification (not updating a notification) then set
* LED, vibrate and ringtone to fire
*/
if (!onlyUpdate) {
// Set up LED pattern and color
if (flashLed) {
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
/*
* Set up LED blinking pattern
*/
int[] led_pattern = null;
if (context.getString(R.string.pref_custom_val).equals(flashLedPattern)) {
led_pattern = parseLEDPattern(flashLedPatternCustom);
} else {
led_pattern = parseLEDPattern(flashLedPattern);
}
// Set to default if there was a problem
if (led_pattern == null) {
led_pattern =
parseLEDPattern(context.getString(R.string.pref_flashled_pattern_default));
}
notification.ledOnMS = led_pattern[0];
notification.ledOffMS = led_pattern[1];
/*
* Set up LED color
*/
// Check if a custom color is set
if (context.getString(R.string.pref_custom_val).equals(flashLedCol)) {
flashLedCol = flashLedColCustom;
}
// Default in case the parse fails
int col = Color.parseColor(context.getString(R.string.pref_flashled_color_default));
// Try and parse the color
if (flashLedCol != null) {
try {
col = Color.parseColor(flashLedCol);
} catch (IllegalArgumentException e) {
// No need to do anything here
}
}
notification.ledARGB = col;
}
/*
* Set up vibrate pattern
*/
TelephonyManager TM = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
int callState = TM.getCallState();
// If vibrate is ON, or if phone is set to vibrate AND the phone is not on a call
if ((vibrate || AudioManager.RINGER_MODE_VIBRATE == AM.getRingerMode())
&& callState != TelephonyManager.CALL_STATE_OFFHOOK) {
long[] vibrate_pattern = null;
if (context.getString(R.string.pref_custom_val).equals(vibrate_pattern_raw)) {
vibrate_pattern = parseVibratePattern(vibrate_pattern_custom_raw);
} else {
vibrate_pattern = parseVibratePattern(vibrate_pattern_raw);
}
if (vibrate_pattern != null) {
notification.vibrate = vibrate_pattern;
} else {
notification.defaults = Notification.DEFAULT_VIBRATE;
}
}
// If in a call, start the media player
if (callState == TelephonyManager.CALL_STATE_OFFHOOK
&& AM.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {
// TODO: make this an option
// if (Log.DEBUG) Log.v("User on a call, running own mediaplayer");
// MediaPlayer mMediaPlayer = MediaPlayer.create(context, alarmSoundURI);
// mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// mMediaPlayer.setLooping(false);
// mMediaPlayer.start();
} else { // Otherwise just use built in notifications
// Notification sound
notification.sound = alarmSoundURI;
}
}
// Set the PendingIntent if the status message is clicked
PendingIntent notifIntent = PendingIntent.getActivity(context, 0, smsIntent, 0);
// Set the messages that show when the status bar is pulled down
notification.setLatestEventInfo(context, contentTitle, contentText, notifIntent);
// Set number of events that this notification signifies (unread messages)
if (unreadCount > 1) {
notification.number = unreadCount;
}
// Set intent to execute if the "clear all" notifications button is
// pressed -
// basically stop any future reminders.
Intent deleteIntent = new Intent(new Intent(context, ReminderReceiver.class));
deleteIntent.setAction(Intent.ACTION_DELETE);
PendingIntent pendingDeleteIntent = PendingIntent.getBroadcast(context, 0, deleteIntent, 0);
notification.deleteIntent = pendingDeleteIntent;
// Seems this is needed for the .number value to take effect
// on the Notification
myNM.cancelAll();
mPrefs.close();
// Finally: run the notification!
if (Log.DEBUG) Log.v("*** Notify running ***");
myNM.notify(notif, notification);
}
}
public static void clear(Context context) {
clear(context, NOTIFICATION_ALERT);
}
public static void clear(Context context, int notif) {
NotificationManager myNM =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
myNM.cancel(notif);
// createNM(context);
// if (myNM != null) {
// Log.v("Notification cleared");
// myNM.cancel(notif);
// }
}
public static void clearAll(Context context, boolean reply) {
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(context);
if (reply
|| myPrefs.getBoolean(context.getString(R.string.pref_markread_key), Boolean
.parseBoolean(context.getString(R.string.pref_markread_default)))) {
NotificationManager myNM =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
myNM.cancelAll();
// createNM(context);
//
// if (myNM != null) {
// myNM.cancelAll();
// Log.v("All notifications cleared");
// }
}
}
public static void clearAll(Context context) {
clearAll(context, true);
}
/*
* Parse the user provided custom vibrate pattern into a long[]
*/
// TODO: tidy this up
public static long[] parseVibratePattern(String stringPattern) {
ArrayList<Long> arrayListPattern = new ArrayList<Long>();
Long l;
if (stringPattern == null) return null;
String[] splitPattern = stringPattern.split(",");
int VIBRATE_PATTERN_MAX_SECONDS = 60000;
int VIBRATE_PATTERN_MAX_PATTERN = 100;
for (int i = 0; i < splitPattern.length; i++) {
try {
l = Long.parseLong(splitPattern[i].trim());
} catch (NumberFormatException e) {
return null;
}
if (l > VIBRATE_PATTERN_MAX_SECONDS) {
return null;
}
arrayListPattern.add(l);
}
// TODO: can i just cast the whole ArrayList into long[]?
int size = arrayListPattern.size();
if (size > 0 && size < VIBRATE_PATTERN_MAX_PATTERN) {
long[] pattern = new long[size];
for (int i = 0; i < pattern.length; i++) {
pattern[i] = arrayListPattern.get(i);
}
return pattern;
}
return null;
}
public static int[] parseLEDPattern(String stringPattern) {
int[] arrayPattern = new int[2];
int on, off;
if (stringPattern == null) return null;
String[] splitPattern = stringPattern.split(",");
if (splitPattern.length != 2) return null;
int LED_PATTERN_MIN_SECONDS = 0;
int LED_PATTERN_MAX_SECONDS = 60000;
try {
on = Integer.parseInt(splitPattern[0]);
} catch (NumberFormatException e) {
return null;
}
try {
off = Integer.parseInt(splitPattern[1]);
} catch (NumberFormatException e) {
return null;
}
if (on >= LED_PATTERN_MIN_SECONDS && on <= LED_PATTERN_MAX_SECONDS
&& off >= LED_PATTERN_MIN_SECONDS && off <= LED_PATTERN_MAX_SECONDS) {
arrayPattern[0] = on;
arrayPattern[1] = off;
return arrayPattern;
}
return null;
}
}
| [
"chema.larrea@gmail.com"
] | chema.larrea@gmail.com | |
f887aa48f34cd5a4bcef7ba729c2cbb6f5622e65 | 59fcb91c15af118e21027486e03681efc7d9f337 | /src/main/java/com/carlos/poc/servicios/DocumentoServicio.java | ca5b6ea32da65b93edc79083ca332e576a6cdb60 | [] | no_license | Carlos-Diaz-DB/huellaRepo | de96f4f486a2586c82c1109e8d1301f1e9ef0851 | 8b23f5cdd3d053b3fca07ed8a3484aecdfed988c | refs/heads/master | 2021-06-21T19:00:31.884609 | 2019-09-24T04:12:31 | 2019-09-24T04:12:31 | 210,504,768 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 463 | java | package com.carlos.poc.servicios;
import java.util.List;
import com.carlos.poc.entidades.Documento;
public interface DocumentoServicio {
public Documento obtenerPorId(int doc);
public List<Documento> listarDocumentosDeUser(int userId);
public List<Documento> listar();
public boolean agregar(Documento doc);
public boolean guardarFile(String doc);
public boolean actualizar(Documento doc, boolean editar);
public boolean borrar(Documento doc);
}
| [
"carloscds2346@gmail.com"
] | carloscds2346@gmail.com |
a651c056d5c4d95c949ca8b809cd0011edbddd5f | 7114b555ecfc26d6ab0b7257104df1d2475bf712 | /autoconfigure/src/main/java/info/developerblog/spring/cloud/marathon/MarathonProperties.java | ea19061a5e2ae8f0cc61a3934f4bdce90a511214 | [
"MIT"
] | permissive | gitter-badger/spring-cloud-marathon | af15712927c141bec82e42a6074bcaedbea53126 | aa7b50a38287f654abe2c5f803689cb940a1700c | refs/heads/master | 2021-01-17T19:58:36.100366 | 2016-07-07T16:08:06 | 2016-07-07T16:08:06 | 62,904,730 | 0 | 0 | null | 2016-07-08T17:09:46 | 2016-07-08T17:09:45 | null | UTF-8 | Java | false | false | 513 | java | package info.developerblog.spring.cloud.marathon;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import javax.validation.constraints.NotNull;
/**
* Created by aleksandr on 07.07.16.
*/
@ConfigurationProperties("spring.cloud.marathon")
@Data
public class MarathonProperties {
@NotNull
private String scheme = "http";
@NotNull
private String host = "localhost";
@NotNull
private int port = 8080;
private boolean enabled = true;
}
| [
"aatarasoff@gmail.com"
] | aatarasoff@gmail.com |
f8f7abcc689d6127e8256f54f270f4faa6691bb1 | b3a02d5f1f60cd584fbb6da1b823899607693f63 | /07_OOP_Advanced/15_DependencyInversionAndInterfaceSegregation_lab/src/p04_recharge/models/Robot.java | 595a8048a97c6c585b334d002e0ebe1ecf8dfb4b | [
"MIT"
] | permissive | akkirilov/SoftUniProject | 20bf0543c9aaa0a33364daabfddd5f4c3e400ba2 | 709d2d1981c1bb6f1d652fe4101c1693f5afa376 | refs/heads/master | 2021-07-11T02:53:18.108275 | 2018-12-04T20:14:19 | 2018-12-04T20:14:19 | 79,428,334 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 818 | java | package p04_recharge.models;
import p04_recharge.interfaces.Rechargeable;
public class Robot extends Worker implements Rechargeable {
private int capacity;
private int currentPower;
public Robot(String id, int capacity) {
super(id);
this.capacity = capacity;
}
public int getCapacity() {
return capacity;
}
public int getCurrentPower() {
return currentPower;
}
public void setCurrentPower(int currentPower) {
this.currentPower = currentPower;
}
public void work(int hours) {
if (hours > this.currentPower) {
hours = currentPower;
}
super.work(hours);
this.currentPower -= hours;
}
@Override
public void recharge() {
this.currentPower = this.capacity;
}
}
| [
"akkirilov@mail.bg"
] | akkirilov@mail.bg |
110342e54839091cd1ab6e9d8cabeb400531864b | 605ef0462c791f979745d43f13d154bf21ad82e9 | /src/Server/GreetingServer.java | dc6c6b06091120c23823dbcd54c96258c6a1d647 | [] | no_license | zychu312/DatabaseServer | 3b94751d5b1ea63c0df163a5b59474b591059510 | fceb424455ee8254d6f158522fbca716383d8acc | refs/heads/master | 2021-01-13T02:31:20.815245 | 2015-04-14T23:21:37 | 2015-04-14T23:21:37 | 33,962,061 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,043 | java | package Server;
import java.net.*;
import java.util.List;
import java.io.*;
public class GreetingServer extends Thread
{
private ServerSocket serverSocket;
ServerStatCalculator serverStatCalculator = new ServerStatCalculator();
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(20000);
serverStatCalculator.Calculate();
}
public void run()
{
ServerStat serverStat = new ServerStat(0,0,0);
ServerDB b = new ServerDB();
while(true)
{
try
{
Socket server = serverSocket.accept();
DataInputStream in = new DataInputStream(server.getInputStream());
serverStat.whereWasPlayer = in.readInt();
serverStat.whereHittedBall = in.readInt();
System.out.println(serverStat.whereWasPlayer);
System.out.println(serverStat.whereHittedBall);
b.insertServerStat(serverStat.whereWasPlayer,serverStat.whereHittedBall);
DataOutputStream out = new DataOutputStream(server.getOutputStream());
for(int i=0; i<80; i++)
{
out.writeDouble(serverStatCalculator.Stats[i]);
}
server.close();
}
catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}
catch(IOException e)
{
e.printStackTrace();
break;
}
}
List<ServerStat> ServerStats = b.selectServerStats();
System.out.println("Lista rekordow: ");
for(ServerStat c: ServerStats)
System.out.println(c);
b.closeConnection();
}
public static void main(String [] args)
{
int port = 3555;
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
} | [
"zychu312@gmail.com"
] | zychu312@gmail.com |
b1122ea2b38b3ec2ff2599c16d5824c201b0f14d | ab97db27dc4dc5fb35c37b2878e6b9ba470fff97 | /src/main/java/de/blau/android/util/StringWithDescription.java | 842a9c7a9a0a76eb195449a8d25da624efa84293 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | comradekingu/osmeditor4android | b711578a45ce4710cf0efb6c0a3af48a1cd2bdd6 | a43a7ad0a5081aabfaf8aaac6282172951f1c6a5 | refs/heads/master | 2020-04-03T04:33:24.225897 | 2018-10-26T19:49:34 | 2018-10-26T19:49:34 | 155,017,200 | 0 | 0 | NOASSERTION | 2018-10-27T23:00:23 | 2018-10-27T23:00:22 | null | UTF-8 | Java | false | false | 4,303 | java | package de.blau.android.util;
import java.io.Serializable;
import java.text.Collator;
import java.util.Comparator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import de.blau.android.presets.ValueWithCount;
@SuppressWarnings("NullableProblems")
public class StringWithDescription implements Comparable<StringWithDescription>, Serializable {
private static final long serialVersionUID = 1L;
private final String value;
private String description;
/**
* Construct a new instance
*
* @param value the value
*/
public StringWithDescription(@NonNull final String value) {
this.value = value;
}
/**
* Construct a new instance
*
* @param value the value
* @param description the description of the value
*/
public StringWithDescription(@NonNull final String value, @Nullable final String description) {
this.value = value;
this.description = description;
}
/**
* Construct a new instance from object of a known type
*
* @param o one of StringWithDescription, ValueWIihCOunt or String
*/
public StringWithDescription(@NonNull Object o) {
if (o instanceof ValueWithCount) {
value = ((ValueWithCount) o).getValue();
description = ((ValueWithCount) o).getDescription();
} else if (o instanceof StringWithDescription) {
value = ((StringWithDescription) o).getValue();
description = ((StringWithDescription) o).getDescription();
} else if (o instanceof String) {
value = (String) o;
description = value;
} else {
value = "";
description = value;
}
}
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @return the description can be null
*/
@Nullable
public String getDescription() {
return description;
}
/**
* Set the description field
*
* @param description the description
*/
public void setDescription(@Nullable String description) {
this.description = description;
}
@Override
public String toString() {
return value + (description != null ? (value == null || "".equals(value) ? "" : " - ") + description : "");
}
@Override
public int compareTo(@NonNull StringWithDescription s) {
return value.compareTo(s.getValue());
}
/**
* Check for equality with a String value
*
* This is likely bad style
*
* @param s String to compare with
* @return true if the value of this object is the same as s
*/
public boolean equals(String s) {
return this.value.equals(s);
}
@Override
public boolean equals(Object o) {
return o != null && (o instanceof StringWithDescription && this == (StringWithDescription) o
|| (this.value.equals(((StringWithDescription) o).value) && ((this.description == null && ((StringWithDescription) o).description == null)
|| (this.description != null && this.description.equals(((StringWithDescription) o).description)))));
}
@Override
public int hashCode() {
int result = 1;
result = 37 * result + (value == null ? 0 : value.hashCode());
result = 37 * result + (description == null ? 0 : description.hashCode());
return result;
}
/**
*
* @author simon
*
*/
public static class LocaleComparator implements Comparator<StringWithDescription> {
Collator defaultLocaleCollator = Collator.getInstance();
@Override
public int compare(StringWithDescription lhs, StringWithDescription rhs) {
String lhsDescription = lhs.getDescription();
if (lhsDescription == null || "".equals(lhsDescription)) {
lhsDescription = lhs.getValue();
}
String rhsDescription = rhs.getDescription();
if (rhsDescription == null || "".equals(rhsDescription)) {
rhsDescription = rhs.getValue();
}
return defaultLocaleCollator.compare(lhsDescription, rhsDescription);
}
}
}
| [
"simon@poole.ch"
] | simon@poole.ch |
f1588bf042805f7798146a695a87e4a337bd7a09 | 6af23ba996c38451b992504fd1afbcfe949539f4 | /src/main/java/fi/haagahelia/serverprogramming/OnSiteIntervention/domain/RepositoryConfiguration.java | 82aadf95d819e1b4697093f54f282a5b482c1570 | [] | no_license | kevinberret/OnSiteIntervention | 84e1a58bb400886aa343878506785f34029be7d7 | dfb604dd948511ddbd27c29b89541a32fa235396 | refs/heads/master | 2020-04-04T18:59:47.018423 | 2018-12-01T18:15:06 | 2018-12-01T18:15:06 | 156,188,100 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 404 | java | package fi.haagahelia.serverprogramming.OnSiteIntervention.domain;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RepositoryConfiguration {
public RepositoryConfiguration(){
super();
}
@Bean
EmployeeEventHandler authorEventHandler() {
return new EmployeeEventHandler();
}
} | [
"berret.kevin@gmail.com"
] | berret.kevin@gmail.com |
ad02c84f588a538c2308130a147305efefaa6a3f | f0826e519e3c29b9150c7fac8daad07544ebd305 | /Tutorial/src/basics.java | c907ff2b9a548f8f8db3f92765ad565a24982eaa | [] | no_license | trybuskrzysztof/wlasne_projekty | 3ae7f81fb46a05a51013ca602b07c3bb6526f877 | 519e26eb47bbe8bc0115ee54ab30cd6011fb9ae2 | refs/heads/master | 2020-04-09T04:40:56.993213 | 2018-12-02T19:17:49 | 2018-12-02T19:17:49 | 160,031,929 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 356 | java | import java.net.MalformedURLException;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
public class basics extends base{
public static void main(String[] args) throws MalformedURLException {
// TODO Auto-generated method stub
AndroidDriver<AndroidElement> driver = Capabilities();
}
}
| [
"trybuskrzysztof@gmail.com"
] | trybuskrzysztof@gmail.com |
ef404ceb020dce646f2cbbb0fbcce52ea2e56795 | dfd7e70936b123ee98e8a2d34ef41e4260ec3ade | /analysis/reverse-engineering/decompile-fitts-20191031-2200/sources/okhttp3/Call.java | d759594bcbcde23e751f71b2cdc2fd0251701f22 | [
"Apache-2.0"
] | permissive | skkuse-adv/2019Fall_team2 | 2d4f75bc793368faac4ca8a2916b081ad49b7283 | 3ea84c6be39855f54634a7f9b1093e80893886eb | refs/heads/master | 2020-08-07T03:41:11.447376 | 2019-12-21T04:06:34 | 2019-12-21T04:06:34 | 213,271,174 | 5 | 5 | Apache-2.0 | 2019-12-12T09:15:32 | 2019-10-07T01:18:59 | Java | UTF-8 | Java | false | false | 391 | java | package okhttp3;
import java.io.IOException;
public interface Call extends Cloneable {
public interface Factory {
Call newCall(Request request);
}
void cancel();
Call clone();
void enqueue(Callback callback);
Response execute() throws IOException;
boolean isCanceled();
boolean isExecuted();
Request request();
}
| [
"33246398+ajid951125@users.noreply.github.com"
] | 33246398+ajid951125@users.noreply.github.com |
502d49348aec89a1f3ae071749bcfbd46bbd479a | dafc6a3e387e3f3d3e7f22f12a4ea34042fd9189 | /backend/src/main/java/io/github/t73liu/model/EncryptionType.java | f4db30664023b0bcfe946253d0a48804c4a096d5 | [
"MIT"
] | permissive | logan2013/trading-bot | 572bbcd2c7274394521c2258debc1c4daf8a57b2 | fc2ab497e7f30a8bfc657f20d0c3e2732cae5c85 | refs/heads/master | 2020-04-07T15:05:31.299567 | 2018-08-09T17:10:01 | 2018-08-09T17:10:01 | 158,472,850 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 359 | java | package io.github.t73liu.model;
public enum EncryptionType {
HMAC_SHA256("HmacSHA256"), // Quadriga
HMAC_SHA384("HmacSHA384"), // Bitfinex
HMAC_SHA512("HmacSHA512"); // Poloniex, Bittrex
private final String name;
EncryptionType(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
| [
"t73liu@gmail.com"
] | t73liu@gmail.com |
0b4c84be783693897931b8e6d27d5b186ab6641e | 48556d0de2295c44d9f94ede7f0c94df8b9cc881 | /spring-boot/src/main/java/cn/edu/cqive/persistence/SampleDao.java | 8ba0423f1a5b78fc78ff6367dfa05d513ff21ca4 | [] | no_license | zhengsh/guice-learn | f9c9fdacd4819a66d0e314540b67dac843722868 | be089060f8e2385945fbe682de548549ff035a26 | refs/heads/master | 2022-11-25T12:59:50.091915 | 2020-08-07T12:16:38 | 2020-08-07T12:16:38 | 285,787,329 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 350 | java | package cn.edu.cqive.persistence;
import org.springframework.stereotype.Component;
@Component
public class SampleDao {
public void save(String data) {
System.out.println(data + " saved.");
}
public String getPersonData(String name) {
System.out.println("Getting person data for: " + name);
return name;
}
}
| [
"zhengshaohong123"
] | zhengshaohong123 |
0e958b10ca1288463612531b95f0957435943e1b | 42f87bf9a2f6a9333d2f37ca7e492f6110426599 | /aws/src/main/java/awspra/aws/domain/entity/BoardEntity.java | 71ba730cee4b8f9a49fc0f2df77cf92393535677 | [] | no_license | gawaine6/aws-test | fdb01e88c2bd1f33e45f42c72ccab3fd584f70a0 | c738fe3d05df03652eb20e193bd8f847aa62f4bb | refs/heads/master | 2023-03-21T08:08:14.411604 | 2021-03-12T07:00:12 | 2021-03-12T07:00:12 | 342,551,911 | 0 | 0 | null | 2021-03-11T05:42:57 | 2021-02-26T11:14:37 | Java | UTF-8 | Java | false | false | 1,049 | java | //package awspra.aws.domain.entity;
//
//import lombok.Builder;
//import lombok.Getter;
//import lombok.NoArgsConstructor;
//
//import javax.persistence.*;
//
//@NoArgsConstructor
//// 디폴트 생성자 추가
//@Getter
//// 모든 필드에 getter 자동생성, getter와 setter 모두 해결해주는 Data도 있음
//@Entity
//// 객체를 테이블과 매핑할 엔티티라고 jpa에 알려주는 역할
//@Table
//// 테이블 정보 명시
//public class BoardEntity {
//
// @Id
// @GeneratedValue(strategy = GenerationType.SEQUENCE)
// private Long id;
//
// @Column(length = 10, nullable = false)
// private String writer;
//
// @Column(length = 100, nullable = false)
// private String title;
//
// @Column(columnDefinition = "text", nullable = false)
// private String content;
//
// @Builder
// public BoardEntity(Long id, String writer, String title, String content) {
// this.id = id;
// this.writer = writer;
// this.title = title;
// this.content = content;
// }
//}
| [
"50446718+gawaine6@users.noreply.github.com"
] | 50446718+gawaine6@users.noreply.github.com |
96d46fb9ef8de9e1a55d4f7c479506c61b671dc6 | d72a2a7f6bc7b20b4c3f567d5f148236a95b95f5 | /src/main/java/com/ajiatech/mapper/AjiaItemCatMapper.java | d1b8e07e6a8dc20568e359f0479fac0b4e95b836 | [] | no_license | yinzhigang12/framework-springmvc | c5b8e3043b0306eb369568cac88b3ba4f3f1f9e2 | 5275db8557cacb8c9c021f4ab8942eb49860365f | refs/heads/master | 2021-01-23T02:16:13.612731 | 2017-09-05T05:42:15 | 2017-09-05T05:42:15 | 102,438,894 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 895 | java | package com.ajiatech.mapper;
import com.ajiatech.pojo.AjiaItemCat;
import com.ajiatech.pojo.AjiaItemCatExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface AjiaItemCatMapper {
long countByExample(AjiaItemCatExample example);
int deleteByExample(AjiaItemCatExample example);
int deleteByPrimaryKey(Long id);
int insert(AjiaItemCat record);
int insertSelective(AjiaItemCat record);
List<AjiaItemCat> selectByExample(AjiaItemCatExample example);
AjiaItemCat selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") AjiaItemCat record, @Param("example") AjiaItemCatExample example);
int updateByExample(@Param("record") AjiaItemCat record, @Param("example") AjiaItemCatExample example);
int updateByPrimaryKeySelective(AjiaItemCat record);
int updateByPrimaryKey(AjiaItemCat record);
} | [
"yinzhigang12@hotmail.com"
] | yinzhigang12@hotmail.com |
34829b4ad96e41eebd18a194993e4b48dd562d52 | a0ba2c1533f80b30de5d4d7606a732a69daf540f | /_mvp/src/main/java/com/hymane/emmm/mvp/BaseModelImpl.java | ab3a0cbc914fa61fd1012f812fc701132db67eff | [
"MIT"
] | permissive | hymanme/Emmm | e5ca3dfe521e6d65b7c63203b851a4cce9a32434 | 6db5d209d42d891cba65bad619d7e9e84e08289e | refs/heads/master | 2020-04-08T22:27:35.746751 | 2019-02-12T08:22:46 | 2019-02-12T08:22:46 | 159,788,034 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 487 | java | package com.hymane.emmm.mvp;
import java.util.HashMap;
/**
* Author :hymane
* Email :hymanmee@gmail.com
* Create at 2018/11/14
* Description:Model 层基类,处理一些公共的业务逻辑,
* 具体业务Model可继承本基类。
*/
public class BaseModelImpl implements IBaseContract.Model {
/***
* 创建一个map存放请求参数
* @return HashMap
*/
protected HashMap<String, Object> newParams() {
return new HashMap<>();
}
}
| [
"lianghaihuang@ctrip.com"
] | lianghaihuang@ctrip.com |
6be04a761734b2c4e42ab2ef7f7f455969fdda16 | f69ee54ebb1943a4a74787d3a91126d554d92141 | /JavaUp/FirstWeb/src/com/filter/utils/CookieUtils.java | e78278354cb80ccb2041260573948d89f56cd3cc | [] | no_license | xymjhome/JavaCode | 657205422042028469d21fd79a154f351fee7f12 | 2359af77b05d5a185f856ed817f3bc71cbfdb959 | refs/heads/master | 2021-05-13T19:42:07.396491 | 2019-03-10T14:45:29 | 2019-03-10T14:45:29 | 116,897,678 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 502 | java | package com.filter.utils;
import javax.servlet.http.Cookie;
/**
* Created by Administrator on 2018/1/20 0020.
*/
public class CookieUtils {
public static Cookie getCookieByName(String name, Cookie[] cookies){
if (cookies != null && name != null) {
for (Cookie c : cookies) {
System.out.println(c.getName());
if (name.equals(c.getName())) {
return c;
}
}
}
return null;
}
}
| [
"xiaoming@qq.com"
] | xiaoming@qq.com |
d7bff3ceab6940f5a2bf937f99dbfda98e4f197c | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/7/7_d185cea992b0ce9b5966ec09dc1ca71806f728ba/EditCallGroup/7_d185cea992b0ce9b5966ec09dc1ca71806f728ba_EditCallGroup_t.java | 183dbc78ed25be7040585cedd4d70dda7797f6e4 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 5,292 | java | /*
*
*
* Copyright (C) 2005 SIPfoundry Inc.
* Licensed by SIPfoundry under the LGPL license.
*
* Copyright (C) 2005 Pingtel Corp.
* Licensed to SIPfoundry under a Contributor Agreement.
*
* $
*/
package org.sipfoundry.sipxconfig.site.admin;
import java.util.Collection;
import org.apache.tapestry.AbstractComponent;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.callback.ICallback;
import org.apache.tapestry.callback.PageCallback;
import org.apache.tapestry.event.PageEvent;
import org.apache.tapestry.event.PageRenderListener;
import org.apache.tapestry.html.BasePage;
import org.apache.tapestry.valid.IValidationDelegate;
import org.sipfoundry.sipxconfig.admin.callgroup.CallGroup;
import org.sipfoundry.sipxconfig.admin.callgroup.CallGroupContext;
import org.sipfoundry.sipxconfig.components.StringSizeValidator;
import org.sipfoundry.sipxconfig.components.TapestryUtils;
public abstract class EditCallGroup extends BasePage implements PageRenderListener {
public static final String PAGE = "EditCallGroup";
public abstract CallGroupContext getCallGroupContext();
public abstract Integer getCallGroupId();
public abstract void setCallGroupId(Integer id);
public abstract CallGroup getCallGroup();
public abstract void setCallGroup(CallGroup callGroup);
public abstract ICallback getCallback();
public abstract void setCallback(ICallback callback);
public void pageBeginRender(PageEvent event_) {
CallGroup callGroup = getCallGroup();
if (null != callGroup) {
return;
}
Integer id = getCallGroupId();
if (null != id) {
CallGroupContext context = getCallGroupContext();
callGroup = context.loadCallGroup(id);
} else {
callGroup = new CallGroup();
}
setCallGroup(callGroup);
if (null == getCallback()) {
setCallback(new PageCallback(ListCallGroups.PAGE));
}
}
/**
* Called when any of the submit components on the form is activated.
*
* Usually submit components are setting properties. formSubmit will first check if the form
* is valid, then it will call all the "action" listeners. Only one of the listeners (the one
* that recognizes the property that is set) will actually do something. This is a
* strange consequence of the fact that Tapestry listeners are pretty much useless because they
* are called while the form is still rewinding and not all changes are committed to beans.
*
* @param cycle current request cycle
*/
public void formSubmit(IRequestCycle cycle) {
if (!isValid()) {
return;
}
UserRingTable ringTable = getUserRingTable();
delete(ringTable);
move(ringTable);
addRow(cycle, ringTable);
}
public void commit(IRequestCycle cycle_) {
if (!isValid()) {
return;
}
saveValid();
getCallGroupContext().activateCallGroups();
}
/**
* Saves current call group and displays add ring page.
*
* @param cycle current request cycle
* @param ringTable component with table of rings
*/
private void addRow(IRequestCycle cycle, UserRingTable ringTable) {
if (!ringTable.getAddRow()) {
return;
}
saveValid();
AddUserRing page = (AddUserRing) cycle.getPage(AddUserRing.PAGE);
page.setCallGroupId(getCallGroupId());
cycle.activate(page);
}
private boolean isValid() {
IValidationDelegate delegate = TapestryUtils.getValidator(this);
AbstractComponent component = (AbstractComponent) getComponent("common");
StringSizeValidator descriptionValidator = (StringSizeValidator) component.getBeans()
.getBean("descriptionValidator");
descriptionValidator.validate(delegate);
return !delegate.getHasErrors();
}
private void saveValid() {
CallGroupContext context = getCallGroupContext();
CallGroup callGroup = getCallGroup();
context.storeCallGroup(callGroup);
Integer id = getCallGroup().getId();
setCallGroupId(id);
}
private void delete(UserRingTable ringTable) {
Collection ids = ringTable.getRowsToDelete();
if (null == ids) {
return;
}
CallGroup callGroup = getCallGroup();
callGroup.removeRings(ids);
CallGroupContext context = getCallGroupContext();
context.storeCallGroup(callGroup);
}
private void move(UserRingTable ringTable) {
int step = -1;
Collection ids = ringTable.getRowsToMoveUp();
if (null == ids) {
step = 1;
ids = ringTable.getRowsToMoveDown();
if (null == ids) {
// nothing to do
return;
}
}
CallGroup callGroup = getCallGroup();
callGroup.moveRings(ids, step);
}
private UserRingTable getUserRingTable() {
return (UserRingTable) getComponent("ringTable");
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
66a2f88b53422e1f12371705a9bd95d3d11662f9 | 147c73d61235f222d9f2c678336e3f29777de6d4 | /src/test/java/com/hoge/ConvCblTest.java | bfac15ffbdd27671601c31e42d5cd24e31e4db6f | [] | no_license | SugioNakazawa/ConvCbl | 3a5e7534a70806e888ec0a0b0d7339667827bf3c | 35bb6e1a37af3ee237605cf8a2a2fd2f9e33f784 | refs/heads/master | 2020-12-14T00:37:20.517652 | 2020-02-07T10:09:21 | 2020-02-07T10:09:21 | 234,579,281 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 11,611 | java | /**
*
*/
package com.hoge;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.Arrays;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author nakazawasugio
*
*/
public class ConvCblTest {
static Logger logger = LoggerFactory.getLogger(ConvCblTest.class.getName());
static String PATH = "src/test/resources/com/hoge/convcbl";
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
/**
* Test method for {@link com.hoge.ConvCbl#main(java.lang.String[])}.
*/
@Test
public void testMain01() {
String[] args = { "-i", "src/test/resources/com/hoge/convcbl/sample01.cbl", "-o", "out" };
try {
ConvCbl.main(args);
Assert.assertEquals(84, Files.readAllLines(Paths.get("out/sample01.dmdl")).size());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void testMainOutDmdlDot() throws IOException {
String output = this.tempFolder.getRoot().getAbsolutePath();
{
String[] args = { "-i", "src/test/resources/com/hoge/convcbl/sample01.cbl", //
"-o", output, "-t", "dmdl", "dot" };
ConvCbl.main(args);
// ls
Files.list(Paths.get(output)).forEach(System.out::println);
// check exist
Assert.assertEquals(84, Files.readAllLines(Paths.get(output + "/sample01.dmdl")).size());
Assert.assertEquals(447, Files.readAllLines(Paths.get(output + "/sample01.dot")).size());
Assert.assertEquals(19745, Files.size(Paths.get(output + "/sample01.dot")));
}
}
@Test
public void testMainNomerge() throws IOException {
String output = this.tempFolder.getRoot().getAbsolutePath();
{
String[] args = { "-i", "src/test/resources/com/hoge/convcbl/sample01.cbl", //
"-o", output, "-t", "dmdl", "dot", "--nomerge" };
ConvCbl.main(args);
// ls
Files.list(Paths.get(output)).forEach(System.out::println);
// check exist
Assert.assertEquals(84, Files.readAllLines(Paths.get(output + "/sample01.dmdl")).size());
Assert.assertEquals(447, Files.readAllLines(Paths.get(output + "/sample01.dot")).size());
Assert.assertEquals(20238, Files.size(Paths.get(output + "/sample01.dot")));
}
}
@Test
public void testMainNoreturn() throws IOException {
String output = this.tempFolder.getRoot().getAbsolutePath();
{
String[] args = { "-i", "src/test/resources/com/hoge/convcbl/sample01.cbl", //
"-o", output, "-t", "dmdl", "dot", "--noreturn" };
ConvCbl.main(args);
// ls
Files.list(Paths.get(output)).forEach(System.out::println);
// check exist
Assert.assertEquals(84, Files.readAllLines(Paths.get(output + "/sample01.dmdl")).size());
Assert.assertEquals(435, Files.readAllLines(Paths.get(output + "/sample01.dot")).size());
Assert.assertEquals(19613, Files.size(Paths.get(output + "/sample01.dot")));
}
}
@Test
public void testMainNomergeNoreturn() throws IOException {
String output = this.tempFolder.getRoot().getAbsolutePath();
{
String[] args = { "-i", "src/test/resources/com/hoge/convcbl/sample01.cbl", //
"-o", output, "-t", "dmdl", "dot", "--nomerge", "--noreturn" };
ConvCbl.main(args);
// ls
Files.list(Paths.get(output)).forEach(System.out::println);
// check exist
Assert.assertEquals(84, Files.readAllLines(Paths.get(output + "/sample01.dmdl")).size());
Assert.assertEquals(435, Files.readAllLines(Paths.get(output + "/sample01.dot")).size());
Assert.assertEquals(20092, Files.size(Paths.get(output + "/sample01.dot")));
}
}
@Test
public void testMainOutDot() throws IOException {
String output = this.tempFolder.getRoot().getAbsolutePath();
{
String[] args = { "-i", "src/test/resources/com/hoge/convcbl/sample01.cbl", //
"-o", output, "-t", "dot" };
ConvCbl.main(args);
// check exist
Assert.assertFalse(Files.exists(Paths.get(output + "/sample01.dmdl")));
Assert.assertTrue(Files.exists(Paths.get(output + "/sample01.dot")));
}
}
@Test
public void testMainNoFileParam() {
String[] args = {};
try {
ConvCbl.main(args);
fail();
} catch (IllegalArgumentException e) {
Assert.assertEquals(Const.MSG_NO_FILE_PARAM, e.getMessage());
} catch (Exception e) {
fail();
}
}
@Test
public void testMainNoFile() {
String[] args = { "-i", "nofile.cbl" };
try {
ConvCbl.main(args);
fail();
} catch (IllegalArgumentException iae) {
Assert.assertEquals(MessageFormat.format(Const.MSG_NO_FILE, "nofile.cbl"), iae.getMessage());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void testMainNoDir() throws IOException {
{
String[] args = { "-i", "src/test/resources/com/hoge/convcbl/sample01.cbl" };
ConvCbl.main(args);
// check exist
Assert.assertTrue(Files.exists(Paths.get("out/sample01.dmdl")));
Assert.assertTrue(Files.exists(Paths.get("out/sample01.dot")));
}
}
@Test
public void testMainIllegalDir() {
{
String[] args = { "-i", "src/test/resources/com/hoge/convcbl/sample01.cbl", "-o", "aaa" };
try {
ConvCbl.main(args);
} catch (IllegalArgumentException e) {
Assert.assertEquals(MessageFormat.format(Const.MSG_NO_DIR, "aaa"), e.getMessage());
} catch (IOException e) {
Assert.fail();
e.printStackTrace();
}
}
}
@Test
public void testMainIllegalParam() {
String[] args = { "-p", "unknown" };
try {
ConvCbl.main(args);
fail();
} catch (IllegalArgumentException iae) {
Assert.assertEquals("Unrecognized option: -p", iae.getMessage());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void testExec00() throws IOException {
ProcedureDiv.LONG_LABEL = true;
String programId = "sample01";
Path fileName = Paths.get(PATH + "/" + programId + ".cbl");
ConvCbl target = new ConvCbl(fileName);
try {
target.setOutDir(Paths.get("out"));
target.exec();
} catch (Exception e) {
e.printStackTrace();
fail();
}
target.getProgram().procDiv.setForkedMerge(true);
target.getProgram().procDiv.outputDataDot(null);
}
@Test
public void testExec01() throws IOException {
ProcedureDiv.LONG_LABEL = true;
String programId = "sample01";
Path fileName = Paths.get(PATH + "/" + programId + ".cbl");
ConvCbl target = new ConvCbl(fileName);
try {
target.setOutDir(Paths.get("out"));
target.exec();
Assert.assertEquals("SAMPLE01", target.getProgram().idDiv.getProgramId());
Assert.assertEquals(2, target.getProgram().idDiv.recList.size());
Assert.assertEquals(7, target.getProgram().envDiv.recList.size());
Assert.assertEquals(63, target.getProgram().dataDiv.recList.size());
Assert.assertEquals(61, target.getProgram().procDiv.recList.size());
} catch (Exception e) {
e.printStackTrace();
fail();
}
outputLog(programId, target);
target.getProgram().dataDiv.logoutContent();
target.getProgram().procDiv.outputDataDot(Paths.get("out/" + programId + ".dot"));
{
// DATA CHEK
String expFile = PATH + "/exp_" + programId + ".dmdl";
String actFile = target.getOutDir() + "/" + programId + ".dmdl";
Assert.assertTrue(
Arrays.equals(Files.readAllBytes(Paths.get(expFile)), Files.readAllBytes(Paths.get(actFile))));
}
{
// PROCEDURE CHECK
target.getProgram().procDiv.logoutCmdTree("out/" + programId + "_tree.txt");
String expFile = PATH + "/exp_" + programId + "_tree.txt";
String actFile = "out/" + programId + "_tree.txt";
Assert.assertTrue(
Arrays.equals(Files.readAllBytes(Paths.get(expFile)), Files.readAllBytes(Paths.get(actFile))));
}
}
@Test
public void testExec02() throws IOException {
String programId = "sample02";
String PATH = "src/test/resources/com/hoge/convcbl";
Path fileName = Paths.get(PATH + "/" + programId + ".cbl");
ConvCbl target = new ConvCbl(fileName);
try {
target.setOutDir(Paths.get("out"));
target.exec();
Assert.assertEquals(2, target.getProgram().idDiv.recList.size());
Assert.assertEquals(6, target.getProgram().envDiv.recList.size());
Assert.assertEquals(44, target.getProgram().dataDiv.recList.size());
Assert.assertEquals(63, target.getProgram().procDiv.recList.size());
} catch (Exception e) {
e.printStackTrace();
fail();
}
outputLog(programId, target);
target.getProgram().procDiv.outputDataDot(Paths.get("out/" + programId + ".dot"));
// DATA CHEK
{
String expFile = PATH + "/exp_" + programId + ".dmdl";
String actFile = "out/" + programId + ".dmdl";
Assert.assertTrue(
Arrays.equals(Files.readAllBytes(Paths.get(expFile)), Files.readAllBytes(Paths.get(actFile))));
}
// PROCEDURE CHECK
target.getProgram().procDiv.logoutCmdTree("out/" + programId + "_tree.txt");
{
String expFile = PATH + "/exp_" + programId + "_tree.txt";
String actFile = "out/" + programId + "_tree.txt";
Assert.assertTrue(
Arrays.equals(Files.readAllBytes(Paths.get(expFile)), Files.readAllBytes(Paths.get(actFile))));
}
}
@Test
public void testExec03() throws IOException {
String programId = "sample03";
String PATH = "src/test/resources/com/hoge/convcbl";
Path fileName = Paths.get(PATH + "/" + programId + ".cbl");
ConvCbl target = new ConvCbl(fileName);
try {
target.setOutDir(Paths.get("out"));
target.exec();
Assert.assertEquals(2, target.getProgram().idDiv.recList.size());
Assert.assertEquals(5, target.getProgram().envDiv.recList.size());
Assert.assertEquals(65, target.getProgram().dataDiv.recList.size());
Assert.assertEquals(76, target.getProgram().procDiv.recList.size());
} catch (Exception e) {
e.printStackTrace();
fail();
}
outputLog(programId, target);
target.getProgram().procDiv.outputDataDot(Paths.get("out/" + programId + ".dot"));
// DATA CHEK
{
String expFile = PATH + "/exp_" + programId + ".dmdl";
String actFile = "out/" + programId + ".dmdl";
Assert.assertTrue(
Arrays.equals(Files.readAllBytes(Paths.get(expFile)), Files.readAllBytes(Paths.get(actFile))));
}
// PROCEDURE CHECK
target.getProgram().procDiv.logoutCmdTree("out/" + programId + "_tree.txt");
{
String expFile = PATH + "/exp_" + programId + "_tree.txt";
String actFile = "out/" + programId + "_tree.txt";
Assert.assertTrue(
Arrays.equals(Files.readAllBytes(Paths.get(expFile)), Files.readAllBytes(Paths.get(actFile))));
}
}
private void outputLog(String programId, ConvCbl target) throws IOException {
// log
logger.info("===========================================================");
target.getProgram().procDiv.logoutRecList();
logger.info("===========================================================");
target.getProgram().procDiv.logoutSecTree();
logger.info("===========================================================");
target.getProgram().procDiv.logoutCmdTree(null);
logger.info("===========================================================");
target.getProgram().procDiv.outputDataDot(null);
}
} | [
"nakazawa@nautilus-technologies.com"
] | nakazawa@nautilus-technologies.com |
7395414d837f01cee7c3f607334d818377433bd2 | c9b1e14e0a0bfa5bfed01240b726d34f3c6a701a | /app/src/main/java/com/streamliners/galleryapp/adapters/ItemTouchHelperAdapter.java | 3524dfbc670d1eb95e1a99f7b7a92e68b83852c7 | [] | no_license | shrutiisharma/GalleryApp | 067c7abcd176a2976a3eecf9b0c04ac723127c24 | 111f2757dd389d96d42c978bddd8f1499848314e | refs/heads/master | 2023-05-29T05:24:37.921970 | 2021-06-16T07:53:34 | 2021-06-16T07:53:34 | 370,956,513 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 183 | java | package com.streamliners.galleryapp.adapters;
public interface ItemTouchHelperAdapter {
void onItemMove(int fromPosition, int toPosition);
void onItemDelete(int position);
}
| [
"72591283+shrutiisharma@users.noreply.github.com"
] | 72591283+shrutiisharma@users.noreply.github.com |
cac86113eac29ac17da4a0239f397242fb307cf1 | 40fa3e9ef976a11d241de9233e5d83d19f984e61 | /prereqs/CSC202/h2/src/test/org/h2/test/synth/TestCrashAPI.java | 62a7847e928491f16d612dc81a97927840bffef6 | [] | no_license | tjbee/homework | 63027d98aedee6e454cf73d0b18689c62ba7d3c5 | f28f7d7db3bc9724a6c41307938d496f019bd81e | refs/heads/master | 2021-01-15T12:20:51.580709 | 2012-07-29T17:34:07 | 2012-07-29T17:34:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 17,337 | java | /*
* Copyright 2004-2010 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.synth;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.BatchUpdateException;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import org.h2.constant.ErrorCode;
import org.h2.constant.SysProperties;
import org.h2.jdbc.JdbcConnection;
import org.h2.store.FileLister;
import org.h2.test.TestAll;
import org.h2.test.TestBase;
import org.h2.test.db.TestScript;
import org.h2.test.synth.sql.RandomGen;
import org.h2.tools.Backup;
import org.h2.tools.DeleteDbFiles;
import org.h2.tools.Restore;
import org.h2.util.IOUtils;
import org.h2.util.MathUtils;
import org.h2.util.New;
/**
* A test that calls random methods with random parameters from JDBC objects.
* This is sometimes called 'Fuzz Testing'.
*/
public class TestCrashAPI extends TestBase {
private static final boolean RECOVER_ALL = false;
private static final Class< ? >[] INTERFACES = { Connection.class, PreparedStatement.class, Statement.class,
ResultSet.class, ResultSetMetaData.class, Savepoint.class,
ParameterMetaData.class, Clob.class, Blob.class, Array.class, CallableStatement.class };
private static final String DIR = "synth";
private ArrayList<Object> objects = New.arrayList();
private HashMap<Class < ? >, ArrayList<Method>> classMethods = New.hashMap();
private RandomGen random = new RandomGen();
private ArrayList<String> statements = New.arrayList();
private int openCount;
private long callCount;
/**
* Run just this test.
*
* @param a ignored
*/
public static void main(String... a) throws Exception {
TestBase.createCaller().init().test();
}
private void recoverAll() throws SQLException {
org.h2.Driver.load();
File[] files = new File("temp/backup").listFiles();
Arrays.sort(files, new Comparator<File>() {
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (File f : files) {
if (!f.getName().startsWith("db-")) {
continue;
}
DeleteDbFiles.execute("data", null, true);
try {
Restore.execute(f.getAbsolutePath(), "data", null, true);
} catch (Exception e) {
System.out.println(f.getName() + " restore error " + e);
// ignore
}
ArrayList<String> dbFiles = FileLister.getDatabaseFiles("data", null, false);
for (String name: dbFiles) {
if (!name.endsWith(".h2.db")) {
continue;
}
name = name.substring(0, name.length() - 6);
try {
DriverManager.getConnection("jdbc:h2:data/" + name, "sa", "").close();
System.out.println(f.getName() + " OK");
} catch (SQLException e) {
System.out.println(f.getName() + " " + e);
}
}
}
}
public void test() throws SQLException {
if (RECOVER_ALL) {
recoverAll();
return;
}
if (config.mvcc || config.networked) {
return;
}
int len = getSize(2, 6);
for (int i = 0; i < len; i++) {
int seed = MathUtils.randomInt(Integer.MAX_VALUE);
testCase(seed);
deleteDb();
}
}
private void deleteDb() {
try {
deleteDb(baseDir + "/" + DIR, null);
} catch (Exception e) {
// ignore
}
}
private Connection getConnection(int seed, boolean delete) throws SQLException {
openCount++;
if (delete) {
deleteDb();
}
// can not use FILE_LOCK=NO, otherwise something could be written into
// the database in the finalize method
String add = "";
// int testing;
// if(openCount >= 32) {
// int test;
// Runtime.getRuntime().halt(0);
// System.exit(1);
// }
// System.out.println("now open " + openCount);
// add += ";TRACE_LEVEL_FILE=3";
// config.logMode = 2;
// }
String dbName = "crashApi" + seed;
String url = getURL(DIR + "/" + dbName, true) + add;
// int test;
// url += ";DB_CLOSE_ON_EXIT=FALSE";
// int test;
// url += ";TRACE_LEVEL_FILE=3";
Connection conn = null;
String fileName = "temp/backup/db-" + uniqueId++ + ".zip";
Backup.execute(fileName, baseDir + "/" + DIR, dbName, true);
// close databases earlier
System.gc();
try {
conn = DriverManager.getConnection(url, "sa", getPassword(""));
// delete the backup if opening was successful
IOUtils.delete(fileName);
} catch (SQLException e) {
if (e.getErrorCode() == ErrorCode.WRONG_USER_OR_PASSWORD) {
// delete if the password changed
IOUtils.delete(fileName);
}
throw e;
}
int len = random.getInt(50);
int first = random.getInt(statements.size() - len);
int end = first + len;
Statement stat = conn.createStatement();
stat.execute("SET LOCK_TIMEOUT 10");
stat.execute("SET WRITE_DELAY 0");
if (random.nextBoolean()) {
if (random.nextBoolean()) {
double g = random.nextGaussian();
int size = (int) Math.abs(10000 * g * g);
stat.execute("SET CACHE_SIZE " + size);
} else {
stat.execute("SET CACHE_SIZE 0");
}
}
stat.execute("SCRIPT NOPASSWORDS NOSETTINGS");
for (int i = first; i < end && i < statements.size(); i++) {
try {
stat.execute("SELECT * FROM TEST WHERE ID=1");
} catch (Throwable t) {
printIfBad(seed, -i, -1, t);
}
try {
stat.execute("SELECT * FROM TEST WHERE ID=1 OR ID=1");
} catch (Throwable t) {
printIfBad(seed, -i, -1, t);
}
String sql = statements.get(i);
try {
// if(openCount == 32) {
// int test;
// System.out.println("stop!");
// }
stat.execute(sql);
} catch (Throwable t) {
printIfBad(seed, -i, -1, t);
}
}
if (random.nextBoolean()) {
try {
conn.commit();
} catch (Throwable t) {
printIfBad(seed, 0, -1, t);
}
}
return conn;
}
private void testOne(int seed) throws SQLException {
printTime("seed: " + seed);
callCount = 0;
openCount = 0;
random = new RandomGen();
random.setSeed(seed);
Connection c1 = getConnection(seed, true);
Connection conn = null;
for (int i = 0; i < 2000; i++) {
// if(i % 10 == 0) {
// for(int j=0; j<objects.size(); j++) {
// System.out.print(objects.get(j));
// System.out.print(" ");
// }
// System.out.println();
// Thread.sleep(1);
// }
if (objects.size() == 0) {
try {
conn = getConnection(seed, false);
} catch (SQLException e) {
if (e.getSQLState().equals("08004")) {
// Wrong user/password [08004]
try {
c1.createStatement().execute("SET PASSWORD ''");
} catch (Throwable t) {
// power off or so
break;
}
try {
conn = getConnection(seed, false);
} catch (Throwable t) {
printIfBad(seed, -i, -1, t);
}
} else if (e.getSQLState().equals("90098")) {
// The database has been closed
break;
} else {
printIfBad(seed, -i, -1, e);
}
}
objects.add(conn);
}
int objectId = random.getInt(objects.size());
if (random.getBoolean(1)) {
objects.remove(objectId);
continue;
}
if (random.getInt(2000) == 0 && conn != null) {
((JdbcConnection) conn).setPowerOffCount(random.getInt(50));
}
Object o = objects.get(objectId);
if (o == null) {
objects.remove(objectId);
continue;
}
Class< ? > in = getJdbcInterface(o);
ArrayList<Method> methods = classMethods.get(in);
Method m = methods.get(random.getInt(methods.size()));
Object o2 = callRandom(seed, i, objectId, o, m);
if (o2 != null) {
objects.add(o2);
}
}
try {
if (conn != null) {
conn.close();
}
c1.close();
} catch (Throwable t) {
printIfBad(seed, -101010, -1, t);
try {
deleteDb();
} catch (Throwable t2) {
printIfBad(seed, -101010, -1, t2);
}
}
objects.clear();
}
private void printError(int seed, int id, Throwable t) {
StringWriter writer = new StringWriter();
t.printStackTrace(new PrintWriter(writer));
String s = writer.toString();
TestBase.logError("new TestCrashAPI().init(test).testCase(" +
seed + "); // Bug " + s.hashCode() + " id=" + id +
" callCount=" + callCount + " openCount=" + openCount +
" " + t.getMessage(), t);
throw new RuntimeException(t);
}
private Object callRandom(int seed, int id, int objectId, Object o, Method m) {
Class< ? >[] paramClasses = m.getParameterTypes();
Object[] params = new Object[paramClasses.length];
for (int i = 0; i < params.length; i++) {
params[i] = getRandomParam(paramClasses[i]);
}
Object result = null;
try {
callCount++;
result = m.invoke(o, params);
} catch (IllegalArgumentException e) {
TestBase.logError("error", e);
} catch (IllegalAccessException e) {
TestBase.logError("error", e);
} catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
printIfBad(seed, id, objectId, t);
}
if (result == null) {
return null;
}
Class< ? > in = getJdbcInterface(result);
if (in == null) {
return null;
}
return result;
}
private void printIfBad(int seed, int id, int objectId, Throwable t) {
if (t instanceof BatchUpdateException) {
// do nothing
} else if (t.getClass().getName().indexOf("SQLClientInfoException") >= 0) {
// do nothing
} else if (t instanceof SQLException) {
SQLException s = (SQLException) t;
int errorCode = s.getErrorCode();
if (errorCode == 0) {
printError(seed, id, s);
} else if (errorCode == ErrorCode.OBJECT_CLOSED) {
if (objectId >= 0) {
// TODO at least call a few more times after close - maybe
// there is still an error
objects.remove(objectId);
}
} else if (errorCode == ErrorCode.GENERAL_ERROR_1) {
// General error [HY000]
printError(seed, id, s);
}
} else {
printError(seed, id, t);
}
}
private Object getRandomParam(Class< ? > type) {
if (type == int.class) {
return new Integer(random.getRandomInt());
} else if (type == byte.class) {
return new Byte((byte) random.getRandomInt());
} else if (type == short.class) {
return new Short((short) random.getRandomInt());
} else if (type == long.class) {
return new Long(random.getRandomLong());
} else if (type == float.class) {
return new Float(random.getRandomDouble());
} else if (type == boolean.class) {
return new Boolean(random.nextBoolean());
} else if (type == double.class) {
return new Double(random.getRandomDouble());
} else if (type == String.class) {
if (random.getInt(10) == 0) {
return null;
}
int randomId = random.getInt(statements.size());
String sql = statements.get(randomId);
if (random.getInt(10) == 0) {
sql = random.modify(sql);
}
return sql;
} else if (type == int[].class) {
// TODO test with 'shared' arrays (make sure database creates a
// copy)
return random.getIntArray();
} else if (type == java.io.Reader.class) {
return null;
} else if (type == java.sql.Array.class) {
return null;
} else if (type == byte[].class) {
// TODO test with 'shared' arrays (make sure database creates a
// copy)
return random.getByteArray();
} else if (type == Map.class) {
return null;
} else if (type == Object.class) {
return null;
} else if (type == java.sql.Date.class) {
return random.randomDate();
} else if (type == java.sql.Time.class) {
return random.randomTime();
} else if (type == java.sql.Timestamp.class) {
return random.randomTimestamp();
} else if (type == java.io.InputStream.class) {
return null;
} else if (type == String[].class) {
return null;
} else if (type == java.sql.Clob.class) {
return null;
} else if (type == java.sql.Blob.class) {
return null;
} else if (type == Savepoint.class) {
// TODO should use generated savepoints
return null;
} else if (type == Calendar.class) {
return Calendar.getInstance();
} else if (type == java.net.URL.class) {
return null;
} else if (type == java.math.BigDecimal.class) {
return new java.math.BigDecimal("" + random.getRandomDouble());
} else if (type == java.sql.Ref.class) {
return null;
}
return null;
}
private Class< ? > getJdbcInterface(Object o) {
for (Class < ? > in : o.getClass().getInterfaces()) {
if (classMethods.get(in) != null) {
return in;
}
}
return null;
}
private void initMethods() {
for (Class< ? > inter : INTERFACES) {
classMethods.put(inter, new ArrayList<Method>());
}
for (Class< ? > inter : INTERFACES) {
ArrayList<Method> list = classMethods.get(inter);
for (Method m : inter.getMethods()) {
list.add(m);
}
}
}
public TestBase init(TestAll conf) throws Exception {
super.init(conf);
if (config.mvcc || config.networked) {
return this;
}
baseDir = TestBase.getTestDir("crash");
startServerIfRequired();
TestScript script = new TestScript();
ArrayList<String> add = script.getAllStatements(config);
initMethods();
org.h2.Driver.load();
statements.addAll(add);
return this;
}
public void testCase(int i) throws SQLException {
int old = SysProperties.getMaxQueryTimeout();
String oldBaseDir = baseDir;
try {
System.setProperty(SysProperties.H2_MAX_QUERY_TIMEOUT, "" + 10000);
baseDir = TestBase.getTestDir("crash");
testOne(i);
} finally {
baseDir = oldBaseDir;
System.setProperty(SysProperties.H2_MAX_QUERY_TIMEOUT, "" + old);
}
}
}
| [
"rayelward@gmail.com"
] | rayelward@gmail.com |
f0dd95acd7548843560380d9e45d55e9b531a2e0 | cfe621e8c36e6ac5053a2c4f7129a13ea9f9f66b | /apps_final/mobi.dream.neko/apk/mobi/monaca/framework/plugin/MonacaPlugin.java | c05b58870be779416023eef66fb12cb91ff68324 | [] | no_license | linux86/AndoirdSecurity | 3165de73b37f53070cd6b435e180a2cb58d6f672 | 1e72a3c1f7a72ea9cd12048d9874a8651e0aede7 | refs/heads/master | 2021-01-11T01:20:58.986651 | 2016-04-05T17:14:26 | 2016-04-05T17:14:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 919 | java | package mobi.monaca.framework.plugin;
import mobi.monaca.utils.MonacaDevice;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MonacaPlugin
extends CordovaPlugin
{
public boolean execute(String paramString, JSONArray paramJSONArray, CallbackContext paramCallbackContext)
throws JSONException
{
if (paramString.equals("getRuntimeConfiguration"))
{
paramString = new JSONObject();
paramString.put("deviceId", MonacaDevice.getDeviceId(cordova.getActivity()));
paramCallbackContext.success(paramString);
return true;
}
return false;
}
}
/* Location:
* Qualified Name: mobi.monaca.framework.plugin.MonacaPlugin
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | [
"i@xuzhao.net"
] | i@xuzhao.net |
617f2df576d2caef8bbab60344fec8969b1c1133 | d3640cbaa034d32300c8fd5d45a01f7bf710c316 | /src/main/java/weblogiccli/Main.java | 25d61a5c1e15d63f6fc84b2076a3b02a0478b3f1 | [] | no_license | olecrivain/weblogic-cli | cfbef57573cf3e7dc4494117a31d573ed6fe56bb | e8f2e5d870d955666b727d9e8797e9fdb7187d9f | refs/heads/master | 2016-09-03T06:53:35.286122 | 2013-05-24T16:11:59 | 2013-05-24T16:11:59 | 9,647,536 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,762 | java | package weblogiccli;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weblogic.logging.LoggingHelper;
import weblogiccli.cmd.Command;
import weblogiccli.cmd.DeployCmd;
import weblogiccli.cmd.ListappsCmd;
import weblogiccli.cmd.UndeployCmd;
import weblogiccli.cmd.exception.ArgsException;
import weblogiccli.conf.Environment;
import weblogiccli.utils.Console;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigParseOptions;
import com.typesafe.config.impl.ConfigImpl;
public class Main extends Command {
private static Logger LOG = LoggerFactory.getLogger(Main.class);
private Map<String, Command> commands = new HashMap<String, Command>();
private static final int OK = 0;
private static final int KO = 1;
public void printHelp() {
LOG.info("Usage : weblogic <commande> [options]");
LOG.info("");
LOG.info("With, listapps List applications");
LOG.info(" deploy Deploy an application");
LOG.info(" undeploy Undeploy an application");
}
public void run(String[] args) {
if (getFlag(args, "-v")) {
// Affiche la version
try {
URL url = Resources.getResource("VERSION");
String version = Resources.toString(url, Charsets.UTF_8);
System.out.println("version : \"" + version + "\"");
} catch (IOException e) {
LOG.error("Cannot retrieve version number.");
}
System.exit(OK);
}
boolean printStackTrace = getFlag(args, "-e");
String cfg = null;
try {
cfg = getOption(args, "-cfg");
} catch (ArgsException e1) {
} finally {
if (cfg == null) {
LOG.error("You have to specify a properties file with the \"-cfg\" option.");
System.exit(KO);
}
}
Map<String, Environment> environments = loadEnvironments(cfg);
commands.put("listapps", new ListappsCmd(environments));
commands.put("deploy", new DeployCmd(environments));
commands.put("undeploy", new UndeployCmd(environments));
if (args.length < 1 || !commands.containsKey(args[0])) {
printHelp();
System.exit(1);
} else {
long startTime = new Date().getTime();
int exitcode = OK;
Command command = commands.get(args[0]);
try {
// Make weblogic logger less verbose...
LoggingHelper.getClientLogger().setLevel(Level.WARNING);
command.run(Arrays.copyOfRange(args, 1, args.length));
printFooter(startTime, exitcode);
} catch (ArgsException e) {
command.printHelp();
exitcode = 1;
} catch (Exception e) {
if (printStackTrace) {
LOG.error(e.getMessage(), e);
} else {
LOG.error(e.getMessage());
}
exitcode = KO;
printFooter(startTime, exitcode);
} finally {
System.exit(exitcode);
}
}
}
private void printFooter(long startTime, int exitcode) {
Console.printEmptyLine();
if (exitcode == OK) {
Console.printSuccess();
} else {
Console.printFailure();
}
long endTime = new Date().getTime();
LOG.info("Total time : {}s", (endTime-startTime)/1000.0);
}
private Map<String, Environment> loadEnvironments(String cfg) {
Config conf = ConfigImpl.parseFileAnySyntax(new File(cfg), ConfigParseOptions.defaults()).toConfig();
Map<String, Environment> environments = new HashMap<String, Environment>();
for (String env : conf.root().keySet()) {
Environment environment = new Environment();
environment.setHost(conf.getString(env + ".host"));
environment.setPort(conf.getInt(env + ".port"));
environment.setUsername(conf.getString(env + ".username"));
environment.setPassword(conf.getString(env + ".password"));
environments.put(env, environment);
}
return environments;
}
public static void main(String[] args) {
Main main = new Main();
main.run(args);
}
}
| [
"olivier.lecrivain@gmail.com"
] | olivier.lecrivain@gmail.com |
93c1be21e4289651d0d913fd524bdc5e926f8514 | d52a4665c9c473169ef39bab1de941cdb8b9fbbd | /ParkHere/app/src/main/java/com/pfp/parkhere/RegisterActivity.java | fc04a2c9bf8bc790e1373fe4879d18be2be80f82 | [] | no_license | dantlz/CS310_PFP_NEW | d9b66327696e41c45327c8d70f9ae91bf1cec1eb | 8638b979fa7c1abb26f1979fb6fc8365d7f2f42b | refs/heads/master | 2021-01-17T18:17:00.611889 | 2016-12-05T20:36:53 | 2016-12-05T20:36:53 | 71,317,392 | 1 | 0 | null | 2016-10-21T22:13:13 | 2016-10-19T04:01:15 | Java | UTF-8 | Java | false | false | 11,382 | java | package com.pfp.parkhere;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import ObjectClasses.Peer;
import ObjectClasses.Status;
//Done Sprint 2
public class RegisterActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
private Button buttonLoadImage;
private Button confirmButton;
private EditText firstNameField;
private EditText lastNameField;
private EditText emailField;
private EditText phoneNumberField;
private EditText passwordField;
private EditText repeatPasswordField;
private Button gotoLoginButton;
private ImageView imageView;
private Spinner statusSpinner;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private Peer currentUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
findViewById(R.id.registerLoad).setVisibility(View.GONE);
buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
//Called when Upload Photo is clicked
@Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
confirmButton = (Button) findViewById(R.id.confirmButton);
confirmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
confirmButtonPressed();
}
});
firstNameField = (EditText) findViewById(R.id.first_name_field);
lastNameField = (EditText) findViewById(R.id.last_name_field);
emailField = (EditText) findViewById(R.id.email_field);
phoneNumberField = (EditText) findViewById(R.id.phone_field);
passwordField = (EditText) findViewById(R.id.password_field);
repeatPasswordField = (EditText) findViewById(R.id.repeat_password_field);
gotoLoginButton = (Button) findViewById(R.id.goToLoginButton);
gotoLoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
imageView = (ImageView) findViewById(R.id.imgView);
statusSpinner = (Spinner) findViewById(R.id.statusSpinner);
// Spinner Drop down elements
List<String> types = new ArrayList<String>();
types.add("Owner");
types.add("Seeker");
final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, types);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
statusSpinner.setAdapter(dataAdapter);
//Firebase
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
System.out.println("Register: " + 1);
if (user != null) {
System.out.println("Register: " + 2);
findViewById(R.id.registerLoad).setVisibility(View.GONE);
Global.peers().child(Global.reformatEmail(user.getEmail())).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("Register: " + 3);
currentUser = dataSnapshot.getValue(Peer.class);
if(currentUser == null)
return;
System.out.println("Register: " + 4);
System.out.println("Register: " + currentUser.getEmailAddress());
Global.setCurUser(currentUser);
startActivity(new Intent(RegisterActivity.this, MapsMainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
finish();
return;
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
else {
return;
}
}
};
mAuth.addAuthStateListener(mAuthListener);
}
private void confirmButtonPressed(){
findViewById(R.id.registerLoad).setVisibility(View.VISIBLE);
String validity = allInputFieldValid();
if(!validity.equals("")) {
findViewById(R.id.registerLoad).setVisibility(View.GONE);
new AlertDialog.Builder(RegisterActivity.this, R.style.MyAlertDialogStyle)
.setTitle("Registration failed")
.setMessage(validity)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
return;
}
mAuth.createUserWithEmailAndPassword(emailField.getText().toString(),
passwordField.getText().toString())
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
findViewById(R.id.registerLoad).setVisibility(View.GONE);
//Check if email is already registered.
if(task.getException().getClass().equals(FirebaseAuthUserCollisionException.class)){
new AlertDialog.Builder(RegisterActivity.this, R.style.MyAlertDialogStyle)
.setTitle("Email already in use")
.setMessage("The email: " + emailField.getText().toString()
+ " is already registered. Please register with a different email or log in")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
return;
}
currentUser = createUserObject();
Global.peers().child(Global.reformatEmail(emailField.getText().toString())).setValue(currentUser);
}
});
}
private Peer createUserObject(){
Peer peer = new Peer();
peer.setEmailAddress(emailField.getText().toString());
peer.setReformattedEmail(Global.reformatEmail(emailField.getText().toString()));
peer.setFirstName(firstNameField.getText().toString());
peer.setLastName(lastNameField.getText().toString());
peer.setPhoneNumber(phoneNumberField.getText().toString());
peer.setDPNonFirebaseRelated(imageView.getDrawable());
peer.setStatus(Status.valueOf(statusSpinner.getSelectedItem().toString().toUpperCase()));
peer.setPreferredStatus(peer.getStatus());
peer.setPhotoID("");
peer.setOwnerRating(0);
return peer;
}
private String allInputFieldValid(){
if(firstNameField.getText().toString().equals(""))
return "First name cannot be empty";
if(lastNameField.getText().toString().equals(""))
return "Last name cannot be empty";
if(emailField.getText().toString().equals("") ||
!Patterns.EMAIL_ADDRESS.matcher(emailField.getText().toString()).matches())
return "Email cannot be empty and must be valid";
if(phoneNumberField.getText().toString().equals("") ||
!Patterns.PHONE.matcher(phoneNumberField.getText().toString()).matches())
return "Phone number cannot be empty and must be valid";
if(passwordField.getText().toString().equals("") ||
repeatPasswordField.getText().toString().equals(""))
return "Password fields cannot be empty";
if(!passwordField.getText().toString().equals(repeatPasswordField.getText().toString()))
return "Password fields must match";
//Password must be at least 10 characters with upper/lower case, number(s), and special characters
if(passwordField.getText().toString().length() < 10)
return "Password must be at least 10 characters";
if((BitmapDrawable)(imageView.getDrawable()) == null)
return "Must set a display picture for your profile";
for(char c: passwordField.getText().toString().toCharArray()){
if("!@#$%^&*()_+-=".contains(String.valueOf(c)))
return "";
}
return "Password must contain at least one special character";
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
imageView.setImageURI(selectedImage);
}
}
}
| [
"tianlinz@dantlz.local"
] | tianlinz@dantlz.local |
bbe368f0255fc798e06300ce6939c95aa72306f3 | e952b365062c86984e48bc2970a89fbfbfa6c5e0 | /app/src/main/java/com/softjads/jorge/hellojesus/topic/TopicFragmentPagerAdapter.java | aefe78f4a04e858a845ef24a7f44c86099a7d442 | [] | no_license | jorgealbertojas/HelloJesus | c3cbb5941ae99858e5bf62195d1ec2d91823a0a7 | 47785dfdfe12066835b8e7fd3cdcc3ce17d13441 | refs/heads/master | 2022-03-09T21:25:05.896412 | 2022-02-22T23:38:00 | 2022-02-22T23:38:00 | 122,330,439 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,459 | java | package com.softjads.jorge.hellojesus.topic;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.softjads.jorge.hellojesus.topic.fragmentTab.BibleFragment;
import com.softjads.jorge.hellojesus.topic.fragmentTab.ExerciseFragment;
import com.softjads.jorge.hellojesus.topic.fragmentTab.MusicFragment;
import com.softjads.jorge.hellojesus.topic.fragmentTab.MusicSingFragment;
/**
* Created by jorge on 23/02/2018.
*/
public class TopicFragmentPagerAdapter extends FragmentPagerAdapter {
private Context mContext;
private String mNameTitle = "";
public TopicFragmentPagerAdapter(Context context, FragmentManager fm, String nameTitle) {
super(fm);
mContext = context;
mNameTitle = nameTitle;
}
// This determines the fragment for each tab
@Override
public Fragment getItem(int position) {
if (position == 0) {
return new BibleFragment();
} else if (position == 1){
return new MusicFragment();
} else if (position == 2){
return new ExerciseFragment();
} else if (position == 3){
return new MusicSingFragment();
} else {
return null;
}
}
// This determines the number of tabs
@Override
public int getCount() {
return 4;
}
}
| [
"jorgealbertojas@gmail.com"
] | jorgealbertojas@gmail.com |
2421701ac5499c18c8193e1cfa142aa3bd18aac4 | 5eb7047ef33702dcd58403abf9902b326e01e06e | /FacadePattern/WarungIndomie/src/model/vegetable/Tomato.java | 7e8b9a1b996bc517456f6c3b940bfa3b62d807af | [] | no_license | vanzpool/fla | 4995ae05773e209ddadbf9627c2decdde5106e0c | 45d6125f1629c0643ac330bb82c1627b09daac26 | refs/heads/master | 2020-04-16T01:33:18.644547 | 2019-01-11T04:27:07 | 2019-01-11T04:27:07 | 165,178,374 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 163 | java | package model.vegetable;
public class Tomato extends Vegetable {
public Tomato() {
// TODO Auto-generated constructor stub
Name = "Tomato";
}
}
| [
"noreply@github.com"
] | vanzpool.noreply@github.com |
baf638de6c8aeeb78fbddc0bb4cdccb5d7a38eb3 | 865719c33033159b3cc870fe333cb523f9cd593b | /Android_ApplicBateau/main/java/com/example/android_applicbateau/Login.java | 501d8d7ae3a1bd09fe28f15e8b2f087c29095cc5 | [] | no_license | Sirorco/Isil-Data-Scientist | fb7c5c66d0b00ad8c4a7d52167c8b00f12ea7a91 | f2d738c48c3365d19bfbb823f7a5c75fff002b1b | refs/heads/main | 2023-02-24T05:22:26.472104 | 2021-01-22T20:38:52 | 2021-01-22T20:38:52 | 315,962,713 | 0 | 0 | null | 2021-01-22T20:47:03 | 2020-11-25T14:24:59 | Java | UTF-8 | Java | false | false | 9,259 | java | package com.example.android_applicbateau;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import Protocol.BaseRequest;
import Protocol.RequestLogin;
import Protocol.RequestLoginInitiator;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
public class Login extends Activity {
private Button checkBoutton,logoutBoutton;
private EditText nomView;
private EditText mdpView;
private String nom, mdp,ipv4Adress,texte="";
private int port;
private RequestLoginInitiator requestLoginInitiator=null;
private RequestLogin requestLogin=null;
private BaseRequest request=null;
private static ObjectOutputStream objectOutputClient = null;
private static ObjectInputStream objectInputClient = null;
private static Socket serveurSocket = null;
private Properties properties;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bundle bundle = getIntent().getExtras();
if(bundle != null)
{
texte = bundle.getString("Logout");
if(texte.equals("Logout"))
{
try {
objectInputClient.close();
objectOutputClient.close();
serveurSocket.close();
objectInputClient = null;
objectOutputClient = null;
serveurSocket = null;
}
catch(Exception e)
{
System.err.println("err" + e);
}
}
}
try {
InputStream is = getBaseContext().getAssets().open("config.properties");
properties = new Properties();
properties.load(is);
ipv4Adress = properties.getProperty("IPV4_SERVER");
port = Integer.parseInt(properties.getProperty("PORT_SERVER"));
is.close();
} catch (Exception e) {
}
nomView = (EditText) findViewById(R.id.Nom);
mdpView = (EditText) findViewById(R.id.Mdp);
checkBoutton = (Button) findViewById(R.id.checkButton);
checkBoutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
nom = nomView.getText().toString();
mdp = mdpView.getText().toString();
threadServeur serv = new threadServeur();
try {
serv.execute(nom, mdp, texte).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(!requestLoginInitiator.getStatus())
Toast.makeText(getApplicationContext(),
"Request Login failed, please try again : " + requestLoginInitiator.getError_msg(), Toast.LENGTH_LONG).show();
else {
if (request.getStatus()) {
Intent menuActivity = new Intent(Login.this, Menu.class);
startActivity(menuActivity);
}
else
{
Toast.makeText(getApplicationContext(),
"Request Login failed, please try again : " + requestLoginInitiator.getError_msg(), Toast.LENGTH_LONG).show();
}
}
}
});
checkBoutton.setEnabled(false);
mdpView.setEnabled(false);
nomView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mdpView.setEnabled(true);
}
@Override
public void afterTextChanged(Editable s) {
}
}
);
mdpView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
checkBoutton.setEnabled(true);
}
@Override
public void afterTextChanged(Editable s) {
}
}
);
}
private class threadServeur extends AsyncTask<String, String,Void>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(String... strings) {
contacteServeur(strings[0],strings[1],strings[2]);
return null;
}
}
private void contacteServeur(String n,String m,String test) {
if (serveurSocket == null) {
try {
serveurSocket = new Socket(ipv4Adress, port);
} catch (Exception e) {
System.err.println("Erreur : " + e);
}
try {
objectOutputClient = new ObjectOutputStream(serveurSocket.getOutputStream());
objectInputClient = new ObjectInputStream(serveurSocket.getInputStream());
} catch (IOException e) {
System.err.println("Erreur : " + e);
}
}
try {
requestLoginInitiator = new RequestLoginInitiator();
requestLoginInitiator.setId(BaseRequest.LOGIN_INITIATOR);
requestLoginInitiator.setSaltChallenge(null);
objectOutputClient.writeObject(requestLoginInitiator);
objectOutputClient.flush();
} catch (Exception e) {
System.err.println("Erreur : " + e);
}
try {
requestLoginInitiator = new RequestLoginInitiator();
requestLoginInitiator = (RequestLoginInitiator) objectInputClient.readObject();
} catch (Exception e) {
System.err.println("Erreur lecture des données : " + e);
}
if(requestLoginInitiator.getStatus())
{
requestLogin = new RequestLogin();
requestLogin.setId(BaseRequest.LOGIN_OTP);
requestLogin.setError_msg(null);
MessageDigest md = null;
try{
md = MessageDigest.getInstance("SHA-256");
}
catch(Exception e)
{
System.err.println("Erreur : " + e);
}
Vector<String> component = new Vector<String>();
component.add(requestLoginInitiator.getSaltChallenge());
component.add(n);
component.add(m);
System.out.println("taille vector : " + component.size());
requestLogin.CalculateDigest(md, component);
requestLogin.setUsername(nom);
try {
objectOutputClient.writeObject(requestLogin);
objectOutputClient.flush();
} catch (Exception e) {
System.err.println("Erreur lecture des données : " + e);
}
try {
request = new BaseRequest();
request = (BaseRequest) objectInputClient.readObject();
} catch (Exception e) {
System.err.println("Erreur lecture des données : " + e);
}
}
}
public static ObjectInputStream getInStream()
{
return objectInputClient;
}
public static ObjectOutputStream getOutStream()
{
return objectOutputClient;
}
public static Socket getServerSocket()
{
return serveurSocket;
}
}
| [
"noreply@github.com"
] | Sirorco.noreply@github.com |
d408ffbfb4cc0b187795b3aecb5ada6fa9a4a863 | 6ed184b51ccd1e16d1dc3b2d718bbd872e1fdabd | /Java2DGame/src/mosfet/game/level/tiles/BasicTile.java | a5a06a2b56071b99cc86363b76baa18f9ee36bd6 | [] | no_license | mosfet386/Test | 193315d60114440c8f9bb0163cf6010f187d3cc7 | 8beb36362ed5009a2c3e1b9cb6b7e506a2f360e1 | refs/heads/master | 2020-04-26T19:19:34.958873 | 2014-04-06T20:28:06 | 2014-04-06T20:28:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 642 | java | package mosfet.game.level.tiles;
import mosfet.game.gfx.Screen;
import mosfet.game.level.Level;
public class BasicTile extends Tile{
protected int tileId; //gets assigned manually for each tile in Tile Class
protected int tileColor;
@Override
public void render(Screen screen, Level level, int x, int y) {
screen.render(x,y,tileId,tileColor,0x00,1);
}
@Override
public void tick(){}
//tileColor: actual colors on tile
//levelMapColor: index of level tile
public BasicTile(int id, int x, int y, int tileColor, int levelMapColor) {
super(id,false,false,levelMapColor);
this.tileId=x+y*32;
this.tileColor=tileColor;
}
}
| [
"mosfet386@gmail.com"
] | mosfet386@gmail.com |
fa49c21edfe0b34a044272461fbbb3ac202f0b81 | 49fff718d30ada7bca77135c70bf9d3ca7c03844 | /src/objects/Projects.java | e91ea448acb21496ec69b0b771953fc8bfae2a3f | [] | no_license | ACCount-Nine38/Material-Hazard-Database | 0c1f3fd3a679f36de5700c731927eac1da0a1774 | eef2c363604d597f9f95575f27db84cc7b51a7ba | refs/heads/master | 2022-11-25T20:31:25.311618 | 2020-07-31T05:10:20 | 2020-07-31T05:10:20 | 283,946,862 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,006 | java | package objects;
import java.util.HashMap;
import javax.swing.JTextArea;
public class Projects {
private String name,path;
private HashMap<String, Integer> materials;
private JTextArea environmentalField;
public Projects(String name, HashMap<String, Integer> materials, JTextArea environmentalField) {
this.name = name;
this.materials = materials;
this.environmentalField = environmentalField;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public HashMap<String, Integer> getMaterials() {
return materials;
}
public void setMaterials(HashMap<String, Integer> materials) {
this.materials = materials;
}
public JTextArea getEnvironmentalField() {
return environmentalField;
}
public void setEnvironmentalField(JTextArea environmentalField) {
this.environmentalField = environmentalField;
}
}
| [
"acc938live@gmail.com"
] | acc938live@gmail.com |
ad40df09c7e5d040e67f0243ab26a36752d57024 | 5eae683a6df0c4b97ab1ebcd4724a4bf062c1889 | /bin/ext-integration/sap/synchronousOM/sapordermgmtbol/src/de/hybris/platform/sap/sapordermgmtbol/transaction/salesdocument/backend/interf/erp/ItemBuffer.java | b902cd3bae8909b5605a1cb990b0163a8958bab4 | [] | no_license | sujanrimal/GiftCardProject | 1c5e8fe494e5c59cca58bbc76a755b1b0c0333bb | e0398eec9f4ec436d20764898a0255f32aac3d0c | refs/heads/master | 2020-12-11T18:05:17.413472 | 2020-01-17T18:23:44 | 2020-01-17T18:23:44 | 233,911,127 | 0 | 0 | null | 2020-06-18T15:26:11 | 2020-01-14T18:44:18 | null | UTF-8 | Java | false | false | 1,528 | java | /*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.sap.sapordermgmtbol.transaction.salesdocument.backend.interf.erp;
import de.hybris.platform.sap.sapordermgmtbol.transaction.item.businessobject.interf.Item;
import java.util.Map;
/**
* Helper Interface to Buffer Item data, typically used by ERP backend implementation.<br>
*
*/
public interface ItemBuffer
{
/**
* The list of items which represents the ERP status. We use it to compile a delta to the status we get from the BO
* layer. Aim is to optimise the LO-API call
*
* @return list of items
*/
Map<String, Item> getItemsERPState();
/**
* The list of items which represents the ERP status. We use it to compile a delta to the status we get from the BO
* layer. Aim is to optimise the LO-API call
*
* @param itemsERPState
* list of items
*/
void setItemsERPState(Map<String, Item> itemsERPState);
/**
* Removes item from ERP state map, together with sub items (free goods!)
*
* @param idAsString
* item ID
*/
void removeItemERPState(String idAsString);
/**
* Clears the buffer for the ERP state of the document.
*/
void clearERPBuffer();
} | [
"travis.d.crawford@accenture.com"
] | travis.d.crawford@accenture.com |
fa23cd0714ec6b3fe4c1d658385b248b1bf5ece7 | 9f30fbae8035c2fc1cb681855db1bc32964ffbd4 | /Java/yangqi/Task4/com/jnshu/util/DateTag.java | f000f095bbfdabeedf44c1c7e8f5cbc30a9142fd | [] | no_license | IT-xzy/Task | f2d309cbea962bec628df7be967ac335fd358b15 | 4f72d55b8c9247064b7c15db172fd68415492c48 | refs/heads/master | 2022-12-23T04:53:59.410971 | 2019-06-20T21:14:15 | 2019-06-20T21:14:15 | 126,955,174 | 18 | 395 | null | 2022-12-16T12:17:21 | 2018-03-27T08:34:32 | null | UTF-8 | Java | false | false | 1,362 | java | package com.jnshu.util;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
/* 自定义jsp标签*/
public class DateTag extends TagSupport {
//定义一个的大数
private static final long seriaVersionUID = 6464168398214506236L;
//定义一个值
private String value;
//定义一个方法
@Override
public int doStartTag() throws JspException {
//这部操作暂时没看懂。是一个强制类型转换?但是value本身就是个string啊。
String vv = "" + value;
try {
//将String(字符串)的类型转换为long
long time = Long.valueOf(vv.trim());
//SimpleDateFormat设置出一个时间格式
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date jut = new Date(time * 1000);
//
String s = dateFormat.format(jut);
//继承JspException父类的方法。。在页面打印这个时间?
pageContext.getOut().write(s);
} catch (Exception e) {
e.printStackTrace();
}
//这是一个返回自己的方法。
return super.doStartTag();
}
public void setValue(String value) {
this.value = value;
}
}
| [
"noreply@github.com"
] | IT-xzy.noreply@github.com |
0c15df5560776f97169e39699c4262cae97a0f0c | a4d5169c7827efbff08aed1694ad3ab4aa61c8bd | /src/main/java/entities/library/Toilet.java | f234e66b6da8cb157dadc88843e6aef61cab2389 | [
"MIT"
] | permissive | ErikNikolajsen/Smart-Home-Simulator-Backend | a3396e76c366f1fb7f89667aaf8354b2ac07970f | 5e394d7a9ff2f2b5d42abb15b4fd22f82f63ab76 | refs/heads/main | 2023-07-12T12:51:19.571123 | 2021-08-21T21:04:52 | 2021-08-21T21:04:52 | 338,468,840 | 0 | 1 | null | 2021-06-23T20:56:50 | 2021-02-13T00:51:39 | Java | UTF-8 | Java | false | false | 902 | java | package entities.library;
import java.util.ArrayList;
import java.util.Arrays;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import entities.SensorActive;
public class Toilet extends SensorActive {
public Toilet() throws MqttPersistenceException, MqttException {
}
public ArrayList<String> defineCommands() {
return new ArrayList<String>(Arrays.asList(
"FLUSH"
));
}
public void defineDefaultState() {
state.put("flush_amount", 0);
state.put("consumed_water", 0.0); // in Liters
}
// Sensor behavior
public void updateState(String command) throws MqttPersistenceException, MqttException {
// Set power status
if (command.equals("FLUSH")) {
state.put("flush_amount", (Integer) state.get("flush_amount") + 1);
state.put("consumed_water", (Double) state.get("consumed_water") + 3.3);
}
}
}
| [
"erik.nikolajsen@gmail.com"
] | erik.nikolajsen@gmail.com |
30f8b0665f0a8f0859150805367ab1a566cd8650 | 6ee47fa5d335ca0aa68e0253d7bf5201ab189ff8 | /Sorting/Shell.java | 48d39ebafa21af93bfa693ffb3dced57486cb717 | [] | no_license | lucypeony/algs4 | d1a04acfc088658f910fbae4d87917cd0525a1f8 | 50e74dd6d6e75cb9910ac8eba9e82221d1580da9 | refs/heads/master | 2021-01-18T11:19:56.987433 | 2016-06-01T08:35:10 | 2016-06-01T08:35:10 | 56,116,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,440 | java | import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
//import edu.princeton.cs.algs4.StdRandom;
public class Shell
{
public static void sort(Comparable[] a)
{
//Sort a[] into increasing order
int N=a.length;
int h=1;
while(h<N/3) h=3*h+1;
while(h>=1)
{
//h-sort the array
for(int i=h;i<N;i++)
{
//Insert a[i] among a[i-h],a[i-2*h],a[i-3*h] ...
for(int j=i;j>=h && less(a[j],a[j-h]);j-=h)
exch(a,j,j-h);
}
h=h/3;
}
}
private static boolean less(Comparable v,Comparable w)
{
return v.compareTo(w)<0;
}
private static void exch(Comparable[] a, int i,int j)
{
Comparable t=a[i];
a[i]=a[j];
a[j]=t;
}
private static void show(Comparable[] a)
{
for(int i=0;i<a.length;i++)
StdOut.print(a[i]+" ");
StdOut.println();
}
public static boolean isSorted(Comparable[] a)
{
for(int i=1;i<a.length;i++)
if(less(a[i],a[i-1]))
return false;
return true;
}
public static void main(String[] args)
{
String[] a=In.readStrings();
sort(a);
assert isSorted(a);
show(a);
}
}
| [
"lucypeony@gmail.com"
] | lucypeony@gmail.com |
2905facf556c23dc67fafaca418f0253939b21bd | 861a37962ed9655c15731fcfe3ffb2d415010fe6 | /PalindromePartitioning.java | a1de55c6fda4a189e018882ce0582404c81afeda | [
"MIT"
] | permissive | fang19911030/Leetcode | ee877f74fccb4929c6bfa50cefc68447c0fa848b | b1014e222d9223b4554acf4a2c57ec0eeeafc7ee | refs/heads/master | 2021-01-19T21:13:23.809994 | 2017-07-25T01:31:19 | 2017-07-25T01:31:19 | 88,628,756 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,132 | java | public class Solution {
List<List<String>> res;
List<String> cur;
public List<List<String>> partition(String s) {
res = new LinkedList<>();
cur = new LinkedList<>();
if(s == null){
return res;
}
backTrack(s, 0);
return res;
}
public void backTrack(String s, int l){
if(cur.size()> 0 && l >= s.length()){
List<String> r = new LinkedList<>(cur);
res.add(r);
}
for(int i=l;i<s.length();i++){
if(isPalindrome(s,l,i)){
if(l==i){
cur.add(Character.toString(s.charAt(i)));
}else{
cur.add(s.substring(l,i+1));
}
backTrack(s,i+1);
cur.remove(cur.size()-1);
}
}
}
private boolean isPalindrome(String s,int l, int r){
int left = l;
int right = r;
while(left<right){
if(s.charAt(left++) != s.charAt(right--)){
return false;
}
}
return true;
}
} | [
"fang291831388@gmail.com"
] | fang291831388@gmail.com |
31d27b2774fac5c5cb3567dbc090aa078981bd9f | be3e51d86bab463da7127d8634459f6d491b6562 | /src/raft/EhsegEsSzomjusag.java | 41d72cae9b5e4b9280959e982ab81a15831128c6 | [] | no_license | FMisi/Raft | e1a4001fc167a154f23dec3cea1d794b31b705fe | 1924be154f2e1b059b4433f35f0f44fe41be8d70 | refs/heads/main | 2023-04-28T04:41:31.480874 | 2021-04-29T14:16:45 | 2021-04-29T14:16:45 | 349,959,572 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 54 | java | package raft;
public class EhsegEsSzomjusag {
}
| [
"felegyimisi@gmail.com"
] | felegyimisi@gmail.com |
d9cf3c58bb2fb0e6cb367753a957607583a66d9a | 3bf3f766172f9eab486a7c002a2b64a75c2c62b8 | /app/src/main/java/com/example/mymap/MyGalleryAdapter.java | cd04b83c37d3c948e3f0560d58797da748d0dd5b | [] | no_license | vietxb0911/SaiGonTrip-AndroidAppDev | 6095da72da47bbb7aa50b52ccdd2576637b27434 | 82543aec5c1fe5f51b79d232b90506ff993a0953 | refs/heads/main | 2023-02-26T12:29:08.103736 | 2020-11-30T16:05:45 | 2020-11-30T16:05:45 | 336,029,311 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,499 | java | package com.example.mymap;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.io.File;
import java.util.ArrayList;
public class MyGalleryAdapter extends RecyclerView.Adapter<MyGalleryAdapter.MyViewHolder> {
@Override
public MyGalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View photoView = inflater.inflate(R.layout.acitivity_gallery_recyclerview_item, parent, false);
MyGalleryAdapter.MyViewHolder viewHolder = new MyGalleryAdapter.MyViewHolder(photoView);
return viewHolder;
}
@Override
public void onBindViewHolder(MyGalleryAdapter.MyViewHolder holder, int position) {
MyPhoto myPhoto = mMyPhotos.get(position);
ImageView imageView = holder.mPhotoImageView;
File file = new File(myPhoto.getUrl());
Uri imageUri = Uri.fromFile(file);
Glide.with(mContext)
.load(imageUri)
.placeholder(R.drawable.ic_launcher_foreground)
.into(imageView);
}
@Override
public int getItemCount() {
return (mMyPhotos.size());
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView mPhotoImageView;
public MyViewHolder(View itemView) {
super(itemView);
mPhotoImageView = (ImageView) itemView.findViewById(R.id.iv_photo);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION) {
MyPhoto myPhoto = mMyPhotos.get(position);
Intent intent = new Intent(mContext, PhotoActivity.class);
intent.putExtra(PhotoActivity.EXTRA_SPACE_PHOTO, myPhoto);
mContext.startActivity(intent);
}
}
}
private ArrayList<MyPhoto> mMyPhotos;
private Context mContext;
public MyGalleryAdapter(Context context, ArrayList<MyPhoto> MyPhotos) {
mContext = context;
mMyPhotos = MyPhotos;
}
}
| [
"nguyenthaison164hv@gmail.com"
] | nguyenthaison164hv@gmail.com |
81cc853888588826e97e8f1f0c9e7373850307e4 | 934002fbaa68a1e014161445fd770ea31438237c | /cloud-web/src/main/java/com/kaka/cloud/controller/HealthController.java | 2cbfa0b225bbadd8c26c7ebaee1636ad966b7372 | [] | no_license | kaka3511/cloud | e36407f16bbe4c1f7b3012b71b6550eb85831e4e | 76a8afddd29b22fa7cf478b8c4a80c669ab78145 | refs/heads/master | 2020-03-21T05:04:34.118909 | 2018-12-25T12:10:15 | 2018-12-25T12:10:15 | 138,142,907 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,216 | java | package com.kaka.cloud.controller;
import com.kaka.cloud.api.AppInfoApi;
import com.kaka.cloud.common.ServiceRequestDto;
import com.kaka.cloud.common.ServiceResultDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author fuwei
* @version V1.0
* @Description: TODO(用一句话描述该文件做什么)
* @date 2018/6/26 11:22
*/
@Controller
@EnableAutoConfiguration
@CrossOrigin(value = "*" ,maxAge = 360)
public class HealthController {
@Autowired
private AppInfoApi appInfoApi;
@RequestMapping(value = "/healthCheck", method = RequestMethod.GET)
@ResponseBody
public ServiceResultDto healthCheck() {
return appInfoApi.getAppInfo(new ServiceRequestDto());
}
@RequestMapping(value = "/healthCheck2", method = RequestMethod.GET)
@ResponseBody
public String healthCheck2(){
return "";
}
}
| [
"fuwei@iboxpay.com"
] | fuwei@iboxpay.com |
5853c7db19f86c7fb2beeecebfea710318aed56c | 94ed7e41d9029e93e6ee1949502e9208acda8e07 | /Guía2/src/com/senati/eti/Caso1.java | ba74889e9a67975c7e6d6f728d45bb201b83728d | [] | no_license | Edu-code-444/guia2 | a73d59245e660537e9fe6a7f71756338b0783c87 | 3146b4c2ea70148ad3452ed7e3d755211f33c537 | refs/heads/master | 2023-03-29T04:50:24.128399 | 2021-03-30T22:14:55 | 2021-03-30T22:14:55 | 353,153,835 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 358 | java | package com.senati.eti;
import java.util.Scanner;
public class Caso1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Ingrese edad: ");
int edad = sc.nextInt();
if (edad >= 18)
System.out.println("Mayor de edad");
else
System.out.println("Menor de edad");
}
}
| [
"AXEL@LAPTOP-15BNULUM"
] | AXEL@LAPTOP-15BNULUM |
2c88d8da9fbefeb1fded764250d85e96315af376 | 1dff4b9816588af53eed89728d1aa46d189e8d9c | /MobileSurveyRest/src/main/java/com/safasoft/mobilesurvey/rest/bean/MasterRole.java | 60916baf1ef551ec8cfb505e94f70a27cb5e4ffb | [] | no_license | awaludinhamid/MobileSurveyRest | 0ee530ab426f337ec2ac4026d6f52e1925d449b0 | 1d7346de050682fe5785cd8d78cedee59fe05805 | refs/heads/master | 2021-07-05T17:16:10.500647 | 2017-09-29T07:44:42 | 2017-09-29T07:44:42 | 105,227,771 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,719 | java | package com.safasoft.mobilesurvey.rest.bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.safasoft.mobilesurvey.rest.bean.support.ActiveRecordAuditBean;
/**
* POJO table MASTER_ROLE
* @created Apr 4, 2016
* @author awal
*/
@SuppressWarnings("serial")
@Entity
@Table(name="MASTER_ROLE")
public class MasterRole extends ActiveRecordAuditBean {
@Id
@Column(name="ROLE_ID")
private int roleId;
@Column(name="ROLE_CODE")
private String roleCode;
@Column(name="ROLE_NAME")
private String roleName;
@Column(name="ROLE_DESC")
private String roleDesc;
@Column(name="ROLE_LEVEL")
private int roleLevel;
@ManyToOne
@JoinColumn(name="ROLE_TYPE_ID")
private MasterRoleType roleType;
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
public int getRoleLevel() {
return roleLevel;
}
public void setRoleLevel(int roleLevel) {
this.roleLevel = roleLevel;
}
public MasterRoleType getRoleType() {
return roleType;
}
public void setRoleType(MasterRoleType roleType) {
this.roleType = roleType;
}
}
| [
"ahamid.dimaha@gmail.com"
] | ahamid.dimaha@gmail.com |
95e7662eb120a55ad5cc3ad53fd9830e30fb97c6 | 793971b09e189564a1a66849f66fbe021140322d | /src/main/java/com/ecogeo/model/AmpItem.java | e14349c6adb6267d2d64cd84dee7b1a2d5a91219 | [] | no_license | Shane0531/ecogeo | 7c3f01a85c59a1ac3b864580bc391962df2e274b | d8fe95e086ae90c175c0ead73240f7cd42c3a2e6 | refs/heads/master | 2021-04-18T22:08:34.943443 | 2019-05-27T01:04:00 | 2019-05-27T01:04:00 | 126,810,573 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 725 | java | package com.ecogeo.model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
/**
* 양서류
*/
@Data
@Entity
@EqualsAndHashCode(callSuper = true)
public class AmpItem extends Item {
public AmpItem() {
}
public AmpItem(String name) {
this.realName = name;
}
@Override
public String getETC() {
String etc = "";
if(propCrisis != null && !propCrisis.isEmpty()) etc += propCrisis;
if((propCrisis != null && !propCrisis.isEmpty()) && (propOrigin != null && !propOrigin.isEmpty())) etc += ", ";
if(propOrigin != null && !propOrigin.isEmpty()) etc += "고";
if((propEcosystem != null && !propEcosystem.isEmpty())) etc += "교";
return etc;
}
}
| [
"tjdghks0531@gmail.com"
] | tjdghks0531@gmail.com |
7e4be01b0d870d8126221be727583125b63c5e7b | 736868517061bc87026d65cb60ef71dab77c527c | /app/src/androidTest/java/com/example/jonas/wetter/ExampleInstrumentedTest.java | 9d94193425da2008ae66c7c15ddb2fa710e3f6c4 | [] | no_license | jonas-st/android-zamg-weather | 21fa19faa0eb84c3151778e192804f9b6fab9438 | 962efb8fe37815111aea170c667ecf572927891e | refs/heads/master | 2020-04-03T02:15:05.694109 | 2018-11-01T11:39:00 | 2018-11-01T11:39:00 | 154,951,021 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 758 | java | package com.example.jonas.wetter;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.jonas.wetter", appContext.getPackageName());
}
}
| [
"jonas.stock@googlemail.com"
] | jonas.stock@googlemail.com |
e709fea929b5447409602d1e03d84ff149ba6a11 | 013acc5cb7e3c3a12e01f8a9bfbf6bf3471c3749 | /common-utils/src/main/java/com/zlead/utils/FileMd5Util.java | 0ce371a1babb7c13ef02c71f44b0972040a47799 | [] | no_license | nayunhao/zlw | 3f86437e938f8a35cfd6af3ec2e47bc24e5d71c9 | 7551fe0d2790399e1b39a76b9b74f57dff8692ec | refs/heads/master | 2022-12-29T00:01:05.248214 | 2019-06-21T02:45:14 | 2019-06-21T02:45:14 | 193,016,477 | 0 | 0 | null | 2022-12-16T04:59:41 | 2019-06-21T02:27:23 | Java | UTF-8 | Java | false | false | 1,898 | java | package com.zlead.utils;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
/**
* @author yangting
* 文件的MD5值
*
*/
public class FileMd5Util {
/**
* 获取单个文件的MD5值!
* @param file
* @return
*/
public static String getFileMD5(File file) {
if (!file.isFile()){
return null;
}
MessageDigest digest = null;
FileInputStream in=null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
}
/**
* 获取文件夹中文件的MD5值
* @param file
* @param listChild ;true递归子目录中的文件
* @return
*/
public static Map<String, String> getDirMD5(File file,boolean listChild) {
if(!file.isDirectory()){
return null;
}
//<filepath,md5>
Map<String, String> map=new HashMap<String, String>();
String md5;
File files[]=file.listFiles();
for(int i=0;i<files.length;i++){
File f=files[i];
if(f.isDirectory()&&listChild){
map.putAll(getDirMD5(f, listChild));
} else {
md5=getFileMD5(f);
if(md5!=null){
map.put(f.getPath(), md5);
}
}
}
return map;
}
public static void main(String[] args) {
File file1 = new File("a.txt");
File file2 = new File("b.txt");
System.out.println(getFileMD5(file1).equals(getFileMD5(file2)));
}
}
| [
"yunhao1104@126.com"
] | yunhao1104@126.com |
d81e807b404b69828f41457086fdb2791e6d3f25 | a7ac6b15261ec7927346abbc7c8b6ae078157f26 | /src/com/jiehoo/jpm/core/Tag.java | 9a4f089562a81f47690b2a4931a986b76a969da1 | [] | no_license | lkerr24/java-picture-manager | f044e1511319a2bc003cdae67a48ceadfb6e24cd | ba5e02759fb2cf01d126ad618ed62fc209f4b5cb | refs/heads/master | 2021-03-12T23:58:21.089208 | 2011-04-06T02:31:44 | 2011-04-06T02:31:44 | 39,370,832 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,067 | java | package com.jiehoo.jpm.core;
import java.util.Date;
public class Tag {
private int ID;
private String name;
private Date lastUsedTime;
private int usedTimes;
public int getID() {
return ID;
}
public void setID(int id) {
ID = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastUsedTime() {
return lastUsedTime;
}
public void setLastUsedTime(Date lastUsedTime) {
this.lastUsedTime = lastUsedTime;
}
public int getUsedTimes() {
return usedTimes;
}
public void use() {
lastUsedTime = new Date();
usedTimes++;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Tag) {
Tag other = (Tag) obj;
return ID == other.ID;
}
return false;
}
@Override
public int hashCode() {
return ID;
}
}
| [
"cherami.lm@gmail.com"
] | cherami.lm@gmail.com |
879a39a1cc59819823aca30fa0a4dfe45b9beb5e | 046e8449407cdb268b0f590b7fcb90340e4d8618 | /src/main/java/com/ticketlog/server/repository/EstadoRepository.java | 59872439e539ab9f148fe69878fa7bff7422f4ce | [] | no_license | regisrfn/TCS-TICKETLOG | 44743c6c40d8c43aa06a4b5e2a317dd75c4ab9b7 | 0db0087e206221de47671ccd9c4c2048b151ab0c | refs/heads/main | 2023-03-05T09:51:40.092732 | 2021-02-19T22:39:52 | 2021-02-19T22:39:52 | 340,094,022 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,447 | java | package com.ticketlog.server.repository;
import java.util.List;
import com.ticketlog.server.dao.EstadoDao;
import com.ticketlog.server.dao.JpaDao;
import com.ticketlog.server.model.Estado;
import com.ticketlog.server.model.Estado.UF;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class EstadoRepository implements EstadoDao {
private JpaDao jpaDataAccess;
@Autowired
public EstadoRepository(JpaDao jpaDataAccess, JdbcTemplate jdbcTemplate) {
this.jpaDataAccess = jpaDataAccess;
}
@Override
public Estado insertEstado(Estado Estado) {
return jpaDataAccess.save(Estado);
}
@Override
public boolean deleteEstadoById(UF id) {
try {
jpaDataAccess.deleteById(id);
return true;
} catch (EmptyResultDataAccessException e) {
e.printStackTrace();
return false;
}
}
@Override
public List<Estado> getAll() {
return jpaDataAccess.findAll();
}
@Override
public Estado getEstado(UF id) {
return jpaDataAccess.findById(id).orElse(null);
}
@Override
public Estado updateEstado(UF id, Estado Estado) {
Estado.setId(id);
return jpaDataAccess.save(Estado);
}
} | [
"regis.rfnrodrigues@gmail.com"
] | regis.rfnrodrigues@gmail.com |
0e84022b64f6d20c4503fffc64d5199856d591cc | 8238479e31641e0c6ab6ab9c21b69abdaa2d6421 | /src/main/java/br/com/alura/jpa/testes/CriarTabelaConta.java | 112d666cbe15f2ff0ffbb262b0d5cd108ad882c1 | [] | no_license | leonardo-teles/financas | c8111c53e4bab6871da51aa95cf61fa142e01985 | a1a562a3c4221e00666e81a46a03cb0086fcd45d | refs/heads/master | 2023-08-10T07:09:48.461563 | 2020-05-05T01:46:42 | 2020-05-05T01:46:42 | 261,334,232 | 1 | 0 | null | 2023-07-23T15:01:46 | 2020-05-05T01:25:26 | Java | UTF-8 | Java | false | false | 299 | java | package br.com.alura.jpa.testes;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class CriarTabelaConta {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("financas");
emf.close();
}
}
| [
"leonardo.teles.almeida@gmail.com"
] | leonardo.teles.almeida@gmail.com |
f62e922b4610310c73b016fca421a96f2695a11f | b559148d9dce141d4a8150f5f9b69a05a90cbe1d | /megastorestorefront/web/src/org/megastore/storefront/controllers/misc/FavIconController.java | cfd0603367cea8d9c4c36ead40b50757db5f57d5 | [] | no_license | Devashish9393/HYB-Megastore | 37bf32a9c4e4da54efc452f0ebc2dd91a01291d1 | fe3089a38b2c2abaec372315d4393d2bbf8ccaee | refs/heads/master | 2021-01-22T19:04:12.318971 | 2017-03-16T06:58:13 | 2017-03-16T06:58:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,260 | java | /*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 hybris AG
* All rights reserved.
*
* This software is the confidential and proprietary information of hybris
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with hybris.
*
*
*/
package org.megastore.storefront.controllers.misc;
import de.hybris.platform.acceleratorstorefrontcommons.controllers.AbstractController;
import de.hybris.platform.cms2.misc.UrlUtils;
import de.hybris.platform.servicelayer.i18n.I18NService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.context.ThemeSource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ThemeResolver;
/**
* Controller for evil clients that go for the favicon.ico directly in the root, redirect them to the real location
*/
@Controller
@Scope("tenant")
public class FavIconController extends AbstractController
{
private static final String FAVICON_THEME_CODE = "img.favIcon";
private static final String ORIGINAL_CONTEXT = "originalContextPath";
@Resource(name = "themeResolver")
private ThemeResolver themeResolver;
@Resource(name = "themeSource")
private ThemeSource themeSource;
@Resource(name = "i18nService")
private I18NService i18nService;
@RequestMapping(value = "/favicon.ico", method = RequestMethod.GET)
public String getFavIcon(final HttpServletRequest request)
{
final String themeName = themeResolver.resolveThemeName(request);
String iconPath = themeSource.getTheme(themeName).getMessageSource()
.getMessage(FAVICON_THEME_CODE, new Object[]{}, i18nService.getCurrentLocale());
final String originalContextPath = (String) request.getAttribute(ORIGINAL_CONTEXT);
final String hostUrl = UrlUtils.extractHostInformationFromRequest(request);
iconPath = hostUrl + originalContextPath + iconPath;
return REDIRECT_PREFIX + iconPath;
}
}
| [
"r.bokolia@replyltd.co.uk"
] | r.bokolia@replyltd.co.uk |
40843133375aaed1cd3333eef611a92fb2da083a | c5f75578eb1eaa39bb372d5d3ec008dd413916f4 | /src/is/ucm/exceptions/UserNotFoundException.java | 12938fb767238c6ff4b51ae8163be0749d67a09e | [] | no_license | diegoambite/Ifridge | dfc2bf0bca66d14edd462e9de6b1c070a33158c3 | 4f3d881d86500f04cc0d0fcf3165a94f61948eca | refs/heads/master | 2020-03-10T05:26:22.726146 | 2018-05-20T17:32:58 | 2018-05-20T17:32:58 | 129,217,823 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 312 | java | package is.ucm.exceptions;
/**
* Exception thrown by the UserDAO when trying to retrieve a User from the database and fail.
* @author iFridge team
*/
@SuppressWarnings("serial")
public class UserNotFoundException extends Exception {
public UserNotFoundException(String message) {
super(message);
}
}
| [
"alessio.papi@live.it"
] | alessio.papi@live.it |
2f8aeb6120f78a540924d2c7d2663e61fb7d9f1a | 62f1ba70236ff53de638a4e0e4fb71ac41743bae | /Selenium-Automation-Elearning-Framework-TestNG/tests/com/training/sanity/tests/SecondCategories.java | b05fb6089fac06db2ce0556ae2a506f9df517300 | [] | no_license | PrathimaR88/RetailProject | 528b0891c037836006648ff5f0fdb3e9e0a75b05 | ea3b3629e8475073b4671991cd53ab19e1fe4fe3 | refs/heads/master | 2022-07-08T02:01:36.182910 | 2019-11-09T07:19:37 | 2019-11-09T07:19:37 | 219,672,265 | 0 | 0 | null | 2022-06-21T02:10:27 | 2019-11-05T06:20:23 | Java | UTF-8 | Java | false | false | 1,838 | java | package com.training.sanity.tests;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.training.pom.AdminLoginPOM;
import com.training.pom.CatalogCategoriesPOM;
import com.training.pom.GenericLoginPOM;
import com.training.utility.DriverFactory;
import com.training.utility.DriverNames;
public class SecondCategories {
private WebDriver driver;
private String adminUrl;
private GenericLoginPOM loginPOM;
private CatalogCategoriesPOM CataPOM;
private static Properties properties;
@BeforeClass
public static void setUpBeforeClass() throws IOException {
properties = new Properties();
FileInputStream inStream = new FileInputStream("./resources/others.properties");
properties.load(inStream);
}
@BeforeMethod
public void setUp() throws Exception {
driver = DriverFactory.getDriver(DriverNames.CHROME);
loginPOM = new GenericLoginPOM(driver);
CataPOM = new CatalogCategoriesPOM(driver);
adminUrl = properties.getProperty("adminURL");
}
@AfterMethod
public void tearDown() throws Exception {
Thread.sleep(1000);
//driver.quit();
}
@Test()
//******RTTC_012 To Verify whether application allows the admin to display list of Categories
public void ValidateCatalog() throws InterruptedException {
driver.get(adminUrl);
loginPOM.Login("admin", "admin@123");
CataPOM.clickOnCategory();
Thread.sleep(7000);
driver.quit();
}
}
| [
"PrathimaR@DESKTOP-IEBHE6F"
] | PrathimaR@DESKTOP-IEBHE6F |
880391bd1555a8350a332b33b4940766f850c39a | ae7f758d4b4abb0f06d735bb9a1dba4804757541 | /ulpay-platform/src/main/java/com/ulpay/testplatform/service/ITestResultService.java | 58c2f2c2c4d36632f09aa8b55c351fe91c198ae6 | [
"MIT"
] | permissive | CalmDownsy/TestPlatform | 5d778c429ec468859c9725d0c49add3fd149bfc6 | d7747a62cc296b8fcd2f3b80f60a0d1bde067e75 | refs/heads/master | 2022-09-24T19:32:38.835393 | 2020-09-11T04:02:01 | 2020-09-11T04:02:01 | 209,929,857 | 1 | 0 | MIT | 2022-09-01T23:13:25 | 2019-09-21T05:25:27 | HTML | UTF-8 | Java | false | false | 1,455 | java | package com.ulpay.testplatform.service;
import com.ulpay.testplatform.domain.TestResult;
import java.util.List;
/**
* 测试计划执行结果Service接口
*
* @author zhangsy
* @date 2019-10-31
*/
public interface ITestResultService
{
/**
* 查询测试计划执行结果
*
* @param resultId 测试计划执行结果ID
* @return 测试计划执行结果
*/
public TestResult selectTestResultById(Long resultId);
/**
* 查询测试计划执行结果列表
*
* @param testResult 测试计划执行结果
* @return 测试计划执行结果集合
*/
public List<TestResult> selectTestResultList(TestResult testResult);
/**
* 新增测试计划执行结果
*
* @param testResult 测试计划执行结果
* @return 结果
*/
public int insertTestResult(TestResult testResult);
/**
* 修改测试计划执行结果
*
* @param testResult 测试计划执行结果
* @return 结果
*/
public int updateTestResult(TestResult testResult);
/**
* 批量删除测试计划执行结果
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteTestResultByIds(String ids);
/**
* 删除测试计划执行结果信息
*
* @param resultId 测试计划执行结果ID
* @return 结果
*/
public int deleteTestResultById(Long resultId);
}
| [
"zhangsy011@ulpay.com"
] | zhangsy011@ulpay.com |
5e8599901522034dcb5457f9ffe1f4be5c52b9ff | 92021bd3c8bb139fdc041d4a63ec87a22d340dc6 | /02_讲义/第三阶段/Dubbo/code/第二部分/demo-base-threadpool/service-provider/src/main/java/com/lagou/service/impl/HelloServiceImpl.java | 30d290eb12f4b143f6ddca00fe8d80c18acae7a4 | [] | no_license | waiting0324/Java_L2_2019.12.23 | a3403947536a7591f02e8c26b4bc17b21e016c87 | 00f087bc592ed1f22857ceef19510e152bbc3b68 | refs/heads/master | 2022-11-11T18:17:05.177281 | 2020-07-05T05:17:04 | 2020-07-05T05:17:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 314 | java | package com.lagou.service.impl;
import com.lagou.service.HelloService;
import org.apache.dubbo.config.annotation.Service;
@Service
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello(String name, int timeToWait) {
return "hello3:"+name;
}
}
| [
"lagouedu@lagou.com"
] | lagouedu@lagou.com |
d0875964fb2552ef42522b184619b80b988f63be | 3088c014ba29ccaad67a9e4cead2cb0826d81c50 | /ASOUB_Lesson/Students/Examples/Week2/Calculator.java | af0c3e40d26283964ec5f6e0fd51bfca6d8e8a51 | [] | no_license | khangaikhuu/cs_introduction | 1abeb0d5c6d342975db984a6007abaa9be3b8bc1 | 8a6a9156c222631e147a47df8c8fb95f0d24261a | refs/heads/master | 2021-07-15T21:09:50.421587 | 2019-01-18T00:57:06 | 2019-01-18T00:57:06 | 147,441,523 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 464 | java |
/**
* Write a description of class Calculator here.
*
* @author (Ochirbileg)
* @version (2018)
*/
public class Calculator
{
private int Var1=1;
private int Var2=3;
public int addNumbers()
{
return Var1 + Var2;
}
public int subtractNumber()
{
return Var2 - Var1;
}
public int divideNumbers()
{
return Var1 / Var2;
}
public int multiplyNumbers()
{
return Var1 * Var2;
}
}
| [
"anandbayarbat@gmail.com"
] | anandbayarbat@gmail.com |
86a9e9b67798d4e6c06f5d189986a0efb502fc3a | 252b4248359a278cd1620007c9720a06f6d01d85 | /src/main/java/net/systemexklusiv/controllerman/beatstepconverter/FileToListOfLinesReader.java | e8b5b206231bfdebae73eb50d13c829735fbeba1 | [
"MIT"
] | permissive | systemexklusiv/beatstep-converter | 4883a74cce61d0680356a69b2ad4089e818d3038 | 24195e73870d3f2c44ce0dbce32bc0fc3aa4d7dd | refs/heads/main | 2023-04-25T19:51:11.504163 | 2021-05-22T14:18:14 | 2021-05-22T14:18:14 | 356,523,189 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,292 | java | package net.systemexklusiv.controllerman.beatstepconverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FileToListOfLinesReader implements HasFileToListOfLinesReader {
private final String filePath;
private static final Logger logger = LoggerFactory.getLogger(FileToListOfLinesReader.class);
public FileToListOfLinesReader(String filePath) {
this.filePath = filePath;
}
public List<String> getContendAsListOfLines() {
Path path = null;
Stream<String> lineStream = null;
try {
FileSystemResource res = new FileSystemResource(filePath);
path = Path.of(res.getURI());
lineStream = Files.lines(path);
return lineStream.collect(Collectors.toList());
} catch (IOException e) {
// e.printStackTrace();
logger.error("Can not find File: " + filePath);
logger.error(e.getMessage());
return Collections.EMPTY_LIST;
} finally {
}
}
}
| [
"sytemexklusiv@gmail.com"
] | sytemexklusiv@gmail.com |
824b71121413818354ab22ef476669a41a4e4b9c | 63fe37b269d2866092ff18cc6a39ef91d6538a25 | /top K elements/RearrangeString.java | c67375107c3d0e6307978b9c06047cbb313c860c | [] | no_license | henryxuy/algorithmPattern | 3091d672d43b37054f31042b730bcfc595fcd22b | 59f29625301166bc0e54cd9be60ac1a9ba79c65a | refs/heads/master | 2023-03-21T06:02:20.285105 | 2021-03-17T16:34:08 | 2021-03-17T16:34:08 | 348,778,891 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,441 | java | import java.util.*;
public class RearrangeString {
private static class CharWithFreq{
char ch;
int freq;
CharWithFreq(char ch, int freq){
this.ch = ch;
this.freq = freq;
}
}
public static String rearrangeString(String str) {
int N = str.length();
HashMap<Character, Integer> freqMap = new HashMap<>();
PriorityQueue<CharWithFreq> maxHeap = new PriorityQueue<>((o1, o2) -> Integer.compare(o2.freq, o1.freq));
for(int i = 0; i < N; i++){
char currentChar = str.charAt(i);
freqMap.put(currentChar, freqMap.getOrDefault(currentChar, 0) + 1);
}
for(Map.Entry<Character, Integer> entry: freqMap.entrySet()){
CharWithFreq currentCharInstance = new CharWithFreq(entry.getKey(), entry.getValue());
maxHeap.offer(currentCharInstance);
}
// construct the string
StringBuilder resultStr = new StringBuilder();
CharWithFreq previousCharInstance = null;
while(!maxHeap.isEmpty()){
// add the char in intersected order. poll() and reserve it to avoid adding it twice continuously
CharWithFreq currentCharInstance = maxHeap.poll();
resultStr.append(currentCharInstance.ch);
currentCharInstance.freq--;
if(previousCharInstance != null){
maxHeap.offer(previousCharInstance);
}
previousCharInstance = currentCharInstance.freq == 0 ? null : currentCharInstance;
}
return resultStr.length() == str.length() ? resultStr.toString() : "";
}
public static String rearrangeStringAnswer(String str) {
Map<Character, Integer> charFrequencyMap = new HashMap<>();
for (char chr : str.toCharArray())
charFrequencyMap.put(chr, charFrequencyMap.getOrDefault(chr, 0) + 1);
PriorityQueue<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<Map.Entry<Character, Integer>>(
(e1, e2) -> e2.getValue() - e1.getValue());
// add all characters to the max heap
maxHeap.addAll(charFrequencyMap.entrySet());
Map.Entry<Character, Integer> previousEntry = null;
StringBuilder resultString = new StringBuilder(str.length());
while (!maxHeap.isEmpty()) {
Map.Entry<Character, Integer> currentEntry = maxHeap.poll();
// add the previous entry back in the heap if its frequency is greater than zero
if (previousEntry != null && previousEntry.getValue() > 0)
maxHeap.offer(previousEntry);
// append the current character to the result string and decrement its count
resultString.append(currentEntry.getKey());
currentEntry.setValue(currentEntry.getValue() - 1);
previousEntry = currentEntry;
}
// if we were successful in appending all the characters to the result string, return it
return resultString.length() == str.length() ? resultString.toString() : "";
}
public static void main(String[] args) {
System.out.println("Rearranged string: " + RearrangeString.rearrangeString("aappp"));
System.out.println("Rearranged string: " + RearrangeString.rearrangeString("Programming"));
System.out.println("Rearranged string: " + RearrangeString.rearrangeString("aapa"));
}
}
| [
"605513104@qq.com"
] | 605513104@qq.com |
8d792ae8ae481f4be14a5b22ff7fa3899f124f77 | 0e810d212047a5383fb010a687f27100ae406eef | /app/src/main/java/qingguoguo/com/mvpdemo/mvp/base/BaseMvpActivity.java | b994570ca7a10ba23ab01aea5c33d7f509ee8220 | [] | no_license | qingguoguo/MVPDemo | 6da58275dfbe17a1184fb2dc464e197e7fe8aaf2 | 61aa518a07452d0f51f22a6e70b00735acf0d635 | refs/heads/master | 2021-10-25T06:42:03.112788 | 2019-04-02T13:31:03 | 2019-04-02T13:31:03 | 115,644,884 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,330 | java | package qingguoguo.com.mvpdemo.mvp.base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import qingguoguo.com.mvpdemo.mvp.InjectPresenter;
import qingguoguo.com.mvpdemo.mvp.Utils;
/**
* 作者:qingguoguo
* 创建日期:2018/1/7 on 15:56
* 描述:
* 1.反射动态创建 Model
* 2.通过注解解决多个 Presenter,泛型保留,方便只有一个 Presenter 的情况
*/
public abstract class BaseMvpActivity<V extends BaseMvpView, P extends BaseMvpPresenter> extends AppCompatActivity implements BaseMvpView {
private P mPresenter;
private List<BaseMvpPresenter> mBasePresenters;
public P getPresenter() {
return mPresenter;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView();
createAndAttachView();
initView();
initData();
}
private void createAndAttachView() {
mBasePresenters = new ArrayList<>();
mPresenter = createPresenter();
// 保留该方法是为了方便只有一个P的情况
Utils.checkNotNull(mPresenter, "mPresenter 不能为 null");
mPresenter.attachView(this);
// @InjectPresenter
// LoginPresenter mLoginPresenter
Field[] declaredFields = this.getClass().getDeclaredFields();
for (Field field : declaredFields) {
InjectPresenter annotation = field.getAnnotation(InjectPresenter.class);
if (annotation != null) {
Class<?> fieldClazz = field.getType();
// 要判断一下类型 获取父类,如果不是 BasePresenter 的子类 抛异常
if (!BaseMvpPresenter.class.isAssignableFrom(fieldClazz)) {
throw new RuntimeException("InjectPresenter 注解的属性应该是 BaseMvpPresenter 的子类");
}
try {
BaseMvpPresenter basePresenter = (BaseMvpPresenter) fieldClazz.newInstance();
field.setAccessible(true);
field.set(this, basePresenter);
basePresenter.attachView(this);
mBasePresenters.add(basePresenter);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
/**
* 允许子类空实现 createPresenter 方法
* 保留该方法是为了方便只有一个P的情况
*
* @return
*/
protected abstract P createPresenter();
protected abstract void initView();
protected abstract void initData();
/**
* 子类调用 setContentView 方法
*/
protected abstract void setContentView();
@Override
protected void onDestroy() {
// 解绑
if (mBasePresenters != null) {
for (BaseMvpPresenter presenter : mBasePresenters) {
presenter.detachView();
}
}
if (mPresenter != null) {
mPresenter.detachView();
}
super.onDestroy();
}
}
| [
"350051556@qq.com"
] | 350051556@qq.com |
1c82d19be9ac76a270bed58a475f36520f4ae81c | 99036e0404b56579c2722315e11ee20d6a620097 | /src/main/java/com/jieyou/sso/mapper/UserMapper.java | 46bcf2767aeb0528674fa58cbacb5634aae61a52 | [] | no_license | YaoChungLin/Jieyou_Sso | fc9066c772ab516fc99a9b0b456600ea1a639121 | 4160ce973192a29b23dc79785427dd18b27898cc | refs/heads/master | 2020-03-12T14:08:56.184351 | 2018-04-23T07:55:07 | 2018-04-23T07:55:07 | 130,660,240 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 169 | java | package com.jieyou.sso.mapper;
import com.github.abel533.mapper.Mapper;
import com.jieyou.sso.pojo.User;
public interface UserMapper extends Mapper<User> {
}
| [
"linyaozong1997@126.com"
] | linyaozong1997@126.com |
c36205822bdd9e853802afcf308fda2e9e5aa668 | 9e9bd7bbfe9ac893ae18ed84be7d36a3421aa043 | /src/main/java/com/shop/service/AdminService.java | f3d983715310ebf0a5f1b83a52f17121949ae400 | [] | no_license | minsangchoi/Spring-Teamproject | 13130ba8915737147f60dbf380586e040c10d508 | 95bd4ac98b7634ef0724f9c4e49d47fc2f9f7119 | refs/heads/master | 2023-07-12T05:13:50.257079 | 2021-07-26T04:49:28 | 2021-07-26T04:49:28 | 383,634,550 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 904 | java | package com.shop.service;
import java.util.List;
import com.shop.model.BookVO;
import com.shop.model.CateVO;
import com.shop.model.Criteria;
import com.shop.model.MemberVO;
public interface AdminService {
/* 상품 등록 */
public void bookEnroll(BookVO book);
/* 카테고리 리스트 */
public List<CateVO> cateList();
/* 상품 리스트 */
public List<BookVO> goodsGetList(Criteria cri);
/* 상품 총 개수 */
public int goodsGetTotal(Criteria cri);
/* 상품 조회 페이지 */
public BookVO goodsGetDetail(int bookId);
/* 상품 수정 */
public int goodsModify(BookVO vo);
/* 상품 정보 삭제 */
public int goodsDelete(int bookId);
/* 회원 리스트 */
public List<MemberVO> memberGetList(Criteria cri);
/* 회원 총 개수 */
public int memberGetTotal(Criteria cri);
/* 회원 정보 삭제 */
public int memberDelete(String memberId);
}
| [
"x4513x@naver.com"
] | x4513x@naver.com |
80207a6069f6754e5630198194b6a51f88912a5c | cf9a7f8eddf5f21d7234d021dab185a8bd46a365 | /src/main/java/org/terasology/spawning/OreonSpawnEvent.java | ed1bbd90b5d2e8d7879d1a4a2e05b216d11133ce | [] | no_license | Naman-sopho/MasterOfOreon | 17aa91deaf407881cc49a0fdd6e43feff1eb4f45 | 9589a2d4587f5a7fd0f673890a16ad542113f1a0 | refs/heads/master | 2020-03-14T05:42:35.398155 | 2019-07-13T11:41:41 | 2019-07-13T11:41:41 | 131,469,949 | 1 | 0 | null | 2018-04-29T05:58:22 | 2018-04-29T05:58:21 | null | UTF-8 | Java | false | false | 1,400 | java | /*
* Copyright 2018 MovingBlocks
*
* 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.terasology.spawning;
import org.terasology.entitySystem.event.Event;
import org.terasology.entitySystem.prefab.Prefab;
import org.terasology.math.geom.Vector3f;
import org.terasology.network.ServerEvent;
/**
* Event sent by the {@link org.terasology.spawning.nui.SpawnScreenLayer} after the player selects an Oreon to spawn.
*/
@ServerEvent
public class OreonSpawnEvent implements Event {
private Prefab oreonPrefab;
private Vector3f location;
public OreonSpawnEvent () {
}
public OreonSpawnEvent(Prefab prefab, Vector3f location) {
this.oreonPrefab = prefab;
this.location = location;
}
public Prefab getOreonPrefab() {
return this.oreonPrefab;
}
public Vector3f getSpawnPosition() {
return this.location;
}
}
| [
"namantiwari.nt@gmail.com"
] | namantiwari.nt@gmail.com |
950923e8d5f8da2b704775fc65fb1f177130b634 | e977c424543422f49a25695665eb85bfc0700784 | /benchmark/icse15/429763/buggy-version/db/derby/code/trunk/java/engine/org/apache/derby/impl/sql/compile/DDLStatementNode.java | 55039e83989d08bdbb6061d70536a0877387cf01 | [] | no_license | amir9979/pattern-detector-experiment | 17fcb8934cef379fb96002450d11fac62e002dd3 | db67691e536e1550245e76d7d1c8dced181df496 | refs/heads/master | 2022-02-18T10:24:32.235975 | 2019-09-13T15:42:55 | 2019-09-13T15:42:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,591 | java | /*
Derby - Class org.apache.derby.impl.sql.compile.DDLStatementNode
Copyright 1997, 2004 The Apache Software Foundation or its licensors, as applicable.
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.apache.derby.impl.sql.compile;
import org.apache.derby.iapi.services.compiler.MethodBuilder;
import org.apache.derby.iapi.sql.ResultSet;
import org.apache.derby.iapi.sql.dictionary.DataDictionary;
import org.apache.derby.iapi.sql.dictionary.SchemaDescriptor;
import org.apache.derby.iapi.sql.dictionary.TableDescriptor;
import org.apache.derby.iapi.sql.compile.CompilerContext;
import org.apache.derby.iapi.sql.conn.Authorizer;
import org.apache.derby.iapi.reference.SQLState;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.impl.sql.compile.ActivationClassBuilder;
import org.apache.derby.iapi.services.sanity.SanityManager;
import org.apache.derby.iapi.reference.ClassName;
import org.apache.derby.iapi.services.classfile.VMOpcode;
import org.apache.derby.catalog.UUID;
/**
* A DDLStatementNode represents any type of DDL statement: CREATE TABLE,
* CREATE INDEX, ALTER TABLE, etc.
*
* @author Jeff Lichtman
*/
abstract class DDLStatementNode extends StatementNode
{
/////////////////////////////////////////////////////////////////////////
//
// CONSTANTS
//
/////////////////////////////////////////////////////////////////////////
public static final int UNKNOWN_TYPE = 0;
public static final int ADD_TYPE = 1;
public static final int DROP_TYPE = 2;
public static final int MODIFY_TYPE = 3;
public static final int LOCKING_TYPE = 4;
/////////////////////////////////////////////////////////////////////////
//
// STATE
//
/////////////////////////////////////////////////////////////////////////
private TableName objectName;
private boolean initOk;
/**
sub-classes can set this to be true to allow implicit
creation of the main object's schema at execution time.
*/
boolean implicitCreateSchema;
/////////////////////////////////////////////////////////////////////////
//
// BEHAVIOR
//
/////////////////////////////////////////////////////////////////////////
public void init(Object objectName)
throws StandardException {
initAndCheck(objectName);
}
/**
Initialize the object name we will be performing the DDL
on and check that we are not in the system schema
and that DDL is allowed.
*/
protected void initAndCheck(Object objectName)
throws StandardException {
this.objectName = (TableName) objectName;
initOk = true;
}
/**
* A DDL statement is always atomic
*
* @return true
*/
public boolean isAtomic()
{
return true;
}
/**
* Return the name of the table being dropped.
* This is the unqualified table name.
*
* @return the relative name
*/
public String getRelativeName()
{
return objectName.getTableName() ;
}
/**
* Return the full dot expression name of the
* object being dropped.
*
* @return the full name
*/
public String getFullName()
{
return objectName.getFullTableName() ;
}
public final TableName getObjectName() { return objectName; }
/**
* Convert this object to a String. See comments in QueryTreeNode.java
* for how this should be done for tree printing.
*
* @return This object as a String
*/
public String toString()
{
if (SanityManager.DEBUG)
{
return ((objectName==null)?"":objectName.toString()) + super.toString();
}
else
{
return "";
}
}
int activationKind()
{
return StatementNode.NEED_DDL_ACTIVATION;
}
/**
* Generic generate code for all DDL statements.
*
* @param acb The ActivationClassBuilder for the class being built
* @param mb The execute() method to be built
*
* @exception StandardException Thrown on error
*/
public final void generate(ActivationClassBuilder acb,
MethodBuilder mb)
throws StandardException
{
if (SanityManager.DEBUG) {
if (!initOk)
SanityManager.THROWASSERT(getClass() + " never called initAndCheck()");
}
// The generated java is the expression:
// return ResultSetFactory.getDDLResultSet(this)
//
acb.pushGetResultSetFactoryExpression(mb); // instance for getDDLResultSet
acb.pushThisAsActivation(mb); // first arg
mb.callMethod(VMOpcode.INVOKEINTERFACE, (String) null, "getDDLResultSet", ClassName.ResultSet, 1);
}
/**
* Get a schema descriptor for this DDL object.
* Uses this.objectName. Always returns a schema,
* we lock in the schema name prior to execution.
* Checks if current authorizationID is owner of the schema.
*
* @return Schema Descriptor
*
* @exception StandardException throws on schema name
* that doesn't exist
*/
protected final SchemaDescriptor getSchemaDescriptor() throws StandardException
{
return getSchemaDescriptor(true);
}
/**
* Get a schema descriptor for this DDL object.
* Uses this.objectName. Always returns a schema,
* we lock in the schema name prior to execution.
*
* @param ownerCheck If check for schema owner is needed
*
* @return Schema Descriptor
*
* @exception StandardException throws on schema name
* that doesn't exist
*/
protected final SchemaDescriptor getSchemaDescriptor(boolean ownerCheck)
throws StandardException
{
String schemaName = objectName.getSchemaName();
//boolean needError = !(implicitCreateSchema || (schemaName == null));
boolean needError = !implicitCreateSchema;
SchemaDescriptor sd = getSchemaDescriptor(schemaName, needError);
CompilerContext cc = getCompilerContext();
if (sd == null) {
/* Disable creating schemas starting with SYS */
if (schemaName.startsWith("SYS"))
throw StandardException.newException(
SQLState.LANG_NO_USER_DDL_IN_SYSTEM_SCHEMA,
statementToString(),
schemaName);
sd = new SchemaDescriptor(getDataDictionary(), schemaName,
(String) null, (UUID)null, false);
if (isPrivilegeCollectionRequired())
cc.addRequiredSchemaPriv(schemaName, null, Authorizer.CREATE_SCHEMA_PRIV);
}
if (ownerCheck && isPrivilegeCollectionRequired())
cc.addRequiredSchemaPriv(sd.getSchemaName(), null,
Authorizer.MODIFY_SCHEMA_PRIV);
/*
** Catch the system schema here.
*/
if (sd.isSystemSchema())
{
throw StandardException.newException(SQLState.LANG_NO_USER_DDL_IN_SYSTEM_SCHEMA,
statementToString(), sd);
}
return sd;
}
protected final TableDescriptor getTableDescriptor()
throws StandardException
{
return getTableDescriptor(objectName);
}
protected final TableDescriptor getTableDescriptor(UUID tableId)
throws StandardException {
TableDescriptor td = getDataDictionary().getTableDescriptor(tableId);
td = checkTableDescriptor(td);
return td;
}
/**
* Validate that the table is ok for DDL -- e.g.
* that it exists, it is not a view, and is not
* a system table, and that its schema is ok.
*
* @return the validated table descriptor, never null
*
* @exception StandardException on error
*/
protected final TableDescriptor getTableDescriptor(TableName tableName)
throws StandardException
{
String schemaName = tableName.getSchemaName();
SchemaDescriptor sd = getSchemaDescriptor(schemaName);
TableDescriptor td = getTableDescriptor(tableName.getTableName(), sd);
if (td == null)
{
throw StandardException.newException(SQLState.LANG_OBJECT_DOES_NOT_EXIST,
statementToString(), tableName);
}
/* beetle 4444, td may have changed when we obtain shared lock */
td = checkTableDescriptor(td);
return td;
}
private TableDescriptor checkTableDescriptor(TableDescriptor td)
throws StandardException
{
String sqlState = null;
switch (td.getTableType()) {
case TableDescriptor.VTI_TYPE:
case TableDescriptor.SYSTEM_TABLE_TYPE:
/*
** Not on system tables (though there are no constraints on
** system tables as of the time this is writen
*/
sqlState = SQLState.LANG_INVALID_OPERATION_ON_SYSTEM_TABLE;
break;
case TableDescriptor.BASE_TABLE_TYPE:
/* need to IX lock table if we are a reader in DDL datadictionary
* cache mode, otherwise we may interfere with another DDL thread
* that is in execution phase; beetle 4343, also see $WS/docs/
* language/SolutionsToConcurrencyIssues.txt (point f)
*/
return lockTableForCompilation(td);
case TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE:
return td;
/*
** Make sure it is not a view
*/
case TableDescriptor.VIEW_TYPE:
sqlState = SQLState.LANG_INVALID_OPERATION_ON_VIEW;
break;
}
throw StandardException.newException(sqlState,
statementToString(), td.getQualifiedName());
}
/**
* Bind the object Name. This means filling in the schema name if it
* wasn't specified.
*
* @param dataDictionary Data dictionary to bind against.
*
* @exception StandardException Thrown on error
*/
public void bindName( DataDictionary dataDictionary )
throws StandardException
{
if (objectName != null)
objectName.bind( dataDictionary );
}
}
| [
"durieuxthomas@hotmail.com"
] | durieuxthomas@hotmail.com |
8e9905084a5567712dc04121c22f88e08d3c81dc | 00e4a1c675ea1f90a45906e317e90ccb41f092d3 | /components/camel-salesforce/camel-salesforce-codegen/src/main/java/org/apache/camel/component/salesforce/codegen/GenerateExecution.java | de78d18127353f8ba6eabf90c98506b440d5544a | [
"Apache-2.0"
] | permissive | rogerchina/camel | 7220a8188d440d8c7c280752784f26c10e6a1b53 | 1897eee905ea3b9e8b037448f5941b6d9363e51b | refs/heads/main | 2022-06-14T07:42:18.566352 | 2022-05-02T13:37:24 | 2022-05-02T13:37:24 | 487,860,956 | 1 | 0 | Apache-2.0 | 2022-05-02T13:45:04 | 2022-05-02T13:45:03 | null | UTF-8 | Java | false | false | 28,126 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.camel.component.salesforce.codegen;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.camel.component.salesforce.api.dto.AbstractSObjectBase;
import org.apache.camel.component.salesforce.api.dto.PickListValue;
import org.apache.camel.component.salesforce.api.dto.SObjectDescription;
import org.apache.camel.component.salesforce.api.dto.SObjectField;
import org.apache.camel.component.salesforce.internal.client.RestClient;
import org.apache.camel.support.IntrospectionSupport;
import org.apache.camel.util.StringHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Goal to generate DTOs for Salesforce SObjects
*/
public class GenerateExecution extends AbstractSalesforceExecution {
public class GeneratorUtility {
private Stack<String> stack;
private final Map<String, AtomicInteger> varNames = new HashMap<>();
public String current() {
return stack.peek();
}
public String enumTypeName(final String sObjectName, final String name) {
return sObjectName + "_" + (name.endsWith("__c") ? name.substring(0, name.length() - 3) : name) + "Enum";
}
public List<SObjectField> externalIdsOf(final String name) {
return descriptions.externalIdsOf(name);
}
public String getEnumConstant(
final String objectName, final String fieldName,
final String picklistValue) {
final String key = String.join(".", objectName, fieldName, picklistValue);
if (enumerationOverrideProperties.containsKey(key)) {
return enumerationOverrideProperties.get(key).toString();
}
final StringBuilder result = new StringBuilder();
boolean changed = false;
if (!Character.isJavaIdentifierStart(picklistValue.charAt(0))) {
result.append("_");
changed = true;
}
for (final char c : picklistValue.toCharArray()) {
if (Character.isJavaIdentifierPart(c)) {
result.append(c);
} else {
// replace non Java identifier character with '_'
result.append('_');
changed = true;
}
}
return changed ? result.toString().toUpperCase() : picklistValue.toUpperCase();
}
public String getFieldType(final SObjectDescription description, final SObjectField field) {
// check if this is a picklist
if (isPicklist(field)) {
if (Boolean.TRUE.equals(useStringsForPicklists)) {
if (picklistsEnumToSObject.containsKey(description.getName())
&& picklistsEnumToSObject.get(description.getName()).contains(field.getName())) {
return enumTypeName(description.getName(), field.getName());
}
return String.class.getName();
} else if (picklistsStringToSObject.containsKey(description.getName())
&& picklistsStringToSObject.get(description.getName()).contains(field.getName())) {
return String.class.getName();
}
// use a pick list enum, which will be created after generating
// the SObject class
return enumTypeName(description.getName(), field.getName());
} else if (isMultiSelectPicklist(field)) {
if (Boolean.TRUE.equals(useStringsForPicklists)) {
if (picklistsEnumToSObject.containsKey(description.getName())
&& picklistsEnumToSObject.get(description.getName()).contains(field.getName())) {
return enumTypeName(description.getName(), field.getName()) + "[]";
}
return String.class.getName() + "[]";
} else if (picklistsStringToSObject.containsKey(description.getName())
&& picklistsStringToSObject.get(description.getName()).contains(field.getName())) {
return String.class.getName() + "[]";
}
// use a pick list enum array, enum will be created after
// generating the SObject class
return enumTypeName(description.getName(), field.getName()) + "[]";
} else {
// map field to Java type
final String soapType = field.getSoapType();
final String lookupType = soapType.substring(soapType.indexOf(':') + 1);
final String type = types.get(lookupType);
if (type == null) {
getLog().warn(String.format("Unsupported field type `%s` in field `%s` of object `%s`", soapType,
field.getName(), description.getName()));
getLog().debug("Currently known types:\n " + types.entrySet().stream()
.map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("\n")));
}
return type;
}
}
public String getLookupRelationshipName(final SObjectField field) {
return StringHelper.notEmpty(field.getRelationshipName(), "relationshipName", field.getName());
}
public List<PickListValue> getUniqueValues(final SObjectField field) {
if (field.getPicklistValues().isEmpty()) {
return field.getPicklistValues();
}
final List<PickListValue> result = new ArrayList<>();
final Set<String> literals = new HashSet<>();
for (final PickListValue listValue : field.getPicklistValues()) {
final String value = listValue.getValue();
if (!literals.contains(value)) {
literals.add(value);
result.add(listValue);
}
}
literals.clear();
Collections.sort(result, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));
return result;
}
public boolean hasDescription(final String name) {
return descriptions.hasDescription(name);
}
public boolean hasMultiSelectPicklists(final SObjectDescription desc) {
for (final SObjectField field : desc.getFields()) {
if (isMultiSelectPicklist(field)) {
return true;
}
}
return false;
}
public boolean hasPicklists(final SObjectDescription desc) {
for (final SObjectField field : desc.getFields()) {
if (isPicklist(field)) {
return true;
}
}
return false;
}
public boolean includeList(final List<?> list, final String propertyName) {
return !list.isEmpty() && !BLACKLISTED_PROPERTIES.contains(propertyName);
}
public boolean isBlobField(final SObjectField field) {
final String soapType = field.getSoapType();
return BASE64BINARY.equals(soapType.substring(soapType.indexOf(':') + 1));
}
public boolean isExternalId(final SObjectField field) {
return field.isExternalId();
}
public boolean isLookup(final SObjectField field) {
return "reference".equals(field.getType());
}
public boolean isMultiSelectPicklist(final SObjectField field) {
return MULTIPICKLIST.equals(field.getType());
}
public boolean isPicklist(final SObjectField field) {
return PICKLIST.equals(field.getType());
}
public boolean isPrimitiveOrBoxed(final Object object) {
final Class<?> clazz = object.getClass();
final boolean isWholeNumberWrapper = Byte.class.equals(clazz) || Short.class.equals(clazz)
|| Integer.class.equals(clazz) || Long.class.equals(clazz);
final boolean isFloatingPointWrapper = Double.class.equals(clazz) || Float.class.equals(clazz);
final boolean isWrapper = isWholeNumberWrapper || isFloatingPointWrapper || Boolean.class.equals(clazz)
|| Character.class.equals(clazz);
final boolean isPrimitive = clazz.isPrimitive();
return isPrimitive || isWrapper;
}
public boolean notBaseField(final String name) {
return !BASE_FIELDS.contains(name);
}
public boolean notNull(final Object val) {
return val != null;
}
public void pop() {
stack.pop();
}
public String javaSafeString(final String val) {
return StringEscapeUtils.escapeJava(val);
}
public Set<Map.Entry<String, Object>> propertiesOf(final Object object) {
final Map<String, Object> properties = new TreeMap<>();
IntrospectionSupport.getProperties(object, properties, null, false);
final Function<Map.Entry<String, Object>, String> keyMapper = e -> StringUtils.capitalize(e.getKey());
final Function<Map.Entry<String, Object>, Object> valueMapper = Map.Entry::getValue;
final BinaryOperator<Object> mergeFunction = (u, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", u));
};
final Supplier<Map<String, Object>> mapSupplier = LinkedHashMap::new;
return properties.entrySet().stream().collect(Collectors.toMap(keyMapper, valueMapper, mergeFunction, mapSupplier))
.entrySet();
}
public void push(final String additional) {
stack.push(additional);
}
public void start(final String initial) {
stack = new Stack<>();
stack.push(initial);
varNames.clear();
}
public String variableName(final String given) {
final String base = StringUtils.uncapitalize(given);
AtomicInteger counter = varNames.computeIfAbsent(base, k -> new AtomicInteger());
return base + counter.incrementAndGet();
}
}
public static final Map<String, String> DEFAULT_TYPES = defineLookupMap();
private static final Set<String> BASE_FIELDS = defineBaseFields();
private static final String BASE64BINARY = "base64Binary";
private static final List<String> BLACKLISTED_PROPERTIES = Arrays.asList("PicklistValues", "ChildRelationships");
private static final Pattern FIELD_DEFINITION_PATTERN = Pattern.compile("\\w+\\.{1}\\w+");
private static final String JAVA_EXT = ".java";
private static final String MULTIPICKLIST = "multipicklist";
private static final String PACKAGE_NAME_PATTERN
= "(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*\\.)+\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*";
private static final String PICKLIST = "picklist";
private static final String SOBJECT_PICKLIST_VM = "/sobject-picklist.vm";
private static final String SOBJECT_POJO_OPTIONAL_VM = "/sobject-pojo-optional.vm";
private static final String SOBJECT_POJO_VM = "/sobject-pojo.vm";
private static final String SOBJECT_QUERY_RECORDS_OPTIONAL_VM = "/sobject-query-records-optional.vm";
private static final String SOBJECT_QUERY_RECORDS_VM = "/sobject-query-records.vm";
private static final String UTF_8 = "UTF-8";
// used for velocity logging, to avoid creating velocity.log
private static final Logger LOG = LoggerFactory.getLogger(GenerateExecution.class.getName());
Map<String, String> customTypes;
ObjectDescriptions descriptions;
VelocityEngine engine = createVelocityEngine();
/**
* Include Salesforce SObjects that match pattern.
*/
String includePattern;
/**
* Location of generated DTO files, defaults to target/generated-sources/camel-salesforce.
*/
File outputDirectory;
/**
* Java package name for generated DTOs.
*/
String packageName;
/**
* Suffix for child relationship property name. Necessary if an SObject has a lookup field with the same name as its
* Child Relationship Name. If setting to something other than default, "List" is a sensible value.
*/
String childRelationshipNameSuffix;
/**
* Override picklist enum value generation via a java.util.Properties instance. Property name format:
* `SObject.FieldName.PicklistValue`. Property value is the desired enum value.
*/
Properties enumerationOverrideProperties = new Properties();
/**
* Names of specific picklist/multipicklist fields, which should be converted to Enum (default case) if property
* {@link this#useStringsForPicklists} is set to true. Format: SObjectApiName.FieldApiName (e.g. Account.DataSource)
*/
String[] picklistToEnums;
/**
* Names of specific picklist/multipicklist fields, which should be converted to String if property
* {@link this#useStringsForPicklists} is set to false. Format: SObjectApiName.FieldApiName (e.g.
* Account.DataSource)
*/
String[] picklistToStrings;
Boolean useStringsForPicklists;
/**
* Exclude Salesforce SObjects that match pattern.
*/
private String excludePattern;
/**
* Do NOT generate DTOs for these Salesforce SObjects.
*/
private String[] excludes;
/**
* Names of Salesforce SObject for which DTOs must be generated.
*/
private String[] includes;
private final Map<String, Set<String>> picklistsEnumToSObject = new HashMap<>();
private final Map<String, Set<String>> picklistsStringToSObject = new HashMap<>();
private final Map<String, String> types = new HashMap<>(DEFAULT_TYPES);
private boolean useOptionals;
public void parsePicklistToEnums() {
parsePicklistOverrideArgs(picklistToEnums, picklistsEnumToSObject);
}
public void parsePicklistToStrings() {
parsePicklistOverrideArgs(picklistToStrings, picklistsStringToSObject);
}
public void processDescription(
final File pkgDir, final SObjectDescription description, final GeneratorUtility utility,
final Set<String> sObjectNames)
throws IOException {
useStringsForPicklists = useStringsForPicklists == null ? Boolean.FALSE : useStringsForPicklists;
parsePicklistToEnums();
parsePicklistToStrings();
childRelationshipNameSuffix = childRelationshipNameSuffix != null
? childRelationshipNameSuffix : "";
// generate a source file for SObject
final VelocityContext context = new VelocityContext();
context.put("packageName", packageName);
context.put("utility", utility);
context.put("esc", StringEscapeUtils.class);
context.put("desc", description);
context.put("useStringsForPicklists", useStringsForPicklists);
context.put("childRelationshipNameSuffix", childRelationshipNameSuffix);
final String pojoFileName = description.getName() + JAVA_EXT;
final File pojoFile = new File(pkgDir, pojoFileName);
context.put("sObjectNames", sObjectNames);
context.put("descriptions", descriptions);
try (final Writer writer = new OutputStreamWriter(new FileOutputStream(pojoFile), StandardCharsets.UTF_8)) {
final Template pojoTemplate = engine.getTemplate(SOBJECT_POJO_VM, UTF_8);
pojoTemplate.merge(context, writer);
}
if (useOptionals) {
final String optionalFileName = description.getName() + "Optional" + JAVA_EXT;
final File optionalFile = new File(pkgDir, optionalFileName);
try (final Writer writer = new OutputStreamWriter(new FileOutputStream(optionalFile), StandardCharsets.UTF_8)) {
final Template optionalTemplate = engine.getTemplate(SOBJECT_POJO_OPTIONAL_VM, UTF_8);
optionalTemplate.merge(context, writer);
}
}
// write required Enumerations for any picklists
if (!useStringsForPicklists || picklistToEnums != null && picklistToEnums.length > 0) {
for (final SObjectField field : description.getFields()) {
if (utility.isPicklist(field) || utility.isMultiSelectPicklist(field)) {
final String enumName = utility.enumTypeName(description.getName(),
field.getName());
final String enumFileName = enumName + JAVA_EXT;
final File enumFile = new File(pkgDir, enumFileName);
context.put("sObjectName", description.getName());
context.put("field", field);
context.put("enumName", enumName);
final Template enumTemplate = engine.getTemplate(SOBJECT_PICKLIST_VM, UTF_8);
try (final Writer writer = new OutputStreamWriter(
new FileOutputStream(enumFile), StandardCharsets.UTF_8)) {
enumTemplate.merge(context, writer);
}
}
}
}
// write the QueryRecords class
final String queryRecordsFileName = "QueryRecords" + description.getName() + JAVA_EXT;
final File queryRecordsFile = new File(pkgDir, queryRecordsFileName);
final Template queryTemplate = engine.getTemplate(SOBJECT_QUERY_RECORDS_VM, UTF_8);
try (final Writer writer = new OutputStreamWriter(new FileOutputStream(queryRecordsFile), StandardCharsets.UTF_8)) {
queryTemplate.merge(context, writer);
}
if (useOptionals) {
// write the QueryRecords Optional class
final String queryRecordsOptionalFileName = "QueryRecords" + description.getName() + "Optional" + JAVA_EXT;
final File queryRecordsOptionalFile = new File(pkgDir, queryRecordsOptionalFileName);
final Template queryRecordsOptionalTemplate = engine.getTemplate(SOBJECT_QUERY_RECORDS_OPTIONAL_VM, UTF_8);
try (final Writer writer
= new OutputStreamWriter(new FileOutputStream(queryRecordsOptionalFile), StandardCharsets.UTF_8)) {
queryRecordsOptionalTemplate.merge(context, writer);
}
}
}
@Override
protected void executeWithClient(final RestClient client) throws Exception {
descriptions = new ObjectDescriptions(
client, getResponseTimeout(), includes, includePattern, excludes, excludePattern, getLog());
// make sure we can load both templates
if (!engine.resourceExists(SOBJECT_POJO_VM) || !engine.resourceExists(SOBJECT_QUERY_RECORDS_VM)
|| !engine.resourceExists(SOBJECT_POJO_OPTIONAL_VM)
|| !engine.resourceExists(SOBJECT_QUERY_RECORDS_OPTIONAL_VM)) {
throw new RuntimeException("Velocity templates not found");
}
// create package directory
// validate package name
if (!packageName.matches(PACKAGE_NAME_PATTERN)) {
throw new RuntimeException("Invalid package name " + packageName);
}
if (outputDirectory.getAbsolutePath().contains("$")) {
outputDirectory = new File("generated-sources/camel-salesforce");
}
final File pkgDir = new File(outputDirectory, packageName.trim().replace('.', File.separatorChar));
if (!pkgDir.exists()) {
if (!pkgDir.mkdirs()) {
throw new RuntimeException("Unable to create " + pkgDir);
}
}
getLog().info("Generating Java Classes...");
Set<String> sObjectNames = StreamSupport.stream(descriptions.fetched().spliterator(), false).map(d -> d.getName())
.collect(Collectors.toSet());
// generate POJOs for every object description
final GeneratorUtility utility = new GeneratorUtility();
for (final SObjectDescription description : descriptions.fetched()) {
if (Defaults.IGNORED_OBJECTS.contains(description.getName())) {
continue;
}
try {
processDescription(pkgDir, description, utility, sObjectNames);
} catch (final IOException e) {
throw new RuntimeException("Unable to generate source files for: " + description.getName(), e);
}
}
getLog().info(String.format("Successfully generated %s Java Classes", descriptions.count() * 2));
}
@Override
protected Logger getLog() {
return LOG;
}
@Override
public void setup() {
if (customTypes != null) {
types.putAll(customTypes);
}
}
private VelocityEngine createVelocityEngine() {
// initialize velocity to load resources from class loader and use Log4J
final Properties velocityProperties = new Properties();
velocityProperties.setProperty(RuntimeConstants.RESOURCE_LOADER, "cloader");
velocityProperties.setProperty("cloader.resource.loader.class", ClasspathResourceLoader.class.getName());
velocityProperties.setProperty(RuntimeConstants.RUNTIME_LOG_NAME, LOG.getName());
final VelocityEngine engine = new VelocityEngine(velocityProperties);
return engine;
}
private static Set<String> defineBaseFields() {
final Set<String> baseFields = new HashSet<>();
for (final Field field : AbstractSObjectBase.class.getDeclaredFields()) {
baseFields.add(field.getName());
}
return baseFields;
}
private static Map<String, String> defineLookupMap() {
// create a type map
// using JAXB mapping, for the most part
// mapping for tns:ID SOAPtype
final String[][] typeMap = new String[][] {//
{ "ID", "String" }, //
{ "string", "String" }, //
{ "integer", "java.math.BigInteger" }, //
{ "int", "Integer" }, //
{ "long", "Long" }, //
{ "short", "Short" }, //
{ "decimal", "java.math.BigDecimal" }, //
{ "float", "Float" }, //
{ "double", "Double" }, //
{ "boolean", "Boolean" }, //
{ "byte", "Byte" }, //
// the blob base64Binary type
// is mapped to String URL
// for retrieving
// the blob
{ "base64Binary", "String" }, //
{ "unsignedInt", "Long" }, //
{ "unsignedShort", "Integer" }, //
{ "unsignedByte", "Short" }, //
{ "dateTime", "java.time.ZonedDateTime" }, //
{ "time", "java.time.OffsetTime" }, //
{ "date", "java.time.LocalDate" }, //
{ "g", "java.time.ZonedDateTime" }, //
// Salesforce maps any types
// like string, picklist,
// reference, etc.
// to string
{ "anyType", "String" }, //
{ "address", "org.apache.camel.component.salesforce.api.dto.Address" }, //
{ "location", "org.apache.camel.component.salesforce.api.dto.GeoLocation" }, //
{ "RelationshipReferenceTo", "String" }//
};
final Map<String, String> lookupMap = new HashMap<>();
for (final String[] entry : typeMap) {
lookupMap.put(entry[0], entry[1]);
}
return Collections.unmodifiableMap(lookupMap);
}
private static void parsePicklistOverrideArgs(final String[] picklists, final Map<String, Set<String>> picklistsToSObject) {
if (picklists != null && picklists.length > 0) {
String[] strings;
for (final String picklist : picklists) {
if (!FIELD_DEFINITION_PATTERN.matcher(picklist).matches()) {
throw new IllegalArgumentException(
"Invalid format provided for picklistFieldToEnum value - allowed format SObjectName.FieldName");
}
strings = picklist.split("\\.");
picklistsToSObject.putIfAbsent(strings[0], new HashSet<>());
picklistsToSObject.get(strings[0]).add(strings[1]);
}
}
}
public void setCustomTypes(Map<String, String> customTypes) {
this.customTypes = customTypes;
}
public void setIncludePattern(String includePattern) {
this.includePattern = includePattern;
}
public void setOutputDirectory(File outputDirectory) {
this.outputDirectory = outputDirectory;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public void setChildRelationshipNameSuffix(String childRelationshipNameSuffix) {
this.childRelationshipNameSuffix = childRelationshipNameSuffix;
}
public void setEnumerationOverrideProperties(Properties enumerationOverrideProperties) {
this.enumerationOverrideProperties = enumerationOverrideProperties;
}
public void setPicklistToEnums(String[] picklistToEnums) {
this.picklistToEnums = picklistToEnums;
}
public void setPicklistToStrings(String[] picklistToStrings) {
this.picklistToStrings = picklistToStrings;
}
public void setUseStringsForPicklists(Boolean useStringsForPicklists) {
this.useStringsForPicklists = useStringsForPicklists;
}
public void setExcludePattern(String excludePattern) {
this.excludePattern = excludePattern;
}
public void setExcludes(String[] excludes) {
this.excludes = excludes;
}
public void setIncludes(String[] includes) {
this.includes = includes;
}
public void setUseOptionals(boolean useOptionals) {
this.useOptionals = useOptionals;
}
public void setDescriptions(ObjectDescriptions descriptions) {
this.descriptions = descriptions;
}
}
| [
"noreply@github.com"
] | rogerchina.noreply@github.com |
77fe81c4065f7ccd197aec3c82497c355b3508e8 | 94ab5579518876367c41fd0cc5016a65c447e52b | /src/test/java/com/cdi/model/oa/propertypath/QuickbookPP.java | d248db8cd2d5e3688eb6a370dd95c4fdcaca585a | [
"Apache-2.0"
] | permissive | ViaOA/oa-core | 31688eb10f304944054fa9b7372e95da927d2123 | a30ce92c6eb1d9557cd1145353717043b4cd0e23 | refs/heads/master | 2023-08-17T10:27:38.649812 | 2022-12-26T21:45:22 | 2022-12-26T21:45:22 | 180,035,642 | 0 | 0 | Apache-2.0 | 2022-12-25T18:39:54 | 2019-04-07T23:21:08 | Java | UTF-8 | Java | false | false | 2,801 | java | // Generated by OABuilder
package com.cdi.model.oa.propertypath;
import com.cdi.model.oa.*;
public class QuickbookPP {
public static String id() {
String s = Quickbook.P_Id;
return s;
}
public static String started() {
String s = Quickbook.P_Started;
return s;
}
public static String enabled() {
String s = Quickbook.P_Enabled;
return s;
}
public static String currentStep() {
String s = Quickbook.P_CurrentStep;
return s;
}
public static String tsCurrentStep() {
String s = Quickbook.P_TsCurrentStep;
return s;
}
public static String allowSendOrders() {
String s = Quickbook.P_AllowSendOrders;
return s;
}
public static String allowGetOrders() {
String s = Quickbook.P_AllowGetOrders;
return s;
}
public static String allowUpdateOrders() {
String s = Quickbook.P_AllowUpdateOrders;
return s;
}
public static String allowDisableOrders() {
String s = Quickbook.P_AllowDisableOrders;
return s;
}
public static String allowItemAdjustments() {
String s = Quickbook.P_AllowItemAdjustments;
return s;
}
public static String allowUpdateCustomers() {
String s = Quickbook.P_AllowUpdateCustomers;
return s;
}
public static String allowDisableCustomers() {
String s = Quickbook.P_AllowDisableCustomers;
return s;
}
public static String allowUpdateItems() {
String s = Quickbook.P_AllowUpdateItems;
return s;
}
public static String allowDisableItems() {
String s = Quickbook.P_AllowDisableItems;
return s;
}
public static String allowUpdateCustomersNow() {
String s = Quickbook.P_AllowUpdateCustomersNow;
return s;
}
public static String allowUpdateItemsNow() {
String s = Quickbook.P_AllowUpdateItemsNow;
return s;
}
public static String lastUpdated() {
String s = Quickbook.P_LastUpdated;
return s;
}
public static String lastGetOrders() {
String s = Quickbook.P_LastGetOrders;
return s;
}
public static String qbwcLastCalled() {
String s = Quickbook.P_QbwcLastCalled;
return s;
}
public static String console() {
String s = Quickbook.P_Console;
return s;
}
public static String warningConsole() {
String s = Quickbook.P_WarningConsole;
return s;
}
public static String qbwcConsole() {
String s = Quickbook.P_QbwcConsole;
return s;
}
public static String finerConsole() {
String s = Quickbook.P_FinerConsole;
return s;
}
}
| [
"vince@viaoa.com"
] | vince@viaoa.com |
f9aa8a06fd0641e5f28b65f421d9c67e7bf13b03 | 53fae24a2a1c59570c53ceb0a3cee18d8ce7837f | /app/src/main/java/com/example/android/sample/myplaceapp/location/PlaceRepository.java | 2448c2b60f70187a17b336a2c6a65028e33c8e8b | [] | no_license | gushernobindsme/MyPlaceApp | 9c8d327e50f7cf05e3778c59d3de6b78742b933b | 4745ca0904b8d1aa6a6f39301e66b33b6b059b4a | refs/heads/master | 2021-01-21T17:17:15.415861 | 2017-03-16T00:21:43 | 2017-03-16T00:21:43 | 85,134,345 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,816 | java | package com.example.android.sample.myplaceapp.location;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
/**
* 位置情報を取得するためのリポジトリ。
*/
public class PlaceRepository {
/**
* 1日をms換算した値。
*/
public static final long DAY = 24L * 60L * 60L * 1000L;
/**
* コンストラクタ。
*/
private PlaceRepository() {
// インスタンス化禁止
}
/**
* データを追加する。
*
* @param context
* @param place
* @return
*/
public static Uri insert(Context context,Place place){
ContentValues values = new ContentValues();
values.put(PlaceDBHelper.COLUMN_LATITUDE,place.getLatitude());
values.put(PlaceDBHelper.COLUMN_LONGITUDE,place.getLongitude());
values.put(PlaceDBHelper.COLUMN_TIME,place.getTime());
return context.getContentResolver().insert(PlaceProvider.CONTENT_URI,values);
}
/**
*
* @param context
* @param day
* @return
*/
public static Place getLastestPlaceInDay(Context context,long day){
// URIにlimit=1を追加する
Uri uri = PlaceProvider.CONTENT_URI.buildUpon()
.appendQueryParameter("limite","1")
.build();
// 指定した日の0:00
long dayStart = (day/DAY) * DAY;
// 指定した日の23:59:59
long dayEnd = dayStart + DAY - 1L;
// 指定した日に記録された位置情報を返す
Cursor cursor = context.getContentResolver().query(uri,
null,
PlaceDBHelper.COLUMN_TIME + " BETWEEN ? AND ?",
new String[]{String.valueOf(dayStart),String.valueOf(dayEnd)},
PlaceDBHelper.COLUMN_REGISTER_TIME + " DESC");
Place place = null;
if(cursor != null && cursor.moveToNext()){
place = cursorToPlace(cursor);
cursor.close();
}
return place;
}
/**
* 記録がつけられた日付を全て返す。
*
* @param context
* @return
*/
public static List<String> getAllDateString(Context context){
// distinctをつける
Uri uri = PlaceProvider.CONTENT_URI.buildUpon()
.appendQueryParameter("distinct","true")
.build();
// 「記録された日」をyyyy-mm-ddに変換する
String timeToDate = "strftime('%Y-%m-%d', " + PlaceDBHelper.COLUMN_TIME + "/ 1000, 'unixepoch') AS DATE";
Cursor cursor = context.getContentResolver().query(uri,
new String[]{timeToDate},
null, null,
PlaceDBHelper.COLUMN_REGISTER_TIME + " DESC");
List<String> dateStrings = new ArrayList<String>();
if(cursor != null){
while (cursor.moveToNext()){
dateStrings.add(cursor.getString(cursor.getColumnIndex("DATE")));
}
cursor.close();
}
return dateStrings;
}
/**
* カーソルからデータを取り出して、Placeオブジェクトに変換する。
*
* @param cursor
* @return
*/
public static Place cursorToPlace(Cursor cursor) {
Place place = new Place();
place.setId(cursor.getLong(cursor.getColumnIndex(PlaceDBHelper.COLUMN_ID)));
place.setLatitude(cursor.getDouble(cursor.getColumnIndex(PlaceDBHelper.COLUMN_LATITUDE)));
place.setLongitude(cursor.getDouble(cursor.getColumnIndex(PlaceDBHelper.COLUMN_LONGITUDE)));
place.setTime(cursor.getLong(cursor.getColumnIndex(PlaceDBHelper.COLUMN_TIME)));
return place;
}
}
| [
"eratakumi@gmail.com"
] | eratakumi@gmail.com |
b60cf29f6d1fdf6b82864dc433c918dd6b3b51e1 | b11f43bb183214234148ab16c0138491d090057e | /JavaFX-Table-CRUD-JPA-EclipseLink/JavaFXJPA/src/com/mcbx/jpa/eclipse/entity/Logsborrowedbooks.java | 783eb0396f3f7ac7787e39b83cd11cc20489c6e9 | [] | no_license | GetMaCuBeX/Snapshots | f1fecd089515f79d174eeefbc2236f347ea6aad4 | fd442c5eebbb9e7f7b0a8cf3803e11ef26b5394b | refs/heads/master | 2022-10-09T23:27:08.622881 | 2020-06-12T16:04:13 | 2020-06-12T16:04:13 | 261,885,019 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,691 | java | /*
* 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 com.mcbx.jpa.eclipse.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Administrator
*/
@Entity
@Table(name = "logsborrowedbooks")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Logsborrowedbooks.findAll", query = "SELECT l FROM Logsborrowedbooks l")
, @NamedQuery(name = "Logsborrowedbooks.findByIdlogsborrowedbooks", query = "SELECT l FROM Logsborrowedbooks l WHERE l.idlogsborrowedbooks = :idlogsborrowedbooks")
, @NamedQuery(name = "Logsborrowedbooks.findByBorroweddate", query = "SELECT l FROM Logsborrowedbooks l WHERE l.borroweddate = :borroweddate")})
public class Logsborrowedbooks implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "idlogsborrowedbooks")
private Integer idlogsborrowedbooks;
@Basic(optional = false)
@Column(name = "borroweddate")
@Temporal(TemporalType.TIMESTAMP)
private Date borroweddate;
@JoinColumn(name = "books_idbooks", referencedColumnName = "idbooks")
@ManyToOne(optional = false)
private Books booksIdbooks;
public Logsborrowedbooks() {
}
public Logsborrowedbooks(Integer idlogsborrowedbooks) {
this.idlogsborrowedbooks = idlogsborrowedbooks;
}
public Logsborrowedbooks(Integer idlogsborrowedbooks, Date borroweddate) {
this.idlogsborrowedbooks = idlogsborrowedbooks;
this.borroweddate = borroweddate;
}
public Integer getIdlogsborrowedbooks() {
return idlogsborrowedbooks;
}
public void setIdlogsborrowedbooks(Integer idlogsborrowedbooks) {
this.idlogsborrowedbooks = idlogsborrowedbooks;
}
public Date getBorroweddate() {
return borroweddate;
}
public void setBorroweddate(Date borroweddate) {
this.borroweddate = borroweddate;
}
public Books getBooksIdbooks() {
return booksIdbooks;
}
public void setBooksIdbooks(Books booksIdbooks) {
this.booksIdbooks = booksIdbooks;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idlogsborrowedbooks != null ? idlogsborrowedbooks.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Logsborrowedbooks)) {
return false;
}
Logsborrowedbooks other = (Logsborrowedbooks) object;
if ((this.idlogsborrowedbooks == null && other.idlogsborrowedbooks != null) || (this.idlogsborrowedbooks != null && !this.idlogsborrowedbooks.equals(other.idlogsborrowedbooks))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.mcbx.jpa.eclipse.entity.Logsborrowedbooks[ idlogsborrowedbooks=" + idlogsborrowedbooks + " ]";
}
}
| [
"jb.mcbx@outloook.com"
] | jb.mcbx@outloook.com |
32ae257971a13392dc8dd18ac10c85b7ca436c6c | e61e56c0dc8f6aa7275f17af8178c9db552add97 | /app/src/main/java/com/example/monitory/VerifyActivity.java | f2994bc7fa8a96a26e8111805f04e0dd00f4c2b3 | [] | no_license | NaufalAshaW/Monitory | 6319e7d106b0884fd4f1ff83504302f216a81d41 | 2a89fe916fd23b51fa6f5faf97812ac2b90a1fac | refs/heads/master | 2023-04-17T18:08:01.683516 | 2021-05-03T12:12:59 | 2021-05-03T12:12:59 | 363,918,195 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 642 | java | package com.example.monitory;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
//Tanggal : 03 Mei 2021
//NIM : 10118063
//Nama : Naufal Asha
//Kelas : IF-2
public class VerifyActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.verify_activity);
}
public void toForm(View view) {
Intent intent = new Intent(this, FormActivity.class);
startActivity(intent);
}
}
| [
"naufal.asha@gmail.com"
] | naufal.asha@gmail.com |
8c016e507b9a63336f3a720cbaab80f2510c16e0 | 0d430563d908de7cda867380b6fe85e77be11c3d | /workspace/practise java/UsingIO/WriterClass.java | e7f4147bcf59534126f739eadcab5c9f5327fa0a | [] | no_license | hshar89/MyCodes | e2eec3b9a2649fec04e5b391d0ca3d4d9d5ae6dc | e388f005353c9606873b6cafdfce1e92d13273e7 | refs/heads/master | 2022-12-23T00:36:01.951137 | 2020-04-03T13:39:22 | 2020-04-03T13:39:22 | 252,720,397 | 1 | 0 | null | 2022-12-16T00:35:41 | 2020-04-03T12:04:10 | Java | UTF-8 | Java | false | false | 471 | java | package UsingIO;
import java.io.*;
public class WriterClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
Writer w = new FileWriter("C:\\Users\\harshsharma3\\Documents\\LearningJava\\testout2.txt");
String content = "Why all my content get overwritten";
w.write(content);
w.close();
System.out.println("Done...");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
| [
"harshsharma3@deloitte.com"
] | harshsharma3@deloitte.com |
688d93283b057dbd041e7ee891736b4988226bf5 | 83b67e767a30020840f5055365e19806fb1c80ad | /app/src/main/java/com/social/boldbuddy/Home/Home_F.java | 23e2a4308e760f673cc8b34ade54fdff47f36bd5 | [] | no_license | anantprsd5/Bold-Buddy | d98d098857db09a90b10a38782c542c1d10e803d | af882bc7b39d5bade70451f8e320d5a547fbf04e | refs/heads/master | 2020-12-26T21:31:59.519556 | 2020-02-01T17:34:01 | 2020-02-01T17:34:01 | 237,650,725 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 33,872 | java | package com.social.boldbuddy.Home;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.daasuu.gpuv.composer.GPUMp4Composer;
import com.daasuu.gpuv.egl.filter.GlWatermarkFilter;
import com.social.boldbuddy.Comments.Comment_F;
import com.social.boldbuddy.Main_Menu.MainMenuFragment;
import com.social.boldbuddy.Main_Menu.RelateToFragment_OnBack.RootFragment;
import com.social.boldbuddy.Profile.Profile_F;
import com.social.boldbuddy.R;
import com.social.boldbuddy.SimpleClasses.API_CallBack;
import com.social.boldbuddy.SimpleClasses.Fragment_Callback;
import com.social.boldbuddy.SimpleClasses.Fragment_Data_Send;
import com.social.boldbuddy.SimpleClasses.Functions;
import com.social.boldbuddy.SimpleClasses.Variables;
import com.social.boldbuddy.Taged.Taged_Videos_F;
import com.social.boldbuddy.VideoAction.VideoAction_F;
import com.downloader.Error;
import com.downloader.OnCancelListener;
import com.downloader.OnDownloadListener;
import com.downloader.OnPauseListener;
import com.downloader.OnProgressListener;
import com.downloader.OnStartOrResumeListener;
import com.downloader.PRDownloader;
import com.downloader.Progress;
import com.downloader.request.DownloadRequest;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.volokh.danylo.hashtaghelper.HashTagHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import static com.facebook.FacebookSdk.getApplicationContext;
/**
* A simple {@link Fragment} subclass.
*/
// this is the main view which is show all the video in list
public class Home_F extends RootFragment implements Player.EventListener, Fragment_Data_Send {
View view;
Context context;
RecyclerView recyclerView;
ArrayList<Home_Get_Set> data_list;
int currentPage=-1;
LinearLayoutManager layoutManager;
ProgressBar p_bar;
SwipeRefreshLayout swiperefresh;
public Home_F() {
// Required empty public constructor
}
int swipe_count=0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view= inflater.inflate(R.layout.fragment_home, container, false);
context=getContext();
p_bar=view.findViewById(R.id.p_bar);
recyclerView=view.findViewById(R.id.recylerview);
layoutManager=new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(false);
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
// this is the scroll listener of recycler view which will tell the current item number
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
//here we find the current item number
final int scrollOffset = recyclerView.computeVerticalScrollOffset();
final int height = recyclerView.getHeight();
int page_no=scrollOffset / height;
if(page_no!=currentPage ){
currentPage=page_no;
Release_Privious_Player();
Set_Player(currentPage);
}
}
});
swiperefresh=view.findViewById(R.id.swiperefresh);
swiperefresh.setProgressViewOffset(false, 0, 200);
swiperefresh.setColorSchemeResources(R.color.black);
swiperefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
currentPage=-1;
Call_Api_For_get_Allvideos();
}
});
Call_Api_For_get_Allvideos();
Load_add();
return view;
}
InterstitialAd mInterstitialAd;
public void Load_add() {
// this is test app id you will get the actual id when you add app in your
//add mob account
MobileAds.initialize(context,
getResources().getString(R.string.ad_app_id));
//code for intertial add
mInterstitialAd = new InterstitialAd(context);
//here we will get the add id keep in mind above id is app id and below Id is add Id
mInterstitialAd.setAdUnitId(context.getResources().getString(R.string.my_Interstitial_Add));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
}
boolean is_add_show=false;
Home_Adapter adapter;
public void Set_Adapter(){
adapter=new Home_Adapter(context, data_list, new Home_Adapter.OnItemClickListener() {
@Override
public void onItemClick(int postion, final Home_Get_Set item, View view) {
switch(view.getId()) {
case R.id.user_pic:
onPause();
OpenProfile(item,false);
break;
case R.id.username:
onPause();
OpenProfile(item,false);
break;
case R.id.like_layout:
Like_Video(postion, item);
break;
case R.id.comment_layout:
OpenComment(item);
break;
case R.id.shared_layout:
if (!is_add_show && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
is_add_show = true;
} else{
is_add_show=false;
final VideoAction_F fragment = new VideoAction_F(item.video_url, new Fragment_Callback() {
@Override
public void Responce(Bundle bundle) {
if(bundle.getString("action").equals("save")){
Save_Video(item);
}
}
});
fragment.show(getChildFragmentManager(), "");
}
break;
}
}
});
adapter.setHasStableIds(true);
recyclerView.setAdapter(adapter);
}
// Bottom two function will call the api and get all the videos form api and parse the json data
private void Call_Api_For_get_Allvideos() {
Log.d("respo",Variables.sharedPreferences.getString(Variables.device_token,"Null"));
JSONObject parameters = new JSONObject();
try {
parameters.put("fb_id", Variables.sharedPreferences.getString(Variables.u_id,"0"));
parameters.put("token",Variables.sharedPreferences.getString(Variables.device_token,"Null"));
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("resp-home",parameters.toString());
Log.d("resp-home",Variables.showAllVideos);
RequestQueue rq = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, Variables.showAllVideos, parameters, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
String respo=response.toString();
Log.d("resp-home",respo);
swiperefresh.setRefreshing(false);
Parse_data(respo);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
swiperefresh.setRefreshing(false);
Toast.makeText(context, "Something wrong with Api", Toast.LENGTH_SHORT).show();
Log.d("respo",error.toString());
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(120000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rq.getCache().clear();
rq.add(jsonObjectRequest);
}
public void Parse_data(String responce){
data_list=new ArrayList<>();
try {
JSONObject jsonObject=new JSONObject(responce);
String code=jsonObject.optString("code");
if(code.equals("200")){
JSONArray msgArray=jsonObject.getJSONArray("msg");
for (int i=0;i<msgArray.length();i++) {
JSONObject itemdata = msgArray.optJSONObject(i);
Home_Get_Set item=new Home_Get_Set();
item.fb_id=itemdata.optString("fb_id");
JSONObject user_info=itemdata.optJSONObject("user_info");
item.first_name=user_info.optString("first_name");
item.last_name=user_info.optString("last_name");
item.profile_pic=user_info.optString("profile_pic");
JSONObject sound_data=itemdata.optJSONObject("sound");
item.sound_id=sound_data.optString("id");
item.sound_name=sound_data.optString("sound_name");
item.sound_pic=sound_data.optString("thum");
JSONObject count=itemdata.optJSONObject("count");
item.like_count=count.optString("like_count");
item.video_comment_count=count.optString("video_comment_count");
item.video_id=itemdata.optString("id");
item.liked=itemdata.optString("liked");
item.video_url=Variables.base_url+itemdata.optString("video");
item.video_description=itemdata.optString("description");
item.thum=Variables.base_url+itemdata.optString("thum");
item.created_date=itemdata.optString("created");
data_list.add(item);
}
Set_Adapter();
}else {
Toast.makeText(context, ""+jsonObject.optString("msg"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// this will call when swipe for another video and
// this function will set the player to the current video
public void Set_Player(final int currentPage){
final Home_Get_Set item= data_list.get(currentPage);
DefaultTrackSelector trackSelector = new DefaultTrackSelector();
final SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(context, trackSelector);
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(context,
Util.getUserAgent(context, "TikTok"));
MediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory)
.createMediaSource(Uri.parse(item.video_url));
player.prepare(videoSource);
player.setRepeatMode(Player.REPEAT_MODE_ALL);
player.addListener(this);
View layout=layoutManager.findViewByPosition(currentPage);
final PlayerView playerView=layout.findViewById(R.id.playerview);
playerView.setPlayer(player);
player.setPlayWhenReady(true);
privious_player=player;
final RelativeLayout mainlayout = layout.findViewById(R.id.mainlayout);
playerView.setOnTouchListener(new View.OnTouchListener() {
private GestureDetector gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
super.onFling(e1, e2, velocityX, velocityY);
float deltaX = e1.getX() - e2.getX();
float deltaXAbs = Math.abs(deltaX);
// Only when swipe distance between minimal and maximal distance value then we treat it as effective swipe
if((deltaXAbs > 100) && (deltaXAbs < 1000)) {
if(deltaX > 0)
{
OpenProfile(item,true);
}
}
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
super.onSingleTapUp(e);
if(!player.getPlayWhenReady()){
privious_player.setPlayWhenReady(true);
}else{
privious_player.setPlayWhenReady(false);
}
return true;
}
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
Show_video_option(item);
}
@Override
public boolean onDoubleTap(MotionEvent e) {
if(!player.getPlayWhenReady()){
privious_player.setPlayWhenReady(true);
}
if(Variables.sharedPreferences.getBoolean(Variables.islogin,false)) {
Show_heart_on_DoubleTap(item, mainlayout, e);
Like_Video(currentPage, item);
}else {
Toast.makeText(context, "Please Login into app", Toast.LENGTH_SHORT).show();
}
return super.onDoubleTap(e);
}
});
@Override
public boolean onTouch(View v, MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true;
}
});
TextView desc_txt=layout.findViewById(R.id.desc_txt);
HashTagHelper.Creator.create(context.getResources().getColor(R.color.maincolor), new HashTagHelper.OnHashTagClickListener() {
@Override
public void onHashTagClicked(String hashTag) {
onPause();
OpenHashtag(hashTag);
}
}).handle(desc_txt);
LinearLayout soundimage = (LinearLayout)layout.findViewById(R.id.sound_image_layout);
Animation aniRotate = AnimationUtils.loadAnimation(context,R.anim.d_clockwise_rotation);
soundimage.startAnimation(aniRotate);
if(Variables.sharedPreferences.getBoolean(Variables.islogin,false))
Functions.Call_Api_For_update_view(getActivity(),item.video_id);
swipe_count++;
if(swipe_count>4){
Show_add();
swipe_count=0;
}
}
public void Show_heart_on_DoubleTap(Home_Get_Set item,final RelativeLayout mainlayout,MotionEvent e){
int x = (int) e.getX()-100;
int y = (int) e.getY()-100;
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
final ImageView iv = new ImageView(getApplicationContext());
lp.setMargins(x, y, 0, 0);
iv.setLayoutParams(lp);
if(item.liked.equals("1"))
iv.setImageDrawable(getResources().getDrawable(
R.drawable.ic_like));
else
iv.setImageDrawable(getResources().getDrawable(
R.drawable.ic_like_fill));
mainlayout.addView(iv);
Animation fadeoutani = AnimationUtils.loadAnimation(context,R.anim.fade_out);
fadeoutani.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
mainlayout.removeView(iv);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
iv.startAnimation(fadeoutani);
}
public void Show_add(){
if(mInterstitialAd.isLoaded()){
mInterstitialAd.show();
}
}
@Override
public void onDataSent(String yourData) {
int comment_count =Integer.parseInt(yourData);
Home_Get_Set item=data_list.get(currentPage);
item.video_comment_count=""+comment_count;
data_list.remove(currentPage);
data_list.add(currentPage,item);
adapter.notifyDataSetChanged();
}
// this will call when go to the home tab From other tab.
// this is very importent when for video play and pause when the focus is changes
boolean is_visible_to_user;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
is_visible_to_user=isVisibleToUser;
if(privious_player!=null && isVisibleToUser){
privious_player.setPlayWhenReady(true);
}else if(privious_player!=null && !isVisibleToUser){
privious_player.setPlayWhenReady(false);
}
}
// when we swipe for another video this will relaese the privious player
SimpleExoPlayer privious_player;
public void Release_Privious_Player(){
if(privious_player!=null) {
privious_player.removeListener(this);
privious_player.release();
}
}
// this function will call for like the video and Call an Api for like the video
public void Like_Video(final int position, final Home_Get_Set home_get_set){
String action=home_get_set.liked;
if(action.equals("1")){
action="0";
home_get_set.like_count=""+(Integer.parseInt(home_get_set.like_count) -1);
}else {
action="1";
home_get_set.like_count=""+(Integer.parseInt(home_get_set.like_count) +1);
}
data_list.remove(position);
home_get_set.liked=action;
data_list.add(position,home_get_set);
adapter.notifyDataSetChanged();
Functions.Call_Api_For_like_video(getActivity(), home_get_set.video_id, action,new API_CallBack() {
@Override
public void ArrayData(ArrayList arrayList) {
}
@Override
public void OnSuccess(String responce) {
}
@Override
public void OnFail(String responce) {
}
});
}
// this will open the comment screen
private void OpenComment(Home_Get_Set item) {
int comment_counnt=Integer.parseInt(item.video_comment_count);
Fragment_Data_Send fragment_data_send=this;
Comment_F comment_f = new Comment_F(comment_counnt,fragment_data_send);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_bottom, R.anim.out_to_top, R.anim.in_from_top, R.anim.out_from_bottom);
Bundle args = new Bundle();
args.putString("video_id",item.video_id);
comment_f.setArguments(args);
transaction.addToBackStack(null);
transaction.replace(R.id.MainMenuFragment, comment_f).commit();
}
// this will open the profile of user which have uploaded the currenlty running video
private void OpenProfile(Home_Get_Set item,boolean from_right_to_left) {
if(Variables.sharedPreferences.getString(Variables.u_id,"0").equals(item.fb_id)){
TabLayout.Tab profile= MainMenuFragment.tabLayout.getTabAt(4);
profile.select();
}else {
Profile_F profile_f = new Profile_F(false);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
if(from_right_to_left)
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
else
transaction.setCustomAnimations(R.anim.in_from_bottom, R.anim.out_to_top, R.anim.in_from_top, R.anim.out_from_bottom);
Bundle args = new Bundle();
args.putString("user_id", item.fb_id);
args.putString("user_name",item.first_name+" "+item.last_name);
args.putString("user_pic",item.profile_pic);
profile_f.setArguments(args);
transaction.addToBackStack(null);
transaction.replace(R.id.MainMenuFragment, profile_f).commit();
}
}
// this will open the profile of user which have uploaded the currenlty running video
private void OpenHashtag(String tag) {
Taged_Videos_F taged_videos_f = new Taged_Videos_F();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_bottom, R.anim.out_to_top, R.anim.in_from_top, R.anim.out_from_bottom);
Bundle args = new Bundle();
args.putString("tag", tag);
taged_videos_f.setArguments(args);
transaction.addToBackStack(null);
transaction.replace(R.id.MainMenuFragment, taged_videos_f).commit();
}
private void Show_video_option(final Home_Get_Set home_get_set) {
final CharSequence[] options = { "Save Video","Cancel" };
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context,R.style.AlertDialogCustom);
builder.setTitle(null);
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Save Video"))
{
if(Functions.Checkstoragepermision(getActivity()))
Save_Video(home_get_set);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void Save_Video(final Home_Get_Set item){
Functions.Show_determinent_loader(context,false,false);
PRDownloader.initialize(getActivity().getApplicationContext());
DownloadRequest prDownloader= PRDownloader.download(item.video_url, Environment.getExternalStorageDirectory() +"/Tittic/", item.video_id+"no_watermark"+".mp4")
.build()
.setOnStartOrResumeListener(new OnStartOrResumeListener() {
@Override
public void onStartOrResume() {
}
})
.setOnPauseListener(new OnPauseListener() {
@Override
public void onPause() {
}
})
.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel() {
}
})
.setOnProgressListener(new OnProgressListener() {
@Override
public void onProgress(Progress progress) {
int prog=(int)((progress.currentBytes*100)/progress.totalBytes);
Functions.Show_loading_progress(prog/2);
}
});
prDownloader.start(new OnDownloadListener() {
@Override
public void onDownloadComplete() {
Applywatermark(item);
}
@Override
public void onError(Error error) {
Delete_file_no_watermark(item);
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
Functions.cancel_determinent_loader();
}
});
}
public void Applywatermark(final Home_Get_Set item){
Bitmap myLogo = ((BitmapDrawable)getResources().getDrawable(R.drawable.ic_watermark_image)).getBitmap();
Bitmap bitmap_resize=Bitmap.createScaledBitmap(myLogo, 50, 50, false);
GlWatermarkFilter filter=new GlWatermarkFilter(bitmap_resize, GlWatermarkFilter.Position.LEFT_TOP);
new GPUMp4Composer(Environment.getExternalStorageDirectory() +"/Tittic/"+item.video_id+"no_watermark"+".mp4",
Environment.getExternalStorageDirectory() +"/Tittic/"+item.video_id+".mp4")
.filter(filter)
.listener(new GPUMp4Composer.Listener() {
@Override
public void onProgress(double progress) {
Log.d("resp",""+(int) (progress*100));
Functions.Show_loading_progress((int)((progress*100)/2)+50);
}
@Override
public void onCompleted() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Functions.cancel_determinent_loader();
Delete_file_no_watermark(item);
Scan_file(item);
}
});
}
@Override
public void onCanceled() {
Log.d("resp", "onCanceled");
}
@Override
public void onFailed(Exception exception) {
Log.d("resp",exception.toString());
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
Delete_file_no_watermark(item);
Functions.cancel_determinent_loader();
Toast.makeText(context, "Try Again", Toast.LENGTH_SHORT).show();
}catch (Exception e){
}
}
});
}
})
.start();
}
public void Delete_file_no_watermark(Home_Get_Set item){
File file=new File(Environment.getExternalStorageDirectory() +"/Tittic/"+item.video_id+"no_watermark"+".mp4");
if(file.exists()){
file.delete();
}
}
public void Scan_file(Home_Get_Set item){
MediaScannerConnection.scanFile(getActivity(),
new String[] { Environment.getExternalStorageDirectory() +"/Tittic/"+item.video_id+".mp4" },
null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
public boolean is_fragment_exits(){
FragmentManager fm = getActivity().getSupportFragmentManager();
if(fm.getBackStackEntryCount()==0){
return false;
}else {
return true;
}
}
// this is lifecyle of the Activity which is importent for play,pause video or relaese the player
@Override
public void onResume() {
super.onResume();
if((privious_player!=null && is_visible_to_user) && !is_fragment_exits() ){
privious_player.setPlayWhenReady(true);
}
}
@Override
public void onPause() {
super.onPause();
if(privious_player!=null){
privious_player.setPlayWhenReady(false);
}
}
@Override
public void onStop() {
super.onStop();
if(privious_player!=null){
privious_player.setPlayWhenReady(false);
}
}
@Override
public void onDestroy() {
super.onDestroy();
if(privious_player!=null){
privious_player.release();
}
}
// Bottom all the function and the Call back listener of the Expo player
@Override
public void onTimelineChanged(Timeline timeline, @Nullable Object manifest, int reason) {
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
@Override
public void onLoadingChanged(boolean isLoading) {
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if(playbackState==Player.STATE_BUFFERING){
p_bar.setVisibility(View.VISIBLE);
}
else if(playbackState==Player.STATE_READY){
p_bar.setVisibility(View.GONE);
}
}
@Override
public void onRepeatModeChanged(int repeatMode) {
}
@Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
@Override
public void onPlayerError(ExoPlaybackException error) {
}
@Override
public void onPositionDiscontinuity(int reason) {
}
@Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
@Override
public void onSeekProcessed() {
}
}
| [
"anantprsd5@gmail.com"
] | anantprsd5@gmail.com |
b35565c087790a7ff6dfee0f0734b0dd5d2ddf24 | 8c522aa6ffb3978eda3cdabd8f7a7ab0f7775c17 | /back-end/src/main/java/backend/repository/model/User.java | d6aca8a29c27162a7f4bfc2e4e3b941fd4373253 | [] | no_license | HDT-Tibi/explosiveButter | 92be202d0a76c3b3942043a3fa477b6f478fdac7 | 5ac8c48df5eb0b730b70c04d224f6dd76419edae | refs/heads/master | 2021-06-18T13:24:16.975806 | 2017-05-15T13:54:01 | 2017-05-15T13:54:01 | 84,468,713 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 5,122 | java | package backend.repository.model;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import org.springframework.security.core.userdetails.UserDetails;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* This class represents the User object, witch is a model for a user that is
* all ready register.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
@Table(name = "User", uniqueConstraints = @UniqueConstraint(columnNames = { "username", "email" }))
public class User implements UserDetails {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
public User() {
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id_user")
private Long idUser;
@Column(unique = true)
@NotNull
private String username;
@NotNull
private String password;
@NotNull
private String firstName;
@NotNull
private String lastName;
@Transient
private long expires;
@NotNull
private boolean accountExpired;
@NotNull
private boolean accountLocked;
@NotNull
private boolean credentialsExpired;
@NotNull
private boolean accountEnabled;
@Transient
private String newPassword;
@NotNull
private String email;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.EAGER, orphanRemoval = true)
private Set<UserAuthority> authorities;
/**
* @param username
*/
public User(String username) {
this.username = username;
}
/**
* @param username
* @param expires
*/
public User(String username, Date expires) {
this.username = username;
this.expires = expires.getTime();
}
/**
* @return {@link Long}
*/
public Long getId() {
return idUser;
}
/**
* @param id
*/
public void setId(Long id) {
this.idUser = id;
}
@Override
public String getUsername() {
return username;
}
/**
* @param username
*/
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
@JsonIgnore
public String getPassword() {
return password;
}
/**
* @param password
*/
@JsonProperty
public void setPassword(String password) {
this.password = password;
}
/**
* @return {@link String}
*/
@JsonIgnore
public String getNewPassword() {
return newPassword;
}
/**
* @param newPassword
*/
@JsonProperty
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
@Override
@JsonIgnore
public Set<UserAuthority> getAuthorities() {
return authorities;
}
// Use Roles as external API
/**
* @return {@link Set} of {@link UserRole}
*/
public Set<UserRole> getRoles() {
Set<UserRole> roles = EnumSet.noneOf(UserRole.class);
if (authorities != null) {
for (UserAuthority authority : authorities) {
roles.add(UserRole.valueOf(authority));
}
}
return roles;
}
/**
* @param roles
*/
public void setRoles(Set<UserRole> roles) {
for (UserRole role : roles) {
grantRole(role);
}
}
/**
* @param role
*/
public void grantRole(UserRole role) {
if (authorities == null) {
authorities = new HashSet<>();
}
authorities.add(role.asAuthorityFor(this));
}
/**
* @param role
*/
public void revokeRole(UserRole role) {
if (authorities != null) {
authorities.remove(role.asAuthorityFor(this));
}
}
/**
* @param role
* @return {@link Boolean}
*/
public boolean hasRole(UserRole role) {
return authorities.contains(role.asAuthorityFor(this));
}
@Override
@JsonIgnore
public boolean isAccountNonExpired() {
return !accountExpired;
}
@Override
@JsonIgnore
public boolean isAccountNonLocked() {
return !accountLocked;
}
@Override
@JsonIgnore
public boolean isCredentialsNonExpired() {
return !credentialsExpired;
}
@Override
@JsonIgnore
public boolean isEnabled() {
return !accountEnabled;
}
/**
* @return {@link Long}
*/
public long getExpires() {
return expires;
}
/**
* @param expires
*/
public void setExpires(long expires) {
this.expires = expires;
}
/**
*
* @return {@link String}
*/
public String getEmail() {
return email;
}
/**
*
* @param email
*/
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return getClass().getSimpleName() + ": " + getUsername();
}
}
| [
"hudematibi@gmail.com"
] | hudematibi@gmail.com |
1aff678f5050f4ab003ba045a36b785a33c4fa68 | ae0c63dc2315f30ef1c579ea68f30632355918cb | /src/java/phuochg/utils/ReceiveMail.java | 7d29c392f1ca707418648879566d57f959284dfc | [] | no_license | fanglong-it/SimpleBlog | 8a87129cb8001ba4b2ca91be3f93cbda90d2c259 | 356da2138914fc23667e0f4f6b022476a0d4fab7 | refs/heads/main | 2023-08-21T23:56:47.198917 | 2021-10-04T06:29:02 | 2021-10-04T06:29:02 | 412,779,034 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,967 | java | /*
* 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 phuochg.utils;
import java.util.Properties;
import java.util.Random;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* @author cunpl
*/
public class ReceiveMail {
private static final String alpha = "abcdefghijklmnopqrstuvwxyz"; // a-z
private static final String alphaUpperCase = alpha.toUpperCase(); // A-Z
private static final String digits = "0123456789"; // 0-9
private static final String ALPHA_NUMERIC = alpha + alphaUpperCase + digits;
private static final Random generator = new Random();
/**
* * Random string with a-zA-Z0-9, not included special characters
*/
public String randomAlphaNumeric(int numberOfCharactor) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numberOfCharactor; i++) {
int number = randomNumber(0, ALPHA_NUMERIC.length() - 1);
char ch = ALPHA_NUMERIC.charAt(number);
sb.append(ch);
}
return sb.toString();
}
public static int randomNumber(int min, int max) {
return generator.nextInt((max - min) + 1) + min;
}
public void sendText(String code, String Username) throws AddressException, MessagingException {
Properties mailServerProperties;
Session getMailSession;
MimeMessage mailMessage;
// Step1: setup Mail Server
mailServerProperties = System.getProperties();
mailServerProperties.put("mail.smtp.port", "587");
mailServerProperties.put("mail.smtp.auth", "true");
mailServerProperties.put("mail.smtp.starttls.enable", "true");
// Step2: get Mail Session
getMailSession = Session.getDefaultInstance(mailServerProperties, null);
mailMessage = new MimeMessage(getMailSession);
mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(Username)); //Thay abc bằng địa chỉ người nhận
// Bạn có thể chọn CC, BCC
// generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress("cc@gmail.com")); //Địa chỉ cc gmail
mailMessage.setSubject("Resuoure Sharing Project");
mailMessage.setText("This mail Is send by Resuoure Sharing Project \n YOUR CODE IS :" + code);
// Step3: Send mail
Transport transport = getMailSession.getTransport("smtp");
// Thay your_gmail thành gmail của bạn, thay your_password thành mật khẩu gmail của bạn
transport.connect("smtp.gmail.com", "Cunplong.1@gmail.com", "ngheloibame");
transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
transport.close();
}
}
| [
"Fang.longpc@gmail.com"
] | Fang.longpc@gmail.com |
9747c93c007d33dbdeeaaee4c0e85ae68eabae90 | 5836171883bbfded2b23c075e323638cd44b48d6 | /REOT/app/src/main/java/com/example/nico_/reot/Main2Activity.java | 1eee6fec8abc415e662b6436b35c0bc6b6aa759e | [] | no_license | NykolaiPerezVelez/REOT | dfb4a88f06e7133e1401d004ca56171e8a49194b | ea59c67b30f06d413a499949f14a64b1c0026baa | refs/heads/master | 2020-04-15T12:42:37.424919 | 2016-11-04T13:25:13 | 2016-11-04T13:25:13 | 65,752,241 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 999 | java | package com.example.nico_.reot;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
| [
"nperez_dcao_smn@outlook.com"
] | nperez_dcao_smn@outlook.com |
80e08aab572f6ce825197ffc68d16276fa805e63 | 2803841ca81841726e2b723bac13624f6a127406 | /game-of-life/src/main/java/me/panavtec/katas/gameoflife/Stage.java | aeb620181e7d978a302ee2de50cf789b454e8d9f | [
"Apache-2.0"
] | permissive | PaNaVTEC/Katas | 14221cdf60c57dba0668d23f966a553701d5e513 | 6e4d3faa5ca542bf0a9183547724817d14fc78bf | refs/heads/master | 2021-01-18T21:43:22.683174 | 2017-11-17T20:01:31 | 2017-11-17T20:01:31 | 43,140,254 | 6 | 2 | null | null | null | null | UTF-8 | Java | false | false | 908 | java | package me.panavtec.katas.gameoflife;
public class Stage {
private Board board;
public Stage(Board board) {
this.board = board;
}
public Board nextStage() {
Board nextStageBoard = board.clone();
for (int row = 0; row < board.getRows(); row++) {
for (int col = 0; col < board.getCols(); col++) {
int liveNeighbours = board.getAliveNeighbours(row, col);
int currentCell = board.getCellSate(row, col);
if (currentCell == CellState.ALIVE) {
if (liveNeighbours < 2) {
nextStageBoard.setCellState(row, col, CellState.DEAD);
} else if (liveNeighbours > 3) {
nextStageBoard.setCellState(row, col, CellState.DEAD);
}
} else {
if (liveNeighbours == 3) {
nextStageBoard.setCellState(row, col, CellState.ALIVE);
}
}
}
}
return nextStageBoard;
}
}
| [
"panavtec@gmail.com"
] | panavtec@gmail.com |
c733dd3997db6707c159c2daacb54c319d76e1ed | 41cde24f3b45bfacde607c24638166503b8eb798 | /ArrayCopyOfDemo.java | bb8077370a827512211b9ec8e53f02171bbf5952 | [] | no_license | ruhani-chawlia/Java_Practice | 76ab8f71bd2ac53304dbd1b54d621aa2e3671355 | 5055cebc7522c5c8e5295630f4b6f9050d052048 | refs/heads/master | 2020-12-31T04:56:05.152939 | 2016-09-19T16:21:10 | 2016-09-19T16:21:10 | 56,082,983 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,102 | java | /*
* 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 JavaTutorials;
/**
*
* @author Ruhani
*/
public class ArrayCopyOfDemo {
public static void main(String[] args) {
int[] arrayOfInt = {22, 23, 26, 29, 31, 58} ;
//searching value in the entire array
int searchIndex_47 = java.util.Arrays.binarySearch(arrayOfInt, 47) ;
int searchIndex_29 = java.util.Arrays.binarySearch(arrayOfInt, 29) ;
System.out.println("searchIndex_47: " + searchIndex_47);
System.out.println("searchIndex_29: " + searchIndex_29 + "\n");
//searching a value in a range
int searchIndexRange_47 = java.util.Arrays.binarySearch(arrayOfInt, 1, 4, 47) ;
int searchIndexRange1_23 = java.util.Arrays.binarySearch(arrayOfInt, 1, 1, 23) ;
System.out.println(" searchIndexRange_47: " + searchIndexRange_47);
System.out.println("searchIndexRange1_47: " + searchIndexRange1_23);
}
}
| [
"rchawlia@gmail.com"
] | rchawlia@gmail.com |
584cfa5c0c645bc6a58d1f61a43dfca60a842766 | 20a5e16ca9f0bcbffdbd68e2d4984e718ff67f32 | /Dagger2-Sample/src/main/java/com/chiclaim/dagger/sample/view/AddMenuBalanceFragment.java | 3dea6b8928315f8ad259afebff2b7f0d470f0aeb | [] | no_license | guanpj/LearningProject | c5fa154e4cb9d38eff3f3ccfff696764dd2ad328 | 1823f0d5bd8e26c26a7b78011b648a732dec8d91 | refs/heads/master | 2020-03-11T12:05:12.357796 | 2019-03-13T13:46:58 | 2019-03-13T13:46:58 | 65,570,847 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,009 | java | package com.chiclaim.dagger.sample.view;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.chiclaim.dagger.sample.ComponentManager;
import com.chiclaim.dagger.sample.R;
import com.chiclaim.dagger.sample.bean.MenuBalance;
import com.chiclaim.dagger.sample.presenter.AddMenuBalancePresenter;
import com.chiclaim.dagger.sample.presenter.dagger.AddMenuBalancePresenterModule;
import com.chiclaim.dagger.sample.presenter.dagger.DaggerAddMenuBalanceComponent;
import javax.inject.Inject;
public class AddMenuBalanceFragment extends Fragment implements IAddMenuBalanceView {
private ProgressDialog dialog;
private TextView tvMenuBalanceList;
@Inject
AddMenuBalancePresenter presenter;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DaggerAddMenuBalanceComponent.builder()
.menuBalanceRepoComponent(ComponentManager.getInstance().getMenuBalanceRepoComponent())
.addMenuBalancePresenterModule(new AddMenuBalancePresenterModule("Chiclaim","湘菜", this))
.build()
.inject(this);//完成注入
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.add_menu_balance_layout, container, false);
tvMenuBalanceList = (TextView) view.findViewById(R.id.tv_menu_balance_list);
view.findViewById(R.id.btn_add_menu_balance).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showLoading();
presenter.addMenuBalance();
}
});
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public void addMenuBalanceSuccess(MenuBalance menuBalance) {
hideLoading();
tvMenuBalanceList.append(menuBalance.getMenuId() + "--" + menuBalance.getMenuName() + "\n");
showToast("Added successfully");
}
@Override
public void addMenuBalanceFailure(String errorMsg) {
hideLoading();
showToast(errorMsg);
}
void showLoading() {
if (dialog == null) {
dialog = new ProgressDialog(getActivity());
dialog.setMessage("请稍后...");
}
dialog.show();
}
void hideLoading() {
if (dialog != null) {
dialog.dismiss();
}
}
public void showToast(String message) {
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
}
| [
"guanpj.me@gmail.com"
] | guanpj.me@gmail.com |
db1d9a4409e997e3ced4b6e3eb402b6f9adf5e3a | 09344a93c8094778e6642afa74e1f838b7e9ffe9 | /LEPL1402_Inheritance/src/main/java/Cat.java | 3db4dc86d093b311602beb9a4daa8fb79d118947 | [] | no_license | Elektrohm/INFO-2 | 1bd0efe98c66eb0cb60e9e0cfd4c8e0313803ea5 | fc27abc398da76370578be241abb3114d7afe87f | refs/heads/master | 2023-07-03T02:51:08.633151 | 2021-08-10T19:57:55 | 2021-08-10T19:57:55 | 394,767,199 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 466 | java | public class Cat extends Animal {
// useful for the test function
private final String forTestMethod = "Thinking";
public Cat() {
// TODO : How can you invoke the Animal constructor from here (with name = "Cat") ?
super("Cat");
}
public void act_forTestMethod() {
// TODO : How could you invoke the parent act method from here with action parameter : the String forTestMethod
super.act(forTestMethod);
}
}
| [
"theo.denis2000@gmail.com"
] | theo.denis2000@gmail.com |
18df399d616212616d6bfa7fc17c62f69242905d | cfb401fcbd20fbcfbd0823054c4f65b974af1233 | /ORS_4/src/main/java/in/co/rays/ors/TestModel/CollegeModelTest.java | 2d48ed206d67c470647d199523f03f6cc67d0e36 | [] | no_license | ankitmewade/orsproject | 00ac59705f3d9f09fea20700da9297d895d0c96c | 5d6753c33269fb9a2264871ca7b6a23ed89dfcda | refs/heads/main | 2023-06-26T16:28:44.909977 | 2021-07-21T07:43:26 | 2021-07-21T07:43:26 | 388,031,176 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,969 | java | package in.co.rays.ors.TestModel;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import in.co.rays.ors.bean.CollegeBean;
import in.co.rays.ors.exception.ApplicationException;
import in.co.rays.ors.exception.DuplicateRecordException;
import in.co.rays.ors.model.CollegeModel;
/**
* College Model Test classes
*
* @author SunilOS
* @version 1.0
* Copyright (c) SunilOS
*
*/
public class CollegeModelTest {
/**
* Model object to test
*/
public static CollegeModel model = new CollegeModel();
/**
* Main method to call test methods.
*
* @param args
* @throws DuplicateRecordException
*/
public static void main(String[] args) throws DuplicateRecordException {
// testAdd();
// testDelete();
// testUpdate();
// testFindByName();
// testFindByPK();
// testSearch();
testList();
}
/**
* Tests add a College
*
* @throws DuplicateRecordException
*/
public static void testAdd() throws DuplicateRecordException {
try {
CollegeBean bean = new CollegeBean();
bean.setId(2L);
bean.setName("Jay");
bean.setAddress("Bhalu");
bean.setState("MP");
bean.setCity("Indore");
bean.setPhoneNo("073124244");
bean.setCreatedBy("Admin");
bean.setModifiedBy("Admin");
bean.setCreatedDatetime(new Timestamp(new Date().getTime()));
bean.setModifiedDatetime(new Timestamp(new Date().getTime()));
long pk = model.add(bean);
System.out.println("Test add succ");
CollegeBean addedBean = model.findByPK(pk);
if (addedBean == null) {
System.out.println("Test add fail");
}
} catch (ApplicationException e) {
e.printStackTrace();
}
}
/**
* Tests delete a College
*/
public static void testDelete() {
try {
CollegeBean bean = new CollegeBean();
long pk = 7L;
bean.setId(pk);
model.delete(bean);
System.out.println("Test Delete succ");
CollegeBean deletedBean = model.findByPK(pk);
if (deletedBean != null) {
System.out.println("Test Delete fail");
}
} catch (ApplicationException e) {
e.printStackTrace();
}
}
/**
* Tests update a College
*/
public static void testUpdate() {
try {
CollegeBean bean = model.findByPK(3L);
bean.setName("Vikram University");
bean.setAddress("Ujjain");
model.update(bean);
System.out.println("Test Update succ");
CollegeBean updateBean = model.findByPK(3L);
if (!"Vikram University".equals(updateBean.getName())) {
System.out.println("Test Update fail");
}
} catch (ApplicationException e) {
e.printStackTrace();
} catch (DuplicateRecordException e) {
e.printStackTrace();
}
}
/**
* Tests find a College by Name.
*/
public static void testFindByName() {
try {
CollegeBean bean = model.findByName("Vikram university");
if (bean == null) {
System.out.println("Test Find By Name fail");
}
System.out.println(bean.getId());
System.out.println(bean.getName());
System.out.println(bean.getAddress());
System.out.println(bean.getState());
System.out.println(bean.getCity());
System.out.println(bean.getPhoneNo());
System.out.println(bean.getCreatedBy());
System.out.println(bean.getCreatedDatetime());
System.out.println(bean.getModifiedBy());
System.out.println(bean.getModifiedDatetime());
} catch (ApplicationException e) {
e.printStackTrace();
}
}
/**
* Tests find a College by PK.
*/
public static void testFindByPK() {
try {
CollegeBean bean = new CollegeBean();
long pk = 2L;
bean = model.findByPK(pk);
if (bean == null) {
System.out.println("Test Find By PK fail");
}
System.out.println(bean.getId());
System.out.println(bean.getName());
System.out.println(bean.getAddress());
System.out.println(bean.getState());
System.out.println(bean.getCity());
System.out.println(bean.getPhoneNo());
System.out.println(bean.getCreatedBy());
System.out.println(bean.getCreatedDatetime());
System.out.println(bean.getModifiedBy());
System.out.println(bean.getModifiedDatetime());
} catch (ApplicationException e) {
e.printStackTrace();
}
}
/**
* Tests search a College by Name
*/
public static void testSearch() {
try {
CollegeBean bean = new CollegeBean();
List list = new ArrayList();
// bean.setName("LNCT");
bean.setAddress("ujjain");
list = model.search(bean, 1, 10);
if (list.size() < 0) {
System.out.println("Test Search fail");
}
Iterator it = list.iterator();
while (it.hasNext()) {
bean = (CollegeBean) it.next();
System.out.println(bean.getId());
System.out.println(bean.getName());
System.out.println(bean.getAddress());
System.out.println(bean.getState());
System.out.println(bean.getCity());
System.out.println(bean.getPhoneNo());
System.out.println(bean.getCreatedBy());
System.out.println(bean.getCreatedDatetime());
System.out.println(bean.getModifiedBy());
System.out.println(bean.getModifiedDatetime());
}
} catch (ApplicationException e) {
e.printStackTrace();
}
}
/**
* Tests get List a College.
*/
public static void testList() {
try {
CollegeBean bean = new CollegeBean();
List list = new ArrayList();
list = model.list(1, 10);
if (list.size() < 0) {
System.out.println("Test list fail");
}
Iterator it = list.iterator();
while (it.hasNext()) {
bean = (CollegeBean) it.next();
System.out.println(bean.getId());
System.out.println(bean.getName());
System.out.println(bean.getAddress());
System.out.println(bean.getState());
System.out.println(bean.getCity());
System.out.println(bean.getPhoneNo());
System.out.println(bean.getCreatedBy());
System.out.println(bean.getCreatedDatetime());
System.out.println(bean.getModifiedBy());
System.out.println(bean.getModifiedDatetime());
}
} catch (ApplicationException e) {
e.printStackTrace();
}
}
}
| [
"ankit.mewade3777@gmail.com"
] | ankit.mewade3777@gmail.com |
f9845a3d9b0c51c3e37e7430896ff4e4bdf263fb | 045d58477ba23f9c909e6c68bdf62c7bdbf5e346 | /sdk/src/main/java/org/ovirt/engine/sdk/decorators/HostNumaNodeStatistics.java | ac803f301f437c640ea90339f6fb0463ece88e04 | [
"Apache-2.0"
] | permissive | dennischen/ovirt-engine-sdk-java | 091304a4a4b3008b68822e22c0a0fdafeaebdd6f | e9a42126e5001ec934d851ff0c8efea4bf6a436f | refs/heads/master | 2021-01-14T12:58:20.224170 | 2015-06-23T11:22:10 | 2015-06-23T14:51:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,581 | java | //
// Copyright (c) 2012 Red Hat, 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.
//
// *********************************************************************
// ********************* GENERATED CODE - DO NOT MODIFY ****************
// *********************************************************************
package org.ovirt.engine.sdk.decorators;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import org.apache.http.Header;
import org.apache.http.client.ClientProtocolException;
import org.ovirt.engine.sdk.common.CollectionDecorator;
import org.ovirt.engine.sdk.exceptions.ServerException;
import org.ovirt.engine.sdk.utils.CollectionUtils;
import org.ovirt.engine.sdk.utils.HttpHeaderBuilder;
import org.ovirt.engine.sdk.utils.HttpHeaderUtils;
import org.ovirt.engine.sdk.utils.UrlBuilder;
import org.ovirt.engine.sdk.utils.UrlBuilder;
import org.ovirt.engine.sdk.utils.UrlHelper;
import org.ovirt.engine.sdk.web.HttpProxyBroker;
import org.ovirt.engine.sdk.web.UrlParameterType;
import org.ovirt.engine.sdk.entities.Action;
/**
* <p>HostNumaNodeStatistics providing relation and functional services
* <p>to {@link org.ovirt.engine.sdk.entities.Statistics }.
*/
@SuppressWarnings("unused")
public class HostNumaNodeStatistics extends
CollectionDecorator<org.ovirt.engine.sdk.entities.Statistic,
org.ovirt.engine.sdk.entities.Statistics,
HostNumaNodeStatistic> {
private HostNumaNode parent;
/**
* @param proxy HttpProxyBroker
* @param parent HostNumaNode
*/
public HostNumaNodeStatistics(HttpProxyBroker proxy, HostNumaNode parent) {
super(proxy, "statistics");
this.parent = parent;
}
/**
* Lists HostNumaNodeStatistic objects.
*
* @return
* List of {@link HostNumaNodeStatistic }
*
* @throws ClientProtocolException
* Signals that HTTP/S protocol error has occurred.
* @throws ServerException
* Signals that an oVirt api error has occurred.
* @throws IOException
* Signals that an I/O exception of some sort has occurred.
*/
@Override
public List<HostNumaNodeStatistic> list() throws ClientProtocolException,
ServerException, IOException {
String url = this.parent.getHref() + SLASH + getName();
return list(url, org.ovirt.engine.sdk.entities.Statistics.class, HostNumaNodeStatistic.class);
}
/**
* Fetches HostNumaNodeStatistic object by id.
*
* @return
* {@link HostNumaNodeStatistic }
*
* @throws ClientProtocolException
* Signals that HTTP/S protocol error has occurred.
* @throws ServerException
* Signals that an oVirt api error has occurred.
* @throws IOException
* Signals that an I/O exception of some sort has occurred.
*/
@Override
public HostNumaNodeStatistic get(UUID id) throws ClientProtocolException,
ServerException, IOException {
String url = this.parent.getHref() + SLASH + getName() + SLASH + id.toString();
return getProxy().get(url, org.ovirt.engine.sdk.entities.Statistic.class, HostNumaNodeStatistic.class);
}
/**
* Fetches HostNumaNodeStatistic object by id.
*
* @return
* {@link HostNumaNodeStatistic }
*
* @throws ClientProtocolException
* Signals that HTTP/S protocol error has occurred.
* @throws ServerException
* Signals that an oVirt api error has occurred.
* @throws IOException
* Signals that an I/O exception of some sort has occurred.
*/
@Override
public HostNumaNodeStatistic getById(String id) throws ClientProtocolException,
ServerException, IOException {
String url = this.parent.getHref() + SLASH + getName() + SLASH + id;
return getProxy().get(url, org.ovirt.engine.sdk.entities.Statistic.class, HostNumaNodeStatistic.class);
}
}
| [
"juan.hernandez@redhat.com"
] | juan.hernandez@redhat.com |
b92bed113b0d8700384ef96bccd311558ac82247 | ab9c5e0ff92b9356b1d1365ba68949c5afb67f13 | /src/main/java/com/dome/web/cmsoconfigdetail/dao/CmsOconfigDetailMapper.java | 7358ce64b415c71357e2b218dfcfb7ab011d96e4 | [] | no_license | 1131660791/HycCms | cf31e57ada4f02d1eb7e788f8242d21d104b3f54 | 30924f28eb8d35b7d4628348d2dda2f4c124eb0a | refs/heads/master | 2022-12-21T18:44:13.601654 | 2020-03-20T06:15:14 | 2020-03-20T06:15:14 | 248,682,653 | 0 | 0 | null | 2022-12-16T08:52:15 | 2020-03-20T06:19:13 | Java | UTF-8 | Java | false | false | 605 | java | package com.dome.web.cmsoconfigdetail.dao;
import java.util.Map;
import com.dome.bean.CmsOconfigDetail;
public interface CmsOconfigDetailMapper {
int deleteByPrimaryKey(String id);
int insert(CmsOconfigDetail record);
int insertSelective(CmsOconfigDetail record);
CmsOconfigDetail selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(CmsOconfigDetail record);
int updateByPrimaryKey(CmsOconfigDetail record);
/**
* 删除医生服务 配置关联
* @param param
* @return
*/
int deleteDoctorConfigDetail(Map<String, Object> param);
} | [
"huangzhongwang@xtoneict.com"
] | huangzhongwang@xtoneict.com |
1d62dee34c466554932c9a9a91346e7d9b462df5 | 688164cacd63b0f755477bf52851deead29db5ac | /Java OOP/SOLID Lab/src/p02_OpenClosedPrinciple/p01_FileStream/File.java | 71d6ab4040780214ef546c6fc6337b256603cdf7 | [] | no_license | ste4o26/Softuni-Tasks | e919d51b1d865f654271ecd8ce9f7c87c355cf20 | 078fa1be4164498073d438460ac0046558a319b7 | refs/heads/master | 2022-06-25T19:50:11.044648 | 2021-04-20T19:56:39 | 2021-04-20T19:56:39 | 242,478,114 | 0 | 0 | null | 2022-06-21T04:14:21 | 2020-02-23T07:55:56 | Java | UTF-8 | Java | false | false | 377 | java | package p02_OpenClosedPrinciple.p01_FileStream;
public class File extends StreamableResource {
private String name;
public File(String name, int length, int sent) {
super(length, sent);
this.setName(name);
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
| [
"36564989+ste4o26@users.noreply.github.com"
] | 36564989+ste4o26@users.noreply.github.com |
7e966d964c16530adb9226d158ed9617976475b3 | ebe6b94a7fbf764d6b4305b952df8debd9bdaf2b | /java_101/hello_java/src/main/java/com/leesper/MethodDemo.java | a62fb73ad025ece7a9d136ac14184a53930a2b51 | [
"MIT"
] | permissive | leesper/become-javaee-engineer | f983b82cdd71195836409823d315222b8d311765 | a0bc84c07797171e34d13cdfe07ae1a23eee3057 | refs/heads/main | 2023-04-07T09:46:25.343610 | 2021-04-13T01:54:58 | 2021-04-13T01:54:58 | 308,783,100 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 927 | java | package com.leesper;
public class MethodDemo {
public static void main(String[] args) {
extractInteger();
overloadOperator();
}
private static void extractInteger() {
int num = 1234;
System.out.println("Unit: " + num % 10);
System.out.println("Decade: " + num / 10 % 10);
System.out.println("Hundreds: " + num / 100 % 10);
System.out.println("Kilobit: " + num / 1000 % 10);
}
private static void overloadOperator() {
System.out.println("1 + 2 = " + add(1, 2));
System.out.println("1 + 2 + 3 = " + add(1, 2, 3));
System.out.println("3.14159 + 3.14159 = " + add(3.14159, 3.14159));
}
private static int add(int a, int b) {
return a + b;
}
private static int add(int a, int b, int c) {
return a + b + c;
}
private static double add(double a, double b) {
return a + b;
}
}
| [
"pascal7718@gmail.com"
] | pascal7718@gmail.com |
f8908356d25d99ab42f9774b2fb0d4788eade2d4 | 6162e85259edf10c87ed6f1d0f23455fdc1507c7 | /posts/java - maven/maven - build gz package/source/build-gz/src/main/java/com/ifi/boot/processing/ExampleInvocation.java | 6b5da0ffeff08579dc7da4a184edbeb858b284be | [] | no_license | nmthong9021/lockex1987.github.io | 6c4a20a52d4553155ce2c2e89aba59c900359093 | 2c4db42a6aaef06f75ee8b5cc7218d1fa4f5ec5b | refs/heads/master | 2023-03-31T13:32:51.601590 | 2021-04-08T03:20:54 | 2021-04-08T03:20:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,133 | java | package com.ifi.boot.processing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import com.ifi.boot.common.Constants;
//@Component
//@ConfigurationProperties
public class ExampleInvocation implements CommandLineRunner {
private static Logger logger = LoggerFactory.getLogger(ExampleInvocation.class);
@Value("${app.working.thread}")
private String nbAppThread;
@Override
public void run(String... arg0) throws Exception {
logger.info("Starting working thread");
int numberAppThread = 1;
try {
numberAppThread = Integer.valueOf(nbAppThread);
} catch (NumberFormatException e) {
logger.info("Default number of thread (1) will be taken");
}
for (int i = 0; i < numberAppThread; i++) {
(new Thread(new Consumer(Constants.BILLY_THREAD_NAME + "_" + i))).start();
Thread.currentThread();
Thread.sleep(1000);
}
}
}
| [
"lockex1987@gmail.com"
] | lockex1987@gmail.com |
9f9b7e40b1d3d5e26dc7e151537ce6178518189d | 5b86d78dd7d7930768cfe1ac71e06817256c040d | /src/main/java/com/isteer/b2c/model/ProductData.java | 3591793062830ae95dab3b931ae86a9a8267c953 | [
"MIT"
] | permissive | Kannanradhi/myrafrance | 35457bf83b8b216b9ac3118027c357f8853a5e65 | f7cb5874fb17a93c0976a7514152d6e3d80629fa | refs/heads/master | 2020-04-26T02:56:50.719383 | 2019-03-01T07:52:10 | 2019-03-01T07:52:10 | 173,250,550 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,495 | java | package com.isteer.b2c.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull;
import android.support.v7.util.DiffUtil;
import com.google.gson.annotations.SerializedName;
@Entity(tableName = "b2c_product_master")
public class ProductData {
public static DiffUtil.ItemCallback<ProductData> DIFF_CALLBACK = new DiffUtil.ItemCallback<ProductData>() {
@Override
public boolean areItemsTheSame(@NonNull ProductData oldItem, @NonNull ProductData newItem) {
return oldItem.getMikey() == newItem.getMikey();
}
@Override
public boolean areContentsTheSame(@NonNull ProductData oldItem, @NonNull ProductData newItem) {
return oldItem.equals(newItem);
}
};
@PrimaryKey
@NonNull
@ColumnInfo(name = "mikey")
@SerializedName("mikey")
private long mikey = 0;
@ColumnInfo(name = "part_no")
@SerializedName("part_no")
private String part_no = "";
@ColumnInfo(name = "display_code")
@SerializedName("display_code")
private String display_code = "";
@ColumnInfo(name = "remark")
@SerializedName("remark")
private String remark = "";
@ColumnInfo(name = "color_name")
@SerializedName("color_name")
private String color_name = "";
@ColumnInfo(name = "list_price")
@SerializedName("list_price")
private double list_price = 0.0;
@ColumnInfo(name = "standard_price")
@SerializedName("standard_price")
private double standard_price = 0.0;
@ColumnInfo(name = "mrp_rate")
@SerializedName("mrp_rate")
private double mrp_rate = 0.0;
@ColumnInfo(name = "taxPercent")
@SerializedName("taxPercent")
private double taxPercent = 0.0;
@ColumnInfo(name = "manu_name")
@SerializedName("manu_name")
private String manu_name = "";
@ColumnInfo(name = "category")
@SerializedName("category")
private String category = "";
@Ignore
private String qty = "";
public long getMikey() {
return mikey;
}
public void setMikey(long mikey) {
this.mikey = mikey;
}
public String getPart_no() {
return part_no;
}
public void setPart_no(String part_no) {
this.part_no = part_no;
}
public String getDisplay_code() {
return display_code;
}
public void setDisplay_code(String display_code) {
this.display_code = display_code;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getColor_name() {
return color_name;
}
public void setColor_name(String color_name) {
this.color_name = color_name;
}
public double getList_price() {
return list_price;
}
public void setList_price(double list_price) {
this.list_price = list_price;
}
public double getStandard_price() {
return standard_price;
}
public void setStandard_price(double standard_price) {
this.standard_price = standard_price;
}
public double getMrp_rate() {
return mrp_rate;
}
public void setMrp_rate(double mrp_rate) {
this.mrp_rate = mrp_rate;
}
public double getTaxPercent() {
return taxPercent;
}
public void setTaxPercent(double taxPercent) {
this.taxPercent = taxPercent;
}
public String getManu_name() {
return manu_name;
}
public void setManu_name(String manu_name) {
this.manu_name = manu_name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getQty() {
return qty;
}
public void setQty(String qty) {
this.qty = qty;
}
}
| [
"gogul@nstore.in"
] | gogul@nstore.in |
6db30be71260c92685c514aaa850164a6c244a9c | 80e83279d59839355a4c8a0ca2324264bddf9e4c | /Simple Spring Crud/src/com/goodreads/dao/Book_masterDao.java | 7b1aaf214f10bb49a931d8e5a4ee57db4243ebf9 | [] | no_license | akgajjar/SpringFramework | da5e216e016b80eacd4b985292633fe9261ad4d3 | 63d9350257e11e905809b35223b79db4f3061a3e | refs/heads/master | 2022-12-24T18:39:30.320548 | 2019-12-03T15:33:18 | 2019-12-03T15:33:18 | 218,501,585 | 0 | 0 | null | 2022-12-16T04:26:25 | 2019-10-30T10:29:35 | CSS | UTF-8 | Java | false | false | 681 | java | package com.goodreads.dao;
import java.util.List;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.goodreads.bin.book_master;
public interface Book_masterDao {
public void setTemplate(HibernateTemplate template);
public void setBdao(Book_category_masterDao bdao);
public void saveBook(book_master b);
public void updateBook(book_master b);
public void deleteBook(book_master b);
public book_master getByISBN(String ISBN);
public List<book_master> getBooks();
public List<book_master> getBooksByCat_Id(int Cat_Id);
public void addintocategory(String ISBN,int Cat_Id);
public void Removefromcategory(String ISBN,int Cat_Id);
}
| [
"aniketgajjar966@gmail.com"
] | aniketgajjar966@gmail.com |
5fb4f50affda5cb86a6c02809e720bed28ccf705 | 459960cf5c9a0e5e254f83ae3971347c30434fdb | /src/java/com/fsrin/menumine/core/dessertmine/xwork/ChangeMineAction.java | a73f3e65d2114df0e4920b23f545c4efe0dc3196 | [] | no_license | bradym80/MenuMine_Java | 92374fbc0fd0b76c209a155ce57d6af4a975fd6f | d33ff38d34c133038a97c587631ec4abc30ffbc6 | refs/heads/master | 2021-01-17T22:41:58.089105 | 2014-01-31T03:52:29 | 2014-01-31T03:52:29 | 16,398,936 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,382 | java | /*
* Created on 2005-1-18
*
*/
package com.fsrin.menumine.core.dessertmine.xwork;
import com.fsrin.menumine.context.webwork.AbstractMenuMineSessionContextAwareAction;
import com.fsrin.menumine.core.minefields.MineFields;
/**
* 2006-01-13 Changes superclass.
* 2006-04-05 RSC Added default field selection.
*
* @author Reid
* @author Nick
* @version 1
*/
public class ChangeMineAction extends AbstractMenuMineSessionContextAwareAction {
// private MenuMineSessionContextWrapper menuMineSessionContextWrapper;
private String key;
public String execute() throws Exception {
MineChanger mineChanger = new MineChanger();
MineFields fields = MineFields.factory.getByKey(this.getKey());
mineChanger.changeMine(this.getMenuMineSessionContextWrapper(), fields);
return SUCCESS;
}
// public MenuMineSessionContextWrapper getMenuMineSessionContextWrapper() {
// return menuMineSessionContextWrapper;
// }
//
// public void setMenuMineSessionContextWrapper(
// MenuMineSessionContextWrapper menuMineSessionContextWrapper) {
// this.menuMineSessionContextWrapper = menuMineSessionContextWrapper;
// }
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
} | [
"matthewbrady@Matthews-MacBook-Air.local"
] | matthewbrady@Matthews-MacBook-Air.local |
a10f01763e9add266f3f1005d5422f2abd951f04 | 639e437f45dac8cb81ffcc01f0e16befde13d3ba | /task_2.8/Main.java | 2834dbd2ffa7ae88da9a85b65e73a88ca2cf39f1 | [] | no_license | toloklo/edu_0871 | e67f3b05f60e0fe5dd9fa7f87aff94a010e01285 | 0bd47fdd095684dd5259ec1ac4f4625deb22bbd1 | refs/heads/master | 2022-12-10T00:00:27.979666 | 2020-09-07T04:04:41 | 2020-09-07T04:04:41 | 288,442,865 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 619 | java | /*
Используя цикл for вывести на экран прямоугольный треугольник из восьмёрок со сторонами 10 и 10.
Пример вывода на экран:
8
88
888
8888
88888
888888
8888888
88888888
888888888
8888888888
*/
public class Main {
public static void main(String[] args) {
//напишите тут ваш код
int j;
for (int i=1; i<11; i++){
j=0;
while (j<i) {
System.out.print("8");
j++;
}
System.out.println();
}
}
}
| [
"noreply@github.com"
] | toloklo.noreply@github.com |
e4ae0f3c7f094d513a0aeb980a9f4f73133f9075 | 71eceeb92b8df64cecb361d62a3dc3d46c619115 | /src/butterflynet/content/ContentType.java | 28f1f5a89aee17f01e0de1a0eaea24c405db06b7 | [] | no_license | ronyeh/butterflynet | 0bd1f1151392b1f8df8e5061ccd8bdc5bd6504ae | 99f34f4b19fcc556ce9b349cb478060f234aabda | refs/heads/master | 2021-01-01T05:34:51.716392 | 2007-08-14T01:29:10 | 2007-08-14T01:29:10 | 37,225,019 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,766 | java | package butterflynet.content;
import java.io.File;
/**
* The data types that exist in our system.
*
* <p>
* This software is distributed under the <a href="http://hci.stanford.edu/research/copyright.txt">
* BSD License</a>.
* </p>
*
* @author <a href="http://graphics.stanford.edu/~ronyeh">Ron B Yeh</a> ( ronyeh(AT)cs.stanford.edu )
*/
public enum ContentType {
AUDIO("Audio", new String[] { "MP3", "WAV" }),
DOCUMENT("Document", new String[] { "RTF", "TXT", "DOC", "PDF", "HTML" }),
// note: only JPEG/JPG files contain EXIF information
PHOTO("Photo", new String[] { "JPEG", "JPG", "PNG", "GIF", "BMP", "TIFF" }),
SPREADSHEET("SpreadSheet", new String[] { "XLS", "CSV" }),
VIDEO("Video", new String[] { "AVI", "MOV", "MPG", "FLV", "MP4" });
private String[] extensions;
// case sensitive name
// a database may use this case insensitively
// a file system would probably use this case sensitively (MS-DOS/Windows is probably a special case)
private String name;
// constructor of the enumerated type
ContentType(String myName, String[] acceptedExtensions) {
name = myName;
extensions = acceptedExtensions;
}
/**
* @return
*/
private String[] getExtensions() {
return extensions;
}
/**
* Checks if the file is of this type, by doing a file extension check.
*
* @param file
* @return
*/
public boolean isFileTypeCompatible(final File file) {
final String fileName = file.getName().toLowerCase();
for (final String s : getExtensions()) {
if (fileName.endsWith(s.toLowerCase())) {
return true;
}
}
return false;
}
/**
*
* @see java.lang.Object#toString()
*/
public String toString() {
return name;
}
} | [
"ronyeh@ecbca8fb-2922-0410-aedb-db38ad70d144"
] | ronyeh@ecbca8fb-2922-0410-aedb-db38ad70d144 |
5d9727f221ddac3763d2884cf0910d0de465e250 | 1caf925b34a3efd651725b8ea66620301cd61a08 | /bike-web/src/main/java/com/example/bikeweb/Dto/ChargeDto.java | 6a4d7a6b67692fdb2e2093e6b3e3cc5bc0550a06 | [] | no_license | jingtian777/bikeweb | d2f5f502d55addeae55e12491d49c5e4c4c469f8 | 18059e3921190886df6cb3f5d3c4b7c655253e94 | refs/heads/master | 2020-05-25T18:58:51.897813 | 2019-05-22T01:47:44 | 2019-05-22T01:47:44 | 187,940,426 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 787 | java | package com.example.bikeweb.Dto;
import com.example.bikeweb.entity.Charge;
import lombok.Data;
import java.io.Serializable;
@Data
public class ChargeDto implements Serializable {
ChargeDto(){}
ChargeDto(Charge charge){
id = charge.getId();
number = charge.getNumber();
password = charge.getPassword();
denomination = charge.getDenomination();
validity = charge.getValidity();
userId = charge.getUserId();
}
private Long id;
String number;
String password;
Integer denomination;
// 有效性(0=有效,1=失效)
Integer validity;
Integer userId;
public static ChargeDto convert(Charge charge){
if(charge == null)
return null;
return new ChargeDto(charge);
}
}
| [
"zhangminyuan@1159331679257976"
] | zhangminyuan@1159331679257976 |
879a962c61ca79031c571acd9e7659815c1f122a | 72dbac3a852c648aabb55085e5ac28b0599a6910 | /src/br/com/hepta/teste/dao/FuncionarioDAO.java | e3271f2d755b5ffe302fab76a7960430e2e362b4 | [] | no_license | rafadelanhese/teste | 0c01b6e86b56e3cdd503410d977273edc25d572f | 6c2dfd9201411cf4c6ad6bcaf9456b91309adbcf | refs/heads/main | 2023-04-30T02:16:53.421993 | 2021-05-07T20:46:22 | 2021-05-07T20:46:22 | 360,647,842 | 0 | 0 | null | 2021-04-22T21:51:03 | 2021-04-22T18:40:00 | null | UTF-8 | Java | false | false | 7,704 | java | package br.com.hepta.teste.dao;
import br.com.hepta.teste.conexao.ConnectionFactory;
import br.com.hepta.teste.entity.Funcionario;
import br.com.hepta.teste.entity.Setor;
import br.com.hepta.teste.interfacedao.IFuncionarioDAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class FuncionarioDAO implements IFuncionarioDAO {
private Connection connection;
private final int LINHAS_AFETADAS = 0;
public FuncionarioDAO(){
this.connection = ConnectionFactory.criarConexao();
}
@Override
public void fecharConexao() {
try{
this.connection.close();
}catch(SQLException sqlException){
sqlException.printStackTrace();
}
}
@Override
public List<Funcionario> listarTodos() {
String sql = "SELECT * FROM Funcionario ORDER BY nome";
List<Funcionario> listaFuncionario = new ArrayList<Funcionario>();
SetorDAO setorDAO = new SetorDAO();
try{
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
listaFuncionario.add(new Funcionario(rs.getInt(1),
rs.getString(4),
setorDAO.procurarPorId(rs.getInt(6)),
rs.getDouble(5),
rs.getString(2),
rs.getInt(3)));
}
setorDAO.fecharConexao();
rs.close();
ps.close();
}catch(SQLException e){
if(connection != null){
try{
connection.rollback();
}catch(SQLException rb){
System.out.println("Erro no rollback: " + rb.getMessage());
}
}
}
return listaFuncionario;
}
@Override
public boolean criar(Funcionario funcionario) {
boolean funcionarioCriado = false;
String sql = "INSERT INTO Funcionario (ds_email, nu_idade, nome, nu_salario, fk_setor) VALUES (?,?,?,?,?)";
try{
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, funcionario.getEmail());
ps.setInt(2, funcionario.getIdade());
ps.setString(3, funcionario.getNome());
ps.setDouble(4, funcionario.getSalario());
ps.setInt(5, funcionario.getSetor().getId());
if(ps.executeUpdate() > LINHAS_AFETADAS)
funcionarioCriado = !funcionarioCriado;
ps.close();
}catch(SQLException e){
if(connection != null){
try{
connection.rollback();
}catch(SQLException rb){
System.out.println("Erro no rollback: " + rb.getMessage());
}
}
}
return funcionarioCriado;
}
@Override
public boolean atualizar(Funcionario funcionario) {
boolean funcionarioAtualizado = false;
String sql = "UPDATE Funcionario SET ds_email=?, nu_idade=?, nome=?, nu_salario=?, fk_setor=? WHERE id_funcionario=?";
try{
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, funcionario.getEmail());
ps.setInt(2, funcionario.getIdade());
ps.setString(3, funcionario.getNome());
ps.setDouble(4, funcionario.getSalario());
ps.setInt(5, funcionario.getSetor().getId());
ps.setInt(6, funcionario.getId());
if(ps.executeUpdate() > LINHAS_AFETADAS)
funcionarioAtualizado = !funcionarioAtualizado;
ps.close();
} catch(SQLException e) {
if(connection != null){
try{
connection.rollback();
}catch(SQLException rb){
System.out.println("Erro no rollback: " + rb.getMessage());
}
}
}
return funcionarioAtualizado;
}
@Override
public Funcionario procurarPorId(int id) {
String sql = "SELECT * FROM Funcionario WHERE id_funcionario=?";
Funcionario funcionario = null;
try{
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if(rs != null && rs.next()){
SetorDAO setorDAO = new SetorDAO();
funcionario = new Funcionario(rs.getInt(1),
rs.getString(4),
setorDAO.procurarPorId(rs.getInt(6)),
rs.getDouble(5),
rs.getString(2),
rs.getInt(3));
setorDAO.fecharConexao();
}
ps.close();
rs.close();
}catch(SQLException e){
e.printStackTrace();
if(connection != null){
try{
connection.setAutoCommit(false);
connection.rollback();
}catch(SQLException rb){
System.out.println("Erro no rollback: " + rb.getMessage());
}
}
}
return funcionario;
}
@Override
public Funcionario procurarPorNome(String nome) {
String sql = "SELECT * FROM Funcionario WHERE nome=?";
Funcionario funcionario = null;
try{
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, nome);
ResultSet rs = ps.executeQuery();
if(rs != null && rs.next()){
SetorDAO setorDAO = new SetorDAO();
Setor setor = setorDAO.procurarPorId(rs.getInt(6));
funcionario = new Funcionario(rs.getInt(1),
rs.getString(4),
setorDAO.procurarPorId(rs.getInt(6)),
rs.getDouble(5),
rs.getString(2),
rs.getInt(3));
setorDAO.fecharConexao();
}
ps.close();
rs.close();
}catch(SQLException e){
if(connection != null){
try{
connection.setAutoCommit(false);
connection.rollback();
}catch(SQLException rb){
System.out.println("Erro no rollback: " + rb.getMessage());
}
}
}
return funcionario;
}
@Override
public boolean deletar(int id) {
boolean funcionarioDeletado = false;
String sql = "DELETE FROM Funcionario WHERE id_funcionario=?";
try{
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1, id);
if(ps.executeUpdate() > LINHAS_AFETADAS)
funcionarioDeletado = !funcionarioDeletado;
ps.close();
}catch(SQLException e){
if(connection != null){
try{
connection.rollback();
}catch(SQLException rb){
System.out.println("Erro no rollback: " + rb.getMessage());
}
}
}
return funcionarioDeletado;
}
}
| [
"rdmmail-1@yahoo.com.br"
] | rdmmail-1@yahoo.com.br |
0d71d00586b0575ebee06b3f87f604ce35f3bbac | 034c2ae56b7ee2627fa38d37f40532b269a99360 | /app/src/main/java/com/example/myapplication/fragment/ContentFragment.java | a68fb92ce72ab899c029e064d9d2bc62c7b3eb81 | [] | no_license | guojunfeng0410/yaojinpet | 17837b62ebbe20cbf50b0f08700c10b7df4a9594 | 3c8fb3d010912f5b2a12958e5a2120acb59f4264 | refs/heads/master | 2021-05-07T17:19:59.290978 | 2017-10-30T02:54:18 | 2017-10-30T02:54:22 | 108,662,115 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,838 | java | package com.example.myapplication.fragment;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.myapplication.R;
import yalantis.com.sidemenu.interfaces.ScreenShotable;
/**
* Created by Konstantin on 22.12.2014.
*/
public class ContentFragment extends Fragment implements ScreenShotable {
public static final String CLOSE = "Close";
public static final String BUILDING = "Building";
public static final String BOOK = "Book";
public static final String PAINT = "Paint";
public static final String CASE = "Case";
public static final String SHOP = "Shop";
public static final String PARTY = "Party";
public static final String MOVIE = "Movie";
private View containerView;
protected ImageView mImageView;
protected int res;
private Bitmap bitmap;
public static ContentFragment newInstance(int resId) {
ContentFragment contentFragment = new ContentFragment();
Bundle bundle = new Bundle();
bundle.putInt(Integer.class.getName(), resId);
contentFragment.setArguments(bundle);
return contentFragment;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.containerView = view.findViewById(R.id.container);//container是布局文件
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
res = getArguments().getInt(Integer.class.getName());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mImageView = (ImageView) rootView.findViewById(R.id.image_content);
mImageView.setClickable(true);
mImageView.setFocusable(true);
mImageView.setImageResource(res);
return rootView;
}
@Override
public void takeScreenShot() {
Thread thread = new Thread() {
@Override
public void run() {
Bitmap bitmap = Bitmap.createBitmap(containerView.getWidth(),
containerView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
containerView.draw(canvas);
ContentFragment.this.bitmap = bitmap;
}
};
thread.start();
}
@Override
public Bitmap getBitmap() {
return bitmap;
}
}
| [
"guojunfeng0401@qq.com"
] | guojunfeng0401@qq.com |
172e6fa470a90467147a34448358c7ec9af5c0d8 | c1f5416b9ce74bba01adbad6a1a67af89c158484 | /app/src/main/java/com/pesan/film2ex/Adapter/MovieAdapter.java | 8289c16d5908ae49262fe6058f3ef04494c396fc | [] | no_license | AhmadSyauqif/Submission-2-dicoding | c6392ac446305819be1e27cc4b5168f6478abec7 | 5489c3808b78960d6426507c5488d0dc42db511a | refs/heads/master | 2022-12-14T09:44:52.766274 | 2020-09-17T21:49:36 | 2020-09-17T21:49:36 | 296,449,471 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,523 | java | package com.pesan.film2ex.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.pesan.film2ex.Model.Movie;
import com.pesan.film2ex.R;
import java.util.ArrayList;
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.Holder> implements View.OnClickListener {
private ArrayList<Movie> listData;
private Context context;
private OnItemClickCallback onItemClickCallback;
public void setOnItemClickCallback(OnItemClickCallback onItemClickCallback) {
this.onItemClickCallback = onItemClickCallback;
}
public void setListData(ArrayList<Movie> listData) {
this.listData = listData;
}
public MovieAdapter(Context context) {
this.context = context;
}
@NonNull
@Override
public Holder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(context).inflate(R.layout.item_movie, viewGroup, false);
return new Holder(view);
}
@Override
public void onBindViewHolder(@NonNull final Holder holder, int i) {
holder.titleMovie.setText(listData.get(i).getTitle());
holder.yearMovie.setText(listData.get(i).getYear());
holder.posterMovie.setImageResource(listData.get(i).getPoster());
Glide.with(context).load(listData.get(i).getPoster()).into(holder.posterMovie);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onItemClickCallback.onItemClicked(listData.get(holder.getAdapterPosition()));
}
});
}
@Override
public void onClick(View view) {
}
@Override
public int getItemCount() {
return listData.size();
}
class Holder extends RecyclerView.ViewHolder {
TextView titleMovie, yearMovie;
ImageView posterMovie;
Holder(@NonNull View itemView) {
super(itemView);
titleMovie = itemView.findViewById(R.id.title_movie);
yearMovie = itemView.findViewById(R.id.year_movie);
posterMovie = itemView.findViewById(R.id.poster_movie);
}
}
public interface OnItemClickCallback {
void onItemClicked(Movie data);
}
}
| [
"xskarfuadi39@gmail.com"
] | xskarfuadi39@gmail.com |
8c904388785a4577c0f8f3c67cbe13c802d66a0c | 335086c483f251e237e51f3d9a724c913ba7b89c | /CS150/Lab5/ContactTest.java | c5c9ab7059313098ce48a43e8e1db7cf5019b318 | [] | no_license | xiaoshi22/Schoolwork | 58054c0b1b6e3ffce3a569d9aa6ee1d1a04ca1ed | 90a695d8eaea5c7ad2df0af1100bfa899fadeaee | refs/heads/master | 2020-04-05T06:29:27.171523 | 2018-11-08T23:04:20 | 2018-11-08T23:04:20 | 156,640,052 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,841 | java |
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* The test class ContactTest.
*
* @author (your name)
* @version (a version number or a date)
*/
public class ContactTest
{
/**
* Default constructor for test class ContactTest
*/
public ContactTest()
{
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*/
@Before
public void setUp()
{
}
/**
* Tears down the test fixture.
*
* Called after every test case method.
*/
@After
public void tearDown()
{
}
@Test
public void compareTo1()
{
Contact contact1 = new Contact("Xiaoshi", "Wang", "6109061952", "wangxi@laf");
Contact contact2 = new Contact("Yifan", "Xu", "6109062313", "xuy@laf");
assertEquals(-1, contact1.compareTo(contact2));
}
@Test
public void compareTo3()
{
Contact contact2 = new Contact("Xiaoshi", "Wang", "6109061952", "wangxi@laf");
Contact contact1 = new Contact("Yifan", "Xu", "6109062313", "xuy@laf");
assertEquals(1, contact1.compareTo(contact2));
}
@Test
public void compareTo4()
{
Contact contact2 = new Contact("Xiaoshi", "Wang", "6109061952", "wangxi@laf");
Contact contact1 = new Contact("Yifan", "Wang", "6109062313", "xuy@laf");
assertEquals(1, contact1.compareTo(contact2));
}
@Test
public void compareTo5()
{
Contact contact1 = new Contact("Xiaoshi", "Wang", "6109061952", "wangxi@laf");
Contact contact2 = new Contact("Xiaoshi", "Wang", "6109062313", "xuy@laf");
assertEquals(0, contact1.compareTo(contact2));
}
}
| [
"xiaoshiwang22@gmail.com"
] | xiaoshiwang22@gmail.com |
50f5c85afcf0e1a6b73234d20f01dedc1919319f | 07e50ecac0b5a9491aa97c0a838246e1743638c6 | /app/src/main/java/com/mem/arkdelivery/ui/dashboard/DashboardViewModel.java | 470236e407c53f437cf0ef838936556d39c7d0db | [] | no_license | MrPonerYea-mem/ArkDelivery | de4e6fc5df133f0353a4ac4af6149b15226a751e | 4da84c69c4b55777b66b4ebf3859523615aa39eb | refs/heads/master | 2022-04-19T11:04:01.084469 | 2020-04-19T15:17:41 | 2020-04-19T15:17:41 | 256,281,626 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 462 | java | package com.mem.arkdelivery.ui.dashboard;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class DashboardViewModel extends ViewModel {
private MutableLiveData<String> mText;
public DashboardViewModel() {
mText = new MutableLiveData<>();
mText.setValue("This is dashboard fragment");
}
public LiveData<String> getText() {
return mText;
}
} | [
"63256783+MrPonerYea-mem@users.noreply.github.com"
] | 63256783+MrPonerYea-mem@users.noreply.github.com |
528d33b8963a9e52952a56a77cf0a53028cc3063 | cff1ab8c7ef12bba3daf7c2a6d0eed3f77689bea | /Saida/src/Saida/Cachorro.java | d7715641eaa21493db8882f3cd57e056809125e1 | [] | no_license | RildoEstacioS/Monitoria | 02f7c79201c3d65134720e5f06b43e36436c3e1e | e70d6b4748bdb2a8bd274bde8644c24b65ab6a9e | refs/heads/master | 2020-11-25T14:35:43.293218 | 2019-11-06T19:17:03 | 2019-11-06T19:17:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 135 | java | package Saida;
public class Cachorro implements Animal{
@Override
public String falar() {
return "au au";
}
}
| [
"maelsantos777@gmail.com"
] | maelsantos777@gmail.com |
5c48425b3a46f50abca46f671b163a94f2d298fb | b7b1ec9efbd7c92fb55f66291f1ee42448946eb2 | /Interface.java | 14bcea9930945f6b13b15ea970c1f503e3bf0b85 | [] | no_license | JVicente7037/patronesdeDisa-o | efe6c856af0ef3f0dd9c6f8d30e96bf966b716ac | 89b3d77a10e6e7c55d28aee01c441d1c6c907757 | refs/heads/master | 2020-05-09T10:45:14.763466 | 2019-04-12T18:49:42 | 2019-04-12T18:49:42 | 181,056,056 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 365 | java | /*
* 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 proxy;
/**
*
* @author USUARIO
*/
public interface Interface {
public void Realizooperaciones(String usuario, String contrasena, String tip);
}
| [
"noreply@github.com"
] | JVicente7037.noreply@github.com |
8f2e210e6eb3d3a11c12abc7e347fc120584cff4 | b64b088b23e6674238cfda4fa8d01b334b8e0273 | /src/main/java/at/mlakar/geoconverter/Application.java | d85718e14ccbca6fdef96204c51835cb42b954ac | [] | no_license | Scoutman/GeoConverter | 1adeac625592e941473f7c06a69931c415cb6689 | 6e49b948c27607f8266621a11c70c3a7d455b531 | refs/heads/master | 2023-02-06T16:53:23.340791 | 2018-08-04T16:23:31 | 2018-08-04T16:23:31 | 128,680,185 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 303 | java | package at.mlakar.geoconverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application
{
public static void main(String[] args)
{
SpringApplication.run(Application.class, args);
}
}
| [
"mail@scoutman.at"
] | mail@scoutman.at |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.