text stringlengths 10 2.72M |
|---|
package com.hoanganhtuan95ptit.awesomekeyboard;
/**
* Created by HOANG ANH TUAN on 7/5/2017.
*/
public enum KeyboardType {
NOMAL,STICKER,PHOTO,COLOR,NOTHING
}
|
package com.citibank.ods.modules.client.customerprvt.functionality;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.struts.action.ActionForm;
import com.citibank.ods.Globals;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.common.functionality.BaseFnc;
import com.citibank.ods.common.functionality.valueobject.BaseFncVO;
import com.citibank.ods.common.util.ODSConstraintDecoder;
import com.citibank.ods.entity.pl.BaseTplCustomerPrvtEntity;
import com.citibank.ods.entity.pl.TbgOfficerEntity;
import com.citibank.ods.entity.pl.TplCustomerPrvtCmplEntity;
import com.citibank.ods.entity.pl.TplCustomerPrvtEntity;
import com.citibank.ods.modules.client.customerprvt.form.BaseCustomerPrvtDetailForm;
import com.citibank.ods.modules.client.customerprvt.functionality.valueobject.BaseCustomerPrvtDetailFncVO;
import com.citibank.ods.persistence.bg.dao.TbgOfficerDAO;
import com.citibank.ods.persistence.pl.dao.BaseTplCustomerPrvtDAO;
import com.citibank.ods.persistence.pl.dao.TplClassCmplcDAO;
import com.citibank.ods.persistence.pl.dao.TplCustomerPrvtCmplDAO;
import com.citibank.ods.persistence.pl.dao.TplCustomerPrvtDAO;
import com.citibank.ods.persistence.pl.dao.TplCustomerPrvtTypeDAO;
import com.citibank.ods.persistence.pl.dao.TplErEmDAO;
import com.citibank.ods.persistence.pl.dao.TplPotentialWealthDAO;
import com.citibank.ods.persistence.pl.dao.factory.ODSDAOFactory;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
* [Class description]
*
* @see package com.citibank.ods.modules.client.customerPrvt.functionality;
* @version 1.0
* @author l.braga,14/03/2007
*
* <PRE>
*
* <U>Updated by: </U> <U>Description: </U>
*
* </PRE>
*/
public abstract class BaseCustomerPrvtDetailFnc extends BaseFnc
{
public static final String C_EXISTING_DATA_CMPL = "1";
/*
* (non-Javadoc)
* @see com.citibank.ods.common.functionality.BaseFnc#updateFncVOFromForm(org.apache.struts.action.ActionForm,
* com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void updateFncVOFromForm( ActionForm form_, BaseFncVO fncVO_ )
{
BaseCustomerPrvtDetailForm form = ( BaseCustomerPrvtDetailForm ) form_;
BaseCustomerPrvtDetailFncVO fncVO = ( BaseCustomerPrvtDetailFncVO ) fncVO_;
BigInteger custNbr = ( form.getCustNbr() != null
&& form.getCustNbr().length() > 0
? new BigInteger(
form.getCustNbr() )
: null );
TplCustomerPrvtEntity tplCustomerPrvtEntity = new TplCustomerPrvtEntity();
TplCustomerPrvtCmplEntity tplCustomerPrvtCmplEntity = new TplCustomerPrvtCmplEntity();
fncVO.setTplCustomerPrvtEntity( tplCustomerPrvtEntity );
fncVO.setTplCustomerPrvtCmplEntity( tplCustomerPrvtCmplEntity );
fncVO.getTplCustomerPrvtEntity().getData().setCustNbr( custNbr );
// Atualizando os dados: Form -> FncVO
fncVO.getTplCustomerPrvtCmplEntity().getData().setCustNbr(
toBigInteger(
form,
form.getCustNbr(),
Globals.FormatKeys.C_FORMAT_NUMBER_INTEGER ) );
fncVO.getTplCustomerPrvtCmplEntity().getData().setClassCmplcCode(
toBigInteger(
form,
form.getClassCmplcCode(),
Globals.FormatKeys.C_FORMAT_NUMBER_INTEGER ) );
fncVO.getTplCustomerPrvtCmplEntity().getData().setPrvtCustTypeCode(
toBigInteger(
form,
form.getPrvtCustTypeCode(),
Globals.FormatKeys.C_FORMAT_NUMBER_INTEGER ) );
fncVO.getTplCustomerPrvtCmplEntity().getData().setOffcrNbr(
toBigInteger(
form,
form.getOffcrNbrSrc(),
Globals.FormatKeys.C_FORMAT_NUMBER_INTEGER ) );
fncVO.getTplCustomerPrvtCmplEntity().getData().setPrvtKeyNbr(
toBigInteger(
form,
form.getPrvtKeyNbr(),
Globals.FormatKeys.C_FORMAT_NUMBER_INTEGER ) );
fncVO.getTplCustomerPrvtCmplEntity().getData().setPrvtCustNbr(
toBigInteger(
form,
form.getPrvtCustNbr(),
Globals.FormatKeys.C_FORMAT_NUMBER_INTEGER ) );
fncVO.getTplCustomerPrvtCmplEntity().getData().setEmNbr( form.getEmNbr() );
fncVO.getTplCustomerPrvtCmplEntity().getData().setErNbr( form.getErNbr() );
fncVO.getTplCustomerPrvtCmplEntity().getData().setWealthPotnlCode(
toBigInteger(
form,
form.getWealthPotnlCode(),
Globals.FormatKeys.C_FORMAT_NUMBER_INTEGER ) );
fncVO.setClickedSearch( "" );
if ( form.getMailRecvInd() != null
&& form.getMailRecvInd().equals(
Globals.BooleanIndicatorKeys.C_BOOLEAN_IND_SIM ) )
{
fncVO.getTplCustomerPrvtCmplEntity().getData().setMailRecvInd(
Globals.BooleanIndicatorKeys.C_BOOLEAN_IND_SIM );
}
else
{
fncVO.getTplCustomerPrvtCmplEntity().getData().setMailRecvInd(
Globals.BooleanIndicatorKeys.C_BOOLEAN_IND_NAO );
}
if ( form.getOffclMailRecvInd() != null
&& form.getOffclMailRecvInd().equals(
Globals.BooleanIndicatorKeys.C_BOOLEAN_IND_SIM ) )
{
fncVO.getTplCustomerPrvtCmplEntity().getData().setOffclMailRecvInd(
Globals.BooleanIndicatorKeys.C_BOOLEAN_IND_SIM );
}
else
{
fncVO.getTplCustomerPrvtCmplEntity().getData().setOffclMailRecvInd(
Globals.BooleanIndicatorKeys.C_BOOLEAN_IND_NAO );
}
fncVO.getTplCustomerPrvtCmplEntity().getData().setGlbRevenSysOffcrNbr(
toBigInteger(
form,
form.getGlbRevenSysOffcrNbr(),
Globals.FormatKeys.C_FORMAT_NUMBER_INTEGER ) );
fncVO.setCmplDataButtonControl( form.getCmplDataButtonControl() );
String custPrvtStatCode = form.getCustPrvtStatCode() != null
? form.getCustPrvtStatCode()
: "";
fncVO.getTplCustomerPrvtCmplEntity().getData().setCustPrvtStatCode(
custPrvtStatCode );
}
/*
* (non-Javadoc)
* @see com.citibank.ods.common.functionality.BaseFnc#updateFormFromFncVO(org.apache.struts.action.ActionForm,
* com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void updateFormFromFncVO( ActionForm form_, BaseFncVO fncVO_ )
{
BaseCustomerPrvtDetailForm form = ( BaseCustomerPrvtDetailForm ) form_;
BaseCustomerPrvtDetailFncVO fncVO = ( BaseCustomerPrvtDetailFncVO ) fncVO_;
DateFormat dateFormat = new SimpleDateFormat(
Globals.FuncionalityFormatKeys.C_FORMAT_DATE_DDMMYYYY );
String custNbr = ( fncVO.getTplCustomerPrvtEntity().getData().getCustNbr() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustNbr().toString()
: null );
String custCpfCnpjNbr = ( fncVO.getTplCustomerPrvtEntity().getData().getCustCpfCnpjNbr() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustCpfCnpjNbr().toString()
: null );
String custShortNameText = ( fncVO.getTplCustomerPrvtEntity().getData().getCustShortNameText() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustShortNameText().toString()
: null );
String custKeyNameText = ( fncVO.getTplCustomerPrvtEntity().getData().getCustKeyNameText() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustKeyNameText().toString()
: null );
String custTypeCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustTypeCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustTypeCode().toString()
: null );
String custFullNameText = ( fncVO.getTplCustomerPrvtEntity().getData().getCustFullNameText() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustFullNameText().toString()
: null );
String custActlStatCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustActlStatCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustActlStatCode().toString()
: null );
String custStatDate = ( fncVO.getTplCustomerPrvtEntity().getData().getCustStatDate() != null
? dateFormat.format( fncVO.getTplCustomerPrvtEntity().getData().getCustStatDate() )
: null );
String custEstabDate = ( fncVO.getTplCustomerPrvtEntity().getData().getCustEstabDate() != null
? dateFormat.format( fncVO.getTplCustomerPrvtEntity().getData().getCustEstabDate() )
: null );
String custEstabTime = ( fncVO.getTplCustomerPrvtEntity().getData().getCustEstabTime() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustEstabTime().toString()
: null );
String custEstabOpId = ( fncVO.getTplCustomerPrvtEntity().getData().getCustEstabOpId() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustEstabOpId().toString()
: null );
String custCnrLastMthAmt = ( fncVO.getTplCustomerPrvtEntity().getData().getCustCnrLastMthAmt() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustCnrLastMthAmt().toString()
: null );
String custCnrYtdAmt = ( fncVO.getTplCustomerPrvtEntity().getData().getCustCnrYtdAmt() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustCnrYtdAmt().toString()
: null );
String custCnrLastYrAmt = ( fncVO.getTplCustomerPrvtEntity().getData().getCustCnrLastYrAmt() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustCnrLastYrAmt().toString()
: null );
String custCnrLastSixMthCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustCnrLastSixMthCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustCnrLastSixMthCode().toString()
: null );
String lastUpdateDate = ( fncVO.getTplCustomerPrvtEntity().getData().getLastUpdateDate() != null
? formatDateTime( fncVO.getTplCustomerPrvtEntity().getData().getLastUpdateDate() )
: null );
String lastUpdateTime = ( fncVO.getTplCustomerPrvtEntity().getData().getLastUpdateTime() != null
? fncVO.getTplCustomerPrvtEntity().getData().getLastUpdateTime().toString()
: null );
String lastUpdateOpId = ( fncVO.getTplCustomerPrvtEntity().getData().getLastUpdateOpId() != null
? fncVO.getTplCustomerPrvtEntity().getData().getLastUpdateOpId().toString()
: null );
String apprvDate = ( fncVO.getTplCustomerPrvtEntity().getData().getApprvDate() != null
? formatDateTime( fncVO.getTplCustomerPrvtEntity().getData().getApprvDate() )
: null );
String apprvTime = ( fncVO.getTplCustomerPrvtEntity().getData().getApprvTime() != null
? fncVO.getTplCustomerPrvtEntity().getData().getApprvTime().toString()
: null );
String custInputOrigCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustInputOrigCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustInputOrigCode().toString()
: null );
String custDupCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustDupCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustDupCode().toString()
: null );
String custCorpBkrApplPrflInd = ( fncVO.getTplCustomerPrvtEntity().getData().getCustCorpBkrApplPrflInd() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustCorpBkrApplPrflInd().toString()
: null );
String custCorpFundApplPrflInd = ( fncVO.getTplCustomerPrvtEntity().getData().getCustCorpFundApplPrflInd() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustCorpFundApplPrflInd().toString()
: null );
String custCetipNbr = ( fncVO.getTplCustomerPrvtEntity().getData().getCustCetipNbr() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustCetipNbr().toString()
: null );
String custBmfNbr = ( fncVO.getTplCustomerPrvtEntity().getData().getCustBmfNbr() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustBmfNbr().toString()
: null );
String custBovespaNbr = ( fncVO.getTplCustomerPrvtEntity().getData().getCustBovespaNbr() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustBovespaNbr().toString()
: null );
String custBvrjNbr = ( fncVO.getTplCustomerPrvtEntity().getData().getCustBvrjNbr() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustBvrjNbr().toString()
: null );
String custSelicNbr = ( fncVO.getTplCustomerPrvtEntity().getData().getCustSelicNbr() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustSelicNbr().toString()
: null );
String custMktCatCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustMktCatCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustMktCatCode().toString()
: null );
String custNoCpfInd = ( fncVO.getTplCustomerPrvtEntity().getData().getCustNoCpfInd() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustNoCpfInd().toString()
: null );
String custNatId = ( fncVO.getTplCustomerPrvtEntity().getData().getCustNatId() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustNatId().toString()
: null );
String custNatIdApplDate = ( fncVO.getTplCustomerPrvtEntity().getData().getCustNatIdApplDate() != null
? dateFormat.format( fncVO.getTplCustomerPrvtEntity().getData().getCustNatIdApplDate() )
: null );
String custNatIdEmitCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustNatIdEmitCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustNatIdEmitCode().toString()
: null );
String custNatIdEmitName = ( fncVO.getTplCustomerPrvtEntity().getData().getCustNatIdEmitName() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustNatIdEmitName().toString()
: null );
String custNatIdEmitStateCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustNatIdEmitStateCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustNatIdEmitStateCode().toString()
: null );
String custCivilStatCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustCivilStatCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustCivilStatCode().toString()
: null );
String custSexCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustSexCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustSexCode().toString()
: null );
String custBirthDate = ( fncVO.getTplCustomerPrvtEntity().getData().getCustBirthDate() != null
? dateFormat.format( fncVO.getTplCustomerPrvtEntity().getData().getCustBirthDate() )
: null );
String custBirthCityText = ( fncVO.getTplCustomerPrvtEntity().getData().getCustBirthCityText() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustBirthCityText().toString()
: null );
String custBirthStateCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustBirthStateCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustBirthStateCode().toString()
: null );
String custBirthCntryCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustBirthCntryCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustBirthCntryCode().toString()
: null );
String custProfCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustProfCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustProfCode().toString()
: null );
String custEmplInd = ( fncVO.getTplCustomerPrvtEntity().getData().getCustEmplInd() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustEmplInd().toString()
: null );
String custDepndNbr = ( fncVO.getTplCustomerPrvtEntity().getData().getCustDepndNbr() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustDepndNbr().toString()
: null );
String custDepndNbrDate = ( fncVO.getTplCustomerPrvtEntity().getData().getCustDepndNbrDate() != null
? dateFormat.format( fncVO.getTplCustomerPrvtEntity().getData().getCustDepndNbrDate() )
: null );
String custOccupCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustOccupCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustOccupCode().toString()
: null );
String custMgmtIncoMinSalCount = ( fncVO.getTplCustomerPrvtEntity().getData().getCustMgmtIncoMinSalCount() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustMgmtIncoMinSalCount().toString()
: null );
String custChkDate = ( fncVO.getTplCustomerPrvtEntity().getData().getCustChkDate() != null
? dateFormat.format( fncVO.getTplCustomerPrvtEntity().getData().getCustChkDate() )
: null );
String custGrcardInd = ( fncVO.getTplCustomerPrvtEntity().getData().getCustGrcardInd() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustGrcardInd().toString()
: null );
String custSocSctyNbr = ( fncVO.getTplCustomerPrvtEntity().getData().getCustSocSctyNbr() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustSocSctyNbr().toString()
: null );
String custCpfOwnInd = ( fncVO.getTplCustomerPrvtEntity().getData().getCustCpfOwnInd() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustCpfOwnInd().toString()
: null );
String custParentLevelInd = ( fncVO.getTplCustomerPrvtEntity().getData().getCustParentLevelInd() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustParentLevelInd().toString()
: null );
String custUsaCtznAuthInd = ( fncVO.getTplCustomerPrvtEntity().getData().getCustUsaCtznAuthInd() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustUsaCtznAuthInd().toString()
: null );
String custUsaCtznAuthOpId = ( fncVO.getTplCustomerPrvtEntity().getData().getCustUsaCtznAuthOpId() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustUsaCtznAuthOpId().toString()
: null );
String custIndivPublicInd = ( fncVO.getTplCustomerPrvtEntity().getData().getCustIndivPublicInd() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustIndivPublicInd().toString()
: null );
String custCitiGrpTieInd = ( fncVO.getTplCustomerPrvtEntity().getData().getCustCitiGrpTieInd() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustCitiGrpTieInd().toString()
: null );
String custBirthCntryCoCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustBirthCntryCoCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustBirthCntryCoCode().toString()
: null );
String custActyAreaCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustActyAreaCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustActyAreaCode().toString()
: null );
String custNoCgcInd = ( fncVO.getTplCustomerPrvtEntity().getData().getCustNoCgcInd() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustNoCgcInd().toString()
: null );
String custFndtnDate = ( fncVO.getTplCustomerPrvtEntity().getData().getCustFndtnDate() != null
? dateFormat.format( fncVO.getTplCustomerPrvtEntity().getData().getCustFndtnDate() )
: null );
String custCoTypeCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustCoTypeCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustCoTypeCode().toString()
: null );
String custGrpCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustGrpCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustGrpCode().toString()
: null );
String custSubGrpCode = ( fncVO.getTplCustomerPrvtEntity().getData().getCustSubGrpCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustSubGrpCode().toString()
: null );
String custIntlNbr = ( fncVO.getTplCustomerPrvtEntity().getData().getCustIntlNbr() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustIntlNbr().toString()
: null );
String custIrrfExemptInd = ( fncVO.getTplCustomerPrvtEntity().getData().getCustIrrfExemptInd() != null
? fncVO.getTplCustomerPrvtEntity().getData().getCustIrrfExemptInd().toString()
: null );
String recStatCode = ( fncVO.getTplCustomerPrvtEntity().getData().getRecStatCode() != null
? fncVO.getTplCustomerPrvtEntity().getData().getRecStatCode().toString()
: null );
DataSet custSexCodeDomain = fncVO.getCustSexCodeDomain() != null
? fncVO.getCustSexCodeDomain()
: null;
DataSet custCivilStatCodeDomain = fncVO.getCustCivilStatCodeDomain() != null
? fncVO.getCustCivilStatCodeDomain()
: null;
DataSet custMktCatCodeDomain = fncVO.getCustMktCatCodeDomain() != null
? fncVO.getCustCivilStatCodeDomain()
: null;
DataSet custDupCodeDomain = fncVO.getCustDupCodeDomain() != null
? fncVO.getCustMktCatCodeDomain()
: null;
DataSet custTypeCodeDomain = fncVO.getCustTypeCodeDomain() != null
? fncVO.getCustTypeCodeDomain()
: null;
DataSet custCitiGrpTieIndDomain = fncVO.getCustCitiGrpTieIndDomain() != null
? fncVO.getCustCitiGrpTieIndDomain()
: null;
DataSet custCorpBkrApplPrflIndDomain = fncVO.getCustCorpBkrApplPrflIndDomain() != null
? fncVO.getCustCorpBkrApplPrflIndDomain()
: null;
DataSet custCorpFundApplPrflIndDomain = fncVO.getCustCorpFundApplPrflIndDomain() != null
? fncVO.getCustCorpFundApplPrflIndDomain()
: null;
DataSet custCpfOwnIndDomain = fncVO.getCustCpfOwnIndDomain() != null
? fncVO.getCustCpfOwnIndDomain()
: null;
DataSet custEmplIndDomain = fncVO.getCustEmplIndDomain() != null
? fncVO.getCustEmplIndDomain()
: null;
DataSet custGrcardIndDomain = fncVO.getCustGrcardIndDomain() != null
? fncVO.getCustGrcardIndDomain()
: null;
DataSet custIndivPublicIndDomain = fncVO.getCustIndivPublicIndDomain() != null
? fncVO.getCustIndivPublicIndDomain()
: null;
DataSet custIrrfExemptIndDomain = fncVO.getCustIrrfExemptIndDomain() != null
? fncVO.getCustIrrfExemptIndDomain()
: null;
DataSet custNoCgcIndDomain = fncVO.getCustNoCgcIndDomain() != null
? fncVO.getCustNoCgcIndDomain()
: null;
DataSet custNoCpfIndDomain = fncVO.getCustNoCpfIndDomain() != null
? fncVO.getCustNoCpfIndDomain()
: null;
DataSet custParentLevelIndDomain = fncVO.getCustParentLevelIndDomain() != null
? fncVO.getCustParentLevelIndDomain()
: null;
DataSet custUsaCtznAuthIndDomain = fncVO.getCustUsaCtznAuthIndDomain() != null
? fncVO.getCustUsaCtznAuthIndDomain()
: null;
/*
* RDIP - Inclusão do descritivo de risco
* Data: 05/01/2011
* Responsável: Eversystems
*/
String rdipDescription = (fncVO.getTplCustomerPrvtEntity().getData().getRdipDescription() != null) ?
fncVO.getTplCustomerPrvtEntity().getData().getRdipDescription():"";
form.setCustNbr( custNbr );
form.setCustCpfCnpjNbr( custCpfCnpjNbr );
form.setCustShortNameText( custShortNameText );
form.setApprvDate( apprvDate );
form.setApprvTime( apprvTime );
form.setCustActlStatCode( custActlStatCode );
form.setCustActyAreaCode( custActyAreaCode );
form.setCustBirthCityText( custBirthCityText );
form.setCustBirthCntryCode( custBirthCntryCode );
form.setCustBirthCntryCoCode( custBirthCntryCoCode );
form.setCustBirthDate( custBirthDate );
form.setCustBirthStateCode( custBirthStateCode );
form.setCustBmfNbr( custBmfNbr );
form.setCustBovespaNbr( custBovespaNbr );
form.setCustBvrjNbr( custBvrjNbr );
form.setCustCetipNbr( custCetipNbr );
form.setCustChkDate( custChkDate );
form.setCustCitiGrpTieInd( custCitiGrpTieInd );
form.setCustCivilStatCode( custCivilStatCode );
form.setCustCnrLastMthAmt( custCnrLastMthAmt );
form.setCustCnrLastSixMthCode( custCnrLastSixMthCode );
form.setCustCnrLastYrAmt( custCnrLastYrAmt );
form.setCustCnrYtdAmt( custCnrYtdAmt );
form.setCustCorpBkrApplPrflInd( custCorpBkrApplPrflInd );
form.setCustCorpFundApplPrflInd( custCorpFundApplPrflInd );
form.setCustCoTypeCode( custCoTypeCode );
form.setCustCpfOwnInd( custCpfOwnInd );
form.setCustDepndNbr( custDepndNbr );
form.setCustDepndNbrDate( custDepndNbrDate );
form.setCustDupCode( custDupCode );
form.setCustEmplInd( custEmplInd );
form.setCustEstabDate( custEstabDate );
form.setCustEstabOpId( custEstabOpId );
form.setCustEstabTime( custEstabTime );
form.setCustFndtnDate( custFndtnDate );
form.setCustFullNameText( custFullNameText );
form.setCustGrcardInd( custGrcardInd );
form.setCustGrpCode( custGrpCode );
form.setCustIndivPublicInd( custIndivPublicInd );
form.setCustInputOrigCode( custInputOrigCode );
form.setCustIntlNbr( custIntlNbr );
form.setCustIrrfExemptInd( custIrrfExemptInd );
form.setCustKeyNameText( custKeyNameText );
form.setCustMgmtIncoMinSalCount( custMgmtIncoMinSalCount );
form.setCustMktCatCode( custMktCatCode );
form.setCustNatId( custNatId );
form.setCustNatIdApplDate( custNatIdApplDate );
form.setCustNatIdEmitCode( custNatIdEmitCode );
form.setCustNatIdEmitName( custNatIdEmitName );
form.setCustNatIdEmitStateCode( custNatIdEmitStateCode );
form.setCustNoCgcInd( custNoCgcInd );
form.setCustNoCpfInd( custNoCpfInd );
form.setCustOccupCode( custOccupCode );
form.setCustParentLevelInd( custParentLevelInd );
form.setCustProfCode( custProfCode );
form.setCustSelicNbr( custSelicNbr );
form.setCustSexCode( custSexCode );
form.setCustSocSctyNbr( custSocSctyNbr );
form.setCustStatDate( custStatDate );
form.setCustSubGrpCode( custSubGrpCode );
form.setCustTypeCode( custTypeCode );
form.setCustUsaCtznAuthInd( custUsaCtznAuthInd );
form.setCustUsaCtznAuthOpId( custUsaCtznAuthOpId );
form.setLastUpdateDate( lastUpdateDate );
form.setLastUpdateOpId( lastUpdateOpId );
form.setLastUpdateTime( lastUpdateTime );
form.setRecStatCode( recStatCode );
form.setCustSexCodeDomain( custSexCodeDomain );
form.setCustCivilStatCodeDomain( custCivilStatCodeDomain );
form.setCustMktCatCodeDomain( custMktCatCodeDomain );
form.setCustDupCodeDomain( custDupCodeDomain );
form.setCustTypeCodeDomain( custTypeCodeDomain );
form.setCustCitiGrpTieIndDomain( custCitiGrpTieIndDomain );
form.setCustCorpBkrApplPrflIndDomain( custCorpBkrApplPrflIndDomain );
form.setCustCorpFundApplPrflIndDomain( custCorpFundApplPrflIndDomain );
form.setCustCpfOwnIndDomain( custCpfOwnIndDomain );
form.setCustEmplIndDomain( custEmplIndDomain );
form.setCustGrcardIndDomain( custGrcardIndDomain );
form.setCustIndivPublicIndDomain( custIndivPublicIndDomain );
form.setCustIrrfExemptIndDomain( custIrrfExemptIndDomain );
form.setCustNoCgcIndDomain( custNoCgcIndDomain );
form.setCustNoCpfIndDomain( custNoCpfIndDomain );
form.setCustParentLevelIndDomain( custParentLevelIndDomain );
form.setCustUsaCtznAuthIndDomain( custUsaCtznAuthIndDomain );
form.setCustPrvtStatCodeDomain( fncVO.getCustPrvtStatCodeDomain() );
form.setRdipDescription(rdipDescription);
form.setClassCmplcCode( fncVO.getTplCustomerPrvtCmplEntity().getData().getClassCmplcCode() != null
? fncVO.getTplCustomerPrvtCmplEntity().getData().getClassCmplcCode().toString()
: "" );
form.setPrvtCustTypeCode( fncVO.getTplCustomerPrvtCmplEntity().getData().getPrvtCustTypeCode() != null
? fncVO.getTplCustomerPrvtCmplEntity().getData().getPrvtCustTypeCode().toString()
: "" );
form.setCustNbrSrc( fncVO.getTplCustomerPrvtCmplEntity().getData().getCustNbr() != null
? fncVO.getTplCustomerPrvtCmplEntity().getData().getCustNbr().toString()
: "" );
form.setEmNbr( fncVO.getTplCustomerPrvtCmplEntity().getData().getEmNbr() != null
? fncVO.getTplCustomerPrvtCmplEntity().getData().getEmNbr()
: "" );
form.setErNbr( fncVO.getTplCustomerPrvtCmplEntity().getData().getErNbr() != null
? fncVO.getTplCustomerPrvtCmplEntity().getData().getErNbr()
: "" );
form.setOffcrNbrSrc( fncVO.getTplCustomerPrvtCmplEntity().getData().getOffcrNbr() != null
? fncVO.getTplCustomerPrvtCmplEntity().getData().getOffcrNbr().toString()
: "" );
form.setPrvtKeyNbr( fncVO.getTplCustomerPrvtCmplEntity().getData().getPrvtKeyNbr() != null
&& fncVO.getTplCustomerPrvtCmplEntity().getData().getPrvtKeyNbr().longValue() > 0
? fncVO.getTplCustomerPrvtCmplEntity().getData().getPrvtKeyNbr().toString()
: "" );
form.setPrvtCustNbr( fncVO.getTplCustomerPrvtCmplEntity().getData().getPrvtCustNbr() != null
&& fncVO.getTplCustomerPrvtCmplEntity().getData().getPrvtCustNbr().longValue() > 0
? fncVO.getTplCustomerPrvtCmplEntity().getData().getPrvtCustNbr().toString()
: "" );
form.setWealthPotnlCode( fncVO.getTplCustomerPrvtCmplEntity().getData().getWealthPotnlCode() != null
? fncVO.getTplCustomerPrvtCmplEntity().getData().getWealthPotnlCode().toString()
: "" );
form.setMailRecvInd( fncVO.getTplCustomerPrvtCmplEntity().getData().getMailRecvInd() != null
? fncVO.getTplCustomerPrvtCmplEntity().getData().getMailRecvInd()
: "" );
form.setOffclMailRecvInd( fncVO.getTplCustomerPrvtCmplEntity().getData().getOffclMailRecvInd() != null
? fncVO.getTplCustomerPrvtCmplEntity().getData().getOffclMailRecvInd()
: "" );
form.setGlbRevenSysOffcrNbr( fncVO.getTplCustomerPrvtCmplEntity().getData().getGlbRevenSysOffcrNbr() != null
&& fncVO.getTplCustomerPrvtCmplEntity().getData().getGlbRevenSysOffcrNbr().longValue() > 0
? fncVO.getTplCustomerPrvtCmplEntity().getData().getGlbRevenSysOffcrNbr().toString()
: "" );
form.setClassCmplcCodeDomain( fncVO.getClassCmplcCodeDomain() );
form.setPrvtCustTypeCodeDomain( fncVO.getPrvtCustTypeCodeDomain());
form.setWealthPotnlCodeDomain( fncVO.getWealthPotnlCodeDomain() );
form.setOffclMailRecvIndDomain( fncVO.getOffclMailRecvIndDomain() );
form.setMailRecvIndDomain( fncVO.getMailRecvIndDomain() );
if ( fncVO.getTplCustomerPrvtCmplEntity().getData().getCustNbr() != null
&& fncVO.getTplCustomerPrvtCmplEntity().getData().getCustNbr().longValue() > 0 )
{
form.setCustText( fncVO.getCustText() );
}
else
{
form.setCustText( "" );
}
if ( fncVO.getTplCustomerPrvtCmplEntity().getData().getOffcrNbr() != null
&& fncVO.getTplCustomerPrvtCmplEntity().getData().getOffcrNbr().intValue() > 0 )
{
form.setOffcrText( fncVO.getOffcrText() );
}
else
{
form.setOffcrText( "" );
}
String custPrvtStatCode = fncVO.getTplCustomerPrvtCmplEntity().getData().getCustPrvtStatCode() != null
? fncVO.getTplCustomerPrvtCmplEntity().getData().getCustPrvtStatCode()
: "";
form.setClickedSearch( fncVO.getClickedSearch() );
form.setCustPrvtStatCode( custPrvtStatCode );
}
/*
* Metodo que carrega os Combos da Tela...
* @see com.citibank.ods.common.functionality.BaseFnc#createFncVO()
*/
public void load( BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
BaseTplCustomerPrvtEntity customerPrvtEntity = null;
BaseCustomerPrvtDetailFncVO detailFncVO = ( BaseCustomerPrvtDetailFncVO ) customerPrvtDetailFncVO_;
BaseTplCustomerPrvtDAO customerPrvtDAO = this.getDAO();
customerPrvtEntity = customerPrvtDAO.find( detailFncVO.getTplCustomerPrvtEntity() );
detailFncVO.setTplCustomerPrvtEntity( customerPrvtEntity );
if ( detailFncVO.getCmplDataButtonControl().equals( C_EXISTING_DATA_CMPL ) )
{
ODSDAOFactory odsDAOFactory = ODSDAOFactory.getInstance();
TplCustomerPrvtCmplDAO tplCustomerPrvtCmplDAO = odsDAOFactory.getTplCustomerPrvtCmplDAO();
detailFncVO.getTplCustomerPrvtCmplEntity().getData().setCustNbr(
detailFncVO.getTplCustomerPrvtEntity().getData().getCustNbr() );
detailFncVO.setTplCustomerPrvtCmplEntity( tplCustomerPrvtCmplDAO.find( detailFncVO.getTplCustomerPrvtCmplEntity() ) );
}
}
protected void loadDomains(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
loadCustCitiGrpTieIndDomain( customerPrvtDetailFncVO_ );
loadCustCorpBkrApplPrflIndDomain( customerPrvtDetailFncVO_ );
loadCustCorpFundApplPrflIndDomain( customerPrvtDetailFncVO_ );
loadCustCpfOwnIndDomain( customerPrvtDetailFncVO_ );
loadCustEmplIndDomain( customerPrvtDetailFncVO_ );
loadCustGrcardIndDomain( customerPrvtDetailFncVO_ );
loadCustIndivPublicIndDomain( customerPrvtDetailFncVO_ );
loadCustIrrfExemptIndDomain( customerPrvtDetailFncVO_ );
loadCustNoCgcIndDomain( customerPrvtDetailFncVO_ );
loadCustNoCpfIndDomain( customerPrvtDetailFncVO_ );
loadCustParentLevelIndDomain( customerPrvtDetailFncVO_ );
loadCustUsaCtznAuthIndDomain( customerPrvtDetailFncVO_ );
loadClassCmplcDomain( customerPrvtDetailFncVO_ );
loadPrvtCustTypeDomain( customerPrvtDetailFncVO_);
loadWealthPotnlDomain( customerPrvtDetailFncVO_ );
loadCustText( customerPrvtDetailFncVO_ );
loadOffcrText( customerPrvtDetailFncVO_ );
loadMailRecvIndDomain( customerPrvtDetailFncVO_ );
loadOffclMailRecvIndDomain( customerPrvtDetailFncVO_ );
loadCustPrvtStatCode( customerPrvtDetailFncVO_ );
}
public void loadErEm( BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
if (customerPrvtDetailFncVO_.getTplCustomerPrvtEntity().getData().getEmNbr()!= null)
{
ODSDAOFactory odsDAOFactory = ODSDAOFactory.getInstance();
TplErEmDAO erEmDAO = odsDAOFactory.getTplErEmDAO();
customerPrvtDetailFncVO_.setErEmEntities( erEmDAO.listByErNbr(customerPrvtDetailFncVO_.getTplCustomerPrvtEntity().getData().getErNbr(),
customerPrvtDetailFncVO_.getTplCustomerPrvtEntity().getData().getEmNbr() ) );
}
}
private void loadCustCitiGrpTieIndDomain(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setCustCitiGrpTieIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
private void loadCustCorpBkrApplPrflIndDomain(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setCustCorpBkrApplPrflIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
private void loadCustCorpFundApplPrflIndDomain(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setCustCorpFundApplPrflIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
private void loadCustCpfOwnIndDomain(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setCustCpfOwnIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
private void loadCustEmplIndDomain(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setCustEmplIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
private void loadCustGrcardIndDomain(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setCustGrcardIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
private void loadCustIndivPublicIndDomain(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setCustIndivPublicIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
private void loadCustIrrfExemptIndDomain(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setCustIrrfExemptIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
private void loadCustNoCgcIndDomain(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setCustNoCgcIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
private void loadCustNoCpfIndDomain(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setCustNoCpfIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
private void loadCustParentLevelIndDomain(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setCustParentLevelIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
private void loadCustUsaCtznAuthIndDomain(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setCustUsaCtznAuthIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
private void loadCustPrvtStatCode(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setCustPrvtStatCodeDomain( ODSConstraintDecoder.decodeCustomerStatCode() );
}
private void loadClassCmplcDomain( BaseCustomerPrvtDetailFncVO customerFncVO_ )
{
//Obtém a instância da Factory
ODSDAOFactory factory = ODSDAOFactory.getInstance();
//Obtém a instância do DAO necessário
TplClassCmplcDAO classCmplcDAO = factory.getTplClassCmplcDAO();
//Realiza a consulta no DAO
DataSet result = classCmplcDAO.loadDomain();
//Atualiza o(s) atributo(s) do fncVO com o(s) dado(s) retornado(s)
customerFncVO_.setClassCmplcCodeDomain( result );
}
private void loadPrvtCustTypeDomain( BaseCustomerPrvtDetailFncVO customerFncVO_ )
{
//Obtém a instância da Factory
ODSDAOFactory factory = ODSDAOFactory.getInstance();
//Obtém a instância do DAO necessário
TplCustomerPrvtTypeDAO customerPrvtTypeDAO = factory.getTplCustomerPrvtTypeDAO();
//Realiza a consulta no DAO
DataSet result = customerPrvtTypeDAO.loadDomain();
//Atualiza o(s) atributo(s) do fncVO com o(s) dado(s) retornado(s)
customerFncVO_.setPrvtCustTypeCodeDomain( result );
}
private void loadWealthPotnlDomain( BaseCustomerPrvtDetailFncVO customerFncVO_ )
{
//Obtém a instância da Factory
ODSDAOFactory factory = ODSDAOFactory.getInstance();
//Obtém a instância do DAO necessário
TplPotentialWealthDAO potentialWealthDAO = factory.getTplPotentialWealthDAO();
//Realiza a consulta no DAO
DataSet result = potentialWealthDAO.loadDomain();
//Atualiza o(s) atributo(s) do fncVO com o(s) dado(s) retornado(s)
customerFncVO_.setWealthPotnlCodeDomain( result );
}
public void loadCustText( BaseCustomerPrvtDetailFncVO customerFncVO_ )
{
if ( customerFncVO_.getTplCustomerPrvtCmplEntity().getData().getCustNbr() != null
&& customerFncVO_.getTplCustomerPrvtCmplEntity().getData().getCustNbr().longValue() > 0 )
{
TplCustomerPrvtEntity customerPrvtEntity = new TplCustomerPrvtEntity();
customerPrvtEntity.getData().setCustNbr(
customerFncVO_.getTplCustomerPrvtCmplEntity().getData().getCustNbr() );
//Obtém a instância da Factory
ODSDAOFactory factory = ODSDAOFactory.getInstance();
//Obtém a instância do DAO necessário
TplCustomerPrvtDAO tplCustomerPrvtDAO = factory.getTplCustomerPrvtDAO();
//Realiza a consulta no DAO
customerPrvtEntity = ( TplCustomerPrvtEntity ) tplCustomerPrvtDAO.find( customerPrvtEntity );
//Atualiza o(s) atributo(s) do fncVO com o(s) dado(s) retornado(s)
customerFncVO_.setCustText( customerPrvtEntity.getData().getCustFullNameText() );
}
}
public void loadOffcrText( BaseCustomerPrvtDetailFncVO customerFncVO_ )
{
if ( customerFncVO_.getTplCustomerPrvtCmplEntity().getData().getOffcrNbr() != null
&& customerFncVO_.getTplCustomerPrvtCmplEntity().getData().getOffcrNbr().intValue() > 0 )
{
TbgOfficerEntity officerEntity = new TbgOfficerEntity();
officerEntity.getData().setOffcrNbr(
customerFncVO_.getTplCustomerPrvtCmplEntity().getData().getOffcrNbr() );
//Obtém a instância da Factory
ODSDAOFactory factory = ODSDAOFactory.getInstance();
//Obtém a instância do DAO necessário
TbgOfficerDAO tbgOfficerDAO = factory.getTbgOfficerDAO();
//Realiza a consulta no DAO
officerEntity = ( TbgOfficerEntity ) tbgOfficerDAO.find( officerEntity );
//Atualiza o(s) atributo(s) do fncVO com o(s) dado(s) retornado(s)
customerFncVO_.setOffcrText( officerEntity.getData().getOffcrNameText() );
}
}
private void loadMailRecvIndDomain(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setMailRecvIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
private void loadOffclMailRecvIndDomain(
BaseCustomerPrvtDetailFncVO customerPrvtDetailFncVO_ )
{
customerPrvtDetailFncVO_.setOffclMailRecvIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
/**
* Converte uma data para o formato de apresentação.
*
* @param date_ - A data a ser convertida - TimeStamp
* @return String - A data no formato de apresentação.
*/
private String formatDateTime( Date date_ )
{
DateFormat dateFormat = new SimpleDateFormat(
Globals.FuncionalityFormatKeys.C_FORMAT_PRESENTATION );
return dateFormat.format( date_ );
}
protected abstract BaseTplCustomerPrvtDAO getDAO();
} |
package pt.joja;
public class JojaDoubleLinkedList {
public static void main(String[] args) {
JojaDoubleLinkedList doubleLinkedList = new JojaDoubleLinkedList();
doubleLinkedList.add(new DoubleHeroNode(1, "宋江", "及时雨"));
doubleLinkedList.add(new DoubleHeroNode(3, "吴用", "智多星"));
doubleLinkedList.add(new DoubleHeroNode(2, "卢俊义", "玉麒麟"));
doubleLinkedList.add(new DoubleHeroNode(4, "林冲", "豹子头"));
doubleLinkedList.list();
}
// 头节点
DoubleHeroNode head = new DoubleHeroNode(0, "", "");
public DoubleHeroNode getHead() {
return head;
}
public void add(DoubleHeroNode heroNode) {
DoubleHeroNode curr = head;
while (curr.next != null) {
curr = curr.next;
}
curr.next = heroNode;
heroNode.prev = curr;
}
public void list() {
DoubleHeroNode curr = head.next;
System.out.println("JojaLinkedList: [");
while (curr != null) {
System.out.println(curr);
curr = curr.next;
}
System.out.println("]");
}
}
class DoubleHeroNode {
int no;
String name;
String nickName;
DoubleHeroNode next;
DoubleHeroNode prev;
public DoubleHeroNode(int no, String name, String nickName) {
this.no = no;
this.name = name;
this.nickName = nickName;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("DoubleHeroNode: { ");
sb.append("no: " + no);
sb.append(", name: " + name);
sb.append(", nickName: " + nickName);
sb.append(" }");
return sb.toString();
}
}
|
package streams.collect;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import common.EmpDAO;
import common.Employee;
public class CollectionDataBaseExample {
public static void main(String[] args) {
//employee테이블에서 1990년대에 입사한 사람들을 List컬렉션에 저장하기
List<Employee> empList = EmpDAO.getEmpList();
Stream<Employee> stream = empList.stream();
LocalDate start = LocalDate.parse("1989-12-31",DateTimeFormatter.ISO_DATE);
LocalDate end = LocalDate.parse("2000-01-01",DateTimeFormatter.ISO_DATE);
// stream.filter(a -> a.getHireDate().isAfter(start)).filter(a->a.getHireDate().isBefore(end))
// .forEach(a -> System.out.println("이름: " + a.getLastName()+ "\t" +"입사일: " + a.getHireDate()));
//job -> ST_CLERK인 사람들의 이름과 급여를 컬렉션에 저장하기
// System.out.println("-------------이름과 급여-------------");
// stream = empList.stream();
// Map<String, Integer> map = stream.filter(a -> a.getJobId().equals("ST_CLERK"))
// .collect(Collectors.toMap(new Function<Employee, String>() {
// @Override
// public String apply(Employee t) {
// return t.getLastName();
// }
// }, new Function<Employee, Integer>() {
// @Override
// public Integer apply(Employee t) {
// return t.getSalary();
// }
// }));
// Set<String> keys = map.keySet();
// for(String s : keys) {
// System.out.println("이름: " + s + ", 급여: " + map.get(s));
// }
// System.out.println();
//job -> ST_CLERK인 사람들의 이름과 급여를 컬렉션에 저장하기<람다!>
System.out.println("-------------이름과 급여-------------");
stream = empList.stream();
Map<String, Integer> map = stream.filter(a -> a.getJobId().equals("ST_CLERK"))
.collect(Collectors.toMap(a -> a.getLastName(), b -> b.getSalary()));
Set<String> keys = map.keySet();
for(String s : keys) {
System.out.println("이름: " + s + "\t" + " 급여: " + map.get(s));
}
System.out.println();
System.out.println("-------------이름과 부서-------------");
stream = empList.stream();
stream.filter(a -> a.getJobId().equals("ST_CLERK"))
.forEach(a -> System.out.println("이름: " + a.getLastName() + "\t" + "부서: " + a.getJobId()));
}
}
|
package com.aob.spring.securityRegistration.repository.model;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@Entity
public class ProjectTask {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String name;
@DateTimeFormat
private LocalDate startDate;
@DateTimeFormat
private LocalDate endDate;
private SubTaskStatus status;
@ManyToOne
@JoinColumn (name = "project_id")
private Project project;
@OneToMany(
mappedBy = "projectTask",
cascade = CascadeType.ALL
)
private List<ProjectSubTask> projectSubTasks = new ArrayList<>();
public ProjectTask() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getStartDate() {
return startDate;
}
public void setStartDate(LocalDate startDate) {
this.startDate = startDate;
}
public LocalDate getEndDate() {
return endDate;
}
public void setEndDate(LocalDate endDate) {
this.endDate = endDate;
}
public SubTaskStatus getStatus() {
return status;
}
public void setStatus(SubTaskStatus status) {
this.status = status;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public List<ProjectSubTask> getProjectSubTasks() {
return projectSubTasks;
}
public void setProjectSubTasks(List<ProjectSubTask> projectSubTasks) {
this.projectSubTasks = projectSubTasks;
}
public void setProjectSubTask(ProjectSubTask projectSubTask) {
this.projectSubTasks.add(projectSubTask);
}
}
|
package com.maliang.core.model;
import java.util.Map;
public class Dict {
private ObjectField key;
private ObjectField value;
private Map<Object,Object> dicts;
public ObjectField getKey() {
return key;
}
public void setKey(ObjectField key) {
this.key = key;
}
public ObjectField getValue() {
return value;
}
public void setValue(ObjectField value) {
this.value = value;
}
public Map<Object, Object> getDicts() {
return dicts;
}
public void setDicts(Map<Object, Object> dicts) {
this.dicts = dicts;
}
}
|
import java.io.FileReader;
import java.util.Iterator;
import com.sgurjar.AppConfig;
/** This is a test driver and sample usage of AppConfig class. **/
public class T1 {
public static void main(String[] args) throws Exception {
String file=
//"YAML-AppConfig-0.16/t/data/config.yaml"
//"YAML-AppConfig-0.16/t/data/normal.yaml"
"YAML-AppConfig-0.16/t/data/vars.yaml"
//"YAML-AppConfig-0.16/t/data/scoping.yaml"
;
AppConfig appconfig=new AppConfig(new FileReader(file));
for(Iterator it=appconfig.config_keys(); it.hasNext();){
String key=(String)it.next();
try{
System.out.println(key + "=" + appconfig.get(key));
}catch(AssertionError e){System.err.println(e.toString());}
}
//System.out.println("eep="+appconfig.get("breezy"));
//System.out.println(appconfig.config());
}
}
|
package com.example.rodrigo.lab2;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.RoomDatabase;
/**
* Created by Rodrigo on 01/03/2018.
*/
@Database(entities = {Fruit.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase{
public abstract FruitsDao fruitsDao();
}
|
package edu.lewis.ap.whitt.rose;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import edu.jenks.dist.lewis.ap.AbstractHighSchoolClass;
import edu.jenks.dist.lewis.ap.Student;
public class HighSchoolClass extends AbstractHighSchoolClass {
int numStudents = students.length;
public HighSchoolClass(Student[] students) {
super(students);
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
}
public double getHighestGPA() {
double[] studGPAs = new double[numStudents];
for (int i = 0; i < numStudents; i++) {
studGPAs[i] = students[i].getGpa();
}
Arrays.sort(studGPAs);
return studGPAs[studGPAs.length - 1];
}
public Student[] getValedictorian() {
double highestGPA = getHighestGPA();
ArrayList<Student> valsList = new ArrayList<Student>();
for (int i = 0; i < students.length; i++) {
if (students[i].getGpa() == highestGPA) {
valsList.add(students[i]);
}
}
Student[] valsArray = (Student[]) valsList.toArray(new Student[] {});
return valsArray;
// Student curVal = students[0];
// for (int i = 0; i < numStudents; i++) {
// if (students[i].getGpa() > curVal.getGpa()) {
// curVal = students[i];
// }
// }
// Student[] test = {curVal};
// return test;
//
// double[] studGPAs = new double[numStudents];
// for (int i = 0; i < numStudents; i++) {
// studGPAs[i] = students[i].getGpa();
// }
// Arrays.sort(studGPAs);
// //find highest gpa and then search all students for that gpa
}
public double getHonorsPercent() {
Student[] honorsStudentsArray = getHonorsStudents();
int numHonorsStudents = honorsStudentsArray.length;
return ((double) numHonorsStudents * 100) / (double) numStudents;
}
public double graduateWithHonorsPercent() {
ArrayList<Student> honorsStudentsList = new ArrayList<Student>();
for (int i = 0; i < numStudents; i++) {
if (students[i].getGpa() >= HONORS_GPA) {
honorsStudentsList.add(students[i]);
}
}
Student[] honorsStudentsArray = (Student[]) honorsStudentsList.toArray(new Student[] {});
int numGradHonors = honorsStudentsArray.length;
return ((double) numGradHonors * 100) / (double) numStudents;
}
public double graduateWithHighestHonorsPercent() {
ArrayList<Student> honorsStudentsList = new ArrayList<Student>();
for (int i = 0; i < numStudents; i++) {
if (students[i].getGpa() >= HIGHEST_HONORS_GPA) {
honorsStudentsList.add(students[i]);
}
}
Student[] honorsStudentsArray = (Student[]) honorsStudentsList.toArray(new Student[] {});
int numGradHonors = honorsStudentsArray.length;
return ((double) numGradHonors * 100) / (double) numStudents;
}
public Student[] getHonorsStudents() {
ArrayList<Student> honorsStudentsList = new ArrayList<Student>();
for (int i = 0; i < numStudents; i++) {
if (students[i].isHonors()) {
honorsStudentsList.add(students[i]);
}
}
Student[] honorsStudentsArray = (Student[]) honorsStudentsList.toArray(new Student[] {});
return honorsStudentsArray;
}
}
|
package com.karya.bean;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
public class ItemShortageReportBean {
private int shrepid;
@NotNull
@NotEmpty(message = "Please enter the warehouse name")
private String warehouseName;
@NotNull
@NotEmpty(message = "Please enter the item")
private String itemCode;
private String actualQty;
private String orderedQty;
private String plannedQty;
private String reservedQty;
private String projectedQty;
public int getShrepid() {
return shrepid;
}
public void setShrepid(int shrepid) {
this.shrepid = shrepid;
}
public String getWarehouseName() {
return warehouseName;
}
public void setWarehouseName(String warehouseName) {
this.warehouseName = warehouseName;
}
public String getItemCode() {
return itemCode;
}
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getActualQty() {
return actualQty;
}
public void setActualQty(String actualQty) {
this.actualQty = actualQty;
}
public String getOrderedQty() {
return orderedQty;
}
public void setOrderedQty(String orderedQty) {
this.orderedQty = orderedQty;
}
public String getPlannedQty() {
return plannedQty;
}
public void setPlannedQty(String plannedQty) {
this.plannedQty = plannedQty;
}
public String getReservedQty() {
return reservedQty;
}
public void setReservedQty(String reservedQty) {
this.reservedQty = reservedQty;
}
public String getProjectedQty() {
return projectedQty;
}
public void setProjectedQty(String projectedQty) {
this.projectedQty = projectedQty;
}
}
|
/**
* --------------------------------------------------------------------------------------------------------------------
* <copyright company="Aspose Pty Ltd" file="PreviewResult.java">
* Copyright (c) 2003-2023 Aspose Pty Ltd
* </copyright>
* <summary>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* </summary>
* --------------------------------------------------------------------------------------------------------------------
*/
package com.groupdocs.cloud.signature.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.groupdocs.cloud.signature.model.FileInfo;
import com.groupdocs.cloud.signature.model.PreviewPage;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Document preview result
*/
@ApiModel(description = "Document preview result")
public class PreviewResult {
@SerializedName("fileInfo")
private FileInfo fileInfo = null;
@SerializedName("size")
private Long size = null;
@SerializedName("pagesCount")
private Integer pagesCount = null;
@SerializedName("pages")
private List<PreviewPage> pages = null;
public PreviewResult fileInfo(FileInfo fileInfo) {
this.fileInfo = fileInfo;
return this;
}
/**
* Input File info
* @return fileInfo
**/
@ApiModelProperty(value = "Input File info")
public FileInfo getFileInfo() {
return fileInfo;
}
public void setFileInfo(FileInfo fileInfo) {
this.fileInfo = fileInfo;
}
public PreviewResult size(Long size) {
this.size = size;
return this;
}
/**
* Input File size
* @return size
**/
@ApiModelProperty(required = true, value = "Input File size")
public Long getSize() {
return size;
}
public void setSize(Long size) {
this.size = size;
}
public PreviewResult pagesCount(Integer pagesCount) {
this.pagesCount = pagesCount;
return this;
}
/**
* Count of pages
* @return pagesCount
**/
@ApiModelProperty(required = true, value = "Count of pages")
public Integer getPagesCount() {
return pagesCount;
}
public void setPagesCount(Integer pagesCount) {
this.pagesCount = pagesCount;
}
public PreviewResult pages(List<PreviewPage> pages) {
this.pages = pages;
return this;
}
public PreviewResult addPagesItem(PreviewPage pagesItem) {
if (this.pages == null) {
this.pages = new ArrayList<PreviewPage>();
}
this.pages.add(pagesItem);
return this;
}
/**
* Document preview pages
* @return pages
**/
@ApiModelProperty(value = "Document preview pages")
public List<PreviewPage> getPages() {
return pages;
}
public void setPages(List<PreviewPage> pages) {
this.pages = pages;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PreviewResult previewResult = (PreviewResult) o;
return Objects.equals(this.fileInfo, previewResult.fileInfo) &&
Objects.equals(this.size, previewResult.size) &&
Objects.equals(this.pagesCount, previewResult.pagesCount) &&
Objects.equals(this.pages, previewResult.pages);
}
@Override
public int hashCode() {
return Objects.hash(fileInfo, size, pagesCount, pages);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PreviewResult {\n");
sb.append(" fileInfo: ").append(toIndentedString(fileInfo)).append("\n");
sb.append(" size: ").append(toIndentedString(size)).append("\n");
sb.append(" pagesCount: ").append(toIndentedString(pagesCount)).append("\n");
sb.append(" pages: ").append(toIndentedString(pages)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package com.mpls.v2.model;
import javax.persistence.*;
import java.util.List;
import static java.util.stream.Collectors.toList;
@Entity
@Table(name = "team")
public class Group {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Column(columnDefinition = "TEXT")
private String description;
private String image;
private Boolean available;
@OneToMany(mappedBy = "team")
private List<User> users;
public Group() {
}
public Group(String name, String description, String image, List<User> users) {
this.name = name;
this.description = description;
this.image = image;
this.users = users;
}
public Boolean getAvailable() {
return available;
}
public Group setAvailable(Boolean available) {
this.available = available;
return this;
}
public Long getId() {
return id;
}
public Group setId(Long id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public Group setName(String name) {
this.name = name;
return this;
}
public String getDescription() {
return description;
}
public Group setDescription(String description) {
this.description = description;
return this;
}
public String getImage() {
return image;
}
public Group setImage(String image) {
this.image = image;
return this;
}
public List<User> getUsers() {
return users;
}
public Group setUsers(List<User> users) {
this.users = users;
return this;
}
@Override
public String toString() {
return "Group{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", image='" + image + '\'' +
", users=" + users.stream().map(User::getUsername).collect(toList()) +
'}';
}
}
|
package org.eddy.rest;
import org.eddy.rest.annotation.RestReference;
import org.eddy.rest.sample.RestTestInterface;
import org.eddy.rest.sample.Say;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static com.google.common.base.CaseFormat.LOWER_CAMEL;
import static com.google.common.base.CaseFormat.LOWER_UNDERSCORE;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RestApplication.class)
public class RestApplicationTests {
@Autowired
private Say say;
@RestReference(url = "http://localhost:8080")
private RestTestInterface restTestInterface;
@Test
public void contextLoads() {
System.out.println(say.getRestSayJson());
System.out.println(restTestInterface.getRestSayJson());
}
@Test
public void test() {
String result = LOWER_CAMEL.to(LOWER_UNDERSCORE, "toString");
System.out.println(result);
}
}
|
package com.ascendaz.roster.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Not Supported Rule")
public class RosterEngineException extends Exception{
private static final long serialVersionUID = 127145295086141737L;
private String message;
public RosterEngineException(String message) {
super();
this.message = message;
}
public String getMessage() {
return message;
}
}
|
package com.bon.common.domain.dto;
import com.alibaba.fastjson.JSONObject;
import com.bon.common.util.StringUtils;
import io.swagger.annotations.ApiModelProperty;
import tk.mybatis.mapper.entity.Example;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
import java.util.Map;
/**
* @program: dubbo-wxmanage
* @description: 基础数据传输对象
* @author: Bon
* @create: 2018-05-03 18:35
**/
public class PageDTO<T> implements Serializable {
@ApiModelProperty(value = "当前页", example = "1")
private int pageNum = 1;
@ApiModelProperty(value = "页面大小", example = "1000")
private int pageSize = 1000;
@ApiModelProperty(value = "排序字段")
private String orderBy;
@ApiModelProperty(value = "是否进行count查询", example = "false", hidden = true)
private boolean count;
@ApiModelProperty(value = "分页合理化", example = "false", hidden = true)
private Boolean reasonable;
@ApiModelProperty(value = "当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果", example = "false", hidden = true)
private Boolean pageSizeZero;
@ApiModelProperty(value = "查询关键字,举例{\"equal_id\":\"1\",\"orMap\":\"{'equal_userId':'2','like_name':'2','in_name':'1,2,3','isNotNull':'name'}\"}", example = "{\"in:id\":\"1,2,3\",\"or:\":\"{'id=':'2','name=':'2','in:name':'1,2,3'}\"}")
private Map<String, Object> keyMap;
@ApiModelProperty(value = "查询模板", hidden = true)
private Example example;
@ApiModelProperty(value = "泛型类型", hidden = true)
private Class<T> tClass;
@ApiModelProperty(value = "模板条件", hidden = true)
private Example.Criteria criteria;
//获取T的class类型
public void getTClass(){
this.tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
//根据条件创建查询模板(根据定义泛型)
public Example createExample() {
this.getTClass();
if (null != this.getKeyMap()) {
example = new Example(tClass);
String flag = "";
for (Map.Entry<String, Object> entry : keyMap.entrySet()) {
if(entry.getValue()==null||StringUtils.isBlank(entry.getValue().toString())){
break;
}
//获取标识值 or:,in: ,notIn:,isNull,isNotNull等等
flag = entry.getKey().split("_")[0];
String key= "";
switch (flag) {
case "orMap":
Map<String, Object> map = JSONObject.parseObject(entry.getValue().toString(),Map.class);
Example example1 = new Example(tClass);
Example.Criteria criteria = example1.createCriteria();
for (Map.Entry<String,Object> en: map.entrySet()) {
//判断类型
if(en.getKey().split("_")[0].equals("isNull")){
criteria.andIsNull(en.getValue().toString());
}else if(en.getKey().split("_")[0].equals("isNotNull")){
criteria.andIsNotNull(en.getValue().toString());
}else if(en.getKey().split("_")[0].equals("in")){
criteria.andIn(StringUtils.camel2Underline(en.getKey().split("_")[1]),Arrays.asList(en.getValue().toString().split(",")));
}else if(en.getKey().split("_")[0].equals("notIn")){
criteria.andNotIn(StringUtils.camel2Underline(en.getKey().split("_")[1]),Arrays.asList(en.getValue().toString().split(",")));
}else if(en.getKey().split("_")[0].equals("equal")){
criteria.andCondition(StringUtils.camel2Underline(en.getKey().split("_")[1])+" =",en.getValue());
}else if(en.getKey().split("_")[0].equals("like")){
criteria.andCondition(StringUtils.camel2Underline(en.getKey().split("_")[1])+" like",en.getValue());
}
}
example.or(criteria);
break;
case "orEqual":
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.or().andCondition(key+" =", entry.getValue());
break;
case "orLike":
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.or().andCondition(key+" like", "%"+entry.getValue()+"%");
break;
case "in":
String strIn[] = entry.getValue().toString().split(",");
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.and().andIn(key,Arrays.asList(strIn));
break;
case "notIn":
String strNotIn[] = entry.getValue().toString().split(",");
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.and().andNotIn(key,Arrays.asList(strNotIn));
break;
case "isNull":
example.and().andIsNull(StringUtils.camel2Underline(entry.getValue().toString()));
break;
case "isNotNull":
example.and().andIsNotNull(StringUtils.camel2Underline(entry.getValue().toString()));
break;
case "equal":
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.and().andCondition(key+" =", entry.getValue());
break;
case "like":
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.and().andCondition(key+" like", "%"+entry.getValue()+"%");
break;
case "greater":
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.and().andCondition(key+ " >=", entry.getValue());
break;
case "less":
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.and().andCondition(key+ " <=", entry.getValue());
break;
default:
example.and().andCondition(entry.getKey(), entry.getValue());
break;
}
}
return example;
} else {
return null;
}
}
//根据条件创建查询模板(自定义泛型)
public Example createExample(T t) {
if (null != this.getKeyMap()) {
example = new Example(t.getClass());
String flag = "";
for (Map.Entry<String, Object> entry : keyMap.entrySet()) {
if(entry.getValue()==null||StringUtils.isBlank(entry.getValue().toString())){
break;
}
//获取标识值 or:,in: ,notIn:,isNull,isNotNull等等
flag = entry.getKey().split("_")[0];
String key= "";
switch (flag) {
case "orMap":
Map<String, Object> map = JSONObject.parseObject(entry.getValue().toString(),Map.class);
Example example1 = new Example(tClass);
Example.Criteria criteria = example1.createCriteria();
for (Map.Entry<String,Object> en: map.entrySet()) {
//判断类型
if(en.getKey().split("_")[0].equals("isNull")){
criteria.andIsNull(en.getValue().toString());
}else if(en.getKey().split("_")[0].equals("isNotNull")){
criteria.andIsNotNull(en.getValue().toString());
}else if(en.getKey().split("_")[0].equals("in")){
criteria.andIn(StringUtils.camel2Underline(en.getKey().split("_")[1]),Arrays.asList(en.getValue().toString().split(",")));
}else if(en.getKey().split("_")[0].equals("notIn")){
criteria.andNotIn(StringUtils.camel2Underline(en.getKey().split("_")[1]),Arrays.asList(en.getValue().toString().split(",")));
}else if(en.getKey().split("_")[0].equals("equal")){
criteria.andCondition(StringUtils.camel2Underline(en.getKey().split("_")[1])+" =",en.getValue());
}else if(en.getKey().split("_")[0].equals("like")){
criteria.andCondition(StringUtils.camel2Underline(en.getKey().split("_")[1])+" like",en.getValue());
}
}
example.or(criteria);
break;
case "orEqual":
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.or().andCondition(key+" =", entry.getValue());
break;
case "orLike":
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.or().andCondition(key+" like", "%"+entry.getValue()+"%");
break;
case "in":
String strIn[] = entry.getValue().toString().split(",");
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.and().andIn(key,Arrays.asList(strIn));
break;
case "notIn":
String strNotIn[] = entry.getValue().toString().split(",");
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.and().andNotIn(key,Arrays.asList(strNotIn));
break;
case "isNull":
example.and().andIsNull(StringUtils.camel2Underline(entry.getValue().toString()));
break;
case "isNotNull":
example.and().andIsNotNull(StringUtils.camel2Underline(entry.getValue().toString()));
break;
case "equal":
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.and().andCondition(key+" =", entry.getValue());
break;
case "like":
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.and().andCondition(key+" like", "%"+entry.getValue()+"%");
break;
case "greater":
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.and().andCondition(key+ " >=", entry.getValue());
break;
case "less":
key= StringUtils.camel2Underline(entry.getKey().split("_")[1]);
example.and().andCondition(key+ " <=", entry.getValue());
break;
default:
example.and().andCondition(entry.getKey(), entry.getValue());
break;
}
}
return example;
} else {
return null;
}
}
public Map<String, Object> getKeyMap() {
return keyMap;
}
public void setKeyMap(Map<String, Object> keyMap) {
this.keyMap = keyMap;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public String getOrderBy() {
return orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
public boolean isCount() {
return count;
}
public void setCount(boolean count) {
this.count = count;
}
public Boolean getReasonable() {
return reasonable;
}
public void setReasonable(Boolean reasonable) {
this.reasonable = reasonable;
}
public Boolean getPageSizeZero() {
return pageSizeZero;
}
public void setPageSizeZero(Boolean pageSizeZero) {
this.pageSizeZero = pageSizeZero;
}
public Example getExample() {
return example;
}
public void setExample(Example example) {
this.example = example;
}
public Class<T> gettClass() {
return tClass;
}
public void settClass(Class<T> tClass) {
this.tClass = tClass;
}
public Example.Criteria getCriteria() {
return criteria;
}
public void setCriteria(Example.Criteria criteria) {
this.criteria = criteria;
}
}
|
package Controlador;
import com.taurus.openbravo.integracionPOS.main.GT_CLS_Main;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.RemoteException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
public class Controller extends Thread
{
@Override
public void run() {
try {
principal();
} catch (InterruptedException | IOException | NoSuchAlgorithmException ex) {
Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void principal() throws InterruptedException, FileNotFoundException, IOException, RemoteException, NoSuchAlgorithmException, ParserConfigurationException
{
//Instancias
GT_CLS_Main iniciar=new GT_CLS_Main();
while(!Thread.currentThread().isInterrupted())
{
iniciar.manejarPeticionesWS();
Thread.sleep(1000);
//Thread.sleep(300000);
}
}
public void kill() {
interrupt();
}
}
|
package com.jt.sys.controller;
import com.jt.common.vo.JsonResult;
import com.jt.common.vo.Node;
import com.jt.sys.entity.SysMenu;
import com.jt.sys.service.SysMenuService;
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 java.util.List;
import java.util.Map;
/**
* 基于客户端请求,借助业务层对角访问菜单信息
* 对菜单信息进行封装并返回
*/
@Controller
@RequestMapping("/menu/")
public class SysMenuController {
@Autowired
private SysMenuService sysMenuService;
/**
* @return 菜单列表页
*/
@RequestMapping("listUI")
public String listUI(){
return "sys/menu_list";
}
/**
* @return 菜单编辑页面
*/
@RequestMapping("editUI")
public String editUI(){
return "sys/menu_edit";
}
@RequestMapping("doFindObjects")
@ResponseBody
public JsonResult doFindObjects() {
List<Map<String, Object>> map = sysMenuService.findObjects();
JsonResult jsonResult = new JsonResult(map, "query ok");
return jsonResult;
}
@RequestMapping("doDeleteObject")
@ResponseBody
public JsonResult doDeleteObject(Integer menuId){
String message = sysMenuService.deleteObject(menuId);
JsonResult jsonResult = new JsonResult(message);
return jsonResult;
}
@RequestMapping("doFindZtreeMenuNodes")
@ResponseBody
public JsonResult doFindZtreeMenuNodes(){
List<Node> nodes = sysMenuService.findZtreeMenuNodes();
JsonResult jsonResult = new JsonResult(nodes, "Query Ok");
return jsonResult;
}
@RequestMapping("doInsertObject")
@ResponseBody
public JsonResult doInsertObject(SysMenu entity) {
String message = sysMenuService.insertObject(entity);
JsonResult jsonResult = new JsonResult(message);
return jsonResult;
}
@RequestMapping("doFindObjectById")
@ResponseBody
public JsonResult doFindObjectById(Integer id) {
SysMenu menu = sysMenuService.findObjectById(id);
JsonResult jsonResult = new JsonResult(menu, "Query Ok");
return jsonResult;
}
@RequestMapping("doUpdateObject")
@ResponseBody
public JsonResult doUpdateObject(SysMenu entity) {
String message = sysMenuService.updateObject(entity);
return new JsonResult(message);
}
}
|
package at.fhv.itm14.fhvgis.webservice.app.services;
import at.fhv.itm14.fhvgis.domain.Device;
import at.fhv.itm14.fhvgis.domain.Track;
import at.fhv.itm14.fhvgis.domain.Transportation;
import at.fhv.itm14.fhvgis.domain.raw.RawMotionValue;
import at.fhv.itm14.fhvgis.domain.raw.RawWaypoint;
import at.fhv.itm14.fhvgis.persistence.DatabaseController;
import at.fhv.itm14.fhvgis.persistence.IDatabaseController;
import at.fhv.itm14.fhvgis.persistence.exceptions.PersistenceException;
import at.fhv.itm14.fhvgis.webservice.app.exceptions.BadRequestException;
import at.fhv.itm14.fhvgis.webservice.app.exceptions.ServiceException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
/**
* Author: Philip Heimböck Date: 13.11.15.
*/
public class DataService {
private final static int NUMBER_OF_TRACKS = 30;
private static HashMap<Integer, String> vehicleMap;
static {
vehicleMap = new HashMap<>();
vehicleMap.put(1, "Walking");
vehicleMap.put(2, "Bicycle");
vehicleMap.put(3, "Bus");
vehicleMap.put(4, "Train");
vehicleMap.put(5, "Car");
vehicleMap.put(6, "Ski");
}
/**
* Creates a new track instance and sets the start time
*
* @param device
* @param startTime
* @return
*/
public Track startTrack(Device device, Instant startTime) throws ServiceException {
Track track = new Track(device, startTime);
device.addTrack(track);
// Persist the track
try {
DatabaseController.getInstance().persistTrack(track);
} catch (PersistenceException e) {
throw new ServiceException("Failed to finish track", e);
}
return track;
}
/**
* Sets the start time of the track and updates it
*
* @param track
* @param startTime
* @return
*/
public Track startTrack(Track track, Instant startTime) throws ServiceException {
track.setStartDate(startTime);
// Update the track
try {
DatabaseController.getInstance().updateTrack(track);
} catch (PersistenceException e) {
throw new ServiceException("Failed to start track", e);
}
return track;
}
/**
* Sets the end time of the track and updates it
*
* @param track
* @param endTime
* @return
*/
public Track finishTrack(Track track, Instant endTime) throws ServiceException {
track.setEndDate(endTime);
// Update the track
try {
DatabaseController.getInstance().updateTrack(track);
} catch (PersistenceException e) {
throw new ServiceException("Failed to finish track", e);
}
return track;
}
/**
* Finds a track object
*
* @param trackId
* @return
*/
public Track getTrack(String trackId) {
try {
return DatabaseController.getInstance().findTrack(UUID.fromString(trackId));
} catch (PersistenceException e) {
e.printStackTrace();
}
return null;
}
/**
* Persists a list of waypoints
*
* @param waypointList
*/
public void persistWaypoints(List<RawWaypoint> waypointList) throws BadRequestException, ServiceException {
IDatabaseController controller = DatabaseController.getInstance();
for (RawWaypoint waypoint : waypointList) {
// All data set?
if (waypoint.getTrack() == null) {
throw new BadRequestException("Track not set!");
}
try {
controller.persistRawWaypoint(waypoint);
} catch (PersistenceException e) {
throw new ServiceException("Failed to persist waypoints", e);
}
}
}
/**
* Finds a transportation
*
* @param vehicleId
* @return
*/
public Transportation getTransportation(int vehicleId) {
try {
String name = mapVehicleIdToName(vehicleId);
if (name != null) {
return DatabaseController.getInstance().findTransportationByName(mapVehicleIdToName(vehicleId));
}
} catch (PersistenceException e) {
e.printStackTrace();
}
return null;
}
/**
* Persists a list of motion values
*
* @param list
*/
public void persistMotionValues(List<RawMotionValue> list) throws ServiceException {
IDatabaseController controller = DatabaseController.getInstance();
for (RawMotionValue motionValues : list) {
try {
controller.persistRawMotionValue(motionValues);
} catch (PersistenceException e) {
throw new ServiceException("Failed to persist motion values", e);
}
}
}
/**
* Creates multiple tracks without start time and waypoints and returns them
*
* @param device
* @return
*/
public List<Track> reserveTracks(Device device) throws ServiceException {
List<Track> reservedTracks = new ArrayList<>();
// Create new track instances without a start date
for (int i = 0; i < NUMBER_OF_TRACKS; i++) {
Track track = new Track(device);
try {
DatabaseController.getInstance().persistTrack(track);
reservedTracks.add(track);
} catch (PersistenceException e) {
throw new ServiceException("Failed to reserve tracks", e);
}
}
return reservedTracks;
}
/**
* Updates the start end end date of the track objects
*
* @param tracks
*/
public void updateTracks(List<Track> tracks) throws ServiceException {
IDatabaseController controller = DatabaseController.getInstance();
try {
for (Track track : tracks) {
// Check if track is existing
Track persisted = controller.findTrack(track.getId());
if (persisted == null) {
// Track ID not found, cannot update
throw new ServiceException("Could not find track with ID " + track.getId().toString());
}
if (!persisted.getDevice().getToken().equals(track.getDevice().getToken())) {
throw new ServiceException("Track doesn't belong to you!");
}
// Change start and end date
persisted.setStartDate(track.getStartDate());
persisted.setEndDate(track.getEndDate());
// Update it
controller.updateTrack(persisted);
}
} catch (PersistenceException e) {
throw new ServiceException("Failed to update tracks");
}
}
/**
* Maps the Vehicle ID to its name
*
* @param vehicleId
* @return
*/
private String mapVehicleIdToName(int vehicleId) {
return vehicleMap.get(vehicleId);
}
public Device getDevice(String id) {
try {
return DatabaseController.getInstance().findDevice(UUID.fromString(id));
} catch (PersistenceException e) {
e.printStackTrace();
return null;
}
}
}
|
//package idv.emp.model;
//
//import java.util.*;
//import java.sql.*;
//
//public class EmpJDBCDAO implements EmpDAO_interface {
// String driver = "org.postgresql.Driver";
//
// String url = "jdbc:postgresql://localhost:5432/testDB" ; //連線ip ,port ,table name
// String userid = "test1";
// String passwd = "test1";
//
// private static final String INSERT_STMT =
// "INSERT INTO emp2 (empno,ename,job,hiredate,sal,comm,deptno) VALUES (emp2_seq.NEXTVAL, ?, ?, ?, ?, ?, ?)";
// private static final String GET_ALL_STMT =
// "SELECT empno,ename,job,to_char(hiredate,'yyyy-mm-dd') hiredate,sal,comm,deptno FROM emp2 order by empno";
// private static final String GET_ONE_STMT =
// "SELECT empno,ename,job,to_char(hiredate,'yyyy-mm-dd') hiredate,sal,comm,deptno FROM emp2 where empno = ?";
// private static final String DELETE =
// "DELETE FROM emp2 where empno = ?";
// private static final String UPDATE =
// "UPDATE emp2 set ename=?, job=?, hiredate=?, sal=?, comm=?, deptno=? where empno = ?";
//
//
// @Override
// public List<Emp2> getAll() {
// List<Emp2> list = new ArrayList<Emp2>();
// Emp2 empVO = null;
// EmpId empid = null;
//
// Connection con = null;
// PreparedStatement pstmt = null;
// ResultSet rs = null;
//
// try {
// Class.forName(driver);
// con = DriverManager.getConnection(url, userid, passwd);
// pstmt = con.prepareStatement(GET_ALL_STMT);
// rs = pstmt.executeQuery();
//
// while (rs.next()) {
// empVO = new Emp2();
// empid = new EmpId();
// empid.setEmpNo(rs.getInt("empno"));
// empVO.setEname(rs.getString("ename"));
// empVO.setJob(rs.getString("job"));
// empVO.setHiredate(rs.getDate("hiredate"));
// empVO.setSal(rs.getBigDecimal("sal"));
// empVO.setComm(rs.getBigDecimal("comm"));
// empVO.setDeptno(rs.getInt("deptno"));
// empVO.setId(empid);
// list.add(empVO); // Store the row in the list
// }
//
// // Handle any driver errors
// } catch (ClassNotFoundException e) {
// throw new RuntimeException("Couldn't load database driver. "
// + e.getMessage());
// // Handle any SQL errors
// } catch (SQLException se) {
// throw new RuntimeException("A database error occured. "
// + se.getMessage());
// // Clean up JDBC resources
// } finally {
// if (rs != null) {
// try {
// rs.close();
// } catch (SQLException se) {
// se.printStackTrace(System.err);
// }
// }
// if (pstmt != null) {
// try {
// pstmt.close();
// } catch (SQLException se) {
// se.printStackTrace(System.err);
// }
// }
// if (con != null) {
// try {
// con.close();
// } catch (Exception e) {
// e.printStackTrace(System.err);
// }
// }
// }
// return list;
// }
//
// public static void main(String[] args) {
//
// EmpJDBCDAO dao = new EmpJDBCDAO();
//
// List<Emp2> list = dao.getAll();
// for (Emp2 aEmp : list) {
// System.out.print(aEmp.getId().getEmpNo() + ",");
// System.out.print(aEmp.getEname() + ",");
// System.out.print(aEmp.getJob() + ",");
// System.out.print(aEmp.getHiredate() + ",");
// System.out.print(aEmp.getSal() + ",");
// System.out.print(aEmp.getComm() + ",");
// System.out.print(aEmp.getDeptno());
// System.out.println();
// }
// }
//} |
package io.spring.bookstore.service;
import io.spring.bookstore.domain.User;
import io.spring.bookstore.repo.UserRepo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collection;
@Service @RequiredArgsConstructor @Transactional @Slf4j
public class UserServiceImpl implements UserService, UserDetailsService {
private final UserRepo userRepo;
private final PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepo.findByUsername(username);
if (user == null) {
log.error("User not found.");
throw new UsernameNotFoundException("User not found in the database");
}else {
log.info("User found: {}", username);
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>());
}
@Override
public User getUser(String username) {
return userRepo.findByUsername(username);
}
@Override
public User saveUser(User user) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
return userRepo.save(user);
}
@Override
public void deleteUser(User user) {
userRepo.delete(user);
}
}
|
/*
* (c) Copyright 2001-2007 PRODAXIS, S.A.S. All rights reserved.
* PRODAXIS PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.prodaxis.junitgenerator.wizards;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWizard;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.WorkbenchException;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.internal.ObjectPluginAction;
/**
* This is a sample new wizard. Its role is to create a new file
* resource in the provided container. If the container resource
* (a folder or a project) is selected in the workspace
* when the wizard is opened, it will accept it as the target
* container. The wizard creates one file with the extension
* "mpe". If a sample multi-page editor (also available
* as a template) is registered for the same extension, it will
* be able to open it.
*
*
* JUnitGeneratorWizard creates the JUnit class associate to the underlying compilationUnit
*/
public class JUnitGeneratorWizard extends Wizard implements INewWizard, IJUnitGenerator {
private JUnitGeneratorWizardPage jUnitGeneratorWizardPage;
protected ICompilationUnit compilationUnit;
protected IEditorPart editorPart;
protected String jUnitName;
/**
* Constructor for JUnitGeneratorWizard.
*/
public JUnitGeneratorWizard() {
super();
setNeedsProgressMonitor(true);
setWindowTitle("JUnitGenerator");
editorPart = null;
}
/**
* Adding the page to the wizard.
*/
public void addPages() {
jUnitGeneratorWizardPage = new JUnitGeneratorWizardPage(compilationUnit);
jUnitGeneratorWizardPage.setImageDescriptor(ImageDescriptor.createFromFile(JUnitGeneratorWizard.class, "newju_wiz.png"));
addPage(jUnitGeneratorWizardPage);
}
/**
* This method is called when 'Finish' button is pressed in
* the wizard. We will create an operation and run it
* using wizard as execution context.
*/
public boolean performFinish() {
final String packageName = jUnitGeneratorWizardPage.getPackageText();
final String className = jUnitGeneratorWizardPage.getClassText();
jUnitName = jUnitGeneratorWizardPage.getJunitText();
final IRunnableWithProgress op = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
final IFile file = doFinish(packageName, className, jUnitName, monitor);
monitor.worked(1);
monitor.setTaskName("Opening file for editing...");
getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
try {
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
setEditorPart(IDE.openEditor(page, file, true));
}
catch (PartInitException e) {
}
}
});
monitor.worked(1);
}
catch (CoreException e) {
throw new InvocationTargetException(e);
}
finally {
monitor.done();
}
}
};
try {
getContainer().run(true, false, op);
}
catch (InterruptedException e) {
return false;
}
catch (InvocationTargetException e) {
Throwable realException = e.getTargetException();
MessageDialog.openError(getShell(), "Error", realException.getMessage());
return false;
}
return true;
}
private IFile doFinish(String packageName, String className, String jUnitName, IProgressMonitor monitor) throws CoreException {
monitor.beginTask("Creating " + className, 2);
// Retrieve the corresponding destination project
IProject project = compilationUnit.getCorrespondingResource().getProject();
String projectName = project.getName() + "_Tests";
IWorkspace workspace = project.getWorkspace();
IProject jUnitProject = null;
IProject[] projects = workspace.getRoot().getProjects();
for (int i = 0; i < projects.length; i++) {
if (projectName.endsWith(projects[i].getName()))
jUnitProject = projects[i];
}
if (null == jUnitProject)
throw new WorkbenchException(projectName + " not found.");
// Retrieve the destination package
String subPackageName = packageName.substring(17, 19);
IFolder packageFolder = jUnitProject.getFolder("src/junit/" + subPackageName);
if (!packageFolder.exists())
throw new WorkbenchException(projectName + "/src/junit/" + subPackageName + " not found.");
// Check if the compilationUnit is an entity
IType iType = compilationUnit.getTypes()[0];
String[] superClassNames = iType.getSuperInterfaceNames();
boolean entity = false;
for (int i = 0; i < superClassNames.length; i++) {
if ("EntityBean".equals(superClassNames[i]))
entity = true;
}
className = className.substring(0, className.length() - 4);
String lowerCaseClassName = new String("" + className.charAt(0)).toLowerCase() + className.substring(1);
IFile file = packageFolder.getFile(new Path(jUnitName + ".java"));
try {
String contents = COMMENTS + PACKAGE.replaceAll("&SubPackageName", subPackageName);
contents += CLASS_DECLARATION.replaceAll("&jUnitName", jUnitName);
if (entity)
contents += ATTRIBUTS_ENTITY.replaceAll("&className", className).replaceAll("&lowerCaseClassName", lowerCaseClassName);
else
contents += ATTRIBUTS_SESSION.replaceAll("&className", className).replaceAll("&lowerCaseClassName", lowerCaseClassName);
contents += CONSTRUCTORS.replaceAll("&className", className).replaceAll("&jUnitName", jUnitName);
if (entity)
contents += DEFAULT_FINDERS.replaceAll("&className", className).replaceAll("&lowerCaseClassName", lowerCaseClassName);
String methodName, lowerCaseMethodName, source;
IMethod[] iMethods = iType.getMethods();
if (entity) {
// First of all, finders
for (int i = 0; i < iMethods.length; i++) {
if (!iMethods[i].getElementName().startsWith("ejbFind"))
continue;
if (iMethods[i].getElementName().equals("ejbFindAll") || iMethods[i].getElementName().equals("ejbFindByPrimaryKey") || iMethods[i].getElementName().equals("ejbFindByExpression"))
continue;
source = iMethods[i].getSource();
if (!source.contains("public "))
continue;
methodName = iMethods[i].getElementName().substring(3);
methodName = new String("" + methodName.charAt(0)).toUpperCase() + methodName.substring(1);
lowerCaseMethodName = new String("" + methodName.charAt(0)).toLowerCase() + methodName.substring(1);
contents += FINDER_METHOD.replaceAll("&className", className).replaceAll("&methodName", methodName).replaceAll("&lowerCaseClassName", lowerCaseClassName).replaceAll("&lowerCaseMethodName", lowerCaseMethodName);
}
}
for (int i = 0; i < iMethods.length; i++) {
if (iMethods[i].getElementName().startsWith("ejbFind") || iMethods[i].getElementName().equals("ejbFindByPrimaryKey") || iMethods[i].getElementName().equals("ejbFindByExpression") || iMethods[i].getElementName().equals("ejbCreate") || iMethods[i].getElementName().equals("beforeRemove") || iMethods[i].getElementName().equals("getEntityContext") || iMethods[i].getElementName().equals("getEntityBeanPersister") || iMethods[i].getElementName().equals("initialize") || iMethods[i].getElementName().equals("makeDirty") || iMethods[i].getElementName().equals("postInitialize") || iMethods[i].getElementName().equals("getSessionContext") || iMethods[i].getElementName().equals("getDataObjectPersister"))
continue;
source = iMethods[i].getSource();
if (!source.contains("public "))
continue;
methodName = new String("" + iMethods[i].getElementName().charAt(0)).toUpperCase() + iMethods[i].getElementName().substring(1);
contents += METHOD.replaceAll("&className", className).replaceAll("&methodName", methodName);
}
if (entity) {
contents += SETUP_ENTITY.replaceAll("&className", className).replaceAll("&lowerCaseClassName", lowerCaseClassName);
contents += TEAR_DOWN_ENTITY.replaceAll("&className", className).replaceAll("&lowerCaseClassName", lowerCaseClassName);
}
else {
contents += SETUP_SESSION.replaceAll("&className", className).replaceAll("&lowerCaseClassName", lowerCaseClassName);
contents += TEAR_DOWN_SESSION.replaceAll("&className", className).replaceAll("&lowerCaseClassName", lowerCaseClassName);
}
InputStream stream = new ByteArrayInputStream(contents.getBytes());
if (file.exists())
file.setContents(stream, true, true, monitor);
else
file.create(stream, true, monitor);
stream.close();
}
catch (IOException e) {
}
return file;
}
/**
* We will accept the selection in the workbench to see if
* we can initialize from it.
* @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
*/
public void init(IWorkbench workbench, IStructuredSelection structuredSelection) {
Object object = structuredSelection.getFirstElement();
if (object instanceof ObjectPluginAction) {
ObjectPluginAction objectPluginAction = (ObjectPluginAction) object;
ISelection iSelection = objectPluginAction.getSelection();
if (iSelection instanceof TreeSelection) {
TreeSelection treeSelection = (TreeSelection) iSelection;
object = treeSelection.getFirstElement();
if (object instanceof ICompilationUnit)
compilationUnit = (ICompilationUnit) object;
}
}
}
public IEditorPart getEditorPart() {
return editorPart;
}
public void setEditorPart(IEditorPart editorPart) {
this.editorPart = editorPart;
}
public String getJUnitName() {
return jUnitName;
}
}
|
package otf.obj;
import java.io.Serializable;
/**
* @author ⋈
*
*/
public class BolusFactorEntity implements Serializable
{
private Long id;
private double factor;
private long startTime;
/**
* @param factor
* @param startTime
*/
public BolusFactorEntity(double factor, long startTime)
{
this.factor = factor;
this.startTime = startTime;
}
public BolusFactorEntity()
{
}
/**
* @return the id
*/
public Long getId()
{
return this.id;
}
/**
* @param id
* the id to set
*/
public void setId(Long id)
{
this.id = id;
}
/**
* @return the factor
*/
public double getFactor()
{
return this.factor;
}
/**
* @param factor
* the factor to set
*/
public void setFactor(double factor)
{
this.factor = factor;
}
/**
* @return the startTime
*/
public long getStartTime()
{
return this.startTime;
}
/**
* @param startTime
* the startTime to set
*/
public void setStartTime(long startTime)
{
this.startTime = startTime;
}
} |
package com.metoo.foundation.dao;
import org.springframework.stereotype.Repository;
import com.metoo.core.base.GenericDAO;
import com.metoo.foundation.domain.GoodsWeight;
@Repository("goodsWeightDAO")
public class GoodsWeightDAO extends GenericDAO<GoodsWeight>{
}
|
package practiceJava;
import java.util.Scanner;
public class Tictactoe {
Scanner sc = new Scanner(System.in);
Tile t = new Tile();
int x = 0, y = 0;
boolean flag = true;
public void disp() {
System.out.println();
for (int i = 0; i < t.tile.length; i++) {
for (int j = 0; j < t.tile.length; j++) {
System.out.print(t.tile[i][j]);
}
System.out.println();
}
System.out.println();
}
public boolean fullCheck() {
for (int i = 0; i < t.tile.length; i++) {
for (int j = 0; j < t.tile.length; j++) {
if (t.tile[i][j] == "0 ") {
return false;
}
}
}
if (drawCheck() == true)
return true;
return false;
}
public boolean drawCheck() {
if (winCheck() == false) {
return true;
}
return false;
}
public boolean tileCheck(int x, int y) {
if (t.tile[x][y] != "0 ") {
System.out.println("이미 선택된 자리입니다.");
return true;
}
return false;
}
public boolean tileIndexCheck(int x, int y) {
if ((x > t.tile.length || x < 1) || (y > t.tile.length || y < 1))
return true;
return false;
}
public void draw() {
this.t = new Tile();
System.out.println("====================");
System.out.println("\n* * * 비겼습니다 * * *\n");
System.out.println("====================");
menu();
}
public void player1() {
try {
int player1 = 1;
System.out.println("Player1's Turn");
while (true) {
System.out.print("좌표값을 입력해주세요. ex)11\n>>");
String place = sc.next();
if (place.length() != 2) {
System.out.println("두자리의 좌표값을 입력해주세요");
continue;
}
if (place.length() == 2) {
this.x = Integer.parseInt(place.substring(0, 1));
this.y = Integer.parseInt(place.substring(1));
if (tileCheck(x, y) == true)
continue;
t.tile[x][y] = "@ ";
disp();
break;
}
break;
}
if (winCheck() == true) {
this.t = new Tile();
win(player1);
flag = false;
}
if (fullCheck() == true) {
draw();
}
} catch (NumberFormatException e) {
System.out.println("숫자로만 입력해주세요.");
player1();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("잘못된 범위입니다.");
System.out.println("1에서 3까지의 좌표만 입력해주세요.");
player1();
}
}
public void player2() {
try {
int player2 = 2;
System.out.println("Player2's Turn");
while (true) {
System.out.print("좌표값을 입력해주세요. ex)11\n>>");
String place = sc.next();
if (place.length() != 2) {
System.out.println("두자리의 좌표값을 입력해주세요");
continue;
}
if (place.length() == 2) {
this.x = Integer.parseInt(place.substring(0, 1));
this.y = Integer.parseInt(place.substring(1));
if (tileCheck(x, y) == true)
continue;
t.tile[x][y] = "# ";
disp();
break;
} // if
break;
} // while
if (winCheck() == true) {
this.t = new Tile();
win(player2);
flag = false;
}
if (fullCheck() == true) {
draw();
}
} catch (NumberFormatException e) {
System.out.println("숫자로만 입력해주세요.");
player2();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("잘못된 범위입니다.");
System.out.println("1에서 3까지의 좌표만 입력해주세요.");
player2();
}
}
public boolean winCheck() {
if (t.tile[1][1] == t.tile[1][2] && t.tile[1][2] == t.tile[1][3]
&& (t.tile[1][3].equals("# ") || t.tile[1][3].equals("@ "))) {
return true;
} else if (t.tile[1][1] == t.tile[2][2] && t.tile[2][2] == t.tile[3][3]
&& (t.tile[3][3].equals("# ") || t.tile[3][3].equals("@ "))) {
return true;
} else if (t.tile[1][1] == t.tile[2][1] && t.tile[2][1] == t.tile[3][1]
&& (t.tile[3][1].equals("# ") || t.tile[3][1].equals("@ "))) {
return true;
} else if (t.tile[2][1] == t.tile[2][2] && t.tile[2][2] == t.tile[2][3]
&& (t.tile[2][3].equals("# ") || t.tile[2][3].equals("@ "))) {
return true;
} else if (t.tile[3][1] == t.tile[3][2] && t.tile[3][2] == t.tile[3][3]
&& (t.tile[3][3].equals("# ") || t.tile[3][3].equals("@ "))) {
return true;
} else if (t.tile[3][1] == t.tile[2][2] && t.tile[2][2] == t.tile[1][3]
&& (t.tile[1][3].equals("# ") || t.tile[1][3].equals("@ "))) {
return true;
} else if (t.tile[1][2] == t.tile[2][2] && t.tile[2][2] == t.tile[3][2]
&& (t.tile[3][2].equals("# ") || t.tile[3][2].equals("@ "))) {
return true;
} else if (t.tile[1][3] == t.tile[2][3] && t.tile[2][3] == t.tile[3][3]
&& (t.tile[3][3].equals("# ") || t.tile[3][3].equals("@ "))) {
return true;
}
return false;
}
public void start() {
System.out.println("===== START =====");
System.out.println("Player 1--> @");
System.out.println("Player 2--> #");
System.out.println("==================");
while (flag == true) {
player1();
if (flag == false)
break;
player2();
if (flag == false)
break;
}
}
public void win(int player) {
if (player == 1) {
System.out.println("=======================");
System.out.println("\n* * * Player 1 승리 * * *\n");
System.out.println("=======================");
menu();
} else {
System.out.println("=======================");
System.out.println("\n* * * Player 2 승리 * * *\n");
System.out.println("=======================");
menu();
}
}
public void exit() {
System.out.println("====== END ======");
}
public void menu() {
while (true) {
System.out.print("1.GameStart 2.EXIT >>");
switch (sc.nextInt()) {
case 1:
start();
continue;
case 2:
exit();
break;
default:
continue;
}// switch
break;
} // while
}
public static void main(String[] args) {
Tictactoe ttt = new Tictactoe();
ttt.menu();
// ttt.disp();
}
}
|
package friend.group.bank.obj.domain.sms.dto;
import lombok.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Setter
@Getter
@Builder
@ToString
@AllArgsConstructor
public class SmsDto {
private String title;
private String message;
private String sender;
private List<SmsMobileDto> receiver;
private String key;
private String username;
private String type;
public void smsOption(String username, String key, String sender){
this.key = key;
this.username = username;
this.sender = sender;
this.type = "java";
}
public static SmsDto userCall(String title, String message, String receiver){
return SmsDto.builder().title(title).message(message).receiver(Arrays.asList(new SmsMobileDto(receiver))).build();
}
public static SmsDto userCall(String title, String message, List<String> receivers){
return SmsDto.builder().title(title).message(message).receiver(receivers.stream().map(SmsMobileDto::new).collect(Collectors.toList())).build();
}
public static SmsDto adminCall(String title, String message, String receiver){
return SmsDto.builder().title(title).message(message).receiver(Arrays.asList(new SmsMobileDto(receiver))).build();
}
}
|
package com.zantong.mobilecttx.presenter.presenterinterface;
/**
* Created by Administrator on 2016/5/5.
*/
public interface LoginPresenter {
void loadView();
void codeNumber();
}
|
package com.sinodynamic.hkgta.dto;
import java.util.Map;
/**
* Created by Mason_Yang on 12/24/2015.
*/
public class ReportRequestDto {
private String sortBy;
private String isAscending;
private String reportFile;
private String fileType;
private Map<String, Object> parameters;
public String getSortBy() {
return sortBy;
}
public void setSortBy(String sortBy) {
this.sortBy = sortBy;
}
public String getIsAscending() {
return isAscending;
}
public void setIsAscending(String isAscending) {
this.isAscending = isAscending;
}
public Map<String, Object> getParameters() {
return parameters;
}
public void setParameters(Map<String, Object> parameters) {
this.parameters = parameters;
}
public String getReportFile() {
return reportFile;
}
public void setReportFile(String reportFile) {
this.reportFile = reportFile;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
}
|
package structuralPatterns.facade;
public class MPEG4CompressionCodec implements Codec {
public String type = "ogg";
}
|
package com.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.test.base.Solution;
/**
* 利用HashMap快速计算
*
* @author YLine
*
* 2018年11月29日 下午3:30:35
*/
public class SolutionB implements Solution
{
private static final int[] primeNums =
{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101};
public List<List<String>> groupAnagrams(String[] strs)
{
List<List<String>> result = new ArrayList<>();
HashMap<Integer, Integer> cacheTypeMap = new HashMap<>();
for (String content : strs)
{
int type = mockHashCode(content);
if (cacheTypeMap.containsKey(type))
{
int index = cacheTypeMap.get(type);
result.get(index).add(content);
}
else
{
cacheTypeMap.put(type, result.size());
List<String> data = new ArrayList<>();
data.add(content);
result.add(data);
}
}
return result;
}
/**
* 计算出一个 独一无二的 int 值(并且不受顺序影响)
* @param str 内容
* @return 独一无二的int值
*/
private int mockHashCode(String str)
{
int result = 1;
for (int i = 0; i < str.length(); i++)
{
result *= primeNums[str.charAt(i) - 'a'];
}
return result;
}
}
|
/*
* @lc app=leetcode.cn id=94 lang=java
*
* [94] 二叉树的中序遍历
*/
// @lc code=start
/**
* Definition for a binary tree node. public class TreeNode { int val; TreeNode
* left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left
* = left; this.right = right; } }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
inorder(root, res);
return res;
}
public void inorder(TreeNode root, List<Integer> res) {
if (root == null)
return;
inorder(root.left, res);
res.add(root.val);
inorder(root.right, res);
}
}
// @lc code=end
|
package hengxiu.courseraPA.w2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import edu.princeton.cs.algs4.StdRandom;
public class RandomizedQueue<Item> implements Iterable<Item> {
private LinkedHashMap<Integer, Item> index2ItemMap;
private LinkedHashMap<Item, Integer> item2IndexMap;
private int size = 0;
// construct an empty randomized queue
public RandomizedQueue() {
index2ItemMap = new LinkedHashMap<>();
item2IndexMap = new LinkedHashMap<>();
size = 0;
}
// is the queue empty?
public boolean isEmpty() {
return size == 0;
}
// return the number of items on the queue
public int size() {
return size;
}
// add the item
public void enqueue(Item item) {
if (item == null) {
throw new java.lang.NullPointerException();
}
index2ItemMap.put(size, item);
item2IndexMap.put(item, size);
size++;
}
// remove and return a random item
public Item dequeue() {
if (isEmpty()) {
throw new java.util.NoSuchElementException();
}
int randomIndex = StdRandom.uniform(size);
Item result = null;
if (randomIndex < size - 1) {
Item lastItem = index2ItemMap.get(size - 1);
result = index2ItemMap.get(randomIndex);
index2ItemMap.put(randomIndex, lastItem);
item2IndexMap.put(lastItem, randomIndex);
index2ItemMap.remove(size - 1);
item2IndexMap.remove(lastItem);
} else {
result = index2ItemMap.get(randomIndex);
index2ItemMap.remove(size - 1);
item2IndexMap.remove(result);
}
size--;
return result;
}
// return (but do not remove) a random item
public Item sample() {
if (isEmpty()) {
throw new java.util.NoSuchElementException();
}
int randomIndex = StdRandom.uniform(size);
return index2ItemMap.get(randomIndex);
}
// return an independent iterator over items in random order
public Iterator<Item> iterator() {
return new RandomizedQueueIterator();
}
private class RandomizedQueueIterator implements Iterator<Item> {
HashMap<Integer, Item> idx2ItMap;
HashMap<Item, Integer> it2IdxMap;
int s = 0;
RandomizedQueueIterator() {
idx2ItMap = new HashMap<>();
it2IdxMap = new HashMap<>();
s = size;
for (Map.Entry<Integer, Item> set : index2ItemMap.entrySet()) {
it2IdxMap.put(set.getValue(), set.getKey());
idx2ItMap.put(set.getKey(), set.getValue());
}
}
@Override
public boolean hasNext() {
return s != 0;
}
@Override
public Item next() {
if (!hasNext()) {
throw new java.util.NoSuchElementException();
}
int randomIndex = StdRandom.uniform(s);
Item result = null;
if (randomIndex < s - 1) {
Item lastItem = idx2ItMap.get(s - 1);
result = idx2ItMap.get(randomIndex);
idx2ItMap.put(randomIndex, lastItem);
it2IdxMap.put(lastItem, randomIndex);
idx2ItMap.remove(s - 1);
it2IdxMap.remove(lastItem);
} else {
result = idx2ItMap.get(randomIndex);
idx2ItMap.remove(s - 1);
it2IdxMap.remove(result);
}
s--;
return result;
}
public void remove() {
/* not supported */
throw new UnsupportedOperationException();
}
}
// unit testing (optional)
public static void main(String[] args) {
RandomizedQueue<Integer> r = new RandomizedQueue<>();
//print(r);
r.enqueue(1);
//print(r);
r.enqueue(2);
//print(r);
r.enqueue(5);
r.enqueue(4);
r.enqueue(3);
System.out.println("out " + r.dequeue());
print(r);
System.out.println("out " + r.dequeue());
print(r);
System.out.println("out " + r.dequeue());
print(r);
System.out.println("out " + r.dequeue());
print(r);
r.enqueue(10);
System.out.println("out " + r.dequeue());
print(r);
/*
System.out.println(r.sample());
System.out.println(r.sample());
System.out.println(r.sample());
System.out.println(r.sample());
System.out.println(r.sample());
System.out.println(r.sample());
System.out.println(r.sample());
System.out.println(r.sample());
*/
}
private static void print(RandomizedQueue<Integer> r) {
System.out.print("SIZE=" + r.size() + " ,");
if (r.isEmpty()) {
System.out.print("EMPTY");
}
for (Integer i : r) {
System.out.print(i + " ");
}
System.out.println();
}
} |
package it.sella.sample.microservice.gallery;
/**
* Created by gbs04154 on 03-01-2019.
*/
public class GalleryImage {
private Integer id;
private String title;
private String url;
public GalleryImage(){
}
public GalleryImage(Integer id, String title, String url){
this.id = id;
this.title = title;
this.url = url;
}
public Integer getId() {
return id;
}
public void setId(final Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(final String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(final String url) {
this.url = url;
}
}
|
package com.xdandroid.sample;
import android.content.*;
import android.os.*;
import com.xdandroid.hellodaemon.*;
import java.util.concurrent.*;
import io.reactivex.*;
import io.reactivex.disposables.*;
public class TraceServiceImpl extends AbsWorkService {
//임무가 완성되지 않았는데, 더 이상 서비스 운행이 필요 없습니까?
public static boolean sShouldStopService;
public static Disposable sDisposable;
public static void stopService() {
//우리는 이제 더 이상 서비스 운행이 필요치 않습니다. 로고 위치를 표시합니다. true
sShouldStopService = true;
//일과 관련된 구독을 취소하다
if (sDisposable != null) sDisposable.dispose();
//취소 Job / Alarm / Subscription
cancelJobAlarmSub();
}
/**
* 임무 완수 여부, 서비스 실행이 필요 없나요?
* @return 서비스를 중단해야 한다, true; 서비스를 시작해야 한다, false; 아무것도 하지 않고, 아무것도 하지 않고, null.
*/
@Override
public Boolean shouldStopService(Intent intent, int flags, int startId) {
return sShouldStopService;
}
@Override
public void startWork(Intent intent, int flags, int startId) {
System.out.println("검사 디스켓에 저장된 데이터가 있는지 없는지 검사하시오");
sDisposable = Observable
.interval(3, TimeUnit.SECONDS)
//취소 시에는 타이머를 취소하고
.doOnDispose(() -> {
System.out.println("데이터를 저장 디스켓에 저장한다.。");
cancelJobAlarmSub();
})
.subscribe(count -> {
System.out.println("매 3초마다 데이터를 수집합니다.... count = " + count);
if (count > 0 && count % 18 == 0) System.out.println("데이터를 저장 디스켓에 저장한다.。 saveCount = " + (count / 18 - 1));
});
}
@Override
public void stopWork(Intent intent, int flags, int startId) {
stopService();
}
/**
* 임무는 지금 실행 중입니까?
* @return 임무가 한창 작동 중이다., true; 임무는 현재 운행 중이다., false;판단할 수 없고 아무것도 하지 않는다 null.
*/
@Override
public Boolean isWorkRunning(Intent intent, int flags, int startId) {
//아직까지 구독을 취소하지 않았다면 임무를 수행하고 있음을 설명할 수 있다.
return sDisposable != null && !sDisposable.isDisposed();
}
@Override
public IBinder onBind(Intent intent, Void v) {
return null;
}
@Override
public void onServiceKilled(Intent rootIntent) {
System.out.println("데이터를 저장 디스켓에 저장한다。");
}
}
|
package blackbird.core.util;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.util.List;
public class MultiException {
public static String generateMultipleExceptionText(List<? extends Exception> exceptions, List<String> headlines) {
String text = "\n";
for (int i = 0; i < exceptions.size(); i++) {
text += headlines.get(i) + ": ";
text += ExceptionUtils.getStackTrace(exceptions.get(i));
text += "\n\n";
}
return text;
}
public static String generateMultipleExceptionText(List<? extends Exception> exceptions) {
String text = "\n";
for (Exception exception : exceptions) {
String lines = ExceptionUtils.getStackTrace(exception);
text += lines.replace("\n", "\n\t");
text += "\n\n";
}
return text;
}
}
|
package com.emg.projectsmanage.bean;
/**
* 编辑工作量统计poi数量对象
*
* @author AD
*
*/
public class CapacityPOICountModel {
private String name = ""; // 编辑工作量统计poi名称
private int count = 0; // 数量
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = this.count + count;
}
}
|
package ro.ase.cts.composite.clase;
public class Composite {
}
|
package com.example.onemap;
import android.provider.BaseColumns;
/**
* 提供dbhelper的String
*
* @author acer
*
*/
public class AcrossConstants implements BaseColumns {
public static final String DATABASE_NAME = "oneMaps.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_LAYERS = "Layers";
public static final String TABLE_PLACE = "PlaceMarks";
// =======================================================================
// ===== COLUMN OF LAYERS ================================================
// =======================================================================
public static final String LA_FIELD_ID = "_id";
public static final String LA_FIELD_LAYER_NAME = "LayerName";
public static final String LA_FIELD_LAYER_SIZE = "LayerSize";
public static final String LA_FIELD_LDESC = "LayerDescription";
public static final String LA_FIELD_DISPLAY = "Display";
public static final String LA_FIELD_CREATE_AT = "CreateAt";
// =======================================================================
// ===== COLUMN OF PLACEMARK =============================================
// =======================================================================
public static final String PM_FIELD_ID = "_id";
public static final String PM_FIELD_LAYER_NAME = "LayerName";
public static final String PM_FIELD_PLACEMARK_NAME = "PlaceMarkName";
public static final String PM_FIELD_DESC = "PlaceMarkDescription";
public static final String PM_FIELD_DISPLAY = "Display";
public static final String PM_FIELD_STYLELINK = "StyleLink";
// =======================================================================
// ==== COLUMN LIST ======================================================
// =======================================================================
public static final String[] LA_COLUMNS = { LA_FIELD_ID,
LA_FIELD_LAYER_NAME, LA_FIELD_LAYER_SIZE, LA_FIELD_LDESC,
LA_FIELD_DISPLAY, LA_FIELD_CREATE_AT };
public static final String[] PM_COLUMNS = { PM_FIELD_ID,
PM_FIELD_LAYER_NAME, PM_FIELD_PLACEMARK_NAME, PM_FIELD_DESC,
PM_FIELD_DISPLAY, PM_FIELD_STYLELINK };
// =======================================================================
// ===== SQLITE SYNTAX ===================================================
// =======================================================================
// TODO CREATE FROM COLUMN (該起上傳功能的前置)
public static final String INIT_LA_TABLE = "CREATE TABLE IF NOT EXISTS "
+ TABLE_LAYERS + " (" + " _id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ LA_FIELD_LAYER_NAME + " TEXT, " + LA_FIELD_LAYER_SIZE
+ " INTEGER, " + LA_FIELD_LDESC + " TEXT, " + LA_FIELD_CREATE_AT
+ " TEXT, " + LA_FIELD_DISPLAY + " TEXT);";
public static final String INIT_PM_TABLE = "CREATE TABLE IF NOT EXISTS "
+ TABLE_PLACE + " (" + " _id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ PM_FIELD_LAYER_NAME + " TEXT, " + PM_FIELD_PLACEMARK_NAME
+ " TEXT, " + PM_FIELD_DESC + " TEXT, " + PM_FIELD_DISPLAY
+ " TEXT, " + PM_FIELD_STYLELINK + " TEXT);";
public static final String DROP_LA_TABLE = "DROP TABLE IF EXISTS "
+ TABLE_LAYERS;
public static final String DROP_PM_TABLE = "DROP TABLE IF EXISTS "
+ TABLE_PLACE;
}// end of AcrossConstants
|
package com.fsClothes.service;
import java.math.BigDecimal;
import java.util.List;
import com.fsClothes.pojo.Admin;
import com.fsClothes.pojo.Page;
/**
* @author MrDCG
* @version 创建时间:2019年9月16日 下午4:08:14
*
*/
public interface AdminService {
List<Admin> findAll();
// 获取分页信息
Page<Admin> findByPageSize(Page<Admin> page);
void insert(Admin admin);
Admin findById(int id);
void update(Admin admin);
void delete(int id);
/**
* 登录
*/
Admin login (String aname,String apwd);
Admin findByAname(String adminName);
Admin findByInvitationCode(String invitationCode);
void resetPassword(int id);
int findAllCount();
/**
* 登录查询
* @param adminName 管理员名字
* @param adminPassword 管理员密码
* @return 管理员
*/
Admin findLogin(String adminName, String adminPassword);
/**
* 修改权限
* @param id adminId
* @param authorization 权限
*/
void modifyAuth(Integer id, Integer authorization);
/**
* 月季度查询营收额
* @param startMonth 开始时间
* @param endMonth 结束时加
* @return 金额
*/
BigDecimal findByOrderDate(String startMonth, String endMonth);
}
|
package com.duanc.serivce.impl.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.duanc.api.web.ShowService;
import com.duanc.inner.common.BasePhoneToDTO;
import com.duanc.mapper.base.BrandMapper;
import com.duanc.mapper.base.ModelMapper;
import com.duanc.mapper.base.PhoneMapper;
import com.duanc.model.base.BasePhone;
import com.duanc.model.dto.PhoneDTO;
@Service("showService")
public class ShowServiceImpl implements ShowService{
@Autowired
private PhoneMapper phoneMapper;
@Autowired
private BrandMapper brandMapper;
@Autowired
private ModelMapper modelMapper;
@Override
public PhoneDTO getPhoneDTO(Integer id) {
BasePhone bp = phoneMapper.selectByPrimaryKey(id);
PhoneDTO phoneDTO = new BasePhoneToDTO().getPhoneDTO(bp,modelMapper,brandMapper);
/*PhoneDTO phoneDTO = new PhoneDTO();
phoneDTO.setBattery(bp.getBatteryCapacity());
phoneDTO.setBrandId(bp.getBrandId());
phoneDTO.setBrandName(brandMapper.selectByPrimaryKey(bp.getBrandId()).getBrandName());
phoneDTO.setCpu(bp.getCpu());
phoneDTO.setCpuCores(bp.getCpuCores());
phoneDTO.setCpuhz(bp.getCpuHz());
phoneDTO.setId(id);
phoneDTO.setListingDate(bp.getListingDate());
phoneDTO.setModelId(bp.getModelId());
phoneDTO.setModelName(modelMapper.selectByPrimaryKey(bp.getModelId()).getModelName());
phoneDTO.setNetType(bp.getNetType());
phoneDTO.setOs(bp.getOs());
phoneDTO.setPicUrl(bp.getPicUrl());
phoneDTO.setPrice(bp.getPrice());
phoneDTO.setRam(bp.getRam());
phoneDTO.setRom(bp.getRom());
phoneDTO.setScreensize(bp.getScreenSize());
phoneDTO.setVersion(bp.getVersion());*/
return phoneDTO;
}
}
|
package structural.composite;
/**
* @author Renat Kaitmazov
*/
/**
* It is a base component where we define common methods
* for both leaves and a composite. It can either an abstract class
* or an interface.
*/
public interface Shape {
void draw(String color);
}
|
package ccs.education.login;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import ccs.education.login.entity.Account;
public class LoginUser extends User {
private Account account;
// Account情報をDTOクラスに設定する、今回のデモではすべてユーザ権限とする
public LoginUser(Account account) {
super(account.getId(), account.getPassword(), AuthorityUtils.createAuthorityList("USER"));
this.account = account;
}
public Account getAccount() {
return account;
}
}
|
package gina.nikol.qnr.demo.dao;
import java.util.List;
import gina.nikol.qnr.demo.entity.Department;
public interface DepartmentDAO {
public List<Department> getDepartments();
public Department getDepartment(int depId);
}
|
package com.shahinnazarov.gradle;
import com.shahinnazarov.gradle.models.k8s.Service;
import com.shahinnazarov.gradle.utils.K8sContext;
import org.junit.Assert;
import org.junit.Test;
import java.util.Properties;
public class K8sServiceGenerationTest {
@Test
public void generateSingle() {
K8sContext.initialize(getSingleService());
K8sContext context = K8sContext.getInstance();
Service service = context.getService("ns01/svc01");
System.out.println(context.getAsYaml(service));
Assert.assertEquals(service.getMetadata().getName(), "engine-event-consumer-service");
}
public Properties getSingleService() {
Properties properties = new Properties();
properties.put("k8s.svc.ns01/svc01.name", "engine-event-consumer-service");
properties.put("k8s.svc.ns01/svc01.selector.applicationName", "application11");
properties.put("k8s.svc.ns01/svc01.type", "NodePort");
properties.put("k8s.svc.ns01/svc01.ports.web.protocol", "TCP");
properties.put("k8s.svc.ns01/svc01.ports.web.port", "8801");
properties.put("k8s.svc.ns01/svc01.ports.web.targetPort", "8801");
properties.put("k8s.svc.ns01/svc01.ports.web.nodePort", "31301");
properties.put("k8s.svc.ns01/svc01.ports.grpc.protocol", "TCP");
properties.put("k8s.svc.ns01/svc01.ports.grpc.port", "8808");
properties.put("k8s.svc.ns01/svc01.ports.grpc.targetPort", "8808");
properties.put("k8s.svc.ns01/svc01.ports.grpc.nodePort", "31308");
return properties;
}
}
|
package com.taobrother.exercise.web;
import com.taobrother.exercise.entity.Employee;
import com.taobrother.exercise.service.EmployeeService;
import com.taobrother.exercise.web.annotation.VerifyName;
import com.taobrother.exercise.web.request.SignUpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class EmployeeController {
private final EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService){
this.employeeService = employeeService;
}
@GetMapping("/api/list")
public ResponseEntity getAllEmployees(){
List<Employee> allEmployees = employeeService.getAllEmployees();
return ResponseEntity.status(HttpStatus.OK).body(allEmployees);
}
@GetMapping("/health")
public ResponseEntity testEndPoint(){
return ResponseEntity.status(HttpStatus.OK).body("services are up");
}
@GetMapping("/api/admin")
public ResponseEntity getAdmin(){
return ResponseEntity.status(HttpStatus.OK).body(employeeService.getEmployeeAdmin());
}
@PostMapping("/api/sign_up")
public ResponseEntity signUp(@RequestBody SignUpRequest request){
employeeService.createEmployee(request.getName());
return ResponseEntity.status(HttpStatus.OK).body("sign up success");
}
}
|
package runners;
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
@RunWith(Cucumber.class)
@CucumberOptions(
publish = true,
//features = "src//test//resources//features//CRMloginfeature.feature",
features = "src//test//resources//tagFeatures//",
glue = {"stepdefs"},
//dryRun=true, //to verify if all the steps are defined or not. it will not execute the test, it will only verify.
//dryRun = false //it will not verify the steps. it will only execute test, by default dryRun is false
monochrome=true,
//tags = "@RegressionTest",
//tags = "@RegressionTest or @SmokeTest", //to execute scenarios that have RegressionTest or SmokeTest
//tags = "@ModuleOne and @RegressionTest",//to execute the Scenarios of RegressionTest only in particular feature file
tags = "@ModuleOne and @SmokeTest",
//tags = "@ModuleOne",//to execute all the cases in ModuleOne
//tags = "@ModuleOne and not @SmokeTest" //to exculde smoketest scenarios
plugin= {"pretty",
"html:target/reports/HtmlReport.html",
//"usage:target/reports/UsageReport",
//"json:target/reports/JSONReport.json",
//"rerun:target/failed_scenarios.txt"
//"com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter:"
}
)
public class CRMJunitRunner{
} |
import java.lang.Math;
import java.util.List;
import java.util.ArrayList;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.Digraph;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class Outcast {
private WordNet wordnet;
public Outcast(WordNet wordnet) {
this.wordnet = wordnet;
}
public String outcast(String[] nouns) {
int max = 0;
String res = "";
for (String noun : nouns) {
int current = 0;
for (String tnoun : nouns) {
current += wordnet.distance(noun, tnoun);
}
if (max < current) {
max = current;
res = noun;
}
}
return res;
}
}
|
//
//©2002-2007 Accenture. All rights reserved.
//
/**
* Classe abstrata que declara o método que valida o acesso de um usuário para uma determinada função do sistema.
*
* @see com.citibank.ods.common.security;
* @version 1.0
* @author marcelo.s.oliveira,June 1 , 2007
*
*/
package com.citibank.ods.common.security;
import com.citibank.ods.common.exception.UnexpectedException;
import com.citibank.ods.common.user.User;
public abstract class Authorization
{
public abstract boolean hasAccess(User user, String s)
throws UnexpectedException;
}
|
package com.jeremiaslongo.apps.spotifystreamer.util;
import android.content.Context;
import android.media.AudioManager;
/**
* Convenience class to deal with audio focus. This class deals with everything related to audio
* focus: it can request and abandon focus, and will intercept focus change events and deliver
* them to a MusicFocusable interface (which, in our case, is implemented by MusicService.
*/
public class AudioFocusHelper implements AudioManager.OnAudioFocusChangeListener {
AudioManager mAM;
MusicFocusable mFocusable;
public AudioFocusHelper(Context ctx, MusicFocusable focusable) {
mAM = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
mFocusable = focusable;
}
/** Requests audio focus. Returns whether request was successful or not. */
public boolean requestFocus() {
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED ==
mAM.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
/** Abandons audio focus. Returns whether request was successful or not. */
public boolean abandonFocus() {
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAM.abandonAudioFocus(this);
}
/**
* Called by AudioManager on audio focus changes. We implement this by calling our
* MusicFocusable appropriately to relay the message.
*/
public void onAudioFocusChange(int focusChange) {
if (mFocusable == null) return;
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
mFocusable.onGainedAudioFocus();
break;
case AudioManager.AUDIOFOCUS_LOSS:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
mFocusable.onLostAudioFocus(false);
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
mFocusable.onLostAudioFocus(true);
break;
default:
}
}
/**
* Represents something that can react to audio focus events. We implement this instead of just
* using AudioManager.OnAudioFocusChangeListener because that interface is only available in SDK
* level 8 and above, and we want our application to work on previous SDKs.
*/
public interface MusicFocusable {
/** Signals that audio focus was gained. */
public void onGainedAudioFocus();
/**
* Signals that audio focus was lost.
*
* @param canDuck If true, audio can continue in "ducked" mode (low volume). Otherwise, all
* audio must stop.
*/
public void onLostAudioFocus(boolean canDuck);
}
} |
package com.example.pokerpursuit;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ImageView iv_qian;
private ImageView iv_hou;
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
};
};
private Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv_qian = (ImageView) findViewById(R.id.iv_qian);
iv_hou = (ImageView) findViewById(R.id.iv_hou);
bt = (Button) findViewById(R.id.bt);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this,
MainActivity1.class);
startActivity(intent);
}
});
iv_qian.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
float rotationY = iv_qian.getRotationY();
float translationY = iv_qian.getTranslationY();
float translationX = iv_qian.getTranslationX();
ObjectAnimator ofFloat8 = ObjectAnimator.ofFloat(iv_hou,
"alpha", 0, 1);
ObjectAnimator ofFloat7 = ObjectAnimator.ofFloat(iv_hou,
"scaleX", 0f, 1f);
ObjectAnimator ofFloat6 = ObjectAnimator.ofFloat(iv_hou,
"scaleY", 0f, 1f);
ObjectAnimator ofFloat5 = ObjectAnimator.ofFloat(iv_qian,
"scaleY", 1f, 0.3f);
ObjectAnimator ofFloat4 = ObjectAnimator.ofFloat(iv_qian,
"scaleX", 1f, 0.3f);
ObjectAnimator ofFloat3 = ObjectAnimator.ofFloat(iv_qian,
"alpha", 1, 0);
ObjectAnimator ofFloat2 = ObjectAnimator.ofFloat(iv_qian,
"rotationY", rotationY + 180);
ObjectAnimator ofFloat = ObjectAnimator.ofFloat(iv_qian,
"translationX", translationX - 500);
ObjectAnimator ofFloat1 = ObjectAnimator.ofFloat(iv_qian,
"translationY", translationY - 500);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(ofFloat).with(ofFloat1).with(ofFloat2)
.with(ofFloat3).with(ofFloat4).with(ofFloat5)
.with(ofFloat6).with(ofFloat7);
animatorSet.setDuration(1000);
animatorSet.start();
}
});
}
}
|
package com.firedata.qtacker.repository.search;
import com.firedata.qtacker.domain.CompanyExtern;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Spring Data Elasticsearch repository for the {@link CompanyExtern} entity.
*/
public interface CompanyExternSearchRepository extends ElasticsearchRepository<CompanyExtern, Long> {
}
|
package ffm.slc.model.enums;
/**
* Indication of whether the position was filled or retired without filling.
*/
public enum PostingResultType {
POSITION_FILLED("Position Filled"),
POSTING_CANCELLED("Posting Cancelled");
private String prettyName;
PostingResultType(String prettyName) {
this.prettyName = prettyName;
}
@Override
public String toString() {
return prettyName;
}
}
|
/*
* MainActivity.java
*
* Version: MainActivity.java, v 1.0 2018/06/16
*
* Revisions:
* Revision 1.0 2018/06/16 08:11:09
* Initial Revision
*
*/
package com.dream.the.code.droidswatch;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.os.Build;
import android.content.*;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.safetynet.SafetyNet;
import com.google.android.gms.safetynet.SafetyNetApi;
import com.google.android.gms.safetynet.SafetyNetClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import java.util.*;
import java.io.*;
/**
* This class is the Welcome page and handles externals application calls (SafteyNetAPI and Rule
* Engine), gathers all device facts and receives the final security evaluation.
*
* @author Mansha Malik
* @author Parinitha Nagaraja
* @author Qiaoran Li
*
*/
public class MainActivity extends AppCompatActivity {
private String mResult = null;
byte[] nonce = new byte[32];
private boolean isSafteyNetAvailable = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = getApplicationContext();
// Send request to SafteyNetAPI if Internet and Google Play Services are available
if ( Utils.isInternetAvailable( context ) && Utils.isGooglePlayServicesAvailable( context) ) {
isSafteyNetAvailable = true;
safteyNetRequest();
}
}
/**
* onEvaluateClick method is called on Evaluate button click.It gathers all device facts and
* sends the facts to Rule Engine for final evaluation
* It sends the result to MainActivity2 for displaying the results to the user
*
* param v View
*
* @return None
*/
public void onEvaluateClick( View v ){
// Check if we are on correct running on Android version (API 24 and above )
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ) {
Context context = v.getContext();
// Gather device facts
StringBuilder allPhoneFacts = gatherPhoneFacts( context );
// Get final evaluation result from rule engine
String finalEvaluation = getFinalSecurityEvaluation( allPhoneFacts.toString() );
// Merging final security evaluation with the facts
String allFactsAndFinalRes = allPhoneFacts.toString() + "@"+ finalEvaluation;
Intent summary = new Intent(MainActivity.this, MainActivity2.class);
summary.putExtra("message",allFactsAndFinalRes);
// Send the result to MainActivity2 for displaying the result to user
startActivity(summary);
finish();
}
}
/**
* getFinalSecurityEvaluation method calls the Rule Engine and gets the final Security
* Evaluation result (Low/Medium/High)
*
* param allDeviceFacts Device facts
*
* @return finalSecurityEvaluationRes Low/Medium/High
*/
private String getFinalSecurityEvaluation( String allDeviceFacts ){
String finalSecurityEvaluationRes = Constants.FINAL_MESSAGE;
try{
// Read the rules from ESRules.txt
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open( Constants.RULES_FILE_NAME )));
String rule = "";
String allRules = "";
//all rules added to the string
while (( rule = reader.readLine()) != null ) {
rule = rule.trim();
if(!rule.equals("")) {
allRules += rule + "@";
}
}
// All rule and device facts from ESRules.txt
allRules = allRules + allDeviceFacts;
//allRules = allRules.substring(0, allRules.length()-1 );
List<String> goals = Arrays.asList( Constants.FINAL_SECURITY_EVAL_GOALS.split(",") );
Entail ruleEngine = new Entail();
for ( String goal : goals ) {
// Call the Rule Engine
if( ruleEngine.ruleEngineProcess( allRules, goal ) ){
finalSecurityEvaluationRes += goal + "!";
break;
}
}
}catch ( IOException ex ){
ex.printStackTrace();
}
// Return the final security evaluation result
return finalSecurityEvaluationRes;
}
/**
* gatherPhoneFacts method gathers all device facts
*
* param context Context
*
* @return factsStringBuilder All device facts
*/
private StringBuilder gatherPhoneFacts( Context context){
StringBuilder factsStringBuilder = new StringBuilder();
List<String> phoneFacts = new ArrayList<String>();
// Fetch App Security aspect facts
AppSecurity appSecurityObj = new AppSecurity();
phoneFacts.addAll( appSecurityObj.appSecurity( context.getPackageManager() ) );
// Fetch Device Feature Security aspect facts
DeviceFeatureSecurity deviceFeatureSecurityObj = new DeviceFeatureSecurity();
phoneFacts.addAll( deviceFeatureSecurityObj.deviceFeatureSecurity() );
// Fetch Sensor Security aspect facts
SensorSecurity sensorSecurityObj = new SensorSecurity();
phoneFacts.addAll( sensorSecurityObj.sensorSecurity( context, mResult, isSafteyNetAvailable, nonce ) );
int numberOfFacts = phoneFacts.size();
int counter = 0;
// For each fact append @
for ( String fact : phoneFacts ) {
counter++;
factsStringBuilder.append( fact );
if( counter != numberOfFacts )
factsStringBuilder.append("@");
}
// Return device facts
return factsStringBuilder;
}
/**
* safteyNetRequest method sends a request to SafteyNetAPI
*
* param None
*
* @return None
*/
private void safteyNetRequest(){
nonce = Utils.generateOneTimeRequestNonce();
SafetyNetClient client = SafetyNet.getClient(MainActivity.this);
Task<SafetyNetApi.AttestationResponse> task = client.attest(nonce, Constants.API_KEY);
task.addOnSuccessListener(MainActivity.this, mSuccessListener)
.addOnFailureListener(MainActivity.this, mFailureListener);
}
/**
* OnSuccessListener method is called when the SafteyNetAPI returns with response.
* mResult will have the response
*
* param None
*
* @return None
*/
private OnSuccessListener<SafetyNetApi.AttestationResponse> mSuccessListener =
new OnSuccessListener<SafetyNetApi.AttestationResponse>() {
@Override
public void onSuccess(SafetyNetApi.AttestationResponse attestationResponse) {
/*
Successfully communicated with SafetyNet API.
Use result.getJwsResult() to get the signed result data. See the server
component of this sample for details on how to verify and parse this result.
*/
mResult = attestationResponse.getJwsResult();
//System.out.print( mResult );
Log.d("tag", "Success! SafetyNet result:\n" + mResult + "\n");
}
};
/**
* OnFailureListener method is called when there is a SafteyNetAPI request error.
* mResult will be null
*
* param None
*
* @return None
*/
private OnFailureListener mFailureListener = new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// An error occurred while communicating with the service.
mResult = null;
if (e instanceof ApiException) {
// An error with the Google Play Services API contains some additional details.
ApiException apiException = (ApiException) e;
Log.d("TAG", "Error: " +
CommonStatusCodes.getStatusCodeString(apiException.getStatusCode()) + ": " +
apiException.getStatusMessage());
} else {
// A different, unknown type of error occurred.
Log.d("TAG", "ERROR! " + e.getMessage());
}
}
};
}
|
package com.freddy.sample.mpesa;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.TextView;
import com.anychart.AnyChart;
import com.anychart.AnyChartView;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.chart.common.dataentry.ValueDataEntry;
import com.anychart.charts.Cartesian;
import com.anychart.core.cartesian.series.Line;
import com.anychart.data.Mapping;
import com.anychart.data.Set;
import com.anychart.enums.MarkerType;
import com.anychart.enums.TooltipPositionMode;
import com.anychart.graphics.vector.Stroke;
import com.freddy.sample.mpesa.Model.funeralpayments;
import java.util.List;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
////import com.github.mikephil.charting.charts.LineChart;
////import com.github.mikephil.charting.data.Entry;
//import com.github.mikephil.charting.data.LineData;
//import com.github.mikephil.charting.data.LineDataSet;
//import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
public class ViewPaymentReportActivity extends AppCompatActivity {
ListView lv;
List<funeralpayments> paymentl;
DatabaseReference paymentRef,funeralpaymentRef;
TextView texv;
// LineChart linechart;
// LineDataSet lineDataSet=new LineDataSet(null,null);
// ArrayList<ILineDataSet> iLineDataSets=new ArrayList<>();
// LineData lineData;
AnyChartView anyChartView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_payment_report);
lv=findViewById(R.id.mylistview);
anyChartView = findViewById(R.id.linegraph);
// linechart=(LineChart)findViewById(R.id.linegraph);
texv=(TextView)findViewById(R.id.showtotalpaidvalue);
paymentl=new ArrayList<>();
paymentRef = FirebaseDatabase.getInstance().getReference().child("funeral requests payments admin");
funeralpaymentRef = FirebaseDatabase.getInstance().getReference().child("funeral requests payments admin");
paymentRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
paymentl.clear();
for (DataSnapshot paymentds : dataSnapshot.getChildren()){
funeralpayments fpmts=paymentds.getValue(funeralpayments.class);
paymentl.add(fpmts);
}
ListAdapter adapter = new ListAdapter(ViewPaymentReportActivity.this,paymentl);
lv.setAdapter(adapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
funeralpaymentRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
int sum=0;
// for(DataSnapshot ds : dataSnapshot.getChildrenCount()){
//
// }
for( DataSnapshot ds :dataSnapshot.getChildren()) {
Map<String,Object> map=(Map<String,Object>) ds.getValue();
Object totalpayment=map.get("amountpaid");
int pValue=Integer.parseInt(String.valueOf(totalpayment));
sum += pValue;
texv.setText(String.valueOf(sum));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
// funeralpaymentRef.addValueEventListener(new ValueEventListener() {
// @Override
// public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// int date;
// int amount;
// try {
// ArrayList<Entry> dataVals = new ArrayList<Entry>();
// if (dataSnapshot.hasChildren()) {
// for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
// funeralpayments fp = dataSnapshot1.getValue(funeralpayments.class);
// date = Integer.parseInt(fp.getPreservationstart());
// amount = Integer.parseInt(fp.getAmountpaid());
//
// dataVals.add(new Entry(date, amount));
//
//
// }
// showChart(dataVals);
// } else {
// linechart.clear();
// linechart.invalidate();
// }
// }catch (Exception e){
// e.printStackTrace();
// }
//
// }
//
// @Override
// public void onCancelled(@NonNull DatabaseError databaseError) {
//
// }
// });
funeralpaymentRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String date;
int amount;
Cartesian cartesian = AnyChart.line();
cartesian.animation(true);
cartesian.padding(10d, 20d, 5d, 20d);
cartesian.crosshair().enabled(true);
cartesian.crosshair()
.yLabel(true)
// TODO ystroke
.yStroke((Stroke) null, null, null, (String) null, (String) null);
cartesian.tooltip().positionMode(TooltipPositionMode.POINT);
cartesian.title("Morgue Payment Representation.");
cartesian.yAxis(0).title("Amount Generated in(Shillings)");
cartesian.xAxis(0).labels().padding(5d, 5d, 5d, 5d);
List<DataEntry> seriesData = new ArrayList<>();
if (dataSnapshot.hasChildren()) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
funeralpayments fp = dataSnapshot1.getValue(funeralpayments.class);
date = (fp.getDate());
amount = Integer.parseInt(fp.getAmountpaid());
seriesData.add(new CustomDataEntry(date, amount));
}
}
// seriesData.add(new CustomDataEntry("1986", 3.6));
// seriesData.add(new CustomDataEntry("1995", 12.0));
// seriesData.add(new CustomDataEntry("1996", 3.2));
// seriesData.add(new CustomDataEntry("1997", 4.1));
// seriesData.add(new CustomDataEntry("1998", 6.3));
// seriesData.add(new CustomDataEntry("2008", 15.7));
// seriesData.add(new CustomDataEntry("2009", 12.0));
Set set = Set.instantiate();
set.data(seriesData);
Mapping series1Mapping = set.mapAs("{ x: 'x', value: 'value' }");
Line series1 = cartesian.line(series1Mapping);
series1.name("Amount Representation");
series1.hovered().markers().enabled(true);
series1.hovered().markers()
.type(MarkerType.CIRCLE)
.size(4d);
series1.tooltip()
.position("right")
.offsetX(5d)
.offsetY(5d);
cartesian.legend().enabled(true);
cartesian.legend().fontSize(13d);
cartesian.legend().padding(0d, 0d, 10d, 0d);
anyChartView.setChart(cartesian);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private class CustomDataEntry extends ValueDataEntry {
CustomDataEntry(String x, Number value) {
super(x, value);
// setValue("value2", value2);
// setValue("value3", value3);
}
}
// private void showChart(ArrayList<Entry> dataVals) {
// lineDataSet.setValues(dataVals);
// lineDataSet.setLabel("Morgue Income Analysis");
// iLineDataSets.clear();
// iLineDataSets.add(lineDataSet);
// lineData=new LineData(iLineDataSets);
// linechart.clear();
// linechart.setData(lineData);
// linechart.invalidate();
//
//
// }
}
|
package io.quarkus.cxf.deployment;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Produces;
import javax.jws.WebParam;
import javax.servlet.DispatcherType;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import io.quarkus.runtime.util.HashUtil;
import org.apache.cxf.common.jaxb.JAXBUtils;
import org.apache.cxf.common.util.StringUtils;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.MethodParameterInfo;
import org.jboss.jandex.Type;
import org.jboss.logging.Logger;
import io.quarkus.arc.Unremovable;
import io.quarkus.arc.deployment.GeneratedBeanBuildItem;
import io.quarkus.arc.deployment.GeneratedBeanGizmoAdaptor;
import io.quarkus.arc.deployment.UnremovableBeanBuildItem;
import io.quarkus.arc.processor.BeanInfo;
import io.quarkus.arc.processor.DotNames;
import io.quarkus.cxf.AbstractCxfClientProducer;
import io.quarkus.cxf.CXFQuarkusServlet;
import io.quarkus.cxf.CXFServletRecorder;
import io.quarkus.deployment.Capabilities;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.ExecutionTime;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.deployment.builditem.nativeimage.NativeImageProxyDefinitionBuildItem;
import io.quarkus.deployment.builditem.nativeimage.NativeImageResourceBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.deployment.builditem.nativeimage.RuntimeInitializedClassBuildItem;
import io.quarkus.gizmo.BranchResult;
import io.quarkus.gizmo.BytecodeCreator;
import io.quarkus.gizmo.ClassCreator;
import io.quarkus.gizmo.ClassOutput;
import io.quarkus.gizmo.FieldCreator;
import io.quarkus.gizmo.MethodCreator;
import io.quarkus.gizmo.MethodDescriptor;
import io.quarkus.gizmo.ResultHandle;
import io.quarkus.jaxb.deployment.JaxbFileRootBuildItem;
import io.quarkus.undertow.deployment.FilterBuildItem;
import io.quarkus.undertow.deployment.ServletBuildItem;
import io.quarkus.undertow.deployment.ServletInitParamBuildItem;
import io.quarkus.vertx.http.deployment.RouteBuildItem;
class QuarkusCxfProcessor {
private static final String JAX_WS_SERVLET_NAME = "org.apache.cxf.transport.servlet.CXFNonSpringServlet;";
private static final String JAX_WS_FILTER_NAME = JAX_WS_SERVLET_NAME;
private static final String FEATURE_CXF = "cxf";
private static final DotName WEBSERVICE_ANNOTATION = DotName.createSimple("javax.jws.WebService");
private static final DotName WEBMETHOD_ANNOTATION = DotName.createSimple("javax.jws.WebMethod");
private static final DotName WEBPARAM_ANNOTATION = DotName.createSimple("javax.jws.WebParam");
private static final DotName WEBRESULT_ANNOTATION = DotName.createSimple("javax.jws.WebResult");
private static final DotName REQUEST_WRAPPER_ANNOTATION = DotName.createSimple("javax.xml.ws.RequestWrapper");
private static final DotName RESPONSE_WRAPPER_ANNOTATION = DotName.createSimple("javax.xml.ws.ResponseWrapper");
private static final DotName SOAPBINDING_ANNOTATION = DotName.createSimple("javax.jws.soap.SOAPBinding");
private static final DotName WEBFAULT_ANNOTATION = DotName.createSimple("javax.jws.WebFault");
private static final DotName ABSTRACT_FEATURE = DotName.createSimple("org.apache.cxf.feature.AbstractFeature");
private static final DotName ABSTRACT_INTERCEPTOR = DotName.createSimple("org.apache.cxf.phase.AbstractPhaseInterceptor");
private static final DotName DATABINDING = DotName.createSimple("org.apache.cxf.databinding");
private static final Logger LOGGER = Logger.getLogger(QuarkusCxfProcessor.class);
private static final List<Class<? extends Annotation>> JAXB_ANNOTATIONS = Arrays.asList(
XmlList.class,
XmlAttachmentRef.class,
XmlJavaTypeAdapter.class,
XmlMimeType.class,
XmlElement.class,
XmlElementWrapper.class);
/**
* JAX-WS configuration.
*/
CxfConfig cxfConfig;
@BuildStep
public void generateWSDL(BuildProducer<NativeImageResourceBuildItem> ressources) {
for (CxfEndpointConfig endpointCfg : cxfConfig.endpoints.values()) {
if (endpointCfg.wsdlPath.isPresent()) {
ressources.produce(new NativeImageResourceBuildItem(endpointCfg.wsdlPath.get()));
}
}
}
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
public void build(List<CXFServletInfoBuildItem> cxfServletInfos,
BuildProducer<RouteBuildItem> routes,
CXFServletRecorder recorder) {
for (CXFServletInfoBuildItem cxfServletInfo : cxfServletInfos) {
recorder.registerCXFServlet(cxfServletInfo.getPath(),
cxfServletInfo.getClassName(), cxfServletInfo.getInInterceptors(),
cxfServletInfo.getOutInterceptors(), cxfServletInfo.getOutFaultInterceptors(),
cxfServletInfo.getInFaultInterceptors(), cxfServletInfo.getFeatures(), cxfServletInfo.getSei(),
cxfServletInfo.getWsdlPath());
}
}
private static final String RESPONSE_CLASS_POSTFIX = "Response";
//TODO check if better to reuse the cxf parsing system to generate only asm from their.
private MethodDescriptor createWrapper(boolean isRequest, String operationName, String namespace, String resultName,
String resultType,
List<WrapperParameter> params, ClassOutput classOutput, String pkg, String className,
List<MethodDescriptor> getters, List<MethodDescriptor> setters) {
//WrapperClassGenerator
ClassCreator classCreator = ClassCreator.builder().classOutput(classOutput)
.className(pkg + "." + className + (isRequest ? "" : RESPONSE_CLASS_POSTFIX))
.build();
MethodDescriptor ctorDescriptor = null;
classCreator.addAnnotation(AnnotationInstance.create(
DotName.createSimple(XmlRootElement.class.getName()), null,
new AnnotationValue[] { AnnotationValue.createStringValue("name", operationName),
AnnotationValue.createStringValue("namespace", namespace) }));
classCreator.addAnnotation(AnnotationInstance.create(
DotName.createSimple(XmlAccessorType.class.getName()), null,
new AnnotationValue[] {
AnnotationValue.createEnumValue("value",
DotName.createSimple(XmlAccessType.class.getName()), "FIELD") }));
//if (!anonymous)
classCreator.addAnnotation(AnnotationInstance.create(
DotName.createSimple(XmlType.class.getName()), null,
new AnnotationValue[] { AnnotationValue.createStringValue("name", operationName),
AnnotationValue.createStringValue("namespace", namespace) }));
// else
//classCreator.addAnnotation(AnnotationInstance.create(
// DotName.createSimple(XmlType.class.getName()), null,
// new AnnotationValue[] { AnnotationValue.createStringValue("name", "")}));
try (MethodCreator ctor = classCreator.getMethodCreator("<init>", "V")) {
ctor.setModifiers(Modifier.PUBLIC);
ctor.invokeSpecialMethod(MethodDescriptor.ofConstructor(Object.class), ctor.getThis());
ctor.returnValue(null);
ctorDescriptor = ctor.getMethodDescriptor();
}
if (!isRequest && resultName != null && resultType != null && !resultType.equals("void")) {
//TODO check if method annotation must been forwarded
try {
createWrapperClassField(getters, setters, classCreator, resultType, resultName,
new ArrayList<AnnotationInstance>());
} catch (Exception e) {
throw new RuntimeException("failed to create fields:" + resultType);
}
}
int i = 0;
for (WrapperParameter param : params) {
AnnotationInstance webparamAnnotation = param.getAnnotation(WEBPARAM_ANNOTATION);
String webParamName = "arg" + i;
String webParamTargetNamespace = namespace;
WebParam.Mode webParamMode = WebParam.Mode.IN;
boolean webParamHeader = false;
//not used
//String webParamPartName = webparamAnnotation.value("partName").asString();
if (webparamAnnotation != null) {
AnnotationValue val = webparamAnnotation.value("name");
if (val != null) {
webParamName = val.asString();
}
val = webparamAnnotation.value("targetNamespace");
if (val != null) {
webParamTargetNamespace = val.asString();
}
val = webparamAnnotation.value("mode");
if (val != null) {
webParamMode = WebParam.Mode.valueOf(val.asEnum());
}
val = webparamAnnotation.value("header");
if (val != null) {
webParamHeader = val.asBoolean();
}
}
if ((webParamMode == WebParam.Mode.OUT && isRequest)
|| (webParamMode == WebParam.Mode.IN && !isRequest))
continue;
createWrapperClassField(getters, setters, classCreator, param.getParameterType().name().toString(), webParamName,
param.getAnnotations());
i++;
}
classCreator.close();
return ctorDescriptor;
}
private void createWrapperClassField(List<MethodDescriptor> getters, List<MethodDescriptor> setters,
ClassCreator classCreator, String identifier, String webParamName, List<AnnotationInstance> paramAnnotations) {
String fieldName = JAXBUtils.nameToIdentifier(webParamName, JAXBUtils.IdentifierType.VARIABLE);
FieldCreator field = classCreator.getFieldCreator(fieldName, identifier)
.setModifiers(Modifier.PRIVATE);
List<DotName> jaxbAnnotationDotNames = JAXB_ANNOTATIONS.stream()
.map(Class::getName)
.map(DotName::createSimple)
.collect(Collectors.toList());
boolean annotationAdded = false;
for (AnnotationInstance ann : paramAnnotations) {
if (jaxbAnnotationDotNames.contains(ann.name())) {
// copy jaxb annotation from param to
field.addAnnotation(AnnotationInstance.create(ann.name(), null, ann.values()));
annotationAdded = true;
}
}
if (!annotationAdded) {
List<AnnotationValue> annotationValues = new ArrayList<>();
annotationValues.add(AnnotationValue.createStringValue("name", webParamName));
//TODO handle a config for factory.isWrapperPartQualified, factory.isWrapperPartNillable, factory.getWrapperPartMinOccurs
// and add annotation value here for it
field.addAnnotation(AnnotationInstance.create(DotName.createSimple(XmlElement.class.getName()),
null, annotationValues));
}
MethodCreator getter = classCreator.getMethodCreator(
JAXBUtils.nameToIdentifier(webParamName, JAXBUtils.IdentifierType.GETTER),
identifier);
getter.setModifiers(Modifier.PUBLIC);
getter.returnValue(getter.readInstanceField(field.getFieldDescriptor(), getter.getThis()));
getters.add(getter.getMethodDescriptor());
MethodCreator setter = classCreator.getMethodCreator(
JAXBUtils.nameToIdentifier(webParamName, JAXBUtils.IdentifierType.SETTER), void.class,
identifier);
setter.setModifiers(Modifier.PUBLIC);
setter.writeInstanceField(field.getFieldDescriptor(), setter.getThis(), setter.getMethodParam(0));
setters.add(setter.getMethodDescriptor());
}
private String getNamespaceFromPackage(String pkg) {
//TODO XRootElement then XmlSchema then derived of package
String[] strs = pkg.split("\\.");
StringBuilder b = new StringBuilder("http://");
for (int i = strs.length - 1; i >= 0; i--) {
b.append(strs[i]);
b.append("/");
}
return b.toString();
}
private static Set<String> classHelpers = new HashSet<>();
static final MethodDescriptor LIST_GET = MethodDescriptor.ofMethod(List.class, "get", Object.class, int.class);
static final MethodDescriptor LIST_ADDALL = MethodDescriptor.ofMethod(List.class, "addAll", Collection.class,
boolean.class);
static final MethodDescriptor ARRAYLIST_CTOR = MethodDescriptor.ofConstructor(ArrayList.class, int.class);
static final MethodDescriptor JAXBELEMENT_GETVALUE = MethodDescriptor.ofMethod(JAXBElement.class, "getValue", Object.class);
static final MethodDescriptor LIST_ADD = MethodDescriptor.ofMethod(List.class, "add", boolean.class, Object.class);
private static final String WRAPPER_HELPER_POSTFIX = "_WrapperTypeHelper";
private static final String WRAPPER_FACTORY_POSTFIX = "Factory";
private String computeSignature(List<MethodDescriptor> getters, List<MethodDescriptor> setters) {
StringBuilder b = new StringBuilder();
b.append(setters.size()).append(':');
for (int x = 0; x < setters.size(); x++) {
if (getters.get(x) == null) {
b.append("null,");
} else {
b.append(getters.get(x).getName()).append('/');
b.append(getters.get(x).getReturnType()).append(',');
}
}
return b.toString();
}
private void createWrapperHelper(ClassOutput classOutput, String pkg, String className,
MethodDescriptor ctorDescriptor, List<MethodDescriptor> getters, List<MethodDescriptor> setters) {
//WrapperClassGenerator
int count = 1;
String newClassName = pkg + "." + className + WRAPPER_HELPER_POSTFIX + count;
while (classHelpers.contains(newClassName)) {
count++;
newClassName = pkg + "." + className + WRAPPER_HELPER_POSTFIX + count;
}
classHelpers.add(newClassName);
ClassCreator classCreator = ClassCreator.builder().classOutput(classOutput)
.className(newClassName)
.build();
Class<?> objectFactoryCls = null;
try {
objectFactoryCls = Class.forName(pkg + ".ObjectFactory");
//TODO object factory creator
// but must be always null for generated class so not sure if we keep that.
//String methodName = "create" + className + setMethod.getName().substring(3);
} catch (ClassNotFoundException e) {
//silently failed
}
FieldCreator factoryField = null;
if (objectFactoryCls != null) {
factoryField = classCreator.getFieldCreator("factory", objectFactoryCls.getName());
}
try (MethodCreator ctor = classCreator.getMethodCreator("<init>", "V")) {
ctor.setModifiers(Modifier.PUBLIC);
ctor.invokeSpecialMethod(MethodDescriptor.ofConstructor(Object.class), ctor.getThis());
if (objectFactoryCls != null && factoryField != null) {
ResultHandle factoryRH = ctor.newInstance(MethodDescriptor.ofConstructor(objectFactoryCls));
ctor.writeInstanceField(factoryField.getFieldDescriptor(), ctor.getThis(), factoryRH);
}
ctor.returnValue(null);
}
try (MethodCreator getSignature = classCreator.getMethodCreator("getSignature", String.class)) {
getSignature.setModifiers(Modifier.PUBLIC);
ResultHandle signatureRH = getSignature.load(computeSignature(getters, setters));
getSignature.returnValue(signatureRH);
}
try (MethodCreator createWrapperObject = classCreator.getMethodCreator("createWrapperObject", Object.class,
List.class)) {
createWrapperObject.setModifiers(Modifier.PUBLIC);
ResultHandle wrapperRH = createWrapperObject.newInstance(ctorDescriptor);
// get list<Object>
ResultHandle listRH = createWrapperObject.getMethodParam(0);
for (int i = 0; i < setters.size(); i++) {
MethodDescriptor setter = setters.get(i);
boolean isList = false;
try {
isList = List.class.isAssignableFrom(Class.forName(setter.getParameterTypes()[0]));
} catch (ClassNotFoundException e) {
// silent fail
}
if (isList) {
MethodDescriptor getter = getters.get(i);
ResultHandle getterListRH = createWrapperObject.invokeVirtualMethod(getter, wrapperRH);
ResultHandle listValRH = createWrapperObject.invokeInterfaceMethod(LIST_GET, listRH,
createWrapperObject.load(i));
createWrapperObject.checkCast(listValRH, List.class);
BranchResult isNullBranch = createWrapperObject.ifNull(getterListRH);
try (BytecodeCreator getterValIsNull = isNullBranch.trueBranch()) {
createWrapperObject.checkCast(listValRH, getter.getReturnType());
createWrapperObject.invokeVirtualMethod(setter, listValRH);
}
try (BytecodeCreator getterValIsNotNull = isNullBranch.falseBranch()) {
createWrapperObject.invokeInterfaceMethod(LIST_ADDALL, getterListRH, listValRH);
}
} else {
boolean isjaxbElement = false;
try {
isjaxbElement = JAXBElement.class.isAssignableFrom(Class.forName(setter.getParameterTypes()[0]));
} catch (ClassNotFoundException e) {
// silent fail
}
ResultHandle listValRH = createWrapperObject.invokeInterfaceMethod(LIST_GET, listRH,
createWrapperObject.load(i));
if (isjaxbElement) {
ResultHandle factoryRH = createWrapperObject.readInstanceField(factoryField.getFieldDescriptor(),
createWrapperObject.getThis());
//TODO invoke virtual objectFactoryClass jaxbmethod
}
createWrapperObject.invokeVirtualMethod(setter, wrapperRH, listValRH);
}
// TODO if setter not created we add by field, but do not think that is needed because I generate everythings
}
createWrapperObject.returnValue(wrapperRH);
}
try (MethodCreator getWrapperParts = classCreator.getMethodCreator("getWrapperParts", List.class, Object.class)) {
getWrapperParts.setModifiers(Modifier.PUBLIC);
ResultHandle arraylistRH = getWrapperParts.newInstance(ARRAYLIST_CTOR, getWrapperParts.load(getters.size()));
ResultHandle objRH = getWrapperParts.getMethodParam(0);
ResultHandle wrapperRH = getWrapperParts.checkCast(objRH, pkg + "." + className);
for (MethodDescriptor getter : getters) {
ResultHandle wrapperValRH = getWrapperParts.invokeVirtualMethod(getter, wrapperRH);
boolean isjaxbElement = false;
try {
isjaxbElement = JAXBElement.class.isAssignableFrom(Class.forName(getter.getReturnType()));
} catch (ClassNotFoundException e) {
// silent fail
}
if (isjaxbElement) {
wrapperValRH = getWrapperParts.ifNull(wrapperValRH).falseBranch().invokeVirtualMethod(JAXBELEMENT_GETVALUE,
wrapperValRH);
}
getWrapperParts.invokeInterfaceMethod(LIST_ADD, arraylistRH, wrapperValRH);
}
getWrapperParts.returnValue(arraylistRH);
}
classCreator.close();
}
private void createWrapperFactory(ClassOutput classOutput, String pkg, String className,
MethodDescriptor ctorDescriptor) {
String factoryClassName = pkg + "." + className + WRAPPER_FACTORY_POSTFIX;
ClassCreator classCreator = ClassCreator.builder().classOutput(classOutput)
.className(factoryClassName)
.build();
try (MethodCreator createWrapper = classCreator.getMethodCreator("create" + className, pkg + "." + className)) {
createWrapper.setModifiers(Modifier.PUBLIC);
ResultHandle[] argsRH = new ResultHandle[ctorDescriptor.getParameterTypes().length];
for (int i = 0; i < ctorDescriptor.getParameterTypes().length; i++) {
argsRH[i] = createWrapper.loadNull();
}
ResultHandle wrapperInstanceRH = createWrapper.newInstance(ctorDescriptor, argsRH);
createWrapper.returnValue(wrapperInstanceRH);
}
}
private void createException(ClassOutput classOutput, String exceptionClassName, DotName name) {
ClassCreator classCreator = ClassCreator.builder().classOutput(classOutput).superClass(Exception.class)
.className(exceptionClassName)
.build();
String FaultClassName = name.toString();
FieldCreator field = classCreator.getFieldCreator("faultInfo", FaultClassName).setModifiers(Modifier.PRIVATE);
//constructor
try (MethodCreator ctor = classCreator.getMethodCreator("<init>", "V", String.class, FaultClassName)) {
ctor.setModifiers(Modifier.PUBLIC);
ctor.invokeSpecialMethod(MethodDescriptor.ofConstructor(Exception.class, String.class), ctor.getThis(),
ctor.getMethodParam(0));
ctor.writeInstanceField(field.getFieldDescriptor(), ctor.getThis(), ctor.getMethodParam(1));
ctor.returnValue(null);
}
try (MethodCreator getter = classCreator.getMethodCreator("getFaultInfo", FaultClassName)) {
getter.setModifiers(Modifier.PUBLIC);
getter.returnValue(getter.readInstanceField(field.getFieldDescriptor(), getter.getThis()));
}
}
@BuildStep
void markBeansAsUnremovable(BuildProducer<UnremovableBeanBuildItem> unremovables) {
unremovables.produce(new UnremovableBeanBuildItem(new Predicate<BeanInfo>() {
@Override
public boolean test(BeanInfo beanInfo) {
String nameWithPackage = beanInfo.getBeanClass().local();
return nameWithPackage.contains(".jaxws_asm") || nameWithPackage.endsWith("ObjectFactory");
}
}));
Set<String> extensibilities = new HashSet<>(Arrays.asList(
"io.quarkus.cxf.AddressTypeExtensibility",
"io.quarkus.cxf.HTTPClientPolicyExtensibility",
"io.quarkus.cxf.HTTPServerPolicyExtensibility",
"io.quarkus.cxf.XMLBindingMessageFormatExtensibility",
"io.quarkus.cxf.XMLFormatBindingExtensibility"));
unremovables
.produce(new UnremovableBeanBuildItem(new UnremovableBeanBuildItem.BeanClassNamesExclusion(extensibilities)));
}
private static final String ANNOTATION_VALUE_INTERCEPTORS = "interceptors";
class WrapperParameter {
private Type parameterType;
private List<AnnotationInstance> annotations;
private String Name;
WrapperParameter(Type parameterType, List<AnnotationInstance> annotations, String name) {
this.parameterType = parameterType;
this.annotations = annotations;
Name = name;
}
public String getName() {
return Name;
}
public List<AnnotationInstance> getAnnotations() {
return annotations;
}
public AnnotationInstance getAnnotation(DotName dotname) {
for (AnnotationInstance ai : annotations) {
if (ai.name().equals(dotname))
return ai;
}
return null;
}
public Type getParameterType() {
return parameterType;
}
}
@BuildStep
public void build(
Capabilities capabilities,
CombinedIndexBuildItem combinedIndexBuildItem,
BuildProducer<FeatureBuildItem> feature,
BuildProducer<ServletBuildItem> servlet,
BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
BuildProducer<FilterBuildItem> filters,
BuildProducer<CXFServletInfoBuildItem> cxfServletInfos,
BuildProducer<ServletInitParamBuildItem> servletInitParameters,
BuildProducer<JaxbFileRootBuildItem> forceJaxb,
BuildProducer<NativeImageProxyDefinitionBuildItem> proxies,
BuildProducer<GeneratedBeanBuildItem> generatedBeans,
BuildProducer<UnremovableBeanBuildItem> unremovableBeans) {
IndexView index = combinedIndexBuildItem.getIndex();
if (!capabilities.isCapabilityPresent(Capabilities.SERVLET)) {
LOGGER.info("CXF running without servlet container.");
LOGGER.info("- Add quarkus-undertow to run CXF within a servlet container");
return;
}
forceJaxb.produce(new JaxbFileRootBuildItem("."));
for (AnnotationInstance annotation : index.getAnnotations(WEBSERVICE_ANNOTATION)) {
if (annotation.target().kind() != AnnotationTarget.Kind.CLASS) {
continue;
}
ClassInfo wsClassInfo = annotation.target().asClass();
reflectiveClass
.produce(new ReflectiveClassBuildItem(true, true, wsClassInfo.name().toString()));
unremovableBeans.produce(new UnremovableBeanBuildItem(
new UnremovableBeanBuildItem.BeanClassNameExclusion(wsClassInfo.name().toString())));
if (!Modifier.isInterface(wsClassInfo.flags())) {
continue;
}
//ClientProxyFactoryBean
proxies.produce(new NativeImageProxyDefinitionBuildItem("java.io.Closeable",
"org.apache.cxf.endpoint.Client", wsClassInfo.name().toString()));
String pkg = wsClassInfo.name().toString();
int idx = pkg.lastIndexOf('.');
if (idx != -1 && idx < pkg.length() - 1) {
pkg = pkg.substring(0, idx);
}
pkg = pkg + ".jaxws_asm";
//TODO config for boolean anonymous = factory.getAnonymousWrapperTypes();
//if (getAnonymousWrapperTypes) pkg += "_an";
AnnotationValue namespaceVal = annotation.value("targetNamespace");
String namespace = namespaceVal != null ? namespaceVal.asString() : getNamespaceFromPackage(pkg);
ClassOutput classOutput = new GeneratedBeanGizmoAdaptor(generatedBeans);
//https://github.com/apache/cxf/blob/master/rt/frontend/jaxws/src/main/java/org/apache/cxf/jaxws/WrapperClassGenerator.java#L234
ClassCreator PackageInfoCreator = ClassCreator.builder().classOutput(classOutput)
.className(pkg + ".package-info")
.build();
List<AnnotationValue> annotationValues = new ArrayList<>();
annotationValues.add(AnnotationValue.createStringValue("namespace", namespace));
annotationValues.add(AnnotationValue.createEnumValue("elementFormDefault",
DotName.createSimple("javax.xml.bind.annotation.XmlNsForm"),
(namespaceVal != null) ? "QUALIFIED" : "UNQUALIFIED"));
PackageInfoCreator.addAnnotation(AnnotationInstance.create(DotName.createSimple(XmlSchema.class.getName()),
null, annotationValues));
// TODO find package annotation with yandex (AnnotationTarget.Kind.package do not exists...
// then forward value and type of XmlJavaTypeAdapter
// PackageInfoCreator.addAnnotation(AnnotationInstance.create(DotName.createSimple(XmlJavaTypeAdapters.class.getName()),
// null, annotationValues));
// PackageInfoCreator.addAnnotation(AnnotationInstance.create(DotName.createSimple(XmlJavaTypeAdapter.class.getName()),
// null, annotationValues));
//TODO get SOAPBINDING_ANNOTATION to get iRPC
List<MethodDescriptor> setters = new ArrayList<>();
List<MethodDescriptor> getters = new ArrayList<>();
for (MethodInfo mi : wsClassInfo.methods()) {
for (Type exceptionType : mi.exceptions()) {
String exceptionName = exceptionType.name().withoutPackagePrefix() + "_Exception";
if (exceptionType.annotation(WEBFAULT_ANNOTATION) != null) {
exceptionName = exceptionType.annotation(WEBFAULT_ANNOTATION).value("name").asString();
}
createException(classOutput, exceptionName, exceptionType.name());
}
String className = StringUtils.capitalize(mi.name());
String operationName = mi.name();
AnnotationInstance webMethodAnnotation = mi.annotation(WEBMETHOD_ANNOTATION);
if (webMethodAnnotation != null) {
AnnotationValue nameVal = webMethodAnnotation.value("operationName");
if (nameVal != null) {
operationName = nameVal.asString();
}
}
AnnotationInstance webResultAnnotation = mi.annotation(WEBRESULT_ANNOTATION);
String resultName = "return";
if (webResultAnnotation != null) {
AnnotationValue resultNameVal = webResultAnnotation.value("name");
if (resultNameVal != null) {
resultName = resultNameVal.asString();
}
}
List<WrapperParameter> wrapperParams = new ArrayList<WrapperParameter>();
for (int i = 0; i < mi.parameters().size(); i++) {
Type paramType = mi.parameters().get(i);
String paramName = mi.parameterName(i);
List<AnnotationInstance> paramAnnotations = new ArrayList<>();
for (AnnotationInstance methodAnnotation : mi.annotations()) {
if (methodAnnotation.target().kind() != AnnotationTarget.Kind.METHOD_PARAMETER)
continue;
MethodParameterInfo paramInfo = methodAnnotation.target().asMethodParameter();
if (paramInfo != null && paramName.equals(paramInfo.name())) {
paramAnnotations.add(methodAnnotation);
}
}
wrapperParams.add(new WrapperParameter(paramType, paramAnnotations, paramName));
}
// todo get REQUEST_WRAPPER_ANNOTATION to avoid creation of wrapper but create helper based on it
MethodDescriptor requestCtor = createWrapper(true, operationName, namespace, resultName,
mi.returnType().toString(), wrapperParams,
classOutput, pkg, className, getters, setters);
createWrapperHelper(classOutput, pkg, className, requestCtor, getters, setters);
createWrapperFactory(classOutput, pkg, className, requestCtor);
getters.clear();
setters.clear();
// todo get RESPONSE_WRAPPER_ANNOTATION to avoid creation of wrapper but create helper based on it
MethodDescriptor responseCtor = createWrapper(false, operationName, namespace, resultName,
mi.returnType().toString(), wrapperParams,
classOutput, pkg, className, getters, setters);
createWrapperHelper(classOutput, pkg, className + RESPONSE_CLASS_POSTFIX, responseCtor, getters, setters);
createWrapperFactory(classOutput, pkg, className + RESPONSE_CLASS_POSTFIX, responseCtor);
getters.clear();
setters.clear();
reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, pkg + "." + className));
reflectiveClass
.produce(new ReflectiveClassBuildItem(true, true, pkg + "." + className + RESPONSE_CLASS_POSTFIX));
reflectiveClass
.produce(new ReflectiveClassBuildItem(true, true, pkg + "." + className + WRAPPER_HELPER_POSTFIX));
reflectiveClass.produce(new ReflectiveClassBuildItem(true, true,
pkg + "." + className + RESPONSE_CLASS_POSTFIX + WRAPPER_HELPER_POSTFIX));
reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, pkg + ".ObjectFactory"));
reflectiveClass
.produce(new ReflectiveClassBuildItem(true, true, pkg + "." + className + WRAPPER_FACTORY_POSTFIX));
reflectiveClass.produce(
new ReflectiveClassBuildItem(true, true,
pkg + "." + className + RESPONSE_CLASS_POSTFIX + WRAPPER_FACTORY_POSTFIX));
}
//MethodDescriptor requestCtor = createWrapper("parameters", namespace,mi.typeParameters(), classOutput, pkg, pkg+"Parameters", getters, setters);
//createWrapperHelper(classOutput, pkg, className, requestCtor, getters, setters);
//getters.clear();
//setters.clear();
}
feature.produce(new FeatureBuildItem(FEATURE_CXF));
//if JAX-WS is installed at the root location we use a filter, otherwise we use a Servlet and take over the whole mapped path
if (cxfConfig.path.equals("/") || cxfConfig.path.isEmpty()) {
filters.produce(FilterBuildItem.builder(JAX_WS_FILTER_NAME, CXFQuarkusServlet.class.getName()).setLoadOnStartup(1)
.addFilterServletNameMapping("default", DispatcherType.REQUEST).setAsyncSupported(true)
.build());
} else {
String mappingPath = getMappingPath(cxfConfig.path);
servlet.produce(ServletBuildItem.builder(JAX_WS_SERVLET_NAME, CXFQuarkusServlet.class.getName())
.setLoadOnStartup(0).addMapping(mappingPath).setAsyncSupported(true).build());
}
reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, CXFQuarkusServlet.class.getName()));
//TODO servletInitParameters
/*
* AbstractHTTPServlet.STATIC_RESOURCES_PARAMETER
* AbstractHTTPServlet.STATIC_WELCOME_FILE_PARAMETER
* AbstractHTTPServlet.STATIC_CACHE_CONTROL
* AbstractHTTPServlet.REDIRECTS_PARAMETER
* AbstractHTTPServlet.REDIRECT_SERVLET_NAME_PARAMETER
* AbstractHTTPServlet.REDIRECT_SERVLET_PATH_PARAMETER
* AbstractHTTPServlet.REDIRECT_ATTRIBUTES_PARAMETER
* AbstractHTTPServlet.REDIRECT_QUERY_CHECK_PARAMETER
* AbstractHTTPServlet.REDIRECT_WITH_INCLUDE_PARAMETER
* AbstractHTTPServlet.USE_X_FORWARDED_HEADERS_PARAMETER
* CXFNonSpringJaxrsServlet.USER_MODEL_PARAM;
* CXFNonSpringJaxrsServlet.SERVICE_ADDRESS_PARAM;
* CXFNonSpringJaxrsServlet.IGNORE_APP_PATH_PARAM;
* CXFNonSpringJaxrsServlet.SERVICE_CLASSES_PARAM;
* CXFNonSpringJaxrsServlet.PROVIDERS_PARAM;
* CXFNonSpringJaxrsServlet.FEATURES_PARAM;
* CXFNonSpringJaxrsServlet.OUT_INTERCEPTORS_PARAM;
* CXFNonSpringJaxrsServlet.OUT_FAULT_INTERCEPTORS_PARAM;
* CXFNonSpringJaxrsServlet.IN_INTERCEPTORS_PARAM;
* CXFNonSpringJaxrsServlet.INVOKER_PARAM;
* CXFNonSpringJaxrsServlet.SERVICE_SCOPE_PARAM;
* CXFNonSpringJaxrsServlet.EXTENSIONS_PARAM;
* CXFNonSpringJaxrsServlet.LANGUAGES_PARAM;
* CXFNonSpringJaxrsServlet.PROPERTIES_PARAM;
* CXFNonSpringJaxrsServlet.SCHEMAS_PARAM;
* CXFNonSpringJaxrsServlet.DOC_LOCATION_PARAM;
* CXFNonSpringJaxrsServlet.STATIC_SUB_RESOLUTION_PARAM;
*/
for (Entry<String, CxfEndpointConfig> webServicesByPath : cxfConfig.endpoints.entrySet()) {
CxfEndpointConfig cxfEndPointConfig = webServicesByPath.getValue();
String relativePath = webServicesByPath.getKey();
String sei = null;
String wsdlPath = null;
if (cxfEndPointConfig.wsdlPath.isPresent()) {
wsdlPath = cxfEndPointConfig.wsdlPath.get();
}
if (cxfEndPointConfig.serviceInterface.isPresent()) {
sei = cxfEndPointConfig.serviceInterface.get();
String wsAbsoluteUrl = cxfEndPointConfig.clientEndpointUrl.isPresent()
? cxfEndPointConfig.clientEndpointUrl.get()
: "http://localhost:8080";
wsAbsoluteUrl = wsAbsoluteUrl.endsWith("/") ? wsAbsoluteUrl.substring(0, wsAbsoluteUrl.length() - 2)
: wsAbsoluteUrl;
wsAbsoluteUrl = relativePath.startsWith("/") ? wsAbsoluteUrl + relativePath
: wsAbsoluteUrl + "/" + relativePath;
generateCxfClientProducer(generatedBeans, sei + "CxfClientProducer", wsAbsoluteUrl, sei, wsdlPath);
}
if (cxfEndPointConfig.implementor.isPresent()) {
DotName webServiceImplementor = DotName.createSimple(cxfEndPointConfig.implementor.get());
ClassInfo wsClass = index.getClassByName(webServiceImplementor);
if (wsClass != null) {
for (Type wsInterfaceType : wsClass.interfaceTypes()) {
//TODO annotation is not seen do not know why so comment it for moment
//if (wsInterfaceType.hasAnnotation(WEBSERVICE_ANNOTATION)) {
sei = wsInterfaceType.name().toString();
//}
}
}
CXFServletInfoBuildItem cxfServletInfo = new CXFServletInfoBuildItem(relativePath,
cxfEndPointConfig.implementor.get(), sei, wsdlPath);
for (AnnotationInstance annotation : wsClass.classAnnotations()) {
switch (annotation.name().toString()) {
case "org.apache.cxf.feature.Features":
HashSet<String> features = new HashSet<>(
Arrays.asList(annotation.value("features").asStringArray()));
cxfServletInfo.getFeatures().addAll(features);
unremovableBeans.produce(new UnremovableBeanBuildItem(
new UnremovableBeanBuildItem.BeanClassNamesExclusion(features)));
reflectiveClass
.produce(
new ReflectiveClassBuildItem(true, true,
annotation.value("features").asStringArray()));
break;
case "org.apache.cxf.interceptor.InInterceptors":
HashSet<String> inInterceptors = new HashSet<>(
Arrays.asList(annotation.value(ANNOTATION_VALUE_INTERCEPTORS).asStringArray()));
cxfServletInfo.getInInterceptors().addAll(inInterceptors);
unremovableBeans.produce(new UnremovableBeanBuildItem(
new UnremovableBeanBuildItem.BeanClassNamesExclusion(inInterceptors)));
reflectiveClass
.produce(new ReflectiveClassBuildItem(true, true,
annotation.value(ANNOTATION_VALUE_INTERCEPTORS).asStringArray()));
break;
case "org.apache.cxf.interceptor.OutInterceptors":
HashSet<String> outInterceptors = new HashSet<>(
Arrays.asList(annotation.value(ANNOTATION_VALUE_INTERCEPTORS).asStringArray()));
cxfServletInfo.getOutInterceptors().addAll(outInterceptors);
unremovableBeans.produce(new UnremovableBeanBuildItem(
new UnremovableBeanBuildItem.BeanClassNamesExclusion(outInterceptors)));
reflectiveClass
.produce(new ReflectiveClassBuildItem(true, true,
annotation.value(ANNOTATION_VALUE_INTERCEPTORS).asStringArray()));
break;
case "org.apache.cxf.interceptor.OutFaultInterceptors":
HashSet<String> outFaultInterceptors = new HashSet<>(
Arrays.asList(annotation.value(ANNOTATION_VALUE_INTERCEPTORS).asStringArray()));
cxfServletInfo.getOutFaultInterceptors().addAll(outFaultInterceptors);
unremovableBeans.produce(new UnremovableBeanBuildItem(
new UnremovableBeanBuildItem.BeanClassNamesExclusion(outFaultInterceptors)));
reflectiveClass
.produce(new ReflectiveClassBuildItem(true, true,
annotation.value(ANNOTATION_VALUE_INTERCEPTORS).asStringArray()));
break;
case "org.apache.cxf.interceptor.InFaultInterceptors":
HashSet<String> inFaultInterceptors = new HashSet<>(
Arrays.asList(annotation.value(ANNOTATION_VALUE_INTERCEPTORS).asStringArray()));
cxfServletInfo.getInFaultInterceptors().addAll(inFaultInterceptors);
unremovableBeans.produce(new UnremovableBeanBuildItem(
new UnremovableBeanBuildItem.BeanClassNamesExclusion(inFaultInterceptors)));
reflectiveClass
.produce(new ReflectiveClassBuildItem(true, true,
annotation.value(ANNOTATION_VALUE_INTERCEPTORS).asStringArray()));
break;
default:
break;
}
}
cxfServletInfos.produce(cxfServletInfo);
}
if (!cxfEndPointConfig.serviceInterface.isPresent() && !cxfEndPointConfig.implementor.isPresent()) {
LOGGER.error("either webservice interface (client) or implementation (server) is mandatory");
}
}
for (ClassInfo subclass : index.getAllKnownSubclasses(ABSTRACT_FEATURE)) {
reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, subclass.name().toString()));
}
for (ClassInfo subclass : index.getAllKnownSubclasses(ABSTRACT_INTERCEPTOR)) {
reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, subclass.name().toString()));
}
for (ClassInfo subclass : index.getAllKnownImplementors(DATABINDING)) {
reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, subclass.name().toString()));
}
}
/**
* Create Producer bean managing webservice client
* <p>
* The generated class will look like
*
* <pre>
* public class FruitWebserviceCxfClientProducer extends AbstractCxfClientProducer {
* @ApplicationScoped
* @Produces
* @Default
* public FruitWebService createService() {
* return (FruitWebService) loadCxfClient ("org.acme.FruitWebService", "http://localhost/fruit",
* "http://myServiceNamespace", "FruitWebServiceName", "http://myPortNamespace", "fruitWebServicePortName");
* }
*
*/
private void generateCxfClientProducer(BuildProducer<GeneratedBeanBuildItem> generatedBean,
String cxfClientProducerClassName, String endpointAddress, String sei, String wsdlUrl) {
ClassOutput classOutput = new GeneratedBeanGizmoAdaptor(generatedBean);
ClassCreator classCreator = ClassCreator.builder().classOutput(classOutput)
.className(cxfClientProducerClassName)
.superClass(AbstractCxfClientProducer.class)
.build();
classCreator.addAnnotation(ApplicationScoped.class);
MethodCreator cxfClientMethodCreator = classCreator.getMethodCreator(
"createService",
sei);
cxfClientMethodCreator.addAnnotation(ApplicationScoped.class);
cxfClientMethodCreator.addAnnotation(Produces.class);
cxfClientMethodCreator.addAnnotation(Default.class);
ResultHandle seiRH = cxfClientMethodCreator.load(sei);
ResultHandle endpointAddressRH = cxfClientMethodCreator.load(endpointAddress);
ResultHandle wsdlUrlRH;
if (wsdlUrl != null) {
wsdlUrlRH = cxfClientMethodCreator.load(wsdlUrl);
} else {
wsdlUrlRH = cxfClientMethodCreator.loadNull();
}
// New configuration
ResultHandle cxfClient = cxfClientMethodCreator.invokeVirtualMethod(
MethodDescriptor.ofMethod(AbstractCxfClientProducer.class,
"loadCxfClient",
Object.class,
String.class,
String.class,
String.class),
cxfClientMethodCreator.getThis(), seiRH, endpointAddressRH, wsdlUrlRH);
ResultHandle cxfClientCasted = cxfClientMethodCreator.checkCast(cxfClient, sei);
cxfClientMethodCreator.returnValue(cxfClientCasted);
classCreator.close();
}
@BuildStep
List<RuntimeInitializedClassBuildItem> runtimeInitializedClasses() {
return Arrays.asList(
new RuntimeInitializedClassBuildItem("io.netty.buffer.PooledByteBufAllocator"),
new RuntimeInitializedClassBuildItem("io.netty.buffer.UnpooledHeapByteBuf"),
new RuntimeInitializedClassBuildItem("io.netty.buffer.UnpooledUnsafeHeapByteBuf"),
new RuntimeInitializedClassBuildItem(
"io.netty.buffer.UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf"),
new RuntimeInitializedClassBuildItem("io.netty.buffer.AbstractReferenceCountedByteBuf"),
new RuntimeInitializedClassBuildItem("org.apache.cxf.staxutils.validation.W3CMultiSchemaFactory"));
}
@BuildStep
void httpProxies(BuildProducer<NativeImageProxyDefinitionBuildItem> proxies) {
proxies.produce(new NativeImageProxyDefinitionBuildItem("org.apache.cxf.common.jaxb.JAXBContextProxy"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("org.apache.cxf.common.jaxb.JAXBBeanInfo"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("org.apache.cxf.common.jaxb.JAXBUtils$BridgeWrapper"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("org.apache.cxf.common.jaxb.JAXBUtils$SchemaCompiler"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("org.apache.cxf.common.util.ASMHelper$ClassWriter"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("javax.wsdl.extensions.soap.SOAPOperation"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("javax.wsdl.extensions.soap.SOAPBody"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("javax.wsdl.extensions.soap.SOAPHeader"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("javax.wsdl.extensions.soap.SOAPAddress"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("javax.wsdl.extensions.soap.SOAPBinding"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("javax.wsdl.extensions.soap.SOAPFault"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("org.apache.cxf.binding.soap.wsdl.extensions.SoapBinding"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("org.apache.cxf.binding.soap.wsdl.extensions.SoapAddress"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("org.apache.cxf.binding.soap.wsdl.extensions.SoapHeader"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("org.apache.cxf.binding.soap.wsdl.extensions.SoapBody"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("org.apache.cxf.binding.soap.wsdl.extensions.SoapFault"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("org.apache.cxf.binding.soap.wsdl.extensions.SoapOperation"));
proxies.produce(new NativeImageProxyDefinitionBuildItem("com.sun.xml.bind.marshaller.CharacterEscapeHandler"));
}
@BuildStep
public void registerReflectionItems(BuildProducer<ReflectiveClassBuildItem> reflectiveItems) {
//TODO load all bus-extensions.txt file and parse it to generate the reflective class.
reflectiveItems.produce(new ReflectiveClassBuildItem(true, true,
"io.quarkus.cxf.QuarkusJAXBBeanInfo",
"org.apache.cxf.common.jaxb.JAXBBeanInfo",
"javax.xml.bind.JAXBContext",
"com.sun.xml.bind.v2.runtime.LeafBeanInfoImpl",
"com.sun.xml.bind.v2.runtime.ArrayBeanInfoImpl",
"com.sun.xml.bind.v2.runtime.ValueListBeanInfoImpl",
"com.sun.xml.bind.v2.runtime.AnyTypeBeanInfo",
"com.sun.xml.bind.v2.runtime.JaxBeanInfo",
"com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl",
"com.sun.xml.bind.v2.runtime.CompositeStructureBeanInfo",
"com.sun.xml.bind.v2.runtime.ElementBeanInfoImpl",
"com.sun.xml.bind.v2.runtime.MarshallerImpl",
"com.sun.xml.bind.v2.runtime.BridgeContextImpl",
"com.sun.xml.bind.v2.runtime.JAXBContextImpl"));
reflectiveItems.produce(new ReflectiveClassBuildItem(false, false,
//manually added
"org.apache.cxf.wsdl.interceptors.BareInInterceptor",
"com.sun.msv.reader.GrammarReaderController",
"org.apache.cxf.binding.soap.interceptor.RPCInInterceptor",
"org.apache.cxf.wsdl.interceptors.DocLiteralInInterceptor",
"StaxSchemaValidationInInterceptor",
"org.apache.cxf.binding.soap.interceptor.SoapHeaderInterceptor",
"org.w3c.dom.Node",
"org.apache.cxf.binding.soap.model.SoapHeaderInfo",
"javax.xml.stream.XMLStreamReader",
"java.util.List",
"org.apache.cxf.service.model.BindingOperationInfo",
"org.apache.cxf.binding.soap.interceptor.CheckFaultInterceptor",
"org.apache.cxf.interceptor.ClientFaultConverter",
"org.apache.cxf.binding.soap.interceptor.EndpointSelectionInterceptor",
"java.io.InputStream",
"org.apache.cxf.service.model.MessageInfo",
"org.apache.cxf.binding.soap.interceptor.MustUnderstandInterceptor",
"org.apache.cxf.interceptor.OneWayProcessorInterceptor",
"java.io.OutputStream",
"org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor",
"org.apache.cxf.binding.soap.interceptor.RPCOutInterceptor",
"org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor",
"org.apache.cxf.binding.soap.interceptor.Soap11FaultOutInterceptor",
"org.apache.cxf.binding.soap.interceptor.Soap12FaultInInterceptor",
"org.apache.cxf.binding.soap.interceptor.Soap12FaultOutInterceptor",
"org.apache.cxf.binding.soap.interceptor.SoapActionInInterceptor",
"org.apache.cxf.binding.soap.wsdl.extensions.SoapBody",
"javax.wsdl.extensions.soap.SOAPBody",
"org.apache.cxf.binding.soap.model.SoapOperationInfo",
"org.apache.cxf.binding.soap.interceptor.SoapOutInterceptor$SoapOutEndingInterceptor",
"org.apache.cxf.binding.soap.interceptor.SoapOutInterceptor",
"org.apache.cxf.binding.soap.interceptor.StartBodyInterceptor",
"java.net.URI",
"java.lang.Exception",
"org.apache.cxf.staxutils.W3CDOMStreamWriter",
"javax.xml.stream.XMLStreamReader",
"javax.xml.stream.XMLStreamWriter",
"org.apache.cxf.common.jaxb.SchemaCollectionContextProxy",
"com.ctc.wstx.sax.WstxSAXParserFactory",
"com.ibm.wsdl.BindingFaultImpl",
"com.ibm.wsdl.BindingImpl",
"com.ibm.wsdl.BindingInputImpl",
"com.ibm.wsdl.BindingOperationImpl",
"com.ibm.wsdl.BindingOutputImpl",
"com.ibm.wsdl.extensions.soap.SOAPAddressImpl",
"com.ibm.wsdl.extensions.soap.SOAPBindingImpl",
"com.ibm.wsdl.extensions.soap.SOAPBodyImpl",
"com.ibm.wsdl.extensions.soap.SOAPFaultImpl",
"com.ibm.wsdl.extensions.soap.SOAPHeaderImpl",
"com.ibm.wsdl.extensions.soap.SOAPOperationImpl",
"com.ibm.wsdl.factory.WSDLFactoryImpl",
"com.ibm.wsdl.FaultImpl",
"com.ibm.wsdl.InputImpl",
"com.ibm.wsdl.MessageImpl",
"com.ibm.wsdl.OperationImpl",
"com.ibm.wsdl.OutputImpl",
"com.ibm.wsdl.PartImpl",
"com.ibm.wsdl.PortImpl",
"com.ibm.wsdl.PortTypeImpl",
"com.ibm.wsdl.ServiceImpl",
"com.ibm.wsdl.TypesImpl",
"com.oracle.xmlns.webservices.jaxws_databinding.ObjectFactory",
"com.sun.codemodel.internal.writer.FileCodeWriter",
"com.sun.codemodel.writer.FileCodeWriter",
"com.sun.org.apache.xerces.internal.utils.XMLSecurityManager",
"com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager",
"com.sun.tools.internal.xjc.api.XJC",
"com.sun.tools.xjc.api.XJC",
"com.sun.xml.bind.api.JAXBRIContext",
"com.sun.xml.bind.api.TypeReference",
"com.sun.xml.bind.DatatypeConverterImpl",
"com.sun.xml.bind.marshaller.CharacterEscapeHandler",
"com.sun.xml.bind.marshaller.MinimumEscapeHandler",
"com.sun.xml.bind.v2.ContextFactory",
"com.sun.xml.internal.bind.api.JAXBRIContext",
"com.sun.xml.internal.bind.api.TypeReference",
"com.sun.xml.internal.bind.DatatypeConverterImpl",
"com.sun.xml.internal.bind.marshaller.MinimumEscapeHandler",
"com.sun.xml.internal.bind.v2.ContextFactory",
"com.sun.xml.ws.runtime.config.ObjectFactory",
"ibm.wsdl.DefinitionImpl",
"io.quarkus.cxf.AddressTypeExtensibility",
"io.quarkus.cxf.CXFException",
"io.quarkus.cxf.HTTPClientPolicyExtensibility",
"io.quarkus.cxf.HTTPServerPolicyExtensibility",
"io.quarkus.cxf.XMLBindingMessageFormatExtensibility",
"io.quarkus.cxf.XMLFormatBindingExtensibility",
"io.swagger.jaxrs.DefaultParameterExtension",
"io.undertow.server.HttpServerExchange",
"io.undertow.UndertowOptions",
"java.lang.invoke.MethodHandles",
"java.rmi.RemoteException",
"java.rmi.ServerException",
"java.security.acl.Group",
"javax.enterprise.inject.spi.CDI",
"javax.jws.Oneway",
"javax.jws.WebMethod",
"javax.jws.WebParam",
"javax.jws.WebResult",
"javax.jws.WebService",
"javax.security.auth.login.Configuration",
"javax.servlet.WriteListener",
"javax.wsdl.Binding",
"javax.wsdl.Binding",
"javax.wsdl.BindingFault",
"javax.wsdl.BindingFault",
"javax.wsdl.BindingInput",
"javax.wsdl.BindingOperation",
"javax.wsdl.BindingOperation",
"javax.wsdl.BindingOutput",
"javax.wsdl.Definition",
"javax.wsdl.Fault",
"javax.wsdl.Import",
"javax.wsdl.Input",
"javax.wsdl.Message",
"javax.wsdl.Operation",
"javax.wsdl.Output",
"javax.wsdl.Part",
"javax.wsdl.Port",
"javax.wsdl.Port",
"javax.wsdl.PortType",
"javax.wsdl.Service",
"javax.wsdl.Types",
"javax.xml.bind.annotation.XmlSeeAlso",
"javax.xml.bind.JAXBElement",
"javax.xml.namespace.QName",
"javax.xml.soap.SOAPMessage",
"javax.xml.transform.stax.StAXSource",
"javax.xml.ws.Action",
"javax.xml.ws.BindingType",
"javax.xml.ws.Provider",
"javax.xml.ws.RespectBinding",
"javax.xml.ws.Service",
"javax.xml.ws.ServiceMode",
"javax.xml.ws.soap.Addressing",
"javax.xml.ws.soap.MTOM",
"javax.xml.ws.soap.SOAPBinding",
"javax.xml.ws.WebFault",
"javax.xml.ws.WebServiceProvider",
"net.sf.cglib.proxy.Enhancer",
"net.sf.cglib.proxy.MethodInterceptor",
"net.sf.cglib.proxy.MethodProxy",
"net.sf.ehcache.CacheManager",
"org.apache.commons.logging.LogFactory",
"org.apache.cxf.binding.soap.SoapBinding",
"org.apache.cxf.binding.soap.SoapFault",
"org.apache.cxf.binding.soap.SoapHeader",
"org.apache.cxf.binding.soap.SoapMessage",
"org.apache.cxf.binding.xml.XMLFault",
"org.apache.cxf.bindings.xformat.ObjectFactory",
"org.apache.cxf.bindings.xformat.XMLBindingMessageFormat",
"org.apache.cxf.bindings.xformat.XMLFormatBinding",
"org.apache.cxf.bus.CXFBusFactory",
"org.apache.cxf.bus.managers.BindingFactoryManagerImpl",
"org.apache.cxf.common.jaxb.NamespaceMapper",
"org.apache.cxf.common.jaxb.SchemaCollectionContextProxy",
"org.apache.cxf.interceptor.Fault",
"org.apache.cxf.jaxb.DatatypeFactory",
"org.apache.cxf.jaxb.JAXBDataBinding",
"org.apache.cxf.jaxrs.utils.JAXRSUtils",
"org.apache.cxf.jaxws.binding.soap.SOAPBindingImpl",
"org.apache.cxf.metrics.codahale.CodahaleMetricsProvider",
"org.apache.cxf.message.Exchange",
"org.apache.cxf.message.ExchangeImpl",
"org.apache.cxf.message.StringMapImpl",
"org.apache.cxf.message.StringMap",
"org.apache.cxf.tools.fortest.cxf523.Database",
"org.apache.cxf.tools.fortest.cxf523.DBServiceFault",
"org.apache.cxf.tools.fortest.withannotation.doc.HelloWrapped",
"org.apache.cxf.transports.http.configuration.HTTPClientPolicy",
"org.apache.cxf.transports.http.configuration.HTTPServerPolicy",
"org.apache.cxf.transports.http.configuration.ObjectFactory",
"org.apache.cxf.ws.addressing.wsdl.AttributedQNameType",
"org.apache.cxf.ws.addressing.wsdl.AttributedQNameType",
"org.apache.cxf.ws.addressing.wsdl.ObjectFactory",
"org.apache.cxf.ws.addressing.wsdl.ServiceNameType",
"org.apache.cxf.ws.addressing.wsdl.ServiceNameType",
"org.apache.cxf.wsdl.http.AddressType",
"org.apache.cxf.wsdl.http.ObjectFactory",
"org.apache.hello_world.Greeter",
"org.apache.hello_world_soap_http.types.StringStruct",
"org.apache.karaf.jaas.boot.principal.Group",
"org.apache.xerces.impl.Version",
"org.apache.yoko.orb.OB.BootManager",
"org.apache.yoko.orb.OB.BootManagerHelper",
"org.codehaus.stax2.XMLStreamReader2",
"org.eclipse.jetty.jaas.spi.PropertyFileLoginModule",
"org.eclipse.jetty.jmx.MBeanContainer",
"org.eclipse.jetty.plus.jaas.spi.PropertyFileLoginModule",
"org.hsqldb.jdbcDriver",
"org.jdom.Document",
"org.jdom.Element",
"org.osgi.framework.Bundle",
"org.osgi.framework.BundleContext",
"org.osgi.framework.FrameworkUtil",
"org.slf4j.impl.StaticLoggerBinder",
"org.slf4j.LoggerFactory",
"org.springframework.aop.framework.Advised",
"org.springframework.aop.support.AopUtils",
"org.springframework.core.io.support.PathMatchingResourcePatternResolver",
"org.springframework.core.type.classreading.CachingMetadataReaderFactory",
"org.springframework.osgi.io.OsgiBundleResourcePatternResolver",
"org.springframework.osgi.util.BundleDelegatingClassLoader",
// org.apache.cxf.extension.BusExtension interface without duplicate
"org.apache.cxf.configuration.spring.ConfigurerImpl",
// policy bus-extensions.txt
"org.apache.cxf.ws.policy.PolicyEngineImpl",
"org.apache.cxf.ws.policy.PolicyEngine",
"org.apache.cxf.policy.PolicyDataEngine",
"org.apache.cxf.ws.policy.PolicyDataEngineImpl",
"org.apache.cxf.ws.policy.AssertionBuilderRegistry",
"org.apache.cxf.ws.policy.AssertionBuilderRegistryImpl",
"org.apache.cxf.ws.policy.PolicyInterceptorProviderRegistry",
"org.apache.cxf.ws.policy.PolicyInterceptorProviderRegistryImpl",
"org.apache.cxf.ws.policy.PolicyBuilder",
"org.apache.cxf.ws.policy.PolicyBuilderImpl",
"org.apache.cxf.ws.policy.PolicyAnnotationListener",
"org.apache.cxf.ws.policy.attachment.ServiceModelPolicyProvider",
"org.apache.cxf.ws.policy.attachment.external.DomainExpressionBuilderRegistry",
"org.apache.cxf.ws.policy.attachment.external.EndpointReferenceDomainExpressionBuilder",
"org.apache.cxf.ws.policy.attachment.external.URIDomainExpressionBuilder",
"org.apache.cxf.ws.policy.attachment.wsdl11.Wsdl11AttachmentPolicyProvider",
"org.apache.cxf.ws.policy.mtom.MTOMAssertionBuilder",
"org.apache.cxf.ws.policy.mtom.MTOMPolicyInterceptorProvider",
//transport undertow bus-extensions.txt
"org.apache.cxf.transport.http_undertow.UndertowDestinationFactory",
"org.apache.cxf.transport.http_undertow.UndertowHTTPServerEngineFactory",
//transport http bus-extensions.txt
"org.apache.cxf.transport.http.HTTPTransportFactory",
"org.apache.cxf.transport.http.HTTPWSDLExtensionLoader",
"org.apache.cxf.transport.http.policy.HTTPClientAssertionBuilder",
"org.apache.cxf.transport.http.policy.HTTPServerAssertionBuilder",
"org.apache.cxf.transport.http.policy.NoOpPolicyInterceptorProvider",
//jaxws bus-extensions.txt
"org.apache.cxf.jaxws.context.WebServiceContextResourceResolver",
//management bus-extensions.txt
"org.apache.cxf.management.InstrumentationManager",
"org.apache.cxf.management.jmx.InstrumentationManagerImpl",
//rt reliable message bus-extensions.txt
"org.apache.cxf.ws.rm.RMManager",
//mex bus-extensions.txt
"org.apache.cxf.ws.mex.MEXServerListener",
//sse bus-extensions.txt
"org.apache.cxf.transport.sse.SseProvidersExtension",
//transport websocket (over undertow) bus-extensions.txt
"org.apache.cxf.transport.websocket.WebSocketTransportFactory",
//rt wsdl bus-extensions.txt
"org.apache.cxf.wsdl.WSDLManager",
"org.apache.cxf.wsdl11.WSDLManagerImpl",
//xml binding bus-extensions.txt
"org.apache.cxf.binding.xml.XMLBindingFactory",
"org.apache.cxf.binding.xml.wsdl11.XMLWSDLExtensionLoader",
//rt soap binding bus-extensions.txt
"org.apache.cxf.binding.soap.SoapTransportFactory",
"org.apache.cxf.binding.soap.SoapBindingFactory",
// core bus-extensions.txt
"org.apache.cxf.bus.managers.PhaseManagerImpl",
"org.apache.cxf.phase.PhaseManager",
"org.apache.cxf.bus.managers.WorkQueueManagerImpl",
"org.apache.cxf.workqueue.WorkQueueManager",
"org.apache.cxf.bus.managers.CXFBusLifeCycleManager",
"org.apache.cxf.buslifecycle.BusLifeCycleManager",
"org.apache.cxf.bus.managers.ServerRegistryImpl",
"org.apache.cxf.endpoint.ServerRegistry",
"org.apache.cxf.bus.managers.EndpointResolverRegistryImpl",
"org.apache.cxf.endpoint.EndpointResolverRegistry",
"org.apache.cxf.bus.managers.HeaderManagerImpl",
"org.apache.cxf.headers.HeaderManager",
"org.apache.cxf.service.factory.FactoryBeanListenerManager",
"org.apache.cxf.bus.managers.ServerLifeCycleManagerImpl",
"org.apache.cxf.endpoint.ServerLifeCycleManager",
"org.apache.cxf.bus.managers.ClientLifeCycleManagerImpl",
"org.apache.cxf.endpoint.ClientLifeCycleManager",
"org.apache.cxf.bus.resource.ResourceManagerImpl",
"org.apache.cxf.resource.ResourceManager",
"org.apache.cxf.catalog.OASISCatalogManager",
"org.apache.cxf.catalog.OASISCatalogManager"));
}
@BuildStep
NativeImageResourceBuildItem nativeImageResourceBuildItem() {
return new NativeImageResourceBuildItem("com/sun/xml/fastinfoset/resources/ResourceBundle.properties",
"META-INF/cxf/bus-extensions.txt",
"META-INF/cxf/cxf.xml",
"META-INF/cxf/org.apache.cxf.bus.factory",
"META-INF/services/org.apache.cxf.bus.factory",
"META-INF/blueprint.handlers",
"META-INF/spring.handlers",
"META-INF/spring.schemas",
"OSGI-INF/metatype/workqueue.xml",
"schemas/core.xsd",
"schemas/blueprint/core.xsd",
"schemas/wsdl/XMLSchema.xsd",
"schemas/wsdl/addressing.xjb",
"schemas/wsdl/addressing.xsd",
"schemas/wsdl/addressing200403.xjb",
"schemas/wsdl/addressing200403.xsd",
"schemas/wsdl/http.xjb",
"schemas/wsdl/http.xsd",
"schemas/wsdl/mime-binding.xsd",
"schemas/wsdl/soap-binding.xsd",
"schemas/wsdl/soap-encoding.xsd",
"schemas/wsdl/soap12-binding.xsd",
"schemas/wsdl/swaref.xsd",
"schemas/wsdl/ws-addr-wsdl.xjb",
"schemas/wsdl/ws-addr-wsdl.xsd",
"schemas/wsdl/ws-addr.xsd",
"schemas/wsdl/wsdl.xjb",
"schemas/wsdl/wsdl.xsd",
"schemas/wsdl/wsrm.xsd",
"schemas/wsdl/xmime.xsd",
"schemas/wsdl/xml.xsd",
"schemas/configuratio/cxf-beans.xsd",
"schemas/configuration/extension.xsd",
"schemas/configuration/parameterized-types.xsd",
"schemas/configuration/security.xjb",
"schemas/configuration/security.xsd");
}
private String getMappingPath(String path) {
String mappingPath;
if (path.endsWith("/")) {
mappingPath = path + "*";
} else {
mappingPath = path + "/*";
}
return mappingPath;
}
@BuildStep
public void createBeans(
BuildProducer<UnremovableBeanBuildItem> unremovableBeans,
BuildProducer<GeneratedBeanBuildItem> generatedBeans,
BuildProducer<ReflectiveClassBuildItem> reflectiveItems) {
for (Entry<String, CxfEndpointConfig> webServicesByPath : cxfConfig.endpoints.entrySet()) {
if (webServicesByPath.getValue().implementor.isPresent()) {
String webServiceName = webServicesByPath.getValue().implementor.get();
String producerClassName = webServiceName + "Producer";
ClassOutput classOutput = new GeneratedBeanGizmoAdaptor(generatedBeans);
createProducer(producerClassName, classOutput, webServiceName);
unremovableBeans.produce(new UnremovableBeanBuildItem(
new UnremovableBeanBuildItem.BeanClassNameExclusion(producerClassName)));
reflectiveItems.produce(new ReflectiveClassBuildItem(true, true, producerClassName));
}
}
}
private void createProducer(String producerClassName,
ClassOutput classOutput,
String webServiceName) {
ClassCreator classCreator = ClassCreator.builder().classOutput(classOutput)
.className(producerClassName)
.build();
classCreator.addAnnotation(ApplicationScoped.class);
MethodCreator namedWebServiceMethodCreator = classCreator.getMethodCreator(
"createWebService_" + HashUtil.sha1(webServiceName),
webServiceName);
namedWebServiceMethodCreator.addAnnotation(ApplicationScoped.class);
namedWebServiceMethodCreator.addAnnotation(Unremovable.class);
namedWebServiceMethodCreator.addAnnotation(Produces.class);
namedWebServiceMethodCreator.addAnnotation(AnnotationInstance.create(DotNames.NAMED, null,
new AnnotationValue[] { AnnotationValue.createStringValue("value", webServiceName) }));
ResultHandle namedWebService = namedWebServiceMethodCreator
.newInstance(MethodDescriptor.ofConstructor(webServiceName));
namedWebServiceMethodCreator.returnValue(namedWebService);
classCreator.close();
}
}
|
public class Ship {
public Ship(String name, String location, String direction) {
int boatLenght;
if (name == "CA"){
boatLenght = 5;
} else if (name == "BS") {
boatLenght = 4;
} else if (name == "CR") {
boatLenght = 3;
} else if (name == "SU") {
boatLenght = 2;
} else if (name == "DE") {
boatLenght = 1;
} else {
}
}
public void isOnSquare(Coordonate){
}
public void Sunk() {
}
public void shotAt() {
}
}
|
package com.dynamic.shop.domainmodels;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "item_section")
public class ItemSection {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
long section_Id;
@Column(name="section_name")
String section_name;
String section_url;
public ItemSection() {}
public ItemSection(String section_name, String section_url) {
super();
this.section_name = section_name;
this.section_url = section_url;
}
public long getSection_Id() {
return section_Id;
}
public void setSection_Id(long section_Id) {
this.section_Id = section_Id;
}
public String getSection_name() {
return section_name;
}
public void setSection_name(String section_name) {
this.section_name = section_name;
}
public String getSection_url() {
return section_url;
}
public void setSection_url(String section_url) {
this.section_url = section_url;
}
}
|
package com.triview.demo.user;
import com.triview.demo.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.Collection;
@RestController
@Validated
@RequestMapping("/api/users")
public class UserController {
private static final String ADMIN_AUTHORITY = "ADMIN";
private final UserRepository repository;
UserController(UserRepository repository) {
this.repository = repository;
}
/**
* Find a user by their email address. Admin users are allowed to find anyone, while regular users may only
* lookup themselves.
*
* @param email search value
* @param authentication OAuth2Authentication authentication object
* @return the found user
* @throws UserNotFoundException if no user with the given email address exists.
*/
@GetMapping("/findByEmail")
@PreAuthorize("hasAuthority('ADMIN') || (authentication.principal == #email)")
User findByEmail(@RequestParam String email, OAuth2Authentication authentication) {
return repository.findByEmail(email).orElseThrow(() -> new UserNotFoundException("email=" + email));
}
@GetMapping("/{id}")
@PostAuthorize("hasAuthority('ADMIN') || (returnObject != null && returnObject.email == authentication.principal)")
User one(@PathVariable Long id) {
return repository.findById(id).orElseThrow(() -> new UserNotFoundException("id=" + id.toString()));
}
@PostMapping
@PreAuthorize("hasAuthority('ADMIN')")
User create(@Valid @RequestBody User user) {
return repository.save(user);
}
@DeleteMapping("/{id}")
@PreAuthorize("hasAuthority('ADMIN')")
void delete(@PathVariable Long id) {
if (repository.existsById(id)) {
repository.deleteById(id);
} else {
throw new UserNotFoundException("id=" + id.toString());
}
}
@GetMapping
Page<User> allUsers(@PageableDefault(size = Integer.MAX_VALUE) Pageable pageable,
OAuth2Authentication authentication) {
if (!isAdmin(authentication)) {
String auth = (String) authentication.getPrincipal();
return repository.findAllByEmail(auth, pageable);
} else {
return repository.findAll(pageable);
}
}
private boolean isAdmin(OAuth2Authentication authentication) {
Collection<GrantedAuthority> authorities = authentication.getAuthorities();
return authorities.stream().anyMatch(ga -> ga.getAuthority().equals(ADMIN_AUTHORITY));
}
}
|
package cn.jiucaituan.common;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import org.dom4j.Document;
import org.dom4j.io.*;
public class XmlExecutor {
public XmlExecutor() {
}
public Document buildDoc(String xml, String charSet) throws Exception {
InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
SAXReader reader = new SAXReader();
InputStreamReader strInStream = new InputStreamReader(inputStream,
charSet);
Document document = reader.read(strInStream);
inputStream.close();
reader = null;
inputStream = null;
return document;
}
public String setCharSet(Document document, String charSet)
throws Exception {
OutputFormat format = OutputFormat.createPrettyPrint();
//
format.setEncoding(charSet);
ByteArrayOutputStream fos = new ByteArrayOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos,
charSet));
XMLWriter writer = new XMLWriter(bw, format);
writer.write(document);
bw.close();
String restr = fos.toString();
fos.close();
return restr;
}
}
|
/* Copyright 2015 Esri
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.esri.arcgis.android.samples.PopupUICustomization;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.esri.android.map.popup.ArcGISEditAttributesAdapter;
import com.esri.android.map.popup.Popup;
import java.util.Calendar;
/*
* Customized Attribute adapter to display graphic's attributes in edit mode
*
*/
public class MyEditAttributesAdapter extends ArcGISEditAttributesAdapter {
private Drawable mAlertIcon;
public MyEditAttributesAdapter(Context context, Popup popup) {
super(context, popup);
// Change the layouts based on the type of the field.
// Code value domain field
setCodedValueLayoutResourceId(R.layout.popup_attribute_spinner,
R.id.label_textView, R.id.value_spinner);
// Range domain field
setRangeValueLayoutResourceId(R.layout.popup_attribute_spinner,
R.id.label_textView, R.id.value_spinner);
// Date field
setDateLayoutResourceId(R.layout.popup_attribute_date,
R.id.label_textView, R.id.value_button);
// Text field
setEditTextLayoutResourceId(R.layout.popup_attribute_edit_text,
R.id.label_textView, R.id.value_editText);
// Date picker used in a date field
setDatePickerLayoutResourceId(R.layout.popup_attribute_date_picker);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final View layout = super.getView(position, convertView, parent);
if (layout != null) {
final AttributeInfo attributeInfo = getAttributeInfo(position);
FIELD_TYPE fieldType = determineFieldType(attributeInfo);
// set onclick listener to handle the click event for the "use current" button.
if (fieldType == FIELD_TYPE.DATE) {
Button nowButton = (Button) layout.findViewById(R.id.now_button);
nowButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
Button dateButton = (Button) layout.findViewById(R.id.value_button);
// set the value of the date field to the current time.
try {
long now = calendar.getTimeInMillis();
mAttributes.put(attributeInfo.fieldInfo.getFieldName(), Long.valueOf(now));
dateButton.setText(mValueFormat.formatValue(mFeatureType, Long.valueOf(now),
mPopup.getPopupInfo().getFieldInfo(attributeInfo.field.getName())));
// call the popup modified listener to allow users to add their logic when a field is changed.
if (mPopup.getPopupListener() != null)
mPopup.getPopupListener().onPopupModified();
} catch (NumberFormatException e) {
// don't set the value, leave blank
}
}
});
}
}
return layout;
}
@Override
protected void setRequiredState(View view, boolean required) {
View actualView = view;
if (view instanceof Spinner) {
Spinner spinner = (Spinner) view;
actualView = spinner.getSelectedView();
}
// Change the icon shown in the alert if a field is required.
if (actualView instanceof TextView) {
TextView editText = (TextView) actualView;
if (required && (Boolean.TRUE.equals(editText.getTag()))) {
if (mAlertIcon == null) {
mAlertIcon = mContext.getResources().getDrawable(R.drawable.required);
mAlertIcon.setColorFilter(Color.argb(255, 180, 180, 0), android.graphics.PorterDuff.Mode.SRC_IN);
int bound = (int) editText.getTextSize() + editText.getCompoundDrawablePadding();
mAlertIcon.setBounds(0, 0, bound, bound);
}
editText.setCompoundDrawables(null, null, mAlertIcon, null);
} else {
editText.setCompoundDrawables(null, null, null, null);
}
}
}
}
|
package cyfixusBot.minigames.lotto;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.font.TextAttribute;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.Timer;
public class TicketFrame extends JFrame implements ActionListener{
private String sender;
private Map attributes;
private TicketPanel ticketPanel;
private int time;
public TicketFrame(){
super("Ticket");
}
public TicketFrame(String sender){
super("Ticket");
setFocusableWindowState(false);
this.sender = sender;
ticketPanel = new TicketPanel(sender);
add(ticketPanel);
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(2600, 400);
setAlwaysOnTop(true);
Timer timer = new Timer(1000, this);
timer.setInitialDelay(0);
timer.start();
}
public void actionPerformed(ActionEvent arg0) {
time++;
if(time % 3 == 0){
setVisible(false);
dispose();
}
}
}
|
package com.esum.web.apps.notifymgr.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.esum.appetizer.config.Configurer;
import com.esum.appetizer.controller.AbstractController;
import com.esum.appetizer.util.PageUtil;
import com.esum.web.apps.notifymgr.service.NotifyMgrService;
import com.esum.web.apps.notifymgr.vo.ErrorCategory;
import com.esum.web.apps.notifymgr.vo.NotifyInfo;
import com.esum.web.apps.notifymgr.vo.NotifyMgr;
import com.esum.web.apps.notifymgr.vo.NotifyModuleInfo;
import com.esum.web.apps.notifymgr.vo.NotifyTemplate;
import com.esum.web.apps.notifymgr.vo.UserInfo;
@Controller
public class NotifyMgrController extends AbstractController{
@Autowired
private NotifyMgrService notifyMgrService;
//수신자 그룹 리스트
@RequestMapping("/service/notifyMgr/recvGroupList")
public String recvGroupList(Model model
,String currentPage
,NotifyInfo notifyInfo
,String pageType
){
if(currentPage == null) currentPage = "1";
int totalCount = notifyMgrService.totalCountNotifyInfo(notifyInfo);
PageUtil pageUtil = new PageUtil(Integer.parseInt(currentPage), Configurer.getPropertyInt("Common.LIST.COUNT_PER_PAGE", 10), 10, totalCount);
List<NotifyInfo> list = notifyMgrService.selectListNotifyInfo(notifyInfo, pageUtil);
model.addAttribute("list",list);
model.addAttribute("notifyInfo",notifyInfo);
model.addAttribute("pageUtil",pageUtil);
if(pageType != null) return "/service/notifyMgr/supervise/recvGroupListPopup";
else return "/service/notifyMgr/recvGroup/recvGroupList";
}
//수신자 그룹 등록
@RequestMapping("/service/notifyMgr/recvGroupAdd")
public String recvGroupAdd(){
return "/service/notifyMgr/recvGroup/recvGroupAdd";
}
//수신자 그룹 등록 - 사용자 조회
@RequestMapping("/service/notifyMgr/recvGroupAdd/searchUserPopup")
public String searchUserPopup(Model model
,String currentPage
,UserInfo userInfo
){
if(currentPage == null) currentPage = "1";
int totalCount = notifyMgrService.totalCountUserInfo(userInfo);
PageUtil pageUtil = new PageUtil(Integer.parseInt(currentPage), 5, 5, totalCount);
List<UserInfo> list = notifyMgrService.selectListUserInfo(pageUtil, userInfo);
model.addAttribute("list", list);
model.addAttribute("userInfo", userInfo);
model.addAttribute("pageUtil", pageUtil);
return "/service/notifyMgr/recvGroup/searchUserPopup";
}
//수신자 그룹 상세보기
@RequestMapping("/service/notifyMgr/recvGroupInfo")
public String recvGroupInfo(Model model,
NotifyInfo notifyInfo
){
NotifyInfo _notifyInfo = notifyMgrService.selectNotifyInfo(notifyInfo);
model.addAttribute("notifyInfo", _notifyInfo);
return "/service/notifyMgr/recvGroup/recvGroupInfo";
}
//통보 관리 리스트
@RequestMapping("/service/notifyMgr/notifyMgrList")
public String notifyMgrList(Model model
,String currentPage
,NotifyMgr notifyMgr
){
if(currentPage == null) currentPage = "1";
int totalCount = notifyMgrService.totalCountNotifyMgr(notifyMgr);
PageUtil pageUtil = new PageUtil(Integer.parseInt(currentPage), Configurer.getPropertyInt("Common.LIST.COUNT_PER_PAGE", 10), 10, totalCount);
List<NotifyMgr> list = notifyMgrService.selectListNotifyMgr(notifyMgr,pageUtil);
model.addAttribute("list", list);
model.addAttribute("notifyMgr", notifyMgr);
model.addAttribute("pageUtil", pageUtil);
return "/service/notifyMgr/supervise/notifyMgrList";
}
//통보 관리 등록
@RequestMapping("/service/notifyMgr/notifyMgrAdd")
public String notifyMgrAdd(){
return "/service/notifyMgr/supervise/notifyMgrAdd";
}
//팝업 - 에러패턴 조회
@RequestMapping("/service/notifyMgr/errorPatternListPopup")
public String errorPatternList(Model model
,String currentPage
,ErrorCategory errorCategory){
if(currentPage == null){
currentPage = "1";
errorCategory.setLangType("ko");
}
int totalCount = notifyMgrService.totalCountErrorCategory(errorCategory);
PageUtil pageUtil = new PageUtil(Integer.parseInt(currentPage), Configurer.getPropertyInt("Common.LIST.COUNT_PER_PAGE", 10), 10, totalCount);
List<ErrorCategory> list = notifyMgrService.selectListErrorCategory(errorCategory,pageUtil);
model.addAttribute("list", list);
model.addAttribute("errorCategory", errorCategory);
model.addAttribute("pageUtil", pageUtil);
return "/service/notifyMgr/supervise/errorPatternListPopup";
}
//팝업 - 메시지 포멧 ID 조회
@RequestMapping("/service/notifyMgr/templateIdListPopup")
public String errorPatternList(Model model
,String currentPage){
if(currentPage == null)currentPage = "1";
int totalCount = notifyMgrService.totalCountNotifyTemplate();
PageUtil pageUtil = new PageUtil(Integer.parseInt(currentPage), Configurer.getPropertyInt("Common.LIST.COUNT_PER_PAGE", 10), 10, totalCount);
List<NotifyTemplate> list = notifyMgrService.selectListNotifyTemplate(pageUtil);
model.addAttribute("list", list);
model.addAttribute("pageUtil", pageUtil);
return "/service/notifyMgr/supervise/templateIdListPopup";
}
//팝업 - 수신자 그룹 조회
@RequestMapping("/service/notifyMgr/recvGroupListPopup")
public String recvGroupList(Model model
,String currentPage
,NotifyInfo notifyInfo
){
if(currentPage == null) currentPage = "1";
int totalCount = notifyMgrService.totalCountNotifyInfo(notifyInfo);
PageUtil pageUtil = new PageUtil(Integer.parseInt(currentPage), Configurer.getPropertyInt("Common.LIST.COUNT_PER_PAGE", 10), 10, totalCount);
List<NotifyInfo> list = notifyMgrService.selectListNotifyInfo(notifyInfo, pageUtil);
model.addAttribute("list",list);
model.addAttribute("notifyInfo",notifyInfo);
model.addAttribute("pageUtil",pageUtil);
return "/service/notifyMgr/supervise/recvGroupListPopup";
}
//팝업 - 통보 모듈 조회
@RequestMapping("/service/notifyMgr/moduleListPopup")
public String moduleList(Model model
,String currentPage
,NotifyModuleInfo notifyModuleInfo
){
if(currentPage == null) currentPage = "1";
int totalCount = notifyMgrService.totalCountNotifyModuleInfo(notifyModuleInfo);
PageUtil pageUtil = new PageUtil(Integer.parseInt(currentPage), Configurer.getPropertyInt("Common.LIST.COUNT_PER_PAGE", 10), 10, totalCount);
List<NotifyModuleInfo> list = notifyMgrService.selectListNotifyModuleInfo(pageUtil, notifyModuleInfo);
model.addAttribute("pageUtil", pageUtil);
model.addAttribute("list", list);
model.addAttribute("notifyModuleInfo", notifyModuleInfo);
return "/service/notifyMgr/supervise/moduleListPopup";
}
//통보 관리 상세보기 [NOTIFY_MGR]
@RequestMapping("/service/notifyMgr/notifyMgrInfo")
public String notifyMgrInfo(Model model,
NotifyMgr notifyMgr
){
NotifyMgr vo = notifyMgrService.selectNotifyMgr(notifyMgr);
model.addAttribute("notifyMgr",vo);
return "/service/notifyMgr/supervise/notifyMgrInfo";
}
//통보 모듈 설정 리스트 [NOTIFY_MODULE_INFO]
@RequestMapping("/service/notifyMgr/notifyModuleInfoList")
public String notifyModuleInfoList(Model model
,String currentPage
,NotifyModuleInfo notifyModuleInfo
){
if(currentPage == null) currentPage = "1";
int totalCount = notifyMgrService.totalCountNotifyModuleInfo(notifyModuleInfo);
PageUtil pageUtil = new PageUtil(Integer.parseInt(currentPage), Configurer.getPropertyInt("Common.LIST.COUNT_PER_PAGE", 10), 10, totalCount);
List<NotifyModuleInfo> list = notifyMgrService.selectListNotifyModuleInfo(pageUtil, notifyModuleInfo);
model.addAttribute("pageUtil", pageUtil);
model.addAttribute("list", list);
model.addAttribute("notifyModuleInfo", notifyModuleInfo);
return "/service/notifyMgr/module/notifyModuleInfoList";
}
//통보 모듈 상세보기 [NOTIFY_MODULE_INFO]
@RequestMapping("/service/notifyMgr/notifyModuleInfo")
public String notifyModuleInfo(Model model
,String notifyModuleId
){
NotifyModuleInfo notifyModuleInfo = notifyMgrService.selectNotifyModuleInfo(notifyModuleId);
model.addAttribute("notifyModuleInfo", notifyModuleInfo);
return "/service/notifyMgr/module/notifyModuleInfo";
}
//통보 모듈 등록 [NOTIFY_MODULE_INFO]
@RequestMapping("/service/notifyMgr/notifyModuleInfoAdd")
public String notifyModuleInfoAdd(Model model
,String notifyModuleId
){
NotifyModuleInfo notifyModuleInfo = notifyMgrService.selectNotifyModuleInfo(notifyModuleId);
model.addAttribute("notifyModuleInfo", notifyModuleInfo);
return "/service/notifyMgr/module/notifyModuleInfoAdd";
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rs.ac.bg.fon.ps.operation.prisustvoTerminu;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import rs.ac.bg.fon.ps.domain.PrisustvoTerminu;
import rs.ac.bg.fon.ps.domain.Termin;
import rs.ac.bg.fon.ps.operation.AbstractGenericOperation;
/**
*
* @author Mr OLOGIZ
*/
public class ZapamtiPrisustvoTerminu extends AbstractGenericOperation<Object> {
@Override
protected void preconditions(Object param) throws Exception {
List<PrisustvoTerminu> prisustvaTerminu = repository.getAll(new PrisustvoTerminu());
for (PrisustvoTerminu prisustvoTerminu : prisustvaTerminu) {
if (Objects.equals(((PrisustvoTerminu) param).getNalogClana().getIdClana(), prisustvoTerminu.getNalogClana().getIdClana())
&& Objects.equals(((PrisustvoTerminu) param).getTermin().getIDTermina(), prisustvoTerminu.getTermin().getIDTermina())) {
throw new Exception("Nalog je vec registrovan za taj termin");
}
}
repository.insert((PrisustvoTerminu) param);
List<Termin> SviTermini = repository.getAll(new Termin());
Termin noviTermin = null;
for (Termin termin : SviTermini) {
if (Objects.equals(((PrisustvoTerminu) param).getTermin().getIDTermina(), termin.getIDTermina())) {
if (termin.getBrojClanova() == termin.getMaksBrojClanova()) {
throw new Exception("Popunjeni kapaciteti termina");
}
noviTermin = termin;
noviTermin.setBrojClanova(noviTermin.getBrojClanova() + 1);
}
}
repository.update(noviTermin);
}
@Override
protected void executeOperation(Object param) throws Exception {
}
}
|
package com.logging;
import java.io.IOException;
import java.sql.SQLException;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class Example{
/* Get the class name to be printed on */
static Logger myLogger = Logger.getLogger(Example.class.getName());
public static void main(String[] args)throws IOException,SQLException{
System.out.println("Inside main....");
String log4jConfPath = "//C:/Users/SHWETA/workspace/Log4jProject/Properties/log.properties";
PropertyConfigurator.configure(log4jConfPath);
// BasicConfigurator.configure();
myLogger.fatal("Hello this is an fatal message");
myLogger.error("Hello this is an error message");
myLogger.warn("Hello this is an warn message");
myLogger.info("Hello this is an info message");
myLogger.debug("Hello this is a debug message");
myLogger.trace("Hello this is a trace message");
}
}
|
package com.github.kemonoske.drophub.core;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
public class HubServer extends Thread {
private int port;
public HubServer(int port) {
this.port = port;
}
@Override
public void run() {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new HubServerInitializer());
bootstrap.bind(port).sync().channel().closeFuture().sync();
} catch (InterruptedException ignored) {
ignored.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
|
package com.v1_4.mydiaryapp.com;
import java.net.URLDecoder;
import java.net.URLEncoder;
import org.json.JSONObject;
import android.content.res.Configuration;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class Screen_CustomText extends Act_ActivityBase {
public DownloadThread downloadThread;
public WebView browser;
public String loadUrl;
public WebView webView;
//onCreate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_customtext);
//activity name
thisActivityName = "Screen_CustomText";
//appDelegate holds current screen
appDelegate = (AppDelegate) this.getApplication();
webView = (WebView)findViewById(R.id.myWebView);
//for local data..
appGuid = appDelegate.currentApp.guid;
appApiKey = appDelegate.currentApp.apiKey;
screenGuid = appDelegate.currentScreen.screenGuid;
saveAsFileName = screenGuid + "_customText.html";
remoteDataCommand = "customTextViewController";
//back button..
ImageButton btnBack = (ImageButton) findViewById(R.id.btnBack);
btnBack.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
//info button
ImageButton btnInfo = (ImageButton) findViewById(R.id.btnInfo);
btnInfo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showInfo();
}
});
//appDelegate.currentScreen.jsonScreenOptions holds variables
try{
JSONObject raw = new JSONObject(appDelegate.currentScreen.jsonScreenOptions);
//screen guid from selected select
try{
screenGuid = raw.getString("screenGuid");
}catch(Exception ex_1){
}
try{
screenGuid = raw.getString("guid");
}catch(Exception ex_2){
}
try{
((TextView)findViewById(R.id.myTitle)).setText(raw.getString("title"));
}catch(Exception ex_3){
}
}catch (Exception je){
Log.i("ZZ", thisActivityName + ":onCreate error : " + appDelegate.currentScreen.jsonScreenOptions);
}
if(webView != null){
//webView settings
webView.setBackgroundColor(0);
webView.setInitialScale(0);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginsEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress){
}
});
webView.setWebViewClient(new WebViewClient(){
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
hideProgress();
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
});
}
}
///////////////////////////////////////////////////
//activity life-cycle overrides
//on configuration changes
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.i("ZZ", thisActivityName + ":onConfigurationChanged called");
}
//onResume
@Override
public void onResume() {
super.onResume();
//Log.i("ZZ", thisActivityName + ":onResume");
//local or remote JSON text...
if(appDelegate.fileExists(saveAsFileName)){
String theText = appDelegate.getLocalText(saveAsFileName);
loadDataString(theText);
}else{
downloadData();
}
}
//onPause
@Override
public void onPause() {
//Log.i("ZZ", thisActivityName + ":onPause");
super.onPause();
}
//onStop
@Override
protected void onStop(){
super.onStop();
//Log.i("ZZ", thisActivityName + ":onStop");
}
//onDestroy
@Override
public void onDestroy() {
//Log.i("ZZ", thisActivityName + ":onDestroy");
super.onDestroy();
}
//activity life-cycle overrides
///////////////////////////////////////////////////
//download data
public void downloadData(){
//show progress
showProgress("Loading...", "We'll save this to speed things up for next time.");
//build URL
String tmpURL = appDelegate.currentApp.dataUrl;
tmpURL += "?appGuid=" + appGuid;
tmpURL += "&appApiKey=" + appApiKey;
tmpURL += "&screenGuid=" + screenGuid;
tmpURL += "&command=" + remoteDataCommand;
downloadThread = new DownloadThread();
downloadThread.setDownloadURL(tmpURL);
downloadThread.setSaveAsFileName(saveAsFileName);
downloadThread.setDownloadType("text");
downloadThread.setThreadRunning(true);
downloadThread.start();
Log.i("ZZ", thisActivityName + ":downloadData: " + tmpURL);
}
//loadURL
public void loadURL(String theUrl){
if(webView != null){
try{
showProgress("Loading..","This screen will load faster next time.");
webView.loadUrl(theUrl);
}catch(Exception je){
hideProgress();
showAlert("Error Loading?","There was a problem loading some data. Please check your internet connection then try again.");
}
}
}
//load string in web-view
public void loadDataString(String theString){
Log.i("ZZ", thisActivityName + ":loadDataString: " + theString);
webView.loadDataWithBaseURL(null, theString, "text/html", "utf-8", "about:blank");
hideProgress();
}
//after download..
Handler downloadTextHandler = new Handler(){
@Override public void handleMessage(Message msg){
if(JSONData.length() < 1){
hideProgress();
showAlert("Error Downloading", "Please check your internet connection then try again.");
}else{
loadDataString(JSONData);
}
}
};
//downloads in background thread..
public class DownloadThread extends Thread{
boolean threadRunning = false;
String downloadURL = "";
String saveAsFileName = "";
String downloadType = "";
void setThreadRunning(boolean bolRunning){
threadRunning = bolRunning;
}
void setDownloadURL(String theURL){
downloadURL = theURL;
}
void setSaveAsFileName(String theFileName){
saveAsFileName = theFileName;
}
void setDownloadType(String imageOrText){
downloadType = imageOrText;
}
@Override
public void run(){
//text downloads
if(downloadType == "text"){
JSONData = appDelegate.downloadText(downloadURL);
appDelegate.saveText(saveAsFileName, JSONData);
downloadTextHandler.sendMessage(downloadTextHandler.obtainMessage());
this.setThreadRunning(false);
}
}
}
//end download thread
/////////////////////////////////////////////////////
//options menu
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
//set up dialog
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.menu_refresh);
dialog.setTitle("Screen Options");
//refresh ..
Button btnRefresh = (Button) dialog.findViewById(R.id.btnRefresh);
btnRefresh.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.cancel();
downloadData();
}
});
//cancel...
Button button = (Button) dialog.findViewById(R.id.btnCancel);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
dialog.cancel();
}
});
//show
dialog.show();
return true;
}
//end menu
/////////////////////////////////////////////////////
}
|
package com.example.narubibi.findate.Activities;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.narubibi.findate.R;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class EditInfoActivity extends AppCompatActivity {
private Toolbar editInfoToolbar;
private TextView edBirth;
private DatePickerDialog.OnDateSetListener dateSetListener;
private String userId, name, birthday, phone, about, job, workplace, swipeImageUrl;
private ImageView imageViewSwipeImage;
private EditText editTextName, editTextPhone, editTextAboutYou, editTextJob, editTextSchoolCompany;
private Button btnConfirm, btnBack;
private FloatingActionButton btnAddImage;
private ProgressBar progressBar;
private FirebaseAuth firebaseAuth;
private DatabaseReference userDb;
private DatePickerDialog datePickerDialog;
private Uri resultUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_info);
editInfoToolbar = findViewById(R.id.edit_info_toolbar);
setSupportActionBar(editInfoToolbar);
getSupportActionBar().setTitle("Edit Info");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
edBirth = (TextView) findViewById(R.id.tv_birth_set);
edBirth.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (datePickerDialog == null) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
String date = (month + 1) + "/" + month + "/" + year;
edBirth.setText(date);
datePickerDialog = new DatePickerDialog(
EditInfoActivity.this,
AlertDialog.THEME_HOLO_DARK,
dateSetListener,
year, month, day);
}
datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
datePickerDialog.show();
}
});
dateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String date = month + "/" + dayOfMonth + "/" + year;
edBirth.setText(date);
}
};
imageViewSwipeImage = findViewById(R.id.iv_swipe_image);
editTextName = findViewById(R.id.ed_edit_info_name);
editTextPhone = findViewById(R.id.ed_edit_info_phone);
editTextAboutYou = findViewById(R.id.ed_edit_info_about);
editTextJob = findViewById(R.id.ed_edit_info_job_title);
editTextSchoolCompany = findViewById(R.id.ed_edit_info_school);
btnConfirm = findViewById(R.id.btn_edit_info_update);
btnBack = findViewById(R.id.btn_edit_info_cancel);
btnAddImage = findViewById(R.id.btn_plus_image);
progressBar = findViewById(R.id.sign_progress);
firebaseAuth = FirebaseAuth.getInstance();
userId = firebaseAuth.getCurrentUser().getUid();
userDb = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
getUserInfo();
btnAddImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setFixAspectRatio(true)
.setAspectRatio(4, 5)
.setMinCropWindowSize(200, 250)
.start(EditInfoActivity.this);
}
});
btnConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveUserInformation();
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
endActivity();
}
});
}
private void getUserInfo() {
userDb.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists() && dataSnapshot.getChildrenCount() > 0) {
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if (map.get("name") != null) {
name = map.get("name").toString();
editTextName.setText(name);
}
if (map.get("birthday") != null) {
birthday = map.get("birthday").toString();
if (!birthday.isEmpty()) {
edBirth.setText(birthday);
String[] dateArray = birthday.split("/");
int year = Integer.parseInt(dateArray[2]);
int month = Integer.parseInt(dateArray[0]);
int date = Integer.parseInt(dateArray[1]);
datePickerDialog = new DatePickerDialog(
EditInfoActivity.this,
AlertDialog.THEME_HOLO_DARK,
dateSetListener,
year, month - 1, date);
}
}
if (map.get("phone") != null) {
phone = map.get("phone").toString();
editTextPhone.setText(phone);
}
if (map.get("job") != null) {
job = map.get("job").toString();
editTextJob.setText(job);
}
if (map.get("about") != null) {
about = map.get("about").toString();
editTextAboutYou.setText(about);
}
if (map.get("workplace") != null) {
workplace = map.get("workplace").toString();
editTextSchoolCompany.setText(workplace);
}
if (map.get("swipe_image_url") != null) {
swipeImageUrl = map.get("swipe_image_url").toString();
Glide.with(imageViewSwipeImage.getContext()).load(swipeImageUrl).into(imageViewSwipeImage);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void saveUserInformation() {
progressBar.setVisibility(View.VISIBLE);
btnConfirm.setEnabled(false);
btnBack.setEnabled(false);
name = editTextName.getText().toString();
birthday = edBirth.getText().toString();
phone = editTextPhone.getText().toString();
job = editTextJob.getText().toString();
about = editTextAboutYou.getText().toString();
workplace = editTextSchoolCompany.getText().toString();
Map<String, Object> userInfo = new HashMap<>();
userInfo.put("name", name);
userInfo.put("birthday", birthday);
userInfo.put("phone", phone);
userInfo.put("job", job);
userInfo.put("about", about);
userInfo.put("workplace", workplace);
userDb.updateChildren(userInfo);
if (resultUri != null) {
final StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("SwipeImages").child(userId);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, byteArrayOutputStream);
byte[] data = byteArrayOutputStream.toByteArray();
UploadTask uploadTask = storageReference.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
finish();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
Map<String, Object> userInfo = new HashMap<>();
userInfo.put("swipe_image_url", downloadUrl.toString());
userDb.updateChildren(userInfo);
endActivity();
}
});
}
else {
endActivity();
}
}
private void endActivity() {
// Intent intent = new Intent(EditInfoActivity.this, MainActivity.class);
// startActivity(intent);
finish();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
resultUri = result.getUri();
// Toast.makeText(EditInfoActivity.this, resultUri.toString(), Toast.LENGTH_LONG).show();
imageViewSwipeImage.setImageURI(resultUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
endActivity();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
endActivity();
break;
}
return true;
}
}
|
package com.gogo.base.utils;
import java.util.ArrayList;
import java.util.List;
public class PageUtil {
public static Integer getStartPageOffset(int pageSize,int pageNo){
return (pageNo-1)*pageSize;
}
public static boolean nextPage(Integer offset, Integer pageSize, Integer total){
if(offset == null || pageSize == null || total == null) {
return false;
}
return (offset + pageSize) < (total) ? true : false;
}
public static boolean nextPageOffset(Integer pageNo, Integer pageSize,Integer total){
if(pageNo == null || pageSize == null || total == null) {
return false;
}
int offset = PageUtil.getStartPageOffset(pageSize, pageNo);
return (offset + pageSize) < (total) ? true : false;
}
public static Integer getPageNoInDefault(Integer pageNo){
return (pageNo==null||pageNo==0)?1:pageNo;
}
public static Integer getPageSizeInDefault(Integer pageSize){
return (pageSize==null||pageSize==0)?20:pageSize;
}
public static Integer getMaxPageSize(){
return 100;
}
public static <T> List<T> operateByPage(List<T> nlist, int offset, int pageSize) {
if(nlist == null || nlist.isEmpty()) {
return new ArrayList<T>();
}
int toIndex = offset+pageSize;
if(nlist.size()<(offset+1))
return null;
else if(nlist.size()<toIndex)
return nlist.subList(offset, nlist.size());
else
return nlist.subList(offset, toIndex);
}
}
|
package org.softRoad.models;
import org.softRoad.models.query.QueryUtils;
import javax.persistence.Table;
@Table(name = "consultant_profile_category")
public class ConsultantProfileCategory {
public final static String CONSULTANT_ID = "consultant_id";
public final static String CATEGORIES_ID = "category_id";
public static String fields(String fieldName, String ... fieldNames) {
return QueryUtils.fields(ConsultantProfileCategory.class, fieldName, fieldNames);
}
}
|
package com.example.studentmanagment;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class AskQueryActivity extends Activity implements
OnItemSelectedListener, OnClickListener {
SessionManager session;
String studentId;
Spinner s1;
EditText t1;
Button b1;
String branch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ask_query);
session = new SessionManager(getApplicationContext());
session.checkLogin();
studentId = session.getUserDetails();
//studentId = getIntent().getStringExtra("email");
Toast.makeText(AskQueryActivity.this, studentId, 2000).show();
s1 = (Spinner) findViewById(R.id.spinner1);
t1 = (EditText) findViewById(R.id.editText1);
s1.setOnItemSelectedListener(this);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.ask_query, menu);
return true;
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int index,
long arg3) {
// TODO Auto-generated method stub
branch = s1.getSelectedItem().toString();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(branch.equals("Select Branch")){
Toast.makeText(AskQueryActivity.this, "Please select a department", 2000).show();
}
else
{
DataBaseHelper dh=new DataBaseHelper(getApplicationContext());
SQLiteDatabase db=dh.getWritableDatabase();
String description=t1.getText().toString();
ContentValues cv=new ContentValues();
cv.put("studentId",studentId);
cv.put("department",branch);
cv.put("description",description);
long check= db.insert("query", null, cv);
if (check>0)
{
Toast.makeText(this, "Record Successfully Inserted", 2000).show();
}
else
{
Toast.makeText(this, "Record Successfully Not Inserted", 2000).show();
}
}
}
}
|
package collection.loader;
import data.*;
import java.io.IOException;
interface Reading {
void reading() throws IOException;
String xmlChecker(String file);
String xmlCheckerMedium(String file);
LabWork Creator(Long id , String name
, Coordinates coordinates , java.time.LocalDate creationDate,
Long minimalPoint , Integer maximumPoint, Difficulty difficulty , Discipline discipline);
}
|
package com.wzh.crocodile.ex00_ready.io.io02_stream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
/**
* @Description: 文本文件输出的快捷方式
* @Author: 吴智慧
* @Date: 2019/11/12 19:59
*/
public class FileOutputShortcut {
/**
* 输出的文件
*/
static String file = System.getProperty("user.dir") + "\\src\\main\\java\\com\\wzh\\crocodile\\ex00_ready\\io\\io02_stream\\BasicFileOutput.out";
public static void main(String[] args) throws IOException {
// 文件绝对路径
// 项目根路径:System.getProperty("user.dir")
String path = System.getProperty("user.dir") + "\\src\\main\\java\\com\\wzh\\crocodile\\ex00_ready\\io\\io02_stream\\BasicFileOutput.java";
// 打开一个文件用于字符输入
String content = BufferedInputFile.read(path);
// 使用内存中的字符串,创建BufferedReader对象
BufferedReader in = new BufferedReader(new StringReader(content));
// 使用文件名,创建Writer对象
// 此处使用了快捷方式,不必都去执行所有的装饰工作
// 其他常见的写入任务都没有快捷方式,因此典型的I/O仍然包含大量的冗余文本
PrintWriter out = new PrintWriter(file);
// 遍历输出文件内容
int lineCount = 1;
String s;
while ((s = in.readLine()) != null){
out.println(lineCount++ + ": " + s);
}
// 关闭文件
// 如果不为所有的输入文件调用close(),就会发现缓冲区内容不会被刷新清空,内容将不完整
out.close();
// 查看输出文件
System.out.println(BufferedInputFile.read(file));
}
}
|
package com.oklink.bitcoinj.params;
import static org.bitcoinj.core.Coin.COIN;
import org.bitcoinj.core.Block;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.StoredBlock;
import org.bitcoinj.core.VerificationException;
import org.bitcoinj.params.AbstractBitcoinNetParams;
import org.bitcoinj.store.BlockStore;
import org.bitcoinj.store.BlockStoreException;
import com.oklink.bitcoinj.core.OKBlock;
public abstract class OKAbstractNetParams extends AbstractBitcoinNetParams {
/**
* Scheme part for OKToken URIs.
*/
public static final String BITCOIN_SCHEME = "oktoken";
public static final Coin MAX_MONEY = COIN.multiply(Integer.MAX_VALUE);
public static final byte[] ANACHOR_FIX_FLAG = {0x4f, 0x4b, 0x54}; //锚定OP_RETURE中的前缀 (OKT)
protected OKBlock genesisBlock;
@Override
public String getPaymentProtocolId() {
// TODO Auto-generated method stub
return null;
}
@Override
public void checkDifficultyTransitions(StoredBlock storedPrev, Block nextBlock, BlockStore blockStore)
throws VerificationException, BlockStoreException {
//不做任何事
}
@Override
public Coin getMaxMoney() {
// TODO Auto-generated method stub
return MAX_MONEY;
}
public OKBlock getGenesisOKBlock(){
return genesisBlock;
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow 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 net.datacrow.console.windows.databaseeditor;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import net.datacrow.console.ComponentFactory;
import net.datacrow.console.Layout;
import net.datacrow.console.windows.DcFrame;
import net.datacrow.core.DcRepository;
import net.datacrow.core.IconLibrary;
import net.datacrow.core.resources.DcResources;
import net.datacrow.settings.DcSettings;
public class DatabaseEditorForm extends DcFrame implements ActionListener {
public DatabaseEditorForm() {
super(DcResources.getText("lblDatabaseEditor"), IconLibrary._icoSettings32);
buildForm();
setHelpIndex("dc.tools.databaseeditor");
}
@Override
public void close() {
DcSettings.set(DcRepository.Settings.stExpertFormSize, getSize());
super.close();
}
private void buildForm() {
QueryPanel queryPanel = new QueryPanel();
JPanel panelActions = new JPanel();
JButton buttonClose = ComponentFactory.getButton(DcResources.getText("lblClose"));
buttonClose.setActionCommand("close");
buttonClose.addActionListener(this);
panelActions.add(buttonClose);
getContentPane().setLayout(Layout.getGBL());
getContentPane().add(queryPanel, Layout.getGBC( 0, 0, 1, 1, 50.0, 50.0
,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
getContentPane().add(panelActions, Layout.getGBC( 0, 1, 1, 1, 1.0, 1.0
,GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 10), 0, 0));
pack();
setSize(DcSettings.getDimension(DcRepository.Settings.stExpertFormSize));
setCenteredLocation();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("close"))
close();
}
}
|
package peter8icestone.concurrency.chapter1;
public class TryConcurrency {
public static void main(String[] args) {
// thread 1
Thread t1 = new Thread(() -> {
System.out.println(Thread.currentThread().getName());
for (int i=0; i<10; i++) {
System.out.println("task 1=>" + i);
try {
// sleep 100 ms
Thread.sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "thread 1");
t1.start();
// main thread
for (int i=0; i<1000; i++) {
System.out.println("task 2=>" + i);
}
}
}
|
package com.spark.collecteLait.Rest.Dto;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class ChauffeurDto {
private Long id;
private Long codeCnss;
private String cin;
private String nom;
private String prenom;
private Date dateNaissance;
private String address;
private Long phone;
private String email;
}
|
package objectDemo;
public class MaleHumanClass extends HumanAbstractClass {
public int MaleAge=0;
public int MaleBirth =0;
private int MaleHeight;
final int MaleSize=20;
public MaleHumanClass() {
}
public MaleHumanClass(int age,int birth) {
this.MaleAge =age;
MaleBirth = birth;
}
//@Override
public void humanRun() {
System.out.println("Male Human is Running");
// HumanAbstractClass.defaultHappyHuman();
}
public int getMaleHeight() {
return MaleHeight;
}
public int setMaleHeight(int b) {
this.MaleHeight=b;
return this.MaleHeight;
}
@Override
public void humanAvgSize() {
// this.HumanStartDate = "Humans started 10,000";
System.out.println("Male Average size is 5'10");
}
public int updateMaleAge() {
this.MaleAge=1;
return this.MaleAge;
}
public int updateMaleAge(int num) {
this.MaleAge = num;
return this.MaleAge;
}
public String sameFunction() {
return "hello from sameFunction with no input parameters";
}
public String sameFunction(int nm) {
StringBuilder returnVar = new StringBuilder("hello from sameFunction");
returnVar.append(nm);
returnVar.append("with int as input parameter");
return returnVar.toString();
}
public void eat(){
System.out.println("Boy is eating");
}
@Override
public void humanBreath() {
// TODO Auto-generated method stub
}
}
|
package cn.xuetang.modules.sys.bean;
import java.util.List;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Many;
import org.nutz.dao.entity.annotation.Name;
import org.nutz.dao.entity.annotation.Table;
/**
* @author Wizzer.cn
* @time 2012-9-13 上午10:54:04
*
*/
@Table("sys_unit")
public class Sys_unit
{
@Column
@Name
private String id;
@Column
private String name;
@Column
private String unitcode;
@Column
private String descript;
@Column
private String address;
@Column
private String telephone;
@Column
private String email;
@Column
private String website;
@Column
private int location;
@Many(target = Sys_user.class, field = "unitid")//一个单位下有N个用户
private List<Sys_user> users;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id=id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
public String getUnitcode()
{
return unitcode;
}
public void setUnitcode(String unitcode)
{
this.unitcode=unitcode;
}
public String getDescript()
{
return descript;
}
public void setDescript(String descript)
{
this.descript=descript;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address=address;
}
public String getTelephone()
{
return telephone;
}
public void setTelephone(String telephone)
{
this.telephone=telephone;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email=email;
}
public String getWebsite()
{
return website;
}
public void setWebsite(String website)
{
this.website=website;
}
public int getLocation()
{
return location;
}
public void setLocation(int location)
{
this.location=location;
}
public List<Sys_user> getUsers() {
return users;
}
public void setUsers(List<Sys_user> users) {
this.users = users;
}
} |
package com.shangdao.phoenix.enums;
public enum ExceptionResultEnum {
UNKNOW_ERROR(-1,"未知错误"),
SUCCESSFUL(0,"OK"),
SMS_ERROR(1000,"短信验证码错误,请重新输入验证码"),
NOMOBILE(1001,"没有手机号"),
BAN_USER_AUTHORIZATION(1011,"禁止用户授权"),
ACT_OBJECT_MUST_MACHINE(1021,"动作对象必须是状态机实体"),
SAME_OBJECT_CODE_NOTSAME(1022,"同一个实体的动作不能相同code"),
ACT_OBJECT_MUST_PROJECT(1023,"动作对象必须是项目实体,才能通知到"),
NOT_EFFECTIVE_ROLECODE(1024,"不是有效的角色code"),
COMPANY_NAME_EXIST(1031,"公司名称已存在,请重新输入"),
APPLY_FORM_EXIST(1032,"您已提交过公司申请单、请等待审核结果"),
INPUT_REFUSR_REASON(1033,"请填写拒绝原因"),
USER_NOT_COMPANY(1034,"该用户不属于本公司"),
DISCOUNT_NOT_HAVE(1035,"请填写价格系数"),
SOME_ONE_USER_NAME(1036,"该公司名称已经被使用"),
YOU_HAVE_COMPANY(1037,"您已经有所属公司,不能再申请"),
USER_NOT_REGISTER(1041,"该用户尚未注册"),
FILE_UPLOAD_ALIYUN_ERROR(1051,"文件上传到阿里云出错"),
FILE_FORMAT_PARSE_ERROR(1052,"上传文件格式解析出错"),
ALIYUN_FILE_FORMAT_ERROR(1053,"阿里云转换文件格式出错"),
ALIYUN_IMG_FORMAT_ERROR(1054,"阿里云图片格式转换出错"),
CHOOSE_DELETE_OBJECT(1061,"请选择要删除的目标"),
WXWORK_NOT_READY(1071,"企业微信服务没启动"),
GROUP_HAVE_NO_PARAM(1072,"group接口必须包含group参数"),
ID_ERROR(1073,"id格式错误"),
HAVE_NO_WORKWX_FUNCTION(1074,"没有启动企业微信功能"),
MENU_NAME_REPEAT(1081,"菜单名称已被使用或者该菜单被删除过"),
MENU_PATH_NEED(1082,"菜单路径必须填写"),
LOG_SAVE_ERROR(1091,"log保存失败"),
DATA_SAVE_ERROR(1092,"数据库保存错误"),
HAVE_NO_TERMINAL(1093,"Header缺少terminal参数"),
TERMINAL_ERROR(1094,"terminal参数格式不合法"),
CREATE_NOT_NEED_ID(1095,"创建对象不允许带id"),
HAVE_NO_ID(1096,"结构中缺少id"),
POST_DATA_ERROR(1097,"解析post数据异常"),
HAVE_NO_START_PUBLIC_WEIXIN_FUNCTION(1101,"没有启动微信公众号功能"),
PBWX_START_ERROR(1102,"微信公众号服务没启动"),
POST_TO_WEIXIN_ERROR(1103,"post提交给微信错误"),
USER_WEIXIN_RETURN_JSON_ERROR(1104,"用户微信返回结果json解析失败"),
ROLE_NAME_CANNOT_REPEAT(1111,"角色名称已被使用"),
ROLE_CODE_CANNOT_REPEAT(1112,"角色Code已被使用"),
ROLE_HAVA_USER(1113,"该角色还在使用中,不能删除"),
ROLE_CODE_CANNOT_UPDATE(1114,"角色CODE不能修改"),
ROLE_NAME_HAVE_USER_DELETE(1115,"该角色名称被删除过,不能再添加"),
ROLE_CODE_HAVE_USER_DELETE(1116,"该角色CODE被删除过,不能再添加"),
USER_NAME_EXIST(1121,"用户名已存在"),
PASSWORD_NOT_SAME(1122,"两次密码不一样"),
USER_NOT_EXIST(1123,"用户不存在"),
UNKNOW_USER_TYPE(1124,"未知用户来源"),
USER_HAVE_DELETE(1125,"该用户已被删除,不能添加"),
UNKNOW_PAY_TYPE(1131,"未知充值类型"),
HAVE_NOT_PAY_AMOUNT(1132,"请输入充值金额"),
ACCOUNT_NO_MONEY(1133,"账户余额不足"),
GIVE_ACCOUNT_NO_MONEY(1134,"赠送账户余额不足");
private Integer code;
private String message;
private ExceptionResultEnum (Integer code,String message){
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
}
|
package main.java.algorithms.bpp;
import java.util.ArrayList;
import main.java.algorithms.BPPAlgorithm;
import main.java.main.product.Box;
import main.java.main.product.Product;
public class NextFit extends BPPAlgorithm
{
/**
* Print all products in the list
*
* @param products
* @return
*/
public static String printAllProducts(ArrayList<Product> products)
{
String productData = "";
for (Product product : products)
{
productData = ("Size: " + product.GetSize() + ". ID: " + product.GetId() + ". Coords" + product.GetCoords()
+ ". Name: " + product.GetName() + ".");
}
return productData;
}
@Override
public ArrayList<Box> getBoxes(ArrayList<Product> products, int boxVolume)
{
Box currentBox = new Box(0);
// clear returnBoxes arraylist so no leftovers of previous calculations
// remain.
returnBoxes.clear();
// loop through all products asked for
for (Product product : products)
{
// check if product fits in current box
if (currentBox.checkFit((int) product.GetSize()))
{
currentBox.addProduct(product);
}
else
{
// else create new box for currentBox and add product then
currentBox = new Box(boxVolume);
currentBox.addProduct(product);
returnBoxes.add(currentBox);
}
}
// set currentBox size 0 again so a new one immediately gets initialized
// and added next time at execution
currentBox = new Box(0);
return returnBoxes;
}
}
|
package com.daikit.graphql.test.introspection;
import java.util.ArrayList;
import java.util.List;
/**
* Introspection full type
*
* @author Thibaut Caselli
*/
public class IntrospectionFullType {
private String kind;
private String name;
private String description;
private List<IntrospectionTypeField> fields = new ArrayList<>();
private List<IntrospectionInputValue> inputFields = new ArrayList<>();
private List<IntrospectionTypeRef> interfaces = new ArrayList<>();
private List<IntrospectionEnum> enumValues = new ArrayList<>();
private List<IntrospectionTypeRef> possibleTypes = new ArrayList<>();
/**
* @return the kind
*/
public String getKind() {
return kind;
}
/**
* @param kind
* the kind to set
*/
public void setKind(final String kind) {
this.kind = kind;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(final String name) {
this.name = name;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description
* the description to set
*/
public void setDescription(final String description) {
this.description = description;
}
/**
* @return the fields
*/
public List<IntrospectionTypeField> getFields() {
return fields;
}
/**
* @param fields
* the fields to set
*/
public void setFields(final List<IntrospectionTypeField> fields) {
this.fields = fields;
}
/**
* @return the inputFields
*/
public List<IntrospectionInputValue> getInputFields() {
return inputFields;
}
/**
* @param inputFields
* the inputFields to set
*/
public void setInputFields(final List<IntrospectionInputValue> inputFields) {
this.inputFields = inputFields;
}
/**
* @return the interfaces
*/
public List<IntrospectionTypeRef> getInterfaces() {
return interfaces;
}
/**
* @param interfaces
* the interfaces to set
*/
public void setInterfaces(final List<IntrospectionTypeRef> interfaces) {
this.interfaces = interfaces;
}
/**
* @return the enumValues
*/
public List<IntrospectionEnum> getEnumValues() {
return enumValues;
}
/**
* @param enumValues
* the enumValues to set
*/
public void setEnumValues(final List<IntrospectionEnum> enumValues) {
this.enumValues = enumValues;
}
/**
* @return the possibleTypes
*/
public List<IntrospectionTypeRef> getPossibleTypes() {
return possibleTypes;
}
/**
* @param possibleTypes
* the possibleTypes to set
*/
public void setPossibleTypes(final List<IntrospectionTypeRef> possibleTypes) {
this.possibleTypes = possibleTypes;
}
}
|
import java.util.*;
public class MyClass
{
public static void main(String args[])
{
String s;
char c;
int len,i,count=1;
Scanner scan=new Scanner(System.in);
s=scan.nextLine();
len=s.length();
for(i=0;i<len;i++)
{
c=s.charAt(i);
if(c==' ')
{
count++;
}
}
System.out.print(count);
}
} |
package br.mpac.dados;
import javax.ejb.Stateless;
import br.mpac.entidade.OrientacaoSexual;
@Stateless
public class OrientacaoSexualDao extends GenericDao<OrientacaoSexual> {
public OrientacaoSexualDao() {
super(OrientacaoSexual.class);
}
}
|
package com.aidigame.hisun.imengstar.ui;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.aidigame.hisun.imengstar.PetApplication;
import com.aidigame.hisun.imengstar.adapter.HomeViewPagerAdapter;
import com.aidigame.hisun.imengstar.bean.Animal;
import com.aidigame.hisun.imengstar.bean.Gift;
import com.aidigame.hisun.imengstar.constant.Constants;
import com.aidigame.hisun.imengstar.http.HttpUtil;
import com.aidigame.hisun.imengstar.util.HandleHttpConnectionException;
import com.aidigame.hisun.imengstar.util.ImageUtil;
import com.aidigame.hisun.imengstar.util.LogUtil;
import com.aidigame.hisun.imengstar.util.StringUtil;
import com.aidigame.hisun.imengstar.view.RoundImageView;
import com.aidigame.hisun.imengstar.widget.ShowProgress;
import com.aidigame.hisun.imengstar.widget.fragment.FourGiftBox;
import com.aidigame.hisun.imengstar.widget.fragment.FourGiftBox.SendGiftResultListener;
import com.aidigame.hisun.imengstar.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.umeng.analytics.MobclickAgent;
/**
* 给人送礼物,弹出框
* @author admin
*
*/
public class DialogGiveSbGiftResultActivity extends Activity{
TextView nextTV,sureTV,rqTV,giftNameTv,animalTV,desTv;
ImageView closeIV,giftIV;
RoundImageView icon;
public static DialogGiveSbGiftResultActivity dialogGiveSbGiftActivity;
RelativeLayout parent,imageLayout;
Handler handleHttpConnectionException;
Animal animal;
Gift gift;
View shine_view,badview;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
dialogGiveSbGiftActivity=this;
setContentView(R.layout.activity_send_gift_result);
MobclickAgent.onEvent(this, "gift_button");
this.animal=(Animal)getIntent().getSerializableExtra("animal");
gift=(Gift)getIntent().getSerializableExtra("gift");
BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds=false;
// options.inSampleSize=4;
options.inPreferredConfig=Bitmap.Config.RGB_565;
options.inPurgeable=true;
options.inInputShareable=true;
displayImageOptions=new DisplayImageOptions
.Builder()
.showImageOnLoading(R.drawable.noimg)
.cacheInMemory(true)
.cacheOnDisc(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.decodingOptions(options)
.build();
initView();
}
private void initView() {
// TODO Auto-generated method stub
closeIV=(ImageView)findViewById(R.id.close_view);
animalTV=(TextView)findViewById(R.id.textView1);
giftNameTv=(TextView)findViewById(R.id.gift_name);
giftIV=(ImageView)findViewById(R.id.gift_iv);
rqTV=(TextView)findViewById(R.id.rq_tv);
nextTV=(TextView)findViewById(R.id.next);
sureTV=(TextView)findViewById(R.id.sure);
desTv=(TextView)findViewById(R.id.textView3);
icon=(RoundImageView)findViewById(R.id.round);
shine_view=findViewById(R.id.shine_view);
badview=findViewById(R.id.shine_view_bad);
imageLayout=(RelativeLayout)findViewById(R.id.imageView1);
parent=(RelativeLayout)findViewById(R.id.share_bitmap_layout);
handleHttpConnectionException=HandleHttpConnectionException.getInstance().getHandler(this);
if(gift.add_rq>0){
Animation anim=AnimationUtils.loadAnimation(this, R.anim.anim_rotate_repeat);
anim.setInterpolator(new LinearInterpolator());
shine_view.setAnimation(anim);
anim.start();
}else{
shine_view.setVisibility(View.GONE);
imageLayout.setBackgroundResource(R.drawable.shake_gift_background1_gray);
giftNameTv.setBackgroundResource(R.drawable.shake_giftname_background_gray);
RelativeLayout.LayoutParams param=(RelativeLayout.LayoutParams)giftNameTv.getLayoutParams();
if(param==null){
}else{
param.leftMargin=(int)(getResources().getDimensionPixelSize(R.dimen.waterfall_padding)*0.3f);
}
final Animation anim=AnimationUtils.loadAnimation(this, R.anim.anim_scale_y_repeat);
anim.setInterpolator(new LinearInterpolator());
anim.setFillAfter(true);
badview.setAnimation(anim);
anim.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
handleHttpConnectionException.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
badview.startAnimation(anim);
}
}, 1000);
}
});
badview.startAnimation(anim);
}
BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds=false;
options.inSampleSize=8;
options.inPreferredConfig=Bitmap.Config.RGB_565;
options.inPurgeable=true;
options.inInputShareable=true;
DisplayImageOptions displayImageOptions=new DisplayImageOptions
.Builder()
.showImageOnLoading(R.drawable.pet_icon)
.showImageOnFail(R.drawable.pet_icon)
.cacheInMemory(true)
.cacheOnDisc(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.decodingOptions(options)
.build();
if(animal!=null){
animalTV.setText("给"+animal.pet_nickName+"送个礼物");
ImageLoader imageLoader=ImageLoader.getInstance();
imageLoader.displayImage(Constants.ANIMAL_DOWNLOAD_TX+animal.pet_iconUrl, icon, displayImageOptions);
}
if(gift!=null){
giftNameTv.setText(""+gift.name+" X 1");
if(gift.add_rq>0){
rqTV.setText("人气 + "+gift.add_rq);
if(animal!=null){
desTv.setText("您送给"+gift.animal.pet_nickName+"一个"+gift.name+","+gift.animal.pet_nickName+gift.effect_des);
}
parent.setBackgroundResource(R.drawable.shake_ground_get2);
}else{
parent.setBackgroundResource(R.drawable.shake_ground_get2_gray);
rqTV.setText("人气 - "+(-gift.add_rq));
if(animal!=null){
desTv.setText("您对"+gift.animal.pet_nickName+"扔了一个"+gift.name+","+gift.animal.pet_nickName+gift.effect_des);
}
}
/*try {
giftIV.setImageBitmap(BitmapFactory.decodeStream(getResources().getAssets().open(""+gift.no+".png")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
loadImage(giftIV, gift);
}
closeIV.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialogGiveSbGiftActivity=null;
if(DialogGiveSbGiftActivity1.dialogGiveSbGiftActivity!=null){
DialogGiveSbGiftActivity1.dialogGiveSbGiftActivity.finish();;;
DialogGiveSbGiftActivity1.dialogGiveSbGiftActivity=null;
}
finish();
System.gc();
}
});
sureTV.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialogGiveSbGiftActivity=null;
if(DialogGiveSbGiftActivity1.dialogGiveSbGiftActivity!=null){
DialogGiveSbGiftActivity1.dialogGiveSbGiftActivity.finish();;;
DialogGiveSbGiftActivity1.dialogGiveSbGiftActivity=null;
}
finish();
System.gc();
}
});
nextTV.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
if(DialogGiveSbGiftActivity1.dialogGiveSbGiftActivity!=null){
DialogGiveSbGiftActivity1.dialogGiveSbGiftActivity.setInvisible(false);;
}
}
});
}
DisplayImageOptions displayImageOptions;
public void loadImage(final ImageView icon,final Gift gift){
ImageLoader imageLoader=ImageLoader.getInstance();
imageLoader.displayImage(gift.detail_image_url, icon, displayImageOptions,new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
// TODO Auto-generated method stub
}
@Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
// TODO Auto-generated method stub
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// TODO Auto-generated method stub
String name="gift"+gift.no+"_";
if(loadedImage!=null&&StringUtil.isEmpty(gift.detail_image_path)){
File f=new File(Constants.Picture_Root_Path+File.separator+name+".jpg");
if(f.exists()){
gift.detail_image_path=Constants.Picture_Root_Path+File.separator+name+".jpg";
}else{
String path=ImageUtil.compressImageByName(loadedImage, name);
if(!StringUtil.isEmpty(path)){
gift.detail_image_path=path;
}else{
gift.detail_image_path=ImageUtil.compressImage(loadedImage, name);
}
}
/*BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=16;
icon.setImageBitmap(BitmapFactory.decodeFile(article.share_path, options));*/
}
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
// TODO Auto-generated method stub
}
});
}
}
|
/**
* AndTinder v0.1 for Android
*
* @Author: Enrique López Mañas <eenriquelopez@gmail.com>
* http://www.lopez-manas.com
*
* TAndTinder is a native library for Android that provide a
* Tinder card like effect. A card can be constructed using an
* image and displayed with animation effects, dismiss-to-like
* and dismiss-to-unlike, and use different sorting mechanisms.
*
* AndTinder is compatible with API Level 13 and upwards
*
* @copyright: Enrique López Mañas
* @license: Apache License 2.0
*/
package com.andtinder.model;
public class Orientations {
public enum Orientation {
Ordered(0), Disordered(1);
public final int value;
private Orientation(int value) {
this.value = value;
}
public static Orientation fromValue(int value) {
for (Orientation style : Orientation.values()) {
if (style.value == value) {
return style;
}
}
return null;
}
}
}
|
package com.longfellow.listnode;
/**
* @author longfellow
* 构造链表
*/
public class ListNode {
public int val;
public ListNode next = null;
public ListNode(int val) {
this.val = val;
}
@Override
public String toString() {
return val + "->" + next;
}
}
|
package gov.nih.nci.ctrp.importtrials.studyprotocolenum;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by pkigonya on 3/30/17.
*/
public class PrimaryPurposeEnumTest {
@Test
public void test() {
String [][] testDataArr = {
{PrimaryPurposeEnum.PREVENTION.toString(), "Prevention"},
{PrimaryPurposeEnum.OTHER.toString(), "Other"}
};
for(String [] enumVals : testDataArr ) {
String enumVal = enumVals[0];
String getByStr = enumVals[1];
assertEquals("Testing getByStr " + enumVal, enumVal, PrimaryPurposeEnum.getByPrimaryPurpose(getByStr).toString());
}
}
} |
package com.system.set.in;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
/**
* 结果输入的出现在了文件中
*
* 重定向标准输入,标准输出
* 现象:生成了RedirectInstance.java文件
*/
public class RedirectTest
{
public static void main(String[] args)
{
testSetOut();
testSetIn();
}
public static void testSetOut()
{
// 一次性创建PrintStream输出流
try
{
// 写入的文件
PrintStream printStream = new PrintStream("RedirectInstance.txt");
// 将标准输出 重定向到ps输出流
System.setOut(printStream);
System.out.println("===========================普通字符串===============================");
System.out.println(new RedirectTest());
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static void testSetIn()
{
FileInputStream fileInputStream = null;
Scanner scanner = null;
try
{
fileInputStream = new FileInputStream("src/com/system/set/in/RedirectTest.java");
// 将标准输入 重定向到 fis输入流
System.setIn(fileInputStream);
// 使用System.in 创建Scanner对象,用于获取标准输入
scanner = new Scanner(System.in);
// 将回车符作为分隔符
scanner.useDelimiter("\n");
while (scanner.hasNext())
{
// 输出输入项
System.out.println("键盘输入的内容是:" + scanner.next());
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
scanner.close();
try
{
fileInputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
|
package iit.android.swarachakra;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
public class SwaraChakra extends View {
private float mOuterRadius;
private float mInnerRadius;
private float mArcTextRadius;
private float centerX, centerY;
private Paint mBlackPaint;
private Paint mWhitePaint;
private Paint mInnerPaint;
private Paint mInnerTextPaint;
private Paint mArcPaint;
private Paint mArcDividerPaint;
private Paint mArcPrevPaint;
private Paint mArcTextPaint;
private float screen_width;
private float screen_height;
private RectF bound;
private static String[] defaultChakra;
private static int nArcs;
private int arc;
private static boolean halantExists;
private KeyAttr currentKey;
private String keyLabel;
public SwaraChakra(Context context) {
super(context);
init(context);
// TODO Auto-generated constructor stub
}
public SwaraChakra(Context context, AttributeSet attrs){
super(context,attrs);
init(context);
}
@SuppressLint("NewApi")
private void init(Context context){
mBlackPaint = new Paint();
mBlackPaint.setColor(Color.BLACK);
mBlackPaint.setAntiAlias(true);
mWhitePaint = new Paint();
mWhitePaint.setColor(Color.WHITE);
mWhitePaint.setAntiAlias(true);
mInnerPaint = new Paint();
mInnerPaint.setColor(Color.rgb(255,255,255));
mInnerPaint.setAntiAlias(true);
mInnerTextPaint = new Paint();
mInnerTextPaint.setColor(Color.BLACK);
mInnerTextPaint.setAntiAlias(true);
mInnerTextPaint.setTextAlign(Align.CENTER);
mArcPaint = new Paint();
mArcPaint.setColor(Color.rgb(48, 48, 48));
mArcPaint.setAntiAlias(true);
mArcDividerPaint = new Paint();
mArcDividerPaint.setColor(Color.rgb(200, 200, 200));
mArcDividerPaint.setAntiAlias(true);
mArcPrevPaint = new Paint();
mArcPrevPaint.setColor(Color.rgb(108, 108, 108));
mArcPrevPaint.setAntiAlias(true);
mArcTextPaint = new Paint();
mArcTextPaint.setColor(Color.rgb(255, 255, 255));
mArcTextPaint.setAntiAlias(true);
mArcTextPaint.setTextAlign(Align.CENTER);
setLayerType(View.LAYER_TYPE_NONE, null);
arc = -1;
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
display.getMetrics(displayMetrics);
screen_width = displayMetrics.widthPixels;
screen_height = displayMetrics.heightPixels;
}
public void setMetrics(int mode){
switch(mode){
case 0:
mOuterRadius = (float) (0.25*Math.min(screen_width, screen_height));
break;
case 1:
mOuterRadius = (float) (0.17*Math.min(screen_width, screen_height));
default:
break;
}
mInnerRadius = (float) (0.3*mOuterRadius);
mArcTextPaint.setTextSize((float) 0.20*mOuterRadius);
mInnerTextPaint.setTextSize((float) 0.25*mOuterRadius);
mArcTextRadius = (float) (0.55*mOuterRadius);
bound = new RectF(mOuterRadius,mOuterRadius,3*mOuterRadius, 3*mOuterRadius);
centerX = bound.centerX();
centerY = bound.centerY();
}
public float getOuterRadius(){
return mOuterRadius;
}
public float getInnerRadius(){
return mInnerRadius;
}
public float getScreenHeight(){
return screen_height;
}
public static void setDefaultChakra(String[] swaras){
defaultChakra = swaras;
nArcs = defaultChakra.length;
}
public static int getNArcs(){
return nArcs;
}
public void setArc(int region){
if(region != arc){
arc = region;
invalidate();
}
}
public void setCurrentKey(KeyAttr currentKey){
this.currentKey = currentKey;
}
public void setKeyLabel(String label){
keyLabel = label;
}
public void desetArc(){
arc = -1;
invalidate();
}
@SuppressLint("NewApi")
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
canvas.drawCircle(centerX, centerY, mOuterRadius, mBlackPaint);
float anglePerArc = (float) (360.0/nArcs);
Paint arcPaint;
for(int i =0; i< nArcs; i++){
arcPaint = mArcPaint;
if(i == arc){arcPaint = mArcPrevPaint;}
//arcs
canvas.drawArc(bound, getMidAngle(i) - anglePerArc/2, anglePerArc-1, true, arcPaint);
//arc seperators
canvas.drawArc(bound, getMidAngle(i) + anglePerArc/2 -1, 1, true, mArcDividerPaint);
}
canvas.drawCircle(centerX, centerY, mInnerRadius, mInnerPaint);
drawLetters(canvas);
}
private void drawLetters(Canvas canvas) {
float offsetY = 0;
Rect textBounds = new Rect();
mInnerTextPaint.getTextBounds(getText(), 0, getText().length(), textBounds);
offsetY = (textBounds.bottom - textBounds.top)/2;
canvas.drawText(getText(), centerX, centerY + offsetY, mInnerTextPaint);
for(int i = 0; i<nArcs; i++){
PointF textPos = getArcTextPoint(i);
canvas.drawText(getTextForArc(i), textPos.x, textPos.y, mArcTextPaint);
}
}
@Override
protected void onMeasure(int measuredWidth, int measuredHeight){
setMeasuredDimension((int)(4*mOuterRadius),(int)(4*mOuterRadius));
}
public static void setHalantExists(boolean b){
halantExists = b;
}
public boolean isHalant(){
boolean thisIsHalant = !currentKey.showCustomChakra;
return (arc == 0) && halantExists && thisIsHalant;
}
public float getMidAngle(int region){
float anglePerArc = (float) (360.0/nArcs);
float offset = -90;
float midAngle = region*anglePerArc + offset;
return midAngle;
}
private PointF getArcTextPoint(int region){
PointF textPos = new PointF();
Rect textBounds = new Rect();
String text = getTextForArc(region);
mArcTextPaint.getTextBounds(text, 0, text.length(), textBounds);
float offsetX = 0;
float offsetY = 0;
offsetY = (textBounds.bottom - textBounds.top)/2;
float angleRad = (float) Math.toRadians(getMidAngle(region));
textPos.x = centerX + (float) (mArcTextRadius*Math.cos(angleRad)) + offsetX;
textPos.y = centerY + (float) (mArcTextRadius*Math.sin(angleRad)) + offsetY;
return textPos;
}
public String getText() {
if(arc < 0){
return keyLabel;
}
return getTextForArc(arc);
}
public String getTextForArc(int region){
String[] chakra = defaultChakra;
if(currentKey.showCustomChakra){
chakra = currentKey.customChakraLayout;
return chakra[region];
}
if(chakra[region]!="") {
String text = keyLabel + chakra[region];
return text;
}else{
String text = chakra[region];
return text;
}
}
}
|
package DesignPatterns.AbstractFactoryPattern;
public class ConcreteProductC1 implements ProductC {
@Override
public void ccc() {
System.out.println("AFP ConcreteProductC1 ccc");
}
}
|
package net.xiaolanglang.web;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import java.io.FileInputStream;
/**
* 测试的基本类
* Created by gaoyang on 14/11/21.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:TestSpringConfig.xml","classpath:TestSpringMVC.xml"})
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
@WebAppConfiguration
public abstract class TestBase {
protected JdbcDatabaseTester databaseTester;
@Before
public void setUp() throws Exception {
databaseTester = new JdbcDatabaseTester("org.hsqldb.jdbcDriver",
"jdbc:hsqldb:mem:testDb;shutdown=true", "SA", "");
IDataSet dataSet = new FlatXmlDataSetBuilder().build(new FileInputStream("src/test/resources/dataSet.xml"));
databaseTester.setDataSet(dataSet);
databaseTester.onSetup();
}
@After
public void tearDown() throws Exception {
databaseTester.onTearDown();
}
}
|
package com.tripper;
import com.google.maps.model.PlacesSearchResult;
public class LocationItem {
private boolean isSelected;
private PlacesSearchResult placesSearchResult;
public LocationItem(PlacesSearchResult placesSearchResult){
this.placesSearchResult = placesSearchResult;
this.isSelected = false;
}
public PlacesSearchResult getPlacesSearchResult() {
return this.placesSearchResult;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
this.isSelected = selected;
}
} |
package com.icanit.app.bmap;
import java.util.ArrayList;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.PoiOverlay;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPoiInfo;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.icanit.app.R;
/**public class MyMKSearchListener implements MKSearchListener,OnClickListener {
private MapView map;
private MapController controller;
private BMapActivity activity;
private MKSearch search;
private PoiOverlay overlay;
public CommunityBoundOverlay cbo;
public View popView;
public TextView merName,addr,phoneNo;
private String uid;
public MyMKSearchListener(MapView map,BMapActivity activity,MKSearch search,CommunityBoundOverlay cbo){
this.map=map;controller=map.getController();
this.activity=activity;this.search=search;
// this.cbo=cbo;popView=LayoutInflater.from(activity).inflate(R.layout.popview_bmap, map,false);
map.addView(popView);popView.setVisibility(View.GONE);
merName=(TextView)popView.findViewById(R.id.textView1);
addr=(TextView)popView.findViewById(R.id.textView2);
phoneNo=(TextView)popView.findViewById(R.id.textView3);
merName.setOnClickListener(this);
}
public void onGetAddrResult(MKAddrInfo info, int error) {
Log.w("MKSearchInfo","@MyMKSearchListener onGetAddrResult,\n" +
"errorCode:"+error+",info:"+info);
if(info==null||error!=0)return;
controller.setCenter(info.geoPt);
activity.centerPoint=info.geoPt;
controller.setZoom(16);
map.getOverlays().add(cbo);
cbo.setDistance(1000);
cbo.setGp(info.geoPt);
map.invalidate();
}
public void onGetBusDetailResult(MKBusLineResult result, int error) {
Log.w("MKSearchInfo","@MyMKSearchListener onGetBusDetailResult,\n" +
"errorCode:"+error+",result:"+result);
}
public void onGetDrivingRouteResult(MKDrivingRouteResult result, int error) {
Log.w("MKSearchInfo","@MyMKSearchListener onGetDrivingRouteResult,\n" +
"errorCode:"+error+",result:"+result);
}
public void onGetPoiDetailSearchResult(int type, int error) {
Log.w("MKSearchInfo","@MyMKSearchListener onGetPoiDetailSearchResult,\n" +
"errorCode:"+error+",type:"+type);
}
public void onGetPoiResult(MKPoiResult result, int type, int error) {
Log.w("MKSearchInfo","@MyMKSearchListener onGetPoiResult,\n" +
"errorCode:"+error+",result:"+result+",type:"+type);
Log.w("mapInfo","@itemizedMapActivity onGetPoiResult,"+type+","+error+","+result);
if(result==null||error!=0)return;
final ArrayList<MKPoiInfo> pois=result.getAllPoi();
map.getOverlays().remove(overlay);
// overlay = new PoiOverlay(activity, map){
// protected boolean onTap(int arg0) {
// MKPoiInfo info = pois.get(arg0);
// uid=info.uid;
// map.updateViewLayout(popView, new MapView.LayoutParams(LayoutParams.WRAP_CONTENT,
// LayoutParams.WRAP_CONTENT,info.pt,MapView.LayoutParams.BOTTOM_CENTER));
// popView.setVisibility(View.VISIBLE);
// merName.setText(info.name);
// addr.setText("µØÖ·£º"+info.address);
// addr.setText("µç»°£º"+info.phoneNum);
// return true;
// }
// public boolean onTap(GeoPoint arg0, MapView arg1) {
// Log.d("mapInfo","@MYMKSearchListener onGeoPoiResul onTap");
// popView.setVisibility(View.GONE);
// return super.onTap(arg0, arg1);
// }
// };
overlay.setData(pois);
map.getOverlays().add(overlay);
map.invalidate();
}
public void onGetRGCShareUrlResult(String result, int error) {
Log.w("MKSearchInfo","@MyMKSearchListener onGetRGCShareUrlResult,\n" +
"errorCode:"+error+",result:"+result);
}
public void onGetSuggestionResult(MKSuggestionResult result, int error) {
Log.w("MKSearchInfo","@MyMKSearchListener onGetSuggestionResult,\n" +
"errorCode:"+error+",result:"+result);
}
public void onGetTransitRouteResult(MKTransitRouteResult result, int error) {
Log.w("MKSearchInfo","@MyMKSearchListener onGetTransitRouteResult,\n" +
"errorCode:"+error+",result:"+result);
}
public void onGetWalkingRouteResult(MKWalkingRouteResult result, int error) {
Log.w("MKSearchInfo","@MyMKSearchListener onGetWalkingRouteResult,\n" +
"errorCode:"+error+",result:"+result);
}
@Override
public void onClick(View v) {
search.poiDetailSearch(uid);
}
}
*/ |
package br.com.secia.apisecia.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@AllArgsConstructor
@Setter
@Getter
public class PrioritiesDto {
private Integer quantidadeUrgente;
private Integer quantidadeAlta;
private Integer quantidadeMedia;
private Integer quantidadeBaixa;
}
|
package com.gxjtkyy.standardcloud.admin.domain.vo;
import com.gxjtkyy.standardcloud.common.domain.vo.BaseVO;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Date;
/**
* @Package com.gxjtkyy.standardcloud.admin.domain.vo.request
* @Author lizhenhua
* @Date 2018/6/27 13:00
*/
@Setter
@Getter
@ToString(callSuper = true)
public class TemplateVO extends BaseVO{
/**id*/
private String id;
/**模板名称*/
private String templateName;
/**文档类型*/
private Integer docType;
/**模板描述*/
private String templateDesc;
/**创建时间*/
private Date createTime;
/**更新时间*/
private Date updateTime;
}
|
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.business;
import java.util.List;
public interface CRUDService<PK, MODEL> {
List<MODEL> findAll() throws BusinessException;
DataTablesResponse<MODEL> findAllPaginated(DataTablesRequest dataTableRequestGrid) throws BusinessException;
void create(MODEL model) throws BusinessException;
MODEL findByPK(PK pk) throws BusinessException;
void update(MODEL model) throws BusinessException;
void delete(MODEL model) throws BusinessException;
}
|
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class CogwheelComponent extends CommonPageObject {
private static final String LOG_OUT_BUTTON = "//*[text()=\"Logout\"]";
@FindBy(how = How.XPATH, using = LOG_OUT_BUTTON)
private WebElement logOutButton;
public CogwheelComponent(WebDriver driver, WebElement element) {
super(driver);
}
public void clickOnLogOutButton() {
logOutButton.click();
}
} |
package com.git.cloud.resmgt.common.dao;
import java.util.List;
import com.git.cloud.common.dao.ICommonDAO;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.resmgt.common.model.po.CmPasswordPo;
public interface ICmPasswordDAO extends ICommonDAO{
/**
* 批量插入设备密码信息
* @Title: insertCmPassword
* @Description: TODO
* @field: @param pwdList
* @field: @throws RollbackableBizException
* @return void
* @throws
*/
public void insertCmPassword(List<CmPasswordPo> pwdList) throws RollbackableBizException;
/**
*
* @Title: insertCmPassword
* @Description: 插入密码信息
* @field: @param cmPasswordPo
* @field: @throws RollbackableBizException
* @return void
* @throws
*/
public void insertCmPassword(CmPasswordPo cmPasswordPo) throws RollbackableBizException;
/**
*
* @Title: updateCmPassword
* @Description: 更新密码信息
* @field: @param cmPasswordPo
* @field: @throws RollbackableBizException
* @return void
* @throws
*/
public void updateCmPassword(CmPasswordPo cmPasswordPo) throws RollbackableBizException;
/**
* 根据资源Id获取密码对象
* @Title: findCmPasswordByResourceId
* @Description: TODO
* @field: @param resourceId
* @field: @return
* @field: @throws RollbackableBizException
* @return CmPasswordPo
* @throws
*/
public CmPasswordPo findCmPasswordByResourceId(String resourceId) throws RollbackableBizException;
/**
* 根据资源Id和用户名,获取密码
* @Title: findCmPasswordByResourceId
* @Description: TODO
* @field: @param resourceId
* @field: @param userName
* @field: @return
* @field: @throws RollbackableBizException
* @return CmPasswordPo
* @throws
*/
public CmPasswordPo findCmPasswordByResourceId(String resourceId, String userName) throws RollbackableBizException;
/**
* @Title: findCmPasswordByResourceUser
* @Description: 根据资源ID和登陆用户获取密码信息
* @field: @param resourceId
* @field: @param userName
* @field: @return
* @field: @throws RollbackableBizException
* @return CmPasswordPo
* @throws
*/
public CmPasswordPo findCmPasswordByResourceUser(String resourceId,
String userName) throws RollbackableBizException;
public void deleteCmPassword(String resourceId) throws RollbackableBizException;
}
|
package com.mirri.mirribilandia.ui.chat;
import android.util.Log;
public class ChatMessage {
boolean left;
String message;
String id;
String orario;
public ChatMessage(boolean left, String message, String id, String orario) {
super();
this.left = left;
this.message = message;
this.id = id;
this.orario = convertDate(orario);
}
private String convertDate(String date) {
String[] separated = date.split(" ");
String hour = separated[1].substring(0,5);
return hour;
}
}
|
package br.edu.horus.bancodadosII;
import java.sql.ResultSet;
import org.junit.Test;
public class TrabalhoAgregacao extends BaseTest{
/*
* 1- Listar id, primeiro nome, e quantidade de pedidos efetuados pelos clientes
* que tem o nome iniciando pela letra A em ordem alfabética.
*
* -> para a quantidade de pedidos necessita fazer um count
*/
@Test
public void testListarQuantidadeDePedidosClienteIniciamComA() throws Exception{
ResultSet r = connection.createStatement().executeQuery(
"SELECT customers.id, customers.first_name, customers.last_name, invoices.total FROM customers " +
" INNER JOIN invoices ON customers.id = invoices.customer_id WHERE"+
" customers.first_name LIKE 'A%' ORDER BY customers.first_name"
);
while (r.next()) {
System.out.println(r.getInt(1) + " " +r.getString(2) + " " + r.getString(3) + " "
+ r.getDouble(4) );
}
}
/*
* 2 - Listar id cliente, nome cliente, id pedido, total do pedido para os 3 pedidos com os maiores
* valores totais efetuados para a cidade chamada Seattle.
*/
@Test
public void test3MaioresPedidosEmSeatle() throws Exception{
ResultSet r = connection.createStatement().executeQuery(
"SELECT customers.id, customers.first_name, invoices.id, invoices.total"+
" FROM customers" +
" INNER JOIN invoices ON invoices.customer_id = customers.id"
+ " WHERE customers.city='Seattle' ORDER BY invoices.total DESC LIMIT 3"
);
while (r.next()) {
System.out.println(r.getInt(1)+ " " + r.getString(2) + " "
+ r.getInt(3) + " " + r.getDouble(4));
}
}
/*
* 3 - Listar o id do produto, nome do produto, e valor total(item.quantidade X produto.preço)
* em todos os pedidos em que ele foi mencionado.
*
* -< esqueceu de multiplicar o items.quantity pelo products.price antes do sum, mas considerei certa
*/
@Test
public void testValorTotalDePedidosDeCadaProduto() throws Exception{
ResultSet r = connection.createStatement().executeQuery(
"select products.id, products.name, sum(items.quantity) from invoices"+
" inner join items on items.invoice_id = invoices.id " +
"inner join products on products.id=items.product_id "
+ "where invoices.total <> 0 group by products.id order by products.id");
while (r.next()) {
System.out.println(r.getString(1)+ " " + r.getString(2)+ " " +r.getString(3));
}
}
/*
* 4 - Listar nome do cliente, quantidade dos pedidos, e média do valor dos pedidos por cliente.
*/
@Test
public void testQuantidadePedidosComValorMedio() throws Exception{
ResultSet r = connection.createStatement().executeQuery(
""
);
while (r.next()) {
System.out.println();
}
}
/*
* 5- Listar nome do produto e a média da quantidade vendida por pedido.
*
* -> Interessante fazer o group by pelo id
* -> A quantidade vendida do produto é representado por items.quantity
*/
@Test
public void testQuantidadeMediaProdutoPorPedido() throws Exception{
ResultSet result = connection.createStatement().executeQuery(
"SELECT products.name, AVG(invoices.total) from invoices" +
" INNER JOIN items ON items.invoice_id = invoices.id" +
" INNER JOIN products ON products.id = items.product_id"+
" GROUP BY products.name"
);
while(result.next()){
System.out.println(
" " + result.getString(1) +
" " + result.getInt(2)
);}
}
/*
* 6 - Listar produtos com quantidade total vendida maior que 10, para a rua que contenha
* "Seventh Av." no nome.
*/
@Test
public void testProdutosComMaisDe10ParaSetimaAvenida() throws Exception{
ResultSet r = connection.createStatement().executeQuery(
""
);
while (r.next()) {
System.out.println();
}
}
/*
* 7 - Listar os somente os produtos que ainda não estão relacionados a nenhum pedidos.
*/
@Test
public void testProdutosSemPedido() throws Exception{
ResultSet r = connection.createStatement().executeQuery(
""
);
while (r.next()) {
System.out.println();
}
}
/*
* 8 - Listar somente os clientes que já estão relacionados a algum pedido.
*/
@Test
public void testClientesSemPedido() throws Exception{
ResultSet r = connection.createStatement().executeQuery(
""
);
while (r.next()) {
System.out.println();
}
}
/*
* 9 - Listar nome do cliente e rua quando a cidade for 'New York'.
*/
@Test
public void testClientesDeNewYork() throws Exception{
ResultSet r = connection.createStatement().executeQuery(
"SELECT customers.first_name, customers.last_name, customers.street FROM customers" +
" WHERE customers.city='New York'"
);
while (r.next()) {
System.out.println(r.getString(1) + " "+ r.getString(2) + " " + r.getString(3));
}
}
/*
* 10 - Listar distintamente o nome dos produtos comprados por 'Laura'.
*/
@Test
public void testProdutosCompradosPorLaura() throws Exception{
ResultSet r = connection.createStatement().executeQuery(
""
);
while (r.next()) {
System.out.println();
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package misadminclienturl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* @author user
*/
public class MISADMINclienturl {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
String name;
int age;
int ch=0;
do{
System.out.println("Enter choice\n \t1:Insert\n\t2:Delete\n\t0:EXIT");
ch=Integer.parseInt(obj.readLine());
switch (ch){
case 1:{
name=obj.readLine();
age=Integer.parseInt(obj.readLine());
System.out.println(insertion(name,age));
break;
}
case 2:{
name=obj.readLine();
System.out.println(deletion(name));break;
}
}
}while(ch!=0);
}
private static boolean deletion(java.lang.String name) {
admin.AdminSide_Service service = new admin.AdminSide_Service();
admin.AdminSide port = service.getAdminSidePort();
return port.deletion(name);
}
private static boolean insertion(java.lang.String name, int age) {
admin.AdminSide_Service service = new admin.AdminSide_Service();
admin.AdminSide port = service.getAdminSidePort();
return port.insertion(name, age);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.