text
stringlengths 10
2.72M
|
|---|
/*
* @(#) BaseFtpInfo.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ims.ftpinfo.base;
import com.esum.appframework.dmo.BaseDMO;
/**
* This is an object that contains data related to the FTP_INFO table. Do not
* modify this class because it will be overwritten if the configuration file
* related to this class is modified.
*
* @hibernate.class table="FTP_INFO"
*/
public abstract class BaseFtpInfo extends BaseDMO {
public static String REF = "FtpInfo";
public static String PROP_INBOUND_GATHER_DIR = "InboundGatherDir";
public static String PROP_OUTBOUND_CONNECTION_MODE = "OutboundConnectionMode";
public static String PROP_OUTBOUND_DIR = "OutboundDir";
public static String PROP_INBOUND_USER_ID = "InboundUserId";
public static String PROP_INBOUND_GATHER_HOST_PORT = "InboundGatherHostPort";
public static String PROP_MOD_DATE = "ModDate";
public static String PROP_INBOUND_GATHER_INTERVAL = "InboundGatherInterval";
public static String PROP_OUTBOUND_USER_ID = "OutboundUserId";
public static String PROP_INBOUND_CONNECTION_MODE = "InboundConnectionMode";
public static String PROP_INBOUND_GATHER_FILE_SUFFIX = "InboundGatherFileSuffix";
public static String PROP_OUTBOUND_USER_PWD = "OutboundUserPwd";
public static String PROP_OUTBOUND_HOST_PORT = "OutboundHostPort";
public static String PROP_INBOUND_GATHER_USE = "InboundGatherUse";
public static String PROP_REG_DATE = "RegDate";
public static String PROP_INBOUND_TRANSFER_TYPE = "InboundTransferType";
public static String PROP_INBOUND_USER_PWD = "InboundUserPwd";
public static String PROP_PARSING_RULE = "ParsingRule";
public static String PROP_OUTBOUND_TRANSFER_TYPE = "OutboundTransferType";
public static String PROP_OUTBOUND_HOST_IP = "OutboundHostIp";
public static String PROP_INTERFACE_ID = "InterfaceId";
public static String PROP_INBOUND_GATHER_HOST_IP = "InboundGatherHostIp";
public static String PROP_INBOUND_GATHER_RENAME = "InboundGatherRename";
public static String PROP_OUTBOUND_RENAME = "OutboundRename";
public static String PROP_INBOUND_GATHER_LOCALE = "InboundGatherLocale";
// constructors
public BaseFtpInfo() {
initialize();
}
/**
* Constructor for primary key
*/
public BaseFtpInfo(String interfaceId) {
this.setInterfaceId(interfaceId);
initialize();
}
/**
* Constructor for required fields
*/
public BaseFtpInfo(String interfaceId, String regDate, String modDate) {
this.setInterfaceId(interfaceId);
this.setRegDate(regDate);
this.setModDate(modDate);
initialize();
}
protected void initialize() {
useInbound = "";
inboundGatherHostIp = "";
inboundGatherHostPort = "";
// inboundUserId = "";
// inboundUserPwd = "";
inboundTransferType = "";
inboundConnectionMode = "";
inboundGatherDir = "";
inboundGatherFileSuffix = "";
inboundGatherInterval = "";
inboundGatherCountOnce = "10";
inboundGatherRename = "";
inboundGatherLocale = "";
inboundGatherUse = "";
inboundNodeId = "";
useOutbound = "";
outboundHostIp = "";
outboundHostPort = "";
// outboundUserId = "";
// outboundUserPwd = "";
outboundDir = "";
outboundTransferType = "";
outboundConnectionMode = "";
outboundRename = "";
parsingRule = "";
regDate = "";
modDate = "";
}
// primary key
protected String interfaceId;
// fields
protected String useInbound;
protected String inboundGatherHostIp;
protected String inboundGatherHostPort;
// protected String inboundUserId;
// protected String inboundUserPwd;
protected String inboundFtpAuthInfoId;
protected String inboundTransferType;
protected String inboundConnectionMode;
protected String inboundGatherDir;
protected String inboundGatherFileSuffix;
protected String inboundGatherStartType;
protected String inboundGatherInterval;
protected String inboundGatherCountOnce;
protected String inboundGatherCronPattern;
protected String inboundGatherRename;
protected String inboundGatherLocale;
protected String inboundGatherPkiAlias;
protected String inboundGatherUseSsl;
protected String inboundGatherUse;
protected String inboundNodeId;
protected String inboundFileEncoding;
protected String useOutbound;
protected String outboundHostIp;
protected String outboundHostPort;
// protected String outboundUserId;
// protected String outboundUserPwd;
protected String outboundFtpAuthInfoId;
protected String outboundDir;
protected String outboundTransferType;
protected String outboundConnectionMode;
protected String outboundRename;
protected String outboundPkiAlias;
protected String outboundUseSsl;
protected String outboundFileEncoding;
protected String parsingRule;
protected String regDate;
protected String modDate;
/**
* Return the unique identifier of this class
*
* @hibernate.id column="INTERFACE_ID"
*/
public String getInterfaceId() {
return interfaceId;
}
/**
* Set the unique identifier of this class
*
* @param interfaceId
* the new ID
*/
public void setInterfaceId(String interfaceId) {
this.interfaceId = interfaceId;
}
public String getUseInbound() {
return useInbound;
}
public void setUseInbound(String useInbound) {
this.useInbound = useInbound;
}
/**
* Return the value associated with the column: INBOUND_GATHER_HOST_IP
*/
public String getInboundGatherHostIp() {
return inboundGatherHostIp;
}
/**
* Set the value related to the column: INBOUND_GATHER_HOST_IP
*
* @param inboundGatherHostIp
* the INBOUND_GATHER_HOST_IP value
*/
public void setInboundGatherHostIp(String inboundGatherHostIp) {
this.inboundGatherHostIp = inboundGatherHostIp;
}
/**
* Return the value associated with the column: INBOUND_GATHER_HOST_PORT
*/
public String getInboundGatherHostPort() {
return inboundGatherHostPort;
}
/**
* Set the value related to the column: INBOUND_GATHER_HOST_PORT
*
* @param inboundGatherHostPort
* the INBOUND_GATHER_HOST_PORT value
*/
public void setInboundGatherHostPort(String inboundGatherHostPort) {
this.inboundGatherHostPort = inboundGatherHostPort;
}
// /**
// * Return the value associated with the column: INBOUND_USER_ID
// */
// public String getInboundUserId() {
// return inboundUserId;
// }
//
// /**
// * Set the value related to the column: INBOUND_USER_ID
// *
// * @param inboundUserId
// * the INBOUND_USER_ID value
// */
// public void setInboundUserId(String inboundUserId) {
// this.inboundUserId = inboundUserId;
// }
//
// /**
// * Return the value associated with the column: INBOUND_USER_PWD
// */
// public String getInboundUserPwd() {
// return inboundUserPwd;
// }
//
// /**
// * Set the value related to the column: INBOUND_USER_PWD
// *
// * @param inboundUserPwd
// * the INBOUND_USER_PWD value
// */
// public void setInboundUserPwd(String inboundUserPwd) {
// this.inboundUserPwd = inboundUserPwd;
// }
/**
* Return the value associated with the column: INBOUND_TRANSFER_TYPE
*/
public String getInboundTransferType() {
return inboundTransferType;
}
/**
* @return the inboundFtpAuthInfoId
*/
public String getInboundFtpAuthInfoId() {
return inboundFtpAuthInfoId;
}
/**
* @param inboundFtpAuthInfoId
* the inboundFtpAuthInfoId to set
*/
public void setInboundFtpAuthInfoId(String inboundFtpAuthInfoId) {
this.inboundFtpAuthInfoId = inboundFtpAuthInfoId;
}
/**
* @return the inboundGatherStartType
*/
public String getInboundGatherStartType() {
return inboundGatherStartType;
}
/**
* @param inboundGatherStartType
* the inboundGatherStartType to set
*/
public void setInboundGatherStartType(String inboundGatherStartType) {
this.inboundGatherStartType = inboundGatherStartType;
}
/**
* @return the inboundGatherCronPattern
*/
public String getInboundGatherCronPattern() {
return inboundGatherCronPattern;
}
/**
* @param inboundGatherCronPattern
* the inboundGatherCronPattern to set
*/
public void setInboundGatherCronPattern(String inboundGatherCronPattern) {
this.inboundGatherCronPattern = inboundGatherCronPattern;
}
/**
* @return the inboundGatherPkiAlias
*/
public String getInboundGatherPkiAlias() {
return inboundGatherPkiAlias;
}
/**
* @param inboundGatherPkiAlias
* the inboundGatherPkiAlias to set
*/
public void setInboundGatherPkiAlias(String inboundGatherPkiAlias) {
this.inboundGatherPkiAlias = inboundGatherPkiAlias;
}
/**
* @return the inboundGatherUseSsl
*/
public String getInboundGatherUseSsl() {
return inboundGatherUseSsl;
}
/**
* @param inboundGatherUseSsl
* the inboundGatherUseSsl to set
*/
public void setInboundGatherUseSsl(String inboundGatherUseSsl) {
this.inboundGatherUseSsl = inboundGatherUseSsl;
}
public String getUseOutbound() {
return useOutbound;
}
public void setUseOutbound(String useOutbound) {
this.useOutbound = useOutbound;
}
/**
* @return the outboundFtpAuthInfoId
*/
public String getOutboundFtpAuthInfoId() {
return outboundFtpAuthInfoId;
}
/**
* @param outboundFtpAuthInfoId
* the outboundFtpAuthInfoId to set
*/
public void setOutboundFtpAuthInfoId(String outboundFtpAuthInfoId) {
this.outboundFtpAuthInfoId = outboundFtpAuthInfoId;
}
/**
* @return the outboundPkiAlias
*/
public String getOutboundPkiAlias() {
return outboundPkiAlias;
}
/**
* @param outboundPkiAlias
* the outboundPkiAlias to set
*/
public void setOutboundPkiAlias(String outboundPkiAlias) {
this.outboundPkiAlias = outboundPkiAlias;
}
/**
* @return the outboundUseSsl
*/
public String getOutboundUseSsl() {
return outboundUseSsl;
}
/**
* @param outboundUseSsl
* the outboundUseSsl to set
*/
public void setOutboundUseSsl(String outboundUseSsl) {
this.outboundUseSsl = outboundUseSsl;
}
/**
* Set the value related to the column: INBOUND_TRANSFER_TYPE
*
* @param inboundTransferType
* the INBOUND_TRANSFER_TYPE value
*/
public void setInboundTransferType(String inboundTransferType) {
this.inboundTransferType = inboundTransferType;
}
/**
* Return the value associated with the column: INBOUND_CONNECTION_MODE
*/
public String getInboundConnectionMode() {
return inboundConnectionMode;
}
/**
* Set the value related to the column: INBOUND_CONNECTION_MODE
*
* @param inboundConnectionMode
* the INBOUND_CONNECTION_MODE value
*/
public void setInboundConnectionMode(String inboundConnectionMode) {
this.inboundConnectionMode = inboundConnectionMode;
}
/**
* Return the value associated with the column: INBOUND_GATHER_DIR
*/
public String getInboundGatherDir() {
return inboundGatherDir;
}
/**
* Set the value related to the column: INBOUND_GATHER_DIR
*
* @param inboundGatherDir
* the INBOUND_GATHER_DIR value
*/
public void setInboundGatherDir(String inboundGatherDir) {
this.inboundGatherDir = inboundGatherDir;
}
/**
* Return the value associated with the column: INBOUND_GATHER_FILE_SUFFIX
*/
public String getInboundGatherFileSuffix() {
return inboundGatherFileSuffix;
}
/**
* Set the value related to the column: INBOUND_GATHER_FILE_SUFFIX
*
* @param inboundGatherFileSuffix
* the INBOUND_GATHER_FILE_SUFFIX value
*/
public void setInboundGatherFileSuffix(String inboundGatherFileSuffix) {
this.inboundGatherFileSuffix = inboundGatherFileSuffix;
}
/**
* Return the value associated with the column: INBOUND_GATHER_INTERVAL
*/
public String getInboundGatherInterval() {
return inboundGatherInterval;
}
/**
* Set the value related to the column: INBOUND_GATHER_INTERVAL
*
* @param inboundGatherInterval
* the INBOUND_GATHER_INTERVAL value
*/
public void setInboundGatherInterval(String inboundGatherInterval) {
this.inboundGatherInterval = inboundGatherInterval;
}
/**
* Return the value associated with the column: INBOUND_GATHER_COUNT_ONCE
*/
public String getInboundGatherCountOnce() {
return inboundGatherCountOnce;
}
/**
* Set the value related to the column: INBOUND_GATHER_COUNT_ONCE
*
* @param inboundGatherCountOnce
* the INBOUND_GATHER_COUNT_ONCE value
*/
public void setInboundGatherCountOnce(String inboundGatherCountOnce) {
this.inboundGatherCountOnce = inboundGatherCountOnce;
}
/**
* Return the value associated with the column: INBOUND_GATHER_USE
*/
public String getInboundGatherUse() {
return inboundGatherUse;
}
/**
* Set the value related to the column: INBOUND_GATHER_USE
*
* @param inboundGatherUse
* the INBOUND_GATHER_USE value
*/
public void setInboundGatherUse(String inboundGatherUse) {
this.inboundGatherUse = inboundGatherUse;
}
public String getInboundNodeId() {
return inboundNodeId;
}
public void setInboundNodeId(String inboundNodeId) {
this.inboundNodeId = inboundNodeId;
}
/**
* Return the value associated with the column: OUTBOUND_HOST_IP
*/
public String getOutboundHostIp() {
return outboundHostIp;
}
/**
* Set the value related to the column: OUTBOUND_HOST_IP
*
* @param outboundHostIp
* the OUTBOUND_HOST_IP value
*/
public void setOutboundHostIp(String outboundHostIp) {
this.outboundHostIp = outboundHostIp;
}
/**
* Return the value associated with the column: OUTBOUND_HOST_PORT
*/
public String getOutboundHostPort() {
return outboundHostPort;
}
/**
* Set the value related to the column: OUTBOUND_HOST_PORT
*
* @param outboundHostPort
* the OUTBOUND_HOST_PORT value
*/
public void setOutboundHostPort(String outboundHostPort) {
this.outboundHostPort = outboundHostPort;
}
// /**
// * Return the value associated with the column: OUTBOUND_USER_ID
// */
// public String getOutboundUserId() {
// return outboundUserId;
// }
//
// /**
// * Set the value related to the column: OUTBOUND_USER_ID
// *
// * @param outboundUserId
// * the OUTBOUND_USER_ID value
// */
// public void setOutboundUserId(String outboundUserId) {
// this.outboundUserId = outboundUserId;
// }
//
// /**
// * Return the value associated with the column: OUTBOUND_USER_PWD
// */
// public String getOutboundUserPwd() {
// return outboundUserPwd;
// }
//
// /**
// * Set the value related to the column: OUTBOUND_USER_PWD
// *
// * @param outboundUserPwd
// * the OUTBOUND_USER_PWD value
// */
// public void setOutboundUserPwd(String outboundUserPwd) {
// this.outboundUserPwd = outboundUserPwd;
// }
/**
* Return the value associated with the column: OUTBOUND_DIR
*/
public String getOutboundDir() {
return outboundDir;
}
/**
* Set the value related to the column: OUTBOUND_DIR
*
* @param outboundDir
* the OUTBOUND_DIR value
*/
public void setOutboundDir(String outboundDir) {
this.outboundDir = outboundDir;
}
/**
* Return the value associated with the column: OUTBOUND_TRANSFER_TYPE
*/
public String getOutboundTransferType() {
return outboundTransferType;
}
/**
* Set the value related to the column: OUTBOUND_TRANSFER_TYPE
*
* @param outboundTransferType
* the OUTBOUND_TRANSFER_TYPE value
*/
public void setOutboundTransferType(String outboundTransferType) {
this.outboundTransferType = outboundTransferType;
}
/**
* Return the value associated with the column: OUTBOUND_CONNECTION_MODE
*/
public String getOutboundConnectionMode() {
return outboundConnectionMode;
}
/**
* Set the value related to the column: OUTBOUND_CONNECTION_MODE
*
* @param outboundConnectionMode
* the OUTBOUND_CONNECTION_MODE value
*/
public void setOutboundConnectionMode(String outboundConnectionMode) {
this.outboundConnectionMode = outboundConnectionMode;
}
/**
* Return the value associated with the column: PARSING_RULE
*/
public String getParsingRule() {
return parsingRule;
}
/**
* Set the value related to the column: PARSING_RULE
*
* @param parsingRule
* the PARSING_RULE value
*/
public void setParsingRule(String parsingRule) {
this.parsingRule = parsingRule;
}
/**
* Return the value associated with the column: REG_DATE
*/
public String getRegDate() {
return regDate;
}
/**
* Set the value related to the column: REG_DATE
*
* @param regDate
* the REG_DATE value
*/
public void setRegDate(String regDate) {
this.regDate = regDate;
}
/**
* Return the value associated with the column: MOD_DATE
*/
public String getModDate() {
return modDate;
}
/**
* Set the value related to the column: MOD_DATE
*
* @param modDate
* the MOD_DATE value
*/
public void setModDate(String modDate) {
this.modDate = modDate;
}
/**
* Return the value associated with the column: INBOUND_GATHER_RENAME
*/
public String getInboundGatherRename() {
return inboundGatherRename;
}
/**
* Set the value related to the column: INBOUND_GATHER_RENAME
*
* @param inboundGatherRename
* the INBOUND_GATHER_RENAME value
*/
public void setInboundGatherRename(String inboundGatherRename) {
this.inboundGatherRename = inboundGatherRename;
}
/**
* Return the value associated with the column: OUTBOUND_RENAME
*/
public String getOutboundRename() {
return outboundRename;
}
/**
* Set the value related to the column: OUTBOUND_RENAME
*
* @param outboundRename
* the OUTBOUND_RENAME value
*/
public void setOutboundRename(String outboundRename) {
this.outboundRename = outboundRename;
}
public String getInboundGatherLocale() {
return inboundGatherLocale;
}
public void setInboundGatherLocale(String inboundGatherLocale) {
this.inboundGatherLocale = inboundGatherLocale;
}
public String getInboundFileEncoding() {
return inboundFileEncoding;
}
public void setInboundFileEncoding(String inboundFileEncoding) {
this.inboundFileEncoding = inboundFileEncoding;
}
public String getOutboundFileEncoding() {
return outboundFileEncoding;
}
public void setOutboundFileEncoding(String outboundFileEncoding) {
this.outboundFileEncoding = outboundFileEncoding;
}
}
|
package view.insuranceSystemView.salesView.salesMan.LookupAvailableProduct;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.util.Vector;
import model.data.customerData.CustomerData;
import model.data.insuranceData.AbsInsuranceData;
import model.dataList.IntDataList;
import view.aConstant.InsuranceSystemViewConstant;
import view.component.BasicLabel;
import view.component.SeparateLine;
import view.component.button.ActionButton;
import view.component.button.LinkButton;
import view.component.group.DynamicGroup;
import view.component.textArea.OutputTextArea;
import view.insuranceSystemView.absInsuranceSystemView.InsuranceSystemView;
public class ShowAvailableProductView extends InsuranceSystemView {
private static final long serialVersionUID = 1L;
// Static
public enum EActionCommands {SigninCustomer,LookupAvailableProduct,WatchActivityPlan, WatchSalesTrainingPlan}
// association
private CustomerData customerData;
// Constructor
public ShowAvailableProductView(ActionListener actionListener, IntDataList<AbsInsuranceData> insuranceDataList, CustomerData customerData) {
// association
this.customerData = customerData;
//create and add component
this.addComponent(new BasicLabel("가입하실 수 있는 보험 상품입니다."));
this.addComponent(new SeparateLine(Color.black));
Vector<AbsInsuranceData> searchedInsuranceData = searching(insuranceDataList);
if(searchedInsuranceData.size()==0){
this.addComponent(new OutputTextArea("고객님께서 가입하실 수 있는 상품이 존재하지 않습니다.", ""));
} else {
DynamicGroup g = new DynamicGroup();
for (AbsInsuranceData insuranceData : searchedInsuranceData) {
g.addGroupComponent(new ActionButton(printline(insuranceData), Integer.toString(insuranceData.getID()), actionListener));
}
this.addComponent(g);
}
this.addToLinkPanel(
new LinkButton(InsuranceSystemViewConstant.SomeThingLookGreat, "", null),
new LinkButton(InsuranceSystemViewConstant.SomeThingLookNide, "", null),
new LinkButton("고객 가입", EActionCommands.SigninCustomer.name(), actionListener),
new LinkButton("가능 보험 조회", EActionCommands.LookupAvailableProduct.name(), actionListener),
new LinkButton("판매 활동 조회", EActionCommands.WatchActivityPlan.name(), actionListener),
new LinkButton("영업 활동 조회", EActionCommands.WatchSalesTrainingPlan.name(), actionListener)
);
}
// 가입가능 보험 조회
public Vector<AbsInsuranceData> searching(IntDataList<AbsInsuranceData> insuranceDataList) {
// IntDataList<AbsInsuranceData> availableInsuranceList= new DataList<AbsInsuranceData>();
Vector<AbsInsuranceData> availableInsuranceList = new Vector<AbsInsuranceData>();
for (AbsInsuranceData insuranceData : insuranceDataList.getList()) {
if (!insuranceData.isCustomerSignIn(this.customerData.getID())
&& insuranceData.getLossPercent() >= insuranceData.insuranceRateCheck(this.customerData)) {
availableInsuranceList.add(insuranceData);
}
}
return availableInsuranceList;
}
// 버튼 값 가공
public String printline(AbsInsuranceData insuranceData) {
// Format : 보험명 (내용 10자리 + ...)
String content = "";
if (insuranceData.getContent().length() > 10) {content = insuranceData.getContent().substring(0, 10);
} else {content = insuranceData.getContent();}
String line = insuranceData.getName() + "(" + content + ")";
return line;
}
}
|
/**
*/
package iso20022.impl;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Map;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.DiagnosticChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentWithInverseEList;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.util.InternalEList;
import iso20022.BusinessProcessCatalogue;
import iso20022.Iso20022Package;
import iso20022.Repository;
import iso20022.TopLevelCatalogueEntry;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Business Process Catalogue</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link iso20022.impl.BusinessProcessCatalogueImpl#getRepository <em>Repository</em>}</li>
* <li>{@link iso20022.impl.BusinessProcessCatalogueImpl#getTopLevelCatalogueEntry <em>Top Level Catalogue Entry</em>}</li>
* </ul>
*
* @generated
*/
public class BusinessProcessCatalogueImpl extends ModelEntityImpl implements BusinessProcessCatalogue {
/**
* The cached value of the '{@link #getTopLevelCatalogueEntry() <em>Top Level Catalogue Entry</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTopLevelCatalogueEntry()
* @generated
* @ordered
*/
protected EList<TopLevelCatalogueEntry> topLevelCatalogueEntry;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected BusinessProcessCatalogueImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Iso20022Package.eINSTANCE.getBusinessProcessCatalogue();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Repository getRepository() {
if (eContainerFeatureID() != Iso20022Package.BUSINESS_PROCESS_CATALOGUE__REPOSITORY) return null;
return (Repository)eInternalContainer();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetRepository(Repository newRepository, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject)newRepository, Iso20022Package.BUSINESS_PROCESS_CATALOGUE__REPOSITORY, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setRepository(Repository newRepository) {
if (newRepository != eInternalContainer() || (eContainerFeatureID() != Iso20022Package.BUSINESS_PROCESS_CATALOGUE__REPOSITORY && newRepository != null)) {
if (EcoreUtil.isAncestor(this, newRepository))
throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
NotificationChain msgs = null;
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
if (newRepository != null)
msgs = ((InternalEObject)newRepository).eInverseAdd(this, Iso20022Package.REPOSITORY__BUSINESS_PROCESS_CATALOGUE, Repository.class, msgs);
msgs = basicSetRepository(newRepository, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.BUSINESS_PROCESS_CATALOGUE__REPOSITORY, newRepository, newRepository));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<TopLevelCatalogueEntry> getTopLevelCatalogueEntry() {
if (topLevelCatalogueEntry == null) {
topLevelCatalogueEntry = new EObjectContainmentWithInverseEList<TopLevelCatalogueEntry>(TopLevelCatalogueEntry.class, this, Iso20022Package.BUSINESS_PROCESS_CATALOGUE__TOP_LEVEL_CATALOGUE_ENTRY, Iso20022Package.TOP_LEVEL_CATALOGUE_ENTRY__BUSINESS_PROCESS_CATALOGUE);
}
return topLevelCatalogueEntry;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public boolean EntriesHaveUniqueName(Map context, DiagnosticChain diagnostics) {
// TODO: implement this method >>> DONE
// Ensure that you remove @generated or mark it @generated NOT
return true;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Iso20022Package.BUSINESS_PROCESS_CATALOGUE__REPOSITORY:
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
return basicSetRepository((Repository)otherEnd, msgs);
case Iso20022Package.BUSINESS_PROCESS_CATALOGUE__TOP_LEVEL_CATALOGUE_ENTRY:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getTopLevelCatalogueEntry()).basicAdd(otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Iso20022Package.BUSINESS_PROCESS_CATALOGUE__REPOSITORY:
return basicSetRepository(null, msgs);
case Iso20022Package.BUSINESS_PROCESS_CATALOGUE__TOP_LEVEL_CATALOGUE_ENTRY:
return ((InternalEList<?>)getTopLevelCatalogueEntry()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
switch (eContainerFeatureID()) {
case Iso20022Package.BUSINESS_PROCESS_CATALOGUE__REPOSITORY:
return eInternalContainer().eInverseRemove(this, Iso20022Package.REPOSITORY__BUSINESS_PROCESS_CATALOGUE, Repository.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Iso20022Package.BUSINESS_PROCESS_CATALOGUE__REPOSITORY:
return getRepository();
case Iso20022Package.BUSINESS_PROCESS_CATALOGUE__TOP_LEVEL_CATALOGUE_ENTRY:
return getTopLevelCatalogueEntry();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Iso20022Package.BUSINESS_PROCESS_CATALOGUE__REPOSITORY:
setRepository((Repository)newValue);
return;
case Iso20022Package.BUSINESS_PROCESS_CATALOGUE__TOP_LEVEL_CATALOGUE_ENTRY:
getTopLevelCatalogueEntry().clear();
getTopLevelCatalogueEntry().addAll((Collection<? extends TopLevelCatalogueEntry>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Iso20022Package.BUSINESS_PROCESS_CATALOGUE__REPOSITORY:
setRepository((Repository)null);
return;
case Iso20022Package.BUSINESS_PROCESS_CATALOGUE__TOP_LEVEL_CATALOGUE_ENTRY:
getTopLevelCatalogueEntry().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Iso20022Package.BUSINESS_PROCESS_CATALOGUE__REPOSITORY:
return getRepository() != null;
case Iso20022Package.BUSINESS_PROCESS_CATALOGUE__TOP_LEVEL_CATALOGUE_ENTRY:
return topLevelCatalogueEntry != null && !topLevelCatalogueEntry.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException {
switch (operationID) {
case Iso20022Package.BUSINESS_PROCESS_CATALOGUE___ENTRIES_HAVE_UNIQUE_NAME__MAP_DIAGNOSTICCHAIN:
return EntriesHaveUniqueName((Map)arguments.get(0), (DiagnosticChain)arguments.get(1));
}
return super.eInvoke(operationID, arguments);
}
} //BusinessProcessCatalogueImpl
|
package loecraftpack.ponies.abilities;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import loecraftpack.enums.Race;
import loecraftpack.packet.PacketHelper;
import loecraftpack.packet.PacketIds;
import loecraftpack.ponies.abilities.active.AbilityBuckTree;
import loecraftpack.ponies.abilities.active.AbilityFireball;
import loecraftpack.ponies.abilities.active.AbilityOreVision;
import loecraftpack.ponies.abilities.active.AbilityTeleport;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.common.network.Player;
import cpw.mods.fml.common.registry.LanguageRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public abstract class ActiveAbility extends AbilityBase
{
// CAUTION: Make sure this is updated when you add abilities.
public static Class[] abilityClasses = new Class[] {AbilityFireball.class, AbilityTeleport.class, AbilityOreVision.class, AbilityBuckTree.class};
public static String[] abilityNames = new String[abilityClasses.length];
protected int activeID = -1;
protected boolean toggled = false;
private boolean isToggleable = false;
private float cycle = 0; // Used while ability is toggled to make cooldown
// animation continually cycle
protected int energyCost = 0;
protected int CooldownGlobal = 0;
protected int CooldownNormal = 0;
protected int Cooldown = 0;
protected float cooldown = 0;
protected int Casttime = 0;
protected float casttime = 0;
private boolean held;
private boolean heldChanged;
private long time;
private long lastTime;
public ActiveAbility(String name, Race race, int cost, int globalCooldown)
{
super(name, race);
CooldownNormal = 1;
energyCost = cost;
this.CooldownGlobal = globalCooldown;
isToggleable = true;
}
public ActiveAbility(String name, Race race, int cost, int globalCooldown, int cooldown)
{
super(name, race);
CooldownNormal = cooldown;
energyCost = cost;
this.CooldownGlobal = globalCooldown;
}
public ActiveAbility(String name, Race race, int cost, int globalCooldown, int cooldown, int casttime)
{
super(name, race);
CooldownNormal = cooldown;
Casttime = casttime;
energyCost = cost;
this.CooldownGlobal = globalCooldown;
}
public static void RegisterAbilities()
{
ActiveAbility[] templateAbilities = NewAbilityArray();
for (int i = 0; i < templateAbilities.length; i++)
{
ActiveAbility ability = templateAbilities[i];
LanguageRegistry.instance().addStringLocalization("item.itemAbility." + ability.icon + ".name", ability.name);
abilityNames[i] = ability.name;
}
}
public static ActiveAbility[] NewAbilityArray()
{
byte id = 0;
ArrayList<ActiveAbility> abilityList = new ArrayList<ActiveAbility>();
for (Class c : abilityClasses)
{
try
{
ActiveAbility ability = (ActiveAbility) c.getConstructor().newInstance();
abilityList.add(ability);
ability.activeID = id;
id++;
}
catch (Exception e)
{
e.printStackTrace();
}
}
return abilityList.toArray(new ActiveAbility[0]);
}
public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player)
{
held = true;
time = System.currentTimeMillis();
if (cooldown <= 0 && (toggled || player.capabilities.isCreativeMode || getEnergyCost(player) <= playerData.energy))
{
if (casttime >= Casttime)
{
System.out.println((isClient()?"Client: ":"Server: ") + playerData.energy);
if ((isClient() && castSpellClient(player, world)) || (!isClient() && castSpellServer(player, world)))
{
cooldown = (Cooldown = CooldownNormal);
casttime = 0;
playerData.setCharge(0, 100);
if (isClient() && !toggled)
playerData.applyGlobalCooldown();
}
if (isToggleable)
{
toggled = !toggled;
if (!toggled)
{
cycle = 0;
if (isClient())
CastSpellUntoggledClient(player);
else
CastSpellUntoggledServer(player);
}
}
}
else
{
casttime += 0.25f;
playerData.setCharge(casttime, Casttime);
}
}
return itemStack;
}
public void onUpdate(EntityPlayer player)
{
if (cooldown > 0)
cooldown -= 0.05f;
if (toggled)
{
if (!player.capabilities.isCreativeMode)
playerData.addEnergy(-getEnergyCostToggled(player), isClient());
if (playerData.energy > getEnergyCostToggled(player))
toggled = isClient() ? CastSpellToggledClient(player) : CastSpellToggledServer(player);
else
toggled = false;
if (!toggled)
{
cycle = 0;
if (isClient())
CastSpellUntoggledClient(player);
else
CastSpellUntoggledServer(player);
}
}
if (time != lastTime || System.currentTimeMillis() - lastTime > 400)
{
lastTime = time;
if (held)
{
heldChanged = true;
}
else
{
if (heldChanged)
{
casttime = 0;
playerData.setCharge(0, 100);
}
heldChanged = false;
}
held = false;
}
}
public boolean isToggled()
{
return toggled;
}
public boolean isToggleable()
{
return isToggleable;
}
@SideOnly(Side.CLIENT)
public static boolean isToggled(int metadata)
{
return AbilityPlayerData.clientData.activeAbilities[metadata].isToggled();
}
@SideOnly(Side.CLIENT)
public void applyGlobalCooldown()
{
System.out.println("----"+this+" "+cooldown+" "+CooldownGlobal);
if (cooldown < CooldownGlobal)
cooldown = (Cooldown = CooldownGlobal);
}
public float getCooldown()
{
if (!toggled)
{
if (Cooldown == 0)
return 0;
return cooldown / Cooldown;
}
else
return cycle;
}
public static float getCooldown(int metadata)
{
return AbilityPlayerData.clientData.activeAbilities[metadata].getCooldown();
}
public Race GetRace()
{
return race;
}
/**
* activation cost
*/
public float getEnergyCost(EntityPlayer player)
{
return energyCost;
}
/**
* sustain cost
*/
public float getEnergyCostToggled(EntityPlayer player)
{
return 0;
}
/**
* used to inform the server of client-only things like particles, raycasting, energy use attempts.
* as well as handle client side logic
*/
protected abstract boolean castSpellClient(EntityPlayer player, World world);
/**
* Ability logic server side. for abilities that don't require the client to send a special packet
*/
protected abstract boolean castSpellServer(EntityPlayer player, World world);
/**
* packet triggered Ability logic - please override the method: castSpellServerPacket(Player player, int attemptID, DataInputStream data) throws IOException
*/
public void castSpellServerByHandler(Player player, DataInputStream data) throws IOException
{
//Debug: server casting availability check info
System.out.println("SERVER CAST "+cooldown+" "+casttime+" "+Casttime);
if (cooldown <= 0 && casttime >= (float)Casttime-0.1f)
{
if (castSpellServerPacket(player, data))
{
cooldown = (Cooldown = CooldownNormal);
casttime = 0;
return;
}
}
PacketDispatcher.sendPacketToPlayer(PacketHelper.Make("loecraftpack", PacketIds.useAbility, activeID, this.playerData.energy), player);
}
/**
* packet triggered Ability logic
*/
protected boolean castSpellServerPacket(Player player, DataInputStream data) throws IOException{return false;};
protected boolean CastSpellToggledClient(EntityPlayer player){return true;}
protected boolean CastSpellToggledServer(EntityPlayer player){return true;}
protected void CastSpellUntoggledClient(EntityPlayer player) {}
protected void CastSpellUntoggledServer(EntityPlayer player) {}
}
|
package com.mercadolibre.bootcampmelifrescos.dtos.response;
import com.mercadolibre.bootcampmelifrescos.model.Batch;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BatchResponse {
private Long batchNumber;
private int currentQuantity;
private LocalDate dueDate;
public BatchResponse(Batch batch) {
this.batchNumber = batch.getId();
this.currentQuantity = batch.getCurrentQuantity();
this.dueDate = batch.getDueDate();
}
}
|
package at.craftworks.challenge.tms.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.http.HttpStatus;
import at.craftworks.challenge.tms.controller.model.TaskDto;
import at.craftworks.challenge.tms.service.TaskNotFoundException;
import at.craftworks.challenge.tms.service.TaskService;
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
@Autowired
private TaskService taskService;
@GetMapping("/all")
public List<TaskDto> fetchAllTasks() {
return new TaskDto().fromTasks(taskService.getAllTasks());
};
@GetMapping
public TaskDto fetchAsingleTask(@RequestParam(required = true, name = "id") Long id) {
try {
return new TaskDto().fromTask(taskService.getOneById(id));
} catch (TaskNotFoundException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Task not found ID: " + id, e);
}
};
@PostMapping
@ResponseStatus(value = HttpStatus.CREATED)
public TaskDto createAsingleTask(@RequestBody TaskDto taskDto) {
return new TaskDto().fromTask(taskService.createTask(taskDto.toTask()));
};
@PutMapping
public TaskDto updateAsingleTask(@RequestBody TaskDto taskDto) {
try {
return new TaskDto().fromTask(taskService.updateTask(taskDto.toTask()));
} catch (TaskNotFoundException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Task not found ID: " + taskDto.getId(), e);
}
};
@DeleteMapping
public TaskDto deleteAsingleTask(@RequestParam(required = true, name = "id") Long id) {
try {
taskService.deleteOneById(id);
} catch (TaskNotFoundException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Task not found ID: " + id, e);
}
return new TaskDto();
};
}
|
package com.qst.dao;
import com.qst.bean.ResumeBasicInfo;
import com.qst.utils.DBUtils;
import java.util.Date;
//简历基本信息DAO
public class ResumeDAO {
public Integer saveResumeBasicInfo(ResumeBasicInfo resumeBasicInfo) {
String sql="insert into resume(name,gender,birthday,curLoc,resLoc,phone,email,intension,experience) values(?,?,?,?,?,?,?,?,?)";
return DBUtils.updateForPrimary(sql,resumeBasicInfo.getName(),resumeBasicInfo.getGender(),resumeBasicInfo.getBirthday(),
resumeBasicInfo.getCurLoc(),resumeBasicInfo.getResLoc(),resumeBasicInfo.getPhone(),resumeBasicInfo.getEmail(),
resumeBasicInfo.getIntension(),resumeBasicInfo.getExperience());
}
public void updateHeadShot(int qid, String fileName) {
String sql="update resume set headShot=? where qid=?";
DBUtils.update(sql,fileName,qid);
}
public ResumeBasicInfo getResumeBasicInfoById(Integer resumeID) {
String sql="select * from resume where qid=?";
ResumeBasicInfo resumeBasicInfo=DBUtils.getSingleObj(ResumeBasicInfo.class,sql,resumeID);
return resumeBasicInfo;
}
}
|
package com.wdl.query.hql.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;
import com.alibaba.fastjson.JSON;
import com.wdl.base.pojo.PageInfo;
import com.wdl.base.service.BaseService;
import com.wdl.query.hql.pojo.Column;
import com.wdl.query.hql.pojo.Query;
import com.wdl.query.hql.pojo.QueryCondition;
import com.wdl.query.hql.pojo.QueryDefinition;
import com.wdl.util.ClassUtil;
import com.wdl.util.StrUtil;
@Controller
@RequestMapping("/queryController")
public class QueryHqlController {
@Resource
private BaseService baseService;
/**
* table通用查询
*
* @param parm
* @return
* @throws Exception
*/
@RequestMapping("/queryData")
@ResponseBody
public Map<String, Object> queryTable(String parm) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
QueryCondition condition = JSON.parseObject(HtmlUtils.htmlUnescape(parm), QueryCondition.class);
Query query = condition.getQuery() != null ? condition.getQuery()
: QueryDefinition.getQueryById(condition.getQueryId());
if (query != null && query.getClassName() != null) {
parseParms(query, condition, map);
map.put("query", JSON.toJSON(query));
map.put("columns", JSON.toJSON(query.getColumnList()));
} else {
throw new RuntimeException("Query is null or className is not exist!");
}
return map;
}
public void parseParms(Query query, QueryCondition con, Map<String, Object> map) {
PageInfo pageInfo = con.getPageInfo() == null ? new PageInfo(query.getPagesize()) : con.getPageInfo();
Map<String, Object> vals = new HashMap<String, Object>();
StringBuffer hql = new StringBuffer();
hql.append("from ");
hql.append(query.getClassName());
hql.append(" where 1=1");
if (query.getJoin() != null) {
hql.append(" and " + query.getJoin());
}
if (con.getConditions() != null) {
int key_index = 0;
for (Map<String, Object> parms : con.getConditions()) {
key_index++;
if (parms.get("value") != null && !"".equals(parms.get("value"))) {
String filter = (parms.get("filter") == null ? null : parms.get("filter").toString());
if (filter == null) {
String filterKey = (String) parms.get("name");
if (query.getColumnList() != null) {
for (Column c : query.getColumnList()) {
if (filterKey.equals(c.getKey())) {
filter = (c.getOper() == null ? "LIKE" : c.getOper());
break;
}
}
}
if (filter == null) {
filter = "like";
}
}
filter = filter.toLowerCase();
// hql中查询使用不支持":sub.name"的方式,需将占位变量替换下
String skey = parms.get("name").toString().replace(".", "_");
if ("EQ".toLowerCase().equals(filter)) {
hql.append(" and ");
hql.append(parms.get("name").toString());
hql.append("=:");
hql.append(skey + key_index);
vals.put(skey + key_index, parseValue(query.getClassName(), parms.get("name").toString(),
parms.get("value"), filter));
} else if ("GT".toLowerCase().equals(filter)) {
hql.append(" and ");
hql.append(parms.get("name").toString());
hql.append(">:");
hql.append(skey + key_index);
vals.put(skey + key_index, parseValue(query.getClassName(), parms.get("name").toString(),
parms.get("value"), filter));
} else if ("GE".toLowerCase().equals(filter)) {
hql.append(" and ");
hql.append(parms.get("name").toString());
hql.append(">=:");
hql.append(skey + key_index);
vals.put(skey + key_index, parseValue(query.getClassName(), parms.get("name").toString(),
parms.get("value"), filter));
} else if ("LT".toLowerCase().equals(filter)) {
hql.append(" and ");
hql.append(parms.get("name").toString());
hql.append("<:");
hql.append(skey + key_index);
vals.put(skey + key_index, parseValue(query.getClassName(), parms.get("name").toString(),
parms.get("value"), filter));
} else if ("LE".toLowerCase().equals(filter)) {
hql.append(" and ");
hql.append(parms.get("name").toString());
hql.append("<=:");
hql.append(skey + key_index);
vals.put(skey + key_index, parseValue(query.getClassName(), parms.get("name").toString(),
parms.get("value"), filter));
} else if ("LIKE".toLowerCase().equals(filter)) {
hql.append(" and ");
hql.append(parms.get("name").toString());
hql.append(" like :");
hql.append(skey + key_index);
vals.put(skey + key_index, parseValue(query.getClassName(), parms.get("name").toString(),
parms.get("value"), filter));
} else if ("BETWEEN".toLowerCase().equals(filter)) {
String[] keys = parms.get("value").toString().split(",");
if (keys.length == 1) {
hql.append(" and ");
hql.append(parms.get("name").toString());
hql.append(" >= :");
hql.append(skey + key_index);
vals.put(skey + key_index,
parseValue(query.getClassName(), parms.get("name").toString(), keys[0], filter));
} else if (keys.length == 2) {
hql.append(" and ");
hql.append(parms.get("name").toString());
if (StrUtil.isEmpty(keys[0])) {
hql.append(" <= :");
hql.append(skey + key_index);
vals.put(skey + key_index, parseValue(query.getClassName(),
parms.get("name").toString(), keys[1], filter));
} else {
hql.append(" between :");
hql.append(skey + key_index);
vals.put(skey + key_index, parseValue(query.getClassName(),
parms.get("name").toString(), keys[0], filter));
key_index++;
hql.append(" and :");
hql.append(skey + key_index);
vals.put(skey + key_index, parseValue(query.getClassName(),
parms.get("name").toString(), keys[1], filter));
}
}
} else if ("IN".toLowerCase().equals(filter)){
String[] keys = parms.get("value").toString().split(",");
if (keys.length > 0) {
hql.append(" and ");
hql.append(parms.get("name").toString());
hql.append(String.format(" in (%s)", parms.get("value").toString().startsWith("'")&&parms.get("value").toString().endsWith("'")?parms.get("value").toString():"'"+parms.get("value").toString()+"'"));
}
}
}
}
}
pageInfo.setCount(baseService.count("select count(*) " + hql.toString(), vals).intValue());
// 排序
String sortInfo = con.getSortInfo() != null ? con.getSortInfo() : query.getOrder();
if (sortInfo != null) {
if (sortInfo.indexOf("_") > -1) {
sortInfo = sortInfo.replace("_", ".");
hql.append(" order by ");
hql.append(sortInfo);
} else {
hql.append(" order by ");
hql.append(sortInfo);
}
}
String select = buildSelect(query);
if ("true".equals(query.getShowPage())) {
List list = baseService.getPageMapByHql(select + hql.toString(), vals, pageInfo.getPageNum(),
pageInfo.getPageSize());
map.put("objList", list);
} else {
map.put("objList", baseService.getPageMapByHql(select + hql.toString(), vals));
}
map.put("pageInfo", pageInfo);
}
public Object parseValue(String className, String name, Object value, String oper) {
Object obj = null;
if (name.contains(".")) {
String[] keys = name.split("\\.");
String[] classNames = className.split(",");
for (String c : classNames) {
if (c.contains(" " + keys[0])) {
className = c.replace(" " + keys[0], "");
className.trim();
}
}
className = ClassUtil.getFieldType(className, keys[1]);
} else {
className = ClassUtil.getFieldType(className, name);
}
if ("java.lang.String".equals(className)) {
obj = value == null ? null : value.toString();
} else if ("java.lang.Integer".equals(className)) {
obj = Integer.parseInt(value.toString());
} else if ("java.lang.Long".equals(className)) {
obj = Long.parseLong(value.toString());
} else if ("java.lang.Double".equals(className)) {
obj = Double.parseDouble(value.toString());
} else if ("java.lang.Float".equals(className)) {
obj = Float.parseFloat(value.toString());
} else if ("java.util.Date".equals(className)) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
obj = sdf.parse(value.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
if ("like".toLowerCase().equals(oper)) {
obj = "%" + obj + "%";
}
return obj;
}
private String buildSelect(Query query) {
String select = "";
select = "select ";
List<Column> columns = query.getColumnList();
List<Column> cols = new ArrayList<Column>();
for (Column c : columns) {
if (exist(query.getClassName(), c.getKey())) {
cols.add(c);
}
}
for (int i = 0; i < cols.size(); i++) {
if (i != cols.size() - 1) {
select += cols.get(i).getKey() + " as " + cols.get(i).getKey().replace(".", "_") + ",";
} else {
select += cols.get(i).getKey() + " as " + cols.get(i).getKey().replace(".", "_") + " ";
}
}
return select;
}
private boolean exist(String className, String key) {
Object obj = null;
if (key.contains(".")) {
String[] keys = key.split("\\.");
String[] classNames = className.split(",");
for (String c : classNames) {
if (c.contains(" " + keys[0])) {
className = c.replace(" " + keys[0], "");
className.trim();
}
}
obj = ClassUtil.getFieldColumnAnnotation(className, keys[1]);
} else {
if (className.contains(",")) {
return false;
}
obj = ClassUtil.getFieldColumnAnnotation(className, key);
}
return obj != null;
}
public static void main(String[] args) {
String str = "1,";
String[] d = str.split(",");
System.out.println(123);
}
}
|
package com.tzl.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient(name = "spring-feign-provider",path = "/testFeign") //声明调用的服务名称
public interface PersonClient {
@GetMapping("/hello")
String hello();
}
|
package com.iot.wookee.searchpicture;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import static android.widget.AdapterView.*;
public class GameActivity extends Activity {
// 사진 뿌려주는 곳
private GridView gridView;
// 1p 2p 퀴즈 리스트 뿌려주는곳
private Gallery [] galleries;
private ImageAdapter gridImageAdapter;
private ImageAdapter [] playerImageAdapters;
// 누구 차례인지 턴 관리.
private int turn; // 1p:0, 2p:1
// 플레이어 진행 상황 확인하기 위해 imageID, index 담는 변수
private class Player {
private int imageID;
private int index;
public Player() {
this.index = 0;
}
}
private Player [] players;
// 1p, 2p 게임 진행 상황 표시판
private TextView [] boards;
// text용 보드
private TextView textBoard;
// 실행중인지 확인
boolean isRunning;
// intent로 정보받기
Intent intent;
int imagetype;
String sex;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
// 남자/여자 구분하기 위해 인자 받는 부분
intent = getIntent();
sex = intent.getStringExtra("sex");
if (sex.equals("man"))
imagetype = 0;
else if (sex.equals("woman"))
imagetype = 1;
// 게임은 항상 1p 부터 시작
turn = 0;
// 플레이어가 게임판을 클릭해서 애니메이션 동작중에 클릭 막기 위한 flag
isRunning = false;
// 플레이어 선언
players = new Player[2];
players[0] = new Player();
players[1] = new Player();
// text용 보드, 나중에 지울것.
textBoard = (TextView)findViewById(R.id.textBoard);
// 문제판 출력부분 (girdView)
gridImageAdapter = new ImageAdapter(this, imagetype);
gridImageAdapter.setFlag(2);
gridView = (GridView) findViewById(R.id.gridView);
gridView.setAdapter(gridImageAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (isRunning == false) {
isRunning = true;
flipCard(view, i, true);
} else
;
printTurn();
}
});
// 1p, 2p 문제 출력부분
playerImageAdapters = new ImageAdapter[2];
galleries = new Gallery[2];
galleries[0] = (Gallery) findViewById(R.id.gallery0);
galleries[1] = (Gallery) findViewById(R.id.gallery1);
boards = new TextView[2];
boards[0] = (TextView)findViewById(R.id.board0);
boards[1] = (TextView)findViewById(R.id.board1);
// 갤러리에 어댑터 설정
for (int i = 0; i < 2; ++i) {
playerImageAdapters[i] = new ImageAdapter(this, imagetype);
playerImageAdapters[i].setFlag(i);
galleries[i].setAdapter(playerImageAdapters[i]);
galleries[i].setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
}
printTurn();
// 갤러리에 셀렉트된 뷰 객체를 전역변수에 담기
galleries[0].setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int index, long l) {
players[0].imageID = playerImageAdapters[0].getImageID(0, index); // 현재 띄워진 이미지의 인덱스 번호를 players[]에 담자.
boards[0].setText("" + (index + 1) + " / 5"); // 진행 상황 출력
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {}
});
galleries[1].setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int index, long l) {
players[1].imageID = playerImageAdapters[1].getImageID(1, index); // 현재 띄워진 이미지의 인덱스 번호를 players[]에 담자.
boards[1].setText("" + (index + 1) + " / 5"); // 진행 상황 출력
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {}
});
}
// ****게임에 쓰이는 함수 고고!****
// 목차
// 1-1 : 한 선수가 카드를 뒤집는다.
// 1-2 : (카드 뒤집는 클래스 부분)
// 1-3 : 뒤집은 카드가 맞는지 확인한다.
// 1-4 : 맞은 경우 다음 문제를 계속 푼다.
// 1-5 : 틀린 경우 다름 플레이어로 턴이 넘어간다.
// 1-6 : 누구 턴인지 출력해주는 함수
// 1-7 : 게임 끝난 후 dialog 창을 출력해준다.
// 1-1 카드 뒤집기 실행하는 함수
public void flipCard(View view, int index, boolean isBack){
FlipAnimation flipAnimation = new FlipAnimation(view, index, isBack);
view.startAnimation(flipAnimation);
}
// 1-2 FlipAnimation 클래스
public class FlipAnimation extends Animation {
private ImageView view;
private int index;
private Camera camera;
private float centerX;
private float centerY;
private boolean isBackward;
public FlipAnimation(View view, int index, boolean isBack) {
this.view = (ImageView)view;
this.index = index;
this.isBackward = isBack;
setDuration(2000);
setFillAfter(false);
setInterpolator(new AccelerateDecelerateInterpolator());
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
centerX = width/2;
centerY = height/2;
camera = new Camera();
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final double radians = Math.PI * interpolatedTime;
float degrees = (float) (360.0 * radians / Math.PI);
if (interpolatedTime >= 0.25f) {
//view.setImageResource(gridImageAdapter.getImageID(2, index));
//원본 이미지 Bitmap
Bitmap originalImg = BitmapFactory.decodeResource(getResources(), gridImageAdapter.getImageID(2, index));
//좌우반전 이미지 효과 및 Bitmap 만들기
Matrix sideInversion = new Matrix();
sideInversion.setScale(-1, 1);
Bitmap sideInversionImg = Bitmap.createBitmap(originalImg, 0, 0,
originalImg.getWidth(), originalImg.getHeight(), sideInversion, false);
view.setImageBitmap(sideInversionImg);
}
if (interpolatedTime > 0.49f && interpolatedTime < 0.53f)
checkCard(view, turn, index);
if (interpolatedTime >= 0.75f)
if(imagetype==0)
view.setImageResource(R.drawable.girlcardback);
else if (imagetype ==1)
view.setImageResource(R.drawable.boycardback);
if (interpolatedTime >= 0.98f)
isRunning = false;
final Matrix matrix = t.getMatrix();
camera.save();
camera.rotateY(degrees);
camera.getMatrix(matrix);
camera.restore();
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
super.applyTransformation(interpolatedTime, t);
}
}
// 1-3 카드 맞는지 확인
private void checkCard(View view, int turn, int index) {
int pickCard = gridImageAdapter.getImageID(2, index);
int playerCard = players[turn].imageID;
if (pickCard == playerCard) {
// textBoard.setText("grid : " + pickCard + "\n" + (turn+1) + "p : " + playerCard + "\n");
Toast.makeText(getApplication(), "정답", Toast.LENGTH_SHORT).show();
if (turn == 0)
nextImage(galleries[0], players[turn]);
else if (turn == 1)
nextImage(galleries[1], players[turn]);
} else {
// textBoard.setText("grid : " + pickCard + "\n" + (turn+1) + "p : " + playerCard + "\n");
Toast.makeText(getApplication(), "땡", Toast.LENGTH_SHORT).show();
switchTurn();
}
}
// 1-4 플레이어 문제 넘기는 함수
private void nextImage(Gallery gallery, Player player){
if (player.index == 4) { // 겜 끝나면 dialog
AlertDialog dialog = createDialogBox(turn);
dialog.show();
} else
gallery.setSelection(++player.index); // 다음 이미지 넘어감
}
// 1-5 플레이어 턴 넘기는 함수
private void switchTurn() {
if (turn == 0)
turn = 1;
else if (turn == 1)
turn = 0; // 여기도 위에꺼랑 마찬가지
printTurn();
}
// 1-6 턴 화면에 출력 함수
private void printTurn() {
if (turn == 0) {
textBoard.setText("◀ 1P");
galleries[0].setAlpha(1f);
galleries[1].setAlpha(0.3f);
} else if (turn == 1){
textBoard.setText("2P ▶");
galleries[0].setAlpha(0.3f);
galleries[1].setAlpha(1f);
}
}
// 1-7 게임 종료 후 dialog 출력
private AlertDialog createDialogBox(int turn) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("승리");
builder.setMessage("★★★★★★★ " + (turn+1) + "P 승리!! 짱짱맨 ★★★★★★");
builder.setIcon(R.drawable.dialog);
builder.setNegativeButton("Quit Game", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
builder.setPositiveButton("Let's Revenge", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent returnIntent = new Intent();
// returnIntent.putExtra("returnsex", sex);
setResult(RESULT_OK, returnIntent);
finish();
}
});
AlertDialog dialog = builder.create();
return dialog;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_BACK:
GameActivity.this.finish();
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) { return true; }
return super.onOptionsItemSelected(item);
}
}
|
package com.edasaki.rpg.commands.owner;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.edasaki.core.utils.RMessages;
import com.edasaki.rpg.PlayerDataRPG;
import com.edasaki.rpg.commands.RPGAbstractCommand;
import com.edasaki.rpg.horses.HorseManager;
public class ReloadHorsesCommand extends RPGAbstractCommand {
public ReloadHorsesCommand(String... commandNames) {
super(commandNames);
}
@Override
public void execute(CommandSender sender, String[] args) {
HorseManager.reload();
sender.sendMessage("Stables reloaded.");
RMessages.announce(ChatColor.RED + "Stables reloaded for updates.");
}
@Override
public void executePlayer(Player p, PlayerDataRPG pd, String[] args) {
}
@Override
public void executeConsole(CommandSender sender, String[] args) {
}
}
|
package com.niksoftware.snapseed.views;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import com.niksoftware.snapseed.MainActivity;
import com.niksoftware.snapseed.MainActivity.Screen;
import com.niksoftware.snapseed.R;
import com.niksoftware.snapseed.controllers.FilterController;
import com.niksoftware.snapseed.controllers.StraightenController;
import com.niksoftware.snapseed.controllers.UPointController;
import com.niksoftware.snapseed.core.DeviceDefs;
import com.niksoftware.snapseed.core.FilterDefs.FilterType;
import com.niksoftware.snapseed.core.NotificationCenter;
import com.niksoftware.snapseed.core.NotificationCenterListener.ListenerType;
import java.util.ArrayList;
import java.util.Iterator;
public class RootView extends ViewGroup {
public static final int ANIMATION_TIME = 333;
private static final boolean PRE_RENDER_BACKGROUND = false;
private EditingToolBar _editingToolBar;
private FilterPanelLandscape _filterPanelLandscape;
private FilterPanelPortrait _filterPanelPortrait;
private int _first_visible_filter_id = 0;
private GlobalToolBar _globalToolBar;
private boolean _hasInit = false;
boolean _isRunningAnimation;
private ItemSelectorView _itemSelectorView;
private ToolButton _revertButtonForNoneTablet;
private boolean _setScrollPos = false;
private WorkingAreaView _workingAreaView;
private final Point displaySizeTemp = new Point();
private Drawable editScreenBackground;
public boolean forceLayoutForFilterGUI = false;
private HelpOverlayView helpOverlay;
private boolean lastOrientationWasLandscape = false;
private Drawable mainScreenBackground;
private final Rect rootViewSizeTemp = new Rect();
private Drawable transitionScreenBackground;
public RootView(Context context) {
super(context);
init();
}
private void init() {
this._workingAreaView = new WorkingAreaView(getContext());
this._workingAreaView.setLayoutParams(new LayoutParams(-1, -1));
addView(this._workingAreaView);
willEnterSMScreen(Screen.MAIN, false);
BitmapDrawable background = new BitmapDrawable(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.new_bg));
background.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
background.setAlpha(255);
background.setAntiAlias(false);
background.setDither(false);
background.setFilterBitmap(false);
this.transitionScreenBackground = background;
Resources resources = getResources();
if (resources == null) {
throw new IllegalStateException("Resources are inaccessible.");
}
this.mainScreenBackground = resources.getDrawable(R.drawable.main_screen_background);
this.editScreenBackground = resources.getDrawable(R.drawable.edit_screen_background);
setScreenBackground(this.mainScreenBackground);
}
private Rect filterPanelBaseFrame(boolean isLandscape, Rect rootViewSize) {
Resources resources = getResources();
if (isLandscape) {
return new Rect(0, getActionBarHeight(), resources.getDimensionPixelSize(R.dimen.tmp_fl_land_panel_width), rootViewSize.height());
}
return new Rect(0, 0, rootViewSize.width(), resources.getDimensionPixelSize(R.dimen.tmp_fl_port_panel_height));
}
public Rect getWorkingAreaRect(boolean isLandscape, Screen state, Rect rootViewSize) {
switch (state) {
case EDIT_CONTROLS_LEFT:
case EDIT_CONTROLS_RIGHT:
return new Rect(0, 0, rootViewSize.width(), rootViewSize.height() - (this._editingToolBar == null ? 0 : this._editingToolBar.getHeight()));
case MAIN:
Rect filterPanelFrame = filterPanelFrame(isLandscape, state, rootViewSize);
Rect globalToolBarFrame = globalToolBarFrame(isLandscape, state, rootViewSize);
if (isLandscape) {
return new Rect(filterPanelFrame.width(), getActionBarHeight(), rootViewSize.width(), rootViewSize.height() - globalToolBarFrame.height());
}
return new Rect(0, getActionBarHeight(), rootViewSize.width(), ((rootViewSize.height() - globalToolBarFrame.height()) - filterPanelFrame.height()) + getResources().getDimensionPixelSize(R.dimen.fl_gradiend_size));
default:
return null;
}
}
public Rect globalToolBarFrame(boolean isLandscape, Screen state, Rect rootViewSize) {
Rect filterPanelFrame = filterPanelFrame(isLandscape, state, rootViewSize);
int globalToolBarHeight = 0;
if (DeviceDefs.isTablet()) {
this._globalToolBar.measure(MeasureSpec.makeMeasureSpec(0, 0), MeasureSpec.makeMeasureSpec(0, 0));
globalToolBarHeight = this._globalToolBar.getMeasuredHeight();
}
if (isLandscape) {
return new Rect(filterPanelFrame.width() + 0, (rootViewSize.height() - globalToolBarHeight) - 0, rootViewSize.width() - 0, rootViewSize.height() - 0);
}
return new Rect(0, ((rootViewSize.height() - 0) - globalToolBarHeight) - filterPanelFrame.height(), rootViewSize.width() - 0, (rootViewSize.height() - 0) - filterPanelFrame.height());
}
public Rect filterPanelFrame(boolean isLandscape, Screen state, Rect rootViewSize) {
Rect rect = filterPanelBaseFrame(isLandscape, rootViewSize);
if (!isLandscape) {
rect.top = rootViewSize.height() - rect.height();
rect.bottom = rootViewSize.height();
}
switch (state) {
case EDIT_CONTROLS_LEFT:
rect.left -= rect.width();
rect.right -= rect.width();
break;
case EDIT_CONTROLS_RIGHT:
rect.left += rootViewSize.width();
rect.right += rootViewSize.width();
break;
}
return rect;
}
public EditingToolBar getEditingToolbar() {
return this._editingToolBar;
}
public void reloadEditingToolbar() {
if (this._editingToolBar != null) {
boolean enabled = this._editingToolBar.getEnabled();
this._editingToolBar.hideUndoPopoverWindow();
removeView(this._editingToolBar);
this._editingToolBar = EditingToolBar.createEditingToolbar(getContext());
FilterController controller = MainActivity.getMainActivity().getFilterController();
this._editingToolBar.setCompareLabelText(FilterType.isCPUFilter(controller.getFilterType()) ? R.string.preview : R.string.compare_btn);
addView(this._editingToolBar);
this._editingToolBar.measure(MeasureSpec.makeMeasureSpec(getWidth(), 1073741824), MeasureSpec.makeMeasureSpec(0, 0));
this._editingToolBar.layout(0, getHeight() - this._editingToolBar.getMeasuredHeight(), this._editingToolBar.getMeasuredWidth(), getHeight());
this._editingToolBar.updateFilterController(controller);
this._editingToolBar.setEnabled(enabled);
if (controller instanceof UPointController) {
try {
controller.onResume();
} catch (Exception e) {
}
}
}
}
public WorkingAreaView getWorkingAreaView() {
return this._workingAreaView;
}
public GlobalToolBar getGlobalToolBar() {
return this._globalToolBar;
}
public ItemSelectorView getItemSelectorView() {
return this._itemSelectorView;
}
public ArrayList<Animator> willEnterSMScreen(Screen state, boolean animate) {
int deltaFromX;
boolean isLandscape = getWidth() > getHeight();
Rect rootViewSize = new Rect(0, 0, getWidth(), getHeight());
ArrayList<Animator> animations = animate ? new ArrayList() : null;
setScreenBackground(this.transitionScreenBackground);
switch (state) {
case EDIT_CONTROLS_LEFT:
case EDIT_CONTROLS_RIGHT:
setSystemUiVisibility(1);
if (this._editingToolBar == null) {
this._editingToolBar = EditingToolBar.createEditingToolbar(getContext());
addView(this._editingToolBar);
this._editingToolBar.measure(MeasureSpec.makeMeasureSpec(getWidth(), 1073741824), MeasureSpec.makeMeasureSpec(0, 0));
int editingToolbarHeight = this._editingToolBar.getMeasuredHeight();
this._editingToolBar.layout(0, getHeight() - this._editingToolBar.getMeasuredHeight(), this._editingToolBar.getMeasuredWidth(), getHeight());
if (animate) {
animations.add(ObjectAnimator.ofFloat(this._editingToolBar, "y", new float[]{(float) getHeight(), (float) (getHeight() - editingToolbarHeight)}));
}
}
if (this._itemSelectorView == null) {
this._itemSelectorView = new ItemSelectorView(MainActivity.getMainActivity());
this._itemSelectorView.measure(MeasureSpec.makeMeasureSpec(getWidth(), 1073741824), MeasureSpec.makeMeasureSpec(getHeight() - this._editingToolBar.getMeasuredHeight(), 1073741824));
this._itemSelectorView.setVisibility(8);
addView(this._itemSelectorView, indexOfChild(this._editingToolBar));
break;
}
break;
case MAIN:
break;
}
View imageView = this._workingAreaView.getImageView();
if (imageView instanceof ImageViewSW) {
((ImageViewSW) imageView).setFillBackground(true);
}
Rect rect = filterPanelFrame(isLandscape, state, rootViewSize);
Screen oldState = MainActivity.getMainActivity().getCurrentScreen();
if (oldState == Screen.EDIT_CONTROLS_RIGHT) {
deltaFromX = rootViewSize.right;
} else if (oldState == Screen.EDIT_CONTROLS_LEFT) {
deltaFromX = -rect.right;
} else {
deltaFromX = -rect.right;
}
if (isLandscape) {
if (this._filterPanelLandscape == null) {
this._filterPanelLandscape = new FilterPanelLandscape(getContext());
addView(this._filterPanelLandscape);
this._setScrollPos = true;
}
if (animate && this._filterPanelLandscape != null && state == Screen.MAIN) {
animations.add(ObjectAnimator.ofFloat(this._filterPanelLandscape, "x", new float[]{(float) deltaFromX, (float) rect.left}));
} else if (this._filterPanelLandscape != null && state == Screen.MAIN) {
this._filterPanelLandscape.setupOnClickListeners();
}
} else {
if (this._filterPanelPortrait == null) {
this._filterPanelPortrait = new FilterPanelPortrait(getContext());
addView(this._filterPanelPortrait);
this._setScrollPos = true;
}
if (animate && this._filterPanelPortrait != null && state == Screen.MAIN) {
animations.add(ObjectAnimator.ofFloat(this._filterPanelPortrait, "x", new float[]{(float) deltaFromX, (float) rect.left}));
} else if (this._filterPanelPortrait != null && state == Screen.MAIN) {
this._filterPanelPortrait.setupOnClickListeners();
}
}
if (this._globalToolBar == null) {
this._globalToolBar = new GlobalToolBar(getContext());
if (DeviceDefs.isTablet()) {
addView(this._globalToolBar);
} else {
View revertButton = this._globalToolBar.getRevertButton();
this._revertButtonForNoneTablet = revertButton;
addView(revertButton);
}
}
if (animate && state == Screen.MAIN) {
if (this._revertButtonForNoneTablet != null) {
animations.add(ObjectAnimator.ofFloat(this._revertButtonForNoneTablet, "alpha", new float[]{0.0f, 1.0f}));
} else if (this._globalToolBar != null) {
animations.add(ObjectAnimator.ofFloat(this._globalToolBar, "alpha", new float[]{0.0f, 1.0f}));
}
}
if (this._hasInit && animate) {
animateWorkingAreaView(animations, state, isLandscape, rootViewSize);
}
return animations;
}
private void animateWorkingAreaView(ArrayList<Animator> anims, Screen state, boolean isLandscape, Rect rootViewSize) {
Rect newWArect = getWorkingAreaRect(isLandscape, state, rootViewSize);
ShadowLayer shadowLayer = this._workingAreaView.getShadowLayer();
Rect oldShadowLayerRect = new Rect(shadowLayer.getLeft(), shadowLayer.getTop(), shadowLayer.getRight(), shadowLayer.getBottom());
Rect newShadowLayerRect = shadowLayer.imageToShadowRect(WorkingAreaView.getFitRect(newWArect, (float) this._workingAreaView.getImageWidth(), (float) this._workingAreaView.getImageHeight(), (float) this._workingAreaView.getBorder()));
if (MainActivity.getMainActivity()._newFilterType == 5) {
float scale = StraightenController.imageScaleFactor(newShadowLayerRect.width(), newShadowLayerRect.height());
int updatedWidth = (int) (((float) newShadowLayerRect.width()) * scale);
int updatedHeight = (int) (((float) newShadowLayerRect.height()) * scale);
newShadowLayerRect.left += (newShadowLayerRect.width() - updatedWidth) / 2;
newShadowLayerRect.top += (newShadowLayerRect.height() - updatedHeight) / 2;
newShadowLayerRect.right = newShadowLayerRect.left + updatedWidth;
newShadowLayerRect.bottom = newShadowLayerRect.top + updatedHeight;
}
shadowLayer.setPivotX((float) (shadowLayer.getWidth() / 2));
shadowLayer.setPivotY((float) (shadowLayer.getHeight() / 2));
shadowLayer.setPivotX(0.0f);
shadowLayer.setPivotY(0.0f);
ObjectAnimator transLeft = ObjectAnimator.ofFloat(shadowLayer, "translationX", new float[]{0.0f, (float) (newShadowLayerRect.left - oldShadowLayerRect.left)});
ObjectAnimator transTop = ObjectAnimator.ofFloat(shadowLayer, "translationY", new float[]{0.0f, (float) (newShadowLayerRect.top - oldShadowLayerRect.top)});
ObjectAnimator scaleX = ObjectAnimator.ofFloat(shadowLayer, "scaleX", new float[]{1.0f, ((float) newShadowLayerRect.width()) / ((float) oldShadowLayerRect.width())});
ObjectAnimator scaleY = ObjectAnimator.ofFloat(shadowLayer, "scaleY", new float[]{1.0f, ((float) newShadowLayerRect.height()) / ((float) oldShadowLayerRect.height())});
anims.add(transLeft);
anims.add(transTop);
anims.add(scaleX);
anims.add(scaleY);
final Screen screen = state;
AnimatorListener animListener = new AnimatorListener() {
public void onAnimationStart(Animator animation) {
RootView.this._isRunningAnimation = true;
RootView.this._workingAreaView.setEnabled(false);
RootView.this.setWillNotDraw(true);
}
public void onAnimationRepeat(Animator animation) {
}
public void onAnimationEnd(Animator animation) {
boolean z;
RootView.this.setWillNotDraw(false);
Rect newRootViewSize = new Rect(0, 0, RootView.this.getWidth(), RootView.this.getHeight());
RootView rootView = RootView.this;
if (newRootViewSize.width() > newRootViewSize.height()) {
z = true;
} else {
z = false;
}
Rect rect = rootView.getWorkingAreaRect(z, screen, newRootViewSize);
RootView.this._workingAreaView.setVisualFrame(rect);
RootView.this._workingAreaView.getShadowLayer().setScaleX(1.0f);
RootView.this._workingAreaView.getShadowLayer().setScaleY(1.0f);
RootView.this._workingAreaView.getShadowLayer().setTranslationX(0.0f);
RootView.this._workingAreaView.getShadowLayer().setTranslationY(0.0f);
RootView.this._workingAreaView.getShadowLayer().setPivotX((float) (rect.width() / 2));
RootView.this._workingAreaView.getShadowLayer().setPivotY((float) (rect.height() / 2));
RootView.this._workingAreaView.doLayout();
RootView.this._workingAreaView.setEnabled(true);
if (screen == Screen.MAIN) {
RootView.this._workingAreaView.removeImageViewGL();
}
NotificationCenter.getInstance().performAction(screen == Screen.MAIN ? ListenerType.DidEnterMainScreen : ListenerType.DidEnterEditingScreen, null);
RootView.this.setScreenBackground(screen == Screen.MAIN ? RootView.this.mainScreenBackground : RootView.this.editScreenBackground);
RootView.this._isRunningAnimation = false;
}
public void onAnimationCancel(Animator animation) {
onAnimationEnd(animation);
}
};
if (state == Screen.MAIN) {
this._workingAreaView.updateImageViewType(MainActivity.getMainActivity().getFilterController().getFilterType());
}
scaleY.addListener(animListener);
}
public boolean isRunningAnimation() {
return this._isRunningAnimation;
}
public void didEnterSMScreen(Screen state, boolean animate, ArrayList<Animator> existingAnimations) {
if (animate) {
boolean updateImageviewType = false;
ArrayList<Animator> animations = existingAnimations != null ? existingAnimations : new ArrayList();
ObjectAnimator animator;
switch (state) {
case EDIT_CONTROLS_LEFT:
case EDIT_CONTROLS_RIGHT:
final View panel = this._filterPanelLandscape != null ? this._filterPanelLandscape : this._filterPanelPortrait;
this._first_visible_filter_id = ((FilterPanelInterface) panel).getFirstVisibleFilterId();
animator = ObjectAnimator.ofFloat(panel, "x", new float[]{(float) panel.getLeft(), (float) (panel.getLeft() - panel.getWidth())});
animations.add(animator);
this._filterPanelLandscape = null;
this._filterPanelPortrait = null;
animator.addListener(new AnimatorListener() {
public void onAnimationStart(Animator animation) {
RootView.this._isRunningAnimation = true;
}
public void onAnimationRepeat(Animator animation) {
}
public void onAnimationEnd(Animator animation) {
RootView.this.removeView(panel);
}
public void onAnimationCancel(Animator animation) {
onAnimationEnd(animation);
}
});
updateImageviewType = true;
if (this._globalToolBar != null) {
if (DeviceDefs.isTablet()) {
removeView(this._globalToolBar);
} else if (this._revertButtonForNoneTablet != null) {
removeView(this._revertButtonForNoneTablet);
this._revertButtonForNoneTablet = null;
}
this._globalToolBar = null;
updateImageviewType = true;
break;
}
break;
case MAIN:
if (this._editingToolBar != null) {
animator = ObjectAnimator.ofFloat(this._editingToolBar, "y", new float[]{(float) this._editingToolBar.getTop(), (float) (this._editingToolBar.getTop() + this._editingToolBar.getHeight())});
animations.add(animator);
final EditingToolBar copy = this._editingToolBar;
this._editingToolBar = null;
animator.addListener(new AnimatorListener() {
public void onAnimationStart(Animator animation) {
RootView.this._isRunningAnimation = true;
}
public void onAnimationRepeat(Animator animation) {
}
public void onAnimationEnd(Animator animation) {
MainActivity.getMainActivity().unlockCurrentOrientation();
RootView.this.removeView(copy);
copy.cleanup();
RootView.this.hideHelpOverlay(false);
RootView.this._isRunningAnimation = false;
if (RootView.this._filterPanelLandscape != null) {
RootView.this._filterPanelLandscape.setupOnClickListeners();
}
if (RootView.this._filterPanelPortrait != null) {
RootView.this._filterPanelPortrait.setupOnClickListeners();
}
}
public void onAnimationCancel(Animator animation) {
onAnimationEnd(animation);
}
});
}
if (this._itemSelectorView != null) {
removeView(this._itemSelectorView);
this._itemSelectorView = null;
break;
}
break;
}
if (!animations.isEmpty()) {
final ArrayList<AnimatorListener> listeners = new ArrayList();
Iterator i$ = animations.iterator();
while (i$.hasNext()) {
Animator animator2 = (Animator) i$.next();
if (animator2.getListeners() != null) {
listeners.addAll(animator2.getListeners());
animator2.removeAllListeners();
}
}
if (updateImageviewType) {
listeners.add(new AnimatorListener() {
public void onAnimationStart(Animator animation) {
}
public void onAnimationRepeat(Animator animation) {
}
public void onAnimationEnd(Animator animation) {
RootView.this._workingAreaView.updateImageViewType(MainActivity.getMainActivity().getFilterController().getFilterType());
RootView.this._workingAreaView.requestLayout();
}
public void onAnimationCancel(Animator animation) {
onAnimationEnd(animation);
}
});
}
AnimatorSet set = new AnimatorSet();
set.playTogether(animations);
set.setDuration(333);
set.setInterpolator(new AccelerateDecelerateInterpolator());
if (listeners.size() > 0) {
set.addListener(new AnimatorListener() {
public void onAnimationStart(Animator animation) {
Iterator i$ = listeners.iterator();
while (i$.hasNext()) {
((AnimatorListener) i$.next()).onAnimationStart(animation);
}
}
public void onAnimationRepeat(Animator animation) {
Iterator i$ = listeners.iterator();
while (i$.hasNext()) {
((AnimatorListener) i$.next()).onAnimationRepeat(animation);
}
}
public void onAnimationEnd(Animator animation) {
RootView.this.post(new Runnable() {
public void run() {
AnonymousClass5.this.onAnimationEndDelayed();
}
});
}
public void onAnimationCancel(Animator animation) {
onAnimationEnd(animation);
}
private void onAnimationEndDelayed() {
Iterator i$ = listeners.iterator();
while (i$.hasNext()) {
((AnimatorListener) i$.next()).onAnimationEnd(null);
}
}
});
}
set.start();
}
}
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (this._filterPanelLandscape != null) {
this._filterPanelLandscape.measure(widthMeasureSpec, heightMeasureSpec);
}
if (this._filterPanelPortrait != null) {
this._filterPanelPortrait.measure(widthMeasureSpec, heightMeasureSpec);
}
if (this._editingToolBar != null) {
this._editingToolBar.measure(widthMeasureSpec, heightMeasureSpec);
}
}
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
boolean isLandscape = right - left > bottom - top;
Screen state = MainActivity.getMainActivity().getCurrentScreen();
this.rootViewSizeTemp.set(0, 0, getWidth(), getHeight());
if (this._workingAreaView != null) {
this._workingAreaView.setVisualFrame(getWorkingAreaRect(isLandscape, state, this.rootViewSizeTemp));
this._workingAreaView.layout(0, 0, getWidth(), getHeight());
if (this.forceLayoutForFilterGUI) {
this._workingAreaView.forceLayoutForFilterGUI();
this.forceLayoutForFilterGUI = false;
}
this._hasInit = true;
}
MainActivity.getMainActivity().getWindowManager().getDefaultDisplay().getSize(this.displaySizeTemp);
if (!(this._filterPanelLandscape == null && this._filterPanelPortrait == null)) {
if (this.displaySizeTemp.y > this.displaySizeTemp.x) {
if (this._filterPanelLandscape != null) {
this._first_visible_filter_id = this._filterPanelLandscape.getFirstVisibleFilterId();
removeView(this._filterPanelLandscape);
this._filterPanelLandscape = null;
}
if (this._filterPanelPortrait == null) {
this._filterPanelPortrait = new FilterPanelPortrait(getContext());
addView(this._filterPanelPortrait);
this._filterPanelPortrait.setupOnClickListeners();
}
} else {
if (this._filterPanelPortrait != null) {
this._first_visible_filter_id = this._filterPanelPortrait.getFirstVisibleFilterId();
removeView(this._filterPanelPortrait);
this._filterPanelPortrait = null;
}
if (this._filterPanelLandscape == null) {
this._filterPanelLandscape = new FilterPanelLandscape(getContext());
addView(this._filterPanelLandscape);
this._filterPanelLandscape.setupOnClickListeners();
}
}
}
Rect rect = filterPanelFrame(isLandscape, state, this.rootViewSizeTemp);
if (this._filterPanelLandscape != null) {
this._filterPanelLandscape.layout(rect.left, rect.top, rect.right, rect.bottom);
if (this.lastOrientationWasLandscape != isLandscape || this._setScrollPos) {
this._filterPanelLandscape.setFirstVisibleFilterId(this._first_visible_filter_id);
}
this._setScrollPos = false;
}
if (this._filterPanelPortrait != null) {
this._filterPanelPortrait.layout(rect.left, rect.top, rect.right, rect.bottom);
if (this.lastOrientationWasLandscape != isLandscape || this._setScrollPos) {
this._filterPanelPortrait.setFirstVisibleFilterId(this._first_visible_filter_id);
}
this._setScrollPos = false;
}
if (this._globalToolBar != null) {
int width;
int height;
if (DeviceDefs.isTablet()) {
rect = globalToolBarFrame(isLandscape, state, this.rootViewSizeTemp);
this._globalToolBar.measure(0, 0);
width = this._globalToolBar.getMeasuredWidth();
height = this._globalToolBar.getMeasuredHeight();
this._globalToolBar.layout(((rect.right + rect.left) - width) / 2, ((rect.bottom + rect.top) - height) / 2, ((rect.right + rect.left) + width) / 2, ((rect.bottom + rect.top) + height) / 2);
} else if (this._revertButtonForNoneTablet != null) {
rect = getWorkingAreaRect(isLandscape, state, this.rootViewSizeTemp);
this._revertButtonForNoneTablet.measure(0, 0);
width = this._revertButtonForNoneTablet.getMeasuredWidth();
height = this._revertButtonForNoneTablet.getMeasuredHeight();
int margin = getResources().getDimensionPixelSize(R.dimen.tmp_wa_tool_button_margin);
this._revertButtonForNoneTablet.layout(rect.left + margin, rect.top + margin, (rect.left + width) + margin, (rect.top + height) + margin);
}
}
int editingToolbarHeight = 0;
if (this._editingToolBar != null) {
if (!(this._editingToolBar.getTranslationY() == 0.0f || isRunningAnimation())) {
this._editingToolBar.setTranslationY(0.0f);
}
this._editingToolBar.measure(MeasureSpec.makeMeasureSpec(getWidth(), 1073741824), MeasureSpec.makeMeasureSpec(0, 0));
int editingToolbarWidth = this._editingToolBar.getMeasuredWidth();
editingToolbarHeight = this._editingToolBar.getMeasuredHeight();
int editingToolbarTop = getHeight() - editingToolbarHeight;
this._editingToolBar.layout(0, editingToolbarTop, editingToolbarWidth, editingToolbarTop + editingToolbarHeight);
}
if (this._itemSelectorView != null) {
this._itemSelectorView.measure(MeasureSpec.makeMeasureSpec(getWidth(), 1073741824), MeasureSpec.makeMeasureSpec(getHeight() - editingToolbarHeight, 1073741824));
this._itemSelectorView.layout(0, (getHeight() - editingToolbarHeight) - this._itemSelectorView.getMeasuredHeight(), this._itemSelectorView.getMeasuredWidth(), getHeight() - editingToolbarHeight);
}
if (this.helpOverlay != null) {
this.helpOverlay.layout(0, state == Screen.MAIN ? getActionBarHeight() : 0, getWidth(), getHeight());
}
this.lastOrientationWasLandscape = isLandscape;
}
private boolean isTouchOutItemSelector(MotionEvent event) {
return event.getAction() == 0 && this._itemSelectorView != null && this._itemSelectorView.getVisibility() == 0 && (((int) event.getY()) > this._itemSelectorView.getBottom() || ((int) event.getY()) < this._itemSelectorView.getTop());
}
public boolean dispatchTouchEvent(MotionEvent event) {
Screen state = MainActivity.getMainActivity().getCurrentScreen();
if (state != Screen.MAIN && isTouchOutItemSelector(event)) {
if (this._itemSelectorView != null) {
this._itemSelectorView.setVisible(false, true);
}
return true;
} else if (super.dispatchTouchEvent(event)) {
return true;
} else {
if (DeviceDefs.isTablet() || state != Screen.MAIN) {
return false;
}
boolean imageViewHit = this._workingAreaView.getImageViewScreenRect().contains((int) event.getX(), (int) event.getY());
int action = event.getAction();
if (this._workingAreaView.isComparing()) {
if (imageViewHit && action != 3 && action != 1) {
return false;
}
this._workingAreaView.endCompare();
return true;
} else if (!imageViewHit || action != 0) {
return false;
} else {
this._workingAreaView.beginCompare(MainActivity.getMainActivity().getEditSession().getOriginalScreenImage());
return true;
}
}
}
public View getFilterList() {
return this._filterPanelLandscape != null ? this._filterPanelLandscape : this._filterPanelPortrait;
}
public void showHelpOverlay(int overlayXmlResId) {
HelpOverlayView helpOverlay = new HelpOverlayView(getContext());
helpOverlay.setUp(overlayXmlResId, getWidth(), getHeight());
if (this.helpOverlay != null) {
removeView(this.helpOverlay);
this.helpOverlay = null;
}
this.helpOverlay = helpOverlay;
addView(this.helpOverlay);
helpOverlay.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == 0) {
RootView.this.hideHelpOverlay(true);
}
return true;
}
});
bringToFront();
}
public void hideHelpOverlay(boolean animated) {
if (this.helpOverlay != null) {
if (animated) {
this.helpOverlay.animate().alpha(0.0f).setListener(new AnimatorListener() {
public void onAnimationStart(Animator animator) {
}
public void onAnimationEnd(Animator animator) {
RootView.this.removeView(RootView.this.helpOverlay);
RootView.this.helpOverlay = null;
}
public void onAnimationCancel(Animator animator) {
onAnimationEnd(animator);
}
public void onAnimationRepeat(Animator animator) {
}
});
return;
}
removeView(this.helpOverlay);
this.helpOverlay = null;
}
}
public void closeAllPopovers() {
if (this._itemSelectorView != null) {
this._itemSelectorView.setVisible(false, false);
}
if (this._editingToolBar != null) {
this._editingToolBar.hideUndoPopoverWindow();
this._editingToolBar.resetStyleButtons();
}
}
private int getActionBarHeight() {
return getResources().getDimensionPixelSize(R.dimen.action_bar_height);
}
private void setScreenBackground(Drawable drawable) {
int width = getWidth();
int height = getHeight();
setBackgroundDrawable(drawable);
}
}
|
package org.aksw.autosparql.tbsl.algorithm.search;
import java.util.ArrayList;
import java.util.List;
/*import javax.annotation.Nonnull;*/
import org.dllearner.algorithms.qtl.filters.Filter;
import org.dllearner.common.index.Index;
import org.dllearner.common.index.IndexResultItem;
import org.dllearner.common.index.IndexResultSet;
public class FilteredIndex extends Index
{
/*@Nonnull*/ final Index index;
/*@Nonnull*/ final Filter filter;
public FilteredIndex(/*@Nonnull*/ Index index,/*@Nonnull*/ Filter filter) {this.index=index;this.filter=filter;}
@Override public List<String> getResources(String queryString, int limit, int offset)
{
List<String> resources = index.getResources(queryString, limit,offset);
// in java 8: resources.stream().filter(r -> filter.isRelevantResource(r)).collect(); ?
List<String> filtered = new ArrayList<String>();
for(String r: resources) {if(filter.isRelevantResource(r)) filtered.add(r);}
return filtered;
}
@Override public IndexResultSet getResourcesWithScores(String queryString, int limit, int offset)
{
IndexResultSet result = index.getResourcesWithScores(queryString, limit,offset);
IndexResultSet filtered = new IndexResultSet();
for(IndexResultItem item : result.getItems()) {if(filter.isRelevantResource(item.getUri())) filtered.addItem(item);}
return filtered;
}
}
|
package com.imagsky.common;
import com.imagsky.util.CommonUtil;
public class PropertiesConstants {
public static final String needLogin = "needLogin";
public static final String externalHost = "externalHost";
public static final String staticContextRoot = "staticContextRoot";
public static final String uploadContextRoot = "uploadContextRoot";
public static final String uploadDirectory = "uploadDirectory";
public static final String urlblacklist = "urlblacklist";
public static final String mainSiteGUID = "mainsite";
public static final String smtp = "host_smtp";
public static final String salesAddress = "email_sales";
public static final String searchRowPerPage = "search_rowperpage";
public static final String secure = "secure";
public static final String bulkOrderOn = "bulkOrderOn";
public static final String boboOn = "boboOn";
public static final String auctionOn = "auctionOn";
public static final String paypalFlg = "paypal";
public static final String cashlimit = "cash.request_without_charge";
public static final String home_newshop = "home_newshop"; // on / off : switch to display new shops list in main page
public static final String email_on = "email_on";
public static final String bidFacebookCheckLogin = "bidFacebookCheckLogin";
/*** V81 ***/
public static final String v81_uploadDirectory = "v81_uploadDirectory";
/*** FACEBOOK Properties Constants ***/
public static final String fb_appid = "fb_appid"; // Facebook App ID
public static final String fb_appsecret = "fb_appsecret"; // Facebook App Password
public static final String fb_tokenurl = "fb_tokenurl"; // URL to obtain access token from FB
public static final String fb_graph = "fb_graph"; // FB Graph API
public static final String fb_namespace = "fb_namespace";
/*** RBT Properties Constants ***/
public static final String rbt_metTargetRate = "rbt_metTargetRate"; // Rate to perform rbt after the price already met the target
public static final String rbt_strtCountDown = "rbt_strtCountDown"; // Number of minutes to start the count down logic
public static String get(String key) {
return System.getProperty(key);
}
public static String[] getList(String key) {
return CommonUtil.stringTokenize(System.getProperty(key), ",");
}
}
|
package com.staniul;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MTTMApplication {
public static void main(String[] args) {
SpringApplication.run(MTTMApplication.class, args);
}
}
|
package com.everis;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Diretor d1 = new Diretor("Joao","Anjos",12,"Almeirim Warner",Arrays.asList("Titanic","Homens de negroe"));
System.out.println(d1);
Ator a1 = new Ator("Joao", "Anjos", 12, TipoAtor.MAIN, Arrays.asList(2010,2011));
System.out.println(a1.toString());
Filme f1 = new Filme("Titanic", 2000, 1, d1, Arrays.asList(a1), TipoFilme.CARTOON);
Filme f2 = new Filme("Piquenique", 2011, 10, d1, Arrays.asList(a1), TipoFilme.CARTOON);
Filme f3 = new Filme("Foca", 2010, 5, d1, Arrays.asList(a1), TipoFilme.CARTOON);
Filme f4 = new Filme("Mama", 2010, 6, d1, Arrays.asList(a1), TipoFilme.CARTOON);
System.out.println();
List<Filme> listaFilme = new ArrayList<Filme>(Arrays.asList(f1,f2,f3,f4));
for (Filme film : listaFilme) {
System.out.println(film);
}
System.out.println("------------------");
Collections.sort(listaFilme);
for (Filme film : listaFilme) {
System.out.println(film);
}
Ator a2 = new Ator("Joao", "Anjos", 10, TipoAtor.MAIN, Arrays.asList(2010,2011));
Ator a4 = new Ator("Pedro", "Anjos", 12, TipoAtor.MAIN, Arrays.asList(2010,2011));
Ator a5 = new Ator("Miguel", "Anjos", 9, TipoAtor.MAIN, Arrays.asList(2010,2011));
Ator a6 = new Ator("Joaquim", "Anjos", 11, TipoAtor.MAIN, Arrays.asList(2010,2011));
List<Ator> listaActor = new ArrayList<Ator>(Arrays.asList(a2,a4,a5,a6));
for (Ator actor : listaActor) {
System.out.println(actor);
}
System.out.println("============");
Collections.sort(listaActor);
for (Ator ator : listaActor) {
System.out.println(ator);
}
Pessoa p1 = new Pessoa("Diana", "Nogueira", 14);
Pessoa p2 = new Pessoa("Joao", "Rafael", 20);
Pessoa p3 = new Pessoa("Joao", "Jacob", 22);
List<Pessoa> listaPessoa = new ArrayList<Pessoa>(Arrays.asList(p1,p2,p3));
Collections.sort(listaPessoa);
for (Pessoa pessoa : listaPessoa) {
System.out.println(pessoa);
}
}
}
|
package DecoratorPattern10.exercise.decorator.concreteDecorator;
import DecoratorPattern10.exercise.component.Component;
import DecoratorPattern10.exercise.decorator.Decorator;
/**
* @Author Zeng Zhuo
* @Date 2020/4/30 16:35
* @Describe
*/
public class ModularEncryption extends Decorator {
public ModularEncryption(Component component) {
super(component);
}
@Override
public String encryption(String password) {
return modularEncryption(super.encryption(password));
}
public String modularEncryption(String password){
System.out.println("使用求模加密:"+password);
return "(求模加密:"+password+")";
}
}
|
package com.download.data;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class SaveData {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("http.proxyHost", "10.110.17.6");
System.setProperty("http.proxyPort", "80");
// try {
// String strUrl = "http://data.hud.gov/Housing_Counselor/search?AgencyName=&City=&State=&RowLimit=&Services=&Languages=";
// //String strUrl = "http://data.hud.gov/Housing_Counselor/getServices";
// URL url = new URL(strUrl);
// InputStreamReader isr = new InputStreamReader(url.openStream(), "utf-8");
// BufferedReader br = new BufferedReader(isr);
//
// String strRead = br.readLine();
// //System.out.println(strRead);
//
// GsonBuilder gsonBuilder = new GsonBuilder();
//
// //gsonBuilder.registerTypeAdapter(HUDList.class, new HUDListDeserializer());
// Gson gson = gsonBuilder.create();
//
// Type hudLists = new TypeToken<List<HUDList>>() {}.getType();
// List<HUDList> lists = gson.fromJson(strRead, hudLists);
// System.out.println(lists.get(2).getAdr1());
// loads configuration and mappings
Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
// builds a session factory from the service registry
SessionFactory factory = cfg.buildSessionFactory(serviceRegistry);
Session session = factory.openSession();
Transaction t = session.beginTransaction();
// //create table for very first time
// for (int i = 0; i < lists.size(); i++) {
// session.save(lists.get(i));
// if (i % 20 == 0) {
// session.flush();
// session.clear();
// }
// }
Query query = session.createQuery("from HUDList");
query.setFirstResult(0);
query.setMaxResults(3);
List<HUDList> lists = query.list();
for (HUDList list : lists) {
System.out.println(list.getAgcid());
System.out.println(list.getAdr1());
System.out.println(list.getNme());
System.out.println(list.getServices());
}
System.out.println(lists.get(2).getAdr1());
// for (HUDList1 hudList1 : lists) {
// session.save(hudList1);
// }
t.commit();
session.close();
System.out.println("Success!!");
// } catch (IOException e){
// e.printStackTrace();
// }
}
}
|
package com.manoharacademy.corejava.programs.fundamentals;
public class TemperatureConversion {
//http://www.mathsisfun.com/temperature-conversion.html
public static void main(String[] args) {
/*
Fahrenheit to Celsius: (°F − 32) x 5/9 = °C
Celsius to Fahrenheit: (°C × 9/5) + 32 = °F
*/
double fahrenheitTemperature = 212;
double celsiusTemperature = ((fahrenheitTemperature - 32) * (5.0 / 9));
System.out.printf("%5.2f F = %5.2f C\n", fahrenheitTemperature,celsiusTemperature);
celsiusTemperature = 37;
fahrenheitTemperature = ((celsiusTemperature * 9 / 5) + 32) ;
System.out.printf("%5.2f C = %5.2f F", celsiusTemperature, fahrenheitTemperature);
}
}
|
package com.UdemyJava;
/**
* Created by Mr3dfx on 2/3/2017.
*/
public class Healthy extends Hamburger {
public Healthy(String breadType, String meatType, String name) {
super("Brown Rye", "Turkey", name);
}
@Override
public String name() {
return "Healthy";
}
@Override
public double price() {
return 2.00;
}
}
|
package org.swanix.interviewquestion.linefukoka;
import java.util.ArrayList;
import java.util.List;
public class Nitin_fufoka {
}
class Solution {
public String[] generateParenthesis(int n) {
List<String> output = new ArrayList<>();
fn(output, n, n, "");
return output.toArray(new String[0]);
}
void fn(List<String> arr, int open, int close, String ans) {
if (open == 0 && close == 0) {
arr.add(ans);
return;
}
if (open > 0) {
fn(arr, open - 1, close, ans + '(');
}
if (close > open) {
fn(arr, open, close - 1, ans + ')');
}
}
}
/* class Solution {
public int solution(int[] n) {
if (n.length == 1) {
return n[0];
}
int noToInclude = 0;
int currSum = n[0];
for (int i = 1; i < n.length; i++) {
int sum = n[i] + noToInclude;
noToInclude = currSum;
currSum = Math.max(sum, currSum);
}
return currSum;
}
}*/
/* public String solution(int t, String[] logs) {
List<String> runningProcess = new ArrayList<>();
int value = 0;
for (int i = 0; i < logs.length; i++) {
String[] info = logs[i].split(" ");
if (Integer.parseInt(info[0]) >= t) {
break;
}
if (info[2].equalsIgnoreCase("running")) {
runningProcess.add(info[1]);
value++;
} else {
if (runningProcess.contains(info[1])) {
runningProcess.remove(info[1]);
value--;
}
}
}
if (value == 1) {
return runningProcess.iterator().next();
} else {
return "-1";
}
}*/
/*
class Solution {
int length;
Entry valArray[];
ArrayList<String> res;
Deque<String> deque;
public String[] solution(String[] n) {
length = n.length;
valArray = new Entry[length];
res = new ArrayList<>();
deque = new LinkedList<>();
outer:
for (int i = 0; i < n.length; i++) {
String[] info = n[i].split(" ");
switch (info[0]) {
case "add":
add(info[1], info[2]);
break;
case "get":
get(info[1]);
break;
case "evict":
evict();
break;
case "remove":
remove(info[1],true);
break;
case "exit":
break outer;
}
}
return res.toArray(new String[0]);
}
public void add(String key, String val) {
int bucket = Math.abs(key.hashCode()) % length;
Entry head = valArray[bucket];
if (head == null) {
valArray[bucket] = new Entry(key, val);
} else {
Entry prev = null;
while (head != null) {
if (head.key.equals(key)) {
head.val = val;
return;
}
prev = head;
head = head.next;
}
if (head == null) {
prev.next = new Entry(key, val);
}
}
deque.remove(key);
deque.addFirst(key);
}
public void get(String key) {
int bucket = Math.abs(key.hashCode()) % length;
Entry head = valArray[bucket];
while (head != null) {
if (head.key.equals(key)) {
res.add(head.val);
deque.remove(key);
deque.addFirst(key);
return;
} else {
head = head.next;
}
}
if (head == null) {
res.add("-1");
}
}
public void remove(String key, boolean addToRes) {
int bucket = Math.abs(key.hashCode()) % length;
Entry head = valArray[bucket];
Entry prev = null;
while (head != null) {
if (head.key.equals(key)) {
if(addToRes) {
res.add(head.val);
}
if(prev!=null){
prev.next = head.next;
}
else{
valArray[bucket] = head.next;
}
return;
}
prev = head;
head = head.next;
}
if (head == null) {
if(addToRes) {
res.add("-1");
}
}
}
public void evict() {
String key = deque.removeLast();
remove(key,false);
}
class Entry {
String key;
String val;
Entry next;
Entry(String key, String val) {
this.key = key;
this.val = val;
}
}
}
*/
|
package com.version.SpringOne.Repository;
import com.version.SpringOne.Model.PostObject;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface PostRepo extends MongoRepository<PostObject,String> {
}
|
package com.zantong.mobilecttx.home.adapter;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zantong.mobilecttx.api.CallBack;
import com.zantong.mobilecttx.api.CarApiClient;
import com.zantong.mobilecttx.base.bean.BaseResult;
import com.zantong.mobilecttx.common.Config;
import com.zantong.mobilecttx.common.PublicData;
import com.zantong.mobilecttx.common.activity.BrowserActivity;
import com.zantong.mobilecttx.fahrschule.activity.FahrschuleActivity;
import com.zantong.mobilecttx.home.activity.CustomCordovaActivity;
import com.zantong.mobilecttx.home.bean.BannersBean;
import com.zantong.mobilecttx.huodong.bean.ActivityCarResult;
import com.zantong.mobilecttx.huodong.dto.ActivityCarDTO;
import com.zantong.mobilecttx.user.activity.LoginActivity;
import com.zantong.mobilecttx.utils.ImageOptions;
import com.zantong.mobilecttx.utils.SPUtils;
import com.zantong.mobilecttx.utils.jumptools.Act;
import cn.qqtheme.framework.global.GlobalConfig;
import cn.qqtheme.framework.widght.banner.CBPageAdapter;
/**
* Created by Sai on 15/8/4.
* 网络图片加载例子
*/
public class FavorableBannerImgHolderView implements CBPageAdapter.Holder<BannersBean> {
private ImageView imageView;
private Context mContext;
@Override
public View createView(Context context) {
mContext = context;
//你可以通过layout文件来创建,也可以像我一样用代码创建,不一定是Image,任何控件都可以进行翻页
imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
return imageView;
}
@Override
public void UpdateUI(final Context context, final int position, final BannersBean data) {
ImageLoader.getInstance().displayImage(
data.getUrl(),
imageView,
ImageOptions.getDefaultOptions());
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
webProcessingService(data);
}
});
}
protected void webProcessingService(BannersBean data) {
PublicData.getInstance().webviewUrl = data.getAdvertisementSkipUrl();
PublicData.getInstance().mHashMap.put("htmlUrl", PublicData.getInstance().webviewUrl);
PublicData.getInstance().webviewTitle = "广告";
PublicData.getInstance().isCheckLogin = false;
if (PublicData.getInstance().webviewUrl.contains("discount")
|| PublicData.getInstance().webviewUrl.contains("happysend")) {//保险
Act.getInstance().gotoIntent(mContext, CustomCordovaActivity.class);
} else if (PublicData.getInstance().webviewUrl.contains("localActivity")) {//百日无违章
if (PublicData.getInstance().loginFlag) {
GlobalConfig.getInstance().eventIdByUMeng(1);
getSignStatus();
} else {
Act.getInstance().gotoIntent(mContext, LoginActivity.class);
}
} else if (PublicData.getInstance().webviewUrl.contains("fahrschule")) {//驾校报名
Act.getInstance().lauchIntentToLogin(mContext, FahrschuleActivity.class);
} else {
Act.getInstance().gotoIntent(mContext, BrowserActivity.class);
CarApiClient.commitAdClick(mContext, data.getId(), new CallBack<BaseResult>() {
@Override
public void onSuccess(BaseResult result) {
}
});
}
}
private void getSignStatus() {
ActivityCarDTO activityCarDTO = new ActivityCarDTO();
activityCarDTO.setUsrnum(PublicData.getInstance().userID);
CarApiClient.getActivityCar(mContext, activityCarDTO, new CallBack<ActivityCarResult>() {
@Override
public void onSuccess(ActivityCarResult result) {
if (result.getResponseCode() == 2000 && !TextUtils.isEmpty(result.getData().getPlateNo())) {
SPUtils.getInstance().setSignStatus(true);
SPUtils.getInstance().setSignCarPlate(result.getData().getPlateNo());
PublicData.getInstance().webviewUrl = Config.HUNDRED_PLAN_HOME;
PublicData.getInstance().webviewTitle = "百日无违章";
Act.getInstance().lauchIntentToLogin(mContext, BrowserActivity.class);
} else if (result.getResponseCode() == 4000) {
SPUtils.getInstance().setSignStatus(false);
PublicData.getInstance().webviewUrl = Config.HUNDRED_PLAN_DEADLINE;
PublicData.getInstance().webviewTitle = "百日无违章";
Act.getInstance().lauchIntentToLogin(mContext, BrowserActivity.class);
}
}
@Override
public void onError(String errorCode, String msg) {
super.onError(errorCode, msg);
}
});
}
}
|
package com.git.cloud.iaas.openstack.service;
import java.util.HashMap;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.git.cloud.iaas.enums.ResultEnum;
import com.git.cloud.iaas.openstack.common.Constants;
import com.git.cloud.iaas.openstack.model.OpenstackException;
import com.git.cloud.iaas.openstack.model.OpenstackIdentityModel;
import com.git.cloud.iaas.openstack.model.ProjectRestModel;
import com.git.cloud.iaas.openstack.model.TenantException;
import com.git.cloud.iaas.openstack.model.TokenModel;
import com.git.support.common.MesgFlds;
import com.git.support.common.OSOperation_bak;
import com.git.support.sdo.impl.BodyDO;
import com.git.support.sdo.impl.ParamDO;
import com.git.support.sdo.inf.IDataObject;
public class OpenstackIdentityService2Impl extends OpenstackIdentityServiceAbstractImpl implements OpenstackIdentityService {
public String getToken(OpenstackIdentityModel model) throws Exception {
// TODO Auto-generated method stub
TokenModel tokenModel = new TokenModel();
tokenModel.setOpenstackIp(model.getOpenstackIp());
tokenModel.setDomainName(model.getDomainName());
tokenModel.setFsUserName(Constants.getConstantsParameter(Constants.OPENSTACK_MANAGE_USER));
tokenModel.setFsPassword(Constants.getConstantsParameter(Constants.OPENSTACK_MANAGE_PWD));
tokenModel.setUserDomain(Constants.getConstantsParameter(Constants.OPENSTACK_MANAGE_DOMAIN));
tokenModel.setProjectName(model.getProjectName());
tokenModel.setProjectDomain(Constants.getConstantsParameter(Constants.OPENSTACK_MANAGE_DOMAIN));
return this.getToken(tokenModel);
}
public String getToken(String openstackIp,String domainName,String manegeOneIp) throws Exception {
TokenModel tokenModel = new TokenModel();
tokenModel.setOpenstackIp(openstackIp);
tokenModel.setDomainName(domainName);
tokenModel.setFsUserName(Constants.getConstantsParameter(Constants.OPENSTACK_MANAGE_USER));
tokenModel.setFsPassword(Constants.getConstantsParameter(Constants.OPENSTACK_MANAGE_PWD));
tokenModel.setUserDomain(Constants.getConstantsParameter(Constants.OPENSTACK_MANAGE_DOMAIN));
tokenModel.setProjectName(Constants.getConstantsParameter(Constants.OPENSTACK_MANAGE_PROJECT));
tokenModel.setProjectDomain(Constants.getConstantsParameter(Constants.OPENSTACK_MANAGE_DOMAIN));
return this.getToken(tokenModel);
}
public String getToken(TokenModel tokenModel) throws Exception {
IDataObject reqData = this.getIDataObject(OSOperation_bak.GET_TOKEN + 206,tokenModel.getOpenstackIp(),tokenModel.getDomainName(),"");
ParamDO param = ParamDO.CreateParamDO();
HashMap<String, Object> paramMap = this.createParamDOMap(tokenModel.getDomainName());
param.setContainer(paramMap);
reqData.setDataObject(MesgFlds.PARAM, param);
BodyDO body = this.createBodyDO("");
body.setString("FS_USER_NAME", tokenModel.getFsUserName());
body.setString("FS_PASSWORD", tokenModel.getFsPassword());
body.setString("PROJECT_NAME", tokenModel.getProjectName());
body.setString("USER_DOMAIN", tokenModel.getUserDomain());
body.setString("PROJECT_DOMAIN", tokenModel.getProjectDomain());
reqData.setDataObject(MesgFlds.BODY, body);
String token = "";
IDataObject rspData = this.execute(reqData);
token = this.getExecuteResultData(rspData, "TOKEN");
if(token == null || "".equals(token)) {
throw new OpenstackException(this.getExecuteMessage(rspData));
}
return token;
}
public String createProjectForManageUser(OpenstackIdentityModel model, ProjectRestModel project) throws Exception {
String projectId = "";
String token = this.getToken(model.getOpenstackIp(), model.getDomainName(),model.getManageOneIp());
model.setToken(token);
// 获取管理员DomainId
String domainId = this.getManageDomain(model);
// 获取管理员用户Id
String userId = this.getManageUser(model);
// // 获取管理员角色Id
String roleId = this.getManageRole(model);
// // 创建project
projectId = this.createProject(model,domainId, project.getProjectName());
// // 为project赋权限
String msg = this.putProjectRole(model,projectId, userId, roleId);
if(!"".equals(msg)) {
throw new TenantException(ResultEnum.OPENSTACK_PROJECT_CREATE_ERROR, "为project赋权限失败");
}
return projectId;
}
/**
* 创建project绑定用户
* @param projectName
* @param userId
* @return
* @throws Exception
*/
public String createProjectForUser(OpenstackIdentityModel model,String projectName, String userId) throws Exception {
String projectId = "";
String token = this.getToken(model.getOpenstackIp(), model.getDomainName(),model.getManageOneIp());
model.setToken(token);
try {
// 获取管理员DomainId
String domainId = this.getManageDomain(model);
// 获取管理员用户Id
String manageUserId = this.getManageUser(model);
// 获取管理员角色Id
String roleId = this.getManageRole(model);
// 创建project
projectId = this.createProject(model,domainId, projectName);
// 为管理员project赋权限
String msg = this.putProjectRole(model,projectId, manageUserId, roleId);
if(!"".equals(msg)) {
throw new Exception("为project赋权限失败");
}
// 为project赋权限
msg = this.putProjectRole(model,projectId, userId, roleId);
if(!"".equals(msg)) {
throw new Exception("为用户project赋权限失败");
}
} catch(Exception e) {
throw new Exception(e.getMessage());
}
return projectId;
}
/**
* 删除project
* @param projectId
* @param networkModel
* @return
* @throws Exception
*/
public void deleteProject(OpenstackIdentityModel model) throws Exception {
model.setToken(this.getToken(model));
IDataObject reqData = this.getIDataObject(OSOperation_bak.DELETE_PROJECT + 206,model.getOpenstackIp(),model.getDomainName(),model.getToken());
ParamDO param = ParamDO.CreateParamDO();
HashMap<String, Object> paramMap = this.createParamDOMap(model.getDomainName());
paramMap.put("PROJECT_ID", model.getProjectId());
param.setContainer(paramMap);
reqData.setDataObject(MesgFlds.PARAM, param);
BodyDO body = this.createBodyDO(model.getToken());
body.setString("PROJECT_ID", model.getProjectId());
reqData.setDataObject(MesgFlds.BODY, body);
IDataObject rspData = this.execute(reqData);
if(this.getExecuteResult(rspData) >= 200 && this.getExecuteResult(rspData) < 300) {
this.getExecuteResultData(rspData);
} else {
throw new OpenstackException(this.getExecuteMessage(rspData));
}
}
public String createProject(OpenstackIdentityModel model,String domainId, String projectName) throws Exception {
String projectId = "";
IDataObject reqData = this.getIDataObject(OSOperation_bak.CREATE_PROJECT + 206,model.getOpenstackIp(),model.getDomainName(),model.getToken());
ParamDO param = ParamDO.CreateParamDO();
HashMap<String, Object> paramMap = this.createParamDOMap(model.getDomainName());
param.setContainer(paramMap);
reqData.setDataObject(MesgFlds.PARAM, param);
BodyDO body = this.createBodyDO(model.getToken());
body.setString("PROJECT_NAME", projectName);
body.setString("DOMAIN_ID", domainId);
reqData.setDataObject(MesgFlds.BODY, body);
IDataObject rspData = this.execute(reqData);
if(this.getExecuteResult(rspData) == 201) {
String result = this.getExecuteResultData(rspData);
JSONObject json = JSONObject.parseObject(result);
projectId = json.getJSONObject("project").getString("id");
} else {
throw new OpenstackException(this.getExecuteMessage(rspData));
}
return projectId;
}
public String putProjectRole(OpenstackIdentityModel model,String projectId, String userId, String roleId) throws Exception {
IDataObject reqData = this.getIDataObject(OSOperation_bak.PUT_PROJECT_ROLE + 206,model.getOpenstackIp(),model.getDomainName(),model.getToken());
ParamDO param = ParamDO.CreateParamDO();
HashMap<String, Object> paramMap = this.createParamDOMap(model.getDomainName());
paramMap.put("PROJECT_ID", projectId);
paramMap.put("USER_ID", userId);
paramMap.put("ROLE_ID", roleId);
param.setContainer(paramMap);
reqData.setDataObject(MesgFlds.PARAM, param);
BodyDO body = this.createBodyDO(model.getToken());
body.setString("PROJECT_ID", projectId);
body.setString("USER_ID", userId);
body.setString("ROLE_ID", roleId);
reqData.setDataObject(MesgFlds.BODY, body);
String result = "";
try {
IDataObject rspData = this.execute(reqData);
if(this.getExecuteResult(rspData) != 204) { // 设置成功编码为204
throw new OpenstackException(this.getExecuteMessage(rspData));
}
} catch(Exception e) {
result = e.getMessage();
}
return result;
}
public String getManageDomain(OpenstackIdentityModel model) throws Exception {
String domainId = "";
String domainName = Constants.getConstantsParameter(Constants.OPENSTACK_MANAGE_DOMAIN);
IDataObject reqData = this.getIDataObject(OSOperation_bak.GET_DOMAIN + 206,model.getOpenstackIp(),model.getDomainName(),model.getToken());
ParamDO param = ParamDO.CreateParamDO();
HashMap<String, Object> paramMap = this.createParamDOMap(model.getDomainName());
param.setContainer(paramMap);
reqData.setDataObject(MesgFlds.PARAM, param);
reqData.setDataObject(MesgFlds.BODY, this.createBodyDO(model.getToken()));
IDataObject rspData = this.execute(reqData);
if(this.getExecuteResult(rspData) == 200) {
String result = this.getExecuteResultData(rspData);
JSONObject json = JSONObject.parseObject(result);
JSONArray jsonArr = json.getJSONArray("domains");
String name = "";
for(int i=0 ; i<jsonArr.size() ; i++) {
name = jsonArr.getJSONObject(i).getString("name");
if(name != null && name.equals(domainName)) {
domainId = jsonArr.getJSONObject(i).getString("id");
break;
}
}
if("".equals(domainId)) {
throw new Exception("domain名称["+domainName+"]在服务器["+model.getOpenstackIp()+"]不存在");
}
} else {
throw new OpenstackException(this.getExecuteMessage(rspData));
}
return domainId;
}
public String getManageUser(OpenstackIdentityModel model) throws Exception {
String userId = "";
String userName = Constants.getConstantsParameter(Constants.OPENSTACK_MANAGE_USER);
IDataObject reqData = this.getIDataObject(OSOperation_bak.GET_USER + 206,model.getOpenstackIp(),model.getDomainName(),model.getToken());
ParamDO param = ParamDO.CreateParamDO();
HashMap<String, Object> paramMap = this.createParamDOMap(model.getDomainName());
param.setContainer(paramMap);
reqData.setDataObject(MesgFlds.PARAM, param);
reqData.setDataObject(MesgFlds.BODY, this.createBodyDO(model.getToken()));
IDataObject rspData = this.execute(reqData);
if(this.getExecuteResult(rspData) == 200) {
String result = this.getExecuteResultData(rspData);
JSONObject json = JSONObject.parseObject(result);
JSONArray jsonArr = json.getJSONArray("users");
String name = "";
for(int i=0 ; i<jsonArr.size() ; i++) {
name = jsonArr.getJSONObject(i).getString("name");
if(name != null && name.equals(userName)) {
userId = jsonArr.getJSONObject(i).getString("id");
break;
}
}
if("".equals(userId)) {
throw new Exception("用户名称["+userName+"]在服务器["+model.getOpenstackIp()+"]不存在");
}
} else {
throw new OpenstackException(this.getExecuteMessage(rspData));
}
return userId;
}
public String getManageRole(OpenstackIdentityModel model) throws Exception {
String roleId = "";
String roleName = Constants.getConstantsParameter(Constants.OPENSTACK_MANAGE_ROLE);
IDataObject reqData = this.getIDataObject(OSOperation_bak.GET_ROLE + 206,model.getOpenstackIp(),model.getDomainName(),model.getToken());
ParamDO param = ParamDO.CreateParamDO();
HashMap<String, Object> paramMap = this.createParamDOMap(model.getDomainName());
param.setContainer(paramMap);
reqData.setDataObject(MesgFlds.PARAM, param);
reqData.setDataObject(MesgFlds.BODY, this.createBodyDO(model.getToken()));
IDataObject rspData = this.execute(reqData);
if(this.getExecuteResult(rspData) == 200) {
String result = this.getExecuteResultData(rspData);
JSONObject json = JSONObject.parseObject(result);
JSONArray jsonArr = json.getJSONArray("roles");
String name = "";
for(int i=0 ; i<jsonArr.size() ; i++) {
name = jsonArr.getJSONObject(i).getString("name");
if(name != null && name.equals(roleName)) {
roleId = jsonArr.getJSONObject(i).getString("id");
break;
}
}
if("".equals(roleId)) {
throw new Exception("角色名称["+roleName+"]在服务器["+model.getOpenstackIp()+"]不存在");
}
} else {
throw new OpenstackException(this.getExecuteMessage(rspData));
}
return roleId;
}
/**
* 创建HA stack
* @param projectId
* @param networkModel
* @return
* @throws Exception
*/
public void createHAStack(OpenstackIdentityModel model) throws Exception {
model.setToken(this.getToken(model));
IDataObject reqData = this.getIDataObject(OSOperation_bak.CREATE_HA_STACK + 206,model.getOpenstackIp(),model.getDomainName(),model.getToken());
ParamDO param = ParamDO.CreateParamDO();
HashMap<String, Object> paramMap = this.createParamDOMap(model.getDomainName());
paramMap.put("PROJECT_ID", model.getProjectId());
param.setContainer(paramMap);
reqData.setDataObject(MesgFlds.PARAM, param);
BodyDO body = this.createBodyDO(model.getToken());
body.setString("PROJECT_ID", model.getProjectId());
reqData.setDataObject(MesgFlds.BODY, body);
this.execute(reqData);
}
/**
* 创建用户
* @param domainId
* @param username
* @param password
* @return
* @throws Exception
*/
public String createUser(OpenstackIdentityModel model,String domainId, String username, String password) throws Exception {
model.setToken(this.getToken(model.getOpenstackIp(),model.getDomainName(),model.getManageOneIp()));
String userId = null;
// 发送请求创建用户
IDataObject reqData = this.getIDataObject(OSOperation_bak.CREATE_USER + 206,model.getOpenstackIp(),model.getDomainName(),model.getToken());
ParamDO param = ParamDO.CreateParamDO();
HashMap<String, Object> paramMap = this.createParamDOMap(model.getDomainName());
param.setContainer(paramMap);
reqData.setDataObject(MesgFlds.PARAM, param);
BodyDO body = this.createBodyDO(model.getToken());
body.setString("DOMAIN_ID", domainId);
body.setString("USER_NAME", username);
body.setString("USER_PASSWORD", password);
reqData.setDataObject(MesgFlds.BODY, body);
// 执行
IDataObject rspData = this.execute(reqData);
if(this.getExecuteResult(rspData) == 201) {
String result = this.getExecuteResultData(rspData);
JSONObject json = JSONObject.parseObject(result);
JSONObject userObj = json.getJSONObject("user");
String id = userObj.getString("id");
userId = id;
}
else {
throw new OpenstackException(this.getExecuteMessage(rspData));
}
return userId;
}
/**
* 删除用户
* @param userId
* @throws Exception
*/
public void deleteUser(OpenstackIdentityModel model,String userId) throws Exception {
model.setToken(this.getToken(model.getOpenstackIp(),model.getDomainName(),model.getManageOneIp()));
IDataObject reqData = this.getIDataObject(OSOperation_bak.DELETE_USER + 206,model.getOpenstackIp(),model.getDomainName(),model.getToken());
ParamDO param = ParamDO.CreateParamDO();
HashMap<String, Object> paramMap = this.createParamDOMap(model.getDomainName());
paramMap.put("USER_ID", userId);
param.setContainer(paramMap);
reqData.setDataObject(MesgFlds.PARAM, param);
BodyDO body = this.createBodyDO(model.getToken());
body.setString("USER_ID", userId);
reqData.setDataObject(MesgFlds.BODY, body);
IDataObject rspData = this.execute(reqData);
if (this.getExecuteResult(rspData) >= 200 && this.getExecuteResult(rspData) < 300) {
this.getExecuteResultData(rspData);
} else {
throw new OpenstackException(this.getExecuteMessage(rspData));
}
}
public String getManageProject(OpenstackIdentityModel model) throws Exception {
model.setToken(this.getToken(model.getOpenstackIp(),model.getDomainName(),model.getManageOneIp()));
String projectId = "";
String projectName = Constants.getConstantsParameter(Constants.OPENSTACK_MANAGE_PROJECT);
IDataObject reqData = this.getIDataObject(OSOperation_bak.GET_PROJECT + 206,model.getOpenstackIp(),model.getDomainName(),model.getToken());
ParamDO param = ParamDO.CreateParamDO();
HashMap<String, Object> paramMap = this.createParamDOMap(model.getDomainName());
param.setContainer(paramMap);
reqData.setDataObject(MesgFlds.PARAM, param);
reqData.setDataObject(MesgFlds.BODY, this.createBodyDO(model.getToken()));
IDataObject rspData = this.execute(reqData);
if(this.getExecuteResult(rspData) == 200) {
String result = this.getExecuteResultData(rspData);
JSONObject json = JSONObject.parseObject(result);
JSONArray jsonArr = json.getJSONArray("projects");
String name = "";
for(int i=0 ; i<jsonArr.size() ; i++) {
name = jsonArr.getJSONObject(i).getString("name");
if(name != null && name.equals(projectName)) {
projectId = jsonArr.getJSONObject(i).getString("id");
break;
}
}
if("".equals(projectId)) {
throw new Exception("project名称["+projectName+"]在服务器["+model.getOpenstackIp()+"]不存在");
}
} else {
throw new OpenstackException(this.getExecuteMessage(rspData));
}
return projectId;
}
@Override
public String getRegion(OpenstackIdentityModel model) throws Exception {
// TODO Auto-generated method stub
//使用6.3
return null;
}
@Override
public JSONObject getTokenForFlavor(String manegeOneIp) throws Exception {
// TODO Auto-generated method stub
//使用6.3
return null;
}
}
|
package com.github.gaoyangthu.esanalysis.hbase.bean;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
* Author: gaoyangthu
* Date: 14-3-13
* Time: 下午7:09
*/
public class UserIndex implements Serializable {
private String id;
private String bdUserUuid;
private Long timestamp;
public UserIndex() {
}
public UserIndex(String id, String bdUserUuid) {
this.id = id;
this.bdUserUuid = bdUserUuid;
}
public UserIndex(String id, String bdUserUuid, Long timestamp) {
this.id = id;
this.bdUserUuid = bdUserUuid;
this.timestamp = timestamp;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBdUserUuid() {
return bdUserUuid;
}
public void setBdUserUuid(String bdUserUuid) {
this.bdUserUuid = bdUserUuid;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("UserIndex{");
sb.append("id='").append(id).append('\'');
sb.append(", bdUserUuid='").append(bdUserUuid).append('\'');
sb.append(", timestamp=").append(timestamp);
sb.append('}');
return sb.toString();
}
}
|
package referencetype.practice;
public class StringExample {
public static void main(String[] args) {
String str1;
str1 = "초코 오레오";
String str2 = " 맥플러리";
System.out.println(str1 + str2);
String str3 = new String("초코 오레오");
System.out.println(str3);
System.out.println("==============");
System.out.println(str1.equals(str3));
System.out.println(str1.hashCode());
System.out.println(str3.hashCode());
System.out.println(System.identityHashCode(str1));
System.out.println(System.identityHashCode(str3));
}
}
|
package com.factory.factoryinsertdetails;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FactoryInsertDetailsApplication {
public static void main(String[] args) {
SpringApplication.run(FactoryInsertDetailsApplication.class, args);
}
}
|
package App.Utility;
import App.Client.Client;
import App.Model.Note;
import App.Model.OnlineNote;
import org.eclipse.egit.github.core.Gist;
import org.eclipse.egit.github.core.GistFile;
import org.eclipse.egit.github.core.service.GistService;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
/**
* The type Gist util.
*/
public class GistUtil{
/**
* Fetch gist by id.
*
* @param gistId the gist id
* @param client the client
* @throws IOException the io exception
*/
public static void fetchGistById(String gistId, Client client) throws IOException{
GistService gistService = new GistService();
gistService.getClient().setCredentials(client.getCredential().getUser(), client.getCredential().getPassword());
Gist gist = gistService.getGist(gistId);
Note newNote = new OnlineNote(gist);
client.getNoteMap().put(newNote.getUrl(), newNote);
}
/**
* Fetch gist by user.
*
* @param client the client
* @throws IOException the io exception
*/
public static void fetchGistByUser(Client client)throws IOException{
GistService gistService = new GistService();
gistService.getClient().setCredentials(client.getCredential().getUser(), client.getCredential().getPassword());
List<Gist> gists = gistService.getGists(client.getCredential().getUser());
for(Gist gist : gists){
Note newNote = new OnlineNote(gist);
client.getNoteMap().put(newNote.getUrl(), newNote);
}
}
/**
* Create new gist.
*
* @param client the client
* @param fileName the file name
* @param content the content
* @return the gist
* @throws IOException the io exception
*/
public static Gist createNewGist(Client client, String fileName, String content)throws IOException{
GistService gistService = new GistService();
gistService.getClient().setCredentials(client.getCredential().getUser(), client.getCredential().getPassword());
Gist localGist = new Gist();
GistFile localGistFile = new GistFile();
localGistFile.setContent(content);
localGistFile.setFilename(fileName);
localGist.setPublic(false);
localGist.setDescription("Created By Miki Cloud Note");
localGist.setFiles(Collections.singletonMap(fileName, localGistFile));
return gistService.createGist(localGist);
}
/**
* Update gist.
*
* @param client the client
* @param fileName the file name
* @param content the content
* @param gistId the gist id
* @return the gist
* @throws IOException the io exception
*/
public static Gist updateGist(Client client, String fileName, String content, String gistId)throws IOException{
GistService gistService = new GistService();
gistService.getClient().setCredentials(client.getCredential().getUser(), client.getCredential().getPassword());
Gist localGist = new Gist();
GistFile localGistFile = new GistFile();
localGistFile.setContent(content);
localGistFile.setFilename(fileName);
localGist.setPublic(false);
localGist.setId(gistId);
localGist.setDescription("Created By Miki Cloud Note");
localGist.setFiles(Collections.singletonMap(fileName, localGistFile));
return gistService.updateGist(localGist);
}
/**
* Get file name string by gist.
*
* @param gist the gist
* @return the string
*/
public static String getFileNameByGist(Gist gist){
GistFile gistFile = (GistFile)gist.getFiles().values().toArray()[0];
return gistFile.getFilename();
}
/**
* Get file raw url by gist string.
*
* @param gist the gist
* @return the string
*/
public static String getFileRawUrlByGist(Gist gist){
GistFile gistFile = (GistFile)gist.getFiles().values().toArray()[0];
return gistFile.getRawUrl();
}
}
|
package com.test;
import java.util.HashSet;
import java.util.Set;
import com.test.base.Solution;
public class SolutionB implements Solution
{
@Override
public int robotSim(int[] commands, int[][] obstacles)
{
int l1 = obstacles.length;
Set<Integer> obstacleSet = new HashSet<>();
for (int[] obs : obstacles)
{
obstacleSet.add((obs[0] << 16) + obs[1]);
}
int dir = 0, maxLen = Integer.MIN_VALUE;
int[] curPos = {0, 0};
for (Integer command : commands)
{
if (command < 0)
dir = updateCurDir(dir, command);
else
{
curPos = updateCurPos(obstacleSet, curPos, dir, command);
maxLen = Math.max(maxLen, (int)Math.pow(curPos[0], 2) + (int)Math.pow(curPos[1], 2));
}
}
return maxLen;
}
private int[] updateCurPos(Set<Integer> obstacleSet, int[] curPos, int dir, int command)
{
int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int[] next = new int[2];
for (int i = 0; i < command; i++)
{
next[0] = curPos[0] + dirs[dir][0];
next[1] = curPos[1] + dirs[dir][1];
if (obstacleSet.contains((next[0] << 16) + next[1]))
{
break;
}
curPos[0] = next[0];
curPos[1] = next[1];
}
return curPos;
}
private int updateCurDir(int dir, int command)
{
if (command == -1)
{
dir = (dir + 1) % 4;
}
else if (command == -2)
{
dir = (dir + 3) % 4;
}
return dir;
}
}
|
package global.dao;
import global.model.Classroom;
import global.model.Department;
import global.model.Level;
import global.model.View_classroom;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class Classroomaccess {
/**
* @author czy
* @param o_id
* :科室编号
* @return “View_classroom”类的数组列表
* @throws SQLException
*
*/
public static ArrayList<View_classroom> getView_classroom(String condition) {
// 生成查找“View_classroom”表的select查询语句
String sql = "SELECT * FROM view_classroom";
// 如果传入的条件不为空,则SQL语句添加查找条件为根据条件查找“View_classroom”视图数据
if (!(condition == null || condition.equals(""))) {
sql += " WHERE " + condition;
}
// 初始化“View_classroom”类的数组列表对象
ArrayList<View_classroom> View_classroomlist = new ArrayList<View_classroom>();
// 取得数据库的连接
Connection con = null;
ResultSet rs = null;
try {
con = Databaseconnection.getconnection();
// 如果数据库的连接为空,则返回空
if (con == null)
return null;
// 生成数据库声明对象
Statement st = con.createStatement();
// 声明对象执行SQL语句,返回满足条件的结果集
rs = st.executeQuery(sql);
// 如果结果集有数据
while (rs.next()) {
// 取出结果集对应字段数据
int b_id = rs.getInt("b_id");
String b_name = rs.getString("b_name");
String b_alias = rs.getString("b_alias");
String b_address = rs.getString("b_address");
int cr_id = rs.getInt("cr_id");
String cr_name = rs.getString("cr_name");
int ct_id = rs.getInt("ct_id");
String ct_name = rs.getString("ct_name");
int seating = rs.getInt("seating");
String d_id = rs.getString("d_id");
String d_name = rs.getString("d_name");
String sl_name = rs.getString("sl_name");
// 根据结果集的数据生成“View_classroom”类对象
View_classroom m = new View_classroom(d_id, d_name, cr_id,
cr_name, sl_name, seating, ct_id, ct_name, b_id,
b_name, b_alias, b_address);
// 将“View_classroom”类对象添加到“View_classroom”类的数组列表对象中
View_classroomlist.add(m);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
rs.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 返回“View_teacher”类的数组列表对象
return View_classroomlist;
}
public static ArrayList<Department> getDepartment(String d_id) {
// 生成查找“Department”表的select查询语句
String sql = "SELECT * FROM department";
// 如果传入的部门编号不为空,则SQL语句添加查找条件为根据部门编号查找“Department”视图数据
if (!(d_id == null || d_id.equals(""))) {
sql += " WHERE d_id='" + d_id + "'";
}
// 初始化“Department”类的数组列表对象
ArrayList<Department> departmentlist = new ArrayList<Department>();
// 取得数据库的连接
Connection con = null;
ResultSet rs = null;
try {
con = Databaseconnection.getconnection();
// 如果数据库的连接为空,则返回空
if (con == null)
return null;
// 生成数据库声明对象
Statement st = con.createStatement();
// 声明对象执行SQL语句,返回满足条件的结果集
rs = st.executeQuery(sql);
// 如果结果集有数据
while (rs.next()) {
// 取出结果集对应字段数据
d_id = rs.getString("d_id");
String d_name = rs.getString("d_name");
// 根据结果集的数据生成“Department”类对象
Department dm = new Department(d_id, d_name);
// 将“Department”类对象添加到“Department”类的数组列表对象中
departmentlist.add(dm);
}
// 返回“Department”类的数组列表对象
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
rs.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return departmentlist;
}
public static ArrayList<Classroom> getClassroom(int cr_id) {
// 生成查找“Level”表的select查询语句
String sql = "SELECT * FROM classroom";
// 如果传入的科室编号不为空,则SQL语句添加查找条件为根据科室编号查找“Level”视图数据
if (!(cr_id == 0)) {
sql += " WHERE cr_id='" + cr_id + "'";
}
// 初始化“Major”类的数组列表对象
ArrayList<Classroom> levellist = new ArrayList<Classroom>();
// 取得数据库的连接
Connection con = null;
ResultSet rs = null;
try {
con = Databaseconnection.getconnection();
// 如果数据库的连接为空,则返回空
if (con == null)
return null;
// 生成数据库声明对象
Statement st = con.createStatement();
// 声明对象执行SQL语句,返回满足条件的结果集
rs = st.executeQuery(sql);
// 如果结果集有数据
while (rs.next()) {
// 取出结果集对应字段数据
cr_id = rs.getInt("cr_id");
String d_id = rs.getString("d_id");
String cr_name = rs.getString("cr_name");
int ct_id = rs.getInt("ct_id");
int cr_seating = rs.getInt("cr_seating");
int b_id = rs.getInt("b_id");
// 根据结果集的数据生成“Level”类对象
Classroom m = new Classroom(cr_id, d_id,cr_name,ct_id,cr_seating,b_id);
// 将“Level”类对象添加到“Level”类的数组列表对象中
levellist.add(m);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
rs.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 返回“levellist”类的数组列表对象
return levellist;
}
}
|
package com.stk123.web.core.config;
import java.io.FileNotFoundException;
import java.net.URL;
import org.apache.commons.digester.Digester;
import org.springframework.util.ResourceUtils;
public class ConfigHelper {
public static void main(String[] args) throws Exception {
MvcConfig mvc = ConfigHelper.parseMvcConfig(MvcConfig.class,"mvc-config.xml");
System.out.println(mvc.getPrefix());
System.out.println(mvc.getForwards().size());
System.out.println(mvc.getForwards().get("404"));
System.out.println(mvc.getActions().size());
System.out.println(mvc.getActions().get("search").getType());
System.out.println(mvc.getActions().get("test").getForward());
}
public static URL getResource(Class clazz, String resName) throws FileNotFoundException {
return ResourceUtils.getURL("classpath:"+resName);
}
public static MvcConfig parseMvcConfig(Class clazz, String resName) throws Exception {
URL url = ConfigHelper.getResource(clazz, resName);
Digester digester = new Digester();
digester.setValidating(false);
digester.addObjectCreate("config", MvcConfig.class);
digester.addObjectCreate("config/forwards/forward", ForwardConfig.class);
digester.addObjectCreate("config/actions/action", ActionConfig.class);
digester.addObjectCreate("config/actions/action/forward", ForwardConfig.class);
digester.addSetProperties("config/forwards/forward");
digester.addSetProperties("config/actions/action");
digester.addSetProperties("config/actions/action/forward");
digester.addSetNext("config/forwards/forward", "addForward");
digester.addSetNext("config/actions/action", "addActionConfig");
digester.addSetNext("config/actions/action/forward", "addForwardConfig");
return (MvcConfig)digester.parse(url.openStream());
}
}
|
package com.xwolf.eop.erp.entity;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Data
public class Jobs {
private Integer jid;
private String jcode;
@NotBlank
@Length(max=60)
private String jname;
@Size(max=150)
private String descr;
@NotNull
private Byte state;
}
|
package com.lorenagallas.fruteriabit.database;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import com.lorenagallas.fruteriabit.daos.FrutaDao;
import com.lorenagallas.fruteriabit.entidades.Fruta;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//anotacion indicando q es una base de datos.
//le digo cuales son mis entidades
//le digo q version es
@Database(entities = {Fruta.class}, version =2)
//abstracta, no puedo crear instancias de esta clase
public abstract class AppDatabase extends RoomDatabase {
public abstract FrutaDao frutaDao(); // aca agregaria todos los daos que yo tenga
//uso de singletone
private static volatile AppDatabase instance; //volatile= va a ir a leer el atributo a la memoria principal siempre
//permite ejecutar en hilos
public static final ExecutorService databaseWriteExecutor = Executors.newFixedThreadPool(4);
public static AppDatabase getInstance( final Context context) {
if(instance == null){
instance = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "fruteria")
.fallbackToDestructiveMigration() //limpiar base de datos cuando se migra de version
.build();
}
return instance;
}
}
|
public class ToeplitzMatrix {
/**
* Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: True
Explanation:
1234
5123
9512
In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]"
*/
public boolean isToeplitzMatrix(int[][] matrix) {
int s=0;
for(int i=0; i<matrix.length; i++){
for(int n=0; n<matrix[i].length; n++){
s= matrix[i][n];
if(i!= matrix.length-1&&n!=matrix[i].length-1){
if(matrix[i+1][n+1]!=s) return false;
}
}
}
return true;
}
/**
* Everytime the only thing to check is matrix[i][n] ?= matrix[i+1][n+1]
*/
}
|
package Model;
// Generated 05/08/2014 21:14:09 by Hibernate Tools 3.6.0
/**
* Cliente generated by hbm2java
*/
public class Cliente implements Comparable<Cliente>, java.io.Serializable{
private Integer idCliente;
private String nome;
private String endereco;
private Integer numero;
private String bairro;
private String complemento;
private String cidade;
private String telComercial;
private String telResidencial;
private String telCelular;
private String email;
private char status;
public Cliente() {
}
public Cliente(int idCliente, String nome, String endereco, Integer numero, String bairro, String complemento, String cidade, String telComercial, String telResidencial, String telCelular, String email, char status) {
this.idCliente = idCliente;
this.nome = nome;
this.endereco = endereco;
this.numero = numero;
this.bairro = bairro;
this.complemento = complemento;
this.cidade = cidade;
this.telComercial = telComercial;
this.telResidencial = telResidencial;
this.telCelular = telCelular;
this.email = email;
this.status = status;
}
public Cliente(String nome, String endereco, Integer numero, String bairro, String complemento, String cidade, String telComercial, String telResidencial, String telCelular, String email, char status) {
this.nome = nome;
this.endereco = endereco;
this.numero = numero;
this.bairro = bairro;
this.complemento = complemento;
this.cidade = cidade;
this.telComercial = telComercial;
this.telResidencial = telResidencial;
this.telCelular = telCelular;
this.email = email;
this.status = status;
}
public Integer getIdCliente() {
return this.idCliente;
}
public void setIdCliente(Integer idCliente) {
this.idCliente = idCliente;
}
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEndereco() {
return this.endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public Integer getNumero() {
return this.numero;
}
public void setNumero(Integer numero) {
this.numero = numero;
}
public String getBairro() {
return this.bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getComplemento() {
return this.complemento;
}
public void setComplemento(String complemento) {
this.complemento = complemento;
}
public String getCidade() {
return this.cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public String getTelComercial() {
return this.telComercial;
}
public void setTelComercial(String telComercial) {
this.telComercial = telComercial;
}
public String getTelResidencial() {
return this.telResidencial;
}
public void setTelResidencial(String telResidencial) {
this.telResidencial = telResidencial;
}
public String getTelCelular() {
return this.telCelular;
}
public void setTelCelular(String telCelular) {
this.telCelular = telCelular;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public char getStatus() {
return this.status;
}
public void setStatus(char status) {
this.status = status;
}
@Override
public int compareTo(Cliente o) {
return this.nome.compareTo(o.getNome());
}
}
|
package com.lenovohit.hcp.base.manager.impl;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.transaction.Transactional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.lenovohit.core.manager.GenericManager;
import com.lenovohit.core.utils.BeanUtils;
import com.lenovohit.core.utils.StringUtils;
import com.lenovohit.hcp.appointment.model.RegInfo;
import com.lenovohit.hcp.base.manager.HisBizChargeManager;
import com.lenovohit.hcp.base.model.HcpUser;
import com.lenovohit.hcp.finance.model.InvoiceInfo;
import com.lenovohit.hcp.finance.model.InvoiceInfoDetail;
import com.lenovohit.hcp.finance.model.InvoiceManage;
import com.lenovohit.hcp.finance.model.OutpatientChargeDetail;
import com.lenovohit.hcp.finance.model.PayWay;
@Transactional
public abstract class AbstractHisBizChargeManagerImpl implements HisBizChargeManager {
@Autowired
protected GenericManager<OutpatientChargeDetail, String> outpatientChargeDetailManager;
@Autowired
protected GenericManager<InvoiceManage, String> invoiceManageManager;
@Autowired
protected GenericManager<InvoiceInfo, String> invoiceInfoManager;
@Autowired
protected GenericManager<RegInfo, String> regInfoManager;
@Autowired
protected GenericManager<PayWay, String> payWayManager;
@Autowired
protected GenericManager<HcpUser, String> hcpUserManager;
@Autowired
protected GenericManager<InvoiceInfoDetail, String> invoiceInfoDetailManager;
@Autowired
private RedisSequenceManager redisSequenceManager;
private static Log log = LogFactory.getLog(AbstractHisBizChargeManagerImpl.class);
protected static final String CANCLELED = "1";
protected static final String UN_CANCLEL = "0";
private Object lock = new Object();
@Override
public void bizAfterPaySuccess(String operator, BigDecimal amt, String orderId, List<String> chargeDetailIds,
Map<String, BigDecimal> payWays) {
log.info("支付成功——回调具体业务逻辑开始");
HcpUser user = getUser(operator);
List<OutpatientChargeDetail> chargeDetails = getChargeDetailInfo(chargeDetailIds);// 不校验是否为空,调用收费会校验
RegInfo info = regInfoManager.get(chargeDetails.get(0).getRegId());
synchronized (lock) {
String invoiceNo = getNewAndUpdateInvoiceNo(chargeDetails.get(0).getHosId(), operator);
log.info("发票号为:" + invoiceNo);
buildAndSaveInvoiceInfo(invoiceNo, user, amt, orderId, info.getPayType(), chargeDetails);
log.info("支付成功——添加保存发票信息表成功");
buildAndSaveInvoiceInfoDetail(invoiceNo, chargeDetails);
log.info("支付成功——添加保存发票信息分类表表成功");
buildAndSavePayWay(invoiceNo, orderId, payWays, chargeDetails.get(0));
log.info("支付成功——添加保存支付方式表成功");
updatePaySuccessInfo(user, amt, orderId, invoiceNo, info, chargeDetails);
log.info("支付成功——修改其他相关信息成功");
}
log.info("支付成功——回调具体业务逻辑结束");
}
@Override
public void bizAfterPayFailed(String operator, BigDecimal amt, String orderId, List<String> chargeDetailIds) {
log.info("支付失败——回调具体业务逻辑开始");
doBizAfterPayFailed(operator, amt, orderId, chargeDetailIds);
log.info("支付失败——回调具体业务逻辑结束");
}
@Override
public void bizAfterRefundSuccess(String hosId, String invoiceNo, HcpUser operator) {
if (StringUtils.isBlank(hosId) || StringUtils.isBlank(invoiceNo))
throw new RuntimeException("医院id以及发票号不能为空");
String payId = redisSequenceManager.get("OC_PAYWAY", "PAY_ID");
Date date = new Date();
log.info("退款成功——回调具体业务逻辑开始");
InvoiceInfo info = refundUpdateInvoiceInfo(hosId, invoiceNo, operator, payId, date);
log.info("退款成功——更新发票信息表成功");
refundUpdateChargeDetails(info, operator, date);
log.info("退款成功——更新收费明细表成功");
refundUpdateInvoiceInfoDetails(info, operator, date);
log.info("退款成功——更新发票分类明细表成功");
refundUpdatePayWays(info, operator, date);
log.info("退款成功——更新支付方式表成功");
refundUpdateOtherInfos(info);
log.info("退款成功——更新其他业务逻辑成功");
log.info("退款成功——回调具体业务逻辑结束");
}
/**
* 退款成功执行其他更新信息,比如挂号修改挂号表
* @param hosId
* @param invoiceNo
*/
protected abstract void refundUpdateOtherInfos(InvoiceInfo info);
/**
* 支付失败执行的逻辑
* @param operator
* @param amt
* @param orderId
* @param chargeDetailIds
*/
protected abstract void doBizAfterPayFailed(String operator, BigDecimal amt, String orderId,
List<String> chargeDetailIds);
/**
* 具体实现类根据自己的业务逻辑处理自己的相关信息
* @param operator
* @param amt
* @param orderId 订单号(即pay_id)
* @param invoiceNo
* @param info
* @param details
*/
protected abstract void updatePaySuccessOtherInfo(HcpUser operator, BigDecimal amt, String orderId,
String invoiceNo, RegInfo regInfo, List<OutpatientChargeDetail> details);
/**
* 发票来源,由具体的实现类负责,比如(挂号、收费。现在只有这两种)
* @return
*/
protected abstract String getInvoiceSource();
/**
* 发票类型,便于查询当前操作员该类型发票使用(挂号发票、门诊发票、住院发票等,具体参考数据字典,看自己对应的是哪种发票)
* @return
*/
protected abstract String getInvoiceType();
/**
* 获取收费明细,由具体的实现类负责
* (根据调用收银台传送的数据获取对应的收费明细,比如挂号传的可能为reg_id(就诊流水),门诊可能为recipe_id(处方id)
* 推荐最好为32位uuid,但是如果数据太多其他实现也可以,不硬性规定,但是要对应收银台传入的数据对应,否则导致线上数据错误)
* @param chargeDetailIds
* @return 查询后的收费明细记录
*/
protected abstract List<OutpatientChargeDetail> getChargeDetailInfo(List<String> chargeDetailIds);
protected final void updatePaySuccessInfo(HcpUser operator, BigDecimal amt, String orderId, String invoiceNo,
RegInfo info, List<OutpatientChargeDetail> details) {
updatePaySuccessChargeDetails(invoiceNo, details,operator);
updatePaySuccessOtherInfo(operator, amt, orderId, invoiceNo, info, details);
}
protected final String getNewAndUpdateInvoiceNo(String hosId, String operator) {
String hql = "from InvoiceManage where hosId = ? and invoiceType = ? and getOper like ? and invoiceState = ?";
List<InvoiceManage> invoiceManage = (List<InvoiceManage>) invoiceManageManager.find(hql, hosId,
getInvoiceType(), operator, InvoiceManage.INVOICE_STATE_USE);
if (invoiceManage.size() != 1)// 此处校验以防万一,一般不会出现,因为在创建订单会校验一次。
throw new RuntimeException("没有可用的发票号,请校验");
InvoiceManage invoice = invoiceManage.get(0);
if (invoice.getInvoiceUse().compareTo(invoice.getInvoiceEnd()) > 0)
throw new RuntimeException("发票号用完请校验");
BigInteger invoiceNo = invoice.getInvoiceUse();
BigInteger newInvoiceNo = invoiceNo.add(new BigInteger("1"));
invoice.setInvoiceUse(newInvoiceNo);
invoiceManageManager.save(invoice);
return invoiceNo.toString();
}
private void updatePaySuccessChargeDetails(String invoiceNo, List<OutpatientChargeDetail> details,HcpUser user) {
for (OutpatientChargeDetail o : details) {
if(o.getOrder()!= null && o.getOrder().getDispenseState().equals("1")){
o.setApplyState(OutpatientChargeDetail.APPLY_STATE_MEDICINED);
}
else{
o.setApplyState(OutpatientChargeDetail.APPLY_STATE_PAY_UNMEDICINE);
}
o.setChargeTime(new Date());
o.setInvoiceNo(invoiceNo);
o.setChargeOper(user);
//o.setDrugDept(user.getLoginDepartment());//默认当前科室
}
outpatientChargeDetailManager.batchSave(details);
}
private void buildAndSavePayWay(String invoiceNo, String orderId, Map<String, BigDecimal> payWays,
OutpatientChargeDetail detail) {
List<PayWay> payWayList = new ArrayList<>();
int i = 1;
for (Map.Entry<String, BigDecimal> entry : payWays.entrySet()) {
PayWay payWay = new PayWay();
payWay.setCreateTime(detail.getCreateTime());
payWay.setPayCost(entry.getValue());
payWay.setInvoiceNo(invoiceNo);
payWay.setPayWay(entry.getKey());// TODO 支付方式转换?
payWay.setPlusMinus(1);
payWay.setPayId(orderId);
payWay.setCreateTime(detail.getCreateTime());
payWay.setCancelFlag(UN_CANCLEL);
payWay.setPayNum(String.valueOf(i++));// paynum,同一个payid的支付序列号,由1递增
payWay.setRegId(detail.getRegId());
payWay.setPatientId(detail.getPatient().getId());
payWay.setHosId(detail.getHosId());
payWayList.add(payWay);
}
payWayManager.batchSave(payWayList);
}
private void buildAndSaveInvoiceInfoDetail(String invoiceNo, List<OutpatientChargeDetail> chargeDetails) {
// 发票明细为根据feecode汇总记录金额,所有需要计算所有的收费明细中的feecode(有重复),汇总按每个feecode计算的总金额来插入
List<InvoiceInfoDetail> details = new ArrayList<>();
Map<String, BigDecimal> feeCodeAmt = countAmtByFeeCode(chargeDetails);
OutpatientChargeDetail o = chargeDetails.get(0);
for (Map.Entry<String, BigDecimal> entry : feeCodeAmt.entrySet()) {
InvoiceInfoDetail invoiceInfoDetail = new InvoiceInfoDetail();
invoiceInfoDetail.setPlusMinus(1);
invoiceInfoDetail.setFeeCode(entry.getKey());
invoiceInfoDetail.setHosId(o.getHosId());
invoiceInfoDetail.setCancelFlag(UN_CANCLEL);
invoiceInfoDetail.setRecipeId("");
invoiceInfoDetail.setRegId(o.getRegId());
invoiceInfoDetail.setRecipeDept(o.getRecipeDept());
invoiceInfoDetail.setExeDept(o.getExeDept());
invoiceInfoDetail.setTotCost(entry.getValue());
invoiceInfoDetail.setInvoiceNo(invoiceNo);
details.add(invoiceInfoDetail);
}
invoiceInfoDetailManager.batchSave(details);
}
private Map<String, BigDecimal> countAmtByFeeCode(List<OutpatientChargeDetail> chargeDetails) {
Map<String, BigDecimal> result = new HashMap<>();
for (OutpatientChargeDetail o : chargeDetails) {
BigDecimal bigDecimal = result.get(o.getFeeCode());
if (StringUtils.isBlank(bigDecimal)) {
result.put(o.getFeeCode(), o.getTotCost());
} else {
BigDecimal pre = result.get(o.getFeeCode());
result.put(o.getFeeCode(), pre.add(o.getTotCost()));
}
}
return result;
}
private void buildAndSaveInvoiceInfo(String invoiceNo, HcpUser operator, BigDecimal amt, String orderId,
String payType, List<OutpatientChargeDetail> details) {
InvoiceInfo invoiceInfo = new InvoiceInfo();
invoiceInfo.setPayType(payType);
invoiceInfo.setPlusMinus(new Integer(1));
invoiceInfo.setInvoiceNo(invoiceNo);
invoiceInfo.setTotCost(amt);
invoiceInfo.setFeeType(details.get(0).getFeeType());
invoiceInfo.setPayType(details.get(0).getFeeType());
invoiceInfo.setRegId(details.get(0).getRegId());
invoiceInfo.setInvoiceOperName(operator != null ? operator.getName() : "");
invoiceInfo.setCancelOperName("");
invoiceInfo.setPayId(orderId);
invoiceInfo.setPrintState(InvoiceInfo.INVOICE_UNPRINT);
invoiceInfo.setInvoiceOper(operator != null ? operator.getId() : "");
invoiceInfo.setRebateType(details.get(0).getRebateType());
invoiceInfo.setIsbalance(InvoiceInfo.UN_BALANCE);
invoiceInfo.setInvoiceTime(details.get(0).getCreateTime());
invoiceInfo.setInvoiceSource(getInvoiceSource());
invoiceInfo.setPatientInfo(details.get(0).getPatient());
invoiceInfo.setHosId(details.get(0).getHosId());
invoiceInfo.setInvoiceType(getInvoiceType());
BigDecimal pubCost = new BigDecimal(0);
BigDecimal ownCost = new BigDecimal(0);
BigDecimal rebateCost = new BigDecimal(0);
// 收费明细可能多条对应一张发票,所有要汇总所有收费明细记录存入一条发票信息
for (OutpatientChargeDetail o : details) {
pubCost = pubCost.add(StringUtils.isBlank(o.getPubCost()) ? new BigDecimal(0) : o.getPubCost());
ownCost = ownCost.add(StringUtils.isBlank(o.getOwnCost()) ? new BigDecimal(0) : o.getOwnCost());
rebateCost = rebateCost.add(StringUtils.isBlank(o.getRebateCost()) ? new BigDecimal(0) : o.getRebateCost());
}
invoiceInfo.setPubCost(pubCost);
invoiceInfo.setOwnCost(ownCost);
invoiceInfo.setRebateCost(rebateCost);
invoiceInfo.setUpdateTime(new Date());
invoiceInfo.setCancelFlag(InvoiceInfo.UN_CANCELED);
invoiceInfoManager.save(invoiceInfo);
// invoiceInfo.setCancelOper("");
// invoiceInfo.setComm("");
// invoiceInfo.setCreateOperId("");
// invoiceInfo.setCreateOper("");
// invoiceInfo.setCreateTime("");
// invoiceInfo.setUpdateOper("");
// invoiceInfo.setUpdateOperId("");
// invoiceInfo.setId("");
// invoiceInfo.setPrintState("");
// invoiceInfo.setCancelTime("");
// invoiceInfo.setPrintLastNo("");
// invoiceInfo.setBalanceId("");
// invoiceInfo.setBalanceTime("");
}
private InvoiceInfo refundUpdateInvoiceInfo(String hosId, String invoiceNo, HcpUser operator, String payId,
Date date) {
String hql = "from InvoiceInfo where hosId = ? and invoiceNo = ? ";
InvoiceInfo invoiceInfo = invoiceInfoManager.findOne(hql, hosId, invoiceNo);
if (invoiceInfo == null)
throw new RuntimeException("查不到该笔发票记录,请校验");
if (CANCLELED.equals(invoiceInfo.getCancelFlag()))
throw new RuntimeException("发票已经被退号,不能再退");
invoiceInfo.setCancelFlag(CANCLELED); // 已取消
invoiceInfo.setCancelOper(operator.getId());
invoiceInfo.setCancelOperName(operator.getName());
invoiceInfo.setCancelTime(date);
invoiceInfo.setUpdateTime(date);
invoiceInfo.setUpdateOper(operator.getName());
invoiceInfo.setUpdateOperId(operator.getId());
InvoiceInfo minusInvoiceInfo = new InvoiceInfo();
BeanUtils.copyProperties(invoiceInfo, minusInvoiceInfo);
minusInvoiceInfo.setId(null);
minusInvoiceInfo.setPayId(payId);
minusInvoiceInfo.setInvoiceOper(operator.getId());
minusInvoiceInfo.setInvoiceOperName(operator.getName());
minusInvoiceInfo.setInvoiceTime(date);
minusInvoiceInfo.setIsbalance(InvoiceInfo.UN_BALANCE);
minusInvoiceInfo.setBalanceId(null);
minusInvoiceInfo.setBalanceTime(null);
minusInvoiceInfo.setCreateOper(operator.getName());
minusInvoiceInfo.setCreateOperId(operator.getId());
minusInvoiceInfo.setCreateTime(date);
minusInvoiceInfo.setPlusMinus(-minusInvoiceInfo.getPlusMinus());
minusInvoiceInfo.setTotCost(minusInvoiceInfo.getTotCost().negate());
minusInvoiceInfo.setPubCost(minusInvoiceInfo.getPubCost().negate());
minusInvoiceInfo.setOwnCost(minusInvoiceInfo.getOwnCost().negate());
minusInvoiceInfo.setRebateCost(minusInvoiceInfo.getRebateCost().negate());
this.invoiceInfoManager.save(invoiceInfo);
return this.invoiceInfoManager.save(minusInvoiceInfo);
}
private HcpUser getUser(String userName) {
return hcpUserManager.findOneByProp("name", userName);
}
private void refundUpdateChargeDetails(InvoiceInfo info, HcpUser user, Date date) {
String hql = "from OutpatientChargeDetail where hosId = ? and invoiceNo = ? ";
List<OutpatientChargeDetail> details = (List<OutpatientChargeDetail>) outpatientChargeDetailManager.find(hql,
info.getHosId(), info.getInvoiceNo());
List<OutpatientChargeDetail> minusDetails = new ArrayList<>();
for (OutpatientChargeDetail chargeDetail : details) {
chargeDetail.setApplyState(OutpatientChargeDetail.APPLY_STATE_PAY_REFUNDED); // 已退费
chargeDetail.setCancelFlag(CANCLELED); // 已取消
chargeDetail.setCancelTime(date);
chargeDetail.setCancelOper(user);
OutpatientChargeDetail minusChargeDetail = new OutpatientChargeDetail();
BeanUtils.copyProperties(chargeDetail, minusChargeDetail);
minusChargeDetail.setId(null);
minusChargeDetail.setChargeOper(user);
minusChargeDetail.setChargeTime(date);
minusChargeDetail.setCreateTime(date);
minusChargeDetail.setQty(new BigDecimal(-1));
if (minusChargeDetail.getPlusMinus() != null) {
minusChargeDetail.setPlusMinus(minusChargeDetail.getPlusMinus().negate());
}
if (minusChargeDetail.getTotCost() != null) {
minusChargeDetail.setTotCost(minusChargeDetail.getTotCost().negate());
}
if (minusChargeDetail.getPubCost() != null) {
minusChargeDetail.setPubCost(minusChargeDetail.getPubCost().negate());
}
if (minusChargeDetail.getOwnCost() != null) {
minusChargeDetail.setOwnCost(minusChargeDetail.getOwnCost().negate());
}
if (minusChargeDetail.getRebateCost() != null) {
minusChargeDetail.setRebateCost(minusChargeDetail.getRebateCost().negate());
}
minusDetails.add(minusChargeDetail);
}
outpatientChargeDetailManager.batchSave(details);
outpatientChargeDetailManager.batchSave(minusDetails);
}
private void refundUpdateInvoiceInfoDetails(InvoiceInfo info, HcpUser user, Date date) {
String hql = "from InvoiceInfoDetail where hosId = ? and invoiceNo = ? ";
List<InvoiceInfoDetail> details = invoiceInfoDetailManager.find(hql, info.getHosId(), info.getInvoiceNo());
List<InvoiceInfoDetail> minusDetails = new ArrayList<>();
for (InvoiceInfoDetail invoiceInfoDetail : details) {
InvoiceInfoDetail minusInvoiceInfoDetail = new InvoiceInfoDetail();
invoiceInfoDetail.setCancelFlag(CANCLELED);
invoiceInfoDetail.setCancelTime(date);
invoiceInfoDetail.setCancelOper(user.getId());
BeanUtils.copyProperties(invoiceInfoDetail, minusInvoiceInfoDetail);
minusInvoiceInfoDetail.setId(null);
if (minusInvoiceInfoDetail.getPlusMinus() != null) {
minusInvoiceInfoDetail.setPlusMinus(-minusInvoiceInfoDetail.getPlusMinus());
}
if (minusInvoiceInfoDetail.getTotCost() != null) {
minusInvoiceInfoDetail.setTotCost(minusInvoiceInfoDetail.getTotCost().negate());
}
minusDetails.add(minusInvoiceInfoDetail);
}
invoiceInfoDetailManager.batchSave(details);
invoiceInfoDetailManager.batchSave(minusDetails);
}
private void refundUpdatePayWays(InvoiceInfo info, HcpUser user, Date date) {
String hql = "from PayWay where hosId = ? and invoiceNo = ? ";
List<PayWay> payWays = payWayManager.find(hql, info.getHosId(), info.getInvoiceNo());
List<PayWay> minusPayWays = new ArrayList<>();
for (PayWay payWay : payWays) {
PayWay minusPayWay = new PayWay();
payWay.setCancelFlag(CANCLELED); // 已取消
payWay.setCancelTime(date);
payWay.setCancelOper(user.getId());
BeanUtils.copyProperties(payWay, minusPayWay);
minusPayWay.setId(null);
minusPayWay.setPayId(info.getPayId());
minusPayWay.setUpdateOper(user.getName());
minusPayWay.setUpdateOperId(user.getId());
minusPayWay.setUpdateTime(date);
minusPayWay.setCreateOper(user.getName());
minusPayWay.setCreateOperId(user.getId());
minusPayWay.setCreateTime(date);
if (minusPayWay.getPlusMinus() != null) {
minusPayWay.setPlusMinus(-minusPayWay.getPlusMinus());
}
if (minusPayWay.getPayCost() != null) {
minusPayWay.setPayCost(minusPayWay.getPayCost().negate());
}
minusPayWays.add(minusPayWay);
}
payWayManager.batchSave(payWays);
payWayManager.batchSave(minusPayWays);
}
}
|
package ru.ifmo.diploma.synchronizer.listeners;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.ifmo.diploma.synchronizer.DirectoriesComparison;
import ru.ifmo.diploma.synchronizer.FileOperation;
import ru.ifmo.diploma.synchronizer.OperationType;
import ru.ifmo.diploma.synchronizer.messages.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.BlockingQueue;
/*
* Created by Юлия on 04.06.2017.
*/
public class DeleteFileListener extends AbstractListener {
private static final Logger LOG = LogManager.getLogger(DeleteFileListener.class);
private BlockingQueue<FileOperation> fileOperations;
public DeleteFileListener(String localAddr, BlockingQueue<AbstractMsg> tasks, DirectoriesComparison dc, BlockingQueue<FileOperation> fileOperations) {
super(localAddr, tasks, dc);
this.fileOperations=fileOperations;
}
@Override
public void handle(AbstractMsg msg) {
if (msg.getType() == MessageType.DELETE_FILE) {
DeleteFileMsg delMsg = (DeleteFileMsg) msg;
LOG.debug("{}: Listener: DELETE_FILE {} from host {}", localAddr, delMsg.getRelativePath(), msg.getSender());
fileOperations.add(new FileOperation(OperationType.ENTRY_DELETE, dc.getAbsolutePath(delMsg.getRelativePath())));
try {
Files.deleteIfExists(Paths.get(dc.getAbsolutePath(delMsg.getRelativePath())));
if (!msg.isBroadcast()) {
tasks.offer(new ResultMsg(localAddr, msg.getSender(), MessageState.SUCCESS, msg));
}
} catch (IOException e) {
if (!msg.isBroadcast()) {
tasks.offer(new ResultMsg(localAddr, msg.getSender(), MessageState.FAILED, msg));
}
e.printStackTrace();
}
}
}
}
|
package com.anitha.popupradioselection;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
final Context context = this;
AlertDialog alertDialog1;
// CharSequence[] values = {" First Item "," Second Item "," Third Item "};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.example_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuAbout:
/* AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Select Your Choice");
builder.setSingleChoiceItems(values, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item)
{
case 0:
Toast.makeText(MainActivity.this, "First Item Clicked", Toast.LENGTH_LONG).show();
break;
case 1:
Toast.makeText(MainActivity.this, "Second Item Clicked", Toast.LENGTH_LONG).show();
break;
case 2:
Toast.makeText(MainActivity.this, "Third Item Clicked", Toast.LENGTH_LONG).show();
break;
}
alertDialog1.dismiss();
}
});
alertDialog1 = builder.create();
alertDialog1.show();*/
LayoutInflater li = LayoutInflater.from(context);
final View promptsView = li.inflate(R.layout.radio_popup, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setView(promptsView);
RadioButton one=promptsView.findViewById(R.id.one);
RadioButton two=promptsView.findViewById(R.id.two);
RadioButton three=promptsView.findViewById(R.id.three);
/*
if(one.isChecked()||two.isChecked()||three.isChecked()|| four.isChecked()){
LayoutInflater lin = LayoutInflater.from(context);
final View promptsView1 = lin.inflate(R.layout.input, null);
AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(context);
alertDialogBuilder1.setView(promptsView1);
EditText password=promptsView1.findViewById(R.id.edit_password);
String password_value=password.getText().toString();
final AlertDialog alertDialog = alertDialogBuilder1.create();
alertDialog.show();
}*/
one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(context);
final View promptsView1 = li.inflate(R.layout.input, null);
AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(context);
alertDialogBuilder1.setView(promptsView1);
EditText password=promptsView1.findViewById(R.id.edit_password);
String password_value=password.getText().toString();
final AlertDialog alertDialog = alertDialogBuilder1.create();
alertDialog.show();
}
});
two.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(context);
final View promptsView1 = li.inflate(R.layout.input, null);
AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(context);
alertDialogBuilder1.setView(promptsView1);
EditText password=promptsView1.findViewById(R.id.edit_password);
String password_value=password.getText().toString();
final AlertDialog alertDialog = alertDialogBuilder1.create();
alertDialog.show();
}
});
three.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(context);
final View promptsView1 = li.inflate(R.layout.input, null);
AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(context);
alertDialogBuilder1.setView(promptsView1);
EditText password=promptsView1.findViewById(R.id.edit_password);
String password_value=password.getText().toString();
final AlertDialog alertDialog = alertDialogBuilder1.create();
alertDialog.show();
}
});
final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
default:
return super.onOptionsItemSelected(item);
}
}
}
|
package com.lenovohit.hwe.treat.service.impl;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import com.lenovohit.hwe.treat.dto.GenericRestDto;
import com.lenovohit.hwe.treat.model.Deposit;
import com.lenovohit.hwe.treat.service.HisDepositService;
import com.lenovohit.hwe.treat.transfer.RestEntityResponse;
import com.lenovohit.hwe.treat.transfer.RestListResponse;
/**
*
* @author xiaweiyi
*/
public class HisDepositRestServiceImpl implements HisDepositService {
GenericRestDto<Deposit> dto;
@Value("${his.baseUrl}")
private String baseUrl;
public HisDepositRestServiceImpl(final GenericRestDto<Deposit> dto) {
super();
this.dto = dto;
}
public HisDepositRestServiceImpl() {}
@Override
public RestEntityResponse<Deposit> getInfo(Deposit request, Map<String, ?> variables) {
// TODO Auto-generated method stub
return null;
}
@Override
public RestListResponse<Deposit> findList(Deposit request, Map<String, ?> variables) {
return dto.getForList("hcp/app/test/deposit/list", request);
}
@Override
public RestEntityResponse<Deposit> recharge(Deposit request, Map<String, ?> variables) {
return dto.postForEntity("hcp/app/test/deposit/recharge", request);
}
@Override
public RestEntityResponse<Deposit> freeze(Deposit request, Map<String, ?> variables) {
return dto.postForEntity("hcp/app/test/deposit/freeze", request);
}
@Override
public RestEntityResponse<Deposit> confirmFreeze(Deposit request, Map<String, ?> variables) {
return dto.postForEntity("hcp/app/test/deposit/confirmFreeze", request);
}
@Override
public RestEntityResponse<Deposit> unfreeze(Deposit request, Map<String, ?> variables) {
return dto.postForEntity("hcp/app/test/deposit/unfreeze", request);
}
@Override
public RestEntityResponse<Deposit> reufndCancel(Deposit request, Map<String, ?> variables) {
// TODO Auto-generated method stub
return null;
}
}
|
package ru.bmn.webpagestat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
*/
public class WebPage {
private final URL url;
private UrlPack internal;
private UrlPack exteranl;
private List<String> badUrls = null;
private boolean isFetched = false;
private static final Pattern REGEX_LINK_PATTERN = Pattern.compile("<a\\s[^>]*?href=['\"]?(.*?)['\"]?.*?>");
public WebPage(String url) {
try {
this.url = new URL(url);
}
catch (MalformedURLException e) {
throw new IllegalArgumentException("Malformed url value");
}
}
public int urlsCount() {
this.fetch();
return this.internal.count() + this.exteranl.count();
}
public UrlPack exteranlUrls() {
this.fetch();
return this.exteranl;
}
public UrlPack internalUrls() {
this.fetch();
return this.internal;
}
private void fetch() {
if (!this.isFetched) {
try {
URLConnection con = this.url.openConnection();
BufferedReader urlContent = new BufferedReader(
new InputStreamReader(con.getInputStream())
);
String line;
this.internal = new UrlPack();
this.exteranl = new UrlPack();
this.badUrls = new LinkedList<>();
while ((line = urlContent.readLine()) != null) {
this.processHtmlLine(line);
}
urlContent.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
this.isFetched = true;
}
}
}
private void processHtmlLine(String line) {
Matcher m = REGEX_LINK_PATTERN.matcher(line);
while (m.find()) {
String url = m.group(1);
try {
URL urlInfo = new URL(url);
if (urlInfo.getHost() == this.url.getHost()) {
this.internal.add(urlInfo);
}
}
catch (MalformedURLException e) {
this.badUrls.add(url);
}
}
}
}
|
package com.openfeint.game.archaeology.message;
import com.openfeint.game.archaeology.beans.CardSet;
import com.openfeint.game.message.GenericMessage;
public class TradeMessage extends GenericMessage {
private CardSet have;
private CardSet need;
/**
* @param playId The id of the player who is trading with market place
* @param have A set of cards the player has
* @param need A set of cards the player wants
*/
public TradeMessage(String playId, CardSet have, CardSet need) {
this.have = have;
this.need = need;
setFrom(playId);
setTo("MarketPlace");
}
public CardSet getHave() {
return have;
}
public CardSet getNeed() {
return need;
}
}
|
package com.gabriel.handyMan.controllers;
import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.time.LocalDateTime;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gabriel.handyMan.models.entity.Reporte;
@SpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class CalcularHorasControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
void test() throws Exception {
MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
requestParams.add("tecnicoId", String.valueOf(1234L));
requestParams.add("numeroSemana", "8");
mockMvc.perform(get("/api/calcularHoras/").params(requestParams).characterEncoding("utf-8")).andExpect(status().isOk());
//fail("Not yet implemented");
}
}
|
package com.imooc.controller;
import com.imooc.pojo.bo.ShopCartBO;
import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisOperator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
* 购物车Controller
*/
@Api(value = "购物车",tags = "购物车功能的相关接口")
@RestController
@RequestMapping("shopcart")
public class ShopCartController extends BaseController{
private static final Logger logger = LoggerFactory.getLogger(PassportController.class);
@Autowired
private RedisOperator redisOperator;
@ApiOperation(value = "同步购物车数据",notes = "同步存储前端cookie上的购物车数据到后端",httpMethod = "GET")
@PostMapping("/add")
public IMOOCJSONResult addShopCart(
@RequestParam String userId, @RequestBody ShopCartBO shopCartBo,
HttpServletRequest request, HttpServletResponse response){
if (StringUtils.isBlank(userId)){
return IMOOCJSONResult.errorMsg("该用户ID不存在!");
}
//用户登录后,前端把购物车数据传过来,后续通过Redis来存储对应购物车数据
String shopCartJson = redisOperator.get(FOODIE_SHOPCART + ":" + userId);
List<ShopCartBO> shopCartBOList;
//redis中已经有购物车
if (StringUtils.isNotBlank(shopCartJson)){
shopCartBOList = JsonUtils.jsonToList(shopCartJson,ShopCartBO.class);
//判断购物车中是否存在已有商品,如果有就累加
boolean isHaving = false;
for (ShopCartBO sc : shopCartBOList) {
String tmpSpecId = sc.getSpecId();
//存在已有商品,进行数量累加
if (tmpSpecId.equals(shopCartBo.getSpecId())){
sc.setBuyCounts(sc.getBuyCounts() + shopCartBo.getBuyCounts());
isHaving = true;
}
}
//购物车不包含该商品
if (!isHaving){
shopCartBOList.add(shopCartBo);
}
}else {
//redis没有购物车
shopCartBOList = new ArrayList<>();
//直接添加到购物车
shopCartBOList.add(shopCartBo);
}
//覆盖现有redis中的购物车
redisOperator.set(FOODIE_SHOPCART + ":" + userId,JsonUtils.objectToJson(shopCartBOList));
return IMOOCJSONResult.ok();
}
@ApiOperation(value = "删除购物车商品",notes = "同步删除用户登录后的购物车商品",httpMethod = "GET")
@PostMapping("/del")
public IMOOCJSONResult delShopCart(
@RequestParam String userId, @RequestParam String itemSpecId,
HttpServletRequest request, HttpServletResponse response){
if (StringUtils.isBlank(userId)){
return IMOOCJSONResult.errorMsg("该用户ID不存在!");
}
//用户登录后,删除购物车商品,通过Redis来同步删除对应购物车数据
String shopCartJson = redisOperator.get(FOODIE_SHOPCART + ":" + userId);
//redis中已经有购物车
if (StringUtils.isNotBlank(shopCartJson)){
List<ShopCartBO> shopCartBOList = JsonUtils.jsonToList(shopCartJson,ShopCartBO.class);
for (ShopCartBO sc : shopCartBOList) {
String tmpSpecId = sc.getSpecId();
//存在已有商品,进行删除
if (tmpSpecId.equals(itemSpecId)){
shopCartBOList.remove(sc);
break;
}
}
//覆盖现有redis中的购物车
redisOperator.set(FOODIE_SHOPCART + ":" + userId,JsonUtils.objectToJson(shopCartBOList));
}
return IMOOCJSONResult.ok();
}
}
|
package poo;
public class Director extends Jefatura {
public Director(String nom, double sue, int aņo, int mes, int dia){
super(nom, sue, aņo, mes, dia);
}
}
|
package com.soldevelo.vmi.testclient.facade;
import com.soldevelo.vmi.enumerations.DiagnosticState;
import com.soldevelo.vmi.packets.TestResultDns;
import com.soldevelo.vmi.time.VerizonTimestamp;
import org.apache.commons.lang.time.StopWatch;
import org.springframework.stereotype.Service;
import org.xbill.DNS.ARecord;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.SimpleResolver;
import org.xbill.DNS.Type;
import java.util.ArrayList;
import java.util.List;
@Service
public class DnsTestFacadeImpl implements DnsTestFacade {
@Override
public List<TestResultDns> dnsResponseTimeTest(String hostname, String serverUrl, int numberOfRepetitions) {
StopWatch stopWatch = new StopWatch();
List<TestResultDns> results = new ArrayList<TestResultDns>();
for (int i = 0; i < numberOfRepetitions; i++) {
try {
stopWatch.reset();
stopWatch.start();
Lookup lookup = new Lookup(hostname, Type.A);
lookup.setResolver(new SimpleResolver(serverUrl));
Record[] records = lookup.run();
stopWatch.stop();
if (records != null && records.length > 0) {
results.add(buildResult(DiagnosticState.COMPLETED, "Success", hostname, serverUrl,
(ARecord) records[0], stopWatch));
} else {
results.add(buildResult(DiagnosticState.ERROR_OTHER, DiagnosticState.ERROR_OTHER, hostname,
serverUrl, null, stopWatch));
}
} catch (Exception e) {
stopWatch.stop();
results.add(buildResult(DiagnosticState.ERROR_OTHER, DiagnosticState.ERROR_OTHER, hostname, serverUrl,
null, stopWatch));
}
}
return results;
}
private TestResultDns buildResult(String diagnosticState, String status, String hostname, String dnsServer,
ARecord record, StopWatch stopWatch) {
TestResultDns testResult = new TestResultDns();
testResult.setResponseTime(stopWatch.getTime());
VerizonTimestamp beginTime = new VerizonTimestamp(stopWatch.getStartTime());
VerizonTimestamp endTime = new VerizonTimestamp(stopWatch.getStartTime() + stopWatch.getTime());
testResult.setTcpOpenRequestTime(beginTime.toString());
testResult.setTcpOpenResponseTime(endTime.toString());
testResult.setDiagnosticState(diagnosticState);
testResult.setStatus(status);
testResult.setDownloadOrUploadUrl(hostname);
testResult.setDnsServerIp(dnsServer);
testResult.setTotalBytesReceivedOrSent(1024L);
if (record != null) {
testResult.setIpAddress(record.getAddress().getHostAddress());
}
return testResult;
}
}
|
package network.nerve.dex.rpc.call;
import io.nuls.core.basic.Result;
import io.nuls.core.exception.NulsException;
import io.nuls.core.log.Log;
import io.nuls.core.rpc.model.ModuleE;
import io.nuls.core.rpc.util.RpcCall;
import network.nerve.dex.context.DexConstant;
import network.nerve.dex.model.bean.AssetInfo;
import java.util.*;
import java.util.stream.Collectors;
public class CrossChainCall {
/**
* 查询已注册资产信息
*
* @return
*/
public static Result<Set<AssetInfo>> getAssetInfoList(int chainId) {
try {
Map params = new HashMap();
params.put("chainId",chainId);
Map data = (Map) RpcCall.request(ModuleE.LG.abbr, "lg_get_all_asset", params);
List<Map<String,Object>> list = (List<Map<String, Object>>) data.get("assets");
return Result.getSuccess(list.stream().map(d->{
AssetInfo r = new AssetInfo();
r.setAssetChainId((Integer) d.get("assetChainId"));
r.setAssetId((Integer) d.get("assetId"));
r.setSymbol(d.get("assetSymbol").toString());
r.setDecimal((Integer) d.get("decimalPlace"));
r.setStatus(DexConstant.ASSET_ENABLE);
return r;
}).collect(Collectors.toSet()));
// Map<String, Object> map = (Map) RpcCall.request(ModuleE.CC.abbr, DexRpcConstant.GET_REGISTERED_CHAIN, new HashMap());
// List<Map<String, Object>> resultList = (List<Map<String, Object>>) map.get("list");
//
// List<AssetInfo> assetInfoList = new ArrayList<>();
//
// for (Map<String, Object> resultMap : resultList) {
// List<Map<String, Object>> assetList = (List<Map<String, Object>>) resultMap.get("assetInfoList");
// if (assetList != null) {
// for (Map<String, Object> assetMap : assetList) {
// AssetInfo assetInfo = new AssetInfo();
// assetInfo.setAssetChainId((Integer) resultMap.get("chainId"));
// assetInfo.setAssetId((Integer) assetMap.get("assetId"));
// assetInfo.setSymbol((String) assetMap.get("symbol"));
// assetInfo.setDecimal((Integer) assetMap.get("decimalPlaces"));
// boolean usable = (boolean) assetMap.get("usable");
// if (usable) {
// assetInfo.setStatus(DexConstant.ASSET_ENABLE);
// } else {
// assetInfo.setStatus(DexConstant.ASSET_DISABLE);
// }
// assetInfoList.add(assetInfo);
// }
// }
// }
// return Result.getSuccess(null).setData(assetInfoList);
} catch (NulsException e) {
Log.error(e);
return Result.getFailed(e.getErrorCode());
}
}
}
|
package com.uniinfo.cloudplat.vo;
public class AuthorizeReqVO {
private String client_id;// true string 申请应用时分配的AppKey。
// private String redirect_uri;// true string 授权回调地址,站外应用需与设置的回调地址一致,站内应用需填写canvas page的地址。
// private String scope;// false string 申请scope权限所需参数,可一次申请多个scope权限,用逗号分隔。使用文档
// private String state;// false string 用于保持请求和回调的状态,在回调时,会在Query Parameter中回传该参数。开发者可以用这个参数验证请求有效性,也可以记录用户请求授权页前的位置。这个参数可用于防止跨站请求伪造(CSRF)攻击
// private String display;// false string 授权页面的终端类型,取值见下面的说明。
// private boolean forcelogin;// false boolean 是否强制用户重新登录,true:是,false:否。默认false。
// private String language;// false string 授权页语言,缺省为中文简体版,en为英文版。英文版测试中,开发者任何意见可反馈至 @微博API
//平台登录时通过用户名密码获取临时凭证,无需重定向
private String uid;
private String pwd;
public String getClient_id() {
return client_id;
}
public void setClient_id(String clientId) {
client_id = clientId;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
|
package com.site.ui;
import java.io.File;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.site.BaseActivity;
import com.site.R;
import com.site.tools.Bimp;
import com.site.tools.Constant;
import com.site.tools.FileUtils;
import com.site.tools.ImageItem;
import com.site.tools.PublicWay;
import com.site.tools.Res;
import com.site.tools.SiteUtil;
import com.site.upload.FormFile;
import com.site.upload.SocketHttpRequester;
/**
* 首页面activity
*
* @version 2014年10月18日 下午11:48:34
*/
public class CopyOfMainActivity extends BaseActivity {
private GridView noScrollgridview;
private GridAdapter adapter;
private View parentView;
private PopupWindow pop = null;
private LinearLayout ll_popup;
public static Bitmap bimap;
private ProgressBar mPgBar;
private TextView mTvProgress;
private FormFile[] formFiles;
private MyTask mTask;
private View upView;
/* 定位相关 */
LocationClient mLocClient;
public MyLocationListenner myListener = new MyLocationListenner();
private BitmapDescriptor mCurrentMarker;
private MapView mMapView;
private BaiduMap baiduMap;
boolean isFirstLoc = true;// 是否首次定位
private String lineIds;
@ViewInject(R.id.title)
private TextView title;
@ViewInject(R.id.editUser)
private TextView editUser;
@ViewInject(R.id.site)
private TextView site;
@OnClick(R.id.site)
public void site(View v) {
finish();
}
@OnClick(R.id.cancel)
public void cancel(View v) {
finish();
}
private String showMsg="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Res.init(this);
bimap = BitmapFactory.decodeResource(getResources(),
R.drawable.icon_addpic_unfocused);
PublicWay.activityList.add(this);
parentView = getLayoutInflater().inflate(R.layout.activity_selectimg,
null);
setContentView(parentView);
Init();
addActivity(this);
ViewUtils.inject(this);
upView = getLayoutInflater().inflate(R.layout.filebrowser_uploading,
null);
mPgBar = (ProgressBar) upView
.findViewById(R.id.pb_filebrowser_uploading);
mTvProgress = (TextView) upView
.findViewById(R.id.tv_filebrowser_uploading);
initView();
initValue();
}
@Override
protected void initView() {
// TODO Auto-generated method stub
title.setText("上报站点信息");
site.setText("线路列表");
editUser.setText("");
// 地图初始化
mMapView = (MapView) findViewById(R.id.bmapView);
baiduMap = mMapView.getMap();
// 开启定位图层
baiduMap.setMyLocationEnabled(true);
// 定位初始化
mLocClient = new LocationClient(this);
mLocClient.registerLocationListener(myListener);
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true);// 打开gps
option.setCoorType("bd09ll"); // 设置坐标类型
option.setScanSpan(72000);
mLocClient.setLocOption(option);
// 普通地图
baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
// 开启交通图线
baiduMap.setTrafficEnabled(true);
// 设置比例尺
baiduMap.setMapStatus(MapStatusUpdateFactory
.newMapStatus(new MapStatus.Builder().zoom(16).build()));
mLocClient.start();
}
@Override
protected void initValue() {
// TODO Auto-generated method stub
}
@OnClick(R.id.input_img)
public void submit(View v) {
new AlertDialog.Builder(CopyOfMainActivity.this).setTitle("上传进度")
.setView(upView).create().show();
ArrayList<ImageItem> imageItems = Bimp.tempSelectBitmap;
formFiles = new FormFile[imageItems.size()];
for (int i=0;i<imageItems.size();i++)
{
ImageItem item=imageItems.get(i);
Bitmap bitmap = item.getBitmap();
String path = item.getImagePath();
if (path == null || "".equals(path))// 拍照没有路径
{
item.setImagePath(path);
}
path = Constant.IMG_PATH + getPicName();
SiteUtil.compressBitmap(bitmap, path);
File imageFile = new File(path);
FormFile formFile = new FormFile(String.valueOf(new Date().getTime()) + i + ".jpg", imageFile, "image","application/octet-stream");
formFiles[i] = formFile;
}
mTask = new MyTask();
mTask.execute();
}
private String getPicName() {
return new Date().getTime() + ".jpg";
}
private class MyTask extends AsyncTask<String, Integer, String> {
@Override
protected void onPostExecute(String result) {
submitResult(result);
}
@Override
protected void onPreExecute() {
mTvProgress.setText("loading...");
}
@Override
protected void onProgressUpdate(Integer... values) {
mPgBar.setProgress(values[0]);
mTvProgress.setText("loading..." + values[0] + "%");
}
@Override
protected String doInBackground(String... param) {
Map<String, String> params = new HashMap<String, String>();
params.put("cityId", SiteUtil.getCity());
params.put("linelist", SiteUtil.getLineIds());
params.put("stopName", SiteUtil.getStopName());
params.put("stopId", SiteUtil.getStopId());
params.put("jingdu", SiteUtil.getLongitude());
params.put("weidu", SiteUtil.getLatitude());
try {
return post(Constant.UPLOAD_URL, params, formFiles);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String post(String path, Map<String, String> params,
FormFile[] files) throws Exception {
final String BOUNDARY = "---------------------------7da2137580612"; // 数据分隔线
final String endline = "--" + BOUNDARY + "--\r\n";// 数据结束标志
SiteUtil.LOG_D(SocketHttpRequester.class, "upload--->post");
int fileDataLength = 0;
for (FormFile uploadFile : files) {// 得到文件类型数据的总长度
SiteUtil.LOG_D(CopyOfMainActivity.class, uploadFile.getFilname());
StringBuilder fileExplain = new StringBuilder();
fileExplain.append("--");
fileExplain.append(BOUNDARY);
fileExplain.append("\r\n");
fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName() + "\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
fileExplain.append("Content-Type: "+ uploadFile.getContentType() + "\r\n\r\n");
fileExplain.append("\r\n");
fileDataLength += fileExplain.length();
if (uploadFile.getInStream() != null)
{
long len = uploadFile.getFile().length();
SiteUtil.LOG_D(SocketHttpRequester.class, "File size:"+ len);
if (uploadFile.getFile() != null) {
fileDataLength += len;
} else {
fileDataLength += len;
}
} else {
fileDataLength += uploadFile.getData().length;
}
}
StringBuilder textEntity = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {// 构造文本类型参数的实体数据
textEntity.append("--");
textEntity.append(BOUNDARY);
textEntity.append("\r\n");
textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
textEntity.append(entry.getValue());
textEntity.append("\r\n");
}
// 计算传输给服务器的实体数据总长度
int dataLength = textEntity.toString().getBytes().length+ fileDataLength + endline.getBytes().length;
URL url = new URL(path);
int port = url.getPort() == -1 ? 80 : url.getPort();
Socket socket = new Socket(InetAddress.getByName(url.getHost()),
port);
Log.i("hbgz", "socket connected is " + socket.isConnected());
OutputStream outStream = socket.getOutputStream();
// 下面完成HTTP请求头的发送
String requestmethod = "POST " + url.getPath() + " HTTP/1.1\r\n";
outStream.write(requestmethod.getBytes());
String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
outStream.write(accept.getBytes());
String language = "Accept-Language: zh-CN\r\n";
outStream.write(language.getBytes());
String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY + "\r\n";
outStream.write(contenttype.getBytes());
String contentlength = "Content-Length: " + dataLength + "\r\n";
outStream.write(contentlength.getBytes());
String alive = "Connection: Keep-Alive\r\n";
outStream.write(alive.getBytes());
String host = "Host: " + url.getHost() + ":" + port + "\r\n";
outStream.write(host.getBytes());
// 写完HTTP请求头后根据HTTP协议再写一个回车换行
outStream.write("\r\n".getBytes());
// 把所有文本类型的实体数据发送出来
outStream.write(textEntity.toString().getBytes());
// 把所有文件类型的实体数据发送出来
int length = 0;
for (FormFile uploadFile : files)
{
StringBuilder fileEntity = new StringBuilder();
fileEntity.append("--");
fileEntity.append(BOUNDARY);
fileEntity.append("\r\n");
fileEntity.append("Content-Disposition: form-data;name=\"" +uploadFile.getParameterName() + "\";filename=\"" +uploadFile.getFilname() + "\"\r\n");
fileEntity.append("Content-Type: "+ uploadFile.getContentType() + "\r\n\r\n");
outStream.write(fileEntity.toString().getBytes());
System.out.println(fileEntity);
if (uploadFile.getInStream() != null)
{
byte[] buffer = new byte[1024];
int len = 0;
while ((len = uploadFile.getInStream().read(buffer, 0, 1024)) != -1)
{
outStream.write(buffer, 0, len);
length += len;
publishProgress((int) ((length / (float) dataLength) * 100));
}
uploadFile.getInStream().close();
} else
{
outStream.write(uploadFile.getData(), 0,uploadFile.getData().length);
}
outStream.write("\r\n".getBytes());
}
// 下面发送数据结束标志,表示数据已经结束
outStream.write(endline.getBytes());
outStream.flush();
InputStreamReader reader = new InputStreamReader(
socket.getInputStream());
int i = 0;
char[] buffer = new char[1024];
while ((i = reader.read(buffer)) != -1) {
boolean requestCodeSuccess = false;
boolean uploadSuccess = false;
String str = new String(buffer);
int start = str.trim().indexOf("{");
int end = str.trim().indexOf("}");
if (start > -1 && end > 0) {
return str.substring(start, end + 1);
}
}
outStream.flush();
outStream.close();
reader.close();
socket.close();
return null;
}
}
public void submitResult(String json)
{
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(json);
JsonObject jsonObject = jsonElement.getAsJsonObject();
String status = jsonObject.get("status").getAsString();
if ("00".equals(status))
{
showMsg="上传成功";
} else
{
showMsg="上传失败,请重试";
}
showDialog();
}
public void showDialog()
{
AlertDialog alertDialog = new AlertDialog.Builder(this).setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
for (int i = 0; i < PublicWay.activityList.size(); i++)
{
if (null != PublicWay.activityList.get(i))
{
PublicWay.activityList.get(i).finish();
}
}
System.exit(0);
}
}).setTitle("提示").setMessage(showMsg).create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
public void Init() {
pop = new PopupWindow(CopyOfMainActivity.this);
View view = getLayoutInflater().inflate(R.layout.item_popupwindows,
null);
ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
pop.setWidth(LayoutParams.MATCH_PARENT);
pop.setHeight(LayoutParams.WRAP_CONTENT);
pop.setBackgroundDrawable(new BitmapDrawable());
pop.setFocusable(true);
pop.setOutsideTouchable(true);
pop.setContentView(view);
RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
parent.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
pop.dismiss();
ll_popup.clearAnimation();
}
});
bt1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
photo();
pop.dismiss();
ll_popup.clearAnimation();
}
});
bt2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(CopyOfMainActivity.this,AlbumActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.activity_translate_in,
R.anim.activity_translate_out);
pop.dismiss();
ll_popup.clearAnimation();
finish();
}
});
bt3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
pop.dismiss();
ll_popup.clearAnimation();
}
});
noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
adapter = new GridAdapter(this);
adapter.update();
noScrollgridview.setAdapter(adapter);
noScrollgridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if (arg2 == Bimp.tempSelectBitmap.size()) {
Log.i("ddddddd", "----------");
ll_popup.startAnimation(AnimationUtils.loadAnimation(
CopyOfMainActivity.this, R.anim.activity_translate_in));
pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
} else {
Intent intent = new Intent(CopyOfMainActivity.this,
GalleryActivity.class);
intent.putExtra("position", "1");
intent.putExtra("ID", arg2);
startActivity(intent);
}
}
});
}
@SuppressLint("HandlerLeak")
public class GridAdapter extends BaseAdapter {
private LayoutInflater inflater;
private int selectedPosition = -1;
private boolean shape;
public boolean isShape() {
return shape;
}
public void setShape(boolean shape) {
this.shape = shape;
}
public GridAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public void update() {
loading();
}
public int getCount() {
if (Bimp.tempSelectBitmap.size() == 6) {
return 6;
}
return (Bimp.tempSelectBitmap.size() + 1);
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int arg0) {
return 0;
}
public void setSelectedPosition(int position) {
selectedPosition = position;
}
public int getSelectedPosition() {
return selectedPosition;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_published_grida,
parent, false);
holder = new ViewHolder();
holder.image = (ImageView) convertView
.findViewById(R.id.item_grida_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (position == Bimp.tempSelectBitmap.size()) {
holder.image.setImageBitmap(BitmapFactory.decodeResource(
getResources(), R.drawable.icon_addpic_unfocused));
if (position == 6) {
holder.image.setVisibility(View.GONE);
}
} else {
holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position)
.getBitmap());
}
return convertView;
}
public class ViewHolder {
public ImageView image;
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
adapter.notifyDataSetChanged();
break;
}
super.handleMessage(msg);
}
};
public void loading() {
new Thread(new Runnable() {
public void run() {
while (true) {
if (Bimp.max == Bimp.tempSelectBitmap.size()) {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
break;
} else {
Bimp.max += 1;
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
}
}
}).start();
}
}
public String getString(String s) {
String path = null;
if (s == null)
return "";
for (int i = s.length() - 1; i > 0; i++) {
s.charAt(i);
}
return path;
}
protected void onRestart() {
adapter.update();
super.onRestart();
}
// 完成
private static final int TAKE_PICTURE = 0x000001;
public void photo() {
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(openCameraIntent, TAKE_PICTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PICTURE:
if (Bimp.tempSelectBitmap.size() < 6 && resultCode == RESULT_OK) {
String fileName = String.valueOf(System.currentTimeMillis());
Bitmap bm = (Bitmap) data.getExtras().get("data");
FileUtils.saveBitmap(bm, fileName);
ImageItem takePhoto = new ImageItem();
takePhoto.setBitmap(bm);
Bimp.tempSelectBitmap.add(takePhoto);
}
break;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
for (int i = 0; i < PublicWay.activityList.size(); i++) {
if (null != PublicWay.activityList.get(i)) {
PublicWay.activityList.get(i).finish();
}
}
System.exit(0);
}
return true;
}
/**
* 定位SDK监听函数
*/
public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
// map view 销毁后不在处理新接收的位置
if (location == null || mMapView == null)
return;
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius())
// 此处设置开发者获取到的方向信息,顺时针0-360
.direction(100).latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
baiduMap.setMyLocationData(locData);
if (isFirstLoc) {
isFirstLoc = false;
LatLng ll = new LatLng(location.getLatitude(),
location.getLongitude());
MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
baiduMap.animateMapStatus(u);
}
}
public void onReceivePoi(BDLocation poiLocation) {
}
}
}
|
package com.GestiondesClub.dto;
import java.util.Date;
import java.util.List;
import com.GestiondesClub.entities.Club;
import com.GestiondesClub.entities.ParticipantEtudiant;
import com.GestiondesClub.entities.ReunionInviter;
import com.GestiondesClub.entities.ReunionParticipant;
import com.GestiondesClub.entities.Salle;
public interface ReunionDto {
Long getId();
String getTitre();
String getSujet();
Date getDateCreation();
Date getDateReunion();
Date getTempdebReunion();
Date getTempfinReunion();
boolean isType();
boolean isSalleConfirmed();
Salle getSalleReunion();
List<ReunionInviter> getLesInviter();
List<ParicipantDto> getLesParticipantsAdmins();
List<etudiantParticipantDto> getLesParticipantsetudiants();
OnlyClubDto getLeClub();
}
|
/*
* Copyright (C) 2011 Marvell International Ltd., All Rights Reserved
*
* MARVELL CONFIDENTIAL
* The source code contained or described herein and all documents related to
* the source code ("Material") are owned by Marvell International Ltd or its
* suppliers or licensors. Title to the Material remains with Marvell International Ltd
* or its suppliers and licensors. The Material contains trade secrets and
* proprietary and confidential information of Marvell or its suppliers and
* licensors. The Material is protected by worldwide copyright and trade secret
* laws and treaty provisions. No part of the Material may be used, copied,
* reproduced, modified, published, uploaded, posted, transmitted, distributed,
* or disclosed in any way without Marvell's prior express written permission.
*
* No license under any patent, copyright, trade secret or other intellectual
* property right is granted to or conferred upon you by disclosure or delivery
* of the Materials, either expressly, by implication, inducement, estoppel or
* otherwise. Any license under such intellectual property rights must be
* express and approved by Marvell in writing.
*
*/
package com.marvell.wifidirect.apitest.tests;
import android.net.wifi.MrvlWifiDirectConfiguration;
import android.net.wifi.MrvlWifiDirectPeer;
import android.os.Parcel;
import android.util.Log;
import junit.framework.TestCase;
/**
* Test cases to exercise the android.net.wifi.configuration class
*
* @since Marvell-0.01
*/
public class WifiDirectConfigurationTest extends TestCase {
MrvlWifiDirectConfiguration conf;
static final String LOG_TAG = "configurationTest";
public void setUp() throws Exception {
super.setUp();
//Create the object to be tested
conf = new MrvlWifiDirectConfiguration();
conf.mName = "Joe Foo";
conf.mGoIntent = 10;
conf.mAcceptConnectionRequests = true;
conf.mConfigMethods = MrvlWifiDirectPeer.CONFIG_METHOD_PBC_PHYS;
}
public void testWriteAndReadParceledconfiguration() {
Parcel parcel = Parcel.obtain();
conf.writeToParcel(parcel, 0);
//done writing, now reset parcel for reading
parcel.setDataPosition(0);
//finish round trip
MrvlWifiDirectConfiguration conf2 = (MrvlWifiDirectConfiguration) conf.CREATOR.createFromParcel(parcel);
assertEquals(conf.mName, conf2.mName);
assertEquals(conf.mGoIntent, conf2.mGoIntent);
assertEquals(conf.mAcceptConnectionRequests, conf2.mAcceptConnectionRequests);
assertEquals(conf.mConfigMethods, conf2.mConfigMethods);
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
}
|
package com.accolite.au.models;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
@Entity
public class Trainer implements Serializable {
@Id // primary key
@GeneratedValue(strategy = GenerationType.AUTO)
private int trainerId;
// @ManyToOne
// @JoinColumn(name = "batch_id")
// private Batch batch;
@OneToOne(targetEntity = BusinessUnit.class, fetch = FetchType.LAZY)
@JoinColumn(name="buId")
private BusinessUnit businessUnit;
@OneToOne(fetch = FetchType.LAZY)
private StudentGroup studentGroup;
@OneToOne(fetch = FetchType.LAZY)
private Session session;
private String trainerName;
private String skypeId;
private String reportingManagerEmailId;
private String emailId;
@CreationTimestamp
private Timestamp createdOn;
public StudentGroup getStudentGroup() {
return studentGroup;
}
public void setStudentGroup(StudentGroup studentGroup) {
this.studentGroup = studentGroup;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public int getTrainerId() {
return trainerId;
}
public void setTrainerId(int trainerId) {
this.trainerId = trainerId;
}
// public Batch getBatch() {
// return batch;
// }
//
// public void setBatch(Batch batch) {
// this.batch = batch;
// }
public BusinessUnit getBusinessUnit() {
return businessUnit;
}
public void setBusinessUnit(BusinessUnit businessUnit) {
this.businessUnit = businessUnit;
}
public String getTrainerName() {
return trainerName;
}
public void setTrainerName(String trainerName) {
this.trainerName = trainerName;
}
public String getSkypeId() {
return skypeId;
}
public void setSkypeId(String skypeId) {
this.skypeId = skypeId;
}
public String getReportingManagerEmailId() {
return reportingManagerEmailId;
}
public void setReportingManagerEmailId(String reportingManagerEmailId) {
this.reportingManagerEmailId = reportingManagerEmailId;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
}
|
/**
* All rights Reserved, Designed By www.tydic.com
* @Title: PictureController.java
* @Package com.taotao.controller
* @Description: TODO(用一句话描述该文件做什么)
* @author: axin
* @date: 2018年12月6日 下午11:57:50
* @version V1.0
* @Copyright: 2018 www.hao456.top Inc. All rights reserved.
*/
package com.taotao.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.taotao.common.utils.JsonUtils;
import com.taotao.service.PictureService;
/**
* @ClassName: PictureController
* @Description: 图片上传控制层
* @author: Axin
* @date: 2018年12月6日 下午11:57:50
* @Copyright: 2018 www.hao456.top Inc. All rights reserved.
*/
@Controller
public class PictureController {
@Autowired
private PictureService pictureService;
@RequestMapping("/pic/upload")
@ResponseBody
public String pictureUpload(MultipartFile uploadFile){
Map<String, Object> result = this.pictureService.uploadPicture(uploadFile);
//为了兼容在火狐浏览器,需要将对象转换为JSON字符串
return JsonUtils.objectToJson(result);
}
}
|
//Created By THLAVLU18301190
package lab01p02t03;
import java.util.Scanner;
public class Lab01p02t03 {
public static void main(String[] args) {
Scanner thl = new Scanner(System.in);
try {
int n= thl.nextInt();
int a[] = new int[n];
a[5] = 99;
int x = n / 0;
} catch (ArithmeticException e) {
System.out.println();
} catch (ArrayIndexOutOfBoundsException e) {
} finally {
System.out.println("THE END");
}
}
}
|
package com.isg.ifrend.core.model.mli.transaction;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
*
* @author aizza.fernando
*
*/
public class StatementDetail implements Serializable {
private static final long serialVersionUID = 6487737586393004689L;
private String accountNumber;
private Date postDate;
private Date transactionDate;
private String description;
private String transactionCode;
private BigDecimal transactionAmount;
public StatementDetail(){
}
public StatementDetail(String accountNumber, Date postDate,
Date transactionDate, String description, String transactionCode,
BigDecimal transactionAmount) {
this.accountNumber = accountNumber;
this.postDate = postDate;
this.transactionDate = transactionDate;
this.description = description;
this.transactionCode = transactionCode;
this.transactionAmount = transactionAmount;
}
/** setter and getter **/
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public Date getPostDate() {
return postDate;
}
public void setPostDate(Date postDate) {
this.postDate = postDate;
}
public Date getTransactionDate() {
return transactionDate;
}
public void setTransactionDate(Date transactionDate) {
this.transactionDate = transactionDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTransactionCode() {
return transactionCode;
}
public void setTransactionCode(String transactionCode) {
this.transactionCode = transactionCode;
}
public BigDecimal getTransactionAmount() {
return transactionAmount;
}
public void setTransactionAmount(BigDecimal transactionAmount) {
this.transactionAmount = transactionAmount;
}
}
|
package xyz.lateralus.components;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import xyz.lateralus.app.BuildConfig;
public class Utils {
private static final String TAG = "Utils";
public static final String NAME_UNKNOWN = "Unknown";
public static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static String getContactName(Context context, String phoneNumber) {
if(phoneNumber.isEmpty()){
return "";
}
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
String contactName = NAME_UNKNOWN;
if (cursor != null && cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
cursor.close();
}
return contactName;
}
public static String parsePhoneNumber(String number){
number = number.replace("\u0000", "").replace("\\u0000", "").replaceAll("\\s", "").replaceAll("[^\\d.]", "");
if(number.startsWith("1")){
number = number.substring(1);
}
return number;
}
public static void hideAppInDrawer(Context ctx){
try {
ctx.getPackageManager().setComponentEnabledSetting(
new ComponentName("xyz.lateralus", "xyz.lateralus.SignInActivity"),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP
);
}
catch(Exception e){
Log.e(TAG, "Could not hide app from drawer: " + e.getMessage());
e.printStackTrace();
}
}
public static void showAppInDrawer(Context ctx){
try {
ctx.getPackageManager().setComponentEnabledSetting(
new ComponentName("xyz.lateralus","xyz.lateralus.SignInActivity"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP
);
}
catch(Exception e){
Log.e(TAG, "Could not show app in drawer: " + e.getMessage());
e.printStackTrace();
}
}
public static boolean internetActive(Context ctx){
ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public static Boolean isGPSOn(Context ctx){
LocationManager locMan = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);;
return (locMan != null && locMan.isProviderEnabled(LocationManager.GPS_PROVIDER));
}
public static Boolean isWiFiConnected(Context ctx){
ConnectivityManager connManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return (wifi != null && wifi.isConnected());
}
public static Boolean isBluetoothOn(){
BluetoothAdapter blue = BluetoothAdapter.getDefaultAdapter();
return (blue != null && blue.isEnabled());
}
public static String getMD5(String str){
try {
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(str.getBytes());
byte messageDigest[] = digest.digest();
StringBuilder hexString = new StringBuilder();
for(int x = 0; x < messageDigest.length; x++) {
hexString.append(Integer.toHexString(0xFF & messageDigest[x]));
}
return hexString.toString();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
// we should crash...
//throw new RuntimeException("MD5 Algorithm Not Found!");
}
return "";
}
public static String getPkgVersion(){
return BuildConfig.VERSION_NAME;
}
public static void openLinkInBrowser(Activity act, String url){
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
act.startActivity(intent);
}
public static boolean checkPlayServices(Activity act) {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(act);
if(resultCode != ConnectionResult.SUCCESS) {
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, act, 9000).show();
}
else {
Log.e(TAG, "This device is not supported.");
act.finish();
}
return false;
}
return true;
}
public static long getTimestampMillis(){
return System.currentTimeMillis();
}
public static String capitalizeFirstChar(String str){
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
public static Boolean passwordHasCorrectLength(String pass){
return pass.length() >= 6;
}
public static Boolean isValidEmail(String email){
return email.length() > 6 && email.contains("@") && email.contains(".");
}
public static String generateDeviceUuid(Context ctx) {
try {
final TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
final String tmDevice, tmSerial, androidId;
tmDevice = "" + tm.getDeviceId();
tmSerial = "" + tm.getSimSerialNumber();
androidId = "" + android.provider.Settings.Secure.getString(ctx.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
return deviceUuid.toString();
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
|
package com.gome.manager.domain;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
/**
*
* 会议实体类.
*
* <pre>
* 修改日期 修改人 修改原因
* 2015年11月6日 caowei 新建
* </pre>
*/
public class Meeting {
DateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
//会议ID
private Long id;
//会议编号
private String code;
//会议名称
private String name;
//参考价格
private String theme;
//图片地址
private String picPath;
//会议描述
private String description;
//状态(0:关闭 1:开启)
private String status;
//修改时间
private String beginTime;
//修改时间
private String endTime;
//创建时间
private String createTime;
//创建人
private String createPer;
//操作账号
private String operateUser;
//欢迎信
private String letterContent;
//欢迎信
private String letterPic;
//欢迎信
private String meetAddr;
public String getMeetAddr() {
return meetAddr;
}
public void setMeetAddr(String meetAddr) {
this.meetAddr = meetAddr;
}
public String getLetterPic() {
return letterPic;
}
public void setLetterPic(String letterPic) {
this.letterPic = letterPic;
}
public String getLetterContent() {
return letterContent;
}
public void setLetterContent(String letterContent) {
this.letterContent = letterContent;
}
public String getOperateUser() {
return operateUser;
}
public void setOperateUser(String operateUser) {
this.operateUser = operateUser;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public String getPicPath() {
return picPath;
}
public void setPicPath(String picPath) {
this.picPath = picPath;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getBeginTime() {
return beginTime;
}
public void setBeginTime(String beginTime) {
this.beginTime = beginTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getCreatePer() {
return createPer;
}
public void setCreatePer(String createPer) {
this.createPer = createPer;
}
}
|
package cn.itcast.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.utils.CheckUtils;
public class RegistServlet extends HttpServlet {
private UserService us = new UserService();
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//1 封装参数到User对象
User u = new User();
try {
BeanUtils.populate(u, request.getParameterMap());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//2.校验
Map<String, String> errors = CheckUtils.checkUser(u);
if(errors.size() > 0){
//有错误,将错误信息放在request域=》转发到注册页面显示
request.setAttribute("errors", errors);
request.getRequestDispatcher("/regist.jsp").forward(request, response);
return;
}
//增加一个功能,验证码
//code1 用户填写的验证码,code2验证码答案
String code1 = request.getParameter("code");
String code2 = (String) request.getSession().getAttribute("code");
if(code1 == null || !code1.equalsIgnoreCase(code2)){
request.setAttribute("error", "验证码错误,请重新输入");
request.getRequestDispatcher("/regist.jsp").forward(request, response);
return;
}
//3调用Service保存
try {
us.regist(u);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("error", e.getMessage());
request.getRequestDispatcher("/regist.jsp").forward(request, response);
return;
}
//4根据结果,跳转到对应页面
response.sendRedirect(request.getContextPath()+"/login.jsp");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
|
package com.github.bot.curiosone.core.knowledge;
import com.github.bot.curiosone.core.knowledge.interfaces.Vertex;
/**
* This class represents a Concept of a Semantic Network.
* @author Christian Sordi.
*/
public class Concept implements Vertex {
/**
* Name of the represented Concept.
*/
private final String id;
/**
* Default class constructor.
* @param id Concept name.
*/
public Concept(String id) {
this.id = id;
}
/**
* Returns Concept name.
*/
@Override
public String getId() {
return id;
}
/**
* Returns Concept String representation.
*/
public String toString() {
return getId();
}
/**
* Method to confront the instance with another object.
* @param o the other Concept to be confronted with.
* @return true, if the concept are equal, false if not.
*/
@Override
public boolean equals(Object o) {
return this.id.equals(((Concept)o).getId());
}
/**
* Returns the HashCode of the Concept name.
*/
@Override
public int hashCode() {
int conta = 0;
for (int x = 0; x < id.length(); x++) {
conta += id.charAt(x) * 31;
}
return conta;
}
}
|
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res) // object of HttpServletResponse interface is response which will be send to the client,here res is a response
{
try{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Cookie ck[]=req.getCookies();
if(ck[0].getName().equals("uname")) //uname is name of cookie which is given by us in first servlet to recognize the user as old user here
{
pw.println("user is recognized as old user");
pw.println("Hello "+ck[0].getValue());
pw.print("<form action='servlet3' method='post'> ");
pw.print("<input type='submit' value='go'>");
pw.print("</form>");
Cookie sck = new Cookie("tname","arpit");
res.addCookie(sck); // note : this is second cookie added in this response ,first cookie(fck) are defined in FirstServlet.java which do not need to add here because it is added automatically in this response since when it comes with request object sent by FirstServlet.java file
pw.close();
}
}catch(Exception e){System.out.println(e);}
}
}
|
package com.appirio.service.member.manager;
import com.amazonaws.util.json.JSONObject;
import com.appirio.eventsbus.api.client.EventProducer;
import com.appirio.eventsbus.api.client.exception.EmptyEventException;
import com.appirio.eventsbus.api.client.exception.EncodingEventException;
import com.appirio.service.EmailVerificationConfiguration;
import com.appirio.service.member.api.*;
import com.appirio.service.member.dao.MemberProfileDAO;
import com.appirio.service.member.dao.MemberStatsDAO;
import com.appirio.service.member.eventbus.EventBusServiceClient;
import com.appirio.service.member.eventbus.EventMessage;
import com.appirio.supply.SupplyException;
import com.appirio.supply.constants.MemberStatus;
import com.appirio.supply.dataaccess.FileInvocationHandler;
import com.appirio.supply.dataaccess.queryhandler.handler.ValidationHandler;
import com.appirio.tech.core.api.v3.response.ApiResponse;
import com.appirio.tech.core.auth.AuthUser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.validator.routines.EmailValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
/**
* Represents the MemberProfileManager used to manage the user profile data
*
* <p>
* Changes in the version 1.1 (Topcoder Member Service - New Endpoint to Update Email Address Code Challenge v1.0)
* - modify updateMemeberProfile to send the email verificaiton
* - add the verifyUserEmail method
* - modify getMemberProfile so that it does not return the new email information for the anonymous user
* </p>
*
* @author TCCoder
* @version 1.1
*
*/
public class MemberProfileManager {
/**
* The role name for admin
*/
public static final String ADMINISTRATOR = "administrator";
/**
* Logger for the class
*/
private Logger logger = LoggerFactory.getLogger(MemberProfileManager.class);
/**
* DAO for Member profile
*/
private MemberProfileDAO memberProfileDAO;
/**
* DAO for member stats
*/
private MemberStatsDAO memberStatsDAO;
/**
* Photo URL domain
*/
private String photoURLDomain;
/**
* File Invocation handler
*/
private FileInvocationHandler fileInvocationHandler;
/**
* Kafka Event Producer
*/
private EventProducer eventProducer;
/**
* The event bus service client field used to send the event
*/
private final EventBusServiceClient eventBusServiceClient;
/**
* The email verification config field
*/
private final EmailVerificationConfiguration emailVerificationConfig;
/**
* Constructor to initialize member profile DAO and file service domain
*
* @param memberProfileDAO the memberProfileDAO to use
* @param memberStatsDAO the memberStatsDAO to use
* @param photoURLDomain the photoURLDomain to use
* @param fileInvocationHandler the fileInvocationHandler to use
* @param eventProducer the eventProducer to use
* @param eventBusServiceClient the eventBusServiceClient to use
*/
public MemberProfileManager(MemberProfileDAO memberProfileDAO, MemberStatsDAO memberStatsDAO,
String photoURLDomain, FileInvocationHandler fileInvocationHandler,
EventProducer eventProducer, EventBusServiceClient eventBusServiceClient,
EmailVerificationConfiguration emailVerificationConfig) {
this.memberProfileDAO = memberProfileDAO;
this.memberStatsDAO = memberStatsDAO;
this.photoURLDomain = photoURLDomain;
this.fileInvocationHandler = fileInvocationHandler;
this.eventProducer = eventProducer;
this.eventBusServiceClient = eventBusServiceClient;
this.emailVerificationConfig = emailVerificationConfig;
}
/**
* Get Member profile
* @param handle Handle of the user
* @param authUser Authentication user
* @return MemberProfile Member profile
* @throws SupplyException Exception for supply
*/
public MemberProfile getMemberProfile(String handle, AuthUser authUser) throws SupplyException {
MemberProfile memberProfile = memberProfileDAO.validateHandle(handle, authUser, true);
MemberStats memberStats = memberStatsDAO.getMemberStats(memberProfile.getUserId());
if(memberStats != null && memberStats.getMaxRating() != null) {
memberProfile.setMaxRating(memberStats.getMaxRating());
}
// if user is not logged in
// if user is not admin user && not asking for my own profile
if (authUser == null || !(isAdmin(authUser) || memberProfile.getUserId().equals(
Integer.valueOf(authUser.getUserId().toString())))) {
memberProfile.setAddresses(null);
memberProfile.setEmail(null);
memberProfile.setFirstName(null);
memberProfile.setLastName(null);
memberProfile.setOtherLangName(null);
memberProfile.setNewEmail(null);
memberProfile.setEmailVerifyToken(null);
memberProfile.setEmailVerifyTokenDate(null);
}
return memberProfile;
}
/**
* Update member profile
*
* @param handle Handle of the user
* @param authUser Authentication user
* @param memberProfile Member profile
* @return MemberProfile Member profile
* @throws SupplyException if any error occurs
* @throws IllegalAccessException if any error occurs
* @throws InvocationTargetException if any error occurs
* @throws InstantiationException if any error occurs
* @throws NoSuchMethodException if any error occurs
*/
public MemberProfile updateMemberProfile(String handle, AuthUser authUser, MemberProfile memberProfile) throws
IllegalAccessException, NoSuchMethodException, InstantiationException, SupplyException,
InvocationTargetException, JsonProcessingException {
MemberProfile existingMemberProfile = memberProfileDAO.validateHandle(handle, authUser, false);
boolean verifyEmail = false;
if (!existingMemberProfile.getEmail().equals(memberProfile.getEmail())) {
verifyEmail = true;
if (!EmailValidator.getInstance().isValid((String) memberProfile.getEmail())) {
throw new SupplyException("The email is invalid:" + memberProfile.getEmail(), HttpServletResponse.SC_BAD_REQUEST);
} else {
String token = RandomStringUtils.randomAlphanumeric(16);
memberProfile.setNewEmail((String) memberProfile.getEmail());
memberProfile.setEmail((String) existingMemberProfile.getEmail());
memberProfile.setEmailVerifyToken(token);
memberProfile.setEmailVerifyTokenDate(new Date());
}
}
memberProfile.setUserId(Integer.valueOf(authUser.getUserId().toString()));
memberProfile.setCreatedBy(existingMemberProfile.getCreatedBy());
memberProfile.setCreatedAt(existingMemberProfile.getCreatedAt());
memberProfile.setUpdatedBy(authUser.getUserId().toString());
memberProfile.setUpdatedAt(new Date());
memberProfile.setStatus(MemberStatus.ACTIVE.toString());
memberProfile.setHandleLower(memberProfile.getHandle().toLowerCase());
memberProfileDAO.updateMemberProfile(memberProfile, true);
// fire event on to the kafka bus to update member profile
ObjectMapper mapper = new ObjectMapper();
publishKafkaEvent(mapper.valueToTree(memberProfile), "member-profile-update-event");
if (memberProfile.getPhotoURL() == null) {
// Delete image from informix
// Create MemberProfilePhotoUpdateEvent object to publish to Kafka bus for informix update
MemberProfilePhotoUpdateEvent eventObj = new
MemberProfilePhotoUpdateEvent(memberProfile.getUserId(), memberProfile.getPhotoURL());
publishKafkaEvent(mapper.valueToTree(eventObj), "member-profile-photo-update-event");
}
if (verifyEmail) {
this.fireEmailVerificationEvent(authUser, memberProfile);
}
MemberProfile result = memberProfileDAO.getMemberProfile(handle);
result.setEmailVerifyToken(null);
result.setEmailVerifyTokenDate(null);
return result;
}
/**
* Verify user email
*
* @param handle the handle to use
* @param authUser the authUser to use
* @param newEmail the newEmail to use
* @param oldEmail the oldEmail to use
* @param token the token to use
* @throws SupplyException if any error occurs
* @throws IllegalAccessException if any error occurs
* @throws InvocationTargetException if any error occurs
* @throws InstantiationException if any error occurs
* @throws NoSuchMethodException if any error occurs
*/
public void verifyUserEmail(String handle, AuthUser authUser, String newEmail, String oldEmail, String token) throws SupplyException,
IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException{
MemberProfile profile = memberProfileDAO.validateHandle(handle, authUser, false);
if (!handle.equals(profile.getHandle())) {
throw new SupplyException("Please login by yourself", HttpServletResponse.SC_BAD_REQUEST);
}
if (profile.getNewEmail() == null || profile.getEmailVerifyToken() == null || profile.getEmailVerifyTokenDate() == null) {
throw new SupplyException("There is no email to verify", HttpServletResponse.SC_BAD_REQUEST);
}
if (!profile.getEmail().equals(oldEmail)) {
throw new SupplyException("The old email does not match:" + oldEmail, HttpServletResponse.SC_BAD_REQUEST);
}
if (!profile.getNewEmail().equals(newEmail)) {
throw new SupplyException("The new email does not match:" + newEmail, HttpServletResponse.SC_BAD_REQUEST);
}
if (!profile.getEmailVerifyToken().equals(token)) {
throw new SupplyException("The token does not match:" + token, HttpServletResponse.SC_BAD_REQUEST);
}
profile.setNewEmail(null);
profile.setEmailVerifyToken(null);
if (new Date().getTime() - profile.getEmailVerifyTokenDate().getTime() >= 1000 * 60 * this.emailVerificationConfig.getTokenExpireTimeInMinutes()) {
profile.setEmailVerifyTokenDate(null);
memberProfileDAO.updateMemberProfile(profile, true);
throw new SupplyException("The token is expired, please verify the email again", HttpServletResponse.SC_BAD_REQUEST);
}
// the token is valid
profile.setEmail(newEmail);
profile.setEmailVerifyTokenDate(null);
memberProfileDAO.updateMemberProfile(profile, true);
}
/**
* Fire email verification event
*
* @param authUser the authUser to use
* @param verificationToken the verificationToken to use
*/
private void fireEmailVerificationEvent(AuthUser authUser, MemberProfile profile) {
EventMessage msg = new EventMessage();
msg.setTopic("member.action.email.profile.emailchange.verification").setMimeType("application/json").setOriginator("tc-member-profile").setTimestamp(new Date());
Map<String, String> data = new LinkedHashMap<String, String>();
data.put("subject", this.emailVerificationConfig.getSubject());
data.put("userHandle", authUser.getHandle());
data.put("verificationAgreeUrl", this.emailVerificationConfig.getVerificationAgreeUrl());
data.put("verificationToken", profile.getEmailVerifyToken());
List<String> recipients = new ArrayList<String>();
recipients.add(profile.getNewEmail());
msg.setPayload("data", data);
msg.setPayload("recipients", recipients);
this.eventBusServiceClient.fireEvent(msg);
}
/**
* Validate and return content type
* @param photoContentType photo content type
* @return String type
*/
private String validateContentType(PhotoContentType photoContentType) throws IllegalAccessException,
InvocationTargetException, InstantiationException, SupplyException, NoSuchMethodException {
List<String> validationMessages = photoContentType.validate();
ValidationHandler.validationException(validationMessages);
return photoContentType.getContentType().split("/")[1];
}
/**
* Validate and return content type
* @param photoTokenContentType photo token
* @return String content type
*/
private String validateToken(PhotoTokenContentType photoTokenContentType) throws SupplyException,
InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
List<String> validationMessages = photoTokenContentType.validate();
ValidationHandler.validationException(validationMessages);
PhotoContentType photoContentType = new PhotoContentType();
photoContentType.setContentType(photoTokenContentType.getContentType());
return validateContentType(photoContentType);
}
/**
* Generate photoUploadUrl
* @param handle Handle of the user
* @param authUser Authentication user
* @return String Photo URL
* @throws Exception Exception
*/
public PhotoTokenURL generatePhotoUploadUrl(String handle, AuthUser authUser,
PhotoContentType photoContentType) throws Exception {
memberProfileDAO.validateHandle(handle, authUser, false);
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date formateDate = df.parse(df.format(date));
long token = formateDate.getTime();
String type = validateContentType(photoContentType);
logger.debug("Image type : " + type);
String fileName = handle + "-" + token + "." + type;
String filePath = "member/profile/" + fileName;
logger.debug("File path : " + filePath);
ApiResponse res = fileInvocationHandler.makeRequest(authUser, filePath, "/uploadurl", "post",
photoContentType.getContentType(), true);
JSONObject response = new JSONObject(res);
JSONObject result = response.getJSONObject("result");
JSONObject content = result.getJSONObject("content");
PhotoTokenURL photoTokenURL = new PhotoTokenURL();
photoTokenURL.setPreSignedURL(content.getString("preSignedURL"));
photoTokenURL.setToken(token);
return photoTokenURL;
}
/**
* Update photo URL
* @param handle Handle of the user
* @param authUser Authentication user
* @param photoTokenContentType Photo token and content type
*/
public String updatePhoto(String handle, AuthUser authUser, PhotoTokenContentType photoTokenContentType)
throws SupplyException, NoSuchMethodException, InstantiationException, IllegalAccessException,
InvocationTargetException, JsonProcessingException, UnsupportedEncodingException {
memberProfileDAO.validateHandle(handle, authUser, false);
MemberProfile memberProfile = memberProfileDAO.getMemberProfile(handle);
memberProfile.setUpdatedBy(authUser.getUserId().toString());
memberProfile.setUpdatedAt(new Date());
String type = validateToken(photoTokenContentType);
logger.debug("Image type : " + type);
String fileName = handle + "-" + photoTokenContentType.getToken() + "." + type;
String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
logger.debug("Encoded file name : " + encodedFileName);
String photoURL = photoURLDomain + "/member/profile/" + encodedFileName;
logger.debug("Photo URL : " + photoURL);
memberProfile.setPhotoURL(photoURL);
memberProfileDAO.updateMemberProfile(memberProfile, false);
// Create MemberProfilePhotoUpdateEvent object to publish to Kafka bus for Informix update
MemberProfilePhotoUpdateEvent eventObj = new
MemberProfilePhotoUpdateEvent(memberProfile.getUserId(), photoURL);
ObjectMapper mapper = new ObjectMapper();
publishKafkaEvent(mapper.valueToTree(eventObj), "member-profile-photo-update-event");
return photoURL;
}
/**
* fireKafkaEvent publishes profile update events on to the kafka bus
*
* @param json Json string
* @param topic Topic name
*/
private void publishKafkaEvent(JsonNode json, String topic) {
// fire an event on to the kafka bus
try {
eventProducer.publish(topic, json);
} catch (EmptyEventException e) {
logger.info("Failed to publish message " + e.getMessage());
} catch (EncodingEventException e) {
logger.info("Event Encoding Error " + e.getMessage());
}
}
/**
* Check whether given role has administrator role.
* @param user the auth user
* @return true if user is not null and has administrator role
*/
private static boolean isAdmin(AuthUser user){
return user != null && user.hasRole(ADMINISTRATOR);
}
}
|
package commandLineMenus.examples.employees.core;
import java.io.Serializable;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
public class Department implements Serializable, Comparable<Department>
{
private static final long serialVersionUID = 1L;
private String name;
private SortedSet<Employee> employees;
private Employee administrator;
public Department(String name)
{
this.name = name;
employees = new TreeSet<>();
administrator = ManageEmployees.getManageEmployees().getRoot();
ManageEmployees.getManageEmployees().add(this);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Employee getAdministrator()
{
return administrator;
}
public void setAdministrator(Employee administrator)
{
Employee root = ManageEmployees.getManageEmployees().getRoot();
if (administrator != root && administrator.getDepartment() != this)
throw new InsufficientRightsException();
this.administrator = administrator;
}
public SortedSet<Employee> getEmployes()
{
return Collections.unmodifiableSortedSet(employees);
}
public Employee addEmploye(String lastName, String firstName, String mail, String password)
{
Employee employee = new Employee(this, lastName, firstName, mail, password);
employees.add(employee);
return employee;
}
void remove(Employee employe)
{
employees.remove(employe);
}
public void remove()
{
ManageEmployees.getManageEmployees().remove(this);
}
@Override
public int compareTo(Department other)
{
return getName().compareTo(other.getName());
}
@Override
public String toString()
{
return name;
}
}
|
package com.ConfigPoste.RecetteCuisine.RecetteCuisine.services;
import java.io.IOException;
public class FileStorageException extends Exception {
public FileStorageException(String s) {
super(s);
}
public FileStorageException(String s, IOException e) {
super(s,e);
}
}
|
package com.shangdao.phoenix.util;
import com.shangdao.phoenix.enums.ExceptionResultEnum;
public class OutsideRuntimeException extends RuntimeException {
private int code;
private Object error;
public OutsideRuntimeException(int code,Object error){
super(error.toString());
this.error = error;
this.code = code;
}
public OutsideRuntimeException(ExceptionResultEnum exceptionResultEnum){
this.code = exceptionResultEnum.getCode();
this.error = exceptionResultEnum.getMessage();
}
public OutsideRuntimeException(ExceptionResultEnum exceptionResultEnum,String message){
this.code = exceptionResultEnum.getCode();
this.error = exceptionResultEnum.getMessage() + message;
}
public OutsideRuntimeException(String message,ExceptionResultEnum exceptionResultEnum){
this.code = exceptionResultEnum.getCode();
this.error = message + exceptionResultEnum.getMessage();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Object getError() {
return error;
}
public void setError(Object error) {
this.error = error;
}
}
|
package com.jgw.supercodeplatform.trace.config;
import java.nio.charset.StandardCharsets;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
/**
* restTempalte配置类
* @author liujianqiang
* @date 2018年9月13日
*/
@Configuration
public class RestTemplateConfig {
@Bean(name="restTemplate")
@LoadBalanced
public RestTemplate restTemplateBalance() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
@Bean(name="restTemplate2")
//@LoadBalanced
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
}
|
package cn.vaf714.entity;
public class Cart {
private String userName;
private String commodityId;
private int buyNum;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCommodityId() {
return commodityId;
}
public void setCommodityId(String commodityId) {
this.commodityId = commodityId;
}
public int getBuyNum() {
return buyNum;
}
public void setBuyNum(int buyNum) {
this.buyNum = buyNum;
}
public Cart(String userName, String commodityId, int buyNum) {
super();
this.userName = userName;
this.commodityId = commodityId;
this.buyNum = buyNum;
}
public Cart() {
super();
}
}
|
package com.ayt.dataprovider;
/**
* @Auther: ayt
* @Date: 2018/8/19 23:22
* @Description: Don't worry ,just try
*/
import org.testng.ITestContext;
import org.testng.annotations.DataProvider;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import java.lang.reflect.Method;
import java.util.Random;
public class DataProvider1{
/**
* 但是dataProvider作为数据提供者只能返回Object[][]和Iterator<Object[]>类型的数据
* @return
*/
@DataProvider(name = "create")
public Object[][] dataCreate(){
int lower=5;
int upper=10;
return new Object[][]{
{lower-1,lower,upper,false},
{lower, lower, upper, true},
};
}
/**
* 数据提供者本身可以接受两个类型的参数:Method和ITestContext
* method:
* 数据提供者代码相当复杂,应该保存在一个地方,这样维护起来更方便。
我们要传入数据的那些测试方法具有许多参数,其中只有少数参数是不一样的。
我们引入了某个方法的特殊情况。
* @param method
* @return
*/
@DataProvider(name="create1")
public Object[][] provideNumbers(Method method){
String methodName = method.getName();
if (methodName.equals("two")){
return new Object[][]{new Object[] {2}};
}
if (methodName.equals("three")){
return new Object[][]{new Object[] {3}};
}
return null;
}
/**
* ITestContext参数
如果一个数据提供者在方法签名中声名了一个ITestContext类型的参数,
TestNG就会将当前的测试上下文设置给它,这使得数据提供者能够知道当前测试执行的运行时刻参数。
* @param iTestContext
* @return
*/
@DataProvider(name ="create2")
public Object[][] randomIntegers(ITestContext iTestContext) {
String[] groups = iTestContext.getIncludedGroups();
int size = 2;
for (String group : groups
) {
if (group.equals("functional-test")) {
size = 10;
break;
}
}
Object[][] result = new Object[size][];
Random random = new Random();
for (int i = 0; i < size; i++) {
result[i] = new Object[]{
new Integer(random.nextInt())
};
}
return result;
}
}
|
package org.rc.rclibrary.utils;
/**
* Description:
* Author: WuRuiqiang(263454190@qq.com)
* Date: 2015-06-02 17:15
*/
public class RegularUtil {
public static String getMobileValidator() {
return "^([1][3|5|7|8]\\d{9})|([6]\\d{5})$";
}
public static String getEmailValidator() {
return "\\w+@(\\w+.)+[a-z]{2,3}";
}
public static String getNotNullValidator() {
return "^\\S+$";
}
public static String getUserNameValidator() {
return "^\\w{5,15}$";
}
public static String getPassWordValidator() {
return "^[a-z0-9A-Z\\._]{6,16}$";
}
}
|
package com.junyoung.searchwheretogoapi.config;
import com.junyoung.searchwheretogoapi.service.place.DefaultMapSearchCounter;
import com.junyoung.searchwheretogoapi.service.place.SearchCounter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CounterConfiguration {
@ConditionalOnMissingBean(SearchCounter.class)
@Bean
public DefaultMapSearchCounter searchCounter() {
return new DefaultMapSearchCounter();
}
}
|
package com.staniul.teamspeak.modules.torunament;
import com.staniul.teamspeak.commands.CommandResponse;
import com.staniul.teamspeak.commands.Teamspeak3Command;
import com.staniul.teamspeak.modules.torunament.data.TournamentPlayer;
import com.staniul.teamspeak.modules.torunament.data.TournamentTeam;
import com.staniul.teamspeak.query.Channel;
import com.staniul.teamspeak.query.Client;
import com.staniul.teamspeak.query.Query;
import com.staniul.teamspeak.query.QueryException;
import com.staniul.teamspeak.query.channel.ChannelProperties;
import com.staniul.teamspeak.security.clientaccesscheck.ClientGroupAccess;
import com.staniul.xmlconfig.CustomXMLConfiguration;
import com.staniul.xmlconfig.annotations.UseConfig;
import com.staniul.xmlconfig.annotations.WireConfig;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;
@Component
@UseConfig("modules/tournament.xml")
public class TournamentChannelCreator {
private final Query query;
@WireConfig
private CustomXMLConfiguration config;
public TournamentChannelCreator(Query query) {
this.query = query;
}
private JdbcTemplate getJdbcTemplate() {
DriverManagerDataSource dataSource = new DriverManagerDataSource(config.getString("jdbc.url"), config.getString("jdbc.login"), config.getString("jdbc.password"));
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
return new JdbcTemplate(dataSource);
}
@Teamspeak3Command("!ctc")
@ClientGroupAccess("servergroups.headadmins")
public CommandResponse createTournamentChannelsCommand(Client client, String params) throws QueryException {
createTournamentChannelsInner();
return new CommandResponse(config.getString("messages.create.successful"));
}
private void createTournamentChannelsInner () throws QueryException {
final JdbcTemplate jdbcTemplate = getJdbcTemplate();
List<TournamentTeam> teams = jdbcTemplate.query(config.getString("query"), TournamentTeam.rowMapper());
for (TournamentTeam tournamentTeam : teams) {
tournamentTeam.setPlayers(
jdbcTemplate.query(config.getString("queryTeammates"), new Object[]{tournamentTeam.getName()}, TournamentPlayer.rowMapper())
);
}
List<Channel> channels = query.getChannelList();
List<Channel> subchannels = channels.stream()
.filter(channel -> channel.getParentId() == config.getInt("parentChannelId"))
.collect(Collectors.toList());
Channel parentchannel = channels.stream()
.filter(channel -> channel.getId() == config.getInt("parentChannelId"))
.findFirst()
.orElse(null);
if (parentchannel == null) throw new IllegalStateException("Parent channel for tournaments not found!");
String channelName = config.getString("parentChannelName").replace("%TEAM_COUNT%", Integer.toString(teams.size()));
if (!parentchannel.getName().equalsIgnoreCase(channelName))
query.channelRename(channelName, parentchannel.getId());
for (TournamentTeam tournamentTeam : teams) {
Channel channel = subchannels.stream()
.filter(channel1 -> channel1.getName().equalsIgnoreCase(tournamentTeam.getName().length() > 40 ? tournamentTeam.getName().substring(0, 40) : tournamentTeam.getName()))
.findFirst()
.orElse(null);
if (channel == null) {
ChannelProperties properties = new ChannelProperties()
.setName(tournamentTeam.getName())
.setParent(config.getInt("parentChannelId"))
.setDescription(
config.getString("channel.description")
.replace("%TEAM_NAME%", tournamentTeam.getName())
.replace("%TEAM_SQUAD%", tournamentTeam.getPlayers().stream()
.map(tp -> String.format("%s [b]%s[/b] (%s)", tp.getName(), tp.getNickname(), tp.getPosition()))
.collect(Collectors.joining("\n")))
)
.setTopic(config.getString("channel.topic").replace("%TEAM_NAME%", tournamentTeam.getName()))
.setCodec(4)
.setCodecQuality(10)
.setMaxClients(5)
.setMaxFamilyClients(5);
try {
query.channelCreate(properties);
} catch (QueryException e) {
if (e.getErrorId() != 771) throw e;
}
}
else {
String description = config.getString("channel.description")
.replace("%TEAM_NAME%", tournamentTeam.getName())
.replace("%TEAM_SQUAD%", tournamentTeam.getPlayers().stream()
.map(tp -> String.format("%s [b]%s[/b] (%s)", tp.getName(), tp.getNickname(), tp.getPosition()))
.collect(Collectors.joining("\n")));
query.channelChangeDescription(description, channel.getId());
}
}
}
}
|
package domain;
public class VerkoopbaarBeeldhouwwerk extends Beeldhouwwerk implements Verkoopbaar {
private double waarde;
public VerkoopbaarBeeldhouwwerk(String titel, String uitvoerder, double gewicht, String materiaal, double waarde) throws DomainException {
super(titel, uitvoerder, gewicht, materiaal);
if (waarde < 0) throw new DomainException("");
this.waarde = waarde;
}
@Override
public void setVerkocht() {
this.isVerkocht = true;
}
@Override
public double getPrijs() {
return waarde * 1.15;
}
@Override
public boolean isUitleenbaar() {
return !isVerkocht() && super.isUitleenbaar();
}
@Override
public String toString() {
return "VerkoopbaarBeeldhouwwerk{" + super.toString() +
"waarde=" + waarde +
'}';
}
}
|
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
public class Count {
/**
* @author Younes Karim
* // count the sale revenue from array taken from the database
**/
public static void countTheMoney() throws SQLException, ClassNotFoundException {
Database.calculateSale();
if (Database.pizzaSale != 0){
System.out.println("The Total sale revenue for all pizzas sold is: " + Database.getPizzaSale() + ",- kr.\n");
} else {
System.out.println(Menu.RED+"Database Error! [6] - Try placing an order first\n"+Menu.RESET);
}
}
/**
* @author Younes Karim
* // Calculate the statistics for every pizza sold in percentage, read from the database and then fed into a String array
* // Super hardcoded i dont know how to do it otherwise
**/
public static void countTheStats(ArrayList<String> stats) throws SQLException, ClassNotFoundException {
String sold = " Sale equals to -----";
Database.pizzaList(stats);
if (!stats.isEmpty()){
System.out.println("//// The most sold pizza in percentage ////\n");
double a1 = Collections.frequency(stats, "Vesuvio");
System.out.println("[1]: Vesuvio:" + sold +"------> ["+ roundDown((a1 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Vesuvio"));
double a2 = Collections.frequency(stats, "Amerikaner");
System.out.println("[2]: Amerikaner:" + sold +"---> ["+ roundDown((a2 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Amerikaner"));
double a3 = Collections.frequency(stats, "Caccoatore");
System.out.println("[3]: Caccoatore:" + sold +"---> ["+ roundDown((a3 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Caccoatore"));
double a4 = Collections.frequency(stats, "Carbona");
System.out.println("[4]: Carbona:" + sold +"------> ["+ roundDown((a4 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Carbona"));
double a5 = Collections.frequency(stats, "Dennis");
System.out.println("[5]: Dennis:" + sold +"-------> ["+ roundDown((a5 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Dennis"));
double a6 = Collections.frequency(stats, "Bertil");
System.out.println("[6]: Bertil:" + sold +"-------> ["+ roundDown((a6 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Bertil"));
double a7 = Collections.frequency(stats, "Silvia");
System.out.println("[7]: Silvia:" + sold +"-------> ["+ roundDown((a7 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Silvia"));
double a8 = Collections.frequency(stats, "Victoria");
System.out.println("[8]: Victoria:" + sold +"-----> ["+ roundDown((a8 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Victoria"));
double a9 = Collections.frequency(stats, "Toronfo");
System.out.println("[9]: Toronfo:" + sold +"------> ["+ roundDown((a9 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Toronfo"));
double a10 = Collections.frequency(stats, "Capricciosa");
System.out.println("[10]: Capricciosa:" + sold +"-> ["+ roundDown((a10 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Capricciosa"));
double a11 = Collections.frequency(stats, "Hawaii");
System.out.println("[11]: Hawaii:" + sold +"------> ["+ roundDown((a11 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Hawaii"));
double a12 = Collections.frequency(stats, "Le Blissola");
System.out.println("[12]: Le Blissola:" + sold +"-> ["+ roundDown((a12 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Le Blissola"));
double a13 = Collections.frequency(stats, "Venezia");
System.out.println("[13]: Venezia:" + sold +"-----> ["+ roundDown((a13 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Venezia"));
double a14 = Collections.frequency(stats, "Mafia");
System.out.println("[14]: Mafia:" + sold +"-------> ["+ roundDown((a14 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Mafia"));
double a15 = Collections.frequency(stats, "Mario");
System.out.println("[15]: Mario:" + sold +"-------> ["+ roundDown((a15 / stats.size()) * 100) + "]% and the amount is: "+ Collections.frequency(stats, "Mario"));
System.out.println("\nThe Total amount of pizzas sold is: ["+stats.size() +"]");
countTheMoney();
} else {
System.out.println(Menu.RED+"Database Error! [6] - Try placing an order first\n"+Menu.RESET);
}
}
/**
* @author phuclv @Stackoverflow
* // function that allows us to input a double and round it down into a two digit number
**/
static double roundDown(double unroundedNumber){
int truncatedNumberInt = (int)( unroundedNumber * Math.pow( 10, 2) );
return truncatedNumberInt / Math.pow( 10, 2);
}
/**
* @author Younes Karim
* // Get the current date and time
**/
public static String getdate() {
LocalDateTime date = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yy @ HH:mm");
return date.format(format);
}
}
|
package com.github.banner;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
/***
* created by android on 2019/4/16
*/
public class BannerRecyclerView extends RecyclerView {
private boolean useGesture=true;
public BannerRecyclerView(@NonNull Context context) {
super(context);
}
public BannerRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public BannerRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public boolean isUseGesture() {
return useGesture;
}
public void setUseGesture(boolean useGesture) {
this.useGesture = useGesture;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if(this.useGesture) {
return super.onTouchEvent(ev);
} else {
return false;
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if(this.useGesture) {
return super.onInterceptTouchEvent(ev);
} else {
return false;
}
}
}
|
package ciphers;
public class ShiftCipher implements Cipher{
private final char[] ALPHABET = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
// private final int CEASAR = 3;
private int key = 3;
public String shiftEncrypt(String plaintext) {
return shift(plaintext, 0);
}
public String shiftDecrypt(String plaintext) {
return shift(plaintext, 1);
}
/**
* Dịch chuyển các ký tự trong một chuỗi bằng Mã hóa dịch chuyển.
*
* @param plant text
* @param typeCrypt: 0 -> encrypt, 1 -> decrypt
* @return cipher text
*/
public String shift(String plaintext, int typeCrypt) {
if (plaintext == null || plaintext.trim().isEmpty())
throw new NullPointerException("Plaintext is null or empty");
char[] letters = plaintext.toCharArray();
char[] result = new char[letters.length];
for (int i = 0; i < letters.length; i++) {
result[i] = isAlphabet(letters[i])
? (typeCrypt == 0 ? encryptLetter(letters[i]) : decryptletter(letters[i]))
: letters[i];
}
return new String(result);
}
private char encryptLetter(char letter) {
return cryptLetter(letter, 0);
}
private char decryptletter(char letter) {
return cryptLetter(letter, 1);
}
/**
* Dịch chuyển ký tự trong alphabet
*
* @param vd:A, b, C, 1
* @return vd:X, y, Z, 1
*/
private char cryptLetter(char letter, int typeCrypt) {
char upLetter = toUppercase(letter);
int alphabetNum = alphabetNum(upLetter);
char newLetter = 0;
if (alphabetNum != -1) {
if (typeCrypt == 0) { // encrypt
// index more than 23 -> index + CEASAR - 26, else -> 26 - index
// sample: index = 24 -> new index = 24 + 3 - 26 = 1
newLetter = (alphabetNum < (ALPHABET.length - this.key))
? ALPHABET[alphabetNum + this.key]
: ALPHABET[alphabetNum + this.key - ALPHABET.length];
} else { // decrypt
// index less than 3 -> 26 + index - 3, else -> index + CEASAR
// sample: index = 2 -> new index = 26 + 2 - 3 = 25
newLetter = (alphabetNum >= (this.key))
? ALPHABET[alphabetNum - this.key]
: ALPHABET[ALPHABET.length + alphabetNum - this.key];
}
}
return upLetter == letter ? newLetter : Character.toLowerCase(newLetter);
}
/**
*
* @param a, b, c
* @return A, B, C
*/
private char toUppercase(char letter) {
if (letter >= 'a' || letter <= 'z')
return Character.toUpperCase(letter);
return letter;
}
/**
* get index of letter in ALPHABET
*
* @param letter
* @return 0-25 || -1(No Exist)
*/
private int alphabetNum(char letter) {
for (int i = 0; i < ALPHABET.length; i++)
if (ALPHABET[i] == letter)
return i;
return -1;
}
private boolean isAlphabet(char letter) {
return ((letter >= 'a' && letter <= 'z') || (letter >= 'A' && letter <= 'Z'));
}
public static void main(String[] args) {
ShiftCipher sc = new ShiftCipher();
String letters = "ABC--18130035 Phung Minh Dat--GHJ XYZ";
String newLetter = sc.shiftEncrypt(letters);
System.out.println("Encrypt: " + letters + " -> " + newLetter);
String oldLetter = sc.shiftDecrypt(newLetter);
System.out.println("Decrypt: " + newLetter + " -> " + oldLetter);
}
public int getKey() {
return key;
}
public ShiftCipher setKey(int key) {
this.key = key;
return this;
}
@Override
public String encrypt(String plaintext) {
return this.shiftEncrypt(plaintext);
}
@Override
public String decrypt(String ciphertext) {
return this.shiftDecrypt(ciphertext);
}
}
|
package com.ytflogin.mvp.view;
/**
* step②
* Created by ytf on 2018/2/26.
* 一个页面对应一个view层接口,提供获取数据的方法
* View层的任务就是抽象页面的数据,提取出来写成方法
*/
public interface IUserView {
// 提供获取用户名和密码信息的数据接口方法
public String getUserName();
public String getPwd();
}
|
package LeetCode;
import java.util.ArrayList;
import java.util.List;
public class SurroundedRegions {
public static void main(String[] args) {
SurroundedRegions solution = new SurroundedRegions();
char[][] board = new char[][] { {'X','O','X','X'},
{'X', 'O', 'O', 'X'},
{'X','X','O','X'},
{'X','O','X','X'}};
solution.solve(board);
for (char[] row : board) for (char c : row) System.out.println(c);
}
/*
* Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example:
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
Explanation:
Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.
Idea:
- Pre-process - Iterate around border and BFS from every 'O' flipping to a 'Z' that we will flip back to 'O' in post-processing step
- Process - Iterate through the grid starting at [1,1] flipping all 'O's with 'X'
- Post-process - Iterate through grid swtiching all Z's back to O's
Possible improvements: store all Z's so that we can more quickly change them back to Os (faster but more memory)
* */
public void solve(char[][] board) {
if (board.length == 0) return;
if (board[0].length == 0) return;
int cols = board[0].length;
int rows = board.length;
//Pre-Process
//top and bottom rows
for (int i = 0; i < cols; i++) {
if (board[0][i] == 'O') bfs(board, new Coordinate(i, 0));
if (board[rows-1][i] == 'O') bfs(board, new Coordinate(i, rows-1));
}
//left and right columns
for (int i = 0; i < board.length; i++) {
if (board[i][0] == 'O') bfs(board, new Coordinate(0, i));
if (board[i][cols-1] == 'O') bfs(board, new Coordinate(0, cols-1));
}
//Process + Post-process steps
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
board[i][j] = board[i][j] == 'O' ? 'X' : board[i][j];
board[i][j] = board[i][j] == 'Z' ? 'O' : board[i][j];
}
}
}
private void bfs(char[][] board, Coordinate coord) {
board[coord.y][coord.x] = 'Z';
List<Coordinate> coords = new ArrayList<>();
coords.add(new Coordinate(coord.x-1, coord.y));
coords.add(new Coordinate(coord.x+1, coord.y));
coords.add(new Coordinate(coord.x, coord.y-1));
coords.add(new Coordinate(coord.x, coord.y+1));
for (Coordinate next : coords) {
if (next.x >= 0 && next.x < board[0].length && next.y >= 0 && next.y < board.length && board[next.y][next.x] == 'O') {
bfs(board, next);
}
}
}
private class Coordinate {
int x;
int y;
Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
}
|
package com.gsccs.sme.shiro.client;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.subject.PrincipalCollection;
import com.gsccs.sme.api.service.AccountServiceI;
/**
* 单点登录
*/
public class ClientCasRealm extends CasRealm {
private AccountServiceI accountAPI;
private String appKey;
public void setAppKey(String appKey) {
System.out.println("APPKEY:" + appKey);
this.appKey = appKey;
}
public String getAppKey() {
return appKey;
}
public AccountServiceI getAccountAPI() {
return accountAPI;
}
public void setAccountAPI(AccountServiceI accountAPI) {
this.accountAPI = accountAPI;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
String username = (String) principals.getPrimaryPrincipal();
System.out.println("*******************");
System.out.println("** " + username + " **");
System.out.println("*******************");
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
// authorizationInfo.setRoles(userService.findRoles(username));
// authorizationInfo.setStringPermissions(userService.findPermissions(username));
return authorizationInfo;
}
}
|
package com.example.daraz_application.api;
import com.example.daraz_application.Model.Users;
import com.example.daraz_application.Model.product;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface UsersAPI {
@GET("daraz_products")
Call<List<Users>> getallItem();
@GET("daraz_products")
// Call<List<Products>> getallProducts();
Call<List<product>> getallProduct();
}
|
package controller;
import ejb.PersonaFacadeLocal;
import entity.Persona;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
@Named(value = "personaController")
@SessionScoped
public class PersonaController implements Serializable{
@EJB
private PersonaFacadeLocal personaEJB;
private Persona persona;
private List<Persona> lista;
public List<Persona> getLista(){
return lista;
}
public void setLista(List<Persona> lista){
this.lista = lista;
}
public Persona getPersona(){
return persona;
}
public void setPersona(Persona persona){
this.persona = persona;
}
@PostConstruct
public void init(){
persona = new Persona();
}
public void insertar(){
try {
personaEJB.create(persona);
} catch (Exception e) {
}
}
public void listar(){
try {
lista = personaEJB.findAll();
} catch (Exception e) {
}
}
public void leerid(Persona per){
try {
this.persona = per;
} catch (Exception e) {
}
}
public void modificar(){
try {
personaEJB.edit(persona);
lista = personaEJB.findAll();
} catch (Exception e) {
}
}
public void eliminar(Persona per){
this.persona = per;
try {
personaEJB.remove(persona);
lista = personaEJB.findAll();
} catch (Exception e) {
}
}
}
|
package org.sky.sys.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.sky.sys.model.SysArea;
import org.sky.sys.model.SysAreaExample;
import org.sky.sys.service.SysAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @ClassName: SysAreaController
* @Description: TODO(地区级联查询)
* @author AK
* @date 2018-5-4 下午8:27:23
*
*/
@Controller
public class SysAreaController extends BaseController{
@Autowired
private SysAreaService sysAreaService;
/**
* 根据上级地区id获取下级地区列表
* @param pid
* @param request
* @param response
* @return
*/
@RequestMapping(value="/sys/SysArea/listSysAreaByPid/{pid}",method=RequestMethod.POST,produces="application/json;charset=UTF-8")
public @ResponseBody List<SysArea> listSysAreaByPid(@PathVariable("pid") String pid, HttpServletRequest request,HttpServletResponse response){
SysAreaExample example = new SysAreaExample();
example.createCriteria().andPidEqualTo(pid);
example.setOrderByClause("id asc");
List<SysArea> list = sysAreaService.listSysAreaByExample(example);
return list;
}
}
|
package com.cb.cbfunny.bean;
import java.io.Serializable;
import java.util.ArrayList;
/**
* 描述:
* Created by zhaohl on 2015-9-21.
*/
public class GIFDataList implements Serializable {
private ArrayList<GIFDrawable> GifDrawableList;
private long lastUpdataTime;
public void updateDownloadTime(){
lastUpdataTime = System.currentTimeMillis();
}
/**
* 是否需要更新 间隔时间20分钟
* @return
*/
public boolean needUpdate(){
return System.currentTimeMillis()-lastUpdataTime>1200000;
}
public ArrayList<GIFDrawable> getGifDrawableList() {
return GifDrawableList;
}
public void setGifDrawableList(ArrayList<GIFDrawable> gifDrawableList) {
GifDrawableList = gifDrawableList;
}
}
|
package menu;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import main_app.Handler;
import main_app.LampPanel;
import main_app.MainMenuHandler;
public class MainMenu extends Menu {
private static final Color BACKGROUND = new Color(15, 15, 25);
public MainMenu (Handler handler) {
super(handler);
this.buttons.add(new Button(0, LampPanel.PWIDTH / 2 - 150, LampPanel.PHEIGHT / 2 - 100, 300, 60, new Color(15, 150, 50, 30), "Single Player", this));
this.buttons.add(new Button(5, LampPanel.PWIDTH / 2 - 150, LampPanel.PHEIGHT / 2 - 25, 300, 60, new Color(15, 150, 50, 30), "Multiplayer", this));
this.buttons.add(new Button(1, LampPanel.PWIDTH / 2 - 150, LampPanel.PHEIGHT / 2 + 50, 300, 60, new Color(15, 150, 50, 30), "Edit World Collisions", this));
this.buttons.add(new Button(3, LampPanel.PWIDTH / 2 - 150, LampPanel.PHEIGHT / 2 + 125, 142, 60, new Color(15, 150, 50, 30), "Client", this));
this.buttons.add(new Button(4, LampPanel.PWIDTH / 2 + 8, LampPanel.PHEIGHT / 2 + 125, 142, 60, new Color(15, 150, 50, 30), "Server", this));
this.buttons.add(new Button(2, LampPanel.PWIDTH / 2 - 150, LampPanel.PHEIGHT / 2 + 200, 300, 60, new Color(15, 150, 50, 30), "Quit", this));
}
@Override
public void execute(int id) {
switch (id) {
case 0:
((MainMenuHandler) handler).startGame();
break;
case 1:
((MainMenuHandler) handler).startWorldCollisionEditor();
break;
case 2:
handler.getPanel().stopGame();
break;
case 3:
((MainMenuHandler) handler).startClient();
break;
case 4:
((MainMenuHandler) handler).startServer();
break;
case 5:
((MainMenuHandler) handler).startMultiplayerGame();
break;
default:
System.out.println("Invalid Button ID");
}
}
public void draw(Graphics g) {
g.setColor(BACKGROUND);
g.fillRect(0, 0, LampPanel.PWIDTH, LampPanel.PHEIGHT);
g.setFont(new Font("Impact", Font.PLAIN, 80));
FontMetrics fm = g.getFontMetrics();
g.setColor(Color.WHITE);
g.drawString("SUPER DUPER LAMP", (int)(LampPanel.PWIDTH / 2 - fm.stringWidth("SUPER DUPER LAMP") / 2), (int)(LampPanel.PHEIGHT / 2 - 160 + (fm.getAscent() / 3)));
super.draw(g);
}
}
|
package com.thoughtworks.ketsu.web;
import com.thoughtworks.ketsu.domain.users.Order;
import com.thoughtworks.ketsu.domain.users.User;
import com.thoughtworks.ketsu.web.jersey.Routes;
import com.thoughtworks.ketsu.web.validators.OrderValidator;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class OrdersApi {
private User user;
public OrdersApi(User user) {
this.user = user;
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response placeOrder(Map<String, Object> info,
@Context Routes routes,
@Context OrderValidator orderValidator) {
orderValidator.validate(info);
return Response.created(routes.orderUrl(user.getId(), user.placeOrder(info).getId())).build();
}
@Path("{id}")
public OrderApi getOrder(@PathParam("id") String id) {
return user.findOrderById(id)
.map(OrderApi::new)
.orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND));
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Order> getAll() {
return user.findAllOrders();
}
}
|
package fi.lyma.minesweeper.logic;
import java.io.Serializable;
/**
* GameMode contains collection of values that are used to store and initialize {@link Minefield}.
*
* @see Minefield
*/
public class GameMode implements Serializable {
public static final GameMode EASY = new GameMode(8, 8, 15);
public static final GameMode MEDIUM = new GameMode(16, 16, 70);
public static final GameMode HARD = new GameMode(18, 18, 85);
private final int fieldWidth, fieldHeight, totalNumberOfMines;
/**
* Constructs GameMode with given parameters.
*
* @param fieldWidth Width of the field
* @param fieldHeight Height of the field
* @param totalNumberOfMines Number of mines in the field
*/
public GameMode(int fieldWidth, int fieldHeight, int totalNumberOfMines) {
this.fieldWidth = fieldWidth;
this.fieldHeight = fieldHeight;
this.totalNumberOfMines = totalNumberOfMines;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GameMode gameMode = (GameMode) o;
if (fieldWidth != gameMode.fieldWidth) {
return false;
}
if (fieldHeight != gameMode.fieldHeight) {
return false;
}
return totalNumberOfMines == gameMode.totalNumberOfMines;
}
@Override
public int hashCode() {
int result = fieldWidth;
result = 31 * result + fieldHeight;
result = 31 * result + totalNumberOfMines;
return result;
}
public int getTotalNumberOfMines() {
return totalNumberOfMines;
}
public int getFieldHeight() {
return fieldHeight;
}
public int getFieldWidth() {
return fieldWidth;
}
@Override
public String toString() {
if (this.equals(EASY)) {
return "Easy";
}
if (this.equals(MEDIUM)) {
return "Medium";
}
if (this.equals(HARD)) {
return "Hard";
}
return String.format("Width: %s, Height: %s, Mines: %s", fieldWidth, fieldHeight, totalNumberOfMines);
}
}
|
package com.android.woong.behaviorsample.vo;
/**
* Created by woong on 2016. 4. 7..
*/
public class MusicVO {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
|
package com.defalt.lelangonline.data;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface RestApi {
// SPLASH ACTIVITY
@Multipart
@POST("/dev/mit/1317003/user_exp.php")
Call<ResponseBody> checkToken(
@Part("token") RequestBody token);
// HOME FRAGMENT
@Multipart
@POST("/dev/mit/1317003/get_auction_best.php")
Call<ResponseBody> getTopAuction(
@Part("desiredCount") RequestBody desiredCount,
@Part("dataOffset") RequestBody dataOffset);
// DETAILS ACTIVITY
@Multipart
@POST("/dev/mit/1317003/get_details.php")
Call<ResponseBody> getDetails(
@Part("auctionID") RequestBody auctionID,
@Part("token") RequestBody token);
@Multipart
@POST("/dev/mit/1317003/get_details_item.php")
Call<ResponseBody> getDetailsItem(
@Part("auctionID") RequestBody auctionID);
@Multipart
@POST("/dev/mit/1317003/get_details_history.php")
Call<ResponseBody> getDetailsHistory(
@Part("desiredCount") RequestBody desiredCount,
@Part("dataOffset") RequestBody dataOffset,
@Part("auctionID") RequestBody auctionID);
@Multipart
@POST("/dev/mit/1317003/create_bid.php")
Call<ResponseBody> postBid(
@Part("auctionID") RequestBody auctionID,
@Part("bidAmount") RequestBody bidAmount,
@Part("token") RequestBody token);
// ITEMS FRAGMENT
@Multipart
@POST("/dev/mit/1317003/get_items.php")
Call<ResponseBody> getItems(
@Part("desiredCount") RequestBody desiredCount,
@Part("dataOffset") RequestBody dataOffset);
@Multipart
@POST("/dev/mit/1317003/get_items_search.php")
Call<ResponseBody> getItemsSearch(
@Part("desiredCount") RequestBody desiredCount,
@Part("dataOffset") RequestBody dataOffset,
@Part("query") RequestBody query);
// AUCTION BY ITEM ACTIVITY
@Multipart
@POST("/dev/mit/1317003/get_auction_by_item.php")
Call<ResponseBody> getAuctionsByItem(
@Part("desiredCount") RequestBody desiredCount,
@Part("dataOffset") RequestBody dataOffset,
@Part("itemID") RequestBody itemID);
// ACCOUNT FRAGMENT
@Multipart
@POST("/dev/mit/1317003/get_profile_by_uid.php")
Call<ResponseBody> getProfileByToken(
@Part("token") RequestBody token);
// PROFILE EDIT ACTIVITY
@Multipart
@POST("/dev/mit/1317003/update_profile.php")
Call<ResponseBody> updateUserWithImage(
@Part("name") RequestBody name,
@Part("phone") RequestBody phone,
@Part("oldPassword") RequestBody oldPassword,
@Part("newPassword") RequestBody newPassword,
@Part("isPasswordChange") RequestBody isPasswordChange,
@Part("isImageEmpty") RequestBody isImageEmpty,
@Part("isImageChange") RequestBody isImageChange,
@Part("token") RequestBody token,
@Part MultipartBody.Part image);
@Multipart
@POST("/dev/mit/1317003/update_profile.php")
Call<ResponseBody> updateUserNoImage(
@Part("name") RequestBody name,
@Part("phone") RequestBody phone,
@Part("oldPassword") RequestBody oldPassword,
@Part("newPassword") RequestBody newPassword,
@Part("isPasswordChange") RequestBody isPasswordChange,
@Part("isImageEmpty") RequestBody isImageEmpty,
@Part("isImageChange") RequestBody isImageChange,
@Part("token") RequestBody token);
// ADD ITEM ACTIVITY
@Multipart
@POST("/dev/mit/1317003/create_item.php")
Call<ResponseBody> postItemWithImage(
@Part("itemName") RequestBody itemName,
@Part("itemDesc") RequestBody itemDesc,
@Part("itemCat") RequestBody itemCat,
@Part("itemVal") RequestBody itemVal,
@Part("isImageEmpty") RequestBody isImageEmpty,
@Part("token") RequestBody token,
@Part MultipartBody.Part image);
@Multipart
@POST("/dev/mit/1317003/create_item.php")
Call<ResponseBody> postItemNoImage(
@Part("itemName") RequestBody itemName,
@Part("itemDesc") RequestBody itemDesc,
@Part("itemCat") RequestBody itemCat,
@Part("itemVal") RequestBody itemVal,
@Part("isImageEmpty") RequestBody isImageEmpty,
@Part("token") RequestBody token);
// ITEM BY USER ACTIVITY
@Multipart
@POST("/dev/mit/1317003/get_items_by_uid.php")
Call<ResponseBody> getItemsByUser(
@Part("desiredCount") RequestBody desiredCount,
@Part("dataOffset") RequestBody dataOffset,
@Part("token") RequestBody token);
@Multipart
@POST("/dev/mit/1317003/remove_item.php")
Call<ResponseBody> removeItem(
@Part("itemID") RequestBody itemID,
@Part("token") RequestBody token);
// ITEM EDIT ACTIVITY
@Multipart
@POST("/dev/mit/1317003/get_item_by_id.php")
Call<ResponseBody> getItemByID(
@Part("itemID") RequestBody itemID);
@Multipart
@POST("/dev/mit/1317003/update_item.php")
Call<ResponseBody> updateItemWithImage(
@Part("itemID") RequestBody itemID,
@Part("itemName") RequestBody itemName,
@Part("itemDesc") RequestBody itemDesc,
@Part("itemCat") RequestBody itemCat,
@Part("itemVal") RequestBody itemVal,
@Part("isImageEmpty") RequestBody isImageEmpty,
@Part("isImageChange") RequestBody isImageChange,
@Part("token") RequestBody token,
@Part MultipartBody.Part image);
@Multipart
@POST("/dev/mit/1317003/update_item.php")
Call<ResponseBody> updateItemNoImage(
@Part("itemID") RequestBody itemID,
@Part("itemName") RequestBody itemName,
@Part("itemDesc") RequestBody itemDesc,
@Part("itemCat") RequestBody itemCat,
@Part("itemVal") RequestBody itemVal,
@Part("isImageEmpty") RequestBody isImageEmpty,
@Part("isImageChange") RequestBody isImageChange,
@Part("token") RequestBody token);
// ADD AUCTION ACTIVITY
@Multipart
@POST("/dev/mit/1317003/get_item_names_by_uid.php")
Call<ResponseBody> getItemNamesByToken(
@Part("token") RequestBody token);
@Multipart
@POST("/dev/mit/1317003/create_auction.php")
Call<ResponseBody> postAuction(
@Part("itemID") RequestBody itemID,
@Part("initPrice") RequestBody initPrice,
@Part("limitPrice") RequestBody limitPrice,
@Part("auctionStart") RequestBody auctionStart,
@Part("auctionEnd") RequestBody auctionEnd,
@Part("token") RequestBody token);
// AUCTION BY USER ACTIVITY
@Multipart
@POST("/dev/mit/1317003/get_auction_by_uid.php")
Call<ResponseBody> getAuctionsByUser(
@Part("desiredCount") RequestBody desiredCount,
@Part("dataOffset") RequestBody dataOffset,
@Part("token") RequestBody token);
}
|
package pro.likada.bean.controller;
import org.primefaces.event.SelectEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pro.likada.bean.backing.CustomerBackingBean;
import pro.likada.bean.model.ContractorModelBean;
import pro.likada.bean.model.CustomerModelBean;
import pro.likada.model.*;
import pro.likada.service.*;
import pro.likada.util.AccessTypeEnum;
import pro.likada.util.ModelConstantEnum;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.FacesEvent;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
/**
* Created by Yusupov on 12/19/2016.
*/
@Named
@RequestScoped
public class CustomerController implements Serializable{
private static final Logger LOGGER = LoggerFactory.getLogger(CustomerController.class);
@Inject
private CustomerService customerService;
@Inject
private CustomerBackingBean customerBackingBean;
@Inject
private CustomerModelBean customerModelBean;
@Inject
private ContractorModelBean contractorModelBean;
@Inject
private ContractorService contractorService;
@Inject
private UserService userService;
@Inject
private LoginController loginController;
@Inject
private ContractorController contractorController;
@Inject
private ContractorOrganizationTypeService contractorOrganizationTypeService;
@Inject
private ContractorAgencyTypeService contractorAgencyTypeService;
/* Delete selected customer in the table from the database, and update table data (customers) */
public void deleteSelectedCustomer(){
if(customerBackingBean.getSelectedCustomer()!=null) {
if(customerBackingBean.getSelectedCustomer().getContractors()!=null || customerBackingBean.getSelectedCustomer().getContractors().size()>0){
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle resourceBundle = ResourceBundle.getBundle("messages", context.getViewRoot().getLocale());
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,resourceBundle.getString("customer.cantDelete"), resourceBundle.getString("customer.hasContractor")));
} else {
LOGGER.info("Delete Customer: {}", customerBackingBean.getSelectedCustomer());
customerService.deleteById(customerBackingBean.getSelectedCustomer().getId());
customerBackingBean.setSelectedCustomer(null);
refreshCustomersTable();
}
}
}
/* Refresh Customers table data (searchStringCustomer is handled in DAO) */
public void refreshCustomersTable(){
LOGGER.info("Refreshing Customers table, filter according: " + customerBackingBean.getSearchStringCustomer());
customerBackingBean.setCustomersForTable(customerService.findAllCustomers(customerBackingBean.getSearchStringCustomer()));
}
/* Get Customers list for table */
public List<Customer> getCustomers(){
if(customerBackingBean.getCustomersForTable()==null) {
LOGGER.info("Unable to load customers from bean, load from database.");
refreshCustomersTable();
}
return customerBackingBean.getCustomersForTable();
}
/* Create a new Customer and redirect to edit page */
public void buttonActionAddCustomer(ActionEvent actionEvent) {
Customer newCustomer = new Customer();
newCustomer.setContractors(new HashSet<Contractor>());
newCustomer.setCustomerManagers(new HashSet<User>());
newCustomer.setCreator(loginController.getCurrentUser());
customerModelBean.setSelectedCustomer(newCustomer);
redirectToEditPage();
}
/* Reset search filter data, and refresh the table of Customers */
public void resetCustomersTableSearchFilter() {
LOGGER.info("Reset Customers table");
customerBackingBean.setSearchStringCustomer(null);
customerBackingBean.setSelectedCustomer(null);
refreshCustomersTable();
}
/* After double click (to edit chosen Customer) redirect to edit page */
public void doubleClickSelectedRowInTableCustomers(){
editCustomer(customerBackingBean.getSelectedCustomer());
}
/* After pressing buttons for edit, set fields for chosen Customer and redirect to edit page */
public void editCustomer(Customer customer){
LOGGER.info("Passing chosen Customer to editing page");
customerModelBean.setSelectedCustomer(customer);
redirectToEditPage();
}
private void redirectToEditPage(){
LOGGER.info("Redirecting to Edit Customer page");
try {
FacesContext.getCurrentInstance().getExternalContext().redirect("edit_customer.xhtml");
} catch (IOException e) {
LOGGER.error(e.getMessage());
e.printStackTrace();
}
}
/** ---- EDIT/CREATE Customer page functionality ---- **/
/** Current Customer's Contractors related functionality **/
/* Get Contractors for popup dialog that are not linked to any Customer for assigning to the currently editing Customer */
public List<Contractor> getNotLinkedContractorsForPopupDialog(){
if(customerBackingBean.getPopupDialogContractors() == null){
LOGGER.info("Unable to load Contractors for popup dialog from bean, load from database.");
refreshContractorsTableInPopupDialog();
}
return customerBackingBean.getPopupDialogContractors();
}
public void refreshContractorsTableInPopupDialog(){
LOGGER.info("Refreshing Contractors table, filter according {} in popup dialog",customerBackingBean.getPopupDialogSearchStringContractorByINN());
customerBackingBean.setPopupDialogContractors(contractorService.findAllContractorsNotLinkedToCustomer(
customerBackingBean.getPopupDialogSearchStringContractorByINN(),
(customerBackingBean.getSelectedCustomer()!=null) ? customerBackingBean.getSelectedCustomer().getContractors() : null));
}
public void resetContractorsTableInPopupDialog() {
LOGGER.info("Reset Contractors table in popup dialog");
customerBackingBean.setPopupDialogSearchStringContractorByINN(null);
customerBackingBean.setPopupDialogSelectedContractor(null);
refreshContractorsTableInPopupDialog();
}
public void doubleClickSelectedRowInTableContractorsPopupDialog(FacesEvent event){
addSelectedContractorFromPopupDialogToCustomer(customerBackingBean.getPopupDialogSelectedContractor());
}
public void addSelectedContractorFromPopupDialogToCustomer(Contractor contractor){
if(!customerBackingBean.getSelectedCustomer().getContractors().contains(contractor)){
LOGGER.info("The selected contractor {} is new for this customer {}", contractor, customerBackingBean.getSelectedCustomer());
contractor.setCreator(null);
customerBackingBean.getSelectedCustomer().getContractors().add(contractor);
customerBackingBean.setSelectedContractorInEditPage(contractor);
}
}
public void extractSelectedContractor() {
if (customerBackingBean.getSelectedContractorInEditPage() != null){
LOGGER.info("Extract contractor {} from the customer {}", customerBackingBean.getSelectedContractorInEditPage(), customerBackingBean.getSelectedCustomer());
customerBackingBean.getSelectedContractorInEditPage().setCustomer(null);
customerBackingBean.getSelectedCustomer().getContractors().remove(customerBackingBean.getSelectedContractorInEditPage());
customerBackingBean.setSelectedContractorInEditPage(null);
}
}
public void deleteSelectedContractor() {
if (customerBackingBean.getSelectedContractorInEditPage() != null && loginController.hasAccessTo(ModelConstantEnum.CUSTOMER, AccessTypeEnum.DELETE)) {
LOGGER.info("Delete contractor {} from the customer {}", customerBackingBean.getSelectedContractorInEditPage(), customerBackingBean.getSelectedCustomer());
if(customerBackingBean.getContractorsRemovedFromCustomer()==null)
customerBackingBean.setContractorsRemovedFromCustomer(new LinkedList<Contractor>());
customerBackingBean.getContractorsRemovedFromCustomer().add(customerBackingBean.getSelectedContractorInEditPage());
customerBackingBean.getSelectedCustomer().getContractors().remove(customerBackingBean.getSelectedContractorInEditPage());
customerBackingBean.setSelectedContractorInEditPage(null);
}
}
public void buttonActionInsertContractor(ActionEvent actionEvent){
LOGGER.info("Reset Contractors table in popup dialog");
customerBackingBean.setPopupDialogSearchStringContractorByINN(null);
customerBackingBean.setPopupDialogSelectedContractor(null);
refreshContractorsTableInPopupDialog();
}
public void doubleClickSelectedRowInTableContractorsInEditCustomerPage() {
redirectToEditContractorPage(customerBackingBean.getSelectedContractorInEditPage());
}
public void redirectToEditContractorPage(Contractor contractor){
LOGGER.info("Redirecting to Edit Contractor pages");
try {
contractorModelBean.setSelectedContractor(contractor);
String url = FacesContext.getCurrentInstance().getViewRoot().getViewId();
FacesContext.getCurrentInstance().getExternalContext().getFlash().put("backUrl", url);
FacesContext.getCurrentInstance().getExternalContext().redirect("edit_contractor.xhtml");
} catch (IOException e) {
LOGGER.error(e.getMessage());
e.printStackTrace();
}
}
public void buttonActionPrepareAddNewContractor(ActionEvent actionEvent){
customerBackingBean.setAlreadyExistContractorsWithINN(null);
customerBackingBean.setInnStringForNewContractor(null);
}
public void buttonActionAddNewContractorByINN(ModelConstantEnum model){
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle resourceBundle = ResourceBundle.getBundle("messages", context.getViewRoot().getLocale());
if(customerBackingBean.getInnStringForNewContractor() == null || customerBackingBean.getInnStringForNewContractor().isEmpty())
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, resourceBundle.getString("error"), resourceBundle.getString("contractor.emptyINNNotAllowed")));
else if (!customerBackingBean.getInnStringForNewContractor().matches("[0-9]{10,}+"))
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, resourceBundle.getString("error"), resourceBundle.getString("contractor.wrongINN")));
else {
ContractorAgencyType contractorAgencyType = contractorAgencyTypeService.findByAgencyType(model.getModelName());
customerBackingBean.setAlreadyExistContractorsWithINN(contractorService.findByINN(customerBackingBean.getInnStringForNewContractor(), contractorAgencyType.getType()));
if(customerBackingBean.getAlreadyExistContractorsWithINN()!=null && customerBackingBean.getAlreadyExistContractorsWithINN().size()>0)
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, resourceBundle.getString("error"), resourceBundle.getString("contractor.alreadyExistWithINN")));
else {
createNewContractorWithINN(customerBackingBean.getInnStringForNewContractor(), contractorAgencyType);
redirectToEditContractorPage(customerBackingBean.getSelectedContractorInEditPage());
}
}
}
private void createNewContractorWithINN(String inn, ContractorAgencyType contractorAgencyType){
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle resourceBundle = ResourceBundle.getBundle("messages", context.getViewRoot().getLocale());
Contractor contractor = new Contractor();
contractor.setInn(inn);
contractor.setNameWork(resourceBundle.getString("contractor.nameWork"));
contractor.setCustomer(customerBackingBean.getSelectedCustomer());
contractor.setOrganizationType(contractorOrganizationTypeService.getAllContractorOrganizationTypes().get(0));
BankAccount newBankAccount = new BankAccount();
contractor.setDefaultBankAccount(newBankAccount);
Set<BankAccount> newBankAccounts = new HashSet<>();
newBankAccounts.add(newBankAccount);
newBankAccount.setContractor(contractor);
contractor.setBankAccounts(newBankAccounts);
Requisite newRequisite = new Requisite();
newRequisite.setActive(true);
newRequisite.setValidFrom(new Date());
Set<Requisite> newRequisites = new HashSet<>();
newRequisites.add(newRequisite);
newRequisite.setContractor(contractor);
contractor.setRequisites(newRequisites);
contractor.setAgencyType(contractorAgencyType);
customerBackingBean.setSelectedContractorInEditPage(contractor);
}
/** Current Customer's Managers related functionality **/
/* Get Users for popup dialog that are not linked to current Customer for assigning as a manager to the currently editing Customer */
public List<User> getUsersForPopupDialogToAssignAsManagerToCustomer(){
if(customerBackingBean.getPopupDialogUsersForManager()==null){
LOGGER.info("Unable to load Users to assign as Manager to the Customer from backing bean, load from database.");
refreshUsersForManagersTableInPopupDialog();
}
return customerBackingBean.getPopupDialogUsersForManager();
}
public void refreshUsersForManagersTableInPopupDialog(){
LOGGER.info("Refreshing Users table, filter according: " + customerBackingBean.getPopupDialogSearchStringUserForManager());
customerBackingBean.setPopupDialogUsersForManager(userService.findAllUsersNotAddedToTable(
customerBackingBean.getPopupDialogSearchStringUserForManager(),
(customerBackingBean.getSelectedCustomer()!=null) ? customerBackingBean.getSelectedCustomer().getCustomerManagers() : null));
}
public void resetUsersForManagerTableInPopupDialog() {
LOGGER.info("Reset Users table data of manager choice dialog");
customerBackingBean.setPopupDialogSearchStringUserForManager(null);
customerBackingBean.setPopupDialogSelectedUserForManager(null);
refreshUsersForManagersTableInPopupDialog();
}
public void doubleClickSelectedRowInTableUserForManager(FacesEvent event){
addSelectedUserForManagerFromPopupDialogToCustomer(customerBackingBean.getPopupDialogSelectedUserForManager());
}
public void addSelectedUserForManagerFromPopupDialogToCustomer(User user){
if(!customerBackingBean.getSelectedCustomer().getCustomerManagers().contains(user)){
LOGGER.info("The selected user {} is a new Manager for the customer {}", user, customerBackingBean.getSelectedCustomer());
customerBackingBean.getSelectedCustomer().getCustomerManagers().add(user);
customerBackingBean.setSelectedUserForManagerInEditPage(user);
}
}
public void removeSelectedManagerFromUser(ActionEvent actionEvent){
LOGGER.info("Remove manager {} from the customer {}", customerBackingBean.getSelectedUserForManagerInEditPage(), customerBackingBean.getSelectedCustomer());
customerBackingBean.getSelectedCustomer().getCustomerManagers().remove(customerBackingBean.getSelectedUserForManagerInEditPage());
customerBackingBean.setSelectedUserForManagerInEditPage(null);
}
public void buttonActionInsertCustomerManager(ActionEvent actionEvent){
customerBackingBean.setPopupDialogSelectedUserForManager(null);
customerBackingBean.setPopupDialogSearchStringUserForManager(null);
refreshUsersForManagersTableInPopupDialog();
}
public void buttonActionSaveCustomer(ActionEvent actionEvent){
LOGGER.info("Save the Customer {}", customerBackingBean.getSelectedCustomer());
if(customerBackingBean.getSelectedCustomer().getTitle()!=null && customerBackingBean.getSelectedCustomer().getTitle().isEmpty())
customerBackingBean.getSelectedCustomer().setTitle("Клиент ИД " + customerBackingBean.getSelectedCustomer().getId());
customerService.save(customerBackingBean.getSelectedCustomer());
if(customerBackingBean.getContractorsRemovedFromCustomer()!=null){
for (Contractor c: customerBackingBean.getContractorsRemovedFromCustomer())
contractorService.deleteById(c.getId());
customerBackingBean.setContractorsRemovedFromCustomer(null);
}
refreshCustomersTable();
redirectToCustomersPage();
}
public void buttonActionCancelSaveCustomer(ActionEvent actionEvent){
LOGGER.info("Cancel saving the Customer {}", customerBackingBean.getSelectedCustomer());
refreshCustomersTable();
redirectToCustomersPage();
}
private void redirectToCustomersPage(){
LOGGER.info("Redirecting to Customers pages");
try {
FacesContext.getCurrentInstance().getExternalContext().redirect("customers.xhtml");
} catch (IOException e) {
LOGGER.error(e.getMessage());
e.printStackTrace();
}
}
}
|
package com.project;
import java.util.List;
import com.project.battle.BattleScreen;
import com.project.button.Button;
import com.project.ship.Ship;
public interface Actionable {
public List<CrewAction> getActions();
public String getFlavorText();
public void doAction(Crew crew,CrewAction action,Ship ship,BattleScreen bs);
public String getName();
public ImageHandler getCardBackground();
public ImageHandler getCardImage();
}
|
package io.nuls.base.api.provider.ledger;
import io.nuls.base.api.provider.BaseReq;
import io.nuls.base.api.provider.BaseRpcService;
import io.nuls.base.api.provider.Provider;
import io.nuls.base.api.provider.Result;
import io.nuls.base.api.provider.account.facade.AccountInfo;
import io.nuls.base.api.provider.ledger.facade.*;
import io.nuls.core.constant.CommonCodeConstanst;
import io.nuls.core.log.Log;
import io.nuls.core.parse.MapUtils;
import io.nuls.core.rpc.model.ModuleE;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @Author: zhoulijun
* @Time: 2019-03-11 13:44
* @Description: 功能描述
*/
@Provider(Provider.ProviderType.RPC)
public class LedgerProviderForRpc extends BaseRpcService implements LedgerProvider {
@Override
protected <T, R> Result<T> call(String method, Object req, Function<R, Result> callback) {
return callRpc(ModuleE.LG.abbr, method, req, callback);
}
@Override
public Result<AccountBalanceInfo> getBalance(GetBalanceReq req) {
Function<Map, Result> callback = res -> {
BigInteger total = new BigInteger(String.valueOf(res.get("total")));
BigInteger freeze = new BigInteger(String.valueOf(res.get("freeze")));
BigInteger available = new BigInteger(String.valueOf(res.get("available")));
AccountBalanceInfo info = new AccountBalanceInfo();
info.setAvailable(available);
info.setFreeze(freeze);
info.setTotal(total);
return success(info);
};
return call("getBalance", req, callback);
}
@Override
public Result<Map> getLocalAsset(GetAssetReq req) {
return callResutlMap("getAssetRegInfoByHash", req);
}
@Override
public Result<Map> getContractAsset(ContractAsset req) {
return callResutlMap("getAssetContract", req);
}
@Override
public Result<Map> regLocalAsset(RegLocalAssetReq req) {
return callResutlMap("chainAssetTxReg", req);
}
@Override
public Result<AssetInfo> getAssetList(GetAssetListReq req) {
return _call("lg_get_all_asset", new BaseReq(), res -> {
try {
List<AssetInfo> list = ((List<Map<String, Object>>) res.get("assets")).stream().map(data->{
AssetInfo assetInfo = new AssetInfo();
assetInfo.setAssetChainId((Integer)data.get("assetChainId"));
assetInfo.setAssetId((Integer) data.get("assetId"));
assetInfo.setSymbol((String) data.get("assetSymbol"));
assetInfo.setAssetType((Integer) data.get("assetType"));
assetInfo.setDecimals((Integer) data.get("decimalPlace"));
return assetInfo;
}).collect(Collectors.toList());
if(req.getAssetType() > 0){
list = list.stream().filter(d->d.getAssetType() == req.getAssetType()).collect(Collectors.toList());
}
return success(list);
} catch (Exception e) {
Log.error("lg_get_all_asset fail", e);
return fail(CommonCodeConstanst.FAILED);
}
});
}
private <T> Result<T> _call(String method, Object req, Function<Map, Result> callback) {
return call(method, req, callback);
}
}
|
/*
* Created by Angel Leon (@gubatron), Alden Torres (aldenml)
* Copyright (c) 2011-2014, FrostWire(R). All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.frostwire.gui.library;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.ToolTipManager;
import javax.swing.UIDefaults;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.plaf.InsetsUIResource;
import org.limewire.i18n.I18nMarker;
import org.limewire.util.CommonUtils;
import org.limewire.util.FileUtils;
import org.limewire.util.OSUtils;
import com.frostwire.alexandria.Library;
import com.frostwire.alexandria.Playlist;
import com.frostwire.alexandria.PlaylistItem;
import com.frostwire.gui.library.SortedListModel.SortOrder;
import com.frostwire.gui.player.MediaPlayer;
import com.frostwire.gui.theme.SkinMenuItem;
import com.frostwire.gui.theme.SkinPopupMenu;
import com.frostwire.gui.theme.ThemeMediator;
import com.frostwire.uxstats.UXAction;
import com.frostwire.uxstats.UXStats;
import com.limegroup.gnutella.gui.DialogOption;
import com.limegroup.gnutella.gui.FileChooserHandler;
import com.limegroup.gnutella.gui.GUIMediator;
import com.limegroup.gnutella.gui.I18n;
import com.limegroup.gnutella.gui.iTunesMediator;
import com.limegroup.gnutella.gui.actions.LimeAction;
import com.limegroup.gnutella.gui.options.ConfigureOptionsAction;
import com.limegroup.gnutella.gui.options.OptionsConstructor;
import com.limegroup.gnutella.gui.tables.DefaultMouseListener;
import com.limegroup.gnutella.gui.tables.MouseObserver;
import com.limegroup.gnutella.gui.tables.TableSettings;
import com.limegroup.gnutella.gui.util.BackgroundExecutorService;
import com.limegroup.gnutella.settings.QuestionsHandler;
/**
*
* @author gubatron
* @author aldenml
*
*/
public class LibraryPlaylists extends AbstractLibraryListPanel {
private DefaultListModel<Object> _model;
private int _selectedIndexToRename;
private LibraryPlaylistsListCell _newPlaylistCell;
private ActionListener _selectedPlaylistAction;
private LibraryPlaylistsMouseObserver _listMouseObserver;
private ListSelectionListener _listSelectionListener;
private JList<Object> _list;
private JScrollPane _scrollPane;
private JTextField _textName;
private JPopupMenu _popup;
private Action refreshAction = new RefreshAction();
private Action refreshID3TagsAction = new RefreshID3TagsAction();
private Action deleteAction = new DeleteAction();
private Action cleanupPlaylistAction = new CleanupPlaylistAction();
private Action renameAction = new StartRenamingPlaylistAction();
private Action importToPlaylistAction = new ImportToPlaylistAction();
private Action importToNewPlaylistAction = new ImportToNewPlaylistAction();
private Action copyPlaylistFilesAction = new CopyPlaylistFilesAction();
private Action exportPlaylistAction = new ExportPlaylistAction();
private Action exportToiTunesAction = new ExportToiTunesAction();
private List<Playlist> importingPlaylists;
public LibraryPlaylists() {
setupUI();
importingPlaylists = new ArrayList<Playlist>();
}
public Dimension getRowDimension() {
Rectangle rect = _list.getUI().getCellBounds(_list, 0, 0);
return rect.getSize();
}
public void addPlaylist(Playlist playlist) {
LibraryPlaylistsListCell cell = new LibraryPlaylistsListCell(null, null, GUIMediator.getThemeImage("playlist"), playlist, _selectedPlaylistAction);
_model.addElement(cell);
}
public void clearSelection() {
_list.clearSelection();
}
public Playlist getSelectedPlaylist() {
LibraryPlaylistsListCell cell = (LibraryPlaylistsListCell) _list.getSelectedValue();
return cell != null ? cell.getPlaylist() : null;
}
protected void setupUI() {
setLayout(new BorderLayout());
GUIMediator.addRefreshListener(this);
setupPopupMenu();
setupModel();
setupList();
_scrollPane = new JScrollPane(_list);
add(_scrollPane);
}
private void setupPopupMenu() {
_popup = new SkinPopupMenu();
_popup.add(new SkinMenuItem(refreshAction));
_popup.add(new SkinMenuItem(refreshID3TagsAction));
_popup.add(new SkinMenuItem(renameAction));
_popup.addSeparator();
_popup.add(new SkinMenuItem(deleteAction));
_popup.add(new SkinMenuItem(cleanupPlaylistAction));
_popup.addSeparator();
_popup.add(new SkinMenuItem(importToPlaylistAction));
_popup.add(new SkinMenuItem(importToNewPlaylistAction));
_popup.addSeparator();
_popup.add(new SkinMenuItem(copyPlaylistFilesAction));
_popup.add(new SkinMenuItem(exportPlaylistAction));
_popup.addSeparator();
if (OSUtils.isWindows() || OSUtils.isMacOSX()) {
_popup.add(new SkinMenuItem(exportToiTunesAction));
}
_popup.addSeparator();
_popup.add(new SkinMenuItem(new ConfigureOptionsAction(OptionsConstructor.LIBRARY_KEY, I18n.tr("Configure Options"), I18n.tr("You can configure the FrostWire\'s Options."))));
}
private void setupModel() {
_model = new DefaultListModel<Object>();
_newPlaylistCell = new LibraryPlaylistsListCell(I18n.tr("New Playlist"), I18n.tr("Creates a new Playlist"), GUIMediator.getThemeImage("playlist_plus"), null, null);
Library library = LibraryMediator.getLibrary();
_selectedPlaylistAction = new SelectedPlaylistActionListener();
_model.addElement(_newPlaylistCell);
for (Playlist playlist : library.getPlaylists()) {
LibraryPlaylistsListCell cell = new LibraryPlaylistsListCell(null, null, GUIMediator.getThemeImage("playlist"), playlist, _selectedPlaylistAction);
_model.addElement(cell);
}
}
private void setupList() {
_listMouseObserver = new LibraryPlaylistsMouseObserver();
_listSelectionListener = new LibraryPlaylistsSelectionListener();
SortedListModel sortedModel = new SortedListModel(_model, SortOrder.ASCENDING, new Comparator<LibraryPlaylistsListCell>() {
@Override
public int compare(LibraryPlaylistsListCell o1, LibraryPlaylistsListCell o2) {
if (o1 == _newPlaylistCell) {
return -1;
}
if (o2 == _newPlaylistCell) {
return 1;
}
return o1.getText().compareTo(o2.getText());
}
});
_list = new LibraryIconList(sortedModel);
_list.setFixedCellHeight(TableSettings.DEFAULT_TABLE_ROW_HEIGHT.getValue());
_list.setCellRenderer(new LibraryPlaylistsCellRenderer());
_list.addMouseListener(new DefaultMouseListener(_listMouseObserver));
_list.addListSelectionListener(_listSelectionListener);
_list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
_list.setLayoutOrientation(JList.VERTICAL);
_list.setPrototypeCellValue(new LibraryPlaylistsListCell("test", "", GUIMediator.getThemeImage("playlist"), null, null));
_list.setVisibleRowCount(-1);
_list.setDragEnabled(true);
_list.setTransferHandler(new LibraryPlaylistsTransferHandler(_list));
ToolTipManager.sharedInstance().registerComponent(_list);
_list.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
list_keyPressed(e);
}
});
_list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() > 1) {
actionStartRename();
}
}
});
_textName = new JTextField();
ThemeMediator.fixKeyStrokes(_textName);
UIDefaults defaults = new UIDefaults();
defaults.put("TextField.contentMargins", new InsetsUIResource(0, 4, 0, 4));
_textName.putClientProperty("Nimbus.Overrides.InheritDefaults", Boolean.TRUE);
_textName.putClientProperty("Nimbus.Overrides", defaults);
_textName.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
textName_keyPressed(e);
}
});
_textName.setVisible(false);
_list.add(_textName);
}
protected void list_keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ESCAPE) {
cancelEdit();
} else if (key == KeyEvent.VK_ENTER) {
if (OSUtils.isMacOSX()) {
actionStartRename();
}
} else if (key == KeyEvent.VK_F2) {
if (!OSUtils.isMacOSX()) {
actionStartRename();
}
} else if (key == KeyEvent.VK_DELETE || (OSUtils.isMacOSX() && key == KeyEvent.VK_BACK_SPACE)) {
deleteAction.actionPerformed(null);
}
if (LibraryUtils.isRefreshKeyEvent(e)) {
refreshSelection();
}
}
protected void textName_keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (_selectedIndexToRename != -1 && key == KeyEvent.VK_ENTER) {
renameSelectedItem(_selectedIndexToRename);
} else if (_selectedIndexToRename == -1 && key == KeyEvent.VK_ENTER) {
createNewPlaylist();
} else if (key == KeyEvent.VK_ESCAPE) {
_textName.setVisible(false);
}
}
public void refreshSelection() {
LibraryPlaylistsListCell cell = (LibraryPlaylistsListCell) _list.getSelectedValue();
if (cell == null) {
// handle special case
if (_model.getSize() == 2 && MediaPlayer.instance().getCurrentPlaylist() == null) {
_list.setSelectedIndex(1);
}
return;
}
Playlist playlist = cell.getPlaylist();
if (playlist != null) {
playlist.refresh();
LibraryMediator.instance().updateTableItems(playlist);
String status = LibraryUtils.getPlaylistDurationInDDHHMMSS(playlist) + ", " + playlist.getItems().size() + " " + I18n.tr("tracks");
LibraryMediator.instance().getLibrarySearch().setStatus(status);
}
executePendingRunnables();
}
private void actionStartRename() {
cancelEdit();
int index = _list.getSelectedIndex();
if (index != -1) {
startEdit(index);
}
}
private void startEdit(int index) {
if (index < 0) {
return;
}
LibraryPlaylistsListCell cell = (LibraryPlaylistsListCell) _model.getElementAt(index);
_selectedIndexToRename = cell.getPlaylist() != null ? index : -1;
String text = cell.getText();
Rectangle rect = _list.getUI().getCellBounds(_list, index, index);
Dimension lsize = rect.getSize();
Point llocation = rect.getLocation();
_textName.setSize(lsize);
_textName.setLocation(llocation);
_textName.setText(text);
_textName.setSelectionStart(0);
_textName.setSelectionEnd(text.length());
_textName.setVisible(true);
_textName.requestFocusInWindow();
_textName.requestFocus();
}
public void selectPlaylist(Playlist playlist) {
Object selectedValue = _list.getSelectedValue();
if (selectedValue != null && ((LibraryPlaylistsListCell) selectedValue).getPlaylist() != null && ((LibraryPlaylistsListCell) selectedValue).getPlaylist().equals(playlist)) {
// already selected
try {
_listSelectionListener.valueChanged(null);
} catch (Exception e) {
System.out.println();
}
return;
}
int size = _model.getSize();
for (int i = 0; i < size; i++) {
try {
LibraryPlaylistsListCell cell = (LibraryPlaylistsListCell) _model.get(i);
if (cell.getPlaylist() != null && cell.getPlaylist().equals(playlist)) {
_list.setSelectedValue(cell, true);
return;
}
} catch (Exception e) {
}
}
}
private void renameSelectedItem(int index) {
if (!_textName.isVisible() || _textName.getText().trim().length() == 0) {
return;
}
Playlist selectedPlaylist = getSelectedPlaylist();
selectedPlaylist.setName(_textName.getText().trim());
selectedPlaylist.save();
_list.repaint();
_textName.setVisible(false);
UXStats.instance().log(UXAction.LIBRARY_PLAYLIST_RENAMED);
}
private void createNewPlaylist() {
if (!_textName.isVisible()) {
return;
}
String name = _textName.getText();
Library library = LibraryMediator.getLibrary();
Playlist playlist = library.newPlaylist(name, name);
playlist.save();
LibraryPlaylistsListCell cell = new LibraryPlaylistsListCell(null, null, GUIMediator.getThemeImage("playlist"), playlist, _selectedPlaylistAction);
_model.addElement(cell);
_list.setSelectedValue(cell, true);
_textName.setVisible(false);
UXStats.instance().log(UXAction.LIBRARY_PLAYLIST_CREATED);
}
private void cancelEdit() {
_selectedIndexToRename = -1;
_textName.setVisible(false);
}
//// handle m3u import/export
/**
* Loads a playlist.
*/
public void importM3U(Playlist playlist) {
File parentFile = FileChooserHandler.getLastInputDirectory();
if (parentFile == null)
parentFile = CommonUtils.getCurrentDirectory();
final File selFile = FileChooserHandler.getInputFile(GUIMediator.getAppFrame(), I18nMarker.marktr("Open Playlist (.m3u)"), parentFile, new PlaylistListFileFilter());
// nothing selected? exit.
if (selFile == null || !selFile.isFile())
return;
String path = selFile.getPath();
try {
path = FileUtils.getCanonicalPath(selFile);
} catch (IOException ignored) {
//LOG.warn("unable to get canonical path for file: " + selFile, ignored);
}
// create a new thread off of the event queue to process reading the files from
// disk
loadM3U(playlist, selFile, path);
}
/**
* Performs the actual reading of the PlayList and generation of the PlayListItems from
* the PlayList. Once we have done the heavy weight construction of the PlayListItem
* list, the list is handed to the swing event queue to process adding the files to
* the actual table model
*
*
* @param selFile - file that we're reading from
* @param path - path of file to open
* @param overwrite - true if the table should be cleared of all entries prior to loading
* the new playlist
*/
private void loadM3U(final Playlist playlist, final File selFile, final String path) {
BackgroundExecutorService.schedule(new Runnable() {
public void run() {
try {
final List<File> files = M3UPlaylist.load(path);
if (playlist != null) {
LibraryUtils.asyncAddToPlaylist(playlist, files.toArray(new File[0]));
} else {
LibraryUtils.createNewPlaylist(files.toArray(new File[0]));
}
} catch (Exception e) {
e.printStackTrace();
GUIMediator.safeInvokeLater(new Runnable() {
public void run() {
GUIMediator.showError("Unable to save playlist");
}
});
}
}
});
}
/**
* Saves a playlist.
*/
public void exportM3U(Playlist playlist) {
if (playlist == null) {
return;
}
String suggestedName = CommonUtils.convertFileName(playlist.getName());
// get the user to select a new one.... avoid FrostWire installation folder.
File suggested;
File suggestedDirectory = FileChooserHandler.getLastInputDirectory();
if (suggestedDirectory.equals(CommonUtils.getCurrentDirectory())) {
suggestedDirectory = new File(CommonUtils.getUserHomeDir(), "Desktop");
}
suggested = new File(suggestedDirectory, suggestedName + ".m3u");
File selFile = FileChooserHandler.getSaveAsFile(GUIMediator.getAppFrame(), I18nMarker.marktr("Save Playlist As"), suggested, new PlaylistListFileFilter());
// didn't select a file? nothing we can do.
if (selFile == null) {
return;
}
// if the file already exists and not the one just opened, ask if it should be
// overwritten.
//TODO: this should be handled in the jfilechooser
if (selFile.exists()) {
DialogOption choice = GUIMediator.showYesNoMessage(I18n.tr("Warning: a file with the name {0} already exists in the folder. Overwrite this file?", selFile.getName()), QuestionsHandler.PLAYLIST_OVERWRITE_OK, DialogOption.NO);
if (choice != DialogOption.YES)
return;
}
String path = selFile.getPath();
try {
path = FileUtils.getCanonicalPath(selFile);
} catch (IOException ignored) {
//LOG.warn("unable to get canonical path for file: " + selFile, ignored);
}
// force m3u on the end.
if (!path.toLowerCase().endsWith(".m3u"))
path += ".m3u";
// create a new thread to handle saving the playlist to disk
saveM3U(playlist, path);
}
/**
* Handles actually copying and writing the playlist to disk.
* @param path - file location to save the list to
*/
private void saveM3U(final Playlist playlist, final String path) {
BackgroundExecutorService.schedule(new Runnable() {
public void run() {
try {
List<File> files = new ArrayList<File>();
List<PlaylistItem> items = playlist.getItems();
for (PlaylistItem item : items) {
File file = new File(item.getFilePath());
if (file.exists()) {
files.add(file);
}
}
M3UPlaylist.save(path, files);
} catch (Exception e) {
e.printStackTrace();
GUIMediator.safeInvokeLater(new Runnable() {
public void run() {
GUIMediator.showError("Unable to save playlist");
}
});
}
}
});
}
public static class LibraryPlaylistsListCell {
private final String _text;
private final String _description;
private final Icon _icon;
private final Playlist _playlist;
private final ActionListener _action;
public LibraryPlaylistsListCell(String text, String description, Icon icon, Playlist playlist, ActionListener action) {
_text = text;
_description = description;
_icon = icon;
_playlist = playlist;
_action = action;
}
public String getText() {
if (_text != null) {
return _text;
} else if (_playlist != null && _playlist.getName() != null) {
return _playlist.getName();
} else {
return "";
}
}
public String getDescription() {
if (_description != null) {
return _description;
} else if (_playlist != null && _playlist.getDescription() != null) {
return _playlist.getDescription();
} else {
return "";
}
}
public Icon getIcon() {
return _icon;
}
public Playlist getPlaylist() {
return _playlist;
}
public ActionListener getAction() {
return _action;
}
}
private class LibraryPlaylistsCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
LibraryPlaylistsListCell cell = (LibraryPlaylistsListCell) value;
setText(cell.getText());
setToolTipText(cell.getDescription());
setPreferredSize(new Dimension(getSize().width, TableSettings.DEFAULT_TABLE_ROW_HEIGHT.getValue()));
Icon icon = cell.getIcon();
if (icon != null) {
setIcon(icon);
}
this.setFont(list.getFont());
ThemeMediator.fixLabelFont(this);
return this;
}
}
private class SelectedPlaylistActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
refreshSelection();
}
}
private class LibraryPlaylistsMouseObserver implements MouseObserver {
public void handleMouseClick(MouseEvent e) {
int index = _list.locationToIndex(e.getPoint());
_list.setSelectedIndex(index);
if (((LibraryPlaylistsListCell) _list.getSelectedValue()).getPlaylist() == null) {
actionStartRename();
}
}
/**
* Handles when the mouse is double-clicked.
*/
public void handleMouseDoubleClick(MouseEvent e) {
}
/**
* Handles a right-mouse click.
*/
public void handleRightMouseClick(MouseEvent e) {
}
/**
* Handles a trigger to the popup menu.
*/
public void handlePopupMenu(MouseEvent e) {
_list.setSelectedIndex(_list.locationToIndex(e.getPoint()));
_popup.show(_list, e.getX(), e.getY());
}
}
private class LibraryPlaylistsSelectionListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
cancelEdit();
if (e != null && e.getValueIsAdjusting()) {
return;
}
LibraryPlaylistsListCell cell = (LibraryPlaylistsListCell) _list.getSelectedValue();
if (cell == null) {
return;
}
LibraryMediator.instance().getLibraryExplorer().clearSelection();
if (cell.getAction() != null) {
cell.getAction().actionPerformed(null);
}
}
}
private class RefreshAction extends AbstractAction {
/**
*
*/
private static final long serialVersionUID = 3259221218056223423L;
public RefreshAction() {
putValue(Action.NAME, I18n.tr("Refresh"));
putValue(Action.SHORT_DESCRIPTION, I18n.tr("Refresh selected"));
putValue(LimeAction.ICON_NAME, "LIBRARY_REFRESH");
}
public void actionPerformed(ActionEvent e) {
refreshSelection();
}
}
private class RefreshID3TagsAction extends AbstractAction {
private static final long serialVersionUID = -472437818841089984L;
public RefreshID3TagsAction() {
putValue(Action.NAME, I18n.tr("Refresh Audio Properties"));
putValue(Action.SHORT_DESCRIPTION, I18n.tr("Refresh the audio properties based on ID3 tags of selected items"));
putValue(LimeAction.ICON_NAME, "LIBRARY_REFRESH");
}
public void actionPerformed(ActionEvent e) {
Playlist playlist = getSelectedPlaylist();
if (playlist != null) {
LibraryUtils.refreshID3Tags(playlist);
}
}
}
private class DeleteAction extends AbstractAction {
private static final long serialVersionUID = 520856485566457934L;
public DeleteAction() {
putValue(Action.NAME, I18n.tr("Delete"));
putValue(Action.SHORT_DESCRIPTION, I18n.tr("Delete Playlist"));
putValue(LimeAction.ICON_NAME, "PLAYLIST_DELETE");
}
public void actionPerformed(ActionEvent e) {
Playlist selectedPlaylist = getSelectedPlaylist();
if (selectedPlaylist != null) {
int showConfirmDialog = JOptionPane.showConfirmDialog(GUIMediator.getAppFrame(), I18n.tr("Are you sure you want to delete the playlist?\n(No files will be deleted)"), I18n.tr("Are you sure?"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (showConfirmDialog != JOptionPane.YES_OPTION) {
return;
}
selectedPlaylist.delete();
_model.removeElement(_list.getSelectedValue());
LibraryMediator.instance().clearLibraryTable();
UXStats.instance().log(UXAction.LIBRARY_PLAYLIST_REMOVED);
}
}
}
private final class CleanupPlaylistAction extends AbstractAction {
private static final long serialVersionUID = 8400749433148927596L;
public CleanupPlaylistAction() {
putValue(Action.NAME, I18n.tr("Cleanup playlist"));
putValue(Action.SHORT_DESCRIPTION, I18n.tr("Remove the deleted items"));
putValue(LimeAction.ICON_NAME, "PLAYLIST_CLEANUP");
}
public void actionPerformed(ActionEvent e) {
Playlist selectedPlaylist = getSelectedPlaylist();
if (selectedPlaylist != null) {
LibraryUtils.cleanup(selectedPlaylist);
LibraryMediator.instance().getLibraryPlaylists().refreshSelection();
}
}
}
private class StartRenamingPlaylistAction extends AbstractAction {
private static final long serialVersionUID = 520856485566457934L;
public StartRenamingPlaylistAction() {
putValue(Action.NAME, I18n.tr("Rename"));
putValue(Action.SHORT_DESCRIPTION, I18n.tr("Rename Playlist"));
putValue(LimeAction.ICON_NAME, "PLAYLIST_RENAME");
}
public void actionPerformed(ActionEvent e) {
startEdit(_list.getSelectedIndex());
}
}
public void reselectPlaylist() {
_listSelectionListener.valueChanged(null);
}
@Override
public void refresh() {
_list.repaint();
}
/**
* <tt>FileFilter</tt> class for only displaying m3u file types in
* the directory chooser.
*/
private static class PlaylistListFileFilter extends FileFilter {
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith("m3u");
}
public String getDescription() {
return I18n.tr("Playlist Files (*.m3u)");
}
}
private final class ImportToPlaylistAction extends AbstractAction {
private static final long serialVersionUID = -9099898749358019734L;
public ImportToPlaylistAction() {
putValue(Action.NAME, I18n.tr("Import .m3u to Playlist"));
putValue(Action.SHORT_DESCRIPTION, I18n.tr("Import a .m3u file into the selected playlist"));
putValue(LimeAction.ICON_NAME, "PLAYLIST_IMPORT_TO");
}
public void actionPerformed(ActionEvent e) {
importM3U(getSelectedPlaylist());
}
}
private final class ImportToNewPlaylistAction extends AbstractAction {
private static final long serialVersionUID = 390846680458085610L;
public ImportToNewPlaylistAction() {
putValue(Action.NAME, I18n.tr("Import .m3u to New Playlist"));
putValue(Action.SHORT_DESCRIPTION, I18n.tr("Import a .m3u file to a new playlist"));
putValue(LimeAction.ICON_NAME, "PLAYLIST_IMPORT_NEW");
}
public void actionPerformed(ActionEvent e) {
importM3U(null);
}
}
public final static class CopyPlaylistFilesAction extends AbstractAction {
public CopyPlaylistFilesAction() {
putValue(Action.NAME, I18n.tr("Export playlist files to folder"));
putValue(Action.SHORT_DESCRIPTION, I18n.tr("Copy all playlist files to a folder of your choosing"));
putValue(LimeAction.ICON_NAME, "PLAYLIST_IMPORT_NEW");
}
public void actionPerformed(ActionEvent e) {
copyPlaylistFilesToFolder(LibraryMediator.instance().getSelectedPlaylist());
}
private void copyPlaylistFilesToFolder(Playlist playlist) {
if (playlist == null || playlist.getItems().isEmpty()) {
return;
}
File suggestedDirectory = FileChooserHandler.getLastInputDirectory();
if (suggestedDirectory.equals(CommonUtils.getCurrentDirectory())) {
suggestedDirectory = new File(CommonUtils.getUserHomeDir(), "Desktop");
}
final File selFolder = FileChooserHandler.getSaveAsDir(GUIMediator.getAppFrame(), I18nMarker.marktr("Where do you want the playlist files copied to?"), suggestedDirectory);
if (selFolder == null) {
return;
}
//let's make a copy of the list in case the playlist will be modified during the copying.
final List<PlaylistItem> playlistItems = new ArrayList<>(playlist.getItems());
BackgroundExecutorService.schedule(new Thread("Library-copy-playlist-files") {
@Override
public void run() {
int n = 0;
int total = playlistItems.size();
String targetName = selFolder.getName();
for (PlaylistItem item : playlistItems) {
File f = new File(item.getFilePath());
if (f.isFile() && f.exists() && f.canRead()) {
try {
Path source = f.toPath();
Path target = FileSystems.getDefault().getPath(selFolder.getAbsolutePath(), f.getName());
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
n++;
//invoked on UI thread later
String status = String.format("Copied %d of %d to %s", n, total, targetName);
LibraryMediator.instance().getLibrarySearch().pushStatus(status);
} catch (IOException e) {
e.printStackTrace();
}
}
}
GUIMediator.launchExplorer(selFolder);
//and clear the output
try {
Thread.sleep(2000);
LibraryMediator.instance().getLibrarySearch().pushStatus("");
} catch (InterruptedException e) {
}
}
});
}
}
private final class ExportPlaylistAction extends AbstractAction {
private static final long serialVersionUID = 6149822357662730490L;
public ExportPlaylistAction() {
putValue(Action.NAME, I18n.tr("Export Playlist to .m3u"));
putValue(Action.SHORT_DESCRIPTION, I18n.tr("Export this playlist into a .m3u file"));
putValue(LimeAction.ICON_NAME, "PLAYLIST_IMPORT_NEW");
}
public void actionPerformed(ActionEvent e) {
exportM3U(getSelectedPlaylist());
}
}
private final class ExportToiTunesAction extends AbstractAction {
private static final long serialVersionUID = 3601146746674363384L;
public ExportToiTunesAction() {
putValue(Action.NAME, I18n.tr("Export Playlist to iTunes"));
putValue(Action.SHORT_DESCRIPTION, I18n.tr("Export this playlist into an iTunes playlist"));
putValue(LimeAction.ICON_NAME, "PLAYLIST_IMPORT_NEW");
}
public void actionPerformed(ActionEvent e) {
Playlist playlist = getSelectedPlaylist();
if (playlist != null) {
List<File> files = new ArrayList<File>();
for (PlaylistItem item : playlist.getItems()) {
File file = new File(item.getFilePath());
files.add(file);
}
iTunesMediator.instance().addSongsiTunes(playlist.getName(), files.toArray(new File[0]));
}
}
}
public void markBeginImport(Playlist playlist) {
try {
if (!importingPlaylists.contains(playlist)) {
importingPlaylists.add(playlist);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void markEndImport(Playlist playlist) {
try {
importingPlaylists.remove(playlist);
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isPlaylistImporting(Playlist playlist) {
try {
return importingPlaylists.contains(playlist);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
|
package com.b.test.security;
import com.b.test.common.SessionUtil;
import com.b.test.common.StringUtils;
import com.b.test.entry.UserDetail;
import com.b.test.entry.UserLogin;
import com.b.test.service.UserLoginService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
/**
* @author zhr
* @description 获取账号密码
* @date 2018-12-10 11:02
**/
@Component
public class UserDetailService implements UserDetailsService {
@Resource
private UserLoginService userLoginService;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
SessionUtil.del("login");
if (StringUtils.isEmpty(s)) {
SessionUtil.put("login", "用户名为空");
throw new UsernameNotFoundException("用户名为空");
}
UserLogin userLogin = new UserLogin();
//别名作为登录账号使用
userLogin.setUsername(s);
List<UserLogin> userLogins = userLoginService.getByBean(userLogin);
if (userLogins == null || userLogins.size() <= 0) {
if (userLogins == null || userLogins.size() <= 0) {
SessionUtil.put("login", "账号不存在");
throw new UsernameNotFoundException("账号不存在");
}
}
UserDetail userDetail = new UserDetail();
userDetail.setUserLogin(userLogins.get(0));
return userDetail;
}
}
|
package testsUnitarios;
import org.junit.Test;
import cartas.BrazoDerechoExodia;
import cartas.BrazoIzquierdoExodia;
import cartas.CabezaExodia;
import cartas.InsectoComeHombres;
import cartas.OllaDeLaCodicia;
import cartas.PiernaDerechaExodia;
import cartas.PiernaIzquierdaExodia;
import excepciones.TengoTodasLasPartesDeExodiaException;
import juego.RecolectorDePartesDeExodia;
public class TestRecolectorDePartesDeExodia {
@Test(expected = TengoTodasLasPartesDeExodiaException.class)
public void testRecolectoTodasLasPartesDeExodiaDevuelveLaExceptionTengoTodasLasPartesDeExodia()
throws TengoTodasLasPartesDeExodiaException {
RecolectorDePartesDeExodia recolector = new RecolectorDePartesDeExodia();
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new BrazoDerechoExodia());
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new BrazoIzquierdoExodia());
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new PiernaDerechaExodia());
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new PiernaIzquierdaExodia());
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new CabezaExodia());
}
@Test
public void testSiNoSonLasPartesDeExodiaNoLanzaNingunaExepcion() throws TengoTodasLasPartesDeExodiaException {
RecolectorDePartesDeExodia recolector = new RecolectorDePartesDeExodia();
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new InsectoComeHombres());
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new OllaDeLaCodicia());
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new PiernaDerechaExodia());
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new PiernaIzquierdaExodia());
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new CabezaExodia());
}
@Test
public void testSiSonPartesDeExodiaRepetidasNoLanzaNingunaExepcion() throws TengoTodasLasPartesDeExodiaException {
RecolectorDePartesDeExodia recolector = new RecolectorDePartesDeExodia();
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new PiernaIzquierdaExodia());
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new PiernaDerechaExodia());
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new PiernaDerechaExodia());
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new PiernaIzquierdaExodia());
recolector.siEsUnaParteDelExodiaQueNoTeniaRecolectar(new CabezaExodia());
}
}
|
package com.example.awesoman.owo2_comic.ui.ComicLocal;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import com.example.awesoman.owo2_comic.R;
import com.example.awesoman.owo2_comic.model.ComicInfo;
import com.example.awesoman.owo2_comic.ui.BaseActivity;
import com.example.awesoman.owo2_comic.ui.ComicLocal.adapter.ChooseChapterAdapter;
import com.example.awesoman.owo2_comic.utils.FileManager;
import com.example.awesoman.owo2_comic.utils.SkipUtil;
import java.util.List;
import butterknife.Bind;
/**
* Created by Awesome on 2017/3/30.
* 选取封面来自章节Activity
*/
public class ChooseChapterActivity extends BaseActivity
implements View.OnClickListener ,ChooseChapterAdapter.IChooseChapter{
@Bind(R.id.titleTxt)
TextView titleTxt;
@Bind(R.id.lv_chapter)
ListView chapterLV;
private ComicInfo comicInfo;
private ChooseChapterAdapter adapter;
private FileManager comicDBManager;
private List<String> chapterList ;
@Override
public int getContentViewID() {
return R.layout.activity_choose_chapter;
}
@Override
public void initView() {
chapterLV = (ListView) findViewById(R.id.lv_chapter);
titleTxt.setText("选择章节文件夹");
Bundle bundle = getIntent().getExtras();
comicDBManager = FileManager.getInstance();
//获取comicEntity信息
comicInfo =(ComicInfo) getIntent().getSerializableExtra("comicInfo");
showChapter();
}
public void showChapter(){
new AsyncTask(){
@Override
protected Object doInBackground(Object[] params) {
adapter = new ChooseChapterAdapter(ChooseChapterActivity.this);
chapterList = comicDBManager.getChapterList(comicInfo.getComicPath());
adapter.setmData(chapterList);
adapter.setListener(ChooseChapterActivity.this);
return null;
}
@Override
protected void onPostExecute(Object o) {
chapterLV.setAdapter(adapter);
}
}.execute();
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id){
case R.id.backBtn:
finish();
break;
}
}
@Override
public void chooseChapter(int position) {
Intent intent = new Intent();
intent.setClass(this,ChooseSurfaceActivity.class);
//传入漫画下章节的地址路径
intent.putExtra("path", comicInfo.getComicPath());
intent.putExtra("chapter",chapterList.get(position));
intent.putExtra("comic_name",comicInfo.getComicName());
SkipUtil.skip(this,intent,false);
}
}
|
package com.zeroentropy.game.handler.enemy;
import org.andengine.engine.handler.physics.PhysicsHandler;
import org.andengine.entity.modifier.EntityModifier;
import org.andengine.entity.modifier.LoopEntityModifier;
import org.andengine.entity.modifier.RotationModifier;
import org.andengine.entity.modifier.SequenceEntityModifier;
import org.andengine.util.math.MathUtils;
import com.zeroentropy.game.sprite.Enemy;
import com.zeroentropy.game.sprite.Player;
import com.zeroentropy.game.util.ZeroConstants;
public class AngryPufferHandler implements IEnemyHandler {
public static AngryPufferHandler getInstance() {
return INSTANCE;
}
private static AngryPufferHandler INSTANCE = new AngryPufferHandler();
private AngryPufferHandler() {
// Arrays.fill(mFrameDurations, FRAME_DURATION_EACH);
}
private static final int mCurrentTileIndex = 47;
private static final int VELOCITY_Y = -20;// -24;
// private static final int MAX_VELOCITY_Y = -30;// -24;
public void enter(final Enemy pSprite) {
if (pSprite.getRotation() != 0)
pSprite.setRotation(0);
// pSprite.setFlippedHorizontal(MathUtils.randomBoolean());
pSprite.resetPhysics();
pSprite.stopAnimation(mCurrentTileIndex);
LoopEntityModifier modifier = new LoopEntityModifier(new SequenceEntityModifier(
new RotationModifier(.75f, -8, 8),
new RotationModifier(.75f, 8, -8)));
pSprite.registerEntityModifier(modifier);
pSprite.setVelocityY(MathUtils.randomFactor(VELOCITY_Y, 0.5f));
}
public void execute(final float pSecondsElapsed, final Enemy pSprite) {
if (pSprite.getX() < 0) {
pSprite.turnRight();
} else if (pSprite.getX() > ZeroConstants.SCENE_WIDTH
- ZeroConstants.BASE_SPRITE_WIDTH) {
pSprite.turnLeft();
}
}
public void exit(final Enemy pSprite) {
pSprite.clearEntityModifiers();
}
@Override
public void executeCollides(final Enemy pSprite, final Player pPlayer) {
// TODO Auto-generated method stub
pSprite.brokenSelf();
// World.getInstance().mPlayer.setState(IPlayer.STATE_JUMP);
// Ôö¼Ó»ðÑÛ£Öµ
// fiery_eyes++;
pPlayer.getStung(20);
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.aot.hint.annotation.Reflective;
/**
* Annotation that identifies methods that initialize the
* {@link org.springframework.web.bind.WebDataBinder} which
* will be used for populating command and form object arguments
* of annotated handler methods.
*
* <p><strong>WARNING</strong>: Data binding can lead to security issues by exposing
* parts of the object graph that are not meant to be accessed or modified by
* external clients. Therefore the design and use of data binding should be considered
* carefully with regard to security. For more details, please refer to the dedicated
* sections on data binding for
* <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-initbinder-model-design">Spring Web MVC</a> and
* <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-ann-initbinder-model-design">Spring WebFlux</a>
* in the reference manual.
*
* <p>{@code @InitBinder} methods support all arguments that
* {@link RequestMapping @RequestMapping} methods support, except for command/form
* objects and corresponding validation result objects. {@code @InitBinder} methods
* must not have a return value; they are usually declared as {@code void}.
*
* <p>Typical arguments are {@link org.springframework.web.bind.WebDataBinder}
* in combination with {@link org.springframework.web.context.request.WebRequest}
* or {@link java.util.Locale}, allowing to register context-specific editors.
*
* @author Juergen Hoeller
* @author Sebastien Deleuze
* @since 2.5
* @see ControllerAdvice
* @see org.springframework.web.bind.WebDataBinder
* @see org.springframework.web.context.request.WebRequest
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Reflective
public @interface InitBinder {
/**
* The names of command/form attributes and/or request parameters
* that this init-binder method is supposed to apply to.
* <p>Default is to apply to all command/form attributes and all request parameters
* processed by the annotated handler class. Specifying model attribute names or
* request parameter names here restricts the init-binder method to those specific
* attributes/parameters, with different init-binder methods typically applying to
* different groups of attributes or parameters.
*/
String[] value() default {};
}
|
package sop.web.management;
import java.util.List;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import dwz.framework.sys.exception.ServiceException;
import dwz.framework.user.User;
import dwz.framework.user.UserServiceMgr;
import dwz.persistence.BaseConditionVO;
import dwz.web.BaseController;
import it.sauronsoftware.base64.Base64;
import sop.persistence.beans.SysUser;
import sop.vo.CustomerVo;
/**
* @Author: LCF
* @Date: 2020/1/9 13:02
* @Package: sop.web.management
*/
@Controller
@RequestMapping(value = "/management/user")
public class UserController extends BaseController {
@Autowired
private UserServiceMgr userMgr;
@RequestMapping("/list")
public ModelAndView list(BaseConditionVO vo) {
ModelAndView mv = new ModelAndView("/management/user/list");
List<SysUser> userList = userMgr.searchUser(vo);
Integer totalCount = userMgr.searchUserNum(vo);
vo.setTotalCount(totalCount);
mv.addObject("totalCount", totalCount);
mv.addObject("pageSize", vo.getPageSize());
mv.addObject("vo", vo);
mv.addObject("userList", userList);
return mv;
}
@RequestMapping("/add")
public ModelAndView add() {
ModelAndView mv = new ModelAndView("/management/user/add");
mv.addObject("coCodes", this.userMgr.getCoCodes());
mv.addObject("user", new SysUser());
return mv;
}
@RequestMapping("/edit/{uname}/{company}")
public ModelAndView edit(@PathVariable("uname") String uname, @PathVariable("company") String company) {
User user = userMgr.getUserByUsernameAndCocode(uname, company);
ModelAndView mv = new ModelAndView("/management/user/edit");
mv.addObject("user", user.getSysUser());
mv.addObject("coCodes", this.userMgr.getCoCodes());
return mv;
}
@RequestMapping("/insert")
@ResponseBody
public ModelAndView insert(SysUser user) {
try {
userMgr.insertUsr(user);
} catch (Exception e) {
return ajaxDoneError(e.getMessage());
}
return ajaxDoneSuccess(getMessage("msg.operation.success"));
}
@RequestMapping("/update")
@ResponseBody
public ModelAndView update(SysUser user) {
try {
userMgr.updUser(user);
} catch (Exception e) {
return ajaxDoneError(e.getMessage());
}
return ajaxDoneSuccess(getMessage("msg.operation.success"));
}
@RequestMapping("/delete/{uname}/{company}")
@ResponseBody
public ModelAndView delete(@PathVariable("uname") String uname, @PathVariable("company") String company) {
try {
User user = userMgr.getUserByUsernameAndCocode(uname, company);
if (user != null)
userMgr.delUser(user.getSysUser());
} catch (Exception e) {
return ajaxDoneError(e.getMessage());
}
return ajaxDoneSuccess(getMessage("msg.operation.success"));
}
}
|
package ejercicio16;
import java.util.Scanner;
/**
*
* @author Javier
*/
public class Ejercicio16 {
double tamano;
double velocidad;
Ejercicio16() {
tamano();
velocidad();
}
void tamano() {
Scanner entrada = new Scanner(System.in);
System.out.print("Tamaño de la descarga en MB: ");
tamano = entrada.nextDouble() * 8; // lo almaceno directamente en megabits
}
void velocidad() {
Scanner entrada = new Scanner(System.in);
System.out.print("Velocidad de la descarga en Mb/s: ");
velocidad = entrada.nextDouble();
}
void calculo() {
double tiempo = tamano / velocidad / 60;
System.out.println("Tardarás " + tiempo + " minutos en descargarlo"); // en minutos
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Ejercicio16 n1 = new Ejercicio16();
n1.calculo();
}
}
|
package com.cxxt.mickys.playwithme.presenter.login;
import android.content.Context;
import com.cxxt.mickys.playwithme.model.bean.response.ResponseResult;
import com.cxxt.mickys.playwithme.model.login.LoginModel;
import com.cxxt.mickys.playwithme.model.login.LoginModelImpl;
import com.cxxt.mickys.playwithme.view.LoginView;
/**
* 登录 presenter 实例化
*
* @author huangyz0918
*/
public class LoginPresenterImpl implements LoginPresenter, OnLoginFinishedListener {
private LoginView loginView;
private LoginModel loginModel;
public LoginPresenterImpl(LoginView loginView) {
this.loginView = loginView;
this.loginModel = new LoginModelImpl();
}
@Override
public void validateCredentials(String username, Context context, String password) {
if (loginView != null) {
loginView.showProgress();
}
loginModel.login(username, context, password, this);
}
@Override
public void onDestroy() {
loginView = null;
}
/*
* 这里的用户名等于用户用户登录的手机号码
* */
@Override
public void onError(String message) {
if (loginView != null) {
loginView.setErrorMessage(message);
}
}
@Override
public void onSuccess(ResponseResult responseResult) {
if (loginView != null) {
loginView.navigateToHome();
}
}
}
|
package chap4_Trees_Graphs;
public class ArrayIntoBST {
Node tree ;
public Node intoBST(int[] array) {
return intoBST(array, 0, array.length - 1) ;
}
private Node intoBST(int[] array, int beg, int end) {
if(end < beg) return null;
int mid = beg + (end - beg)/2;
return new Node(array[mid], intoBST(array, beg, mid - 1), intoBST(array, mid +1, end));
}
}
|
package revolt.backend.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import revolt.backend.entity.Country;
@Repository
public interface CountryRepository extends JpaRepository<Country, Long> {
}
|
package com.dabis.trimsalon.beans;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;
public class Factuur
{
private long id;
private Set<Boekhouding> factuurregels;
private Calendar factuurdatum;
private String factuurnummer;
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the factuurregels
*/
public Set<Boekhouding> getFactuurregels() {
if( factuurregels == null ) factuurregels = new HashSet<Boekhouding>();
return factuurregels;
}
/**
* @param factuurregels the factuurregels to set
*/
public void setFactuurregels(Set<Boekhouding> factuurregels) {
this.factuurregels = factuurregels;
}
/**
* Add one Factuurregel
*/
public void addFactuurregel(Boekhouding item) {
getFactuurregels().add(item);
}
/**
* Remove one Factuurregel
*/
public void removeFactuurregel(Boekhouding item) {
if( factuurregels != null ) {
factuurregels.remove(item);
}
}
/**
* @return the factuurdatum
*/
public Calendar getFactuurdatum() {
return factuurdatum;
}
/**
* @param factuurdatum the factuurdatum to set
*/
public void setFactuurdatum(Calendar factuurdatum) {
this.factuurdatum = factuurdatum;
}
/**
* @return the factuurnummer
*/
public String getFactuurnummer() {
return factuurnummer;
}
/**
* @param factuurnummer the factuurnummer to set
*/
public void setFactuurnummer(String factuurnummer) {
this.factuurnummer = factuurnummer;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.