blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2
values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 9.45M | extension stringclasses 28
values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e5aa3bd9b806b4d58138852c596a5bf8a875a3f | 08b8d598fbae8332c1766ab021020928aeb08872 | /src/gcom/seguranca/acesso/ControladorAcessoSEJB.java | fbb27b6146b862375530c7ded70826666a07d313 | [] | no_license | Procenge/GSAN-CAGEPA | 53bf9bab01ae8116d08cfee7f0044d3be6f2de07 | dfe64f3088a1357d2381e9f4280011d1da299433 | refs/heads/master | 2020-05-18T17:24:51.407985 | 2015-05-18T23:08:21 | 2015-05-18T23:08:21 | 25,368,185 | 3 | 1 | null | null | null | null | WINDOWS-1252 | Java | false | false | 158,912 | java | /*
* Copyright (C) 2007-2007 the GSAN – Sistema Integrado de Gestão de Serviços de Saneamento
*
* This file is part of GSAN, an integrated service management system for Sanitation
*
* GSAN 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 2 of the License.
*
* GSAN 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, write to the Free Software
* Foundation, Inc., 59 Temple Place – Suite 330, Boston, MA 02111-1307, USA
*/
/*
* GSAN – Sistema Integrado de Gestão de Serviços de Saneamento
* Copyright (C) <2007>
* Adriano Britto Siqueira
* Alexandre Santos Cabral
* Ana Carolina Alves Breda
* Ana Maria Andrade Cavalcante
* Aryed Lins de Araújo
* Bruno Leonardo Rodrigues Barros
* Carlos Elmano Rodrigues Ferreira
* Cláudio de Andrade Lira
* Denys Guimarães Guenes Tavares
* Eduardo Breckenfeld da Rosa Borges
* Fabíola Gomes de Araújo
* Flávio Leonardo Cavalcanti Cordeiro
* Francisco do Nascimento Júnior
* Homero Sampaio Cavalcanti
* Ivan Sérgio da Silva Júnior
* José Edmar de Siqueira
* José Thiago Tenório Lopes
* Kássia Regina Silvestre de Albuquerque
* Leonardo Luiz Vieira da Silva
* Márcio Roberto Batista da Silva
* Maria de Fátima Sampaio Leite
* Micaela Maria Coelho de Araújo
* Nelson Mendonça de Carvalho
* Newton Morais e Silva
* Pedro Alexandre Santos da Silva Filho
* Rafael Corrêa Lima e Silva
* Rafael Francisco Pinto
* Rafael Koury Monteiro
* Rafael Palermo de Araújo
* Raphael Veras Rossiter
* Roberto Sobreira Barbalho
* Rodrigo Avellar Silveira
* Rosana Carvalho Barbosa
* Sávio Luiz de Andrade Cavalcante
* Tai Mu Shih
* Thiago Augusto Souza do Nascimento
* Tiago Moreno Rodrigues
* Vivianne Barbosa Sousa
*
* Este programa é software livre; você pode redistribuí-lo e/ou
* modificá-lo sob os termos de Licença Pública Geral GNU, conforme
* publicada pela Free Software Foundation; versão 2 da
* Licença.
* Este programa é distribuído na expectativa de ser útil, mas SEM
* QUALQUER GARANTIA; sem mesmo a garantia implícita de
* COMERCIALIZAÇÃO ou de ADEQUAÇÃO A QUALQUER PROPÓSITO EM
* PARTICULAR. Consulte a Licença Pública Geral GNU para obter mais
* detalhes.
* Você deve ter recebido uma cópia da Licença Pública Geral GNU
* junto com este programa; se não, escreva para Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307, USA.
*
* GSANPCG
* Eduardo Henrique
*/
package gcom.seguranca.acesso;
import gcom.batch.FiltroFuncionalidadeIniciada;
import gcom.batch.FuncionalidadeIniciada;
import gcom.cadastro.imovel.Imovel;
import gcom.cadastro.localidade.*;
import gcom.cadastro.sistemaparametro.SistemaParametro;
import gcom.fachada.Fachada;
import gcom.interceptor.RegistradorOperacao;
import gcom.seguranca.acesso.usuario.*;
import gcom.seguranca.transacao.FiltroTabelaColuna;
import gcom.seguranca.transacao.Tabela;
import gcom.seguranca.transacao.TabelaColuna;
import gcom.util.*;
import gcom.util.email.ErroEmailException;
import gcom.util.email.ServicosEmail;
import gcom.util.filtro.*;
import gcom.util.parametrizacao.ParametroGeral;
import gcom.util.parametrizacao.batch.ParametroBatch;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.ejb.CreateException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import org.hibernate.HibernateException;
import org.hibernate.Session;
/**
* Definição da lógica de negócio do Session Bean de ControladorCliente
*
* @author Sávio Luiz
* @created 25 de Abril de 2005
*/
/**
* Descrição da classe
*
* @author Administrador
* @date 04/07/2006
*/
public class ControladorAcessoSEJB
implements SessionBean {
private static final long serialVersionUID = 1L;
SessionContext sessionContext;
private IRepositorioAcesso repositorioAcesso;
/**
* < <Descrição do método>>
*
* @exception CreateException
* Descrição da exceção
*/
public void ejbCreate() throws CreateException{
repositorioAcesso = RepositorioAcessoHBM.getInstancia();
}
/**
* < <Descrição do método>>
*/
public void ejbRemove(){
}
/**
* < <Descrição do método>>
*/
public void ejbActivate(){
}
/**
* < <Descrição do método>>
*/
public void ejbPassivate(){
}
/**
* Seta o valor de sessionContext
*
* @param sessionContext
* O novo valor de sessionContext
*/
public void setSessionContext(SessionContext sessionContext){
this.sessionContext = sessionContext;
}
/**
* Método que consulta todas as TabelaColunas que estejam ligadas a uma
* Operacao
*
* @author Thiago Toscano
* @date 23/03/2006
* @return
* @throws ControladorException
*/
public Collection getTabelaColunaPertencenteOperacao() throws ControladorException{
// cria a coleção de retorno
Collection retorno = null;
// obtém a sessão
Session session = HibernateUtil.getSession();
try{
FiltroTabelaColuna filtroTabelaColuna = new FiltroTabelaColuna();
filtroTabelaColuna.adicionarCaminhoParaCarregamentoEntidade(FiltroTabelaColuna.TABELA);
// pesquisa a coleção de atividades e atribui a variável "retorno"
retorno = GeradorHQLCondicional.gerarCondicionalQuery(
filtroTabelaColuna,
"gcom.seguranca.transacao.TabelaColuna",
"tabelaColuna",
" select tabelaColuna "
+ " from TabelaColuna as tabelaColuna "
+ PersistenciaUtil.processaObjetosParaCarregamentoJoinFetch("tabelaColuna", filtroTabelaColuna
.getColecaoCaminhosParaCarregamentoEntidades())
+ " where tabelaColuna in ( select operacao.tabelaColuna "
+ " from Operacao as operacao " + " where operacao.tabelaColuna is not null)" + "",
session).list();
// Carrega os objetos informados no filtro
/*
* if (!filtroTabelaColuna
* .getColecaoCaminhosParaCarregamentoEntidades().isEmpty()) {
* PersistenciaUtil.processaObjetosParaCarregamento(
* filtroTabelaColuna
* .getColecaoCaminhosParaCarregamentoEntidades(), retorno); }
*/
// erro no hibernate
}catch(ErroRepositorioException e){
// levanta a exceção para a próxima camada
throw new ControladorException("Erro no Hibernate", e);
}catch(HibernateException e){
// levanta a exceção para a próxima camada
throw new ControladorException("Erro no Hibernate", e);
}finally{
// fecha a sessão
HibernateUtil.closeSession(session);
}
return retorno;
}
/**
* Método que pesquisa todas as tabelas colunas que tem ligacao com operacao
* pela operacao tabela
*
* @author thiago toscano
* @date 23/03/2006
* @param idOperacao
* @return
* @throws ControladorException
*/
public Collection getTabelaColunaDasOperacaoTabela(Integer idOperacao) throws ControladorException{
// cria a coleção de retorno
Collection retorno = null;
// obtém a sessão
Session session = HibernateUtil.getSession();
try{
// FiltroTabelaColuna filtroTabelaColuna = new FiltroTabelaColuna();
// filtroTabelaColuna.adicionarCaminhoParaCarregamentoEntidade(FiltroTabelaColuna.TABELA);
// filtroOperacao.adicionarCaminhoParaCarregamentoEntidade(FiltroOperacao.TABELA_COLUNA);
FiltroOperacaoTabela filtroOperacaoTabela = new FiltroOperacaoTabela();
// pesquisa a coleção de atividades e atribui a variável "retorno"
retorno = GeradorHQLCondicional.gerarCondicionalQuery(
filtroOperacaoTabela,
"gcom.seguranca.acesso.OperacaoTabela",
"operacaoTabela",
" select distinct operacaoTabela.tabela.tabelaColunas "
+ " from OperacaoTabela as operacaoTabela "
+ PersistenciaUtil.processaObjetosParaCarregamentoJoinFetch("operacaoTabela",
filtroOperacaoTabela.getColecaoCaminhosParaCarregamentoEntidades())
+ " inner join operacaoTabela.operacao as operacao "
+ " inner join operacaoTabela.tabela as tabela " + " inner join tabela.tabelaColunas as tc "
+ " where operacaoTabela.operacao.id = " + idOperacao + "", session).list();
// Carrega os objetos informados no filtro
/*
* if (!filtroOperacaoTabela
* .getColecaoCaminhosParaCarregamentoEntidades().isEmpty()) {
* PersistenciaUtil.processaObjetosParaCarregamento(
* filtroOperacaoTabela
* .getColecaoCaminhosParaCarregamentoEntidades(), retorno); }
*/
// erro no hibernate
}catch(ErroRepositorioException e){
// levanta a exceção para a próxima camada
throw new ControladorException("Erro no Hibernate", e);
}catch(HibernateException e){
// levanta a exceção para a próxima camada
throw new ControladorException("Erro no Hibernate", e);
}finally{
// fecha a sessão
HibernateUtil.closeSession(session);
}
return retorno;
}
/**
* Retorna o valor de controladorUtil
*
* @return O valor de controladorUtil
*/
private ControladorUtilLocal getControladorUtil(){
ControladorUtilLocalHome localHome = null;
ControladorUtilLocal local = null;
// pega a instância do ServiceLocator.
ServiceLocator locator = null;
try{
locator = ServiceLocator.getInstancia();
localHome = (ControladorUtilLocalHome) locator.getLocalHome(ConstantesJNDI.CONTROLADOR_UTIL_SEJB);
// guarda a referencia de um objeto capaz de fazer chamadas à
// objetos remotamente
local = localHome.create();
return local;
}catch(CreateException e){
throw new SistemaException(e);
}catch(ServiceLocatorException e){
throw new SistemaException(e);
}
}
/**
* Retorna a interface remota de ControladorParametro
*
* @return A interface remota do controlador de parâmetro
*/
private ControladorUsuarioLocal getControladorUsuario(){
ControladorUsuarioLocalHome localHome = null;
ControladorUsuarioLocal local = null;
// pega a instância do ServiceLocator.
ServiceLocator locator = null;
try{
locator = ServiceLocator.getInstancia();
localHome = (ControladorUsuarioLocalHome) locator.getLocalHome(ConstantesJNDI.CONTROLADOR_USUARIO_SEJB);
// guarda a referencia de um objeto capaz de fazer chamadas à
// objetos remotamente
local = localHome.create();
return local;
}catch(CreateException e){
throw new SistemaException(e);
}catch(ServiceLocatorException e){
throw new SistemaException(e);
}
}
/**
* [UC0280] Inserir Funcionalidade
* Metodo que verifica os dados da tabela e inseri a funcionalidade
*
* @author Rômulo Aurélio
* @date 28/04/2006
* @param funcionalidade
* @throws ControladorException
*/
public Integer inserirFuncionalidade(Funcionalidade funcionalidade, Collection colecaoFuncionalidadeDependencia)
throws ControladorException{
// Verifica se todos os campos obrigatorios foram preenchidos
if((funcionalidade.getDescricao() == null || funcionalidade.getDescricao().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO))
&& (funcionalidade.getDescricaoAbreviada() == null || funcionalidade.getDescricaoAbreviada().equals(
"" + ConstantesSistema.NUMERO_NAO_INFORMADO))
&& (funcionalidade.getCaminhoMenu() == null || funcionalidade.getCaminhoMenu().equals(
"" + ConstantesSistema.NUMERO_NAO_INFORMADO))
&& (funcionalidade.getCaminhoMenu() == null || funcionalidade.getCaminhoMenu().equals(
"" + ConstantesSistema.NUMERO_NAO_INFORMADO))){
throw new ControladorException("atencao.filtro.nenhum_parametro_informado");
}
// Verifica se o campo Descrição foi preenchido
if(funcionalidade.getDescricao() == null || funcionalidade.getDescricao().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, " Descrição");
}
// Verifica se o campo DescricaoAbreviada foi preenchido
if(funcionalidade.getDescricaoAbreviada() == null
|| funcionalidade.getDescricaoAbreviada().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, "Descrição Abreviada");
}
// Verifica se o campo CaminhoMenu foi preenchido
if(funcionalidade.getCaminhoMenu() == null || funcionalidade.getCaminhoMenu().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, "Caminho Menu");
}
// Verifica se o campo CaminhoURL foi preenchido
if(funcionalidade.getCaminhoUrl() == null || funcionalidade.getCaminhoUrl().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, "Caminho URL");
}
// Verifica se o campo IndicadorPontoEntrada foi preenchido
if(funcionalidade.getIndicadorPontoEntrada() == null
|| funcionalidade.getIndicadorPontoEntrada().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, " Ponto de Entrada");
}
// Verifica se o campo Modulo foi preenchido
if(funcionalidade.getModulo() == null || funcionalidade.getModulo().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.naoinformado", null, "Módulo");
}
FiltroFuncionalidade filtroFuncionalidade = new FiltroFuncionalidade();
filtroFuncionalidade.adicionarParametro(new ParametroSimples(FiltroFuncionalidade.DESCRICAO, funcionalidade.getDescricao()));
Collection colecaoFuncionalidade = getControladorUtil().pesquisar(filtroFuncionalidade, Funcionalidade.class.getName());
if(colecaoFuncionalidade != null && !colecaoFuncionalidade.isEmpty()){
throw new ControladorException("atencao.descricao_ja_existente", null, "" + funcionalidade.getDescricao() + "");
}
funcionalidade.setUltimaAlteracao(new Date());
Integer idFuncionalidade = (Integer) getControladorUtil().inserir(funcionalidade);
if(colecaoFuncionalidadeDependencia != null && !colecaoFuncionalidadeDependencia.isEmpty()){
Iterator iterator = colecaoFuncionalidadeDependencia.iterator();
while(iterator.hasNext()){
FuncionalidadeDependencia funcionalidadeDependencia = new FuncionalidadeDependencia();
Funcionalidade funcionalidadeInserir = (Funcionalidade) iterator.next();
funcionalidadeDependencia.setFuncionalidade(funcionalidadeInserir);
FuncionalidadeDependenciaPK funcionalidadeDependenciaPK = new FuncionalidadeDependenciaPK();
funcionalidadeDependenciaPK.setFuncionalidadeDependenciaId(funcionalidadeDependencia.getFuncionalidade().getId());
funcionalidadeDependenciaPK.setFuncionalidadeId(funcionalidade.getId());
funcionalidadeDependencia.setComp_id(funcionalidadeDependenciaPK);
this.getControladorUtil().inserir(funcionalidadeDependencia);
}
}
return idFuncionalidade;
}
/**
* [UC0281] Manter Funcionalidade [SB0001] Atualizar Funcionalidade Metodo
* que atualiza a funcionalidade
*
* @author Rômulo Aurélio
* @date 17/05/2006
* @param funcionalidade
* @throws ControladorException
*/
public void atualizarFuncionalidade(Funcionalidade funcionalidade, Collection colecaoFuncionalidadeDependencia)
throws ControladorException{
// Verifica se todos os campos obrigatorios foram preenchidos
if((funcionalidade.getDescricao() == null || funcionalidade.getDescricao().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO))
&& (funcionalidade.getDescricaoAbreviada() == null || funcionalidade.getDescricaoAbreviada().equals(
"" + ConstantesSistema.NUMERO_NAO_INFORMADO))
&& (funcionalidade.getCaminhoMenu() == null || funcionalidade.getCaminhoMenu().equals(
"" + ConstantesSistema.NUMERO_NAO_INFORMADO))
&& (funcionalidade.getCaminhoMenu() == null || funcionalidade.getCaminhoMenu().equals(
"" + ConstantesSistema.NUMERO_NAO_INFORMADO))){
throw new ControladorException("atencao.filtro.nenhum_parametro_informado");
}
// Verifica se o campo Descrição foi preenchido
if(funcionalidade.getDescricao() == null || funcionalidade.getDescricao().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, " Descrição");
}
// Verifica se o campo DescricaoAbreviada foi preenchido
if(funcionalidade.getDescricaoAbreviada() == null
|| funcionalidade.getDescricaoAbreviada().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, "Descrição Abreviada");
}
// Verifica se o campo CaminhoMenu foi preenchido
if(funcionalidade.getCaminhoMenu() == null || funcionalidade.getCaminhoMenu().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, "Caminho Menu");
}
// Verifica se o campo CaminhoURL foi preenchido
if(funcionalidade.getCaminhoUrl() == null || funcionalidade.getCaminhoUrl().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, "Caminho URL");
}
// Verifica se o campo IndicadorPontoEntrada foi preenchido
if(funcionalidade.getIndicadorPontoEntrada() == null
|| funcionalidade.getIndicadorPontoEntrada().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, " Ponto de Entrada");
}
// [FS0003] - Atualização realizada por outro usuário
FiltroFuncionalidade filtroFuncionalidade = new FiltroFuncionalidade();
filtroFuncionalidade.adicionarParametro(new ParametroSimples(FiltroFuncionalidade.ID, funcionalidade.getId()));
Collection colecaoFuncionalidadeBase = getControladorUtil().pesquisar(filtroFuncionalidade, Funcionalidade.class.getName());
if(colecaoFuncionalidadeBase == null || colecaoFuncionalidadeBase.isEmpty()){
sessionContext.setRollbackOnly();
throw new ControladorException("atencao.atualizacao.timestamp");
}
Funcionalidade funcionalidadeBase = (Funcionalidade) colecaoFuncionalidadeBase.iterator().next();
if(funcionalidadeBase.getUltimaAlteracao().after(funcionalidade.getUltimaAlteracao())){
sessionContext.setRollbackOnly();
throw new ControladorException("atencao.atualizacao.timestamp");
}
filtroFuncionalidade.limparListaParametros();
// Verifica se o campo Modulo foi preenchido
if(funcionalidade.getModulo() == null || funcionalidade.getModulo().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.naoinformado", null, "Módulo");
}
String descFuncionalidadeNaBase = funcionalidadeBase.getDescricao();
if(!funcionalidade.getDescricao().equalsIgnoreCase(descFuncionalidadeNaBase)){
filtroFuncionalidade.adicionarParametro(new ParametroSimples(FiltroFuncionalidade.DESCRICAO, funcionalidade.getDescricao()));
Collection colecaoFuncionalidade = getControladorUtil().pesquisar(filtroFuncionalidade, Funcionalidade.class.getName());
if(colecaoFuncionalidade != null && !colecaoFuncionalidade.isEmpty()){
throw new ControladorException("atencao.descricao_ja_existente", null, "" + funcionalidade.getDescricao() + "");
}
}
funcionalidade.setUltimaAlteracao(new Date());
getControladorUtil().atualizar(funcionalidade);
FiltroFuncionalidadeDependencia filtroFuncionalidadeDependencia = new FiltroFuncionalidadeDependencia();
filtroFuncionalidadeDependencia.adicionarParametro(new ParametroSimples(FiltroFuncionalidadeDependencia.FUNCIONALIDADE_ID,
funcionalidade.getId()));
Collection colecaoFuncionalidadeDependenciaBase = getControladorUtil().pesquisar(filtroFuncionalidadeDependencia,
FuncionalidadeDependencia.class.getName());
if(colecaoFuncionalidadeDependenciaBase != null && !colecaoFuncionalidadeDependenciaBase.isEmpty()){
Iterator colecaoFuncionalidadeDependenciaBaseIterator = colecaoFuncionalidadeDependenciaBase.iterator();
while(colecaoFuncionalidadeDependenciaBaseIterator.hasNext()){
FuncionalidadeDependencia funcionalidadeDependenciaBase = (FuncionalidadeDependencia) colecaoFuncionalidadeDependenciaBaseIterator
.next();
getControladorUtil().remover(funcionalidadeDependenciaBase);
}
}
if(colecaoFuncionalidadeDependencia != null && !colecaoFuncionalidadeDependencia.isEmpty()){
Iterator colecaoFuncionalidadeDependenciaIterator = colecaoFuncionalidadeDependencia.iterator();
while(colecaoFuncionalidadeDependenciaIterator.hasNext()){
FuncionalidadeDependencia funcionalidadeDependenciaTela = (FuncionalidadeDependencia) colecaoFuncionalidadeDependenciaIterator
.next();
FuncionalidadeDependencia funcionalidadeDependencia = new FuncionalidadeDependencia();
funcionalidadeDependencia.setFuncionalidade(funcionalidade);
funcionalidadeDependencia.setFuncionalidadeDependencia(funcionalidadeDependenciaTela.getFuncionalidadeDependencia());
FuncionalidadeDependenciaPK funcionalidadeDependenciaPK = new FuncionalidadeDependenciaPK();
funcionalidadeDependenciaPK
.setFuncionalidadeDependenciaId(funcionalidadeDependencia.getFuncionalidadeDependencia().getId());
funcionalidadeDependenciaPK.setFuncionalidadeId(funcionalidade.getId());
funcionalidadeDependencia.setComp_id(funcionalidadeDependenciaPK);
getControladorUtil().inserir(funcionalidadeDependencia);
}
}
}
/**
* [UC0197] Filtrar Operações Efetuadas
*
* @author Saulo Lima
* @date 18/05/2012
* @param
* @throws ControladorException
*/
public Collection<Funcionalidade> pesquisarFuncionalidadesComOperacaoAuditavel() throws ControladorException{
Collection<Funcionalidade> retorno = null;
try{
retorno = repositorioAcesso.pesquisarFuncionalidadesComOperacaoAuditavel();
}catch(ErroRepositorioException e){
e.printStackTrace();
throw new ControladorException("erro.sistema", e);
}
return retorno;
}
/*
* public void inserirOperacao(Operacao operacao, Collection<Tabela>
* colecaoOperacaoTabela) throws ControladorException { // Verifica se todos
* os campos obrigatorios foram preenchidos // Verifica se o campo Descrição
* foi preenchido
* if (funcionalidade.getDescricao() == null ||
* funcionalidade.getDescricao().equals( "" +
* ConstantesSistema.NUMERO_NAO_INFORMADO)) { throw new
* ControladorException("atencao.Informe_entidade", null, " Descrição"); } //
* Verifica se o campo DescricaoAbreviada foi preenchido
* if (funcionalidade.getDescricaoAbreviada() == null ||
* funcionalidade.getDescricaoAbreviada().equals( "" +
* ConstantesSistema.NUMERO_NAO_INFORMADO)) { throw new
* ControladorException("atencao.Informe_entidade", null, "Descrição
* Abreviada"); } // Verifica se o campo CaminhoMenu foi preenchido
* if (funcionalidade.getCaminhoMenu() == null ||
* funcionalidade.getCaminhoMenu().equals( "" +
* ConstantesSistema.NUMERO_NAO_INFORMADO)) { throw new
* ControladorException("atencao.Informe_entidade", null, "Caminho Menu"); } //
* Verifica se o campo CaminhoURL foi preenchido
* if (funcionalidade.getCaminhoUrl() == null ||
* funcionalidade.getCaminhoUrl().equals( "" +
* ConstantesSistema.NUMERO_NAO_INFORMADO)) { throw new
* ControladorException("atencao.Informe_entidade", null, "Caminho URL"); } //
* Verifica se o campo IndicadorPontoEntrada foi preenchido
* if (funcionalidade.getIndicadorPontoEntrada() == null ||
* funcionalidade.getIndicadorPontoEntrada().equals( "" +
* ConstantesSistema.NUMERO_NAO_INFORMADO)) { throw new
* ControladorException("atencao.Informe_entidade", null, " Ponto de
* Entrada"); } // Verifica se o campo Modulo foi preenchido
* if (funcionalidade.getModulo() == null ||
* funcionalidade.getModulo().equals( "" +
* ConstantesSistema.NUMERO_NAO_INFORMADO)) { throw new
* ControladorException("atencao.naoinformado", null, "Módulo"); }
* FiltroFuncionalidade filtroFuncionalidade = new FiltroFuncionalidade();
* filtroFuncionalidade.adicionarParametro(new ParametroSimples(
* FiltroFuncionalidade.DESCRICAO, funcionalidade.getDescricao()));
* filtroFuncionalidade.adicionarParametro(new ParametroSimples(
* FiltroFuncionalidade.DESCRICAO_ABREVIADA, funcionalidade
* .getDescricaoAbreviada()));
* filtroFuncionalidade.adicionarParametro(new ParametroSimples(
* FiltroFuncionalidade.CAMINHO_MENU, funcionalidade .getCaminhoMenu()));
* filtroFuncionalidade.adicionarParametro(new ParametroSimples(
* FiltroFuncionalidade.CAMINHO_URL, funcionalidade .getCaminhoUrl()));
* filtroFuncionalidade.adicionarParametro(new ParametroSimples(
* FiltroFuncionalidade.INDICADOR_PONTO_ENTRADA, funcionalidade
* .getIndicadorPontoEntrada()));
* Collection colecaoFuncionalidade = getControladorUtil().pesquisar(
* filtroFuncionalidade, Funcionalidade.class.getName());
* if (colecaoFuncionalidade != null && !colecaoFuncionalidade.isEmpty()) {
* throw new ControladorException("atencao.descricao_ja_existente", null,
* FiltroFuncionalidade.DESCRICAO); }
* Iterator iterator = colecaoFuncionalidadeDependencia.iterator();
* while (iterator.hasNext()) {
* FuncionalidadeDependencia funcionalidadeDependencia =
* (FuncionalidadeDependencia) iterator .next();
* funcionalidadeDependencia.setFuncionalidade(funcionalidade);
* this.getControladorUtil().inserir(funcionalidadeDependencia); }
* operacao.setUltimaAlteracao(new Date());
* Integer idOperacao = (Integer) getControladorUtil().inserir(operacao);
* operacao.setId(idOperacao);
* for(Tabela tabela : colecaoOperacaoTabela){
* OperacaoTabela operacaoTabela = new OperacaoTabela(new
* OperacaoTabelaPK(idOperacao, tabela.getId()));
* this.getControladorUtil().inserir(operacaoTabela); } }
*/
/**
* Inseri um grupo na base de dados e suas permissões
* [UC0278] Inserir Grupo
*
* @author Pedro Alexandre
* @date 21/07/2006
* @param grupo
* @param colecaoGrupoFuncionalidadeOperacao
* @throws ControladorException
*/
public void inserirGrupo(Grupo grupo, Collection colecaoGrupoFuncionalidadeOperacao) throws ControladorException{
// Seta a data de última alteração do grupo
grupo.setUltimaAlteracao(new Date());
// Inseri o grupo no sistema
getControladorUtil().inserir(grupo);
/*
* Caso o usuário tenha informado alguma permissãopara o grupo inseri as
* permissões do grupo na tabela GrupoFuncionalidadeOperacao
*/
if(colecaoGrupoFuncionalidadeOperacao != null && !colecaoGrupoFuncionalidadeOperacao.isEmpty()){
// Cria o iterator das permissões
Iterator iteratorGrupoFuncionalidadeOperacao = colecaoGrupoFuncionalidadeOperacao.iterator();
// Laço para adicionar as todas as permissões informadas para o
// grupo
while(iteratorGrupoFuncionalidadeOperacao.hasNext()){
// Cria o objeto GrupoFuncionalidadeOperacao que vai representar
// a permissão do grupo
GrupoFuncionalidadeOperacao grupoFuncionalidadeOperacao = (GrupoFuncionalidadeOperacao) iteratorGrupoFuncionalidadeOperacao
.next();
// Seta o grupo inserido na permissão
grupoFuncionalidadeOperacao.setGrupo(grupo);
// Cria a chave para a permissão do grupo
GrupoFuncionalidadeOperacaoPK grupoFuncionalidadeOperacaoPK = new GrupoFuncionalidadeOperacaoPK();
grupoFuncionalidadeOperacaoPK.setFuncionalidadeId(grupoFuncionalidadeOperacao.getFuncionalidade().getId());
grupoFuncionalidadeOperacaoPK.setOperacaoId(grupoFuncionalidadeOperacao.getOperacao().getId());
grupoFuncionalidadeOperacaoPK.setGrupoId(grupoFuncionalidadeOperacao.getGrupo().getId());
// Seta a chave na permissão
grupoFuncionalidadeOperacao.setComp_id(grupoFuncionalidadeOperacaoPK);
// Inseri a permissão do grupo no sistema
getControladorUtil().inserir(grupoFuncionalidadeOperacao);
}
}
}
/**
* Método que atualiza um grupo e seus acessos
* [UC0279] - Manter Grupo
*
* @author Pedro Alexandre
* @date 03/07/2006
* @param grupo
* @param grupoFuncionalidadeOperacao
*/
public void atualizarGrupo(Grupo grupo, Collection colecaoGrupoFuncionalidadeOperacao) throws ControladorException{
/*
* Pesquisa o grupo na base de dados e verifica se o registro não foi
* atualizado por outro usuário durante essa transação
*/
FiltroGrupo filtroGrupo = new FiltroGrupo();
filtroGrupo.adicionarParametro(new ParametroSimples(FiltroGrupo.ID, grupo.getId()));
Collection colecaoGrupo = getControladorUtil().pesquisar(filtroGrupo, Grupo.class.getName());
if(colecaoGrupo != null && !colecaoGrupo.isEmpty()){
// Recupera o grupo na base de dados
Grupo grupoNaBase = (Grupo) colecaoGrupo.iterator().next();
// [FS0004] - Atualização realizada por outro usuário
if(grupoNaBase.getUltimaAlteracao().after(grupo.getUltimaAlteracao())){
sessionContext.setRollbackOnly();
throw new ControladorException("atencao.atualizacao.timestamp");
}
}
/*
* Seta a data da ultima atualização do grupo e atualiza os dados do
* grupo
*/
grupo.setUltimaAlteracao(new Date());
getControladorUtil().atualizar(grupo);
/*
* Cria o filtro para pesquisar as permissões já cadastradas para o
* grupo
*/
FiltroGrupoFuncionalidadeOperacao filtroGrupoFuncionalidadeOperacao = new FiltroGrupoFuncionalidadeOperacao();
filtroGrupoFuncionalidadeOperacao
.adicionarParametro(new ParametroSimples(FiltroGrupoFuncionalidadeOperacao.GRUPO_ID, grupo.getId()));
filtroGrupoFuncionalidadeOperacao.setConsultaSemLimites(true);
Collection colecaoGrupoFuncionalidadeOperacaoCadastradas = getControladorUtil().pesquisar(filtroGrupoFuncionalidadeOperacao,
GrupoFuncionalidadeOperacao.class.getName());
// Caso exista permissões cadastradas para o grupo que está sendo
// atualizado
if(colecaoGrupoFuncionalidadeOperacaoCadastradas != null && !colecaoGrupoFuncionalidadeOperacaoCadastradas.isEmpty()
&& colecaoGrupoFuncionalidadeOperacao != null){
// Cria o iterator das permissões cadastradas para o grupo
Iterator iteratorGrupoFuncionalidadeOperacao = colecaoGrupoFuncionalidadeOperacaoCadastradas.iterator();
// Laço para remover as permissões que foram retiradas pelo usuário
// para o grupo
while(iteratorGrupoFuncionalidadeOperacao.hasNext()){
// Recupera a permissão do grupo do iterator
GrupoFuncionalidadeOperacao grupoFuncionalidadeOperacao = (GrupoFuncionalidadeOperacao) iteratorGrupoFuncionalidadeOperacao
.next();
/*
* Caso a permissão não esteja contida na nova coleção de
* permissões registradas pelo usuário para atualizar o grupo
* Remove as retrições para essa operação e depois remove a
* permissão para a operação
*/
if(!colecaoGrupoFuncionalidadeOperacao.contains(grupoFuncionalidadeOperacao)){
/*
* Cria o filtro para pesquisar se existe alguma restriçaõ
* para essa operação para algum usuário, Setando o código
* do grupo, código da funcionalidade e código da operação
*/
FiltroUsuarioGrupoRestricao filtroUsuarioGrupoRestricao = new FiltroUsuarioGrupoRestricao();
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.GRUPO_ID,
grupoFuncionalidadeOperacao.getGrupo().getId()));
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.FUNCIONALIDADE_ID,
grupoFuncionalidadeOperacao.getFuncionalidade().getId()));
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.OPERACAO_ID,
grupoFuncionalidadeOperacao.getOperacao().getId()));
// Pesquisa as retrições para a operação
Collection<UsuarioGrupoRestricao> restricoes = getControladorUtil().pesquisar(filtroUsuarioGrupoRestricao,
UsuarioGrupoRestricao.class.getName());
/*
* Caso exista restrição para a operação remove as
* restrições para depois remover a permissão para a
* operação
*/
if(restricoes != null && !restricoes.isEmpty()){
// Laço para remover todas as restrições
for(UsuarioGrupoRestricao usuarioGrupoRestricao : restricoes){
getControladorUtil().remover(usuarioGrupoRestricao);
}
}
// Remove a permissão
getControladorUtil().remover(grupoFuncionalidadeOperacao);
}
}
}
/*
* Caso o usuário tenha informado algum acesso para o grupo que está
* sendo atualizado, inseri todos os acessos do grupo informados inserir
* na tabela grupo_funcionalidade_operacao
*/
if(colecaoGrupoFuncionalidadeOperacao != null && !colecaoGrupoFuncionalidadeOperacao.isEmpty()){
// Cria o iterator para as permissões do grupo informadas pelo
// usuário
Iterator iterator = colecaoGrupoFuncionalidadeOperacao.iterator();
while(iterator.hasNext()){
// Recupera a permissão do iterator
GrupoFuncionalidadeOperacao grupoFuncionalidadeOperacao = (GrupoFuncionalidadeOperacao) iterator.next();
grupoFuncionalidadeOperacao.setGrupo(grupo);
// Cria a chave para a permissão
GrupoFuncionalidadeOperacaoPK grupoFuncionalidadeOperacaoPK = new GrupoFuncionalidadeOperacaoPK();
grupoFuncionalidadeOperacaoPK.setFuncionalidadeId(grupoFuncionalidadeOperacao.getFuncionalidade().getId());
grupoFuncionalidadeOperacaoPK.setOperacaoId(grupoFuncionalidadeOperacao.getOperacao().getId());
grupoFuncionalidadeOperacaoPK.setGrupoId(grupoFuncionalidadeOperacao.getGrupo().getId());
// Seta a chave composta na permissão
grupoFuncionalidadeOperacao.setComp_id(grupoFuncionalidadeOperacaoPK);
// Caso a permissão ainda não esteja cadastrada para o grupo
// inseri a permissão para o grupo
if(!colecaoGrupoFuncionalidadeOperacaoCadastradas.contains(grupoFuncionalidadeOperacao)){
getControladorUtil().inserir(grupoFuncionalidadeOperacao);
}
}
}
}
/**
* Remove os grupos selecionados na tela de manter grupo e os
* relacionamentos existentes para o grupo(remove da tabela
* GrupoFuncionalidadeOperacao).
* [UC0279] - Manter Grupo
*
* @author Pedro Alexandre
* @date 29/06/2006
* @param idsGrupos
* @throws ControladorException
*/
public void removerGrupo(String[] idsGrupos) throws ControladorException{
// Laço para remover todos os grupos informados
for(int i = 0; i < idsGrupos.length; i++){
// Verifica se o grupo existe realmente na base
FiltroGrupo filtroGrupo = new FiltroGrupo();
filtroGrupo.adicionarParametro(new ParametroSimples(FiltroGrupo.ID, idsGrupos[i]));
Collection colecaoGrupo = getControladorUtil().pesquisar(filtroGrupo, Grupo.class.getName());
/*
* Caso a pesquisa tenha retornado o grupo remove todas as
* permissões existentes para o grupoe depois remove o grupo do
* sistema
*/
if(colecaoGrupo != null && !colecaoGrupo.isEmpty()){
// Recupera o grupo da coleção
Grupo grupo = (Grupo) colecaoGrupo.iterator().next();
// Pesquisa todos os acessos do grupo
FiltroGrupoFuncionalidadeOperacao filtroGrupoFuncionalidadeOperacao = new FiltroGrupoFuncionalidadeOperacao();
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(FiltroGrupoFuncionalidadeOperacao.GRUPO_ID, grupo
.getId()));
Collection colecaoGrupoFuncionalidadeOperacao = getControladorUtil().pesquisar(filtroGrupoFuncionalidadeOperacao,
GrupoFuncionalidadeOperacao.class.getName());
// Caso exista acessos para o grupo(na tabela
// GrupoFuncinalidadeOperacao) remove todos os
// acessos do grupo antes de remover o grupo
if(colecaoGrupoFuncionalidadeOperacao != null && !colecaoGrupoFuncionalidadeOperacao.isEmpty()){
// Cria o iterator para remover todos os acessos do grupo
Iterator iteratorGrupoFuncionalidadeOperacao = colecaoGrupoFuncionalidadeOperacao.iterator();
// Laço para remover todos os acessos do grupo
while(iteratorGrupoFuncionalidadeOperacao.hasNext()){
// Recupera o acesso do grupo da coleção
GrupoFuncionalidadeOperacao grupoFuncionalidadeOperacao = (GrupoFuncionalidadeOperacao) iteratorGrupoFuncionalidadeOperacao
.next();
// Remove o acesso do grupo
getControladorUtil().remover(grupoFuncionalidadeOperacao);
}
}
// Remove o grupo selecionado
getControladorUtil().remover(grupo);
}
}
}
/**
* Permite inserir uma ResolucaoDiretoria
* [UC0217] Inserir Resolução de Diretoria
*
* @author Rafael Corrêa
* @date 30/03/2006
*/
public Integer inserirSituacaoUsuario(UsuarioSituacao usuarioSituacao) throws ControladorException{
FiltroUsuarioSituacao filtroUsuarioSituacao = new FiltroUsuarioSituacao();
filtroUsuarioSituacao.adicionarParametro(new ParametroSimples(FiltroUsuarioSituacao.DESCRICAO, usuarioSituacao
.getDescricaoUsuarioSituacao()));
Collection colecaoResolucaoDiretoria = getControladorUtil().pesquisar(filtroUsuarioSituacao, UsuarioSituacao.class.getName());
if(colecaoResolucaoDiretoria != null && !colecaoResolucaoDiretoria.isEmpty()){
throw new ControladorException("atencao.desc_ja_existente_situacao_usuario", null, usuarioSituacao
.getDescricaoUsuarioSituacao());
}
usuarioSituacao.setUltimaAlteracao(new Date());
Integer id = (Integer) getControladorUtil().inserir(usuarioSituacao);
return id;
}
/**
* Inseri uma operação e seus relacionamentos com as tabelas se existir
* [UC0284]Inserir Operação
*
* @author Pedro Alexandre
* @date 08/05/2006
* @param operacao
* @param colecaoOperacaoTabela
* @throws ControladorException
*/
public void inserirOperacao(Operacao operacao, Collection<Tabela> colecaoOperacaoTabela, Usuario usuarioLogado)
throws ControladorException{
// [FS0001 Verificar existência da descrição]
// Cria o filtro de operação para verificar se já existe uma operação
// cadastrada
// com a descrição informada
FiltroOperacao filtroOperacao = new FiltroOperacao();
filtroOperacao.adicionarParametro(new ParametroSimples(FiltroOperacao.DESCRICAO, operacao.getDescricao().toUpperCase()));
Collection colecaoOperacao = getControladorUtil().pesquisar(filtroOperacao, Operacao.class.getName());
// Caso exista operação cadastrada com a operação informada
// levanta a exceção para o usuário
if(colecaoOperacao != null && !colecaoOperacao.isEmpty()){
throw new ControladorException("atencao.descricao.operacao.ja.existente", null, operacao.getDescricao());
}
// [FS0004 - Verificar existência da funcionalidade]
// Cria o filtro de funcionalidade para verificar se existe a
// funcionalidade informada
FiltroFuncionalidade filtroFuncionalidade = new FiltroFuncionalidade();
filtroFuncionalidade.adicionarParametro(new ParametroSimples(FiltroFuncionalidade.ID, operacao.getFuncionalidade().getId()));
Collection colecaoFuncionalidade = getControladorUtil().pesquisar(filtroFuncionalidade, Funcionalidade.class.getName());
// Caso a funcionalidade informada não esteja cadastrada no sistema
// levanta uma exceção para o cliente
if(colecaoFuncionalidade == null || colecaoFuncionalidade.isEmpty()){
throw new ControladorException("atencao.funcionalidade.inexistente", null, operacao.getDescricao());
}
// Cria a variável que vai aramzenar o tipo da operação
OperacaoTipo operacaoTipo = null;
// Caso o tipo da operação tenha sido informada
// pesquisa o tipo da operação no sistema
// Caso contrário levanta uma exceção indicando que o tipo da operação
// não foi informada
if(operacao.getOperacaoTipo() != null){
FiltroOperacaoTipo filtroOperacaoTipo = new FiltroOperacaoTipo();
filtroOperacaoTipo.adicionarParametro(new ParametroSimples(FiltroOperacaoTipo.ID, operacao.getOperacaoTipo().getId()));
Collection colecaoOperacaoTipo = getControladorUtil().pesquisar(filtroOperacaoTipo, OperacaoTipo.class.getName());
// Caso o tipo da operação informada não exista
// levanta uma exceção indicando que o tipo da operação não existe
// Caso contrário recupera o tipo da operação da coleção pesquisada
if(colecaoOperacaoTipo == null || colecaoOperacaoTipo.isEmpty()){
throw new ControladorException("atencao.operacao_tipo.inexistente", null, "" + operacao.getOperacaoTipo().getId());
}else{
operacaoTipo = (OperacaoTipo) Util.retonarObjetoDeColecao(colecaoOperacaoTipo);
}
}else{
throw new ControladorException("atencao.operacao_tipo.nao.informado", null);
}
if(operacao.getIndicadorAuditoria() != ConstantesSistema.SIM.intValue()
&& operacao.getIndicadorAuditoria() != ConstantesSistema.NAO.intValue()){
throw new ControladorException("atencao.naoinformado", null, "Indicador de Auditoria");
}
// Caso o tipo da operação informada seja pesquisar
// verifica o preenchimento do argumento de pesquisa
if(operacaoTipo.getId().intValue() == OperacaoTipo.PESQUISAR.intValue()){
// Caso o argumento de pesquisa não tenha sido informado
// levanta uma exceção indicando que o argumento de pesquisa não foi
// informado
if(operacao.getTabelaColuna() == null){
throw new ControladorException("atencao.argumento_pesquisa.nao.informado", null);
}else{
// [FS0005 - Verificar existência do argumento de pesquisa]
// Cria o filtro para pesqusiar o argumento de pesquisa
// informado
FiltroTabelaColuna filtroTabelaColuna = new FiltroTabelaColuna();
filtroTabelaColuna.adicionarParametro(new ParametroSimples(FiltroTabelaColuna.ID, operacao.getTabelaColuna().getId()));
// Pesquisa o argumento de pesquisa
Collection colecaoTabelaColuna = getControladorUtil().pesquisar(filtroTabelaColuna, TabelaColuna.class.getName());
// Caso o argumento de pesquisa não esteja cadastrado
// levanta uma exceção indicando que o argumento de pesquisa não
// existe
// Caso contrário recupera o argumento de pesquisa da coleção
if(colecaoTabelaColuna == null || colecaoTabelaColuna.isEmpty()){
throw new ControladorException("atencao.argumento_pesquisa.inexistente", null);
}else{
// [FS0011 - Verificar argumento de pesquisa]
TabelaColuna argumentoPesquisa = (TabelaColuna) Util.retonarObjetoDeColecao(colecaoTabelaColuna);
// Caso o argumento de pesquisa informado não seja chave
// primária
// levanta uma exceçaõ indicando que o argumento de pesquisa
// não é chave primária da tabela
if(argumentoPesquisa.getIndicadorPrimaryKey() == ConstantesSistema.NAO){
throw new ControladorException("atencao.argumento_pesquisa.nao.chave.primaria", null);
}
// Cria o filtro para verificar se já existe operação com o
// argumento de pesquisa informado
FiltroOperacao filtroOperacaoComArgumentoPesquisa = new FiltroOperacao();
filtroOperacaoComArgumentoPesquisa.adicionarParametro(new ParametroSimples(FiltroOperacao.TABELA_COLUNA_ID,
argumentoPesquisa.getId()));
Collection colecaoOperacaoComArgumentoPesquisa = getControladorUtil().pesquisar(filtroOperacaoComArgumentoPesquisa,
Operacao.class.getName());
// Caso já existe operação com o argumento de pesquisa
// informado
// levanta uma exceção indicando que já existe uma operação
// com o
// argumento de pesquisa informado
if(colecaoOperacaoComArgumentoPesquisa != null && !colecaoOperacaoComArgumentoPesquisa.isEmpty()){
Operacao operacaoComArgumentoPesquisa = (Operacao) Util.retonarObjetoDeColecao(colecaoOperacaoComArgumentoPesquisa);
throw new ControladorException("atencao.argumento_pesquisa.ja.associado", null, operacaoComArgumentoPesquisa
.getDescricao());
}
}
}
}else{
// Caso o tipo de operação não seja "pesquisar"
if(operacaoTipo.getIndicadorAtualiza() == ConstantesSistema.SIM){
// Caso o usuário não tenha informado nenhuma tabela
if(colecaoOperacaoTabela == null || colecaoOperacaoTabela.isEmpty()){
throw new ControladorException("atencao.tabela.nao.informada", null);
}
// [FS0007 - Verificar existência da operação]
if(operacao.getOperacaoPesquisa() != null){
// Cria o filtro para pesquisar a operação de pesquisa
// informada
FiltroOperacao filtroOperacaoPesquisa = new FiltroOperacao();
filtroOperacaoPesquisa.adicionarParametro(new ParametroSimples(FiltroOperacao.ID, operacao.getOperacaoPesquisa()
.getId()));
Collection colecaoOperacaoPesquisa = getControladorUtil().pesquisar(filtroOperacaoPesquisa, Operacao.class.getName());
// Caso a operação de pesquisa não esteja cadastrada
// levanta uma exceção indicando que a operação de pesquisa
// não existe
if(colecaoOperacaoPesquisa == null || colecaoOperacaoPesquisa.isEmpty()){
throw new ControladorException("atencao.operacao_pesquisa.inexistente", null);
}
}
}
}
// ------------ REGISTRAR TRANSAÇÃO ----------------
// RETIRAR ISSO DEPOIS
// *******************************************************
usuarioLogado = Usuario.USUARIO_TESTE;
// ***************************************************************************
RegistradorOperacao registradorOperacao = new RegistradorOperacao(Operacao.OPERACAO_OPERACAO_INSERIR, new UsuarioAcaoUsuarioHelper(
usuarioLogado, UsuarioAcao.USUARIO_ACAO_EFETUOU_OPERACAO));
Operacao operacaoRegistrarTransacao = new Operacao();
operacaoRegistrarTransacao.setId(Operacao.OPERACAO_OPERACAO_INSERIR);
OperacaoEfetuada operacaoEfetuada = new OperacaoEfetuada();
operacaoEfetuada.setOperacao(operacaoRegistrarTransacao);
operacao.setOperacaoEfetuada(operacaoEfetuada);
operacao.adicionarUsuario(usuarioLogado, UsuarioAcao.USUARIO_ACAO_EFETUOU_OPERACAO);
registradorOperacao.registrarOperacao(operacao);
// ------------ REGISTRAR TRANSAÇÃO ----------------
// Inseri a operação no sistema e recupera o id gerado
Integer idOperacao = (Integer) getControladorUtil().inserir(operacao);
// Seta o id no objeto
operacao.setId(idOperacao);
// Caso exista a coleção de tabela
// Inseri todos os relacionamento entre a operação inserida e as tabelas
// informadas
if(colecaoOperacaoTabela != null){
for(Tabela tabela : colecaoOperacaoTabela){
OperacaoTabela operacaoTabela = new OperacaoTabela(new OperacaoTabelaPK(idOperacao, tabela.getId()));
// operacaoTabela.setOperacaoEfetuada(operacaoEfetuada);
// operacaoTabela.adicionarUsuario(usuarioLogado,
// UsuarioAcao.USUARIO_ACAO_EFETUOU_OPERACAO);
// registradorOperacao.registrarOperacao(operacaoTabela);
this.getControladorUtil().inserir(operacaoTabela);
}
}
}
/**
* Permite inserir uma ResolucaoDiretoria
* [UC0297] Inserir Abrangência Usuario
*
* @author Thiago Tenório
* @date 30/03/2006
*/
public Integer inserirAbrangenciaUsuario(UsuarioAbrangencia usuarioAbrangencia) throws ControladorException{
FiltroAbrangenciaUsuario filtroAbrangenciaUsuario = new FiltroAbrangenciaUsuario();
filtroAbrangenciaUsuario.adicionarParametro(new ParametroSimples(FiltroAbrangenciaUsuario.DESCRICAO, usuarioAbrangencia
.getDescricao()));
filtroAbrangenciaUsuario.adicionarParametro(new ParametroSimples(FiltroAbrangenciaUsuario.DESCRICAO_ABREVIADA, usuarioAbrangencia
.getDescricaoAbreviada()));
if(usuarioAbrangencia.getUsuarioAbrangenciaSuperior() != null
&& !usuarioAbrangencia.getUsuarioAbrangenciaSuperior().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
filtroAbrangenciaUsuario.adicionarParametro(new ParametroSimples(FiltroAbrangenciaUsuario.ABRANGENCIA_SUPERIOR,
usuarioAbrangencia.getUsuarioAbrangenciaSuperior()));
}
filtroAbrangenciaUsuario.adicionarParametro(new ParametroSimples(FiltroAbrangenciaUsuario.INDICADOR_USO, usuarioAbrangencia
.getIndicadorUso()));
// Aqui
Collection colecaoUsuarioAbrangencia = getControladorUtil().pesquisar(filtroAbrangenciaUsuario, UsuarioAbrangencia.class.getName());
if(colecaoUsuarioAbrangencia != null && !colecaoUsuarioAbrangencia.isEmpty()){
throw new ControladorException("atencao.numero_resolucao_ja_existente");
}
usuarioAbrangencia.setUltimaAlteracao(new Date());
Integer id = (Integer) getControladorUtil().inserir(usuarioAbrangencia);
return id;
}
/**
* [UC0294] Manter Situação Usuário [] Atualizar Situação do Usuario Metodo
* que atualiza a Situação Usuario
*
* @author Thiago Tenório
* @date 25/05/2006
* @param Situação
* Usuário
* @throws ControladorException
*/
public void atualizarSituacaoUsuario(UsuarioSituacao usuarioSituacao, Collection colecaoUsuarioSituacao) throws ControladorException{
// Verifica se todos os campos obrigatorios foram preenchidos
if((usuarioSituacao.getDescricaoUsuarioSituacao() == null || usuarioSituacao.getDescricaoUsuarioSituacao().equals(
"" + ConstantesSistema.NUMERO_NAO_INFORMADO))
&& (usuarioSituacao.getDescricaoAbreviada() == null || usuarioSituacao.getDescricaoAbreviada().equals(
"" + ConstantesSistema.NUMERO_NAO_INFORMADO))
&& (usuarioSituacao.getId() == null || usuarioSituacao.getId().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO))
&& (usuarioSituacao.getIndicadorUso() == null || usuarioSituacao.getIndicadorUso().equals(
"" + ConstantesSistema.NUMERO_NAO_INFORMADO))){
throw new ControladorException("atencao.filtro.nenhum_parametro_informado");
}
// Verifica se o campo Descrição foi preenchido
if(usuarioSituacao.getDescricaoUsuarioSituacao() == null
|| usuarioSituacao.getDescricaoUsuarioSituacao().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, " Descrição");
}
// Verifica se o campo DescricaoAbreviada foi preenchido
if(usuarioSituacao.getDescricaoAbreviada() == null
|| usuarioSituacao.getDescricaoAbreviada().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, "Descrição Abreviada");
}
// Verifica se o campo IndicadorUso foi preenchido
if(usuarioSituacao.getIndicadorUso() == null
|| usuarioSituacao.getIndicadorUso().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, " Indicador de Uso");
}
// Verifica se o campo IndicadorUsoSistema preenchido
if(usuarioSituacao.getIndicadorUsoSistema() == null
|| usuarioSituacao.getIndicadorUsoSistema().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, " Indicador de Uso Exclusivo do Sistema");
}
// [FS0003] - Atualização realizada por outro usuário
FiltroSituacaoUsuario filtroSituacaoUsuario = new FiltroSituacaoUsuario();
filtroSituacaoUsuario.adicionarParametro(new ParametroSimples(FiltroSituacaoUsuario.ID, usuarioSituacao.getId()));
Collection colecaoUsuarioSituacaoBase = getControladorUtil().pesquisar(filtroSituacaoUsuario, UsuarioSituacao.class.getName());
if(colecaoUsuarioSituacaoBase == null || colecaoUsuarioSituacaoBase.isEmpty()){
sessionContext.setRollbackOnly();
throw new ControladorException("atencao.atualizacao.timestamp");
}
UsuarioSituacao usuarioSituacaoBase = (UsuarioSituacao) colecaoUsuarioSituacaoBase.iterator().next();
if(usuarioSituacaoBase.getUltimaAlteracao().after(usuarioSituacaoBase.getUltimaAlteracao())){
sessionContext.setRollbackOnly();
throw new ControladorException("atencao.atualizacao.timestamp");
}
usuarioSituacao.setUltimaAlteracao(new Date());
getControladorUtil().atualizar(usuarioSituacao);
}
/**
* [UC0298] Manter Abrangência Usuário [] Atualizar Abrangência do Usuario
* Metodo que atualiza a Situação Usuario
*
* @author Thiago Tenório
* @date 25/05/2006
* @param Abrangência
* Usuário
* @throws ControladorException
*/
public void atualizarAbrangenciaUsuario(UsuarioAbrangencia usuarioAbrangencia) throws ControladorException{
// Verifica se todos os campos obrigatorios foram preenchidos
if((usuarioAbrangencia.getDescricao() == null || usuarioAbrangencia.getDescricao().equals(
"" + ConstantesSistema.NUMERO_NAO_INFORMADO))
&& (usuarioAbrangencia.getUsuarioAbrangenciaSuperior() == null || usuarioAbrangencia.getDescricaoAbreviada()
.equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO))
&& (usuarioAbrangencia.getDescricaoAbreviada() == null || usuarioAbrangencia.getDescricaoAbreviada().equals(
"" + ConstantesSistema.NUMERO_NAO_INFORMADO))
&& (usuarioAbrangencia.getId() == null || usuarioAbrangencia.getId().equals(
"" + ConstantesSistema.NUMERO_NAO_INFORMADO))
&& (usuarioAbrangencia.getIndicadorUso() == null || usuarioAbrangencia.getIndicadorUso().equals(
"" + ConstantesSistema.NUMERO_NAO_INFORMADO))){
throw new ControladorException("atencao.filtro.nenhum_parametro_informado");
}
// Verifica se o campo Descrição foi preenchido
if(usuarioAbrangencia.getDescricao() == null
|| usuarioAbrangencia.getDescricao().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, " Descrição");
}
// Verifica se o campo DescricaoAbreviada foi preenchido
if(usuarioAbrangencia.getDescricaoAbreviada() == null
|| usuarioAbrangencia.getDescricaoAbreviada().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, "Descrição Abreviada");
}
// Verifica se o campo IndicadorUso foi preenchido
if(usuarioAbrangencia.getIndicadorUso() == null
|| usuarioAbrangencia.getIndicadorUso().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, " Indicador de Uso");
}
// Verifica se o campo AbrangenciaSuperior foi preenchido
if(usuarioAbrangencia.getUsuarioAbrangenciaSuperior() == null
|| usuarioAbrangencia.getUsuarioAbrangenciaSuperior().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, " Indicador de Uso");
}
// Verifica se o campo Codigo foi preenchido
if(usuarioAbrangencia.getId() == null || usuarioAbrangencia.getId().equals("" + ConstantesSistema.NUMERO_NAO_INFORMADO)){
throw new ControladorException("atencao.Informe_entidade", null, " Indicador de Uso Exclusivo do Sistema");
}
// [FS0003] - Atualização realizada por outro usuário
FiltroAbrangenciaUsuario filtroAbrangenciaUsuario = new FiltroAbrangenciaUsuario();
filtroAbrangenciaUsuario.adicionarParametro(new ParametroSimples(FiltroAbrangenciaUsuario.ID, usuarioAbrangencia.getId()));
Collection colecaoUsuarioAbrangenciaBase = getControladorUtil().pesquisar(filtroAbrangenciaUsuario,
UsuarioAbrangencia.class.getName());
if(colecaoUsuarioAbrangenciaBase == null || colecaoUsuarioAbrangenciaBase.isEmpty()){
sessionContext.setRollbackOnly();
throw new ControladorException("atencao.atualizacao.timestamp");
}
UsuarioAbrangencia usuarioAbrangenciaBase = (UsuarioAbrangencia) colecaoUsuarioAbrangenciaBase.iterator().next();
if(usuarioAbrangencia.getUltimaAlteracao().after(usuarioAbrangenciaBase.getUltimaAlteracao())){
sessionContext.setRollbackOnly();
throw new ControladorException("atencao.atualizacao.timestamp");
}
usuarioAbrangencia.setUltimaAlteracao(new Date());
getControladorUtil().atualizar(usuarioAbrangencia);
}
/**
* Constroi um menu de acesso de acordo com as permissões que o usuário que
* está logado no sistema conteme monta o link de retorno com o link
* informado.
* [UC0277] - Construir menu de acesso
*
* @author Pedro Alexandre
* @date 10/07/2006
* @param usuarioLogado
* @param linkRetorno
* @return
* @throws ControladorException
*/
public String construirMenuAcesso(Usuario usuarioLogado, String linkRetorno) throws ControladorException{
Collection<Funcionalidade> colecaoFuncionalidadesPermitidas = new ArrayList();
// Cria a colecão que vai armazenar os módulos aos que o usuário tem
// alguma funcionalidade cadastrada
Collection modulos = new ArrayList();
// Inicializa a variável que vai definir os identicadores dos nós
// principais da arvore
int contador = 0;
// Variável que vai armazenar o código do nó principal temporariamente
// para incluir as funcionalidades do módulo atual
int temp;
// Cria a primeira parte da arvore
StringBuffer menu = new StringBuffer();
menu
.append("<link rel=\"StyleSheet\" href=\"/sgcq/css/dtree.css\" type=\"text/css\" /><script type=\"text/javascript\" src=\"/sgcq/javascript/dtree.js\"></script>\n");
menu.append("<div class=\"dtree\">\n");
menu.append("<script><!--\n p = new dTree('p');\n");
menu.append("p.add(0,-1,'Funcionalidades');\n");
Collection colecaoGruposUsuario = getControladorUsuario().pesquisarGruposUsuario(usuarioLogado.getId());
if(!usuarioLogado.getUsuarioTipo().getId().equals(UsuarioTipo.USUARIO_TIPO_ADMINISTRADOR)){
/*
* Pesquisa os grupos do usuário logado e seta esses grupos no
* filtro para a pesquisa das funcionalidade que os grupos tem
* acesso.
*/
Iterator iterator = colecaoGruposUsuario.iterator();
FiltroGrupoFuncionalidadeOperacao filtroGrupoFuncionalidadeOperacao = new FiltroGrupoFuncionalidadeOperacao();
filtroGrupoFuncionalidadeOperacao.adicionarCaminhoParaCarregamentoEntidade("funcionalidade.modulo");
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.FUNCIONALIDADE_INDICADOR_PONTO_ENTRADA, ConstantesSistema.SIM));
filtroGrupoFuncionalidadeOperacao.setConsultaSemLimites(true);
// Inseri os grupos do usuário no filtro
while(iterator.hasNext()){
Grupo grupoUsuario = (Grupo) iterator.next();
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(FiltroGrupoFuncionalidadeOperacao.GRUPO_ID,
grupoUsuario.getId(), FiltroParametro.CONECTOR_OR));
}
/*
* Pesquisa as funcionalidades as quais o usuário tem acesso através
* dos grupos a que o usuário pertence.
*/
Collection<GrupoFuncionalidadeOperacao> permissoes = getControladorUtil().pesquisar(filtroGrupoFuncionalidadeOperacao,
GrupoFuncionalidadeOperacao.class.getName());
Iterator<GrupoFuncionalidadeOperacao> iteratorPermissoes = permissoes.iterator();
/*
* Retira as funcionalidades repetidas cadastradas para o usuário
* que está logado recupera também os módulos para ser gerada a
* arvore
*/
while(iteratorPermissoes.hasNext()){
// Recupera a funcionalidade
GrupoFuncionalidadeOperacao grupoFuncionalidadeOperacao = iteratorPermissoes.next();
Funcionalidade funcionalidadePermitida = grupoFuncionalidadeOperacao.getFuncionalidade();
// Caso a funcionalidade ainda não esteja na coleção de
// funcionalidades de acesso do usuário
// adiciona a funcionalidade a coleção
if(!colecaoFuncionalidadesPermitidas.contains(funcionalidadePermitida)){
colecaoFuncionalidadesPermitidas.add(funcionalidadePermitida);
}
// Recupera o módulo da funcionalidade
Modulo moduloPermitido = funcionalidadePermitida.getModulo();
// Caso o modulo ainda não esteja na coleção de modulos de
// acesso do usuário
// adiciona o modulo a coleção
if(!modulos.contains(moduloPermitido)){
modulos.add(moduloPermitido);
}
}
}else{
FiltroFuncionalidade filtroFuncionalidade = new FiltroFuncionalidade();
filtroFuncionalidade.adicionarParametro(new ParametroSimples(FiltroFuncionalidade.INDICADOR_PONTO_ENTRADA,
ConstantesSistema.SIM));
filtroFuncionalidade.adicionarCaminhoParaCarregamentoEntidade("modulo");
filtroFuncionalidade.setConsultaSemLimites(true);
Collection<Funcionalidade> permissoes = getControladorUtil().pesquisar(filtroFuncionalidade, Funcionalidade.class.getName());
Iterator<Funcionalidade> iteratorPermissoes = permissoes.iterator();
while(iteratorPermissoes.hasNext()){
Funcionalidade funcionalidadePermitida = iteratorPermissoes.next();
colecaoFuncionalidadesPermitidas.add(funcionalidadePermitida);
// Recupera o módulo da funcionalidade
Modulo moduloPermitido = funcionalidadePermitida.getModulo();
// Caso o modulo ainda não esteja na coleção de modulos de
// acesso do usuário
// adiciona o modulo a coleção
if(!modulos.contains(moduloPermitido)){
modulos.add(moduloPermitido);
}
}
}
/*
* Inicio do código dinâmico para cria a arvore de acesso
*/
// Cria o iterator dos modulos do usuário logado
Iterator iteratorModulos = modulos.iterator();
/*
* Laço para incluir todos os modulos na árvore e as suas
* funcionalidades
*/
while(iteratorModulos.hasNext()){
// A variável temp vai conter o valor do contador
temp = ++contador;
// Recupera o modulo do iterator
Modulo modulo = (Modulo) iteratorModulos.next();
// Inseri o nó do modulo na árvore
menu.append("p.add(" + temp + "," + "0" + ",'" + modulo.getDescricaoModulo() + "');\n");
// Coloca a coleção de funcionalidades permitidas para o usuário que
// está logado no iterator
Iterator iteratorFuncionalidadesPermitidas = colecaoFuncionalidadesPermitidas.iterator();
// Laço para incluir todas as funcionalidades na árvore
while(iteratorFuncionalidadesPermitidas.hasNext()){
// Incrementa o contador
++contador;
// Pega a funcionalidade do iterator
Funcionalidade funcionalidade = (Funcionalidade) iteratorFuncionalidadesPermitidas.next();
// Caso a funcionalidade pertença ao modulo atual
// inseri a funcionalidade na arvoré dentro do nó do módulo
if(modulo.getId().equals(funcionalidade.getModulo().getId())
&& funcionalidade.getIndicadorPontoEntrada().equals(ConstantesSistema.SIM)){
FiltroGrupoFuncionalidadeOperacao filtroFuncionalidadeCadastradaParaUsuario = new FiltroGrupoFuncionalidadeOperacao();
filtroFuncionalidadeCadastradaParaUsuario.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.FUNCIONALIDADE_ID, funcionalidade.getId()));
filtroFuncionalidadeCadastradaParaUsuario.setConsultaSemLimites(true);
Iterator iteratorGrupos = colecaoGruposUsuario.iterator();
// Inseri os grupos do usuário no filtro
while(iteratorGrupos.hasNext()){
Grupo grupoUsuario = (Grupo) iteratorGrupos.next();
filtroFuncionalidadeCadastradaParaUsuario.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.GRUPO_ID, grupoUsuario.getId(), FiltroParametro.CONECTOR_OR,
colecaoGruposUsuario.size()));
}
Collection funcionlidadeCadastradaParaUsuario = getControladorUtil().pesquisar(
filtroFuncionalidadeCadastradaParaUsuario, GrupoFuncionalidadeOperacao.class.getName());
if(funcionlidadeCadastradaParaUsuario == null || funcionlidadeCadastradaParaUsuario.isEmpty()){
menu.append("p.add(" + contador + "," + temp + ",'" + funcionalidade.getDescricao() + "','" + linkRetorno
+ "&codigoFuncionalidade=" + funcionalidade.getId() + "');\n");
}else{
menu.append("p.add(" + contador + "," + temp + ",'" + funcionalidade.getDescricao() + "','" + linkRetorno
+ "&codigoFuncionalidade=" + funcionalidade.getId() + "','','','','check.gif');\n");
}
}
}
}
// Fim do código dinâmico
/*
* Parte final da arvore de acesso
*/
menu.append("p.draw();\n//--></script>\n");
menu.append("</div>");
// Retorna o javascript que monta a arvore de acesso
return menu.toString();
}
/**
* Metódo responsável por validar o login e senha do usuário, verificando se
* o usuário existe no sistema.
* [UC0287] - Efetuar Login
*
* @author Pedro Alexandre
* @date 04/07/2006
* @param login
* @param senha
* @return
* @throws ControladorException
*/
public Usuario validarUsuario(String login, String senha) throws ControladorException{
// Variável que vai armazenar o usuário logado
Usuario retorno = null;
// Cria o filtro de usuário
FiltroUsuario filtroUsuario = new FiltroUsuario();
// Busca o usuário por senha e login
filtroUsuario.adicionarParametro(new ParametroSimples(FiltroUsuario.LOGIN, login));
filtroUsuario.adicionarCaminhoParaCarregamentoEntidade(FiltroUsuario.GERENCIA_REGIONAL);
filtroUsuario.adicionarCaminhoParaCarregamentoEntidade(FiltroUsuario.LOCALIDADE_ELO);
filtroUsuario.adicionarCaminhoParaCarregamentoEntidade(FiltroUsuario.LOCALIDADE);
filtroUsuario.adicionarCaminhoParaCarregamentoEntidade(FiltroUsuario.USUARIO_SITUACAO);
filtroUsuario.adicionarCaminhoParaCarregamentoEntidade(FiltroUsuario.USUARIO_TIPO);
filtroUsuario.adicionarCaminhoParaCarregamentoEntidade(FiltroUsuario.UNIDADE_ORGANIZACIONAL);
filtroUsuario.adicionarCaminhoParaCarregamentoEntidade(FiltroUsuario.FUNCIONARIO);
filtroUsuario.adicionarCaminhoParaCarregamentoEntidade(FiltroUsuario.EMPRESA);
// filtroUsuario.adicionarParametro(new
// ParametroSimples(FiltroUsuario.SENHA,senha));
try{
// Criptografa a senha para compará-la no banco de dados
filtroUsuario.adicionarParametro(new ParametroSimples(FiltroUsuario.SENHA, Criptografia.encriptarSenha(senha)));
}catch(ErroCriptografiaException e){
sessionContext.setRollbackOnly();
throw new ControladorException("erro.criptografia.senha");
}
// Faz a pesquisa
Collection usuarioEncontrado = getControladorUtil().pesquisar(filtroUsuario, Usuario.class.getName());
// Caso tenha encontrad o usuário no sistema com o login e a senha
// informados
// retorna o usuário para o casode uso que chamou a função
if(!usuarioEncontrado.isEmpty()){
retorno = (Usuario) usuarioEncontrado.iterator().next();
}
// Retorna o usuário encontrado ou nulo se não encontrar
return retorno;
}
/**
* Metódo responsável por registrar o acesso do usuário incrementando o nº
* de acessos e atualizando a data do ultimo acesso do usuário.
* [UC0287] - Efetuar Login
*
* @author Pedro Alexandre
* @date 04/07/2006
* @param usuario
* @throws ControladorException
*/
public void registrarAcessoUsuario(Usuario usuario) throws ControladorException{
// Seta o valor um para o nº de acessos
int numeroAcesso = 1;
// Caso não seja a primeira vez que o usuário tenha acessado o sistema
// incrementa o nº de acesso + 1
if(usuario.getNumeroAcessos() != null){
numeroAcesso = (usuario.getNumeroAcessos().intValue() + numeroAcesso);
}
// Atualiza o nº de acessos do usuário
usuario.setNumeroAcessos(new Integer(numeroAcesso));
// Atualiza a data do último acesso do usuário
Date data = new Date();
usuario.setUltimoAcesso(data);
// Chama o metódo para atualizar o usuário
try{
repositorioAcesso.atualizarRegistrarAcessoUsuario(usuario);
}catch(ErroRepositorioException e){
throw new ControladorException("erro.sistema", e);
}
}
/**
* Metódo responsável por criar a arvore do menu com todas as permissões do
* usuário de acordo com os grupos que o usuário pertence.
* [UC0287] - Efetuar Login
*
* @author Pedro Alexandre
* @date 04/07/2006
* @param permissoesUsuario
* @return
* @throws ControladorException
*/
public FuncionalidadeCategoria pesquisarArvoreFuncionalidades(Collection permissoesUsuario) throws ControladorException{
// Cria a coleção que vai armazenar as funcionalidade permitidas para o
// usuário acessar
Collection funcionalidadesPermitidasAcesso = new ArrayList();
// Obtém a lista de todas as funcionalidades do sistema
Collection funcionalidades = null;
FiltroFuncionalidade filtroFuncionalidade = new FiltroFuncionalidade();
filtroFuncionalidade.adicionarParametro(new ParametroSimples(FiltroFuncionalidade.INDICADOR_PONTO_ENTRADA, ConstantesSistema.SIM));
filtroFuncionalidade.setCampoOrderBy(FiltroFuncionalidade.NUMERO_ORDEM_MENU);
filtroFuncionalidade.setConsultaSemLimites(true);
// Pesquisa todas as funcionalidades cadastradas no sistema
funcionalidades = getControladorUtil().pesquisar(filtroFuncionalidade, Funcionalidade.class.getName());
// Cria o iterator das funcionalidades cadastradas no sistema
Iterator iteratorFuncionalidadesPermissoes = funcionalidades.iterator();
// Laço para criar o menu com as funcionalidades permitidas para o
// usuário
while(iteratorFuncionalidadesPermissoes.hasNext()){
// Recupera a funcionalidade do iterator
Funcionalidade funcionalidade = (Funcionalidade) iteratorFuncionalidadesPermissoes.next();
// Usa a coleção de permissões para eliminar as funcionalidades que
// o usuário não
// pode acessar
Iterator iteratorPermissoes = permissoesUsuario.iterator();
while(iteratorPermissoes.hasNext()){
GrupoFuncionalidadeOperacao grupoFuncionalidadeOperacao = (GrupoFuncionalidadeOperacao) iteratorPermissoes.next();
GrupoFuncionalidadeOperacaoPK chavePermissao = grupoFuncionalidadeOperacao.getComp_id();
// Verifica se a funcionalidade tem o mesmo id da funcionalidade
// e representa a mesma operação da permissão
// para verificar se o usuário tem acesso
if(funcionalidade.getId().equals(chavePermissao.getFuncionalidadeId())){
// A permissão foi encontrada para esta funcionalidade e a
// mesma entra na lista das permitidas
funcionalidadesPermitidasAcesso.add(funcionalidade);
}
}
}
// Cria o iterator das funcionalidades permitidas para o usuário acessar
Iterator iterator = funcionalidadesPermitidasAcesso.iterator();
// Primeira Funcionalidade da arvore
FuncionalidadeCategoria arvoreFuncionalidades = new FuncionalidadeCategoria("Menu");
FuncionalidadeCategoria arvoreFuncionalidadesRetorno = arvoreFuncionalidades;
// Laço para criar a arvore do menu
while(iterator.hasNext()){
// Recupera a funcionalidade
Funcionalidade funcionalidadeInserir = (Funcionalidade) iterator.next();
// Recupera o caminho do menu onde a funcionalidade vai ficar
String caminho = funcionalidadeInserir.getCaminhoMenu();
arvoreFuncionalidades = arvoreFuncionalidadesRetorno;
// Cria a string para pegar os parâmetros que estão separados por /
StringTokenizer stringTokenizer = new StringTokenizer(caminho, "/");
// Laço para criar a string que constroi o menu
while(stringTokenizer.hasMoreTokens()){
// Recupera o nome da funcionalidade
String nomeFuncionalidade = stringTokenizer.nextToken();
FuncionalidadeCategoria funcionalidade = arvoreFuncionalidades.pesquisarCategoria(nomeFuncionalidade);
// O caminho ainda não existe na arvore
if(funcionalidade == null){
funcionalidade = new FuncionalidadeCategoria(nomeFuncionalidade);
// O caminho ainda não existe na arvore
arvoreFuncionalidades.adicionarFuncionalidadeCategoria(funcionalidade);
}
arvoreFuncionalidades = funcionalidade;
}
// Adiciona a funcionalidade a arvore de funcionalidades permitidas
arvoreFuncionalidades.adicionarFuncionalidadeCategoria(funcionalidadeInserir);
}
return arvoreFuncionalidadesRetorno;
}
/**
* Metódo responsável por atualizar as datas de expiração do login do
* usuário assim como definir uma nova senha para o login
* [UC0289] Efetuar Alteração da Senha
*
* @author Pedro Alexandre
* @date 13/07/2006
* @param usuarioLogado
* @param dataNascimentoString
* @param cpf
* @param lembreteSenha
* @param novaSenha
* @param confirmacaoNovaSenha
* @throws ControladorException
*/
public void efetuarAlteracaoSenha(Usuario usuarioLogado, String dataNascimentoString, String cpf, String lembreteSenha,
String novaSenha, String confirmacaoNovaSenha) throws ControladorException{
// [UC0288] - Validar Nova Senha
this.validarNovaSenha(usuarioLogado, dataNascimentoString, cpf, lembreteSenha, novaSenha, confirmacaoNovaSenha);
/*
* Recupera os parâmetros do sistema para recuperar o nº de dias da
* expiração do acesso e o nº de dias de para a mensagem de expiração
*/
SistemaParametro sistemaParametro = getControladorUtil().pesquisarParametrosDoSistema();
Short numeroDiasExpiracaoAcesso = sistemaParametro.getNumeroDiasExpiracaoAcesso();
Short numeroDiasMensagemExpiracao = sistemaParametro.getNumeroDiasMensagemExpiracao();
// Cria e recupera as datas necessárias para verificar se alteração de
// senha é permitida
Date dataAtual = new Date();
Date dataInicioCadastro = usuarioLogado.getDataCadastroInicio();
Date dataFimCadastro = usuarioLogado.getDataCadastroFim();
Date dataExpiracaoAcesso = null;
Date dataPrazoMensagemExpiracao = null;
/*
* Caso o nº de dias para expiração de acesso for nulo atribui zero a
* ele, a mesma coisa para o nº de dias da mensagem de expiração
*/
if(numeroDiasExpiracaoAcesso == null){
numeroDiasExpiracaoAcesso = 0;
}
if(numeroDiasMensagemExpiracao == null){
numeroDiasMensagemExpiracao = 0;
}
/*
* Caso a data de inicio do cadastro esteja preenchida e a data atual
* mais o nº de dias para expirar for maior que a data de fim do
* cadastro a data de expiração do acesso será a data fim do cadastro
* Caso contrário a data de expiração vai ser adata atual mais o nº de
* dias de expiração de acesso
*/
if(dataInicioCadastro != null && dataFimCadastro != null
&& (Util.adicionarNumeroDiasDeUmaData(dataAtual, numeroDiasExpiracaoAcesso)).after(dataFimCadastro)){
dataExpiracaoAcesso = dataFimCadastro;
}else{
dataExpiracaoAcesso = Util.adicionarNumeroDiasDeUmaData(dataAtual, numeroDiasExpiracaoAcesso);
}
/*
* Caso a data de inicioa do cadastro esteja preenchida e a data atual
* mas a diferença entre o nº de dias para expiração e o nº de dias da
* mensagem de expiração for maior que a data fim do cadastro a data do
* prazo para mensagem de expiração vai ser a data fim do cadastro mais
* o nº de dias mensagem de expiração Caso contrário a data para o prazo
* de expiração da mensagem será a data atual mais a diferença entre o
* nº de dias para expiração e o nº de dias da mensagem de expiração
*/
if(dataInicioCadastro != null
&& dataFimCadastro != null
&& (Util.adicionarNumeroDiasDeUmaData(dataAtual, (numeroDiasExpiracaoAcesso - numeroDiasMensagemExpiracao)))
.after(dataFimCadastro)){
dataPrazoMensagemExpiracao = Util.subtrairNumeroDiasDeUmaData(dataFimCadastro, numeroDiasMensagemExpiracao);
}else{
dataPrazoMensagemExpiracao = Util.adicionarNumeroDiasDeUmaData(dataAtual,
(numeroDiasExpiracaoAcesso - numeroDiasMensagemExpiracao));
}
// Valida a data de nascimento digitada
Date dataNascimento = null;
if(!Util.isVazioOuBranco(dataNascimentoString)){
SimpleDateFormat dataFormato = new SimpleDateFormat("dd/MM/yyyy");
try{
dataNascimento = dataFormato.parse(dataNascimentoString);
}catch(ParseException ex){
throw new ControladorException("atencao.data.invalida", null, "Data de Nascimento");
}
}
// Cria a situaçdo usuário e setaseu valor para senha ativa
UsuarioSituacao usuarioSituacao = new UsuarioSituacao();
usuarioSituacao.setId(UsuarioSituacao.ATIVO);
/*
* Criptografa a nova senha gerada para ser usada pelo usuário
*/
try{
novaSenha = Criptografia.encriptarSenha(novaSenha);
}catch(ErroCriptografiaException e){
sessionContext.setRollbackOnly();
throw new ControladorException("erro.criptografia.senha");
}
// Últimas senhas criptografadas do usuário para evitar repetições
UsuarioSenha usuarioSenha = new UsuarioSenha();
usuarioSenha.setUsuario(usuarioLogado);
usuarioSenha.setNomeSenha(novaSenha);
usuarioSenha.setUltimaAlteracao(new Date());
getControladorUtil().inserir(usuarioSenha);
// Atualiza os dados do usuário
usuarioLogado.setSenha(novaSenha);
usuarioLogado.setDataExpiracaoAcesso(dataExpiracaoAcesso);
usuarioLogado.setDataPrazoMensagemExpiracao(dataPrazoMensagemExpiracao);
usuarioLogado.setDataNascimento(dataNascimento);
usuarioLogado.setCpf(cpf);
usuarioLogado.setLembreteSenha(lembreteSenha);
usuarioLogado.setUltimaAlteracao(new Date());
usuarioLogado.setUsuarioSituacao(usuarioSituacao);
// ------------ REGISTRAR TRANSAÇÃO ----------------
RegistradorOperacao registradorOperacao = new RegistradorOperacao(Operacao.OPERACAO_EFETUAR_ALTERACAO_SENHA,
new UsuarioAcaoUsuarioHelper(usuarioLogado, UsuarioAcao.USUARIO_ACAO_EFETUOU_OPERACAO));
Operacao operacao = new Operacao();
operacao.setId(Operacao.OPERACAO_EFETUAR_ALTERACAO_SENHA);
OperacaoEfetuada operacaoEfetuada = new OperacaoEfetuada();
operacaoEfetuada.setOperacao(operacao);
usuarioLogado.setOperacaoEfetuada(operacaoEfetuada);
usuarioLogado.adicionarUsuario(usuarioLogado, UsuarioAcao.USUARIO_ACAO_EFETUOU_OPERACAO);
registradorOperacao.registrarOperacao(usuarioLogado);
// ------------ REGISTRAR TRANSAÇÃO ----------------
// Atualiza os dados do usuário
getControladorUtil().atualizar(usuarioLogado);
}
/**
* Metódo responsável por validar todos os dados informados pelo usuário
* para cadastrar uma nova senha para o usuário.
* [UC0288] - Validar Nova Senha
*
* @author Pedro Alexandre
* @date 13/07/2006
* @author Eduardo Henrique
* @date 30/05/2008
* Alteração para validar se o cpf informado (caso exista - [FS0008]) já existe na base,
* se o mesmo não for nulo
* @param usuarioLogado
* @param dataNascimentoString
* @param cpf
* @param lembreteSenha
* @param novaSenha
* @param confirmacaoNovaSenha
* @throws ControladorException
*/
public void validarNovaSenha(Usuario usuarioLogado, String dataNascimentoString, String cpf, String lembreteSenha, String novaSenha,
String confirmacaoNovaSenha) throws ControladorException{
// Recupera o login do usuário logado
String login = usuarioLogado.getLogin();
// [FS0005] - Verificar data de nascimento do login
Date dataNascimentoUsuarioLogado = usuarioLogado.getDataNascimento();
if(dataNascimentoUsuarioLogado != null){
// [FS0003] - Validar Data
Date dataNascimento = null;
SimpleDateFormat dataFormato = new SimpleDateFormat("dd/MM/yyyy");
try{
dataNascimento = dataFormato.parse(dataNascimentoString);
}catch(ParseException ex){
throw new ControladorException("atencao.data.invalida", null, "Data de Nascimento");
}
// Recupera a data atual
Date dataAtual = new Date();
// [FS0004] - Verificar data maior ou igual a data corrente
if(!dataNascimento.before(dataAtual)){
throw new ControladorException("atencao.data_nascimento.anterior.dataatual", null, login, Util.formatarData(dataAtual));
}
if(dataNascimento.compareTo(dataNascimentoUsuarioLogado) != 0){
throw new ControladorException("atencao.data_nascimento.incorreta.login", null, login);
}
}
// [FS0008] - Verificar CPF do login
// Recupera o CPF do usuário que está logado e verifica
// se é o mesmo que foi informado ná página
// Caso o usuário não tenha cadastrado o cpf verifica se existe
// um outro usuário já com esse cpf informado
String cpfUsuarioLogado = usuarioLogado.getCpf();
if(cpfUsuarioLogado != null && !cpfUsuarioLogado.trim().equals("")){
if(!cpf.equals(cpfUsuarioLogado)){
throw new ControladorException("atencao.cpf.incorreto.login", null, login);
}
}else if(cpf != null && !cpf.trim().equals("")){
FiltroUsuario filtroUsuarioComCpf = new FiltroUsuario();
filtroUsuarioComCpf.adicionarParametro(new ParametroSimples(FiltroUsuario.CPF, cpf));
Collection colecaoUsuariosComCpf = getControladorUtil().pesquisar(filtroUsuarioComCpf, Usuario.class.getName());
// Caso exista um usuário cadastrado com o cpf informado
if(colecaoUsuariosComCpf != null && !colecaoUsuariosComCpf.isEmpty()){
throw new ControladorException("atencao.cpf.jainformado.login", null, login);
}
}
// [FS0011] - Validar confirmação da nova senha
if(!novaSenha.equals(confirmacaoNovaSenha)){
throw new ControladorException("atencao.confirmacao.novasenha.invalida");
}
// [FS0010] - Validar Senha
this.validarSenha(novaSenha);
String quantidadeHistorico = ParametroGeral.P_SENHA_QUANTIDADE_HISTORICO.executar();
if(quantidadeHistorico != null){
Integer valor = Util.converterStringParaInteger(quantidadeHistorico);
if(valor != null && valor.intValue() > 0){
Collection<String> senhasAnteriores = null;
try{
senhasAnteriores = this.repositorioAcesso.pesquisarUsuarioSenha(usuarioLogado.getId(), valor);
}catch(ErroRepositorioException e){
sessionContext.setRollbackOnly();
e.printStackTrace();
}
if(!Util.isVazioOrNulo(senhasAnteriores)){
String senhaCriptografada = null;
try{
// Criptografa a nova senha gerada para ser usada pelo usuário
senhaCriptografada = Criptografia.encriptarSenha(novaSenha);
}catch(ErroCriptografiaException e){
sessionContext.setRollbackOnly();
throw new ControladorException("erro.criptografia.senha");
}
for(String senhaAnterior : senhasAnteriores){
if(senhaAnterior.equals(senhaCriptografada)){
throw new ControladorException("atencao.senha.invalida", null, "As últimas " + valor.intValue()
+ " senhas não podem se repetir.");
}
}
}
}
}
}
/**
* [UC0287] - Efetuar Login
* Metódo responsável por enviar uma nova senha para o e-mail do usuário com
* situação pendente
* [SB0002] - Lembrar senha
*
* @author Pedro Alexandre
* @date 14/07/2006
* @author Virgínia Melo
* @date 16/02/2009
* Adicionado validação para emailDestinatario
* @param login
* @param cpf
* @param dataNascimentoString
* @throws ControladorException
*/
public void lembrarSenha(String login, String cpf, String dataNascimentoString) throws ControladorException{
// [FS0006] - Validar data
Date dataNascimento = null;
SimpleDateFormat dataFormato = new SimpleDateFormat("dd/MM/yyyy");
try{
dataNascimento = dataFormato.parse(dataNascimentoString);
}catch(ParseException ex){
throw new ControladorException("atencao.data.invalida", null, "Data de Nascimento");
}
// [FS0007] Verificar data maior ou igual a data corrente
Date dataAtual = new Date();
if(!dataNascimento.before(dataAtual)){
throw new ControladorException("atencao.data_nascimento.anterior.dataatual", null, login, Util.formatarData(dataAtual));
}
// Cria o filtro e pesquisa o usuário com o login informado
FiltroUsuario filtroUsuario = new FiltroUsuario();
filtroUsuario.adicionarParametro(new ParametroSimples(FiltroUsuario.LOGIN, login));
filtroUsuario.adicionarCaminhoParaCarregamentoEntidade("usuarioSituacao");
Collection usuarios = this.getControladorUtil().pesquisar(filtroUsuario, Usuario.class.getName());
// Recupera o usuário que está solicitando o lembrete da senha
Usuario usuarioLogado = (Usuario) usuarios.iterator().next();
// [UC0008] - Verificar data de nascimento do login
Date dataNascimentoUsuarioLogado = usuarioLogado.getDataNascimento();
if(dataNascimentoUsuarioLogado != null && dataNascimento.compareTo(dataNascimentoUsuarioLogado) != 0){
throw new ControladorException("atencao.data_nascimento.incorreta.login", null, login);
}
// [FS0012] - Verificar situação do usuário para lembrar senha
UsuarioSituacao usuarioSituacao = usuarioLogado.getUsuarioSituacao();
if(!usuarioSituacao.getId().equals(UsuarioSituacao.ATIVO)){
throw new ControladorException("atencao.situacao_usuario.invalida.lembrar_senha", null, login, usuarioSituacao
.getDescricaoUsuarioSituacao());
}
// Recupera o CPF do usuário que está logado e verifica se é o mesmo que foi informado ná
// página
String cpfUsuarioLogado = usuarioLogado.getCpf();
if(cpfUsuarioLogado != null && !cpfUsuarioLogado.trim().equals("")){
// [FS0010] - Verificar CPF do login
if(!cpf.equals(cpfUsuarioLogado)){
throw new ControladorException("atencao.cpf.incorreto.login", null, login);
}
}
// Obtém uma senha temporária com 6 caracteres essa senha será atribuida ao usuário e sua
// situação vai estar pendente
String novaSenha;
String senhaCriptografada;
try{
novaSenha = Util.geradorSenha(6);
senhaCriptografada = Criptografia.encriptarSenha(novaSenha);
}catch(ErroCriptografiaException e1){
throw new ControladorException("erro.criptografia.senha");
}
// Atualiza os dados do usuário informando que a nova senha está pendente
usuarioSituacao = new UsuarioSituacao();
usuarioSituacao.setId(UsuarioSituacao.PENDENTE_SENHA);
usuarioLogado.setUsuarioSituacao(usuarioSituacao);
usuarioLogado.setSenha(senhaCriptografada);
usuarioLogado.setUltimaAlteracao(new Date());
getControladorUtil().atualizar(usuarioLogado);
SistemaParametro sistemaParametro = getControladorUtil().pesquisarParametrosDoSistema();
// Trecho de código responsável por enviar a nova senha do usuário para o email cadastrado
String emailDestinatario = usuarioLogado.getDescricaoEmail();
String emailRemetente = sistemaParametro.getDescricaoEmail();
StringBuilder corpoEmail = new StringBuilder();
corpoEmail.append("Login:" + login);
corpoEmail.append(System.getProperty("line.separator"));
corpoEmail.append("Senha:" + novaSenha);
String assuntoEmail = "Solicitação de senha";
// Validação email destinatário
if(emailDestinatario == null || emailDestinatario.trim().equals("")){
sessionContext.setRollbackOnly();
throw new ControladorException("atencao.envio_email");
}
try{
ServicosEmail.enviarMensagem(emailRemetente, emailDestinatario, assuntoEmail, corpoEmail.toString());
}catch(ErroEmailException e){
sessionContext.setRollbackOnly();
throw new ControladorException(e.getMessage());
}
}
/**
* [UC0288] - Validar nova senha
* Metódo que verifica se a senha informada está de acordo com o padrão de
* segurança adotado.
* [FS0011] - Validar senha
*
* @author Pedro Alexandre
* @date 14/07/2006
* @param senha
* @throws ControladorException
*/
private void validarSenha(String senha) throws ControladorException{
String quantidadeMinimaCaracteres = ParametroGeral.P_SENHA_QUANTIDADE_MINIMA_CARACTERES.executar();
Integer quantidade = Util.converterStringParaInteger(quantidadeMinimaCaracteres);
if(senha.length() < quantidade.intValue()){
throw new ControladorException("atencao.senha.invalida", null, "Senha deve ter pelo menos " + quantidade.intValue()
+ " caracteres.");
}
int contadorMinusculas = 0;
int contadorMaiusculas = 0;
int contadorNumeros = 0;
int contadorEspeciais = 0;
char[] caracteresSenha = senha.toCharArray();
for(char caracter : caracteresSenha){
if(Character.isLowerCase(caracter)){
contadorMinusculas++;
}else if(Character.isUpperCase(caracter)){
contadorMaiusculas++;
}else if(Character.isDigit(caracter)){
contadorNumeros++;
}else if(Util.isCaracterEspecial(String.valueOf(caracter))){
contadorEspeciais++;
}
}
String quantidadeMinimaLetrasMinusculas = ParametroGeral.P_SENHA_QUANTIDADE_MINIMA_LETRAS_MINUSCULAS.executar();
if(quantidadeMinimaLetrasMinusculas != null){
Integer valor = Util.converterStringParaInteger(quantidadeMinimaLetrasMinusculas);
if(valor != null && valor.intValue() > contadorMinusculas){
throw new ControladorException("atencao.senha.invalida", null, "Senha deve ter pelo menos " + valor.intValue()
+ " letra(s) minúscula(s).");
}
}
String quantidadeMinimaLetrasMaiusculas = ParametroGeral.P_SENHA_QUANTIDADE_MINIMA_LETRAS_MAIUSCULAS.executar();
if(quantidadeMinimaLetrasMaiusculas != null){
Integer valor = Util.converterStringParaInteger(quantidadeMinimaLetrasMaiusculas);
if(valor != null && valor.intValue() > contadorMaiusculas){
throw new ControladorException("atencao.senha.invalida", null, "Senha deve ter pelo menos " + valor.intValue()
+ " letra(s) maiúscula(s).");
}
}
String quantidadeMinimaNumeros = ParametroGeral.P_SENHA_QUANTIDADE_MINIMA_NUMEROS.executar();
if(quantidadeMinimaNumeros != null){
Integer valor = Util.converterStringParaInteger(quantidadeMinimaNumeros);
if(valor != null && valor.intValue() > contadorNumeros){
throw new ControladorException("atencao.senha.invalida", null, "Senha deve ter pelo menos " + valor.intValue()
+ " número(s).");
}
}
String quantidadeMinimaCaracteresEspeciais = ParametroGeral.P_SENHA_QUANTIDADE_MINIMA_CARACTERES_ESPECIAIS.executar();
if(quantidadeMinimaCaracteresEspeciais != null){
Integer valor = Util.converterStringParaInteger(quantidadeMinimaCaracteresEspeciais);
if(valor != null && valor.intValue() > contadorEspeciais){
throw new ControladorException("atencao.senha.invalida", null, "Senha deve ter pelo menos " + valor.intValue()
+ " caracter(es) especial(is).");
}
}
}
/**
* Verifica se uma url solicitada para o servidor é uma funcionalidade ou
* uma operação
*
* @author Pedro Alexandre
* @date 18/07/2006
* @param url
* @return
* @throws ControladorException
*/
public Map<Integer, String> verificarTipoURL(String url) throws ControladorException{
// Variável que vai conter uma string indicando se a url é uma operação
// ou uma funcionalidade
Map<Integer, String> retorno = null;
// Caso a url starte com "/"(barra) retira a barra da url
if(url.startsWith("/")){
url = url.substring(1);
}
// Cria o filtro para pesquisar a funcionalidade na base de dados pela
// url informada
FiltroFuncionalidade filtroFuncionalidade = new FiltroFuncionalidade();
// filtroFuncionalidade.adicionarParametro(new
// ParametroSimples(FiltroFuncionalidade.CAMINHO_URL,url));
filtroFuncionalidade.adicionarParametro(new ComparacaoTexto(FiltroFuncionalidade.CAMINHO_URL, url));
// Pesquisa a funcionalidade com a url
Collection colecaoFuncionalidade = getControladorUtil().pesquisar(filtroFuncionalidade, Funcionalidade.class.getName());
/*
* Caso exista funcionalidade cadastrada para esta url indica que a url
* é uma funcionalidade. Caso contrário verifica se a url é uma
* operação.
*/
if(colecaoFuncionalidade != null && !colecaoFuncionalidade.isEmpty()){
Funcionalidade funcionalidadeAtual = (Funcionalidade) Util.retonarObjetoDeColecao(colecaoFuncionalidade);
retorno = new HashMap<Integer, String>();
retorno.put(funcionalidadeAtual.getId(), "funcionalidade");
}else{
// Cria o filtro de operação para verificar se a url é uma operação
FiltroOperacao filtroOperacao = new FiltroOperacao();
// filtroOperacao.adicionarParametro(new
// ParametroSimples(FiltroOperacao.CAMINHO_URL,url));
filtroOperacao.adicionarParametro(new ComparacaoTexto(FiltroOperacao.CAMINHO_URL, url));
// Pesquisa a operação com a url
Collection colecaoOperacao = getControladorUtil().pesquisar(filtroOperacao, Operacao.class.getName());
/*
* Caso exista operação cadastrada para esta url indica que a url é
* uma operação
*/
if(colecaoOperacao != null && !colecaoOperacao.isEmpty()){
Operacao operacaoAtual = (Operacao) Util.retonarObjetoDeColecao(colecaoOperacao);
retorno = new HashMap<Integer, String>();
retorno.put(operacaoAtual.getId(), "operacao");
}
}
// Retorna uma string indicando se a url é uma funcionalidade ou
// operação
return retorno;
}
/**
* Metódo que verifica se o usuário tem permissão para acessar a
* funcionalidade que está sendo requisitada (existe ocorrência na tabela
* GrupoFuncionalidadeOperacao). Verifica se o(s) grupo(s) que o usuário
* pertence tem acesso a funcionalidade e se todas as operações desta
* funcionalidade não estão com restrições(existe ocorrência na tabela
* UsuarioGrupoRestricao)
*
* @author Pedro Alexandre
* @date 18/07/2006
* @param usuarioLogado
* @param urlFuncionalidade
* @param colecaoGruposUsuario
* @return
* @throws ControladorException
*/
public boolean verificarAcessoPermitidoFuncionalidade(Usuario usuarioLogado, String urlFuncionalidade, Collection colecaoGruposUsuario)
throws ControladorException{
// Cria a variável que indica se o usuário tem ou não acesso a
// funcionalidade
boolean retorno = false;
// Caso a url starte com "/"(barra) retira a barra da url
if(urlFuncionalidade.startsWith("/")){
urlFuncionalidade = urlFuncionalidade.substring(1);
}
// Cria o filtro para pesquisar a funcionalidade com a url informada
FiltroFuncionalidade filtroFuncionalidade = new FiltroFuncionalidade();
// filtroFuncionalidade.adicionarParametro(new
// ParametroSimples(FiltroFuncionalidade.CAMINHO_URL,urlFuncionalidade));
filtroFuncionalidade.adicionarParametro(new ComparacaoTexto(FiltroFuncionalidade.CAMINHO_URL, urlFuncionalidade));
// Pesquisa a funcionalidade com a url informada
Collection colecaoFuncionalidade = getControladorUtil().pesquisar(filtroFuncionalidade, Funcionalidade.class.getName());
// Variável que vai armazenar a funcionalidade pesquisada
Funcionalidade funcionalidade = null;
// Caso a pesquisa retorne a funcionalidade
/*
* @Date 18/04/2008
* Incluído por Eduardo Henrique para atender à verificação das páginas de tabelas
* auxiliares
* antes havia um if, e não havia iteração na coleção
*/
for(Iterator iterator = colecaoFuncionalidade.iterator(); iterator.hasNext();){
// Recupera a funcionalidade da coleção
funcionalidade = (Funcionalidade) iterator.next();
// funcionalidade = (Funcionalidade) colecaoFuncionalidade.iterator()
// .next();
// Cria a variável que vao armazenar as funcionalidades permitidas
// para ser acessadas
// com a operaçaõ que está sendo requisitada
Collection<Funcionalidade> colecaoFuncionalidadesPermitidas = new ArrayList();
colecaoFuncionalidadesPermitidas.add(funcionalidade);
// Cria o filtro para verificar se existe permissão para acessar a
// funcionalidade
// existe ocorrência na tabela GrupoFuncionalidadeOperacao
FiltroGrupoFuncionalidadeOperacao filtroGrupoFuncionalidadeOperacao = new FiltroGrupoFuncionalidadeOperacao();
// Cria o filtro para pesquisar se a funcionalidade é dependente de
// alguma outra funcionalidade
// para verificar se a operaçaõ foi cadastrada para a funcionalidade
// da propria operação
// ou com uma funcionalidade principal com relação de dependência
// com a funcionalidade da propria operação
FiltroFuncionalidadeDependencia filtroFuncionalidadeDependencia = new FiltroFuncionalidadeDependencia();
filtroFuncionalidadeDependencia.adicionarParametro(new ParametroSimples(
FiltroFuncionalidadeDependencia.FUNCIONALIDADE_DEPENDENCIA, funcionalidade.getId()));
Collection colecaoFuncionalidadePrincipal = getControladorUtil().pesquisar(filtroFuncionalidadeDependencia,
FuncionalidadeDependencia.class.getName());
/*
* Caso a coleção de funcionalidade principal não estiver vazia
* adiciona as funcionalidades no filtro para pesquisar as
* permissões
*/
if(colecaoFuncionalidadePrincipal != null && !colecaoFuncionalidadePrincipal.isEmpty()){
Iterator iteratorFuncionalidadePrincipal = colecaoFuncionalidadePrincipal.iterator();
// Laço para adicionar as funcionalidades principais a coleção
// de funcionalidades permitidas
while(iteratorFuncionalidadePrincipal.hasNext()){
FuncionalidadeDependencia funcionalidadeDependencia = (FuncionalidadeDependencia) iteratorFuncionalidadePrincipal
.next();
colecaoFuncionalidadesPermitidas.add(funcionalidadeDependencia.getFuncionalidade());
}
}
// Cria um contador para auxiliar na criação dos filtros
int cont = 1;
/*
* Caso a coleção de funcionalidades permitidas não esteja vazia
* adicona os ids das funcionalidades permitidas no filtro para
* pesquisar as permissões
*/
if(colecaoFuncionalidadesPermitidas != null && !colecaoFuncionalidadesPermitidas.isEmpty()){
Iterator<Funcionalidade> iteratorFuncionalidadesPeritidas = colecaoFuncionalidadesPermitidas.iterator();
// Laço para adicionar os ids das funcionalidades permitidas no
// filtro
while(iteratorFuncionalidadesPeritidas.hasNext()){
// Recupera a funcionalidade do iterator
Funcionalidade funcionalidadePermitida = iteratorFuncionalidadesPeritidas.next();
/*
* Caso a coleção possua uma única funcionalidade permitida
* para o usuário adiciona o id da coleção no filtro sem
* nenhum conector Caso contrário verifica qual a posição do
* iterator para adicionar o id com o conector correto
*/
if(colecaoFuncionalidadesPermitidas.size() == 1){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.FUNCIONALIDADE_ID, funcionalidadePermitida.getId()));
}else{
// Caso seja a primeira funcionalidade adiciona o id com
// o conector "OR"
// e informa quantas funcionalidades vai ter para inseri
// os parenteses
if(cont == 1){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.FUNCIONALIDADE_ID, funcionalidadePermitida.getId(),
FiltroParametro.CONECTOR_OR, colecaoFuncionalidadesPermitidas.size()));
cont++;
}else{
/*
* Caso seja a última funcionalidade da coleção
* adiciona o id da funcionalidade sem conector Caso
* contrário adiciona o id da funcionalidade com o
* conector "OR"
*/
if(cont == colecaoFuncionalidadesPermitidas.size()){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.FUNCIONALIDADE_ID, funcionalidadePermitida.getId()));
cont++;
}else{
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.FUNCIONALIDADE_ID, funcionalidadePermitida.getId(),
ParametroSimples.CONECTOR_OR));
cont++;
}
}
}
}
}
// Inicializa o contador para auxiliar no filtro de grupos
cont = 1;
// Cria o iteratorpara a coleção de grupos do usuário logado
Iterator iteratorGruposUsuario = colecaoGruposUsuario.iterator();
// Laço para adicionar os grupos do usuário no filtro
while(iteratorGruposUsuario.hasNext()){
// Recupera o grupo do iterator
Grupo grupoUsuario = (Grupo) iteratorGruposUsuario.next();
/*
* Caso a coleção possua um único grupo para o usuário adiciona
* o id do grupo no filtro sem nenhum conector Caso contrário
* verifica qual a posição do iterator para adicionar o id com o
* conector correto
*/
if(colecaoGruposUsuario.size() == 1){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(FiltroGrupoFuncionalidadeOperacao.GRUPO_ID,
grupoUsuario.getId()));
}else{
// Caso seja o primeiro grupo adiciona o id com o conector
// "OR"
// e informa quantos grupos vai ter para inserir os
// parenteses
if(cont == 1){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.GRUPO_ID, grupoUsuario.getId(), FiltroParametro.CONECTOR_OR,
colecaoGruposUsuario.size()));
cont++;
}else{
/*
* Caso seja o último grupo da coleção adiciona o id do
* grupo sem conector Caso contrário adiciona o id
* dogrupo com o conector "OR"
*/
if(cont == colecaoGruposUsuario.size()){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.GRUPO_ID, grupoUsuario.getId()));
cont++;
}else{
filtroGrupoFuncionalidadeOperacao
.adicionarParametro(new ParametroSimples(FiltroGrupoFuncionalidadeOperacao.GRUPO_ID,
grupoUsuario.getId(), ParametroSimples.CONECTOR_OR));
cont++;
}
}
}
}
/*
* Cria o filtro para pesquisar as operaçãoes da funcionalidade
* requisitada para verificar se o usuário tem acesso a alguma
* operação da funcionalidade
*/
FiltroOperacao filtroOperacao = new FiltroOperacao();
filtroOperacao.adicionarParametro(new ParametroSimples(FiltroOperacao.FUNCIONALIDADE_ID, funcionalidade.getId()));
Collection colecaoOperacoesFuncionalidade = getControladorUtil().pesquisar(filtroOperacao, Operacao.class.getName());
// Inicializa o contador para auxiliar no filtro de operações
cont = 1;
// Cria o iterator das operações
Iterator iteratorOperacoesFuncionalidade = colecaoOperacoesFuncionalidade.iterator();
// Laço para adicionar as operações da funcionalidade no filtro
while(iteratorOperacoesFuncionalidade.hasNext()){
// Recupera a operação da funcionalidade
Operacao operacaoFuncionalidade = (Operacao) iteratorOperacoesFuncionalidade.next();
/*
* Caso a coleção possua uma única operação para a
* funcionalidade adiciona o id da operação no filtro sem nenhum
* conector Caso contrário verifica qual a posição do iterator
* para adicionar o id com o conector correto
*/
if(colecaoOperacoesFuncionalidade.size() == 1){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.OPERACAO_ID, operacaoFuncionalidade.getId()));
}else{
// Caso seja a primeira operação adiciona o id com o
// conector "OR"
// e informa quantas operações vai ter para inserir os
// parenteses
if(cont == 1){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.OPERACAO_ID, operacaoFuncionalidade.getId(),
FiltroParametro.CONECTOR_OR, colecaoOperacoesFuncionalidade.size()));
cont++;
}else{
/*
* Caso seja a última operação da coleção adiciona o id
* da operação sem conector Caso contrário adiciona o id
* da operação com o conector "OR"
*/
if(cont == colecaoOperacoesFuncionalidade.size()){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.OPERACAO_ID, operacaoFuncionalidade.getId()));
cont++;
}else{
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.OPERACAO_ID, operacaoFuncionalidade.getId(),
ParametroSimples.CONECTOR_OR));
cont++;
}
}
}
}
// Pesquisa se o usuário tem permissão para acessar a funcionalidade
Collection permissoes = getControladorUtil().pesquisar(filtroGrupoFuncionalidadeOperacao,
GrupoFuncionalidadeOperacao.class.getName());
/*
* Caso o usuário tenha permissão para acessar a funcionalidade
* verifica se existe restrição para todas as operações da
* funcionalidade
*/
if(permissoes != null && !permissoes.isEmpty()){
/*
* Cria o filtro para pesquisar todas as restrições do usuário
* seta o código do usuário logado e o código da funcionalidade
* no filtro
*/
FiltroUsuarioGrupoRestricao filtroUsuarioGrupoRestricao = new FiltroUsuarioGrupoRestricao();
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.USUARIO_ID, usuarioLogado
.getId()));
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.FUNCIONALIDADE_ID,
funcionalidade.getId()));
/*
* Bloco de código para montar o filtro com todos os grupos do
* usuário logado
*/
Iterator iteratorGruposUsuarioPermissoes = colecaoGruposUsuario.iterator();
cont = 1;
// Laço para inserir todos os grupos no filtro
while(iteratorGruposUsuarioPermissoes.hasNext()){
// Recupera o grupo do usuário
Grupo grupoUsuario = (Grupo) iteratorGruposUsuarioPermissoes.next();
/*
* Caso a coleção de grupos de usuário tenha apenas um
* elemento adiciona o grupo no filtro sem o conector "OR"
* Caso contrário vai adicionar os grupos um a um com seus
* conectores
*/
if(colecaoGruposUsuario.size() == 1){
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.GRUPO_ID,
grupoUsuario.getId()));
}else{
if(cont == 1){
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.GRUPO_ID,
grupoUsuario.getId(), FiltroParametro.CONECTOR_OR, colecaoGruposUsuario.size()));
cont++;
}else{
if(cont == colecaoGruposUsuario.size()){
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.GRUPO_ID,
grupoUsuario.getId()));
cont++;
}else{
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.GRUPO_ID,
grupoUsuario.getId(), ParametroSimples.CONECTOR_OR));
cont++;
}
}
}
}
// Fim do bloco para adicionar os grupos no filtro
// Inicializa ocontador para auxiliar no filtro das permissões
cont = 1;
// Cria o iterator das permissões
Iterator iteratorPermissoes = permissoes.iterator();
// Laço para inserir todas as operações no filtro
while(iteratorPermissoes.hasNext()){
// Recupera a permissão do iterator
GrupoFuncionalidadeOperacao grupoFuncionalidadeOperacao = (GrupoFuncionalidadeOperacao) iteratorPermissoes.next();
/*
* Caso a coleção de permissões de usuário tenha apenas um
* elemento adiciona a operação no filtro sem o conector
* "OR" Caso contrário vai adicionar as operações uma a uma
* com seus conectores
*/
if(permissoes.size() == 1){
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.OPERACAO_ID,
grupoFuncionalidadeOperacao.getComp_id().getOperacaoId()));
}else{
if(cont == 1){
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.OPERACAO_ID,
grupoFuncionalidadeOperacao.getComp_id().getOperacaoId(), FiltroParametro.CONECTOR_OR,
permissoes.size()));
cont++;
}else{
if(cont == colecaoGruposUsuario.size()){
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(
FiltroUsuarioGrupoRestricao.OPERACAO_ID, grupoFuncionalidadeOperacao.getComp_id()
.getOperacaoId()));
cont++;
}else{
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(
FiltroUsuarioGrupoRestricao.OPERACAO_ID, grupoFuncionalidadeOperacao.getComp_id()
.getOperacaoId(), ParametroSimples.CONECTOR_OR));
cont++;
}
}
}
}
// Fim do bloco para adicionar as operações no filtro
// Pesquisa as restrições do usuário
Collection restricoes = getControladorUtil().pesquisar(filtroUsuarioGrupoRestricao, UsuarioGrupoRestricao.class.getName());
/*
* Caso o nº de restrições for menor que o nº de permissões seta
* a flag para indicar que o usuário tem acesso a funcionalidade
*/
if(restricoes.size() < permissoes.size()){
retorno = true;
/*
* Chama o metódo para registrar o acesso do usuário a
* funcionalidade na tabela UsuarioFavorito
*/
this.registrarFuncionalidadeAcessada(usuarioLogado, funcionalidade);
}
}
}
// Retorna uma flag indicando se o usuário tem acesso a funcionalidade
return retorno;
}
/**
* Metódo que verifica se o usuário tem permissão para acessar a operação
* que está sendo requisitada (existe ocorrência na tabela
* GrupoFuncionalidadeOperacao). Verifica se o(s) grupo(s) que o usuário
* pertence tem acesso a operação e se a operação desta funcionalidade não
* estão com restrição(existe ocorrência na tabela UsuarioGrupoRestricao)
*
* @author Pedro Alexandre
* @date 18/07/2006
* @param usuarioLogado
* @param urlOperacao
* @param colecaoGruposUsuario
* @return
* @throws ControladorException
*/
public boolean verificarAcessoPermitidoOperacao(Usuario usuarioLogado, String urlOperacao, Collection colecaoGruposUsuario)
throws ControladorException{
// Cria a flag que vai indicar se o usuário tem acesso para operação ou
// não
boolean retorno = false;
// Caso a url inicia com barra retira a barra da url
if(urlOperacao.startsWith("/")){
urlOperacao = urlOperacao.substring(1);
}
// Cria o filtro para pesquisar a operação da url informada
// e carrega a funcionalidade da operação
FiltroOperacao filtroOperacao = new FiltroOperacao();
// filtroOperacao.adicionarParametro(new
// ParametroSimples(FiltroOperacao.CAMINHO_URL,urlOperacao));
filtroOperacao.adicionarParametro(new ComparacaoTexto(FiltroOperacao.CAMINHO_URL, urlOperacao));
filtroOperacao.adicionarCaminhoParaCarregamentoEntidade("funcionalidade");
// Pesquisa a operação no sistema com a url informada
Collection colecaoOperacao = getControladorUtil().pesquisar(filtroOperacao, Operacao.class.getName());
// Cria as variáveis que vão armazenar a funcionalidade e a operação
Funcionalidade funcionalidadeOperacao = null;
Operacao operacao = null;
/*
* Caso a coleção de operações não esteja vazia pesquisa as permissões
* do usuário e as restrições
*/
if(colecaoOperacao != null && !colecaoOperacao.isEmpty()){
// Recupera a operação do iterator
operacao = (Operacao) colecaoOperacao.iterator().next();
// Recupera a funcionalidade da operação
funcionalidadeOperacao = operacao.getFuncionalidade();
// Cria a coleção que vai armazenar as funcionalidades permitidas
// para
// cadastrar coma operação requerida
Collection<Funcionalidade> colecaoFuncionalidadesPermitidas = new ArrayList();
colecaoFuncionalidadesPermitidas.add(funcionalidadeOperacao);
/*
* Cria o filtro de funcionalidades depêndencia para pesquisar se a
* funcionalidade da operação requerida pelo usuário tem alguma
* funcionalidade ligada a ela como principal
*/
FiltroFuncionalidadeDependencia filtroFuncionalidadeDependencia = new FiltroFuncionalidadeDependencia();
filtroFuncionalidadeDependencia.adicionarCaminhoParaCarregamentoEntidade("funcionalidadeDependencia");
filtroFuncionalidadeDependencia.adicionarCaminhoParaCarregamentoEntidade("funcionalidade");
filtroFuncionalidadeDependencia.adicionarParametro(new ParametroSimples(
FiltroFuncionalidadeDependencia.FUNCIONALIDADE_DEPENDENCIA, funcionalidadeOperacao.getId()));
Collection colecaoFuncionalidadePrincipal = getControladorUtil().pesquisar(filtroFuncionalidadeDependencia,
FuncionalidadeDependencia.class.getName());
/*
* Caso a coleção de funcionalidades principais não esteja vazia
* adiciona as funcionalidades a coleção de funcionalidades
* permitidas
*/
if(colecaoFuncionalidadePrincipal != null && !colecaoFuncionalidadePrincipal.isEmpty()){
Iterator iteratorFuncionalidadePrincipal = colecaoFuncionalidadePrincipal.iterator();
// Laço para adicionar a funcionalidade a coleção de
// funcionalidades permitidas
while(iteratorFuncionalidadePrincipal.hasNext()){
FuncionalidadeDependencia funcionalidadeDependencia = (FuncionalidadeDependencia) iteratorFuncionalidadePrincipal
.next();
colecaoFuncionalidadesPermitidas.add(funcionalidadeDependencia.getFuncionalidade());
}
}
// Cria o filtro para pesquisar as permissões do usuário para a
// operação informada
FiltroGrupoFuncionalidadeOperacao filtroGrupoFuncionalidadeOperacao = new FiltroGrupoFuncionalidadeOperacao();
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(FiltroGrupoFuncionalidadeOperacao.OPERACAO_ID,
operacao.getId()));
// Cria um contador para inserir os grupos do usuário no filtro
int cont = 1;
/*
* Caso a coleção de funcionalidades permitidas não esteja vazia
* adicona os ids das funcionalidades permitidas no filtro para
* pesquisar as permissões para a operação
*/
if(colecaoFuncionalidadesPermitidas != null && !colecaoFuncionalidadesPermitidas.isEmpty()){
// Cria o iterator das funcionalidades permitidas
Iterator<Funcionalidade> iteratorFuncionalidadesPermitidas = colecaoFuncionalidadesPermitidas.iterator();
// Laço para adicionar os ids das funcionalidades permitidas no
// filtro
while(iteratorFuncionalidadesPermitidas.hasNext()){
// Recupera a funcionalidade do iterator
Funcionalidade funcionalidadePermitida = iteratorFuncionalidadesPermitidas.next();
/*
* Caso a coleção possua uma única funcionalidade permitida
* para o usuário adiciona o id da coleção no filtro sem
* nenhum conector Caso contrário verifica qual a posição do
* iterator para adicionar o id com o conector correto
*/
if(colecaoFuncionalidadesPermitidas.size() == 1){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.FUNCIONALIDADE_ID, funcionalidadePermitida.getId()));
}else{
// Caso seja a primeira funcionalidade adiciona o id com
// o conector "OR"
// e informa quantas funcionalidades vai ter para inseri
// os parenteses
if(cont == 1){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.FUNCIONALIDADE_ID, funcionalidadePermitida.getId(),
FiltroParametro.CONECTOR_OR, colecaoFuncionalidadesPermitidas.size()));
cont++;
}else{
/*
* Caso seja a última funcionalidade da coleção
* adiciona o id da funcionalidade sem conector Caso
* contrário adiciona o id da funcionalidade com o
* conector "OR"
*/
if(cont == colecaoFuncionalidadesPermitidas.size()){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.FUNCIONALIDADE_ID, funcionalidadePermitida.getId()));
cont++;
}else{
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.FUNCIONALIDADE_ID, funcionalidadePermitida.getId(),
ParametroSimples.CONECTOR_OR));
cont++;
}
}
}
}
}
// Inicializa o contador para auxiliar com a coleção de grupos
cont = 1;
// Cria oa iterator dos grupos do usuário
Iterator iteratorGruposUsuario = colecaoGruposUsuario.iterator();
// Laço para adicionar os ids dos grupos no filtro
while(iteratorGruposUsuario.hasNext()){
// Recupera o grupo da coleção
Grupo grupoUsuario = (Grupo) iteratorGruposUsuario.next();
/*
* Caso a coleção de grupos do usuário não esteja vazia adicona
* os ids dos grupos do usuário no filtro para pesquisar as
* permissões para a operação
*/
if(colecaoGruposUsuario.size() == 1){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(FiltroGrupoFuncionalidadeOperacao.GRUPO_ID,
grupoUsuario.getId()));
}else{
// Caso seja o primeiro grupo adiciona o id com o conector
// "OR"
// e informa quantos grupos vai ter para inserir os
// parenteses
if(cont == 1){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.GRUPO_ID, grupoUsuario.getId(), FiltroParametro.CONECTOR_OR,
colecaoGruposUsuario.size()));
cont++;
}else{
/*
* Caso seja o último grupo da coleção adiciona o id do
* grupo sem conector Caso contrário adiciona o id do
* grupo com o conector "OR"
*/
if(cont == colecaoGruposUsuario.size()){
filtroGrupoFuncionalidadeOperacao.adicionarParametro(new ParametroSimples(
FiltroGrupoFuncionalidadeOperacao.GRUPO_ID, grupoUsuario.getId()));
cont++;
}else{
filtroGrupoFuncionalidadeOperacao
.adicionarParametro(new ParametroSimples(FiltroGrupoFuncionalidadeOperacao.GRUPO_ID,
grupoUsuario.getId(), ParametroSimples.CONECTOR_OR));
cont++;
}
}
}
}
// Pesquisa as permissões do usuário
Collection permissoes = getControladorUtil().pesquisar(filtroGrupoFuncionalidadeOperacao,
GrupoFuncionalidadeOperacao.class.getName());
/*
* Caso exista permissões para o usuário acessar a operação pesquisa
* as restrições da operação para o usuário
*/
if(permissoes != null && !permissoes.isEmpty()){
// Cria o filtro para pesquisar as restrições do usuário
// seta no filtro o código do usuário da funcionalidade e da
// operação
FiltroUsuarioGrupoRestricao filtroUsuarioGrupoRestricao = new FiltroUsuarioGrupoRestricao();
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.USUARIO_ID, usuarioLogado
.getId()));
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.OPERACAO_ID, operacao
.getId()));
// Laço para adicionar os ids dos grupos no filtro
while(iteratorGruposUsuario.hasNext()){
// Recupera o grupo da coleção
Grupo grupoUsuario = (Grupo) iteratorGruposUsuario.next();
/*
* Caso a coleção de grupos do usuário não esteja vazia
* adicona os ids dos grupos do usuário no filtro para
* pesquisar as restrições para a operação
*/
if(colecaoGruposUsuario.size() == 1){
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.GRUPO_ID,
grupoUsuario.getId()));
}else{
// Caso seja o primeiro grupo adiciona o id com o
// conector "OR"
// e informa quantos grupos vai ter para inserir os
// parenteses
if(cont == 1){
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.GRUPO_ID,
grupoUsuario.getId(), FiltroParametro.CONECTOR_OR, colecaoGruposUsuario.size()));
cont++;
}else{
/*
* Caso seja o último grupo da coleção adiciona o id
* do grupo sem conector Caso contrário adiciona o
* id do grupo com o conector "OR"
*/
if(cont == colecaoGruposUsuario.size()){
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.GRUPO_ID,
grupoUsuario.getId()));
cont++;
}else{
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(FiltroUsuarioGrupoRestricao.GRUPO_ID,
grupoUsuario.getId(), ParametroSimples.CONECTOR_OR));
cont++;
}
}
}
}
// Inicializa o contador para auxiliar com a coleção de
// funcionalidades permitidas.
cont = 1;
// Caso a coleção de funcionalidades permitidas não esteja
// vazia.
if(colecaoFuncionalidadesPermitidas != null && !colecaoFuncionalidadesPermitidas.isEmpty()){
// Cria o iterator das funcionalidades permitidas.
Iterator<Funcionalidade> iteratorFuncionalidadesPermitidas = colecaoFuncionalidadesPermitidas.iterator();
// Laço para adicionar os ids das funcionalidades permitidas
// no filtro.
while(iteratorFuncionalidadesPermitidas.hasNext()){
// Recupera a funcionalidade do iterator
Funcionalidade funcionalidadePermitida = iteratorFuncionalidadesPermitidas.next();
/*
* Caso a coleção possua uma única funcionalidade
* permitida para o usuário adiciona o id da coleção no
* filtro sem nenhum conector. Caso contrário verifica
* qual a posição do iterator para adicionar o id com o
* conector correto para pesquisar as restrições da
* operação.
*/
if(colecaoFuncionalidadesPermitidas.size() == 1){
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(
FiltroUsuarioGrupoRestricao.FUNCIONALIDADE_ID, funcionalidadePermitida.getId()));
}else{
// Caso seja a primeira funcionalidade adiciona o id
// com o conector "OR"
// e informa quantas funcionalidades vai ter para
// inserir os parenteses.
if(cont == 1){
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(
FiltroUsuarioGrupoRestricao.FUNCIONALIDADE_ID, funcionalidadePermitida.getId(),
FiltroParametro.CONECTOR_OR, colecaoFuncionalidadesPermitidas.size()));
cont++;
}else{
/*
* Caso seja a última funcionalidade da coleção
* adiciona o id da funcionalidade sem conector.
* Caso contrário adiciona o id do grupo com o
* conector "OR".
*/
if(cont == colecaoFuncionalidadesPermitidas.size()){
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(
FiltroUsuarioGrupoRestricao.FUNCIONALIDADE_ID, funcionalidadePermitida.getId()));
cont++;
}else{
filtroUsuarioGrupoRestricao.adicionarParametro(new ParametroSimples(
FiltroUsuarioGrupoRestricao.FUNCIONALIDADE_ID, funcionalidadePermitida.getId(),
ParametroSimples.CONECTOR_OR));
cont++;
}
}
}
}
}
// Pesquisa as restrições do usuário para a operação solicitada
Collection restricoes = getControladorUtil().pesquisar(filtroUsuarioGrupoRestricao, UsuarioGrupoRestricao.class.getName());
/*
* Caso o nº de restrições for menor que o nº de permissões seta
* a flag para indicar que o usuário tem acesso a operação
*/
if(restricoes.size() < permissoes.size()){
retorno = true;
}
}
}
// Retorna uma flag indicando se o usuário tem acesso a operação
return retorno;
}
/**
* [UC0285] - Manter Operação
* Metódo responsável por atualizar uma operação no sistema e os
* relacionamentos entre a tabela e a operação
* [SB0001] - Atualizar Operação
*
* @author Pedro Alexandre
* @date 02/08/2006
* @param operacao
* @param colecaoOperacaoTabela
* @throws ControladorException
*/
public void atualizarOperacao(Operacao operacao, Collection<OperacaoTabela> colecaoOperacaoTabela, Usuario usuarioLogado)
throws ControladorException{
/*
* [FS0009] - Verificar preenchimento dos campos
*/
if(operacao.getDescricao() == null || operacao.getDescricao().trim().equals("")){
throw new ControladorException("atencao.naoinformado", null, "Descrição");
}
if(operacao.getDescricaoAbreviada() == null || operacao.getDescricaoAbreviada().trim().equals("")){
throw new ControladorException("atencao.naoinformado", null, "Descrição Abreviada");
}
if(operacao.getCaminhoUrl() == null || operacao.getCaminhoUrl().trim().equals("")){
throw new ControladorException("atencao.naoinformado", null, "Caminho URL");
}
if(operacao.getFuncionalidade() == null){
throw new ControladorException("atencao.naoinformado", null, "Funcionalidade");
}
if(operacao.getOperacaoTipo() == null){
throw new ControladorException("atencao.naoinformado", null, "Tipo de Operação");
}
if(operacao.getIndicadorAuditoria() != ConstantesSistema.SIM.intValue()
&& operacao.getIndicadorAuditoria() != ConstantesSistema.NAO.intValue()){
throw new ControladorException("atencao.naoinformado", null, "Indicador de Auditoria");
}
/*
* [FS0010] - Atualização realizada por outro usuário Pesquisa a
* operação no base de dados e verifica se a operação foi atualizada por
* outro usuário durante esta operaçãode remoção
*/
FiltroOperacao filtroOperacao = new FiltroOperacao();
filtroOperacao.adicionarParametro(new ParametroSimples(FiltroOperacao.ID, operacao.getId()));
Collection colecaoOperacaoBase = getControladorUtil().pesquisar(filtroOperacao, Operacao.class.getName());
if(colecaoOperacaoBase == null || colecaoOperacaoBase.isEmpty()){
sessionContext.setRollbackOnly();
throw new ControladorException("atencao.atualizacao.timestamp");
}
// Recupera a operação na base de dados
Operacao operacaoNaBase = (Operacao) colecaoOperacaoBase.iterator().next();
/*
* Caso a data de ultima alteração da operação na base for posterior a
* operação que vai ser removida levanta uma exceção para o usuário
* informando que a operação foi atualizada por outro usuário durante a
* tentativa de remoção
*/
if(operacaoNaBase.getUltimaAlteracao().after(operacao.getUltimaAlteracao())){
sessionContext.setRollbackOnly();
throw new ControladorException("atencao.atualizacao.timestamp");
}
/*
* [FS0001] - Verificar existência da descrição verifica se já existe
* uma operação cadastrada com a descrição informada na base de dados
*/
filtroOperacao.limparListaParametros();
String descricaoOperacaoNaBase = operacaoNaBase.getDescricao();
if(!operacao.getDescricao().equalsIgnoreCase(descricaoOperacaoNaBase)){
filtroOperacao.adicionarParametro(new ParametroSimples(FiltroOperacao.DESCRICAO, operacao.getDescricao()));
Collection colecaoOperacaoComDescricao = getControladorUtil().pesquisar(filtroOperacao, Operacao.class.getName());
if(colecaoOperacaoComDescricao != null && !colecaoOperacaoComDescricao.isEmpty()){
throw new ControladorException("atencao.descricao_ja_existente", null, operacao.getDescricao() + "");
}
}
/*
* [FS0002] - Verificar existência da url verifica se já existe uma
* operação cadastrada com a url informada
*/
filtroOperacao.limparListaParametros();
String urlOperacaoNaBase = operacaoNaBase.getCaminhoUrl();
if(!operacao.getCaminhoUrl().equalsIgnoreCase(urlOperacaoNaBase)){
filtroOperacao.adicionarParametro(new ParametroSimples(FiltroOperacao.CAMINHO_URL, operacao.getCaminhoUrl()));
Collection colecaoOperacaoComURL = getControladorUtil().pesquisar(filtroOperacao, Operacao.class.getName());
if(colecaoOperacaoComURL != null && !colecaoOperacaoComURL.isEmpty()){
throw new ControladorException("atencao.url_ja_existente", null, operacao.getCaminhoUrl() + "");
}
}
/*
* [FS0004 - Verificar existência da funcionalidade] Cria o filtro de
* funcionalidade para verificar se existe a funcionalidade informada
*/
FiltroFuncionalidade filtroFuncionalidade = new FiltroFuncionalidade();
filtroFuncionalidade.adicionarParametro(new ParametroSimples(FiltroFuncionalidade.ID, operacao.getFuncionalidade().getId()));
Collection colecaoFuncionalidade = getControladorUtil().pesquisar(filtroFuncionalidade, Funcionalidade.class.getName());
// Caso a funcionalidade informada não esteja cadastrada no sistema
// levanta uma exceção para o cliente
if(colecaoFuncionalidade == null || colecaoFuncionalidade.isEmpty()){
throw new ControladorException("atencao.funcionalidade.inexistente", null, operacao.getDescricao());
}
// Cria a variável que vai aramzenar o tipo da operação
OperacaoTipo operacaoTipo = null;
/*
* Caso o tipo da operação tenha sido informada pesquisa o tipo da
* operação no sistema Caso contrário levanta uma exceção indicando que
* o tipo da operação não foi informada
*/
if(operacao.getOperacaoTipo() != null){
FiltroOperacaoTipo filtroOperacaoTipo = new FiltroOperacaoTipo();
filtroOperacaoTipo.adicionarParametro(new ParametroSimples(FiltroOperacaoTipo.ID, operacao.getOperacaoTipo().getId()));
Collection colecaoOperacaoTipo = getControladorUtil().pesquisar(filtroOperacaoTipo, OperacaoTipo.class.getName());
/*
* Caso o tipo da operação informada não exista levanta uma exceção
* indicando que o tipo da operação não existe Caso contrário
* recupera o tipo da operação da coleção pesquisada
*/
if(colecaoOperacaoTipo == null || colecaoOperacaoTipo.isEmpty()){
throw new ControladorException("atencao.operacao_tipo.inexistente", null, "" + operacao.getOperacaoTipo().getId());
}else{
operacaoTipo = (OperacaoTipo) Util.retonarObjetoDeColecao(colecaoOperacaoTipo);
}
}else{
throw new ControladorException("atencao.operacao_tipo.nao.informado", null);
}
// Caso o tipo da operação informada seja pesquisar
// verifica o preenchimento do argumento de pesquisa
if(operacaoTipo.getId().intValue() == OperacaoTipo.PESQUISAR.intValue()){
// Caso o argumento de pesquisa não tenha sido informado
// levanta uma exceção indicando que o argumento de pesquisa não foi
// informado
if(operacao.getTabelaColuna() == null){
throw new ControladorException("atencao.argumento_pesquisa.nao.informado", null);
}else{
// [FS0005 - Verificar existência do argumento de pesquisa]
// Cria o filtro para pesqusiar o argumento de pesquisa
// informado
FiltroTabelaColuna filtroTabelaColuna = new FiltroTabelaColuna();
filtroTabelaColuna.adicionarParametro(new ParametroSimples(FiltroTabelaColuna.ID, operacao.getTabelaColuna().getId()));
// Pesquisa o argumento de pesquisa
Collection colecaoTabelaColuna = getControladorUtil().pesquisar(filtroTabelaColuna, TabelaColuna.class.getName());
/*
* Caso o argumento de pesquisa não esteja cadastrado levanta
* uma exceção indicando que o argumento de pesquisa não existe
* Caso contrário recupera o argumento de pesquisa da coleção
*/
if(colecaoTabelaColuna == null || colecaoTabelaColuna.isEmpty()){
throw new ControladorException("atencao.argumento_pesquisa.inexistente", null);
}else{
// [FS0013 - Verificar argumento de pesquisa]
TabelaColuna argumentoPesquisa = (TabelaColuna) Util.retonarObjetoDeColecao(colecaoTabelaColuna);
/*
* Caso o argumento de pesquisa informado não seja chave
* primária levanta uma exceçaõ indicando que o argumento de
* pesquisa não é chave primária da tabela
*/
if(argumentoPesquisa.getIndicadorPrimaryKey() == ConstantesSistema.NAO){
throw new ControladorException("atencao.argumento_pesquisa.nao.chave.primaria", null);
}
// Cria o filtro para verificar se já existe operação com o
// argumento de pesquisa informado
FiltroOperacao filtroOperacaoComArgumentoPesquisa = new FiltroOperacao();
filtroOperacaoComArgumentoPesquisa.adicionarParametro(new ParametroSimples(FiltroOperacao.TABELA_COLUNA_ID,
argumentoPesquisa.getId()));
Collection colecaoOperacaoComArgumentoPesquisa = getControladorUtil().pesquisar(filtroOperacaoComArgumentoPesquisa,
Operacao.class.getName());
/*
* Caso já existe operação com o argumento de pesquisa
* informado levanta uma exceção indicando que já existe uma
* operação com o argumento de pesquisa informado
*/
if(colecaoOperacaoComArgumentoPesquisa != null && !colecaoOperacaoComArgumentoPesquisa.isEmpty()){
Operacao operacaoComArgumentoPesquisa = (Operacao) Util.retonarObjetoDeColecao(colecaoOperacaoComArgumentoPesquisa);
throw new ControladorException("atencao.argumento_pesquisa.ja.associado", null, operacaoComArgumentoPesquisa
.getDescricao());
}
}
}
}else{
// Caso o tipo de operação não seja "pesquisar"
if(operacaoTipo.getIndicadorAtualiza() == ConstantesSistema.SIM){
// Caso o usuário não tenha informado nenhuma tabela
if(colecaoOperacaoTabela == null || colecaoOperacaoTabela.isEmpty()){
throw new ControladorException("atencao.tabela.nao.informada", null);
}
// [FS0007 - Verificar existência da operação]
if(operacao.getOperacaoPesquisa() != null){
// Cria o filtro para pesquisar a operação de pesquisa
// informada
FiltroOperacao filtroOperacaoPesquisa = new FiltroOperacao();
filtroOperacaoPesquisa.adicionarParametro(new ParametroSimples(FiltroOperacao.ID, operacao.getOperacaoPesquisa()
.getId()));
Collection colecaoOperacaoPesquisa = getControladorUtil().pesquisar(filtroOperacaoPesquisa, Operacao.class.getName());
// Caso a operação de pesquisa não esteja cadastrada
// levanta uma exceção indicando que a operação de pesquisa
// não existe
if(colecaoOperacaoPesquisa == null || colecaoOperacaoPesquisa.isEmpty()){
throw new ControladorException("atencao.operacao_pesquisa.inexistente", null);
}
}
}
}
// ------------ REGISTRAR TRANSAÇÃO ----------------
RegistradorOperacao registradorOperacao = new RegistradorOperacao(Operacao.OPERACAO_OPERACAO_ATUALIZAR,
new UsuarioAcaoUsuarioHelper(usuarioLogado, UsuarioAcao.USUARIO_ACAO_EFETUOU_OPERACAO));
Operacao operacaoRegistrarTransacao = new Operacao();
operacaoRegistrarTransacao.setId(Operacao.OPERACAO_OPERACAO_ATUALIZAR);
OperacaoEfetuada operacaoEfetuada = new OperacaoEfetuada();
operacaoEfetuada.setOperacao(operacaoRegistrarTransacao);
operacao.setOperacaoEfetuada(operacaoEfetuada);
operacao.adicionarUsuario(usuarioLogado, UsuarioAcao.USUARIO_ACAO_EFETUOU_OPERACAO);
registradorOperacao.registrarOperacao(operacao);
// ------------ REGISTRAR TRANSAÇÃO ----------------
// Seta a data de ultima alteração e atualiza a operação
operacao.setUltimaAlteracao(new Date());
getControladorUtil().atualizar(operacao);
/*
* Cria o filtro para recuperar os relacionamentos entre a operação e a
* tabela
*/
FiltroOperacaoTabela filtroOperacaoTabela = new FiltroOperacaoTabela();
filtroOperacaoTabela.adicionarParametro(new ParametroSimples(FiltroOperacaoTabela.OPERACAO_ID, operacao.getId()));
Collection<OperacaoTabela> colecaoOperacaoTabelaNaBase = getControladorUtil().pesquisar(filtroOperacaoTabela,
OperacaoTabela.class.getName());
/*
* Caso exista tabela relacionadas com a operação remove os
* relacionamentos da base caso o relacionamento tenha sido removido
* pelo usuário ou remove da coleção que dos novos relacionamentos
* marcados caso já exista na base
*/
if(colecaoOperacaoTabelaNaBase != null && !colecaoOperacaoTabelaNaBase.isEmpty() && colecaoOperacaoTabela != null
&& !colecaoOperacaoTabela.isEmpty()){
// Cria o iterator do relacionamento entre tabela e operação
Iterator<OperacaoTabela> iteratorOperacaoTabelaNaBase = colecaoOperacaoTabelaNaBase.iterator();
/*
* Laço para remover os relacionamentos entre tabela e operação que
* foram removidos pelo usuário
*/
while(iteratorOperacaoTabelaNaBase.hasNext()){
// Recupera o relacionamento da base de dados do iterator
OperacaoTabela operacaoTabelaNaBase = iteratorOperacaoTabelaNaBase.next();
/*
* Caso a coleção informada pelo usuário não tenha o
* relacionamento que está na na base de dados remove o
* relacionamento da base de dados
*/
if(!colecaoOperacaoTabela.contains(operacaoTabelaNaBase)){
// ------------ REGISTRAR TRANSAÇÃO ----------------
// operacaoTabelaNaBase.setOperacaoEfetuada(operacaoEfetuada);
// operacaoTabelaNaBase.adicionarUsuario(usuarioLogado,
// UsuarioAcao.USUARIO_ACAO_EFETUOU_OPERACAO);
// registradorOperacao.registrarOperacao(operacaoTabelaNaBase);
// ------------ REGISTRAR TRANSAÇÃO ----------------
// Remove o relacionamento entre tabela e operação
getControladorUtil().remover(operacaoTabelaNaBase);
}else{
colecaoOperacaoTabela.remove(operacaoTabelaNaBase);
}
}
}
/*
* Caso a coleção de relacionamento entre tabela e operação ainda tenha
* algum relacionamento que foi informado pelo usuário e que ainda não
* esteja cadastrado na base de dados inseri o relacionamento na base de
* dados
*/
if(colecaoOperacaoTabela != null && !colecaoOperacaoTabela.isEmpty()){
// Cria o iterator para inserir os relacionamentos entre tabela e
// operação
Iterator<OperacaoTabela> iteratorOperacaoTabelaInformado = colecaoOperacaoTabela.iterator();
// Laço para inserir o relacionamento entre tabela e operação
while(iteratorOperacaoTabelaInformado.hasNext()){
// Recupera o relacionamento informado pelo usuário
OperacaoTabela operacaoTabelaInformado = iteratorOperacaoTabelaInformado.next();
// ------------ REGISTRAR TRANSAÇÃO ----------------
// operacaoTabelaInformado.setOperacaoEfetuada(operacaoEfetuada);
// operacaoTabelaInformado.adicionarUsuario(usuarioLogado,
// UsuarioAcao.USUARIO_ACAO_EFETUOU_OPERACAO);
// registradorOperacao.registrarOperacao(operacaoTabelaInformado);
// ------------ REGISTRAR TRANSAÇÃO ----------------
// Inseri o relacionamento entre tabela e operação
getControladorUtil().inserir(operacaoTabelaInformado);
}
}
}
/**
* [UC0285] - Manter Operação
* Metódo responsável por remover uma operação no sistema e os
* relacionamentos entre a tabela e a operação
* [SB0002] - Excluir Operação
*
* @author Pedro Alexandre
* @date 02/08/2006
* @param idsOperacao
* @throws ControladorException
*/
public void removerOperacao(String[] idsOperacao, Usuario usuarioLogado) throws ControladorException{
// ------------ REGISTRAR TRANSAÇÃO ----------------
RegistradorOperacao registradorOperacao = new RegistradorOperacao(Operacao.OPERACAO_OPERACAO_REMOVER, new UsuarioAcaoUsuarioHelper(
usuarioLogado, UsuarioAcao.USUARIO_ACAO_EFETUOU_OPERACAO));
Operacao operacaoRegistrarTransacao = new Operacao();
operacaoRegistrarTransacao.setId(Operacao.OPERACAO_OPERACAO_REMOVER);
OperacaoEfetuada operacaoEfetuada = new OperacaoEfetuada();
operacaoEfetuada.setOperacao(operacaoRegistrarTransacao);
// ------------ REGISTRAR TRANSAÇÃO ----------------
// Laço para remover todas as operações selecionadas
for(int i = 0; i < idsOperacao.length; i++){
// Cria o filtro para pesquisar a operação que vai ser removida
FiltroOperacao filtroOperacao = new FiltroOperacao();
filtroOperacao.adicionarParametro(new ParametroSimples(FiltroOperacao.ID, idsOperacao[i]));
Collection colecaoOperacao = getControladorUtil().pesquisar(filtroOperacao, Operacao.class.getName());
/*
* Caso a pesquisa retorne a operação selecionada para remoção
* recupera a operação da coleçaõ de pesquisa para ser removida Caso
* contrário passa para a próxima operação no array
*/
if(colecaoOperacao != null && !colecaoOperacao.isEmpty()){
// Recupera a operação que vai ser removida
Operacao operacao = (Operacao) colecaoOperacao.iterator().next();
// Cria o filtro para recuperar os relacionamentos entre a
// operação e as tabelas da operação
FiltroOperacaoTabela filtroOperacaoTabela = new FiltroOperacaoTabela();
filtroOperacaoTabela.adicionarParametro(new ParametroSimples(FiltroOperacaoTabela.OPERACAO_ID, operacao.getId()));
Collection colecaoOperacaoTabela = getControladorUtil().pesquisar(filtroOperacaoTabela, OperacaoTabela.class.getName());
/*
* Caso exista relacionamentos entre operação e tabela
* cadastradas para a operação que vai ser removida, remove os
* relacionamentos antes de remover a operação
*/
if(colecaoOperacaoTabela != null && !colecaoOperacaoTabela.isEmpty()){
// Coloca a coleção de TabelaOPeracao no iterator
Iterator<OperacaoTabela> iteratorOperacaoTabela = colecaoOperacaoTabela.iterator();
// Laço para remover todos os relacionamentos TabelaOperacao
while(iteratorOperacaoTabela.hasNext()){
// Recupera o relacionamento da coleção
OperacaoTabela operacaoTabela = iteratorOperacaoTabela.next();
// ------------ REGISTRAR TRANSAÇÃO ----------------
// operacaoTabela.setOperacaoEfetuada(operacaoEfetuada);
// operacaoTabela.adicionarUsuario(usuarioLogado,
// UsuarioAcao.USUARIO_ACAO_EFETUOU_OPERACAO);
// registradorOperacao.registrarOperacao(operacaoTabela);
// ------------ REGISTRAR TRANSAÇÃO ----------------
// Remove o relacionamento
getControladorUtil().remover(operacaoTabela);
}
}
// ------------ REGISTRAR TRANSAÇÃO ----------------
operacao.setOperacaoEfetuada(operacaoEfetuada);
operacao.adicionarUsuario(usuarioLogado, UsuarioAcao.USUARIO_ACAO_EFETUOU_OPERACAO);
registradorOperacao.registrarOperacao(operacao);
// ------------ REGISTRAR TRANSAÇÃO ----------------
// Remove a operação selecionada
getControladorUtil().remover(operacao);
}
}
}
/**
* Metódo responsável por registrar a funcionalidade que o usuário está
* acessando no momento
*
* @author Pedro Alexandre
* @date 08/08/2006
* @param usuarioLogado
* @param funcionalidade
* @throws ControladorException
*/
private void registrarFuncionalidadeAcessada(Usuario usuarioLogado, Funcionalidade funcionalidade) throws ControladorException{
// /*
// * Caso a funcionalidade seja ponto de entrada registra o acesso a
// * funcionalidade pelo usuário (incluir na tabela UsuarioFavorito)
// */
// if(funcionalidade.getIndicadorPontoEntrada().equals(ConstantesSistema.SIM)){
//
// // Recupera o nº máximo de funcionalidades registradas para últimos
// // acessos
// SistemaParametro sistemaParametros = getControladorUtil().pesquisarParametrosDoSistema();
// int numeroMaximoFavorito = sistemaParametros.getNumeroMaximoFavorito();
//
// // Cria o objeto UsuarioFavorito que representa a funcionalidade
// // acessada pelo usuário
// UsuarioFavorito usuarioFavorito = new UsuarioFavorito(new
// UsuarioFavoritoPK(usuarioLogado.getId(), funcionalidade.getId()),
// new Short("1"), new Date(), funcionalidade, usuarioLogado);
//
// // Cria o filtro para pesquisar os últimos acessos do usuário
// FiltroUsuarioFavorito filtroUsuarioFavoritoCadastrados = new FiltroUsuarioFavorito();
// filtroUsuarioFavoritoCadastrados.adicionarParametro(new
// ParametroSimples(FiltroUsuarioFavorito.USUARIO_ID, usuarioLogado
// .getId()));
// filtroUsuarioFavoritoCadastrados.adicionarParametro(new ParametroSimples(
// FiltroUsuarioFavorito.INDICADOR_FAVORITO_ULTIMO_ACESSADO, ConstantesSistema.SIM));
// filtroUsuarioFavoritoCadastrados.setCampoOrderBy(FiltroUsuarioFavorito.ULTIMA_ALTERACAO);
// Collection<UsuarioFavorito> colecaoUsuarioFavoritosCadastrados =
// getControladorUtil().pesquisar(
// filtroUsuarioFavoritoCadastrados, UsuarioFavorito.class.getName());
//
// /*
// * Caso a coleção de ultimos acessos do usuário esteja vazia
// * registra o primeiro acesso do usuário no sistema
// */
// if(colecaoUsuarioFavoritosCadastrados == null ||
// colecaoUsuarioFavoritosCadastrados.isEmpty()){
// getControladorUtil().inserir(usuarioFavorito);
// }else{
// /*
// * Caso já exista acessos cadatrado para o usuário que está
// * logado e o nº de acessos registrados seja menor que o máximo
// * permitido verifica se já existe registro para a
// * funcionalidade acessada se existir atualiza a data de último
// * acesso se não existir inseri o registro na tabela
// * UsuarioFavorito
// */
// if(colecaoUsuarioFavoritosCadastrados.size() < numeroMaximoFavorito){
// if(!colecaoUsuarioFavoritosCadastrados.contains(usuarioFavorito)){
// getControladorUtil().inserir(usuarioFavorito);
// }else{
// getControladorUtil().atualizar(usuarioFavorito);
// }
// }else{
// /*
// * Caso o nº de de acessos registrados seja igual ao nº
// * máximo permitido verifica se a funcionalidade acessada já
// * está registrada para este usuário Caso já esteja
// * registrada para o usuário atualiza apenas a data de
// * última alteração Caso não esteja registrada remove o
// * registro com menor data de último acesso e adiciona o
// * novo acesso.
// */
// if(colecaoUsuarioFavoritosCadastrados.size() == numeroMaximoFavorito){
// /*
// * Caso o acesso feito pelo usuário logado não esteja
// * cadastrado remove o acesso com a data de ultimo
// * acesso menor
// */
// if(!colecaoUsuarioFavoritosCadastrados.contains(usuarioFavorito)){
//
// // Recupera o acesso que foi acessado mais
// // antigamente para ser removido
// UsuarioFavorito usuarioFavoritoUltimoAcessado =
// colecaoUsuarioFavoritosCadastrados.iterator().next();
// getControladorUtil().remover(usuarioFavoritoUltimoAcessado);
//
// // Inseri o acesso mais recente a funcionalidade
// getControladorUtil().inserir(usuarioFavorito);
// }else{
// // Atualiza a data de ultimo acesso
// getControladorUtil().atualizar(usuarioFavorito);
// }
// }else{
// // Caso o nº de acessos for maior que o permitido
// }
// }
// }
// }
}
/**
* Metódo responsável por verificar se o usuário tem abrangência sobre a
* operação e o nível de informação que estão sendo informados.
* [UC0XXX] Verificar Acesso Abrangência
*
* @author Pedro Alexandre
* @date 08/11/2006
* @param abrangencia
* @return
* @throws ControladorException
*/
public boolean verificarAcessoAbrangencia(Abrangencia abrangencia) throws ControladorException{
this.carregarAbrangencia(abrangencia);
boolean retorno = true;
UsuarioAbrangencia usuarioAbrangencia = abrangencia.getUsuario().getUsuarioAbrangencia();
// DADOS INFORMADOS PARA EXECUTAR A OPERAÇÃO
GerenciaRegional gerenciaRegionalInformada = abrangencia.getGerenciaRegional();
UnidadeNegocio unidadeNegocioInformada = abrangencia.getUnidadeNegocio();
Localidade eloPoloInformado = abrangencia.getEloPolo();
Localidade localidadeInformada = abrangencia.getLocalidade();
// ABRANGENCIA DO USUARIO
GerenciaRegional gerenciaRegionalUsuario = abrangencia.getUsuario().getGerenciaRegional();
// UnidadeNegocio unidadeNegocioUsuario =
// abrangencia.getUsuario().getUnidadeNegocio();
Localidade eloPoloUsuario = abrangencia.getUsuario().getLocalidadeElo();
Localidade localidadeUsuario = abrangencia.getUsuario().getLocalidade();
Integer nivelAbrangencia = usuarioAbrangencia.getId();
switch(nivelAbrangencia.intValue()){
case UsuarioAbrangencia.ESTADO_INT:
retorno = true;
break;
case UsuarioAbrangencia.GERENCIA_REGIONAL_INT:
if(gerenciaRegionalInformada != null){
if(gerenciaRegionalUsuario.getId().intValue() == gerenciaRegionalInformada.getId().intValue()){
retorno = true;
}else{
retorno = false;
}
}else{
retorno = false;
}
break;
case UsuarioAbrangencia.UNIDADE_NEGOCIO_INT:
if(unidadeNegocioInformada != null){
if(unidadeNegocioInformada.getId().intValue() == unidadeNegocioInformada.getId().intValue()){
retorno = true;
}else{
retorno = false;
}
}else{
retorno = false;
}
break;
case UsuarioAbrangencia.ELO_POLO_INT:
if(eloPoloInformado != null){
if(eloPoloUsuario.getId().intValue() == eloPoloInformado.getId().intValue()){
retorno = true;
}else{
retorno = false;
}
}else{
retorno = false;
}
break;
case UsuarioAbrangencia.LOCALIDADE_INT:
if(localidadeInformada != null){
if(localidadeUsuario.getId().intValue() == localidadeInformada.getId().intValue()){
retorno = true;
}else{
retorno = false;
}
}else{
retorno = false;
}
break;
}
return retorno;
}
/**
* <Breve descrição sobre o caso de uso>
* <Identificador e nome do caso de uso>
*
* @author Pedro Alexandre
* @date 13/11/2006
* @param abrangencia
*/
private void carregarAbrangencia(Abrangencia abrangencia) throws ControladorException{
GerenciaRegional gerenciaRegional = abrangencia.getGerenciaRegional();
UnidadeNegocio unidadeNegocio = abrangencia.getUnidadeNegocio();
Localidade eloPolo = abrangencia.getEloPolo();
Localidade localidade = abrangencia.getLocalidade();
Imovel imovel = abrangencia.getImovel();
SetorComercial setorComercial = abrangencia.getSetorComercial();
Quadra quadra = abrangencia.getQuadra();
String consulta = null;
try{
if(gerenciaRegional != null){
// para gerência não precisa carregar nada
}else if(unidadeNegocio != null){
consulta = "from UnidadeNegocio as unidadeNegocio " + "inner join fetch unidadeNegocio.gerenciaRegional gerenciaRegional "
+ "where unidadeNegocio.id = " + unidadeNegocio.getId();
UnidadeNegocio unidadeNegocioPesquisado = (UnidadeNegocio) this.repositorioAcesso.pesquisarObjetoAbrangencia(consulta);
if(unidadeNegocioPesquisado != null && unidadeNegocioPesquisado.getGerenciaRegional() != null){
abrangencia.setGerenciaRegional(unidadeNegocioPesquisado.getGerenciaRegional());
}
}else if(eloPolo != null){
consulta = "from Localidade as elo " + "left join fetch elo.unidadeNegocio unidadeNegocio "
+ "left join fetch unidadeNegocio.gerenciaRegional gerenciaRegional " + "where elo.localidade.id = "
+ eloPolo.getId();
Localidade eloPoloPesquisado = (Localidade) this.repositorioAcesso.pesquisarObjetoAbrangencia(consulta);
if(eloPoloPesquisado != null && eloPoloPesquisado.getUnidadeNegocio() != null){
abrangencia.setUnidadeNegocio(eloPoloPesquisado.getUnidadeNegocio());
abrangencia.setGerenciaRegional(eloPoloPesquisado.getUnidadeNegocio().getGerenciaRegional());
}
}else if(localidade != null){
consulta = "from Localidade as localidade " + "inner join fetch localidade.localidade elo "
+ "left join fetch elo.unidadeNegocio unidadeNegocio "
+ "left join fetch unidadeNegocio.gerenciaRegional gerenciaRegional " + "where localidade.id = "
+ localidade.getId();
Localidade localidadePesquisada = (Localidade) this.repositorioAcesso.pesquisarObjetoAbrangencia(consulta);
if(localidadePesquisada != null && localidadePesquisada.getLocalidade() != null){
abrangencia.setEloPolo(localidadePesquisada.getLocalidade());
abrangencia.setUnidadeNegocio(localidadePesquisada.getLocalidade().getUnidadeNegocio());
if(localidadePesquisada.getLocalidade().getUnidadeNegocio() != null){
abrangencia.setGerenciaRegional(localidadePesquisada.getLocalidade().getUnidadeNegocio().getGerenciaRegional());
}
}
}else if(imovel != null){
consulta = "from Imovel as imovel " + "inner join fetch imovel.localidade localidade "
+ "inner join fetch localidade.localidade elo " + "left join fetch elo.unidadeNegocio unidadeNegocio "
+ "left join fetch unidadeNegocio.gerenciaRegional gerenciaRegional " + "where imovel.id = "
+ imovel.getId();
Imovel imovelPesquisado = (Imovel) this.repositorioAcesso.pesquisarObjetoAbrangencia(consulta);
if(imovelPesquisado != null && imovelPesquisado.getLocalidade() != null
&& imovelPesquisado.getLocalidade().getLocalidade() != null){
abrangencia.setLocalidade(imovelPesquisado.getLocalidade());
abrangencia.setEloPolo(imovelPesquisado.getLocalidade().getLocalidade());
abrangencia.setUnidadeNegocio(imovelPesquisado.getLocalidade().getLocalidade().getUnidadeNegocio());
if(imovelPesquisado.getLocalidade().getLocalidade().getUnidadeNegocio() != null){
abrangencia.setGerenciaRegional(imovelPesquisado.getLocalidade().getLocalidade().getUnidadeNegocio()
.getGerenciaRegional());
}
}
}else if(setorComercial != null){
consulta = "from SetorComercial as setorComercial " + "inner join fetch setorComercial.localidade localidade "
+ "inner join fetch localidade.localidade elo " + "left join fetch elo.unidadeNegocio unidadeNegocio "
+ "left join fetch unidadeNegocio.gerenciaRegional gerenciaRegional " + "where setorComercial.id = "
+ setorComercial.getId();
SetorComercial setorComercialPesquisado = (SetorComercial) this.repositorioAcesso.pesquisarObjetoAbrangencia(consulta);
if(setorComercialPesquisado != null && setorComercialPesquisado.getLocalidade() != null
&& setorComercialPesquisado.getLocalidade().getLocalidade() != null){
abrangencia.setLocalidade(setorComercialPesquisado.getLocalidade());
abrangencia.setEloPolo(setorComercialPesquisado.getLocalidade().getLocalidade());
abrangencia.setUnidadeNegocio(setorComercialPesquisado.getLocalidade().getLocalidade().getUnidadeNegocio());
if(setorComercialPesquisado.getLocalidade().getLocalidade().getUnidadeNegocio() != null){
abrangencia.setGerenciaRegional(setorComercialPesquisado.getLocalidade().getLocalidade().getUnidadeNegocio()
.getGerenciaRegional());
}
}
}else if(quadra != null){
consulta = "from Quadra as quadra " + "inner join fetch quadra.setorComercial setorComercial "
+ "inner join fetch setorComercial.localidade localidade " + "inner join fetch localidade.localidade elo "
+ "left join fetch elo.unidadeNegocio unidadeNegocio "
+ "left join fetch unidadeNegocio.gerenciaRegional gerenciaRegional " + "where quadra.id = "
+ quadra.getId();
Quadra quadraPesquisada = (Quadra) this.repositorioAcesso.pesquisarObjetoAbrangencia(consulta);
if(quadraPesquisada != null && quadraPesquisada.getSetorComercial() != null
&& quadraPesquisada.getSetorComercial().getLocalidade() != null){
abrangencia.setSetorComercial(quadraPesquisada.getSetorComercial());
abrangencia.setLocalidade(quadraPesquisada.getSetorComercial().getLocalidade());
abrangencia.setEloPolo(quadraPesquisada.getSetorComercial().getLocalidade().getLocalidade());
abrangencia.setUnidadeNegocio(quadraPesquisada.getSetorComercial().getLocalidade().getLocalidade().getUnidadeNegocio());
if(quadraPesquisada.getSetorComercial().getLocalidade().getLocalidade().getUnidadeNegocio() != null){
abrangencia.setGerenciaRegional(quadraPesquisada.getSetorComercial().getLocalidade().getLocalidade()
.getUnidadeNegocio().getGerenciaRegional());
}
}
}/*
* else if(municipio != null){ consulta = "from Municipio as
* municipio " + "inner join fetch municipio.setorComercial
* setorComercial " + "inner join fetch
* setorComercial.localidade localidade " + "inner join fetch
* localidade.localidade elo " + "inner join fetch
* elo.unidadeNegocio unidadeNegocio " + "inner join fetch
* unidadeNegocio.gerenciaRegional gerenciaRegional " + "where
* municipio.id = " + municipio.getId();
* Municipio municipioPesquisada =
* (Municipio)repositorioAcesso.pesquisarObjetoAbrangencia(consulta);
* abrangencia.setSetorComercial(municipioPesquisada.getSetorComercial());
* abrangencia.setLocalidade(municipioPesquisada.getSetorComercial().getLocalidade());
* abrangencia.setEloPolo(municipioPesquisada.getSetorComercial().getLocalidade().
* getLocalidade());
*
* abrangencia.setUnidadeNegocio(municipioPesquisada.getSetorComercial().getLocalidade().
* getLocalidade().getUnidadeNegocio());
*
* abrangencia.setGerenciaRegional(municipioPesquisada.getSetorComercial().getLocalidade(
* ).getLocalidade().getUnidadeNegocio().getGerenciaRegional()); }
*/
}catch(ErroRepositorioException e){
throw new ControladorException("Erro no Hibernate", e);
}
}
/**
* [UC3043] Registrar Log de Execução do Processo
* Registra uma mensagem no log do processo em execução
*
* @author Hugo Lima
* @date 19/12/2011
* @param idFuncionalidadeIniciada
* @param mensagem
* @throws ControladorException
*/
public void registrarLogExecucaoProcesso(Integer idFuncionalidadeIniciada, String mensagem) throws ControladorException{
try{
// 2. Caso exista o parâmetro de sistema referente ao registro de log do processo (a
// partir da tabela PARAMETRO_SISTEMA com PASI_CDPARAMETRO = “P_REGISTRO_LOG_PROCESSO”),
// e seu valor seja (PASI_VLPARAMETRO) seja igual a 1
if(ParametroBatch.P_REGISTRO_LOG_PROCESSO.executar().equals(ConstantesSistema.SIM.toString())){
// Consulta a funcionalidade passada no parametro
FiltroFuncionalidadeIniciada filtroFuncionalidadeIniciada = new FiltroFuncionalidadeIniciada();
filtroFuncionalidadeIniciada.adicionarParametro(new ParametroSimples(FiltroFuncionalidadeIniciada.ID,
idFuncionalidadeIniciada));
Collection colecaoFuncionalidadeIniciada = Fachada.getInstancia().pesquisar(filtroFuncionalidadeIniciada,
FuncionalidadeIniciada.class.getName());
FuncionalidadeIniciada funcionalidadeIniciada = (FuncionalidadeIniciada) Util
.retonarObjetoDeColecao(colecaoFuncionalidadeIniciada);
// 2.1. O sistema adiciona a mensagem recebida no final do log do processo em
// execução
funcionalidadeIniciada.adicionarLinhaTextoLogExecucao(mensagem);
// funcionalidadeIniciada.setTextoLogExecucao(IoUtil.transformarObjetoParaBytes(mensagem));
this.getControladorUtil().atualizar(funcionalidadeIniciada);
}
}catch(Exception e){
throw new ControladorException(e.getMessage());
}
}
/**
* Consulta os dados de acesso do usuário ao Módulo gestão de Leitura
*
* @author Felipe Rosacruz
* @date 25/03/2014
* @param usuariologado
* @throws ControladorException
*/
public Object[] consultarDadosAcessoGcsME(Usuario usuariologado) throws ControladorException{
Object[] retorno = null;
try{
retorno = repositorioAcesso.consultarDadosAcessoGcsME(usuariologado);
}catch(Exception ex){
throw new ControladorException(ex.getMessage());
}
return retorno;
}
} | [
"Yara.Souza@procenge.com.br"
] | Yara.Souza@procenge.com.br |
eaa3c708e414323f7f876b30984d946e66e4a07f | 5586359a7504701056d33628c5bc353820a04f33 | /EscapeFromInsanityIsland/src/byui/cit260/EscapeFromInsanityIsland/model/WaterChallenge.java | d539d7cdf356a94d9f50c382d6072ede853da7cd | [] | no_license | charphilip/EscapeFromInsanityIslandTeam | 1c83672e4f8011723cbf44a63f2e6d8b2d67cec5 | 32f89ca9366adc4c1212fc7ecb39ac656a0ca05c | refs/heads/master | 2016-09-14T09:23:21.604896 | 2016-05-29T02:08:46 | 2016-05-29T02:08:46 | 58,565,426 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,940 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package byui.cit260.EscapeFromInsanityIsland.model;
import java.io.Serializable;
import java.util.Objects;
/**
*
* @author warllen
*/
public class WaterChallenge extends Challenge implements Serializable{
private int pointsGaineds;
private String experienceReceived;
private String name;
private String problem;
private String solution;
public WaterChallenge() {
}
public int getPointsGaineds() {
return pointsGaineds;
}
public void setPointsGaineds(int pointsGaineds) {
this.pointsGaineds = pointsGaineds;
}
public String getExperienceReceived() {
return experienceReceived;
}
public void setExperienceReceived(String experienceReceived) {
this.experienceReceived = experienceReceived;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProblem() {
return problem;
}
public void setProblem(String problem) {
this.problem = problem;
}
public String getSolution() {
return solution;
}
public void setSolution(String solution) {
this.solution = solution;
}
@Override
public int hashCode() {
int hash = 3;
hash = 17 * hash + this.pointsGaineds;
hash = 17 * hash + Objects.hashCode(this.experienceReceived);
hash = 17 * hash + Objects.hashCode(this.name);
hash = 17 * hash + Objects.hashCode(this.problem);
hash = 17 * hash + Objects.hashCode(this.solution);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final WaterChallenge other = (WaterChallenge) obj;
if (this.pointsGaineds != other.pointsGaineds) {
return false;
}
if (!Objects.equals(this.experienceReceived, other.experienceReceived)) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
if (!Objects.equals(this.problem, other.problem)) {
return false;
}
if (!Objects.equals(this.solution, other.solution)) {
return false;
}
return true;
}
@Override
public String toString() {
return "WaterChallenges{" + "poinGaineds=" + pointsGaineds + ", experienceReceived=" + experienceReceived + ", name=" + name + ", problem=" + problem + ", solution=" + solution + '}';
}
}
| [
"FELIPE@MendiPati"
] | FELIPE@MendiPati |
c3cee44a8e85c91e4ee18d408833d78a1151462b | 4cc6fb1fde80a1730b660ba5ec13ad5f3228ea5c | /java-lihongjie/thinking-in-java-4-code/src/main/java/generics/ByteSet.java | 331b53ef9dc018bb40c6ef09a98448de56efaaa0 | [
"MIT"
] | permissive | lihongjie/tutorials | c598425b085549f5f7a29b1c7bf0c86ae9823c94 | c729ae0eac90564e6366bc4907dcb8a536519956 | refs/heads/master | 2023-08-19T05:03:23.754199 | 2023-08-11T08:25:29 | 2023-08-11T08:25:29 | 124,048,964 | 0 | 0 | MIT | 2018-04-01T06:26:19 | 2018-03-06T08:51:04 | Java | UTF-8 | Java | false | false | 352 | java | package generics;//: generics/ByteSet.java
import java.util.*;
public class ByteSet {
Byte[] possibles = {1, 2, 3, 4, 5, 6, 7, 8, 9};
Set<Byte> mySet =
new HashSet<Byte>(Arrays.asList(possibles));
// But you can't do this:
// Set<Byte> mySet2 = new HashSet<Byte>(
// Arrays.<Byte>asList(1,2,3,4,5,6,7,8,9));
} ///:~
| [
"you@example.com"
] | you@example.com |
16cadd5869599b1153b2bb88222a72e80dbfcb55 | b37726900ee16a5b72a6cd7b2a2d72814fffe924 | /src/main/java/vn/com/vndirect/web/struts2/portlet/MarketNewsAJAXAction.java | 50fc4d6585d946e44e0ccd7f8ad16c8a49dc89b2 | [] | no_license | UnsungHero0/portal | 6b9cfd7271f2b1d587a6f311de49c67e8dd8ff9f | 32325d3e1732d900ee3f874c55890afc8f347700 | refs/heads/master | 2021-01-20T06:18:01.548033 | 2014-11-12T10:27:43 | 2014-11-12T10:27:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,568 | java | package vn.com.vndirect.web.struts2.portlet;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import vn.com.vndirect.business.INewsInfoManager;
import vn.com.vndirect.commons.i18n.I18NUtility;
import vn.com.vndirect.commons.utility.Constants;
import vn.com.vndirect.domain.extend.SearchIfoNews;
import vn.com.vndirect.domain.struts2.portlet.MarketNewsAJAXModel;
import vn.com.web.commons.domain.db.SearchResult;
import vn.com.web.commons.exception.FunctionalException;
import vn.com.web.commons.exception.SystemException;
import vn.com.web.commons.servercfg.ServerConfig;
import vn.com.web.commons.utility.Utilities;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
@SuppressWarnings("serial")
public class MarketNewsAJAXAction extends ActionSupport implements ModelDriven<MarketNewsAJAXModel> {
/* class logger */
private static Logger logger = Logger.getLogger(MarketNewsAJAXAction.class);
/* data model */
private MarketNewsAJAXModel model = new MarketNewsAJAXModel();
@Autowired
private INewsInfoManager newsInfoManager;
/**
* Setting the manager for NewsOnline
*
* @param newsInfoManager
*/
public void setNewsInfoManager(INewsInfoManager newsInfoManager) {
this.newsInfoManager = newsInfoManager;
}
public MarketNewsAJAXModel getModel() {
return model;
}
@SuppressWarnings("unchecked")
public String executeMarketNewsHome() throws FunctionalException, SystemException {
final String LOCATION = "executeMarketOverviewHome";
if (logger.isDebugEnabled()) {
logger.debug(LOCATION + "::BEGIN");
}
try {
SearchIfoNews searchObj = model.getSearchIfoNews();
searchObj.setOrderByDate(true);
searchObj.setStatus(Constants.IServerConfig.DataRef.ItemCodes.NewsStatus.APPROVED);
searchObj.setNewsType(ServerConfig.getOnlineValue(Constants.IServerConfig.DataRef.ItemCodes.NewsType.MARKET_NEWS));
searchObj.setLocale(I18NUtility.getCurrentLocale());
searchObj.setNumberItem(Integer.parseInt(ServerConfig.getOnlineValue(Constants.IServerConfig.Paging.ITEMS_PER_PAGE)));
SearchResult result = newsInfoManager.searchMartketNews(searchObj, model.getPagingInfo());
logger.debug("result:" + result.size());
// request.setAttribute(Constants.Paging.DEFAULT_KEY, result);
model.setSearchResult(result);
} catch (Exception e) {
logger.error(LOCATION + ":: Exception: " + e);
Utilities.processErrors(this, e);
}
if (logger.isDebugEnabled()) {
logger.debug(LOCATION + "::END");
}
return SUCCESS;
}
}
| [
"minh.nguyen@vndirect.com.vn"
] | minh.nguyen@vndirect.com.vn |
0a389a8cf85aed90cfe675a91215ac4cd58e3a8d | 28935683223311c6345a7c7a0ed2e5f19cfa94d8 | /app/src/main/java/com/google/android/apps/exposurenotification/logging/LogcatAnalyticsLogger.java | 1cfbaad46211a84e6e46493ca8d6eaeba6a6a5e8 | [
"Apache-2.0"
] | permissive | isabella232/exposure-notifications-android | 64ba16ea78d56d508874c5eaf2d7611b962cf48f | 0220325466214966368b1f1e5cc0eb8a6a380df7 | refs/heads/master | 2023-06-05T08:16:17.444741 | 2021-06-21T17:25:39 | 2021-06-21T17:28:13 | 380,784,965 | 0 | 0 | Apache-2.0 | 2021-06-27T16:15:55 | 2021-06-27T16:14:38 | null | UTF-8 | Java | false | false | 5,887 | java | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.google.android.apps.exposurenotification.logging;
import android.content.Context;
import android.util.Log;
import androidx.annotation.AnyThread;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import com.google.android.apps.exposurenotification.R;
import com.google.android.apps.exposurenotification.network.VolleyUtils;
import com.google.android.apps.exposurenotification.proto.ApiCall.ApiCallType;
import com.google.android.apps.exposurenotification.proto.RpcCall.RpcCallResult;
import com.google.android.apps.exposurenotification.proto.RpcCall.RpcCallType;
import com.google.android.apps.exposurenotification.proto.UiInteraction.EventType;
import com.google.android.apps.exposurenotification.proto.WorkManagerTask.Status;
import com.google.android.apps.exposurenotification.proto.WorkManagerTask.WorkerTask;
import com.google.android.apps.exposurenotification.storage.AnalyticsLoggingEntity;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.nearby.exposurenotification.ExposureNotificationStatusCodes;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import dagger.hilt.android.qualifiers.ApplicationContext;
import java.util.concurrent.TimeoutException;
import javax.inject.Inject;
/**
* Analytics logger which logs to Logcat only
*/
public class LogcatAnalyticsLogger implements AnalyticsLogger {
private final String healthAuthorityCode;
private final String tag;
@Inject
public LogcatAnalyticsLogger(@ApplicationContext Context context) {
Context appContext = context.getApplicationContext();
healthAuthorityCode = appContext.getResources().getString(R.string.enx_regionIdentifier);
tag = "ENX." + healthAuthorityCode;
Log.i(tag, "Using logcat analytics logger.");
}
@Override
@UiThread
public void logUiInteraction(EventType event) {
if (event == EventType.LOW_STORAGE_WARNING_SHOWN) {
Log.e(tag, event.toString());
} else {
Log.i(tag, event.toString());
}
}
@Override
@AnyThread
public void logWorkManagerTaskStarted(WorkerTask workerTask) {
Log.i(tag, workerTask + " started.");
}
@Override
@AnyThread
public void logApiCallFailure(ApiCallType apiCallType, Exception exception) {
if (exception instanceof ApiException) {
if (((ApiException) exception).getStatusCode()
== ExposureNotificationStatusCodes.RESOLUTION_REQUIRED) {
Log.i(tag, apiCallType + " requires resolution");
return;
}
}
Log.e(tag, apiCallType + " failed.", exception);
}
@Override
@AnyThread
public void logApiCallSuccess(ApiCallType apiCallType) {
Log.i(tag, apiCallType + " succeeded.");
}
@Override
@AnyThread
public ListenableFuture<?> logApiCallFailureAsync(
ApiCallType apiCallType, Exception exception) {
logApiCallFailure(apiCallType, exception);
return Futures.immediateVoidFuture();
}
@Override
@AnyThread
public ListenableFuture<?> logApiCallSuccessAsync(ApiCallType apiCallType) {
logApiCallSuccess(apiCallType);
return Futures.immediateVoidFuture();
}
@Override
@AnyThread
public void logRpcCallSuccess(RpcCallType rpcCallType, int payloadSize) {
Log.i(tag, rpcCallType + " succeeded with payload size: " + payloadSize);
}
@Override
@AnyThread
public void logRpcCallFailure(RpcCallType rpcCallType, Throwable error) {
RpcCallResult rpcCallResult = VolleyUtils.getLoggableResult(error);
int httpStatus = VolleyUtils.getHttpStatus(error);
String errorCode = VolleyUtils.getErrorCode(error);
String errorMessage = VolleyUtils.getErrorMessage(error);
Log.e(tag, rpcCallType + " failed. "
+ " Result:[" + rpcCallResult + "]"
+ " HTTP status:[" + httpStatus + "]"
+ " Server error:[" + errorCode + ":" + errorMessage + "]");
}
@Override
@AnyThread
public ListenableFuture<?> logRpcCallSuccessAsync(RpcCallType rpcCallType, int payloadSize) {
logRpcCallSuccess(rpcCallType, payloadSize);
return Futures.immediateVoidFuture();
}
@Override
@AnyThread
public ListenableFuture<?> logRpcCallFailureAsync(RpcCallType rpcCallType, Throwable error) {
logRpcCallFailure(rpcCallType, error);
return Futures.immediateVoidFuture();
}
@Override
@AnyThread
public void logWorkManagerTaskSuccess(WorkerTask workerTask) {
Log.i(tag, workerTask + " finished with status: " + Status.STATUS_SUCCESS);
}
@Override
@AnyThread
public void logWorkManagerTaskFailure(WorkerTask workerTask, Throwable t) {
Status status = Status.STATUS_FAIL;
if (t instanceof TimeoutException) {
status = Status.STATUS_TIMEOUT;
}
Log.e(tag, workerTask + " failed with status: " + status);
}
@Override
@AnyThread
public void logWorkManagerTaskAbandoned(WorkerTask workerTask) {
Log.e(tag, workerTask + " finished with status: " + Status.STATUS_ABANDONED);
}
@Override
@AnyThread
public ListenableFuture<Void> sendLoggingBatchIfConsented(boolean isENEnabled) {
// No action as logcat logger doesn't send anything off device
Log.i(tag, "LogcatAnalytics logger - no batch upload operation specified");
return Futures.immediateVoidFuture();
}
}
| [
"noreply@google.com"
] | noreply@google.com |
ec18a0d1a47a4911a0844b34f700043e2024c671 | 91312b6add83ec8b9dbc559481c42bf026c2b9b0 | /app/src/main/java/com/example/anilreddy/rxjavasampleapp/ui/rxbus/RxBusActivity.java | d3f71afd3c2e8f14fabf96037ac141a6c23a707f | [] | no_license | AnilRdyAleti/RxjavaSampleApp | 459f68a2ee10732598d2b50ddbe4e9a2a957fc1e | bc86642226d9f62cd1868ece44208ad2c5f1afaa | refs/heads/master | 2020-03-16T09:07:37.053761 | 2018-05-09T14:02:02 | 2018-05-09T14:02:02 | 132,609,172 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 411 | java | package com.example.anilreddy.rxjavasampleapp.ui.rxbus;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.example.anilreddy.rxjavasampleapp.R;
public class RxBusActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rx_bus);
}
}
| [
"AnilRdyAleti@github.com"
] | AnilRdyAleti@github.com |
6e2728f572e93ce649e4f72c2e1b589eb051b07c | 7febfe6ae5dc681a4855c36e6ff4299822c36f2c | /app/src/main/java/com/github/florent37/xebia/ui/view/MaskableFrameLayout.java | 2a548b885a3030476cc2b2bf06744014fd36c977 | [
"Apache-2.0"
] | permissive | virendersran01/Potier | 60f843e2e138e54de9e26edd86d4ce331dd02b8e | 23c2699848802a5c52feca417483a9e79a115a43 | refs/heads/master | 2020-11-29T21:48:46.354070 | 2015-05-08T12:58:09 | 2015-05-08T12:58:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,262 | java | package com.github.florent37.xebia.ui.view;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import com.github.florent37.xebia.R;
/**
* FROM https://github.com/christophesmet/android_maskable_layout
* Created by Christophe on 12/07/2014.
*/
public class MaskableFrameLayout extends FrameLayout {
//Constants
private static final String TAG = "MaskableFrameLayout";
private static final int MODE_ADD = 0;
private static final int MODE_CLEAR = 1;
private static final int MODE_DARKEN = 2;
private static final int MODE_DST = 3;
private static final int MODE_DST_ATOP = 4;
private static final int MODE_DST_IN = 5;
private static final int MODE_DST_OUT = 6;
private static final int MODE_DST_OVER = 7;
private static final int MODE_LIGHTEN = 8;
private static final int MODE_MULTIPLY = 9;
private static final int MODE_OVERLAY = 10;
private static final int MODE_SCREEN = 11;
private static final int MODE_SRC = 12;
private static final int MODE_SRC_ATOP = 13;
private static final int MODE_SRC_IN = 14;
private static final int MODE_SRC_OUT = 15;
private static final int MODE_SRC_OVER = 16;
private static final int MODE_XOR = 17;
private Handler mHandler;
//Mask props
@Nullable
private Drawable mDrawableMask = null;
@Nullable
private Bitmap mFinalMask = null;
//Drawing props
private Paint mPaint = null;
private PorterDuffXfermode mPorterDuffXferMode = null;
public MaskableFrameLayout(Context context) {
super(context);
}
public MaskableFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
construct(context, attrs);
}
public MaskableFrameLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
construct(context, attrs);
}
private void construct(Context context, AttributeSet attrs) {
mHandler = new Handler();
setDrawingCacheEnabled(true);
if (Build.VERSION.SDK_INT >= 11) {
setLayerType(LAYER_TYPE_SOFTWARE, null); //Only works for software layers
}
mPaint = createPaint();
Resources.Theme theme = context.getTheme();
if (theme != null) {
TypedArray a = theme.obtainStyledAttributes(
attrs,
R.styleable.MaskableLayout,
0, 0);
try {
//Load the mask if specified in xml
initMask(loadMask(a));
//Load the mode if specified in xml
mPorterDuffXferMode = getModeFromInteger(
a.getInteger(R.styleable.MaskableLayout_porterduffxfermode, 0));
initMask(mDrawableMask);
} finally {
if (a != null) {
a.recycle();
}
}
} else {
log("Couldn't load theme, mask in xml won't be loaded.");
}
registerMeasure();
}
private Paint createPaint() {
Paint output = new Paint(Paint.ANTI_ALIAS_FLAG);
output.setXfermode(mPorterDuffXferMode);
return output;
}
//Mask functions
@Nullable
private Drawable loadMask(TypedArray a) {
return a.getDrawable(R.styleable.MaskableLayout_mask);
}
private void initMask(@Nullable Drawable input) {
if (input != null) {
mDrawableMask = input;
if (mDrawableMask instanceof AnimationDrawable) {
mDrawableMask.setCallback(this);
}
} else {
log("Are you sure you don't want to provide a mask ?");
}
}
@Nullable
public Drawable getDrawableMask() {
return mDrawableMask;
}
@Nullable
private Bitmap makeBitmapMask(@Nullable Drawable drawable) {
if (drawable != null) {
if (getMeasuredWidth() > 0 && getMeasuredHeight() > 0) {
Bitmap mask = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mask);
drawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
drawable.draw(canvas);
return mask;
} else {
log("Can't create a mask with height 0 or width 0. Or the layout has no children and is wrap content");
return null;
}
} else {
log("No bitmap mask loaded, view will NOT be masked !");
}
return null;
}
public void setMask(int drawableRes) {
Resources res = getResources();
if (res != null) {
setMask(res.getDrawable(drawableRes));
} else {
log("Unable to load resources, mask will not be loaded as drawable");
}
}
public void setMask(@Nullable Drawable input) {
initMask(input);
swapBitmapMask(makeBitmapMask(mDrawableMask));
invalidate();
}
//Once the size has changed we need to remake the mask.
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
setSize(w, h);
}
private void setSize(int width, int height) {
if (width > 0 && height > 0) {
if (mDrawableMask != null) {
//Remake the 9patch
swapBitmapMask(makeBitmapMask(mDrawableMask));
}
} else {
log("Width and height must be higher than 0");
}
}
//Drawing
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (mFinalMask != null && mPaint != null) {
mPaint.setXfermode(mPorterDuffXferMode);
canvas.drawBitmap(mFinalMask, 0.0f, 0.0f, mPaint);
mPaint.setXfermode(null);
} else {
log("Mask or paint is null ...");
}
}
//Once inflated we have no height or width for the mask. Wait for the layout.
private void registerMeasure() {
final ViewTreeObserver treeObserver = MaskableFrameLayout.this.getViewTreeObserver();
if (treeObserver != null && treeObserver.isAlive()) {
treeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewTreeObserver aliveObserver = treeObserver;
if (!aliveObserver.isAlive()) {
aliveObserver = MaskableFrameLayout.this.getViewTreeObserver();
}
if (aliveObserver != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
aliveObserver.removeOnGlobalLayoutListener(this);
} else {
aliveObserver.removeGlobalOnLayoutListener(this);
}
} else {
log("GlobalLayoutListener not removed as ViewTreeObserver is not valid");
}
swapBitmapMask(makeBitmapMask(mDrawableMask));
}
});
}
}
//Logging
private void log(String message) {
Log.d(TAG, message);
}
//Animation
@Override
public void invalidateDrawable(Drawable dr) {
if (dr != null) {
initMask(dr);
swapBitmapMask(makeBitmapMask(dr));
invalidate();
}
}
@Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
if (who != null && what != null) {
mHandler.postAtTime(what, when);
}
}
@Override
public void unscheduleDrawable(Drawable who, Runnable what) {
if (who != null && what != null) {
mHandler.removeCallbacks(what);
}
}
private void swapBitmapMask(@Nullable Bitmap newMask) {
if (newMask != null) {
if (mFinalMask != null && !mFinalMask.isRecycled()) {
mFinalMask.recycle();
}
mFinalMask = newMask;
}
}
//Utils
private PorterDuffXfermode getModeFromInteger(int index) {
PorterDuff.Mode mode = null;
switch (index) {
case MODE_ADD:
if (Build.VERSION.SDK_INT >= 11) {
mode = PorterDuff.Mode.ADD;
} else {
log("MODE_ADD is not supported on api lvl " + Build.VERSION.SDK_INT);
}
case MODE_CLEAR:
mode = PorterDuff.Mode.CLEAR;
break;
case MODE_DARKEN:
mode = PorterDuff.Mode.DARKEN;
break;
case MODE_DST:
mode = PorterDuff.Mode.DST;
break;
case MODE_DST_ATOP:
mode = PorterDuff.Mode.DST_ATOP;
break;
case MODE_DST_IN:
mode = PorterDuff.Mode.DST_IN;
break;
case MODE_DST_OUT:
mode = PorterDuff.Mode.DST_OUT;
break;
case MODE_DST_OVER:
mode = PorterDuff.Mode.DST_OVER;
break;
case MODE_LIGHTEN:
mode = PorterDuff.Mode.LIGHTEN;
break;
case MODE_MULTIPLY:
mode = PorterDuff.Mode.MULTIPLY;
break;
case MODE_OVERLAY:
if (Build.VERSION.SDK_INT >= 11) {
mode = PorterDuff.Mode.OVERLAY;
} else {
log("MODE_OVERLAY is not supported on api lvl " + Build.VERSION.SDK_INT);
}
case MODE_SCREEN:
mode = PorterDuff.Mode.SCREEN;
break;
case MODE_SRC:
mode = PorterDuff.Mode.SRC;
break;
case MODE_SRC_ATOP:
mode = PorterDuff.Mode.SRC_ATOP;
break;
case MODE_SRC_IN:
mode = PorterDuff.Mode.SRC_IN;
break;
case MODE_SRC_OUT:
mode = PorterDuff.Mode.SRC_OUT;
break;
case MODE_SRC_OVER:
mode = PorterDuff.Mode.SRC_OVER;
break;
case MODE_XOR:
mode = PorterDuff.Mode.XOR;
break;
default:
mode = PorterDuff.Mode.DST_IN;
}
log("Mode is " + mode.toString());
return new PorterDuffXfermode(mode);
}
}
| [
"champigny.florent@gmail.com"
] | champigny.florent@gmail.com |
2bbb03e60ab9b13d93ea491c0776666102412253 | 20eb62855cb3962c2d36fda4377dfd47d82eb777 | /newEvaluatedBugs/Jsoup_19_buggy/mutated/980/Element.java | 53e6ce920f78f5c4b1a7c328725dc6fc25e74095 | [] | no_license | ozzydong/CapGen | 356746618848065cce4e253e5d3c381baa85044a | 0ba0321b6b1191443276021f1997833342f02515 | refs/heads/master | 2023-03-18T20:12:02.923428 | 2020-08-21T03:08:28 | 2020-08-21T03:08:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 43,704 | java | package org.jsoup.nodes;
import org.jsoup.helper.StringUtil;
import org.jsoup.helper.Validate;
import org.jsoup.parser.Parser;
import org.jsoup.parser.Tag;
import org.jsoup.select.*;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* A HTML element consists of a tag name, attributes, and child nodes (including text nodes and
* other elements).
*
* From an Element, you can extract data, traverse the node graph, and manipulate the HTML.
*
* @author Jonathan Hedley, jonathan@hedley.net
*/
public class Element extends Node {
private Tag tag;
private static final Pattern classSplit = Pattern.compile("\\s+");
/**
* Create a new, standalone Element. (Standalone in that is has no parent.)
*
* @param tag tag of this element
* @param baseUri the base URI
* @param attributes initial attributes
* @see #appendChild(Node)
* @see #appendElement(String)
*/
public Element(Tag tag, String baseUri, Attributes attributes) {
super(baseUri, attributes);
Validate.notNull(tag);
this.tag = tag;
}
/**
* Create a new Element from a tag and a base URI.
*
* @param tag element tag
* @param baseUri the base URI of this element. It is acceptable for the base URI to be an empty
* string, but not null.
* @see Tag#valueOf(String)
*/
public Element(Tag tag, String baseUri) {
this(tag, baseUri, new Attributes());
}
@Override
public String nodeName() {
return tag.getName();
}
/**
* Get the name of the tag for this element. E.g. {@code div}
*
* @return the tag name
*/
public String tagName() {
return tag.getName();
}
/**
* Change the tag of this element. For example, convert a {@code <span>} to a {@code <div>} with
* {@code el.tagName("div");}.
*
* @param tagName new tag name for this element
* @return this element, for chaining
*/
public Element tagName(String tagName) {
Validate.notEmpty(tagName, "Tag name must not be empty.");
tag = Tag.valueOf(tagName);
return this;
}
/**
* Get the Tag for this element.
*
* @return the tag object
*/
public Tag tag() {
return tag;
}
/**
* Test if this element is a block-level element. (E.g. {@code <div> == true} or an inline element
* {@code <p> == false}).
*
* @return true if block, false if not (and thus inline)
*/
public boolean isBlock() {
return tag.isBlock();
}
/**
* Get the {@code id} attribute of this element.
*
* @return The id attribute, if present, or an empty string if not.
*/
public String id() {
return attributes.get("id");
}
/**
* Set an attribute value on this element. If this element already has an attribute with the
* key, its value is updated; otherwise, a new attribute is added.
*
* @return this element
*/
public Element attr(String attributeKey, String attributeValue) {
super.attr(attributeKey, attributeValue);
return this;
}
/**
* Set a boolean attribute value on this element. Setting to <code>true</code> sets the attribute value to "" and
* marks the attribute as boolean so no value is written out. Setting to <code>false</code> removes the attribute
* with the same key if it exists.
*
* @param attributeKey the attribute key
* @param attributeValue the attribute value
*
* @return this element
*/
public Element attr(String attributeKey, boolean attributeValue) {
attributes.put(attributeKey, attributeValue);
return this;
}
/**
* Get this element's HTML5 custom data attributes. Each attribute in the element that has a key
* starting with "data-" is included the dataset.
* <p>
* E.g., the element {@code <div data-package="jsoup" data-language="Java" class="group">...} has the dataset
* {@code package=jsoup, language=java}.
* <p>
* This map is a filtered view of the element's attribute map. Changes to one map (add, remove, update) are reflected
* in the other map.
* <p>
* You can find elements that have data attributes using the {@code [^data-]} attribute key prefix selector.
* @return a map of {@code key=value} custom data attributes.
*/
public Map<String, String> dataset() {
return attributes.dataset();
}
@Override
public final Element parent() {
return (Element) parentNode;
}
/**
* Get this element's parent and ancestors, up to the document root.
* @return this element's stack of parents, closest first.
*/
public Elements parents() {
Elements parents = new Elements();
accumulateParents(this, parents);
return parents;
}
private static void accumulateParents(Element el, Elements parents) {
Element parent = el.parent();
if (parent != null && !parent.tagName().equals("#root")) {
parents.add(parent);
accumulateParents(parent, parents);
}
}
/**
* Get a child element of this element, by its 0-based index number.
* <p>
* Note that an element can have both mixed Nodes and Elements as children. This method inspects
* a filtered list of children that are elements, and the index is based on that filtered list.
* </p>
*
* @param index the index number of the element to retrieve
* @return the child element, if it exists, otherwise throws an {@code IndexOutOfBoundsException}
* @see #childNode(int)
*/
public Element child(int index) {
return children().get(index);
}
/**
* Get this element's child elements.
* <p>
* This is effectively a filter on {@link #childNodes()} to get Element nodes.
* </p>
* @return child elements. If this element has no children, returns an
* empty list.
* @see #childNodes()
*/
public Elements children() {
// create on the fly rather than maintaining two lists. if gets slow, memoize, and mark dirty on change
List<Element> elements = new ArrayList<Element>(childNodes.size());
for (Node node : childNodes) {
if (node instanceof Element)
elements.add((Element) node);
}
return new Elements(elements);
}
/**
* Get this element's child text nodes. The list is unmodifiable but the text nodes may be manipulated.
* <p>
* This is effectively a filter on {@link #childNodes()} to get Text nodes.
* @return child text nodes. If this element has no text nodes, returns an
* empty list.
* </p>
* For example, with the input HTML: {@code <p>One <span>Two</span> Three <br> Four</p>} with the {@code p} element selected:
* <ul>
* <li>{@code p.text()} = {@code "One Two Three Four"}</li>
* <li>{@code p.ownText()} = {@code "One Three Four"}</li>
* <li>{@code p.children()} = {@code Elements[<span>, <br>]}</li>
* <li>{@code p.childNodes()} = {@code List<Node>["One ", <span>, " Three ", <br>, " Four"]}</li>
* <li>{@code p.textNodes()} = {@code List<TextNode>["One ", " Three ", " Four"]}</li>
* </ul>
*/
public List<TextNode> textNodes() {
List<TextNode> textNodes = new ArrayList<TextNode>();
for (Node node : childNodes) {
if (node instanceof TextNode)
textNodes.add((TextNode) node);
}
return Collections.unmodifiableList(textNodes);
}
/**
* Get this element's child data nodes. The list is unmodifiable but the data nodes may be manipulated.
* <p>
* This is effectively a filter on {@link #childNodes()} to get Data nodes.
* </p>
* @return child data nodes. If this element has no data nodes, returns an
* empty list.
* @see #data()
*/
public List<DataNode> dataNodes() {
List<DataNode> dataNodes = new ArrayList<DataNode>();
for (Node node : childNodes) {
if (node instanceof DataNode)
dataNodes.add((DataNode) node);
}
return Collections.unmodifiableList(dataNodes);
}
/**
* Find elements that match the {@link Selector} CSS query, with this element as the starting context. Matched elements
* may include this element, or any of its children.
* <p>
* This method is generally more powerful to use than the DOM-type {@code getElementBy*} methods, because
* multiple filters can be combined, e.g.:
* </p>
* <ul>
* <li>{@code el.select("a[href]")} - finds links ({@code a} tags with {@code href} attributes)
* <li>{@code el.select("a[href*=example.com]")} - finds links pointing to example.com (loosely)
* </ul>
* <p>
* See the query syntax documentation in {@link org.jsoup.select.Selector}.
* </p>
*
* @param cssQuery a {@link Selector} CSS-like query
* @return elements that match the query (empty if none match)
* @see org.jsoup.select.Selector
* @throws Selector.SelectorParseException (unchecked) on an invalid CSS query.
*/
public Elements select(String cssQuery) {
return Selector.select(cssQuery, this);
}
/**
* Add a node child node to this element.
*
* @param child node to add.
* @return this element, so that you can add more child nodes or elements.
*/
public Element appendChild(Node child) {
Validate.notNull(child);
// was - Node#addChildren(child). short-circuits an array create and a loop.
reparentChild(child);
childNodes.add(child);
child.setSiblingIndex(childNodes.size() - 1);
return this;
}
/**
* Add a node to the start of this element's children.
*
* @param child node to add.
* @return this element, so that you can add more child nodes or elements.
*/
public Element prependChild(Node child) {
Validate.notNull(child);
addChildren(0, child);
return this;
}
/**
* Inserts the given child nodes into this element at the specified index. Current nodes will be shifted to the
* right. The inserted nodes will be moved from their current parent. To prevent moving, copy the nodes first.
*
* @param index 0-based index to insert children at. Specify {@code 0} to insert at the start, {@code -1} at the
* end
* @param children child nodes to insert
* @return this element, for chaining.
*/
public Element insertChildren(int index, Collection<? extends Node> children) {
Validate.notNull(children, "Children collection to be inserted must not be null.");
int currentSize = childNodeSize();
if (index < 0) index += currentSize +1; // roll around
Validate.isTrue(index >= 0 && index <= currentSize, "Insert position out of bounds.");
ArrayList<Node> nodes = new ArrayList<Node>(children);
Node[] nodeArray = nodes.toArray(new Node[nodes.size()]);
addChildren(index, nodeArray);
return this;
}
/**
* Create a new element by tag name, and add it as the last child.
*
* @param tagName the name of the tag (e.g. {@code div}).
* @return the new element, to allow you to add content to it, e.g.:
* {@code parent.appendElement("h1").attr("id", "header").text("Welcome");}
*/
public Element appendElement(String tagName) {
Element child = new Element(Tag.valueOf(tagName), baseUri());
appendChild(child);
return child;
}
/**
* Create a new element by tag name, and add it as the first child.
*
* @param tagName the name of the tag (e.g. {@code div}).
* @return the new element, to allow you to add content to it, e.g.:
* {@code parent.prependElement("h1").attr("id", "header").text("Welcome");}
*/
public Element prependElement(String tagName) {
Element child = new Element(Tag.valueOf(tagName), baseUri());
prependChild(child);
return child;
}
/**
* Create and append a new TextNode to this element.
*
* @param text the unencoded text to add
* @return this element
*/
public Element appendText(String text) {
TextNode node = new TextNode(text, baseUri());
appendChild(node);
return this;
}
/**
* Create and prepend a new TextNode to this element.
*
* @param text the unencoded text to add
* @return this element
*/
public Element prependText(String text) {
TextNode node = new TextNode(text, baseUri());
prependChild(node);
return this;
}
/**
* Add inner HTML to this element. The supplied HTML will be parsed, and each node appended to the end of the children.
* @param html HTML to add inside this element, after the existing HTML
* @return this element
* @see #html(String)
*/
public Element append(String html) {
Validate.notNull(html);
List<Node> nodes = Parser.parseFragment(html, this, baseUri());
addChildren(nodes.toArray(new Node[nodes.size()]));
return this;
}
/**
* Add inner HTML into this element. The supplied HTML will be parsed, and each node prepended to the start of the element's children.
* @param html HTML to add inside this element, before the existing HTML
* @return this element
* @see #html(String)
*/
public Element prepend(String html) {
Validate.notNull(html);
List<Node> nodes = Parser.parseFragment(html, this, baseUri());
addChildren(0, nodes.toArray(new Node[nodes.size()]));
return this;
}
/**
* Insert the specified HTML into the DOM before this element (as a preceding sibling).
*
* @param html HTML to add before this element
* @return this element, for chaining
* @see #after(String)
*/
@Override
public Element before(String html) {
return (Element) super.before(html);
}
/**
* Insert the specified node into the DOM before this node (as a preceding sibling).
* @param node to add before this element
* @return this Element, for chaining
* @see #after(Node)
*/
@Override
public Element before(Node node) {
return (Element) super.before(node);
}
/**
* Insert the specified HTML into the DOM after this element (as a following sibling).
*
* @param html HTML to add after this element
* @return this element, for chaining
* @see #before(String)
*/
@Override
public Element after(String html) {
return (Element) super.after(html);
}
/**
* Insert the specified node into the DOM after this node (as a following sibling).
* @param node to add after this element
* @return this element, for chaining
* @see #before(Node)
*/
@Override
public Element after(Node node) {
return (Element) super.after(node);
}
/**
* Remove all of the element's child nodes. Any attributes are left as-is.
* @return this element
*/
public Element empty() {
childNodes.clear();
return this;
}
/**
* Wrap the supplied HTML around this element.
*
* @param html HTML to wrap around this element, e.g. {@code <div class="head"></div>}. Can be arbitrarily deep.
* @return this element, for chaining.
*/
@Override
public Element wrap(String html) {
return (Element) super.wrap(html);
}
/**
* Get a CSS selector that will uniquely select this element.
* <p>
* If the element has an ID, returns #id;
* otherwise returns the parent (if any) CSS selector, followed by {@literal '>'},
* followed by a unique selector for the element (tag.class.class:nth-child(n)).
* </p>
*
* @return the CSS Path that can be used to retrieve the element in a selector.
*/
public String cssSelector() {
if (id().length() > 0)
return "#" + id();
StringBuilder selector = new StringBuilder(tagName());
String classes = StringUtil.join(classNames(), ".");
if (classes.length() > 0)
selector.append('.').append(classes);
if (parent() == null || parent() instanceof Document) // don't add Document to selector, as will always have a html node
return selector.toString();
selector.insert(0, " > ");
if (parent().select(selector.toString()).size() > 1)
selector.append(String.format(
":nth-child(%d)", elementSiblingIndex() + 1));
return parent().cssSelector() + selector.toString();
}
/**
* Get sibling elements. If the element has no sibling elements, returns an empty list. An element is not a sibling
* of itself, so will not be included in the returned list.
* @return sibling elements
*/
public Elements siblingElements() {
if (parentNode == null)
return new Elements(0);
List<Element> elements = parent().children();
Elements siblings = new Elements(elements.size() - 1);
for (Element el: elements)
if (el != this)
siblings.add(el);
return siblings;
}
/**
* Gets the next sibling element of this element. E.g., if a {@code div} contains two {@code p}s,
* the {@code nextElementSibling} of the first {@code p} is the second {@code p}.
* <p>
* This is similar to {@link #nextSibling()}, but specifically finds only Elements
* </p>
* @return the next element, or null if there is no next element
* @see #previousElementSibling()
*/
public Element nextElementSibling() {
if (parentNode == null) return null;
List<Element> siblings = parent().children();
Integer index = indexInList(this, siblings);
Validate.notNull(index);
if (siblings.size() > index+1)
return siblings.get(index+1);
else
return null;
}
/**
* Gets the previous element sibling of this element.
* @return the previous element, or null if there is no previous element
* @see #nextElementSibling()
*/
public Element previousElementSibling() {
if (parentNode == null) return null;
List<Element> siblings = parent().children();
Integer index = indexInList(this, siblings);
Validate.notNull(index);
if (index > 0)
return siblings.get(index-1);
else
return null;
}
/**
* Gets the first element sibling of this element.
* @return the first sibling that is an element (aka the parent's first element child)
*/
public Element firstElementSibling() {
// todo: should firstSibling() exclude this?
List<Element> siblings = parent().children();
return siblings.size() > 1 ? siblings.get(0) : null;
}
/**
* Get the list index of this element in its element sibling list. I.e. if this is the first element
* sibling, returns 0.
* @return position in element sibling list
*/
public Integer elementSiblingIndex() {
if (parent() == null) return 0;
return indexInList(this, parent().children());
}
/**
* Gets the last element sibling of this element
* @return the last sibling that is an element (aka the parent's last element child)
*/
public Element lastElementSibling() {
List<Element> siblings = parent().children();
return siblings.size() > 1 ? siblings.get(siblings.size() - 1) : null;
}
private static <E extends Element> Integer indexInList(Element search, List<E> elements) {
Validate.notNull(search);
Validate.notNull(elements);
for (int i = 0; i < elements.size(); i++) {
E element = elements.get(i);
if (element == search)
return i;
}
return null;
}
// DOM type methods
/**
* Finds elements, including and recursively under this element, with the specified tag name.
* @param tagName The tag name to search for (case insensitively).
* @return a matching unmodifiable list of elements. Will be empty if this element and none of its children match.
*/
public Elements getElementsByTag(String tagName) {
Validate.notEmpty(tagName);
tagName = tagName.toLowerCase().trim();
return Collector.collect(new Evaluator.Tag(tagName), this);
}
/**
* Find an element by ID, including or under this element.
* <p>
* Note that this finds the first matching ID, starting with this element. If you search down from a different
* starting point, it is possible to find a different element by ID. For unique element by ID within a Document,
* use {@link Document#getElementById(String)}
* @param id The ID to search for.
* @return The first matching element by ID, starting with this element, or null if none found.
*/
public Element getElementById(String id) {
Validate.notEmpty(id);
Elements elements = Collector.collect(new Evaluator.Id(id), this);
if (elements.size() > 0)
return elements.get(0);
else
return null;
}
/**
* Find elements that have this class, including or under this element. Case insensitive.
* <p>
* Elements can have multiple classes (e.g. {@code <div class="header round first">}. This method
* checks each class, so you can find the above with {@code el.getElementsByClass("header");}.
*
* @param className the name of the class to search for.
* @return elements with the supplied class name, empty if none
* @see #hasClass(String)
* @see #classNames()
*/
public Elements getElementsByClass(String className) {
Validate.notEmpty(className);
return Collector.collect(new Evaluator.Class(className), this);
}
/**
* Find elements that have a named attribute set. Case insensitive.
*
* @param key name of the attribute, e.g. {@code href}
* @return elements that have this attribute, empty if none
*/
public Elements getElementsByAttribute(String key) {
Validate.notEmpty(key);
key = key.trim().toLowerCase();
return Collector.collect(new Evaluator.Attribute(key), this);
}
/**
* Find elements that have an attribute name starting with the supplied prefix. Use {@code data-} to find elements
* that have HTML5 datasets.
* @param keyPrefix name prefix of the attribute e.g. {@code data-}
* @return elements that have attribute names that start with with the prefix, empty if none.
*/
public Elements getElementsByAttributeStarting(String keyPrefix) {
Validate.notEmpty(keyPrefix);
keyPrefix = keyPrefix.trim().toLowerCase();
return Collector.collect(new Evaluator.AttributeStarting(keyPrefix), this);
}
/**
* Find elements that have an attribute with the specific value. Case insensitive.
*
* @param key name of the attribute
* @param value value of the attribute
* @return elements that have this attribute with this value, empty if none
*/
public Elements getElementsByAttributeValue(String key, String value) {
return Collector.collect(new Evaluator.AttributeWithValue(key, value), this);
}
/**
* Find elements that either do not have this attribute, or have it with a different value. Case insensitive.
*
* @param key name of the attribute
* @param value value of the attribute
* @return elements that do not have a matching attribute
*/
public Elements getElementsByAttributeValueNot(String key, String value) {
return Collector.collect(new Evaluator.AttributeWithValueNot(key, value), this);
}
/**
* Find elements that have attributes that start with the value prefix. Case insensitive.
*
* @param key name of the attribute
* @param valuePrefix start of attribute value
* @return elements that have attributes that start with the value prefix
*/
public Elements getElementsByAttributeValueStarting(String key, String valuePrefix) {
return Collector.collect(new Evaluator.AttributeWithValueStarting(key, valuePrefix), this);
}
/**
* Find elements that have attributes that end with the value suffix. Case insensitive.
*
* @param key name of the attribute
* @param valueSuffix end of the attribute value
* @return elements that have attributes that end with the value suffix
*/
public Elements getElementsByAttributeValueEnding(String key, String valueSuffix) {
return Collector.collect(new Evaluator.AttributeWithValueEnding(key, valueSuffix), this);
}
/**
* Find elements that have attributes whose value contains the match string. Case insensitive.
*
* @param key name of the attribute
* @param match substring of value to search for
* @return elements that have attributes containing this text
*/
public Elements getElementsByAttributeValueContaining(String key, String match) {
return Collector.collect(new Evaluator.AttributeWithValueContaining(key, match), this);
}
/**
* Find elements that have attributes whose values match the supplied regular expression.
* @param key name of the attribute
* @param pattern compiled regular expression to match against attribute values
* @return elements that have attributes matching this regular expression
*/
public Elements getElementsByAttributeValueMatching(String key, Pattern pattern) {
return Collector.collect(new Evaluator.AttributeWithValueMatching(key, pattern), this);
}
/**
* Find elements that have attributes whose values match the supplied regular expression.
* @param key name of the attribute
* @param regex regular expression to match against attribute values. You can use <a href="http://java.sun.com/docs/books/tutorial/essential/regex/pattern.html#embedded">embedded flags</a> (such as (?i) and (?m) to control regex options.
* @return elements that have attributes matching this regular expression
*/
public Elements getElementsByAttributeValueMatching(String key, String regex) {
Pattern pattern;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Pattern syntax error: " + regex, e);
}
return getElementsByAttributeValueMatching(key, pattern);
}
/**
* Find elements whose sibling index is less than the supplied index.
* @param index 0-based index
* @return elements less than index
*/
public Elements getElementsByIndexLessThan(int index) {
return Collector.collect(new Evaluator.IndexLessThan(index), this);
}
/**
* Find elements whose sibling index is greater than the supplied index.
* @param index 0-based index
* @return elements greater than index
*/
public Elements getElementsByIndexGreaterThan(int index) {
return Collector.collect(new Evaluator.IndexGreaterThan(index), this);
}
/**
* Find elements whose sibling index is equal to the supplied index.
* @param index 0-based index
* @return elements equal to index
*/
public Elements getElementsByIndexEquals(int index) {
return Collector.collect(new Evaluator.IndexEquals(index), this);
}
/**
* Find elements that contain the specified string. The search is case insensitive. The text may appear directly
* in the element, or in any of its descendants.
* @param searchText to look for in the element's text
* @return elements that contain the string, case insensitive.
* @see Element#text()
*/
public Elements getElementsContainingText(String searchText) {
return Collector.collect(new Evaluator.ContainsText(searchText), this);
}
/**
* Find elements that directly contain the specified string. The search is case insensitive. The text must appear directly
* in the element, not in any of its descendants.
* @param searchText to look for in the element's own text
* @return elements that contain the string, case insensitive.
* @see Element#ownText()
*/
public Elements getElementsContainingOwnText(String searchText) {
return Collector.collect(new Evaluator.ContainsOwnText(searchText), this);
}
/**
* Find elements whose text matches the supplied regular expression.
* @param pattern regular expression to match text against
* @return elements matching the supplied regular expression.
* @see Element#text()
*/
public Elements getElementsMatchingText(Pattern pattern) {
return Collector.collect(new Evaluator.Matches(pattern), this);
}
/**
* Find elements whose text matches the supplied regular expression.
* @param regex regular expression to match text against. You can use <a href="http://java.sun.com/docs/books/tutorial/essential/regex/pattern.html#embedded">embedded flags</a> (such as (?i) and (?m) to control regex options.
* @return elements matching the supplied regular expression.
* @see Element#text()
*/
public Elements getElementsMatchingText(String regex) {
Pattern pattern;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Pattern syntax error: " + regex, e);
}
return getElementsMatchingText(pattern);
}
/**
* Find elements whose own text matches the supplied regular expression.
* @param pattern regular expression to match text against
* @return elements matching the supplied regular expression.
* @see Element#ownText()
*/
public Elements getElementsMatchingOwnText(Pattern pattern) {
return Collector.collect(new Evaluator.MatchesOwn(pattern), this);
}
/**
* Find elements whose text matches the supplied regular expression.
* @param regex regular expression to match text against. You can use <a href="http://java.sun.com/docs/books/tutorial/essential/regex/pattern.html#embedded">embedded flags</a> (such as (?i) and (?m) to control regex options.
* @return elements matching the supplied regular expression.
* @see Element#ownText()
*/
public Elements getElementsMatchingOwnText(String regex) {
Pattern pattern;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Pattern syntax error: " + regex, e);
}
return getElementsMatchingOwnText(pattern);
}
/**
* Find all elements under this element (including self, and children of children).
*
* @return all elements
*/
public Elements getAllElements() {
return Collector.collect(new Evaluator.AllElements(), this);
}
/**
* Gets the combined text of this element and all its children. Whitespace is normalized and trimmed.
* <p>
* For example, given HTML {@code <p>Hello <b>there</b> now! </p>}, {@code p.text()} returns {@code "Hello there now!"}
*
* @return unencoded text, or empty string if none.
* @see #ownText()
* @see #textNodes()
*/
public String text() {
final StringBuilder accum = new StringBuilder();
new NodeTraversor(new NodeVisitor() {
public void head(Node node, int depth) {
if (node instanceof TextNode) {
TextNode textNode = (TextNode) node;
appendNormalisedText(accum, textNode);
} else if (node instanceof Element) {
Element element = (Element) node;
if (accum.length() > 0 &&
(element.isBlock() || element.tag.getName().equals("br")) &&
!TextNode.lastCharIsWhitespace(accum))
accum.append(" ");
}
}
public void tail(Node node, int depth) {
}
}).traverse(this);
return accum.toString().trim();
}
/**
* Gets the text owned by this element only; does not get the combined text of all children.
* <p>
* For example, given HTML {@code <p>Hello <b>there</b> now!</p>}, {@code p.ownText()} returns {@code "Hello now!"},
* whereas {@code p.text()} returns {@code "Hello there now!"}.
* Note that the text within the {@code b} element is not returned, as it is not a direct child of the {@code p} element.
*
* @return unencoded text, or empty string if none.
* @see #text()
* @see #textNodes()
*/
public String ownText() {
StringBuilder sb = new StringBuilder();
ownText(sb);
return sb.toString().trim();
}
private void ownText(StringBuilder accum) {
for (Node child : childNodes) {
if (child instanceof TextNode) {
TextNode textNode = (TextNode) child;
appendNormalisedText(accum, textNode);
} else if (child instanceof Element) {
appendWhitespaceIfBr((Element) child, accum);
}
}
}
private static void appendNormalisedText(StringBuilder accum, TextNode textNode) {
String text = textNode.getWholeText();
if (preserveWhitespace(textNode.parentNode))
accum.append(text);
else
StringUtil.appendNormalisedWhitespace(accum, text, TextNode.lastCharIsWhitespace(accum));
}
private static void appendWhitespaceIfBr(Element element, StringBuilder accum) {
if (element.tag.getName().equals("br") && !TextNode.lastCharIsWhitespace(accum))
accum.append(" ");
}
static boolean preserveWhitespace(Node node) {
// looks only at this element and one level up, to prevent recursion & needless stack searches
if (node != null && node instanceof Element) {
Element element = (Element) node;
return element.tag.preserveWhitespace() ||
element.parent() != null && element.parent().tag.preserveWhitespace();
}
return false;
}
/**
* Set the text of this element. Any existing contents (text or elements) will be cleared
* @param text unencoded text
* @return this element
*/
public Element text(String text) {
Validate.notNull(text);
empty();
TextNode textNode = new TextNode(text, baseUri);
appendChild(textNode);
return this;
}
/**
Test if this element has any text content (that is not just whitespace).
@return true if element has non-blank text content.
*/
public boolean hasText() {
for (Node child: childNodes) {
if (child instanceof TextNode) {
TextNode textNode = (TextNode) child;
if (!textNode.isBlank())
return true;
} else if (child instanceof Element) {
Element el = (Element) child;
if (el.hasText())
return true;
}
}
return false;
}
/**
* Get the combined data of this element. Data is e.g. the inside of a {@code script} tag.
* @return the data, or empty string if none
*
* @see #dataNodes()
*/
public String data() {
StringBuilder sb = new StringBuilder();
for (Node childNode : childNodes) {
if (childNode instanceof DataNode) {
DataNode data = (DataNode) childNode;
sb.append(data.getWholeData());
} else if (childNode instanceof Element) {
Element element = (Element) childNode;
String elementData = element.data();
sb.append(elementData);
}
}
return sb.toString();
}
/**
* Gets the literal value of this element's "class" attribute, which may include multiple class names, space
* separated. (E.g. on <code><div class="header gray"></code> returns, "<code>header gray</code>")
* @return The literal class attribute, or <b>empty string</b> if no class attribute set.
*/
public String className() {
return attr("class").trim();
}
/**
* Get all of the element's class names. E.g. on element {@code <div class="header gray">},
* returns a set of two elements {@code "header", "gray"}. Note that modifications to this set are not pushed to
* the backing {@code class} attribute; use the {@link #classNames(java.util.Set)} method to persist them.
* @return set of classnames, empty if no class attribute
*/
public Set<String> classNames() {
String[] names = classSplit.split(className());
Set<String> classNames = new LinkedHashSet<String>(Arrays.asList(names));
classNames.remove(""); // if classNames() was empty, would include an empty class
return classNames;
}
/**
Set the element's {@code class} attribute to the supplied class names.
@param classNames set of classes
@return this element, for chaining
*/
public Element classNames(Set<String> classNames) {
Validate.notNull(classNames);
attributes.put("class", StringUtil.join(classNames, " "));
return this;
}
/**
* Tests if this element has a class. Case insensitive.
* @param className name of class to check for
* @return true if it does, false if not
*/
/*
Used by common .class selector, so perf tweaked to reduce object creation vs hitting classnames().
Wiki: 71, 13 (5.4x)
CNN: 227, 91 (2.5x)
Alterslash: 59, 4 (14.8x)
Jsoup: 14, 1 (14x)
*/
public boolean hasClass(String className) {
String classAttr = attributes.get("class");
if (classAttr.equals("") || classAttr.length() < className.length())
return false;
final String[] classes = classSplit.split(classAttr);
for (String name : classes) {
if (className.equalsIgnoreCase(name))
return true;
}
return false;
}
/**
Add a class name to this element's {@code class} attribute.
@param className class name to add
@return this element
*/
public Element addClass(String className) {
Validate.notNull(className);
Set<String> classes = classNames();
classes.add(className);
classNames(classes);
return this;
}
/**
Remove a class name from this element's {@code class} attribute.
@param className class name to remove
@return this element
*/
public Element removeClass(String className) {
Validate.notNull(className);
Set<String> classes = classNames();
classes.remove(className);
classNames(classes);
return this;
}
/**
Toggle a class name on this element's {@code class} attribute: if present, remove it; otherwise add it.
@param className class name to toggle
@return this element
*/
public Element toggleClass(String className) {
Validate.notNull(className);
Set<String> classes = classNames();
if (classes.contains(className))
classes.remove(className);
else
classes.add(className);
classNames(classes);
return this;
}
/**
* Get the value of a form element (input, textarea, etc).
* @return the value of the form element, or empty string if not set.
*/
public String val() {
if (tagName().equals("textarea"))
return text();
else
return attr("value");
}
/**
* Set the value of a form element (input, textarea, etc).
* @param value value to set
* @return this element (for chaining)
*/
public Element val(String value) {
if (tagName().equals("textarea"))
text(value);
else
attr("value", value);
return this;
}
void outerHtmlHead(StringBuilder accum, int depth, Document.OutputSettings out) {
if (accum.length() > 0 && out.prettyPrint() && (tag.formatAsBlock() || (parent() != null && parent().tag().formatAsBlock()) || out.outline()) )
indent(accum, depth, out);
accum
.append("<")
.append(children());
attributes.html(accum, out);
// selfclosing includes unknown tags, isEmpty defines tags that are always empty
if (childNodes.isEmpty() && tag.isSelfClosing()) {
if (out.syntax() == Document.OutputSettings.Syntax.html && tag.isEmpty())
accum.append('>');
else
accum.append(" />"); // <img> in html, <img /> in xml
}
else
accum.append(">");
}
void outerHtmlTail(StringBuilder accum, int depth, Document.OutputSettings out) {
if (!(childNodes.isEmpty() && tag.isSelfClosing())) {
if (out.prettyPrint() && (!childNodes.isEmpty() && (
tag.formatAsBlock() || (out.outline() && (childNodes.size()>1 || (childNodes.size()==1 && !(childNodes.get(0) instanceof TextNode))))
)))
indent(accum, depth, out);
accum.append("</").append(tagName()).append(">");
}
}
/**
* Retrieves the element's inner HTML. E.g. on a {@code <div>} with one empty {@code <p>}, would return
* {@code <p></p>}. (Whereas {@link #outerHtml()} would return {@code <div><p></p></div>}.)
*
* @return String of HTML.
* @see #outerHtml()
*/
public String html() {
StringBuilder accum = new StringBuilder();
html(accum);
return getOutputSettings().prettyPrint() ? accum.toString().trim() : accum.toString();
}
private void html(StringBuilder accum) {
for (Node node : childNodes)
node.outerHtml(accum);
}
/**
* Set this element's inner HTML. Clears the existing HTML first.
* @param html HTML to parse and set into this element
* @return this element
* @see #append(String)
*/
public Element html(String html) {
empty();
append(html);
return this;
}
public String toString() {
return outerHtml();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Element element = (Element) o;
return tag.equals(element.tag);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (tag != null ? tag.hashCode() : 0);
return result;
}
@Override
public Element clone() {
return (Element) super.clone();
}
}
| [
"justinwm@163.com"
] | justinwm@163.com |
e22dfd5076530e615147c213ad5a03a335eed727 | d9d6bf45ee70fb26bb775a794ebf497c6ddad59c | /src/main/java/com/design/u049/B/TimeoutAlertHander.java | 2b016f24a12a16d94e04b4127b62d425a94bef32 | [] | no_license | jiangsiYang/designModel_geekbang | 60788a9a70cc468a57749a7a8f2a6a2db248e000 | a48b4e9774ea5f705a0a6d88bf61caa2dc839edb | refs/heads/master | 2022-12-26T03:36:36.400697 | 2022-12-11T12:21:28 | 2022-12-11T12:21:28 | 231,164,579 | 45 | 23 | null | 2022-12-16T05:09:19 | 2020-01-01T01:45:18 | Java | UTF-8 | Java | false | false | 551 | java | package com.design.u049.B;
/**
* // 改动二:添加新的handler
*/
public class TimeoutAlertHander extends AlertHandler {
public TimeoutAlertHander(AlertRule rule, Notification notification) {
super(rule, notification);
}
@Override
public void check(ApiStatInfo apiStatInfo) {
long timeoutTps = apiStatInfo.getTimeoutCount() / apiStatInfo.getDurationOfSeconds();
if (timeoutTps > rule.getMatchedRule(apiStatInfo.getApi()).getMaxTimeoutTps()) {
notification.notify("...");
}
}
}
| [
"353098889@qq.com"
] | 353098889@qq.com |
99ee18de8bd5d0e7815049e2319f69748543f4f7 | e8526ac94719402f1258750f211e26319f287b29 | /lab5/src/mobile/Mobile.java | 054d3e0d9c3a256fc423503e89c3dc19d81366fd | [] | no_license | Mckan/D-A | 9adb336c82737706dc7165219d289a37a7c21162 | b97bc01775e476cebe47ac555f82fad44eb2f333 | refs/heads/master | 2020-05-26T21:16:58.713532 | 2012-05-09T16:09:00 | 2012-05-09T16:09:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,023 | java | package mobile;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Mobile {
private enum MobileType { SIMPLE, COMPOSITE }
private MobileType type;
private float weight; // Simple
private float leftLength, rightLength; // Composite
private Mobile left, right;
public Mobile( float weight ) {
type = MobileType.SIMPLE;
this.weight = weight;
left = null;
right = null;
}
public Mobile( Mobile left, float leftLength, Mobile right, float rightLength ) {
type = MobileType.COMPOSITE;
this.left = left;
this.right = right;
this.leftLength = leftLength;
this.rightLength = rightLength;
}
// Return the total mass of the mobile
public float getWeight() {
if ( isSimple() )
return weight;
else
return left.getWeight() + right.getWeight();
}
// Return the maximum height of the mobile
public int getHeight() {
if( ( isSimple() == true) )
{
return 1;
}
else {
return right.getHeight() + left.getHeight();
}
}
// Print the leaves of the mobile
public void flatten() {
if(isSimple())
{
System.out.print((int)weight + " ");
}
else
{
left.flatten();
right.flatten();
}
}
// Print a structured view of the mobile
public void prettyPrint() {
if(isSimple())
{
System.out.print("(" + (int)weight + ")");
}
else
{ System.out.print("[");
left.prettyPrint();
System.out.print("," + (int)leftLength + ",");
right.prettyPrint();
System.out.print("," + (int)rightLength);
System.out.print("]");
}
}
// Determine if the mobile is balanced
public boolean isBalanced() {
final double eps = 0.000001;
return isSimple() ||
left.isBalanced() && right.isBalanced() &&
Math.abs( leftLength * left.getWeight() -
rightLength * right.getWeight() ) < eps;
}
// Determine if two mobiles are equal
public boolean equals( Object rhs ) {
if(rhs == null || getClass() != rhs.getClass() )
return false;
else
{
Mobile tmp = (Mobile) rhs;
return ((isSimple() && tmp.isSimple()) && weight == tmp.weight) ||
left.equals(tmp.left) && right.equals(tmp.right);
}
}
// Return a clone of this mobile
public Mobile clone() {
Mobile tmp = null;
try{
tmp = (Mobile) super.clone();
}catch(Exception E)
{System.out.println(E);}
tmp.leftLength = leftLength;
tmp.rightLength = rightLength;
tmp.weight = weight;
return tmp;
}
// Change this mobile to its mirror image
public void mirror() {
Mobile tmp;
float tmpLength;
if(!isSimple())
{
left.mirror();
}
tmp = right;
tmpLength = rightLength;
right = left;
rightLength = leftLength;
left = tmp;
leftLength = tmpLength;
}
private boolean isSimple() {
return type == MobileType.SIMPLE;
}
public static void main(String[] args) {
Mobile m1 = new Mobile( 1 ),
m2 = new Mobile( new Mobile( 2 ), 6, new Mobile( 3 ), 4 ),
m = new Mobile(m1,10, m2, 2 );
System.out.println("Total mass: " + m.getWeight() );
System.out.println("Height: " + m.getHeight() );
m.flatten(); System.out.println();
m.prettyPrint(); System.out.println();
if ( m.isBalanced() )
System.out.println("Balanced!");
else
System.out.println("Not balanced!");
Mobile m22 = new Mobile( new Mobile( 2 ), 6, new Mobile( 3 ), 4 ),
m3 = new Mobile( m1, 10, m22, 2 );
if ( m.equals(m3) )
System.out.println("Equal!"); // They should be!
else
System.out.println("Not equal!");
Mobile c = m.clone();
if ( c.equals(m) )
System.out.println("Equal!"); // They should be!
else
System.out.println("Not equal!");
if ( c == m )
System.out.println("Identical!"); // They should definately not!
else
System.out.println("Not identical!");
m.mirror();
m.prettyPrint(); System.out.println();
m.mirror();
m.prettyPrint(); System.out.println();
}
}
| [
"mckan91@gmail.com"
] | mckan91@gmail.com |
0854bf31e6712e5951ffb4dd13259387cd421fd0 | d41a9e6c9b882a548f5cbb97b7ec62d1ec1e6a77 | /BACKEND/weatherappmain/src/main/java/com/demo/exceptionhandler/ExceptionResponseHandler.java | 9fa552cdcda50f087550d3c2d2cfcd95139fe9c0 | [] | no_license | NaflaShajahan/Weatherapp | 49cd22a617c3e0fd50c1afcfd5ef85948e30395a | 304b7078843c9f4a3a9d9255c2ee0e4e45438cf5 | refs/heads/main | 2023-07-06T22:32:37.945818 | 2021-08-09T18:06:57 | 2021-08-09T18:06:57 | 394,387,369 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,381 | java | package com.demo.exceptionhandler;
import javax.security.auth.login.AccountNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import com.demo.service.exception.ErrorDetails;
@RestController
@ControllerAdvice
public class ExceptionResponseHandler {
@ExceptionHandler(Exception.class)
ResponseEntity<ErrorDetails> handleOtherError(Exception ex, WebRequest request){
ErrorDetails details=new ErrorDetails();
details.setEmail("nafla@ust.global.com");
details.setErrorMessage("some internal server error please contact ust global");
details.setDetails(request.getDescription(false));
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(details);
}
@ExceptionHandler(AccountNotFoundException.class)
ResponseEntity<ErrorDetails> handle404Error(Exception ex, WebRequest request){
ErrorDetails details=new ErrorDetails();
details.setEmail("nafla@ust.global.com");
details.setErrorMessage(ex.getMessage());
details.setDetails(request.getDescription(false));
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(details);
}
}
| [
"Nafla.Shajahan@ust.com"
] | Nafla.Shajahan@ust.com |
991a6bf86689d2fe625977451cd3a4217142d6b9 | 3e8d851fe647b6ce61a7e4f7116cb684cef0529e | /Milk And It's Product Management/zones/south_zone/karnataka/mysore/mysore.java | 97cee72f7b782bfa8d0492bbea4c61b275fe6ffa | [] | no_license | Ankuuush/Java | 11b24839ae3c7bc63560844dbd1c5fcb63d67b22 | 06d9c907eb40ca4d7b105bc2d0eabbd471808f83 | refs/heads/master | 2023-01-21T15:29:22.352739 | 2020-12-01T06:38:31 | 2020-12-01T06:38:31 | 317,447,001 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,344 | java | package zones.south_zone.karnataka.mysore;
import zones.*;
import java.io.*;
public class mysore
{
public void cmpny()throws IOException
{
try{
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
System.out.println("[1]--> NANDANI");
try{Thread.sleep(200);}catch(Exception e){}
System.out.println("[2]--> AMUL");
try{Thread.sleep(200);}catch(Exception e){}
System.out.println("[3]--> MILMA");
try{Thread.sleep(200);}catch(Exception e){}
int a=Integer.parseInt(br.readLine());
switch (a)
{
case 1:
NANDANI ob=new NANDANI();
ob.prdcts();
break;
case 2:
AMUL ob1=new AMUL();
ob1.prdcts();
break;
case 3:
MILMA ob2=new MILMA();
ob2.prdcts();
break;
default: System.out.println("\nWrong input");
try{Thread.sleep(500);}catch (Exception e){}
System.out.println("\f");
mysore oi=new mysore();
oi.cmpny();
}
}catch(Exception e1)
{
System.out.println("\nWrong input");
try{Thread.sleep(500);}catch (Exception e){}
System.out.println("\f");
mysore oi=new mysore();
oi.cmpny();
}
}
} | [
"68370434+Ankuuush@users.noreply.github.com"
] | 68370434+Ankuuush@users.noreply.github.com |
31e42ac2915832eb9ae5affbaef7af704c292cd3 | a02424746af6415f784e4930a21d6c715949620e | /platform/src/main/java/com/oa/platform/web/interceptor/WebSocketHandshakeInterceptor.java | ca07324f954057a2ff977620552867327bd95e53 | [] | no_license | lylalv/oa | 0f4f626f4f20e21f0f6f85a319da5ee67329b4b4 | 2e724b5c2c217c604aecd06e4be2faaeca0e6740 | refs/heads/master | 2022-04-18T11:26:26.890590 | 2020-04-17T16:59:51 | 2020-04-17T16:59:51 | 256,251,793 | 0 | 0 | null | 2020-04-16T15:15:28 | 2020-04-16T15:15:27 | null | UTF-8 | Java | false | false | 2,302 | java | package com.oa.platform.web.interceptor;
import com.oa.platform.common.WebSocketCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import javax.servlet.http.HttpSession;
import java.util.Map;
/**
* WebSocket握手拦截器
* @author Feng
* @date 2018/10/15
*/
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
private static Logger logger = LoggerFactory.getLogger(HandshakeInterceptor.class);
/**
* 在握手之后
*/
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object
> attributes) throws Exception {
logger.debug("beforeHandshake start.....");
logger.debug(request.getClass().getName());
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession(false);
if (session != null) {
//使用userName区分WebSocketHandler,以便定向发送消息
String userName = (String) session.getAttribute(WebSocketCache.SESSION_USERNAME);
logger.info(userName+" login");
attributes.put(WebSocketCache.WEBSOCKET_USERNAME,userName);
/*使用websocketSessionKey区分WebSocketHandler modify by feng*/
String websocketSessionKey = userName + ";" + session.getId();
attributes.put(WebSocketCache.WEBSOCKET_SESSION_KEY, websocketSessionKey);
System.err.println("connect success");
}else{
logger.debug("httpsession is null");
}
}
return true;
}
/**
* 在握手之前
*/
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
}
}
| [
"445121408@qq.com"
] | 445121408@qq.com |
ae67397d688284cfaabd9e3afe54aa15eb149c6a | 62db6dcb5048cf618acf693b70212ad50693cbfd | /src/main/java/com/example/hvac/HVACImpl.java | 5a56149d510fa77888a536ef483baec479359c86 | [] | no_license | cbirajdar/HVAC | cd4930a7f6c3ab8febeb0cea189929b7e6bf8dc1 | c9001e08fd2e720376c791a22508970b4b949f66 | refs/heads/master | 2020-12-24T23:38:49.118015 | 2016-06-16T19:41:17 | 2016-06-16T19:41:17 | 61,158,213 | 0 | 1 | null | 2016-06-14T21:52:48 | 2016-06-14T21:52:46 | Java | UTF-8 | Java | false | false | 414 | java | package com.example.hvac;
import com.example.hvac.HVAC;
public class HVACImpl implements HVAC {
private int currentTemp;
public HVACImpl() {
}
public HVACImpl(int temp) {
this.currentTemp = temp;
}
@Override
public void heat(boolean on) {
}
@Override
public void cool(boolean on) {
}
@Override
public void fan(boolean on) {
}
@Override
public int temp() {
return currentTemp;
}
}
| [
"chetan.birajdar@surveysampling.com"
] | chetan.birajdar@surveysampling.com |
b7627a864b252c4d1461b16514387aed1d9a8878 | a3cc0e822f3c8402178e50137eb78bdfb4d1bb11 | /src/main/java/com/bdt/framework/common/realm/ShiroDbRealm.java | 27fbb7e8bb39bd8e15d802338bebd8ad29043dfe | [] | no_license | zhanghongbo001/play | 54b5567217a6479f16f2db354f93b1598c02a1d0 | 615b3186619c04f217829a29f84698f23e9b9c49 | refs/heads/master | 2021-06-30T13:16:12.834438 | 2017-09-20T14:59:56 | 2017-09-20T14:59:56 | 104,209,521 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,252 | java | package com.bdt.framework.common.realm;
import com.bdt.biz.UserBiz;
import com.bdt.framework.entity.User;
import com.bdt.framework.exception.BusinessException;
import com.bdt.framework.utils.CipherUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashSet;
import java.util.Set;
/**
* @author zhanghongbo
* @data 2016/7/19.
*/
public class ShiroDbRealm extends AuthorizingRealm {
private static Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);
private static final String ALGORITHM = "MD5";
@Autowired
private UserBiz userBiz;
public ShiroDbRealm() {
super();
}
/**
* 验证登陆
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken authcToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
User user = userBiz.getUserByName(token.getUsername());
if(user.getStatus()!=false){
throw new BusinessException("邮箱已经激活,请直接登录!");
}else {
CipherUtil cipher = new CipherUtil();//MD5加密
if (user != null) {
return new SimpleAuthenticationInfo(user.getName(), user.getPassword(), getName());
} else {
throw new AuthenticationException();
}
}
}
/**
* 登陆成功之后,进行角色和权限验证
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
/*这里应该根据userName使用role和permission 的serive层来做判断,并将对应 的权限加进来,下面简化了这一步*/
Set<String> roleNames = new HashSet<String>();
Set<String> permissions = new HashSet<String>();
roleNames.add("admin");//添加角色。对应到index.jsp
roleNames.add("administrator");
permissions.add("create");//添加权限,对应到index.jsp
permissions.add("login?main");
permissions.add("login?logout");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
info.setStringPermissions(permissions);
return info;
}
/**
* 清除所有用户授权信息缓存.
*/
public void clearCachedAuthorizationInfo(String principal) {
SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
clearCachedAuthorizationInfo(principals);
}
/**
* 清除所有用户授权信息缓存.
*/
public void clearAllCachedAuthorizationInfo() {
Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
if (cache != null) {
for (Object key : cache.keys()) {
cache.remove(key);
}
}
}
}
| [
"1002688187@qq.com"
] | 1002688187@qq.com |
50e97e3cb017eb2aec4edd26dc7f8b5535a4bf67 | a60da0a14b877645bcdb9d9ff0b3ba92ba70bfdb | /src/main/java/in/lms/sinchan/model/request/TenantUpdateRequest.java | f2ad64c5b6e3905cefcbe1dbb64e6b2eb7e015db | [] | no_license | 1InfinityDoesExist/LMS | cc640deceb5ac84d7362ee1b2e3cf55b8b6cadf1 | 5ff11536a71b78e8cd67277a3b104bd15f12f166 | refs/heads/master | 2023-01-28T02:21:38.966576 | 2020-12-02T16:21:57 | 2020-12-02T16:21:57 | 308,910,129 | 0 | 0 | null | 2020-12-02T16:21:59 | 2020-10-31T15:18:55 | Java | UTF-8 | Java | false | false | 258 | java | package in.lms.sinchan.model.request;
import org.springframework.stereotype.Component;
@Component
@lombok.Data
public class TenantUpdateRequest {
private String description;
private String organizationName;
private String registratioNumber;
}
| [
"avinash.patel@gaiansolutions.com"
] | avinash.patel@gaiansolutions.com |
4be228ea2f419645536f8b0bade77fc8fe2eb2e6 | e43662b9792fd446eea83652d61dd92ff6686068 | /src/main/java/de/is/project/shop/impl/domain/InvoiceImpl.java | d276f302dccf59aa16c30e6385655dc6e1efab09 | [] | no_license | huntingveggi/shop-impl | 944cdc8ec824a173090d4cac269f40d089ed6949 | 6f8f1bc1333b13b31afc58354ed7e2f9e92744d3 | refs/heads/master | 2016-08-04T07:21:49.314365 | 2014-03-06T19:59:47 | 2014-03-06T19:59:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,327 | java | package de.is.project.shop.impl.domain;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import de.is.project.shop.api.domain.Invoice;
import de.is.project.shop.api.domain.OrderItem;
@Entity(name="invoices")
public class InvoiceImpl extends AbstractEntity implements Invoice {
Date invoiceDate;
Collection<OrderItem> orderItems = new LinkedList<>();
@Override
//@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(targetEntity = OrderItemImpl.class, cascade = { CascadeType.ALL }, orphanRemoval=true, fetch = FetchType.LAZY)
@JoinColumn(name="bill_of_delivery_id")
public Collection<OrderItem> getOrderItems() {
return this.orderItems;
}
@Override
@Column(name = "InvoiceDate", nullable = false)
public Date getInvoiceDate() {
return this.invoiceDate;
}
@Override
public void setInvoiceDate(Date invoiceDate) {
this.invoiceDate = invoiceDate;
}
public void setOrderItems(Collection<OrderItem> orderItems){
this.orderItems=orderItems;
}
}
| [
"red_steel@web.de"
] | red_steel@web.de |
6e25fdddb16deef8f792a53844ad47b9bb28a8f6 | e6d78fc1e26983738a9d2d37adcde9734d517c3a | /src/test/java/com/blackenedsystems/montyhall/MontyHallSimulatorTest.java | 1fda212d6e4d5cec78c02bae2bea331214e65ae8 | [] | no_license | blackenedsystems/monty-hall | 891178f27c3e40d55756ffb25268595284cc2b79 | 7bb9e1c9f97d64f01d00fa6b69fb1e73ff1cf1bd | refs/heads/master | 2021-07-01T21:57:20.037636 | 2014-05-19T15:00:04 | 2014-05-19T15:00:04 | 19,453,305 | 0 | 0 | null | 2021-06-22T04:36:40 | 2014-05-05T11:14:18 | Java | UTF-8 | Java | false | false | 4,212 | java | package com.blackenedsystems.montyhall;
import org.junit.Test;
import java.math.BigDecimal;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Alan Tibbetts
* @since 3/5/14 12:51
*/
public class MontyHallSimulatorTest {
private static final int NUMBER_OF_ITERATIONS = 1000; // should be enough to be statistically valid
@Test
public void simulateWin_playerDoesNotChange() {
MontyHallSimulator mhs = new MontyHallSimulator();
Game mockGame = mock(Game.class);
PrizeBox winningBox = new PrizeBox(PrizeBox.WINNER);
PrizeBox losingBox = new PrizeBox(PrizeBox.LOSER);
when(mockGame.makePlayerSelection()).thenReturn(winningBox);
when(mockGame.makeHostSelection()).thenReturn(losingBox);
boolean doesPlayerWin = mhs.executeGame(mockGame, false);
assertTrue("Player Wins", doesPlayerWin);
}
@Test
public void simulateWin_playerMakesChange() {
MontyHallSimulator mhs = new MontyHallSimulator();
Game mockGame = mock(Game.class);
PrizeBox winningBox = new PrizeBox(PrizeBox.WINNER);
PrizeBox losingBox = new PrizeBox(PrizeBox.LOSER);
when(mockGame.makePlayerSelection()).thenReturn(losingBox);
when(mockGame.makeHostSelection()).thenReturn(losingBox);
when(mockGame.swapBoxes(losingBox)).thenReturn(winningBox);
boolean doesPlayerWin = mhs.executeGame(mockGame, true);
assertTrue("Player Wins", doesPlayerWin);
}
@Test
public void simulateLoss_playerDoesNotChange() {
MontyHallSimulator mhs = new MontyHallSimulator();
Game mockGame = mock(Game.class);
PrizeBox losingBox = new PrizeBox(PrizeBox.LOSER);
when(mockGame.makePlayerSelection()).thenReturn(losingBox);
when(mockGame.makeHostSelection()).thenReturn(losingBox);
boolean doesPlayerWin = mhs.executeGame(mockGame, false);
assertFalse("Player Loses", doesPlayerWin);
}
@Test
public void simulateLoss_playerMakesChange() {
MontyHallSimulator mhs = new MontyHallSimulator();
Game mockGame = mock(Game.class);
PrizeBox winningBox = new PrizeBox(PrizeBox.WINNER);
PrizeBox losingBox = new PrizeBox(PrizeBox.LOSER);
when(mockGame.makePlayerSelection()).thenReturn(winningBox);
when(mockGame.makeHostSelection()).thenReturn(losingBox);
when(mockGame.swapBoxes(winningBox)).thenReturn(losingBox);
boolean doesPlayerWin = mhs.executeGame(mockGame, true);
assertFalse("Player Loses", doesPlayerWin);
}
@Test
public void runSimulation_playerChanges() {
MontyHallSimulator mhs = new MontyHallSimulator();
SimulationStats stats = mhs.simulate(NUMBER_OF_ITERATIONS, true);
assertNotNull("Stats", stats);
assertEquals("Wins + Losses = " + NUMBER_OF_ITERATIONS, NUMBER_OF_ITERATIONS, stats.getWins() + stats.getLosses());
assertTrue("Player wins more than 50%", stats.getWinPercentage().compareTo(new BigDecimal("50")) > 0);
}
@Test
public void runSimulation_playerDoesNotChange() {
MontyHallSimulator mhs = new MontyHallSimulator();
SimulationStats stats = mhs.simulate(NUMBER_OF_ITERATIONS, false);
assertNotNull("Stats", stats);
assertEquals("Wins + Losses = " + NUMBER_OF_ITERATIONS, NUMBER_OF_ITERATIONS, stats.getWins() + stats.getLosses());
assertTrue("Player wins less than 50%", stats.getWinPercentage().compareTo(new BigDecimal("50")) < 0);
}
@Test
public void runSimulation() {
MontyHallSimulator mhs = new MontyHallSimulator();
mhs.runSimulation(500);
assertNotNull("Changing Stats", mhs.getPlayerSwapsBoxStats());
assertNotNull("Not Changing Stats", mhs.getPlayerKeepsOriginalBoxStats());
assertTrue("Player wins more than 50% when swapping", mhs.getPlayerSwapsBoxStats().getWinPercentage().compareTo(new BigDecimal("50")) > 0);
assertTrue("Player wins less than 50% when sticking", mhs.getPlayerKeepsOriginalBoxStats().getWinPercentage().compareTo(new BigDecimal("50")) < 0);
}
}
| [
"alan@blackenedsystems.com"
] | alan@blackenedsystems.com |
12be79dc6e2230646f6c880e16375ddf6e1f65cd | f65f8e885050875ecac2623236be596d55afd0e2 | /Cplusplus/src/cpp/controller/MessageController.java | dd0e68e00070074685a948ad4a7e102c729956d0 | [] | no_license | MINIMINI1/Cplusplus | 1820b1d6dc9378928e96ba33039669a5799a6530 | 43be935cc9bfa95734fd1ba8a65874c663b0d0ef | refs/heads/master | 2020-06-18T11:19:41.515640 | 2016-12-02T00:57:11 | 2016-12-02T00:57:11 | 75,134,228 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 360 | java | package cpp.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cpp.dao.MessageDao;
@Controller
@RequestMapping("/cpp")
public class MessageController {
@Autowired
private MessageDao dao;
}
| [
"hoonmas9212@gmail.com"
] | hoonmas9212@gmail.com |
b5b721d1b8bcb776d5a525f3cee7c9293c779a60 | 4d5d99751666f5ba9d335da193bf1f695320a16e | /src/main/java/org/atom/login/model/payload/AuthenticationRequest.java | 298d5471b961cfb78eed67ce1cf13bee014498aa | [] | no_license | saikatHi6/security_module | 8171ae67b9fb2b97bdf0439f9e21831326ea5e07 | 0aa4e7be1f8978d7dcd15be4f18eee40779aa74a | refs/heads/master | 2022-06-07T22:28:39.780419 | 2020-05-06T06:13:27 | 2020-05-06T06:13:27 | 260,773,556 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 793 | java | package org.atom.login.model.payload;
import java.io.Serializable;
import javax.validation.constraints.NotBlank;
public class AuthenticationRequest implements Serializable {
@NotBlank
private String usernameOrEmail;
@NotBlank
private String password;
public String getUsernameOrEmail() {
return usernameOrEmail;
}
public void setUsernameOrEmail(String usernameOrEmail) {
this.usernameOrEmail = usernameOrEmail;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
//need default constructor for JSON Parsing
public AuthenticationRequest()
{
}
public AuthenticationRequest(String username, String password) {
this.setUsernameOrEmail(username);
this.setPassword(password);
}
}
| [
"ssadhukhan@vmware.com"
] | ssadhukhan@vmware.com |
19c1df23717bcdba766fcd77f0806f827acf5bf6 | af6251ee729995455081c4f4e48668c56007e1ac | /web/src/main/java/mmp/gps/monitor/dao/IMapLayerDao.java | becc64a7c6d54dca061bd614f057a5d783f8cb50 | [] | no_license | LXKing/monitor | b7522d5b95d2cca7e37a8bfc66dc7ba389e926ef | 7d1eca454ce9a93fc47c68f311eca4dcd6f82603 | refs/heads/master | 2020-12-01T08:08:53.265259 | 2018-12-24T12:43:32 | 2018-12-24T12:43:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 939 | java | package mmp.gps.monitor.dao;
import mmp.gps.common.util.KeyValue;
import mmp.gps.domain.mapLayer.MapLayerDto;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface IMapLayerDao {
List<MapLayerDto> query(String userId, String filter);
MapLayerDto getMapLayInfo(String mapLayerId);
void create(MapLayerDto dto);
MapLayerDto fetch(String id);
int update(MapLayerDto dto);
void delete(String id);
void deleteAreaInMaplayer(String id);
void addAreas(List<KeyValue> areas);
void removeArea(String mapLayerId, long areaId, int areaType);
List<Long> getCircleAreas(String mapLayerId);
List<Long> getRectangleAreas(String mapLayerId);
List<Long> getPolygonAreas(String mapLayerId);
List<Long> getRouteAreas(String mapLayerId);
List<Long> getPois(String mapLayerId);
void setVisible(String mapLayerId, boolean visible);
}
| [
"heavenlystate@163.com"
] | heavenlystate@163.com |
50662e46ccc099d1b24132c522d1a81da703a6d0 | c23ee131d72f7a1904282793db6193045bb0218d | /김윤하0129/src/a8_반복/ForEx.java | 7eb317dae3ed7bc9877ac9d969cc72c5f60a356a | [] | no_license | xdbsgk/javaStudy20210811 | 59d7522f73981eed87e543275e7bed0022cdec3f | d037741429d10e06a4da2953845317d24d8f31b3 | refs/heads/master | 2023-08-28T18:24:57.735994 | 2021-10-08T12:02:48 | 2021-10-08T12:02:48 | 397,576,247 | 2 | 0 | null | null | null | null | UHC | Java | false | false | 297 | java | package a8_반복;
public class ForEx {
public static void main(String[] args) {
for(int i = 0; i < 100; i++) {
System.out.println(i);
}
/* for와 while정리
for(;true;) {
System.out.println("for문");
}
while(true) {
System.out.println("while문");
}
*/
}
}
| [
"="
] | = |
40b36d903fa17d6a7cf8b0e6c0e33743eee15857 | cfd35e0c4975bb48885a341a04c90b136717d1c7 | /app/src/test/java/com/highgreat/sven/junit/SharedPreferencesHelperWithMockTest.java | 7345c8d22ae731569f6ce27632e3406ad40a63ec | [] | no_license | games2sven/JUit | 6b7407fb10b8a1176803bae7af452f8d4ee0fee5 | 36f3143211c213b4d0c6a6d730f918cf3603de1e | refs/heads/master | 2022-10-16T21:29:29.955612 | 2020-06-13T10:02:34 | 2020-06-13T10:02:34 | 271,982,793 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,878 | java | package com.highgreat.sven.junit;
import android.content.SharedPreferences;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Calendar;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
/**
* 在单元测试中使用Mock,依赖Mockito开源库,Mock可以让依赖Android库的类通过模拟数据或行为实现在本地JVM上运行单元测试。
* 但由于需要编写Mock数据,所以会增加代码量
*
* @Version
*/
@RunWith(MockitoJUnitRunner.class)
public class SharedPreferencesHelperWithMockTest {
private static final String TEST_NAME = "Test name";
private static final String TEST_EMAIL = "test@email.com";
private static final Calendar TEST_DATE_OF_BIRTH = Calendar.getInstance();
private SharedPreferenceEntry mSharedPreferenceEntry;
private SharedPreferencesHelper mSharedPreferencesHelper;
private SharedPreferencesHelper mBrokenSharedPreferencesHelper;
/** Mock变量,使用@Mock注解完成实例化 */
@Mock
SharedPreferences mMockSharedPreferences;
@Mock
SharedPreferences.Editor mMockEditor;
@Mock
SharedPreferences mMockBrokenSharedPreferences;
@Mock
SharedPreferences.Editor mMockBrokenEditor;
@Before
public void setUp() throws Exception {
mSharedPreferenceEntry = new SharedPreferenceEntry(TEST_NAME, TEST_DATE_OF_BIRTH, TEST_EMAIL);
mSharedPreferencesHelper = new SharedPreferencesHelper(mockSharePreferences());
mBrokenSharedPreferencesHelper = new SharedPreferencesHelper(mockBrokenMockSharedPreference());
}
/**
* 测试保存数据是否成功
*/
@Test
public void sharedPreferencesHelper_SavePersonalInformation() throws Exception {
assertThat(mSharedPreferencesHelper.savePersonalInfo(mSharedPreferenceEntry), is(true));
}
/**
* 测试保存数据,然后获取数据是否成功
*/
@Test
public void sharedPreferencesHelper_SaveAndReadPersonalInformation() throws Exception {
mSharedPreferencesHelper.savePersonalInfo(mSharedPreferenceEntry);
SharedPreferenceEntry sharedPreferenceEntry = mSharedPreferencesHelper.getPersonalInfo();
assertThat(isEquals(mSharedPreferenceEntry, sharedPreferenceEntry), is(true));
}
/**
* 保存数据失败的相关操作
*/
@Test
public void sharedPreferencesHelper_SavePersonalInformationFailed_ReturnsFalse() {
// Read personal information from a broken SharedPreferencesHelper
boolean success =
mBrokenSharedPreferencesHelper.savePersonalInfo(mSharedPreferenceEntry);
assertThat("Makes sure writing to a broken SharedPreferencesHelper returns false", success,
is(false));
}
/**
* 编写Mock相关代码,代码中mock了SharedPreferences类的getXxx的相关操作,
* 均返回SharedPreferenceEntry对象的值,同时在代码中使用到了commit和edit,都需要在方法中进行mock实现
* Creates a mocked SharedPreferences.
*/
private SharedPreferences mockSharePreferences(){
when(mMockSharedPreferences.getString(eq(SharedPreferencesHelper.KEY_NAME), anyString()))
.thenReturn(mSharedPreferenceEntry.getName());
when(mMockSharedPreferences.getString(eq(SharedPreferencesHelper.KEY_EMAIL), anyString()))
.thenReturn(mSharedPreferenceEntry.getEmail());
when(mMockSharedPreferences.getLong(eq(SharedPreferencesHelper.KEY_DOB), anyLong()))
.thenReturn(mSharedPreferenceEntry.getDateOfBirth().getTimeInMillis());
when(mMockEditor.commit()).thenReturn(true);
when(mMockSharedPreferences.edit()).thenReturn(mMockEditor);
return mMockSharedPreferences;
}
/**
* Creates a mocked SharedPreferences that fails when writing.
*/
private SharedPreferences mockBrokenMockSharedPreference() {
// Mocking a commit that fails.
when(mMockBrokenEditor.commit()).thenReturn(false);
// Return the broken MockEditor when requesting it.
when(mMockBrokenSharedPreferences.edit()).thenReturn(mMockBrokenEditor);
return mMockBrokenSharedPreferences;
}
private boolean isEquals(SharedPreferenceEntry sharedPreferenceEntry, SharedPreferenceEntry target){
return sharedPreferenceEntry.getName().equals(target.getName())&&sharedPreferenceEntry.getEmail().equals(target.getEmail())&&sharedPreferenceEntry.getDateOfBirth().equals(target.getDateOfBirth());
}
}
| [
"zhouli@hg-fly.com"
] | zhouli@hg-fly.com |
337eca422a3da6fee7e5e29df6632c59dee377f4 | c307750062bb20269e84c6bb09abea7116b396ad | /contact9/src/main/java/cn/ucai/contact9/inter/I.java | 0bb2dbf46e2f32525561bcecc62444abb67c42e3 | [] | no_license | BoomBone/Traning | 78cca64d17c07eff8bcf913b5115a1f924342e39 | a623507b1758d0685f552d0d5fecd456cc825707 | refs/heads/master | 2020-03-18T19:37:34.289015 | 2018-05-28T13:38:25 | 2018-05-28T13:38:25 | 135,165,959 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,406 | java | package cn.ucai.contact9.inter;
public interface I {
String SERVER_URL = "http://139.196.185.33:8080/SuperQQ3Server/Server";
// String SERVER_URL = "http://10.0.2.2:8080/SuperQQ3Server/Server";
String PAGE_ID = "pageId";
String PAGE_SIZE = "pageSize";
interface User {
String TABLE_NAME = "user";
String ID = "id";
String USER_NAME = "userName";
String NICK = "nick";
String AVATAR = "avatar";
String HEADER = "header";
String PASSWORD = "password";
String LATITUDE = "latitude";
String LONGITUDE = "longitude";
String GROUPS = "groups";
String UN_READ_MSG_COUNT = "unreadMsgCount";
}
interface Contact extends User {
String TABLE_NAME = "contact";
String NAME = "name";
String MYUID = "myuid";
String CUID = "cuid";
String IS_GET_MY_LOCATION = "isGetMyLocation";
String IS_SHOW_MY_LOCATION = "isShowMyLocation";
}
interface Avatar {
String FILE_NAME = "fileName";
}
/** 上传图片的类型:user_avatar或group_icon */
String AVATAR_TYPE = "avatarType";
String KEY_REQUEST = "request";
/**
* 客户端上传头像的请求
*/
String REQUEST_UPLOAD_AVATAR = "upload_avatar";
/**
* 客户端发送的登陆请求
*/
String REQUEST_LOGIN = "login";
String REQUEST_DOWNLOAD_AVATAR_URL =I.SERVER_URL
+"?"+KEY_REQUEST+"=download_avatar"
+"&"+ User.USER_NAME+"=";
String REQUEST_DOWNLOAD_CONTACT_LIST = "download_contact_list";
}
| [
"ticccccc@163.com"
] | ticccccc@163.com |
6673f90bab1d9a3dda1047bc19f4b17d49675f3c | bcb24a475aad2ea6c9bcf71c9c78f4208bee5f8b | /oauthsvc/src/itest/java/com/oz/oauth/test/OauthClientTest.java | d8d9fe107c82cf850f45a530e5592e55e79a508e | [] | no_license | ozguramac/penr-oz-zuul | 055728eb11a3d3446b6f1a808f46ee22fea26a74 | 0380dc049b9cc5a177440ddcd9f2807bbe845166 | refs/heads/master | 2021-07-16T18:52:05.876911 | 2017-10-24T19:12:30 | 2017-10-24T19:12:30 | 108,139,520 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,622 | java | package com.oz.oauth.test;
import com.oz.oauth.OauthSvcApplication;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.HttpHeaders;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.client.resource.UserApprovalRequiredException;
import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException;
import org.springframework.security.oauth2.client.test.BeforeOAuth2Context;
import org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration;
import org.springframework.security.oauth2.client.test.OAuth2ContextSetup;
import org.springframework.security.oauth2.client.test.RestTemplateHolder;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitResourceDetails;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
import org.springframework.security.oauth2.client.token.grant.redirect.AbstractRedirectResourceDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.config.annotation.builders.JdbcClientDetailsServiceBuilder;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestOperations;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Arrays;
import java.util.logging.Logger;
/**
* Created by Ozgur V. Amac on 12/4/15.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = OauthSvcApplication.class)
@WebIntegrationTest(randomPort = true)
public class OauthClientTest implements RestTemplateHolder {
private static final Logger log = Logger.getLogger(OauthClientTest.class.getName());
private RestOperations restOp = new TestRestTemplate();
@Value("http://localhost:${local.server.port}")
private String host;
@Rule
public OAuth2ContextSetup context = OAuth2ContextSetup.standard(this);
@Autowired
private DataSource dataSource;
private final String clientWithSecret = "oz-client-with-secret";
private final String trustedClient = "oz-trusted-client";
private final String clientWithRedirect = "oz-client-with-registered-redirect";
private final String secret = "oursecret";
//private final String anyUser = "anyUser";
//private final String trustedUser = "trustedUser";
@Value("${security.user.name}")
private String svcAcct;
@Value("${security.user.password}")
private String password;
private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
@BeforeOAuth2Context
public void setupTestData() throws Exception
{//TODO: Use spring objects to recreate data
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement stmt = null;
//Remove client data (relies on delete cascade)
for (final String clientId :
new String[] { clientWithSecret, trustedClient, clientWithRedirect})
{
try {
stmt = conn.prepareStatement("delete from oauth_client_details where client_id=?");
stmt.setString(1, clientId);
stmt.execute();
} finally {
if (stmt != null) {
stmt.close();
}
}
}
}
finally {
if (conn != null) {
conn.close();
}
}
//Recreate clients config
final JdbcClientDetailsServiceBuilder clientBuilder =
new JdbcClientDetailsServiceBuilder()
.dataSource(dataSource)
.passwordEncoder(passwordEncoder)
;
clientBuilder
.withClient(trustedClient)
.authorizedGrantTypes(
"password"
,"authorization_code"
,"refresh_token"
,"implicit"
)
.authorities(
"ROLE_CLIENT"
,"ROLE_TRUSTED_CLIENT"
)
.scopes(
"read"
,"write"
,"trust"
)
.resourceIds("sunapee")
.accessTokenValiditySeconds(60)
.and()
.withClient(clientWithRedirect)
.authorizedGrantTypes("authorization_code")
.authorities("ROLE_CLIENT")
.scopes(
"read"
,"trust"
)
.resourceIds("sunapee")
.redirectUris("http://sunapee?key=value")
.and()
.withClient(clientWithSecret)
.authorizedGrantTypes(
"client_credentials"
,"password"
)
.authorities("ROLE_CLIENT")
.scopes("read")
.resourceIds("sunapee")
.secret(secret)
;
clientBuilder.build();
}
@Override
public void setRestTemplate(RestOperations restTemplate) {
restOp = restTemplate;
}
@Override
public RestOperations getRestTemplate() {
return restOp;
}
private void assertApiAccess() {
//TODO: Implement this
// final ResponseEntity<String> re = getRestTemplate().getForEntity(host + "/sunapee-mock/user-api", String.class);
// Assert.assertTrue(re.getStatusCode().is2xxSuccessful());
// log.info(re.getBody());
}
@Test
@OAuth2ContextConfiguration(ResourceOwner.class)
public void testWithResourceOwner() throws Exception {
assertApiAccess();
}
@Test
@OAuth2ContextConfiguration(ClientCredentials.class)
public void testWithClientCredentials() throws Exception {
final OAuth2AccessToken accessToken = context.getAccessToken();
Assert.assertNotNull(accessToken);
Assert.assertNull(accessToken.getRefreshToken());
assertApiAccess();
}
@Test
@OAuth2ContextConfiguration(resource = ImplicitResource.class, initialize = false)
public void testWithImplicitResource() throws Exception {
setTokenAuthHeaders(svcAcct);
try {
Assert.assertNotNull(context.getAccessToken());
Assert.fail("Expected user redirect error");
}
catch (UserRedirectRequiredException urre) {
context.getAccessTokenRequest().add(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
context.getAccessTokenRequest().add("scope.read", "true");
Assert.assertNotNull(context.getAccessToken());
assertApiAccess();
}
}
@Test
@OAuth2ContextConfiguration(resource = AuthorizationCode.class, initialize = false)
public void testWithAuthorizationCode() throws Exception {
setTokenAuthHeaders(svcAcct);
try {
Assert.assertNotNull(context.getAccessToken());
Assert.fail("Expected user redirect error to obtain access token");
}
catch (UserRedirectRequiredException urre)
{
Assert.assertTrue(urre.getRedirectUri().startsWith(
((AbstractRedirectResourceDetails)context.getResource()).getUserAuthorizationUri()));
Assert.assertNull(context.getAccessTokenRequest().getAuthorizationCode());
try {
Assert.assertNotNull(context.getAccessToken());
Assert.fail("Expected user redirect error for user approval");
}
catch (UserApprovalRequiredException uare)
{
Assert.assertTrue(uare.getApprovalUri().startsWith(
((AbstractRedirectResourceDetails)context.getResource()).getUserAuthorizationUri()));
Assert.assertNull(context.getAccessTokenRequest().getAuthorizationCode());
context.getAccessTokenRequest().add(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
Assert.assertNotNull(context.getAccessToken());
Assert.assertNotNull(context.getAccessTokenRequest().getAuthorizationCode());
assertApiAccess();
}
}
}
private void setTokenAuthHeaders(final String username) {
final HttpHeaders headers = new HttpHeaders();
final String userPswd = username+":"+password;
headers.set("Authorization"
,"Basic " + new String(Base64.encode(userPswd.getBytes())));
context.getAccessTokenRequest().setHeaders(headers);
}
static class ResourceOwner extends ResourceOwnerPasswordResourceDetails {
public ResourceOwner(final Object target) {
final OauthClientTest test = (OauthClientTest) target;
setAccessTokenUri(test.host + "/oauth/token");
setClientId(test.clientWithSecret);
setId(getClientId());
setClientSecret(test.secret);
setUsername(test.svcAcct);
setPassword(test.password);
setScope(Arrays.asList("read"));
}
}
static class ClientCredentials extends ClientCredentialsResourceDetails {
public ClientCredentials(final Object target) {
final OauthClientTest test = (OauthClientTest) target;
setAccessTokenUri(test.host + "/oauth/token");
setClientId(test.clientWithSecret);
setId(getClientId());
setClientSecret(test.secret);
setScope(Arrays.asList("read"));
}
}
static class ImplicitResource extends ImplicitResourceDetails {
public ImplicitResource(final Object target) {
final OauthClientTest test = (OauthClientTest) target;
setAccessTokenUri(test.host + "/oauth/authorize");
setUserAuthorizationUri(test.host + "/oauth/authorize");
setClientId(test.trustedClient);
setId(getClientId());
setScope(Arrays.asList("read"));
setPreEstablishedRedirectUri("http://sunapee");
}
}
static class AuthorizationCode extends AuthorizationCodeResourceDetails {
public AuthorizationCode(final Object target) {
final OauthClientTest test = (OauthClientTest) target;
setAccessTokenUri(test.host + "/oauth/token");
setUserAuthorizationUri(test.host + "/oauth/authorize");
setClientId(test.clientWithRedirect);
setId(getClientId());
setScope(Arrays.asList("read"));
setPreEstablishedRedirectUri("http://sunapee?key=value");
}
}
}
| [
"ozguramac@users.noreply.github.com"
] | ozguramac@users.noreply.github.com |
8088ee525bfb9ab2c4ce01bec19194f6efa59197 | bca2cada7ce2022a4649cc6647ded2cee1ce60b1 | /src/main/java/com/study/abstractFactory/ModrenFactory.java | c9c579084d37d8ac51b7d31788eee33b3f157979 | [] | no_license | jianbo-fly/studydesignpatterns | 61240c22261c9c931dd0be6827fe9f19f50df107 | 53cc031a03ba28849142ec946ed8d4ea89f54a8d | refs/heads/master | 2022-12-20T02:44:57.515211 | 2020-10-24T08:33:00 | 2020-10-24T08:33:00 | 306,839,798 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 328 | java | package com.study.abstractFactory;
/**
* 具体的一个工厂 现代人的工厂
*/
public class ModrenFactory extends AbstractFactory{
Food createFood() {
return new Breaked();
}
Vehicle createVehicle() {
return new Car();
}
Weapon createWeapon() {
return new AK47();
}
}
| [
"1476125669@qq.com"
] | 1476125669@qq.com |
e17399c3e3d365b31548173762f32a57bce92c6f | 2cae7e4b8527ddbfd689574b471f72d30eec0a33 | /src/test/java/mx/iteso/components/impl/TestVideoGameFacade.java | ee47578438c91d4ef0421444ac1fe116e77710ab | [
"MIT"
] | permissive | rominavarela-java/facade-pattern | dadbe5e5107a79b77276b603cb1bd6512fab4ad5 | ff58b85735fa2d202056fdb814bfdcd3479ccb1b | refs/heads/master | 2021-01-10T23:53:47.972129 | 2015-11-27T14:47:48 | 2015-11-27T14:47:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,301 | java | package mx.iteso.components.impl;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import mx.iteso.components.GameConsole;
import mx.iteso.components.GameController;
import mx.iteso.components.Lights;
import mx.iteso.components.Router;
import mx.iteso.components.SoundSystem;
import mx.iteso.components.TV;
import mx.iteso.components.VideoGame;
import mx.iteso.facade.VideoGameFacade;
public class TestVideoGameFacade {
TV tv;
GameConsole console;
GameController controller;
SoundSystem soundSystem;
Router router;
Lights lights;
VideoGame game;
VideoGameFacade facade;
@Before
public void setup() {
tv= Mockito.mock(TV.class);
console= Mockito.mock(GameConsole.class);
controller= Mockito.mock(GameController.class);
soundSystem= Mockito.mock(SoundSystem.class);
router= Mockito.mock(Router.class);
lights= Mockito.mock(Lights.class);
game= Mockito.mock(VideoGame.class);
facade= new VideoGameFacade(tv, console, controller, soundSystem, router, lights);
}
@Test
public void testPlayOnlineGame(String gameName){
facade.playOnlineGame("test game name");
}
@Test
public void testStopPlayingGame(){
facade.stopPlayingGame();
}
}
| [
"rominavarela.mx@gmail.com"
] | rominavarela.mx@gmail.com |
b5efecddf749b06049ec9fd90c6c2905fe621900 | 151a428aa79dadc70f0f611c20ed4d84ad1aa79a | /uisp-2017/src/main/java/it/redhat/demo/uisp/rest/mapper/UispNotFoundExceptionMapper.java | 81d4494027b8d7008b21f49d7ada63cb836ed8fb | [
"Apache-2.0"
] | permissive | fax4ever/middleware-play | 20362d1d9b8c7345ca0303890f74ed94235dffc6 | 231c0f0904c2afdcc3ffcda5ffc9a631ddaf4a1b | refs/heads/master | 2021-01-19T20:05:56.797225 | 2017-09-17T07:47:41 | 2017-09-17T07:47:41 | 88,485,471 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,361 | java | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.
*/
/**
* Created by fabio on 20/08/2017.
*/
package it.redhat.demo.uisp.rest.mapper;
import javax.inject.Inject;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import it.redhat.demo.uisp.service.exception.UispNotFoundException;
import org.slf4j.Logger;
@Provider
public class UispNotFoundExceptionMapper implements ExceptionMapper<UispNotFoundException> {
@Inject
private Logger log;
@Override
public Response toResponse(UispNotFoundException exception) {
return Response.status(404)
.entity(new Error(exception))
.type(MediaType.APPLICATION_JSON)
.build();
}
}
| [
"fabiomassimo.ercoli@gmail.com"
] | fabiomassimo.ercoli@gmail.com |
e3bcf3d22cf1d8691fbb92d2e4d49089005d5f7c | 7d0a65e6172a52e956fbcc19eef45bf0d3eda8e2 | /Zadanie/src/main/java/model/Worker.java | 1f1bbf3e9a2ef08f9506c59b83c04710b8ba313f | [] | no_license | Vladislav-Kaverdiy/My-projects | 69795e81a2367e97730939f5a0cf738eba846941 | f059129b05919ff28d023a577c5e7dc23ebc7e8a | refs/heads/master | 2021-01-24T01:40:53.031843 | 2018-05-07T21:23:03 | 2018-05-07T21:23:03 | 122,818,184 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,951 | java | package model;
import java.util.Date;
public class Worker {
private int workerId;
private String firstName;
private String lastName;
private int age;
private String email;
private String phone;
private Date registerDate;
private int departmentId;
public int getWorkerId() {
return workerId;
}
public void setWorkerId(int workerId) {
this.workerId = workerId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getRegisterDate() {
return registerDate;
}
public void setRegisterDate(Date registerDate) {
this.registerDate = registerDate;
}
public int getDepartmentId() {
return departmentId;
}
public void setDepartmentId(int departmentId) {
this.departmentId = departmentId;
}
@Override
public String toString() {
return "Worker{" +
"workerId=" + workerId +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", age=" + age +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
", registerDate=" + registerDate +
", departmentId=" + departmentId +
'}';
}
}
| [
"vladyslav.kaverdii@nure.ua"
] | vladyslav.kaverdii@nure.ua |
b2077ee27d78dbf3af4582121cd8ba3dcf0d7528 | 7efc0534f1ca4e3beb9cea6fea5dd894f79907ca | /MultiThreadingEx/src/com/newth/th/Player.java | ed276efa0b78d9878ccf34659ec5d2cba987ab04 | [] | no_license | rkront2020/Java_Space | 0b221ce73049ea65b35f3df9646c8f2b28e6c020 | 6d062e71573671ec30663a02f16eb9ae39851f5f | refs/heads/master | 2020-05-04T23:49:10.428677 | 2019-04-05T05:43:11 | 2019-04-05T05:43:11 | 179,554,173 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 357 | java | package com.newth.th;
public class Player extends Thread {
String threadName;
ThreadGroup tg;
public Player(String threadName, ThreadGroup tg) {
this.threadName = threadName;
this.tg = tg;
}
@Override
public void run() {
Life.getLife();
for(int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName());
}
}
}
| [
"rkront2020@gmail.com"
] | rkront2020@gmail.com |
e766ed0b1692036b17c8792d22ed521b83159dcf | 13fc3cec59ec5ebc8a6d6f4b3ed0ac34d9e48b3f | /shop-user-center/shop-user/src/main/java/com/qfedu/user/config/ApiCoreApp.java | a0db17f2c68b4120e684b8ac129e3b80f6f0d85a | [] | no_license | LY-GO/shop-project | b21748c77800a993e6b9c6cceb437ba7bb1066e3 | a8a43865eb8e5d517095c0481c4c408836a958f7 | refs/heads/master | 2023-01-07T08:18:53.835108 | 2020-11-12T16:33:27 | 2020-11-12T16:33:27 | 312,334,333 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 976 | java | package com.qfedu.user.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class ApiCoreApp implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat
);
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
} | [
"410237002@qq.com"
] | 410237002@qq.com |
3596711d94805abafce1fa401290cffeaf59afdd | f475dbb992f61487266384fdd6c36ab7b20fc2d0 | /src/main/java/com/tjs/common/sms/service/SmsTransactionService.java | 733bdc207abfbc3a96036b9e48610a589fd0d612 | [
"Apache-2.0"
] | permissive | tjscreators/endlos | c039405006a97452abe27e4a11651dd9b6e1d6fa | cf7819c716ac7a1a95a31ee77d60059a040a129d | refs/heads/master | 2022-12-25T04:05:45.380409 | 2020-09-24T10:23:20 | 2020-09-24T10:23:20 | 297,992,002 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,495 | java | /*******************************************************************************
* Copyright -2018 @Emotome
*
* 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.tjs.common.sms.service;
import java.util.List;
import com.tjs.common.service.BaseService;
import com.tjs.common.sms.model.SmsTransactionModel;
/**
*
* @author JD
* @since 16/05/2019
*/
public interface SmsTransactionService extends BaseService<SmsTransactionModel> {
String SMS_TRANSACTION_MODEL = "smsTransactionModel";
String LIGHT_SMS_TRANSACTION_MODEL = "lightSmsTransactionModel";
/**
* this method for get all transactional sms by status.
*
* @param statusId
* @return
*/
List<SmsTransactionModel> getDataByStatus(Integer statusId);
/**
* This method is used to get sms records list base on given count.
*
* @param limit
* @return
*/
List<SmsTransactionModel> getSmsList(int limit);
}
| [
"tjscreators@gmail.com"
] | tjscreators@gmail.com |
a47176f8c1751b6e7ac5b7b87504186ed2fc472f | e53f693aa3f3a7f0534d544efc66e135f3ca6e72 | /app/src/main/java/domain/fincas/com/fincas/lecheingre.java | 06ac2f62180032605e883d276bf0d0cfee6fdf47 | [] | no_license | jturizo2/Finca | fad4d06e34e2459add022b69eed9d875bb18d00d | fac625a217740ed9acc0fcdada9cd6858bd136e3 | refs/heads/master | 2021-05-06T16:18:35.706641 | 2018-04-04T04:51:11 | 2018-04-04T04:51:11 | 113,688,539 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,156 | java | package domain.fincas.com.fincas;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class lecheingre extends AppCompatActivity {
private EditText cod1,litros,fecha,etPlannedDate;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lecheingre);
cod1= (EditText) findViewById(R.id.cod2);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
litros= (EditText) findViewById(R.id.litros);
//fecha= (EditText) findViewById(R.id.fecha2);
String fc = dateFormat.format(date.getTime());
//fecha.setText(fc);
//--------------- datepicker---------------------------------
etPlannedDate = (EditText) findViewById(R.id.etPlannedDate);
etPlannedDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDatePickerDialog();
}
});
etPlannedDate.setText(fc);
//--------------- datepicker---------------------------------
}
@Override
public void onBackPressed(){
Intent i = new Intent(lecheingre.this, botones_ingreso_info.class);
startActivity(i);
finish();
}
//metodo mostrar datepicker
private void showDatePickerDialog() {
DatePickerFragment newFragment = DatePickerFragment.newInstance(new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
// +1 because january is zero
final String selectedDate = day + " / " + (month+1) + " / " + year;
etPlannedDate.setText(selectedDate);
}
});
newFragment.show(getFragmentManager(), "datePicker");
} // fin metodo mostrar datepicker
public void guardar(View view) {
String gcod1 = cod1.getText().toString();
String glitros = litros.getText().toString();
String gfecha = etPlannedDate .getText().toString().replace(" ","");
//------------------------------------------------------------------------------------
//-----Se busca si el cod existe en los animales
// Cod actual
String use=cod1.getText().toString();
// Lista de codigos existentes
UsersSQLiteHelper admine = new UsersSQLiteHelper(this, "FINCAS", null, 1);
SQLiteDatabase db = admine.getWritableDatabase();
Cursor fila = db.rawQuery("SELECT CODIGO FROM ANIMALESN", null);
String ssd ="";
String flag="nada";
while (fila.moveToNext()) {
String prube= fila.getString(0);
if(use.equals(prube)){
flag="algop";
break;
}
}
db.close();
if(flag.equals("nada")){
Toast.makeText(this, "El código no existe!!!", Toast.LENGTH_LONG).show();
}else{
UsersSQLiteHelper admine6 = new UsersSQLiteHelper(this, "FINCAS", null, 1);
SQLiteDatabase db6 = admine6.getWritableDatabase();
Cursor fila6 = db6.rawQuery("SELECT ID FROM ANIMALESN WHERE CODIGO='"+use+"' AND ETAPAP='Vaca'", null);
String flag6="nada";
while (fila6.moveToNext()) {
String prube= fila.getString(0);
if(use.equals(prube)){
flag6="algop";
break;
}
}
db6.close();
// Verificar si es vaca----------------
if(flag6.equals("nada")){
Toast.makeText(this, "El animal no es una vaca!!!", Toast.LENGTH_LONG).show();
}else{
if(glitros.equals("")){
glitros="0";
}
//Base de datos
UsersSQLiteHelper admine9 = new UsersSQLiteHelper(this, "FINCAS", null, 1);
SQLiteDatabase db9 = admine9.getWritableDatabase();
ContentValues registro = new ContentValues();
registro.put("COD", gcod1);
registro.put("LITROS", glitros);
registro.put("FECHA", gfecha);
db9.insert("LECHE", null, registro);
db9.close();
Toast.makeText(this, "Información registrada!!", Toast.LENGTH_LONG).show();
Intent i = new Intent(lecheingre.this, botones_ingreso_info.class);
startActivity(i);
finish();
}
}
}
} | [
"jlsilva@uninorte.edu.co"
] | jlsilva@uninorte.edu.co |
e8abe8144a927f2b3ed996a95aff9211eae26a69 | 99491debb70866677edc01d9af1bfaadac914978 | /src/main/java/com/id/wasta/data/repository/jpa/TIdSpecializationInformationJpaRepository.java | 30899fd1890b1344c734e34ba1b24eac5c70ea17 | [] | no_license | srnu/wasta | a9dbf4772d6584aacb952b12a4d0e6842d8fa77c | c55498cd42b8114ee0bb9342c9905868632e9ddc | refs/heads/master | 2022-12-12T06:54:57.769288 | 2020-09-13T09:41:53 | 2020-09-13T09:41:53 | 295,119,733 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 445 | java | package com.id.wasta.data.repository.jpa;
import java.util.List;
import com.id.util.data.repository.jpa.BaseRepository;
import com.id.wasta.bean.jpa.TIdSpecializationInformationEntity;
/**
* Repository : TIdSpecializationInformation.
*/
public interface TIdSpecializationInformationJpaRepository extends BaseRepository<TIdSpecializationInformationEntity, Long> {
List<TIdSpecializationInformationEntity> findByPesPeiKey(Long peiKey);
}
| [
"venkatrao@infodynamic.in"
] | venkatrao@infodynamic.in |
55db932c4e98c7657ab07c763706ce363447dc79 | 9acfc3fc6d0ddcd597495ffe7908ef79482a608a | /latte-core/src/main/java/haodong/com/latte_core/ui/loader/LatteLoader.java | 48e0302902d157fd343dc244385ef96003d4facd | [] | no_license | haodongLing/MyFastEcDemo | 2a04d7a576cb52d4f485323cc13c4611c191ab70 | b9c8b5d25c1bb57d64365d224af0165324780f93 | refs/heads/master | 2020-03-26T08:38:18.033069 | 2018-08-14T11:44:57 | 2018-08-14T11:44:57 | 144,712,563 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,070 | java | package haodong.com.latte_core.ui.loader;
import android.content.Context;
import android.support.v7.app.AppCompatDialog;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import com.wang.avi.AVLoadingIndicatorView;
import java.util.ArrayList;
import haodong.com.latte_core.R;
import haodong.com.latte_core.util.dimen.DimenUtil;
public class LatteLoader {
private static final int LOADER_SIZE_SCALE = 8;
private static final int LOADER_OFFSET_SCALE = 10;
private static final ArrayList<AppCompatDialog> LOADERS = new ArrayList<>();
private static final String DEFAULT_LOADER = LoaderStyle.BallClipRotatePulseIndicator.name();
public static void showLoading(Context context, Enum<LoaderStyle> type) {
showLoading(context, type.name());
}
public static void showLoading(Context context, String type) {
final AppCompatDialog dialog = new AppCompatDialog(context, R.style.dialog);
final AVLoadingIndicatorView avLoadingIndicatorView = LoaderCreater.create(type, context);
dialog.setContentView(avLoadingIndicatorView);
int deviceWidth = DimenUtil.getScreenWidth();
int deviceHeight = DimenUtil.getScreenHeight();
final Window dialogWindow = dialog.getWindow();
if (dialogWindow != null) {
final WindowManager.LayoutParams lp = dialogWindow.getAttributes();
lp.width = deviceWidth / LOADER_SIZE_SCALE;
lp.height = deviceHeight / LOADER_SIZE_SCALE;
lp.height = lp.height + deviceHeight / LOADER_OFFSET_SCALE;
lp.gravity = Gravity.CENTER;
}
LOADERS.add(dialog);
dialog.show();
}
public static void showLoading(Context context) {
showLoading(context, DEFAULT_LOADER);
}
public static void stopLoading() {
for (AppCompatDialog dialog : LOADERS) {
if (dialog != null) {
if (dialog.isShowing()) {
dialog.cancel();
}
}
}
}
}
| [
"Lhd@472754233"
] | Lhd@472754233 |
38e6e113ec8f60cce8e8b6d5c6ac0b94874e6675 | ac36189779f7e72d18116a8eb1f0b125d64e52cf | /Set1/Leetcode/101/TreeNode.java | 50960612b8f83454dec2b6c34c3d93f76a2cc6eb | [] | no_license | vinhvu200/Algorithm | f11e732d8e4f1c24d69ebf97ae68cea683d73c29 | bcbd5006157b15e18b11f5c8c39d3314d7aad143 | refs/heads/master | 2021-01-23T05:04:52.542442 | 2017-08-08T21:43:36 | 2017-08-08T21:43:36 | 92,952,699 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 100 | java | public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
| [
"vinhvu200@gmail.com"
] | vinhvu200@gmail.com |
cad30eff622a9e0006ef747ab2f8617f78fa294d | 86fb2fdfef583dbbd30b4b386a75f9512e2e3168 | /src/core/java/au/net/netstorm/boost/nursery/eight/legged/spider/factory/supplied/Mappings.java | 67667dd2173abb4204fe7ac43f52934f5f5d9e00 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | kef/boost | a1aa4febb0dbc05c0a7983c73cb9ba7ed264cb3e | cf4fba51ac98e463b8fe994024f8f61240c0a360 | refs/heads/master | 2021-01-22T06:53:41.163500 | 2008-09-01T11:29:56 | 2008-09-01T11:29:56 | 48,002 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 163 | java | package au.net.netstorm.boost.nursery.eight.legged.spider.factory.supplied;
public interface Mappings extends Iterable<Mapping> {
void add(Mapping mapper);
}
| [
"mark.hibberd@05db6a09-9903-0410-bedf-ba9bc4063e48"
] | mark.hibberd@05db6a09-9903-0410-bedf-ba9bc4063e48 |
962a4d239ca30fc51a6e142ea7d787a7152e8a74 | 147bb3dcf2effdd4a0400b1356606f44aad20cee | /SnakeCore/src/main/java/de/ostfalia/snakecore/model/game/SnakeColor.java | 485721c92a0471421e0b29e37108c2c54d930946 | [] | no_license | Bummelnderboris/Patterns_and_Frameworks | e2d2979ec5f414183ab8b78c6645573b0aa56307 | 881ea72150ddc210158a019d9b4d3ab0a845a27c | refs/heads/master | 2023-03-04T07:54:23.443557 | 2021-02-18T14:53:30 | 2021-02-18T14:53:30 | 302,651,498 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 997 | java | package de.ostfalia.snakecore.model.game;
import javafx.scene.paint.Color;
/**
* @author Benjamin Wulfert
* A special color class because javafx-color objects cant get serialized
*/
public class SnakeColor {
public double red, green, blue;
private transient Color javaFXColor;
public SnakeColor() {
red = 0.5d;
green = 0.5d;
blue = 0.5d;
}
public SnakeColor(Color fxColor){
red = fxColor.getRed();
green = fxColor.getGreen();
blue = fxColor.getBlue();
}
public SnakeColor(double red, double green, double blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
public SnakeColor fromJavaFXColor(Color color){
return new SnakeColor(color.getRed(), color.getGreen(), color.getBlue());
}
public Color toJavaFxColor(){
if(javaFXColor == null){
javaFXColor = new Color(red, green, blue, 1);
}
return javaFXColor;
}
}
| [
"wulfert.benjamin@googlemail.com"
] | wulfert.benjamin@googlemail.com |
61c93132396da2338f71687c6a0b4ee60ff6b946 | 180e78725121de49801e34de358c32cf7148b0a2 | /dataset/protocol1/spoon/learning/6537/CtVariableReferenceImpl.java | b5668ea851a844299150dd843c7c1e06da4d9d3c | [] | no_license | ASSERT-KTH/synthetic-checkstyle-error-dataset | 40e8d1e0a7ebe7f7711def96a390891a6922f7bd | 40c057e1669584bfc6fecf789b5b2854660222f3 | refs/heads/master | 2023-03-18T12:50:55.410343 | 2019-01-25T09:54:39 | 2019-01-25T09:54:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,432 | java | /**
* Copyright (C) 2006-2018 INRIA and contributors
* Spoon - http://spoon.gforge.inria.fr/
*
* This software is governed by the CeCILL-C License under French law and
* abiding by the rules of distribution of free software. You can use, modify
* and/or redistribute the software under the terms of the CeCILL-C license as
* circulated by CEA, CNRS and INRIA at http://www.cecill.info.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the CeCILL-C License for more details.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-C license and that you accept its terms.
*/
package spoon.support.reflect.reference;
import spoon.reflect.annotations.MetamodelPropertyField;
import spoon.reflect.declaration.CtVariable;
import spoon.reflect.declaration.ModifierKind;
import spoon.reflect.reference.CtTypeReference;
import spoon.reflect.reference.CtVariableReference;
import spoon.reflect.visitor.CtVisitor;
import java.lang.reflect.AnnotatedElement;
import java.util.Collections;
import java.util.Set;
import static spoon.reflect.path.CtRole.TYPE;
public abstract class CtVariableReferenceImpl<T> extends CtReferenceImpl implements CtVariableReference<T> {
private static final long serialVersionUID = 1L;
@MetamodelPropertyField(role = TYPE)
CtTypeReference<T> type;
public CtVariableReferenceImpl() {
}
@Override
public void accept(CtVisitor visitor) {
// nothing
}
@Override
public CtTypeReference<T> getType() {
return type;
}
@Override
public <C extends CtVariableReference<T>> C setType(CtTypeReference<T> type) {
if (type != null) {
type.setParent(this);
}
getFactory().getEnvironment().getModelChangeListener().onObjectUpdate(this, TYPE, type, this.type);
this.type = type;
return (C) this;
}
@Override
protected AnnotatedElement getActualAnnotatedElement() {
// this is never available through reflection
return null;
}
@Override
public CtVariable<T> getDeclaration() {
return null;
}
@Override
public Set<ModifierKind> getModifiers() {
CtVariable<T> v = getDeclaration();
if(v != null) {
return v.getModifiers();
}
return Collections.emptySet();
}
@Override
public CtVariableReference<T> clone() {
return (CtVariableReference<T>) super.clone();
}
}
| [
"bloriot97@gmail.com"
] | bloriot97@gmail.com |
316cda55486abf1b4b3bd48989ba96032a434332 | e7378b1f51e50b6a5f621ca89f4e47d3bebc2fd4 | /src/main/java/org/einnovator/util/types/TypeUtil.java | 1391bdcca7213d72ab49170c40c5b328a8c4cc2d | [] | no_license | einnovator/einnovator-util | 98a65da6bea90677811027fb992270eedb776258 | 2dc88eabc0381d4828c7e2efc6e168f3d93acca2 | refs/heads/master | 2023-04-10T11:19:09.529620 | 2021-02-28T17:48:39 | 2021-02-28T17:48:39 | 157,023,192 | 0 | 0 | null | 2021-04-26T20:45:16 | 2018-11-10T21:30:11 | Java | UTF-8 | Java | false | false | 19,818 | java | package org.einnovator.util.types;
import java.awt.Color;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.einnovator.util.meta.MetaException;
import org.einnovator.util.meta.MetaUtil;
/**
* Miscellaneous type utility operations.
*
* @author {@code support@einnovator.org}
*/
public class TypeUtil {
public static boolean isCollection(Class<?> type) {
return type.isArray() || isResizableCollection(type);
}
public static boolean isResizableCollection(Class<?> type) {
return Collection.class.isAssignableFrom(type) || TypedCollection.class.isAssignableFrom(type);
}
public static boolean isIndexedCollection(Class<?> type) {
if (type.isArray()) {
return true;
}
if (List.class.isAssignableFrom(type)) {
return true;
}
return false;
}
public static boolean isEmpty(Object value) {
return sizeSafe(value)==0;
}
public static int size(Object obj) {
Class<?> type = obj.getClass();
if (type.isArray()) {
return Array.getLength(obj);
}
if (Collection.class.isAssignableFrom(type)) {
return ((Collection<?>)obj).size();
}
return -1;
}
public static int sizeSafe(Object obj) {
int n = size(obj);
if (n>=0) {
return n;
}
throw new RuntimeException("Object of type '" + obj.getClass().getName() + "' is not an array or collection");
}
public static Object getComponent(Object obj, int index) {
Class<?> type = obj.getClass();
if (type.isArray()) {
return Array.get(obj, index);
}
if (List.class.isAssignableFrom(type)) {
return ((List<?>)obj).get(index);
}
return null;
}
@SuppressWarnings("unchecked")
public static void setComponent(Object obj, int index, Object value) {
Class<?> type = obj.getClass();
if (type.isArray()) {
Array.set(obj, index, value);
} else if (List.class.isAssignableFrom(type)) {
((List<Object>)obj).set(index, value);
}
}
public static Class<?> getComponentType(Member member) {
Class<?> type = MetaUtil.getType(member);
if (type.isArray()) {
return type.getComponentType();
}
return getTypeArgument(member, 0);
}
public static Class<?> getMapKeyType(Member member) {
return getTypeArgument(member, 0);
}
public static Class<?> getMapValueType(Member member) {
return getTypeArgument(member, 0);
}
public static Class<?> getTypeArgument(Member member, int index) {
Type gtype = MetaUtil.getGenericType(member);
return getTypeArgument(gtype, index);
}
public static Class<?> getTypeArgument(Field field) {
Type gtype = field.getGenericType();
return getTypeArgument(gtype, 0);
}
public static Class<?> getTypeArgument(Method method) {
Type gtype = method.getGenericReturnType();
return getTypeArgument(gtype, 0);
}
public static Class<?> getTypeArgument(Type gtype, int index) {
if (gtype instanceof ParameterizedType) {
Type[] actualTypes = ((ParameterizedType)gtype).getActualTypeArguments();
if (actualTypes.length>index && actualTypes[index] instanceof Class) {
return (Class<?>)actualTypes[index];
}
}
return null;
}
public static Type getGenericInterface(Class<?> type, Class<?> interfaceType) {
Type[] gtypes = type.getGenericInterfaces();
for (Type gtype: gtypes) {
if (gtype instanceof ParameterizedType) {
ParameterizedType ptype = (ParameterizedType)gtype;
if (ptype.getRawType().equals(interfaceType)) {
return gtype;
}
}
}
return null;
}
public static Class<?> getType(Class<?> theClass, Field field) {
Type gtype = field.getGenericType();
if (gtype!=null && gtype instanceof TypeVariable) {
TypeVariable<?> var = (TypeVariable<?>)gtype;
Class<?> type = getGenericParameterType(theClass, var.getName());
if (type!=null) {
return type;
}
}
return field.getType();
}
public static Class<?> getType(Class<?> theClass, Method method) {
Type gtype = method.getGenericReturnType();
if (gtype!=null && gtype instanceof TypeVariable) {
TypeVariable<?> var = (TypeVariable<?>)gtype;
Class<?> type = getGenericParameterType(theClass, var.getName());
if (type!=null) {
return type;
}
}
return method.getReturnType();
}
public static Class<?> getGenericParameterType(Class<?> type, String name) {
if (type.getSuperclass()!=null) {
TypeVariable<?>[] vars = type.getSuperclass().getTypeParameters();
int i = 0;
for (TypeVariable<?> var: vars) {
if (var.getName().equals(name)) {
Type gtype = type.getGenericSuperclass();
if (gtype instanceof ParameterizedType) {
Type[] types = ((ParameterizedType)gtype).getActualTypeArguments();
Type atype = types[i];
if (atype instanceof Class) {
return (Class<?>)atype;
}
return null;
//throw new MetaException("Unable to determined actual type for generic type variable "
//+ name + " in " + type);
}
}
i++;
}
}
return null;
}
public static Class<?> getComponentType(Object obj) {
Class<?> type = obj.getClass();
if (type.isArray()) {
return type.getComponentType();
}
if (TypedCollection.class.isAssignableFrom(type)) {
return ((TypedCollection<?>)obj).getComponentType();
}
if (List.class.isAssignableFrom(type)) {
if (((List<?>)obj).size()>0) {
return ((List<?>)obj).get(0).getClass();
}
}
if (Collection.class.isAssignableFrom(type)) {
Iterator<?> it = ((Collection<?>)obj).iterator();
return it.hasNext() ? it.next().getClass() : Object.class;
}
if (Collection.class.isAssignableFrom(type)) {
return Object.class; //hack: no way to get generic component type
}
return null;
}
public static Class<?> getComponentType(Class<?> type) {
if (type.isArray()) {
return type.getComponentType();
}
if (Collection.class.isAssignableFrom(type)) {
return Object.class; //hack: no way to get generic component type
}
return type;
}
public static boolean isPrimitiveWrapper(Class<?> type) {
return type.equals(Integer.class) || type.equals(Short.class) ||
type.equals(Long.class) || type. equals(Byte.class) ||
type.equals(Float.class) || type.equals(Double.class) ||
type.equals(Character.class) || type.equals(Boolean.class);
}
public static boolean isPrimitive(Class<?> type) {
return type.isPrimitive() || isPrimitiveWrapper(type);
}
public static boolean isCharacter(Class<?> type) {
return String.class.equals(Character.class) ||
String.class.equals(Character.TYPE);
}
public static boolean isText(Class<?> type) {
return String.class.equals(type) || StringBuffer.class.equals(type) || StringBuilder.class.equals(type);
}
public static boolean isSimple(Class<?> type) {
return isNumeric(type) || isBool(type) || isCharacter(type)
|| String.class.isAssignableFrom(type)
|| Date.class.isAssignableFrom(type)
|| type==Color.class
|| type.isEnum();
}
public static boolean isPrimitiveOrSimple(Class<?> type) {
return type.isPrimitive() || isPrimitiveWrapper(type) || isSimple(type);
}
public static boolean isNumeric(Class<?> type) {
return isNumber(box(type));
}
public static boolean isFixedSizeNumber(Class<?> type) {
return isDecimal(type) || isInt(type);
}
public static boolean isNumber(Class<?> type) {
return Number.class.isAssignableFrom(type);
}
public static boolean isDecimal(Class<?> type) {
return type==Float.TYPE || type==Float.class || type==Double.TYPE || type==Double.class;
}
public static boolean isFloat(Class<?> type) {
return type==Float.TYPE || type==Float.class;
}
public static boolean isDouble(Class<?> type) {
return type==Double.TYPE || type==Double.class;
}
public static boolean isInt(Class<?> type) {
return type==Short.TYPE || type==Short.class ||
type==Integer.TYPE || type==Integer.class ||
type==Long.TYPE || type==Long.class ||
type==Byte.TYPE || type==Byte.class;
}
public static boolean isLong(Class<?> type) {
return type==Long.TYPE || type==Long.class;
}
public static boolean isShort(Class<?> type) {
return type==Short.TYPE || type==Short.class ;
}
public static boolean isInteger(Class<?> type) {
return type==Integer.TYPE || type==Integer.class;
}
public static boolean isByte(Class<?> type) {
return type==Byte.TYPE || type==Byte.class;
}
public static boolean isBool(Class<?> type) {
return type==Boolean.TYPE || type==Boolean.class;
}
public static boolean isFalse(Object value) {
return !isTrue(value);
}
public static boolean isTrueStrict(String s) {
s = s.toLowerCase();
return s.equals("true");
}
public static boolean isTrue(String s) {
return isTrue(s, true);
}
public static boolean isTrue(String s, boolean ignoreCase) {
if (s==null) {
return false;
}
s = s.trim();
if (s.isEmpty()) {
return false;
}
if (ignoreCase && s.equalsIgnoreCase("false") ||
!ignoreCase && s.equals("false")) {
return false;
}
return true;
}
static public boolean isTrue(Object value) {
if (value==null) {
return false;
}
if (value instanceof Boolean) {
return (Boolean)value;
}
if (value instanceof String) {
return isTrue((String)value);
}
return cast(value, Boolean.class);
}
public static boolean isZeroOrFalse(Object v) {
if (v==null) return false;
return isZero(v) || isFalse(v);
}
public static boolean isZero(Object v) {
if (v==null) {
return false;
}
Object zero = zero(v.getClass());
if (zero==null) {
return false;
}
return zero.equals(v);
}
public static Object zero(Class<?> type) {
if (isInteger(type)) {
return 0;
}
if (isLong(type)) {
return 0L;
}
if (isShort(type)) {
return (short)0;
}
if (isByte(type)) {
return (byte)0;
}
if (isDouble(type)) {
return (double)0.0;
}
if (isFloat(type)) {
return (float)0.0;
}
if (isCharacter(type)) {
return '\0';
}
if (isBool(type)) {
return false;
}
return null;
}
public static boolean isPrimitiveSimilar(Class<?> ty0, Class<?> ty1) {
if (isByte(ty0) && isByte(ty1)) return true;
if (isInteger(ty0) && isInteger(ty1)) return true;
if (isShort(ty0) && isShort(ty1)) return true;
if (isLong(ty0) && isLong(ty1)) return true;
if (isFloat(ty0) && isFloat(ty1)) return true;
if (isDouble(ty0) && isDouble(ty1)) return true;
return false;
}
@SuppressWarnings("unchecked")
public static <T> T cast(Object obj, Class<? extends T> type) {
if (Object.class.equals(type)) {
return (T)obj;
}
if (obj==null) {
return null;
}
if (type==null) {
return (T)obj;
}
Class<?> type0 = obj.getClass();
if (type0==type) {
return (T)obj;
}
if (type0.isAssignableFrom(type)) {
return (T)obj;
}
if (isBool(type0) && isBool(type)) {
return (T)obj;
}
if (isNumeric(type0) && isNumeric(type)) {
if (isByte(type)) {
if (isByte(obj.getClass())) return (T)obj;
if (obj instanceof Double) return (T)(new Byte(((Double)obj).byteValue()));
if (obj instanceof Float) return (T)(new Byte(((Float)obj).byteValue()));
if (obj instanceof Integer) return (T)(new Byte(((Integer)obj).byteValue()));
if (obj instanceof Long) return (T)(new Byte(((Long)obj).byteValue()));
if (obj instanceof Short) return (T)(new Byte(((Short)obj).byteValue()));
}
if (isInteger(type)) {
if (isInteger(obj.getClass())) return (T)obj;
if (obj instanceof Double) return (T)(new Integer(((Double)obj).intValue()));
if (obj instanceof Float) return (T)(new Integer(((Float)obj).intValue()));
if (obj instanceof Byte) return (T)(new Integer(((Byte)obj).intValue()));
if (obj instanceof Long) return (T)(new Integer(((Long)obj).intValue()));
if (obj instanceof Short) return (T)(new Integer(((Short)obj).intValue()));
}
if (isShort(type)) {
if (isShort(obj.getClass())) return (T)obj;
if (obj instanceof Double) return (T)(new Short(((Double)obj).shortValue()));
if (obj instanceof Float) return (T)(new Short(((Float)obj).shortValue()));
if (obj instanceof Byte) return (T)(new Short(((Byte)obj).shortValue()));
if (obj instanceof Long) return (T)(new Short(((Long)obj).shortValue()));
if (obj instanceof Integer) return (T)(new Short(((Integer)obj).shortValue()));
}
if (isLong(type)) {
if (isLong(obj.getClass())) return (T)obj;
if (obj instanceof Double) return (T)(new Long(((Double)obj).longValue()));
if (obj instanceof Float) return (T)(new Long(((Float)obj).longValue()));
if (obj instanceof Byte) return (T)(new Long(((Byte)obj).longValue()));
if (obj instanceof Short) return (T)(new Long(((Short)obj).longValue()));
if (obj instanceof Integer) return (T)(new Long(((Integer)obj).longValue()));
}
if (isDouble(type)) {
if (isDouble(obj.getClass())) return (T)obj;
if (obj instanceof Float) return (T)(new Double(((Float)obj).doubleValue()));
if (obj instanceof Byte) return (T)(new Double(((Byte)obj).doubleValue()));
if (obj instanceof Short) return (T)(new Double(((Short)obj).doubleValue()));
if (obj instanceof Integer) return (T)(new Double(((Integer)obj).doubleValue()));
if (obj instanceof Long) return (T)(new Double(((Long)obj).doubleValue()));
}
if (isFloat(type)) {
if (isFloat(obj.getClass())) return (T)obj;
if (obj instanceof Double) return (T)(new Float(((Double)obj).floatValue()));
if (obj instanceof Byte) return (T)(new Float(((Byte)obj).floatValue()));
if (obj instanceof Short) return (T)(new Float(((Short)obj).floatValue()));
if (obj instanceof Integer) return (T)(new Float(((Integer)obj).floatValue()));
if (obj instanceof Long) return (T)(new Float(((Long)obj).floatValue()));
}
}
if (type.equals(String.class)) return (T)obj.toString();
if (type0.equals(String.class) && isNumeric(type)) {
String s = (String) obj;
return (T)parse(type, s);
}
if (isBool(type0)) {
if (isInt(type)) return (T)new Integer((((Boolean)obj).booleanValue() ? 1 : 0));
if (isShort(type)) return (T)new Short((((Boolean)obj).booleanValue() ? (short)1 : (short)0));
if (isLong(type)) return (T)new Long((((Boolean)obj).booleanValue() ? (long)1 : (long)0));
if (isByte(type)) return (T)new Byte((((Boolean)obj).booleanValue() ? (byte)1: (byte)0));
if (isFloat(type)) return (T)new Float((((Boolean)obj).booleanValue() ? (float)1: (float)0));
if (isDouble(type)) return (T)new Double((((Boolean)obj).booleanValue() ? (double)1: (double)0));
}
return null;
}
public static Object parse(Class<?> type, String s) {
if (type.equals(String.class)) {
return s;
}
if (s.equalsIgnoreCase("null")) {
return null;
}
if (isBool(type)) return Boolean.parseBoolean(s);
if (isByte(type)) return Byte.decode(s);
if (isLong(type)) return Long.decode(s);
if (isInteger(type)) return Integer.decode(s);
if (isShort(type)) return Short.decode(s);
if (isFloat(type)) return Float.parseFloat(s);
if (isDouble(type)) return Double.parseDouble(s);
if (isNumber(type)) {
float f = Float.parseFloat(s);
if (f==(int)f) {
if ((int)f==(long)f) return new Integer((int)f);
return new Long((long)f);
}
}
if (type.isEnum()) {
Object[] lv = type.getEnumConstants();
for (Object v: lv) {
String vs = String.format("%s", v);
if (s.equalsIgnoreCase(vs)) { return v; }
}
}
throw new RuntimeException("parse error:" + type + " " + s);
}
/**
* Find the enumerated value with given ordinal.
*
* @param type the enumerated type
* @param n the enumerated ordinal value
* @return the enumerate value
*/
public static Enum<?> getEnumValueFromOrdinal(Class<Enum<?>> type, int n) {
Enum<?>[] lv = type.getEnumConstants();
for (Enum<?> v: lv) {
if (v.ordinal()==n) {
return v;
}
}
return null;
}
/**
* Find the enumerated value with matching name (case ignored).
*
* @param type the enumerated type
* @param text the text representation of the enumerated value
* @return the enumerate value
*/
public static Enum<?> getEnumValueFromString(Class<Enum<?>> type, String text) {
for (Enum<?> v: type.getEnumConstants()) {
if (text.equalsIgnoreCase(v.toString())) {
return (Enum<?>)v;
}
}
return null;
}
private static Map<Class<?>, Class<?>> boxMap, unboxMap;
static {
boxMap = new HashMap<Class<?>, Class<?>>();
unboxMap = new HashMap<Class<?>, Class<?>>();
boxMap.put(Integer.TYPE, Integer.class);
boxMap.put(Long.TYPE, Long.class);
boxMap.put(Byte.TYPE, Byte.class);
boxMap.put(Short.TYPE, Short.class);
boxMap.put(Boolean.TYPE, Boolean.class);
boxMap.put(Character.TYPE, Character.class);
boxMap.put(Float.TYPE, Float.class);
boxMap.put(Double.TYPE, Double.class);
unboxMap.put(Integer.class, Integer.TYPE);
unboxMap.put(Long.class, Long.TYPE);
unboxMap.put(Byte.class, Byte.TYPE);
unboxMap.put(Short.class, Short.TYPE);
unboxMap.put(Boolean.class, Boolean.TYPE);
unboxMap.put(Character.class, Character.TYPE);
unboxMap.put(Float.class, Float.TYPE);
unboxMap.put(Double.class, Double.TYPE);
}
public static Class<?> box(Class<?> type) {
Class<?> boxed = boxMap.get(type);
return boxed!=null ? boxed : type;
}
public static Class<?> unbox(Class<?> type) {
Class<?> unboxed = unboxMap.get(type);
return unboxed!=null ? unboxed : type;
}
public static String[] getClassNames(Class<?>[] classes) {
String[] classNames = new String[classes.length];
int i = 0;
for (Class<?> klass: classes) {
classNames[i++] = klass.getName();
}
return classNames;
}
/**
* Get the uni-dimensional array type for a component type.
*
* @param componentType the component type
* @return the array type.
*/
public static Class<?> getArrayType(Class<?> componentType) {
return MetaUtil.forName("[L" + componentType.getName() + ";");
}
/**
* Get the uni-dimensional array type for a component type.
*
* @param componentType the component type
* @return the array type.
* @throws MetaException if the array type can not be found
*/
public static Class<?> getRequiredArrayType(Class<?> componentType) {
return MetaUtil.forNameRequired("[L" + componentType.getName() + ";");
}
/**
* Check whether an array with the (formal) parameter types of one method
* is compatible with (actual) parameter of types specified by a second array.
*
* @param formalTypes formal types
* @param actualTypes the actual types
* @return <code>true</code>, if the actual parameter types are compatible with the
* actual parameterTypes; <code>false</code>, otherwise.
*/
public static boolean assignableFrom(Class<?>[] formalTypes, Class<?>[] actualTypes) {
if (formalTypes.length!=actualTypes.length) {
return false;
}
for (int i=0; i<actualTypes.length; i++) {
if (formalTypes[i].isAssignableFrom(actualTypes[i])) {
return false;
}
}
return true;
}
} | [
"jsimao71@gmail.com"
] | jsimao71@gmail.com |
7115854ed14a05c27bb5c281dce54a49ee483972 | 5ec9bb57971a4d6cb44326314698b25190aa4f97 | /robertkochhu/week03/day3/DiceSet/src/DiceSet.java | 7e5ebe7f6dc12122ad97c8e5a65e3c101bc52870 | [] | no_license | green-fox-academy/robertkochhu | 934b3dc4cbe06841403948185847de8462d064d0 | 5dcea7eff827b894fa91d85c6869d489e9432fdc | refs/heads/master | 2020-03-25T00:03:42.823599 | 2018-12-14T11:50:29 | 2018-12-14T11:50:29 | 143,167,116 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,393 | java | import java.util.Arrays;
class DiceSet {
// You have a `DiceSet` class which has a list for 6 dices
// You can roll all of them with roll()
// Check the current rolled numbers with getCurrent()
// You can reroll with reroll()
// Your task is to roll the dices until all of the dices are 6
int[] dices = new int[6];
int[] roll() {
for (int i = 0; i < dices.length; i++) {
dices[i] = (int) (Math.random() * 6) + 1;
}
return dices;
}
int[] getCurrent() {
return dices;
}
int getCurrent(int i) {
return dices[i];
}
void reroll() {
for (int i = 0; i < dices.length; i++) {
dices[i] = (int) (Math.random() * 6) + 1;
}
}
void reroll(int k) {
dices[k] = (int) (Math.random() * 6) + 1;
}
public static void main(String[] args) {
DiceSet diceSet = new DiceSet();
diceSet.getCurrent();
diceSet.roll();
diceSet.getCurrent();
diceSet.getCurrent(5);
diceSet.reroll();
diceSet.getCurrent();
diceSet.reroll(4);
diceSet.getCurrent();
int sum = diceSet.dices[0] + diceSet.dices[1] + diceSet.dices[2] + diceSet.dices[3] + diceSet.dices[4] + diceSet.dices[5];
do {
diceSet.roll();
System.out.println("GOT IT");
} while (sum == 36);
}
}
| [
"robert.koch.hu1@gmail.com"
] | robert.koch.hu1@gmail.com |
f22beb254dc12c520eaa458100c93b5542ad5613 | 4a3a7c334952d3674cceffb8b697dd3fbe50173f | /src/test/java/dn/web/girl/controller/HelloControllerTest.java | 82c99957d7f43764bcbf194feda78f50aa6c3055 | [] | no_license | 17796645107/SpringBootDemo | 351bde567206b2405b66aa1318f76f01e4d8e621 | 0044a61f34fc8d2b1fe83cd97cf955b64b77e738 | refs/heads/master | 2020-04-03T16:16:33.319930 | 2018-10-30T14:23:43 | 2018-10-30T14:23:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,265 | java | package dn.web.girl.controller;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
/**
* @Author: dengning
* @Description: 测试类
* @Date: Created in 16:16 2018/10/27
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void girlListTest() throws Exception{
//请求路径测试
// mockMvc.perform(MockMvcRequestBuilders.get("/getGirls")).andExpect(MockMvcResultMatchers.status().isOk());
// 返回信息测试
mockMvc.perform(MockMvcRequestBuilders.get("/getGirls"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("aaa"));
;
}
} | [
"33450180+17796645107@users.noreply.github.com"
] | 33450180+17796645107@users.noreply.github.com |
adf88cb9bb9925278b0a956b68e98c28e9281585 | 5e34330846b0599adf926703f2fd3e906a1c4026 | /week05_31862/app/src/main/java/com/example/week05_31862/MainActivity.java | 73e52446dca8e19ef9489264b515fa1ade56a449 | [] | no_license | iansebs/Mobile_Sebastian_31862 | 0e441e1167d434bca79c4ea29abcd44a03ee8ac7 | b8e14c350e8fd43da8415c7283e44f1d08c69112 | refs/heads/main | 2023-04-22T23:12:01.345252 | 2021-05-10T09:52:54 | 2021-05-10T09:52:54 | 335,644,631 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,417 | java | package com.example.week05_31862;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
public class MainActivity extends AppCompatActivity {
private SeekBar sbRed, sbGreen, sbBlue;
private RadioGroup rgBentuk;
private RadioButton rbPilih;
private ImageButton btnWarna;
private CustomView customView;
private int red = 0;
private int green = 0;
private int blue = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sbRed = findViewById(R.id.sbRed);
sbGreen = findViewById(R.id.sbGreen);
sbBlue = findViewById(R.id.sbBlue);
btnWarna= findViewById(R.id.btnWarna);
rgBentuk = findViewById(R.id.rgBentuk);
customView=findViewById(R.id.customView);
customView= new CustomView(this);
rgBentuk.setOnCheckedChangeListener(
new RadioGroup.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup group, int checkedId){
int intRb = rgBentuk.getCheckedRadioButtonId();
rbPilih = findViewById(intRb);
String bentuk = rbPilih.getText().toString();
customView.gantiBentuk(bentuk);
}
});
sbRed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser){}
@Override
public void onStartTrackingTouch(SeekBar seekBar){}
@Override
public void onStopTrackingTouch(SeekBar seekBar){
red = sbRed.getProgress();
customView.gantiWarna(red,green,blue);
btnWarna.setBackgroundColor(Color.rgb(red,green,blue));
}
});
sbGreen.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser){}
@Override
public void onStartTrackingTouch(SeekBar seekBar){}
@Override
public void onStopTrackingTouch(SeekBar seekBar){
green = sbGreen.getProgress();
customView.gantiWarna(red,green,blue);
btnWarna.setBackgroundColor(Color.rgb(red,green,blue));
}
});
sbBlue.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser){}
@Override
public void onStartTrackingTouch(SeekBar seekBar){}
@Override
public void onStopTrackingTouch(SeekBar seekBar){
blue = sbBlue.getProgress();
customView.gantiWarna(red,green,blue);
btnWarna.setBackgroundColor(Color.rgb(red,green,blue));
}
});
}
}
| [
"64369602+iansebs@users.noreply.github.com"
] | 64369602+iansebs@users.noreply.github.com |
dd4debbd0fa6b0e2859469a28b78562cc8af60a5 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/12/12_e7750464f8283c67db4ccfb3125aeb885c54027d/VirtualBoxController/12_e7750464f8283c67db4ccfb3125aeb885c54027d_VirtualBoxController_s.java | f7763766db4134f401eccb63db29a2bcd70de115 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 9,309 | java | package de.uniba.wiai.dsg.betsy.virtual.host;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.virtualbox_4_2.CleanupMode;
import org.virtualbox_4_2.IAppliance;
import org.virtualbox_4_2.IMachine;
import org.virtualbox_4_2.IMedium;
import org.virtualbox_4_2.ISession;
import org.virtualbox_4_2.IVirtualBox;
import org.virtualbox_4_2.LockType;
import org.virtualbox_4_2.VBoxException;
import org.virtualbox_4_2.VirtualBoxManager;
import de.uniba.wiai.dsg.betsy.Configuration;
import de.uniba.wiai.dsg.betsy.virtual.host.exceptions.vm.VirtualMachineNotFoundException;
/**
* The {@link VirtualBoxController} establishes the connection between betsy and
* VirtualBox. It can be used to resolve machines, import or delete them.
*
* @author Cedric Roeck
* @version 1.0
*/
public class VirtualBoxController {
public static final String BETSY_VBOX_GROUP = "/betsy-engines";
private final Logger log = Logger.getLogger(getClass());
private final Configuration config = Configuration.getInstance();
private final Map<String, VirtualMachine> virtualMachines = new HashMap<>();
private final VirtualBoxManager vbManager;
private IVirtualBox vBox;
private VirtualBoxImporter vBoxImporter;
public VirtualBoxController() {
this.vbManager = VirtualBoxManager.createInstance(null);
}
/**
* Initialize the controller and connect to the VBoxWebSrv.
*/
public void init() {
String host = config.getValueAsString("virtualisation.vboxwebsrv.host",
"http://127.0.0.1");
String port = config.getValueAsString("virtualisation.vboxwebsrv.port",
"18083");
String username = config.getValueAsString(
"virtualisation.vboxwebsrv.user", "user");
String password = config.getValueAsString(
"virtualisation.vboxwebsrv.password", "password");
try {
this.vbManager.connect(host + ":" + port, username, password);
} catch (org.virtualbox_4_2.VBoxException exception) {
if (exception.getMessage().contains(
"reasonText argument for createFault was passed NULL")) {
log.warn("Connecting to vboxWebSrv failed, trying to deactivate websrvauthlibrary...");
// try to switch the auth mode of VirtualBox
String vbpath = config
.getValueAsString("virtualisation.vbox.vboxmanage");
Runtime r = Runtime.getRuntime();
String cmd[] = { vbpath, "setproperty", "websrvauthlibrary",
"null" };
try {
r.exec(cmd);
log.info("... set VirtualBox websrvauthlibrary to 'null'");
} catch (Exception e2) {
log.warn("... couldn't null VirtualBox websrvauthlibrary:",
e2);
}
this.vbManager.connect(host + ":" + port, username, password);
log.info("Conneting to vboxWebSrv succeeded!");
} else if (exception.getMessage().equals(
"HTTP transport error: "
+ "java.net.ConnectException: Connection refused")) {
log.error("VBoxWebSrv does not seem to be running on the specified address!");
throw exception;
} else {
// unknown exception, can't solve situation
log.error("Unknown exception while connecting to vboxWebSrv");
throw exception;
}
}
this.vBox = vbManager.getVBox();
log.debug(String.format("Using VirtualBox version '%s'",
vBox.getVersion()));
// no delay, continue with network usage immediately
this.setLinkUpDelay(0);
this.vBoxImporter = new VirtualBoxImporter(this.vBox);
}
/**
* Check if VirtualBox contains a virtual machine with the given name inside
* the group 'betsy-engines'.
*
* @param vmName
* name of the VM to search
* @return true if VirtualBox contains a name with the name
*/
public boolean containsMachine(final String vmName) {
if (StringUtils.isBlank(vmName)) {
throw new IllegalArgumentException(
"vmName must not be null or empty");
}
List<String> groups = new LinkedList<>();
groups.add(BETSY_VBOX_GROUP);
List<IMachine> machines = vBox.getMachinesByGroups(groups);
if (machines.isEmpty()) {
log.info("VirtualBox does not contain any machines yet.");
return false;
}
for (IMachine vm : machines) {
if (vm.getName().equals(vmName)) {
return true;
}
}
return false;
}
/**
* Import the Engine's virtualMachine from the given file.
*
* @param vmName
* desired name of the virtualMachine
* @param engineName
* name of the engine the new VM belongs to
* @param importFile
* file of the appliance to import
*/
public void importVirtualMachine(final String vmName,
final String engineName, final File importFile) {
if (StringUtils.isBlank(vmName)) {
throw new IllegalArgumentException(
"The name of the vm to import must not be null or empty");
}
if (StringUtils.isBlank(engineName)) {
throw new IllegalArgumentException(
"The name of the engine to import must not be null or empty");
}
if (importFile == null) {
throw new IllegalArgumentException(
"The file to import must not be null");
}
IMachine importedVm = null;
ISession session = null;
try {
IAppliance appliance = vBoxImporter.importAppliance(importFile);
// by definition the appliance container could contain several
// separated machines which must be imported each at it's own.
for (String uuid : appliance.getMachines()) {
importedVm = vBox.findMachine(uuid);
// acquire session lock
session = vbManager.getSessionObject();
importedVm.lockMachine(session, LockType.Write);
IMachine lockedVM = session.getMachine();
vBoxImporter
.adjustMachineSettings(lockedVM, vmName, engineName);
try {
session.unlockMachine();
session = null;
} catch (VBoxException exception) {
// ignore if was not locked
log.debug("Failed to unlock session after import");
}
} // END FOR ITERATION
} catch (VBoxException exception) {
// session must be unlocked for deleting the vm
if (session != null) {
try {
session.unlockMachine();
} catch (VBoxException exception2) {
log.debug("Failed to unlock session after import exception");
// ignore if was not locked
}
}
if (importedVm != null) {
log.debug("Exception during import, delete VM again.");
// Error --> delete VM again
this.deleteMachine(importedVm);
}
log.warn("Unexpected import exception:", exception);
}
}
/**
* Get the {@link VirtualMachine} of betsy with the given name.
*
* @param name
* name of the VirtualMachine to get
* @return VirtualMachine with the searched name
* @throws VirtualMachineNotFoundException
* thrown if there is no VirtualMachine with this name
*/
public VirtualMachine getVirtualMachine(final String name)
throws VirtualMachineNotFoundException {
if (virtualMachines.containsKey(name)) {
return virtualMachines.get(name);
} else {
VirtualMachine vm = new VirtualMachine(vbManager, getMachine(name));
virtualMachines.put(name, vm);
return vm;
}
}
/**
* Get the {@link IMachine} of VirtualBox with the given name.
*
* @param name
* name of the IMachine to get
* @return IMachine with the searched name
* @throws VirtualMachineNotFoundException
* thrown if there is no IMachine with this name
*/
public IMachine getMachine(final String name)
throws VirtualMachineNotFoundException {
List<String> groups = new LinkedList<>();
groups.add(BETSY_VBOX_GROUP);
List<IMachine> machines = vBox.getMachinesByGroups(groups);
for (IMachine machine : machines) {
if (machine.getName().equals(name)) {
return machine;
}
}
throw new VirtualMachineNotFoundException("VirtualMachine with name '"
+ name + "' could not be found in betsy's VirtualBox group.");
}
/**
* Get the directory where VirtualBox stores it's VirtualMachine files.
*
* @return directory where VirtualBox stores it's VirtualMachine files.
*/
public File getVBoxVirtualMachineFolder() {
// get default vm folder
return new File(vBox.getSystemProperties().getDefaultMachineFolder());
}
private void deleteMachine(final IMachine machine) {
File logFolder = new File(machine.getLogFolder());
logFolder.delete();
List<IMedium> removableMediums = machine.unregister(CleanupMode.Full);
machine.delete(removableMediums);
}
/**
* The LinkUpDelay specifies how many milliseconds the network adapter of
* the guest machine remains silent until he resumes his work stored in his
* networkstack.
*
* @param milliSeconds
* timeout to set in ms
*/
private void setLinkUpDelay(int milliSeconds) {
if (Integer.parseInt(vBox.getExtraData("VBoxInternal/Devices/e1000/0/"
+ "Config/LinkUpDelay")) != milliSeconds) {
log.info("Disabling LinkUpDelay for this VirtualBox instance...");
vBox.setExtraData(
"VBoxInternal/Devices/e1000/0/Config/LinkUpDelay",
Integer.toString(milliSeconds));
}
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
8509e018ec8d3f3a5b80ed1b07335e5bae5871aa | 5a54beafa56e6e76efbcad27987c7669e1777302 | /AndroidFramework/src/com/jwd/views/DefinedToast.java | 1d393ad2ab89e313058a562e49ecb8d726bd464a | [] | no_license | jwdtommy/ZinngerDota2 | bf84c3d724622fcff42f9fcb83bce574494b2a21 | 512a51f16e77d3442faaf7d57e8f548987ac786b | refs/heads/master | 2020-06-04T03:36:43.551772 | 2013-06-04T01:12:01 | 2013-06-04T01:12:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,928 | java | package com.jwd.views;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;
public class DefinedToast extends TextView {
public final static int TYPE_SUCCESS = 1;
public final static int TYPE_FAILED = -1;
public final static int TYPE_NOTHING = 0;
private boolean isShowing = false;
private Context context;
private int A_duration = 400;
private int show_duration = 2000;
private final static int SHOW_POP = 7070;
private final static int CLOSE_POPUP = 7071;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SHOW_POP:
setVisibility(View.VISIBLE);
break;
case CLOSE_POPUP:
disToast();
break;
default:
break;
}
}
};
public DefinedToast(Context context) {
super(context);
this.context = context;
}
public DefinedToast(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
public void toastResult(String msg, int type) {
if (isShowing) {
return;
} else {
isShowing = true;
}
setText(msg);
if (type == TYPE_FAILED) {
setBackgroundColor(Color.argb(200, 187, 23, 23));
} else if (type == 0) {
setBackgroundColor(Color.argb(200, 0, 0, 0));
} else if (type == 1) {
setBackgroundColor(Color.argb(200, 11, 88, 11));
}
setTextSize(13);
TranslateAnimation ta = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF,
0f);
ta.setInterpolator(new DecelerateInterpolator(2.0F));
ta.setDuration(A_duration);
startAnimation(ta);
handler.postDelayed(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(SHOW_POP);
}
}, A_duration);
handler.postDelayed(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(CLOSE_POPUP);
}
}, show_duration + A_duration);
}
private void disToast() {
if (this != null)
setVisibility(View.GONE);
int A_duration = 400;
TranslateAnimation ta = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
-1.0f);
ta.setInterpolator(new AccelerateInterpolator(2.0F));//new AccelerateInterpolator()
ta.setDuration(A_duration);
startAnimation(ta);
try {
Thread.sleep(A_duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
isShowing = false;
}
}
| [
"659579390@qq.com"
] | 659579390@qq.com |
c16ebfe10aa950390f8a2756e27179044e959c49 | faddf8bb58c5e1da28ddda8fde59abccf8c34808 | /src/main/java/com/kangzz/mtool/enums/EnumerationUtil.java | 3e36605caea679748aad5793594589b98755c188 | [] | no_license | kangzz/mtool | 330a7e826d9a123278a0fb758cb88f94336c3d01 | aaca1c7e13864a752d8571d4770322cfc291584d | refs/heads/master | 2020-04-17T16:24:08.398581 | 2017-10-23T09:56:58 | 2017-10-23T09:56:58 | 66,936,819 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 795 | java | package com.kangzz.mtool.enums;
import com.kangzz.mtool.util.ObjectUtil;
import org.apache.commons.collections4.IteratorUtils;
import org.apache.commons.collections4.iterators.EnumerationIterator;
import java.util.Enumeration;
/**
* 描述:枚举工具类
* 作者 :kangzz
* 日期 :2016-12-17 10:17:02
*/
public final class EnumerationUtil {
/** Don't let anyone instantiate this class. */
private EnumerationUtil(){
}
/**
* 描述:判断枚举中是否存在某个值
* 作者 :kangzz
* 日期 :2016-12-17 10:18:18
*/
public static <O> boolean contains(Enumeration<O> enumeration,O value){
return ObjectUtil.isNullOrEmpty(enumeration) ? false : IteratorUtils.contains(new EnumerationIterator<O>(enumeration), value);
}
}
| [
"zhuang_it@163.com"
] | zhuang_it@163.com |
5ee1baed485719f10795f078315c9734ccc6716d | 9c43706cef30060db6e78b3dda2a2f81741c5b00 | /src/main/java/servlet/GetStationListServlet.java | 9d00137f7c5da08ae23ccf362eab90878aed6b15 | [] | no_license | makewheels/PirateBus | 925941b9655457364361a3048b81a5e54f922aef | e03c6ffb5cef643a294f4afd62264e629bec4467 | refs/heads/master | 2021-10-20T20:27:44.042512 | 2019-03-01T14:43:58 | 2019-03-01T14:43:58 | 165,213,292 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,433 | java | package servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import bean.stationinfo.my.BusStop;
import bean.stationinfo.my.MyStationInfo;
import util.FileUtil;
/**
* 站点列表
*
* @author Administrator
*
*/
public class GetStationListServlet extends HttpServlet {
private static final long serialVersionUID = 3249228653410736282L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String busName = request.getParameter("busName");
String direction = request.getParameter("direction");
// 读公交线路
List<BusStop> busStopList = JSON.parseObject(
FileUtil.readTextFile(
GetStationListServlet.class.getResource("/stationinfo/my/" + busName + ".json").getPath()),
MyStationInfo.class).getBusLineList().get(Integer.parseInt(direction)).getBusStopList();
List<String> clientBusStopList = new ArrayList<>();
for (BusStop busStop : busStopList) {
clientBusStopList.add(busStop.getName());
}
// 回写站点列表
response.setCharacterEncoding("utf-8");
response.getWriter().write(JSON.toJSONString(clientBusStopList));
}
}
| [
"spring@qbserver.cn"
] | spring@qbserver.cn |
337262c5c3961a3ffb58330b879d1471c47d8e3d | 708c25c6df0890bf4f6c57f56e15cc252d369e27 | /src/stacks/Stack.java | fe4acc57a064c7555f0ad8d047ed81ac272246e5 | [] | no_license | neeravmudgal/test_algo | f11e9359fa1df35e74faf13e6b65b8071ff73e63 | d703d126082be17a441aecd0fd7852e08347560a | refs/heads/master | 2016-09-13T15:38:15.788825 | 2016-05-18T08:14:17 | 2016-05-18T08:14:17 | 59,095,202 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 99 | java | package stacks;
public interface Stack {
public void push(String input);
public String pop();
}
| [
"neeravmugdal@Neeravs-MacBook-Pro.local"
] | neeravmugdal@Neeravs-MacBook-Pro.local |
c670af72b6ca339d48d7caaa6e9ae6495463f758 | c78c0e6b45816002e9726475d4c38fc9b2b1800d | /src/alien/Predicoward.java | 69deec6d37b71483bdeb7a9dacc51e5b86692f74 | [
"Unlicense"
] | permissive | jamespic/AlienWar | a0cdb63d5d2ae2b6744e7b61465be249526cbbb4 | 9c05509b2cfbd42b0005d3f2af6f2ceae9d24c6d | refs/heads/master | 2021-01-17T21:28:26.666121 | 2014-07-04T11:12:13 | 2014-07-04T11:12:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,392 | java | package alien;
import planet.Move;
import java.util.ArrayList;
import java.awt.Point;
/* Predict + Cat = Predicat! */
public class Predicoward extends Alien {
/*
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - P - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
Risk score = sum of manhattan distances of all aliens within vision range
*/
@Override
public void setAbilityPoints( float[] abilities ) {
abilities[3] = 10;
}
@Override
public Move move( char[][] fields ) {
/* Some credits to Eagle for letting me learn how to do the moves */
int vision = getVisionFieldsCount(); //count of fields / middle
Move bestMove=Move.STAY;
int bestRiskScore=10000;
int riskScore=0;
ArrayList<Point> aliens = new ArrayList<Point>();
//generate alien list
for (int x=0; x<=vision*2; x++) {
for(int y=0; y<=vision*2; y++){
if(fields[x][y]=='A'){
aliens.add(new Point(x,y));
}
}
}
for (Move move : Move.values()) {
int x = vision + move.getXOffset();
int y = vision + move.getYOffset();
riskScore = 0;
for(Point alienCoord : aliens){
riskScore += this.getDistance(x, y, alienCoord);
}
if(riskScore < bestRiskScore){
// System.out.print("new safe route : ");
// System.out.println(move);
// System.out.print("Risk score : " + riskScore);
// System.out.println("---------------");
bestRiskScore = riskScore;
bestMove = move;
}
}
return bestMove;
}
@Override
public boolean wantToFight( int[] enemyAbilities ) {
//I don't want to fight :(
return false;
}
//Return Manhattan Distance
private int getDistance(int x, int y, Point to){
return Math.abs(x-(int)to.getX())+Math.abs(y-(int)to.getY());
}
} | [
"james.pickering@hermes-europe.co.uk"
] | james.pickering@hermes-europe.co.uk |
e5b8f5b34be9e0217a5d8354ca59ab628444f699 | ebd21e2eace0003eae5cfd0f856c109b3d44c721 | /src/main/java/me/ebenezergraham/honours/platform/interfaces/IRewardEngine.java | c41bee9a865025ff9da9b989eff349d9a5702d29 | [] | no_license | openmeed/platfrom | 3de988a1d851a23f75091692b323a0698960f786 | 55e26a81613c1ca0287b8d3dd05bc2b6d782aa36 | refs/heads/master | 2023-01-15T07:37:58.309976 | 2020-01-02T14:45:48 | 2020-01-02T14:45:48 | 233,009,113 | 0 | 0 | null | 2023-01-07T13:35:25 | 2020-01-10T09:09:59 | Java | UTF-8 | Java | false | false | 373 | java | package me.ebenezergraham.honours.platform.interfaces;
import me.ebenezergraham.honours.platform.model.Payload;
import me.ebenezergraham.honours.platform.model.Reward;
import java.util.Map;
public interface IRewardEngine {
void process(Payload payload);
void validationCriteria(Map<String,Boolean> criteria);
boolean validate(Payload payload, Reward reward);
}
| [
"ebenezergraham69@gmail.com"
] | ebenezergraham69@gmail.com |
0cc531f6d4ebbc9d18bed3acb91e2c0e940c07f9 | 480c585224af449a8af9e0c95589d9a993eee558 | /src/com/company/printAllSubstringOfaString.java | 4e57cdc8141a4fd0afae82238e0121c36bc5e417 | [] | no_license | alams3510/practiceJavaProgram | 7eaa99c78e6bc8d4dc6b2767a321a0077ddbfcd1 | 44a479abdc7535817e19c92d99b5ee1b6283fcbe | refs/heads/master | 2023-08-11T05:42:14.125205 | 2021-09-20T14:11:57 | 2021-09-20T14:11:57 | 408,471,516 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 384 | java | package com.company;
import java.util.*;
public class printAllSubstringOfaString {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
int l=s.length();
for(int i=0;i<l;i++){
for(int j=i+1;j<=l;j++){
System.out.println(s.substring(i,j));
}
}
}
}
| [
"alams3510@gmail.com"
] | alams3510@gmail.com |
6d4b08273a1dc629f421dfc7cbc7d1c5252ff2de | ac94ac4e2dca6cbb698043cef6759e328c2fe620 | /labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualMachineTemplateInVirtualDatacenter.java | e5bb53053c4e48abbe4c3ba303617a699dc6b432 | [
"Apache-2.0"
] | permissive | andreisavu/jclouds | 25c528426c8144d330b07f4b646aa3b47d0b3d17 | 34d9d05eca1ed9ea86a6977c132665d092835364 | refs/heads/master | 2021-01-21T00:04:41.914525 | 2012-11-13T18:11:04 | 2012-11-13T18:11:04 | 2,503,585 | 2 | 0 | null | 2012-10-16T21:03:12 | 2011-10-03T09:11:27 | Java | UTF-8 | Java | false | false | 1,581 | java | /**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.abiquo.domain.cloud;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Wrapper to hold the information of a virtual machine template scoped to a
* concrete hypervisor type.
*
* @author Ignasi Barrera
*/
public class VirtualMachineTemplateInVirtualDatacenter {
private VirtualMachineTemplate template;
private VirtualDatacenter zone;
public VirtualMachineTemplateInVirtualDatacenter(final VirtualMachineTemplate template, final VirtualDatacenter zone) {
super();
this.template = checkNotNull(template, "template");
this.zone = checkNotNull(zone, "zone");
}
public VirtualMachineTemplate getTemplate() {
return template;
}
public VirtualDatacenter getZone() {
return zone;
}
}
| [
"ignasi.barrera@abiquo.com"
] | ignasi.barrera@abiquo.com |
25c4611901d3256e931fef1a6d4b6ef24293a374 | 0f715e795e6748eaaa31d9cdfa626ffd76a12d86 | /prac_sel_soap/autoIT/src/autoIT/autoIT_eg.java | fc5262de9569f011167f0c56943752517018bb90 | [] | no_license | fardeen4h/seleniu_soap_practice | 0e8009b6f30325bdb7192bb4cca4c37661e082bd | 472ec44c54a30fa8aace4d11e978b7d419e01dcb | refs/heads/master | 2023-01-03T19:27:12.911931 | 2020-10-30T22:03:17 | 2020-10-30T22:03:17 | 308,364,081 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,851 | java | package autoIT;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
public class autoIT_eg {
public static void main(String[] args) throws InterruptedException, IOException {
// TODO Auto-generated method stub
String downloadPath=System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\resources\\chromedriver.exe");
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadPath);
ChromeOptions options=new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
ChromeDriver driver= new ChromeDriver(options);
// driver.get("https://the-internet.herokuapp.com/");
driver.get("https://smallpdf.com/pdf-to-word");
//for basic authentication pop up you can use the follwoing notaion
//http://Username:Password@SiteURL
//we can pass the above driver.get() like this
// driver.get("https://admin:admin@the-internet.herokuapp.com/");
// driver.findElement(By.linkText("Basic Auth")).click();
driver.findElement(By.xpath("//span[@class='sc-1rkezdt-7 cxlSWI']")).click();;
// driver.findElement(By.linkText("File Upload")).click();
// driver.findElement(By.xpath("//input[@id='file-upload']")).click();
Thread.sleep(3000);
Runtime.getRuntime().exec(System.getProperty("user.dir")+"\\resources\\uploadfile.exe");
WebDriverWait wait=new WebDriverWait(driver,10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='kov65o-0 iPohUv']//div[1]//div[@class='sc-1an4xct-0 kuIGAX']")));
// Thread.sleep(7000);
driver.findElement(By.xpath("//div[@class='kov65o-0 iPohUv']//div[1]//div[@class='sc-1an4xct-0 kuIGAX']")).click();
// Thread.sleep(7000);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//button[@class='sc-1mvwhop-0 bqmdbl']")));
driver.findElement(By.xpath("//button[@class='sc-1mvwhop-0 bqmdbl']")).click();
// Runtime.getRuntime().exec("E:\\autoitexe\\uploadfile.exe");
// Thread.sleep(7000);
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//span[@class='wnolmd-2 etrSPs']")));
driver.findElement(By.xpath("//span[@class='wnolmd-2 etrSPs']")).click();
Thread.sleep(7000);
File f=new File(downloadPath+"\\Exit Formality-converted.docx");
if(f.exists())
{
Assert.assertTrue(f.exists());
if(f.delete())
System.out.println("file deleted");
}
// driver.findElement(By.id("file-submit")).click();
}
}
| [
"fardeenkhan.btech16@gmail.com"
] | fardeenkhan.btech16@gmail.com |
7b5c0675b8197e7b499f2445e8776b090e305269 | 09a953cd99c21947825d99fedf47ee158314b4c9 | /src/com/company/AllPermutationsI.java | 5646da98c25fdd2e4cab9dab61d0b26a09a945da | [] | no_license | riooooorio/CodingPractice | 1960695a1013f21780de92c2a2a06daac74a0dd8 | efd4aea5e48d3aec7ffa2668c0bcabf00e26973d | refs/heads/master | 2023-02-22T03:50:08.434284 | 2021-01-25T22:03:04 | 2021-01-25T22:03:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,511 | java | package com.company;
import java.util.*;
public class AllPermutationsI {
// DFS solution with swapping
// Time O(n! * n)
// Space O(n)
public List<String> permutations(String input) {
// Write your solution here
List<String> result = new ArrayList<>();
char[] array = input.toCharArray();
helper(array, 0, result);
return result;
}
// choose the character to be a the position of "index"
// all the already chosen position are (0, index - 1)
// all the candidate characters can be at position "index"
// are in the sub-array of (index, array.length - 1)
private void helper(char[] array, int index, List<String> result) {
// terminate condition:
// only when we have already chosen the characters for all the positions,
// we can have a complete permutation
if (index == array.length) {
result.add(new String(array));
return;
}
// all the possible characters could be placed at index are
// the characters in the sub-array (index, array.length - 1)
for (int i = index; i < array.length; i++) {
swap(array, index, i);
helper(array, index + 1, result);
// remember to swap back when back track to previous level
swap(array, index, i);
}
}
private void swap(char[] array, int i, int j) {
char tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
| [
"vivianxinzhang@gmail.com"
] | vivianxinzhang@gmail.com |
935e6e1c249b7b0d5f5ee9ba0eeaa49b490d272f | e54a29d3144d3d196389d274da27ffad2ccf7e58 | /src/pbo2/myframe.java | e67ce82112b4a70b828f5273e2fb8f3754c6b2ec | [] | no_license | enocomel14/PBO2 | 6a95fe92acc3be0fe1092b4f82a610975fd51571 | 45538e2689d7d4cf1259f4bdabfe2dc858e07c66 | refs/heads/master | 2021-08-06T11:13:10.167968 | 2017-11-05T12:24:52 | 2017-11-05T12:24:52 | 109,578,202 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 469 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pbo2;
public class myframe {
string pesan;
int bilbulat;
double bildesimal;
void cetakAttribute(){
system.out.println("isi dari pesan :"+pesan);
system.out.println("isi dari bibulat:"+bilbulat);
system.out.println("isi dari bildesimal:"+bildesimal);
}
}
| [
"32240707+enocomel14@users.noreply.github.com"
] | 32240707+enocomel14@users.noreply.github.com |
14e745cf533241b10384afbda892065acf73703c | 32cc06a3c85d9443256f422a87303c7624c61420 | /app/src/main/java/com/aerogear/androidshowcase/features/device/views/DeviceViewImpl.java | 4bfad568420c4ab61da2ed68b0af643b90f1bdc6 | [
"Apache-2.0"
] | permissive | ananthrajtag/android-showcase-template | 690ff6353a9cf0f7bbae87be8805e0a91be5a39d | 6f4fe2ac6922e57dc3530a3e73c2f3a468fb5528 | refs/heads/master | 2020-06-18T09:25:28.206188 | 2019-07-12T04:17:53 | 2019-07-12T04:17:53 | 196,251,594 | 0 | 0 | Apache-2.0 | 2019-07-10T17:53:34 | 2019-07-10T17:53:33 | null | UTF-8 | Java | false | false | 348 | java | package com.aerogear.androidshowcase.features.device.views;
import android.app.Fragment;
import com.aerogear.androidshowcase.mvp.views.BaseAppView;
/**
* Created by tjackman on 16/10/17.
*/
public class DeviceViewImpl extends BaseAppView implements DeviceView {
public DeviceViewImpl(Fragment fragment) {
super(fragment);
}
}
| [
"tom.dls@hotmail.com"
] | tom.dls@hotmail.com |
7b32f9e99dde7e81ff1dbd4f650d4c48bbf1f6b2 | a30eb3e490796e71693bde0a69e19bb50f1c662c | /app/src/main/java/com/example/juddyreina/proyecto/guia.java | d295719b043294254150a4b104f0109880c0f398 | [] | no_license | juddyk/Proyecto | 314c1c17a192c0ff285d2389c09c23886c42e0fa | 61a154edac1f02219243d266381fff239f029154 | refs/heads/master | 2021-01-10T09:24:51.816182 | 2016-01-20T08:14:35 | 2016-01-20T08:14:35 | 49,973,543 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,132 | java | package com.example.juddyreina.proyecto;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class guia extends AppCompatActivity implements Animation.AnimationListener {
private TextView tvTitle;
private TextView tvInfo;
private ImageButton btnOut;
private ImageView img;
Animation animZoomI;
Animation animZoomO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guia);
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/TimKid.ttf");
tvTitle=(TextView) findViewById(R.id.titleG);
tvInfo=(TextView) findViewById(R.id.idinfo);
img=(ImageView) findViewById(R.id.idImagen);
btnOut=(ImageButton) findViewById(R.id.btnExit);
tvTitle.setTypeface(myCustomFont);
tvInfo.setTypeface(myCustomFont);
animZoomI = AnimationUtils.loadAnimation(this, R.anim.zoom_in);
animZoomI.setAnimationListener(this);
animZoomO = AnimationUtils.loadAnimation(this, R.anim.zoom_out);
animZoomO.setAnimationListener(this);
img.setImageResource(R.drawable.nina);
tvInfo.setText(R.string.help);
btnOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
img.clearAnimation();
Intent i = new Intent(guia.this, Mostrar.class);
startActivity(i);
}
});
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
// Animation is repeating
}
@Override
public void onAnimationStart(Animation animation) {
// Animation started
}
}
| [
"reina.jk@gmail.com"
] | reina.jk@gmail.com |
17e77aae1cb10f434492ca0ae4919543cf6e6917 | e7ac66d01d498b739b236753cbb95da0a2c4d8ad | /carrental-web/src/main/java/ch/xxx/carrental/ui/rest/CrApplication.java | 4cdccf8e5937693f3b7b26bb47e7d7a670ccfd9c | [
"Apache-2.0"
] | permissive | Anoopkr/ejb-angular-sample | 9817f31614fc8669b68a0ef8411a524913fb4170 | af476d29babfc47114723b698dd74161169c05a9 | refs/heads/development | 2023-01-16T05:02:33.133963 | 2020-02-05T17:10:03 | 2020-02-05T17:10:03 | 238,495,125 | 0 | 0 | Apache-2.0 | 2023-01-07T14:30:31 | 2020-02-05T16:23:07 | null | UTF-8 | Java | false | false | 2,345 | java | /**
* Copyright 2016 Sven Loesekann
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 ch.xxx.carrental.ui.rest;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import ch.xxx.carrental.ui.dto.CrDetail;
import ch.xxx.carrental.ui.dto.CrLogMsg;
import ch.xxx.carrental.ui.dto.CrMessage;
import ch.xxx.carrental.ui.dto.CrPeriod;
import ch.xxx.carrental.ui.dto.CrPortfolio;
import ch.xxx.carrental.ui.dto.CrTableRow;
import ch.xxx.carrental.ui.interceptor.JaxRsExceptionMapper;
import ch.xxx.carrental.ui.rest.model.CrDetailResource;
import ch.xxx.carrental.ui.rest.model.CrLogResource;
import ch.xxx.carrental.ui.rest.model.CrTableResource;
import io.swagger.jaxrs.config.BeanConfig;
@ApplicationPath("rest")
public class CrApplication extends Application {
public CrApplication() {
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion("1.5.10");
beanConfig.setSchemes(new String[]{"http"});
beanConfig.setHost("localhost:8080");
beanConfig.setBasePath("/carrental-web/rest");
beanConfig.setResourcePackage("ch.xxx.carrental.ui.rest.model");
beanConfig.setScan(true);
}
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(CrPortfolio.class);
classes.add(CrDetail.class);
classes.add(CrMessage.class);
classes.add(CrPeriod.class);
classes.add(CrTableRow.class);
classes.add(CrLogMsg.class);
classes.add(CrTableResource.class);
classes.add(CrDetailResource.class);
classes.add(CrLogResource.class);
classes.add(io.swagger.jaxrs.listing.ApiListingResource.class);
classes.add(io.swagger.jaxrs.listing.SwaggerSerializers.class);
classes.add(JaxRsExceptionMapper.class);
return classes;
}
}
| [
"anoopply2009@gmail.com"
] | anoopply2009@gmail.com |
156600bba1a950a19eb33241b49a2acfbd318870 | 2a5947b7ab9a4ef021b79c807c93636ec39a850f | /CGuide3 Plugin/src/org/di/uminho/cguide/wizard/Edit/Condition/EditConditionPage2.java | 6560df17159c0501aa6140978c3c196a2d1e48c1 | [] | no_license | bilalbenma/CompGuide-Editor | ab231eab5c3c8f088b8e1f32bbcab99006aa322a | d724634a939fea80a17ad2eee258b600dcb64273 | refs/heads/master | 2021-06-18T06:52:44.149950 | 2017-07-13T16:37:47 | 2017-07-13T16:37:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,802 | java | package org.di.uminho.cguide.wizard.Edit.Condition;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.swing.ButtonGroup;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import org.protege.editor.core.ui.wizard.WizardPanel;
import org.protege.editor.owl.OWLEditorKit;
import org.protege.editor.owl.ui.AbstractOWLWizardPanel;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLDataPropertyExpression;
import org.semanticweb.owlapi.model.OWLIndividual;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLOntology;
public class EditConditionPage2 extends AbstractOWLWizardPanel {
public static final String ID = "EditConditionPage2";
public static final String title = "Insert Temporal Restriction Data Required";
public int temporalrestriction_type = 0;
private JRadioButton maxmintemporalrestriction_ratiobutton;
private JRadioButton temporalrestriction_ratiobutton;
public JTextField maxtemporalrestriction_textfield;
public JTextField temporalrestriction_textfield;
private JLabel temporaloperator_label;
public JComboBox temporaloperator_combobox;
private JLabel temporalunit_label;
public JTextField mintemporalrestriction_textfield;
public JComboBox temporalunit_combobox;
private String maxtemporalrestrictionvalue = new String(), mintemporalrestrictionvalue = new String(),
temporalrestrictionvalue = new String(), temporaloperator = new String(), temporalunit = new String();
private int type;
public EditConditionPage2(OWLEditorKit owlEditorKit, String condition_individual) {
super(ID, title, owlEditorKit);
getCondition_data(condition_individual);
}
protected void createUI(JComponent parent) {
setInstructions("Please insert the Temporal Restriction for this Clinical Condition.");
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] { 106, 5, 180, 0, 0 };
gridBagLayout.rowHeights = new int[] { 23, 0, 23, 20, 20, 20, 20, 0 };
gridBagLayout.columnWeights = new double[] { 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE };
gridBagLayout.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
parent.setLayout(gridBagLayout);
maxmintemporalrestriction_ratiobutton = new JRadioButton("Max/Min Temporal Restriction:", true);
GridBagConstraints gbc_maxmintemporalrestriction_ratiobutton = new GridBagConstraints();
gbc_maxmintemporalrestriction_ratiobutton.anchor = GridBagConstraints.EAST;
gbc_maxmintemporalrestriction_ratiobutton.insets = new Insets(0, 0, 5, 5);
gbc_maxmintemporalrestriction_ratiobutton.gridwidth = 2;
gbc_maxmintemporalrestriction_ratiobutton.gridx = 0;
gbc_maxmintemporalrestriction_ratiobutton.gridy = 0;
parent.add(maxmintemporalrestriction_ratiobutton, gbc_maxmintemporalrestriction_ratiobutton);
maxtemporalrestriction_textfield = new JTextField();
maxtemporalrestriction_textfield.setColumns(10);
maxtemporalrestriction_textfield.setEnabled(true);
maxtemporalrestriction_textfield.setToolTipText("Enter Maximum Temporal Restriction");
GridBagConstraints gbc_maxtemporalrestriction_textfield = new GridBagConstraints();
gbc_maxtemporalrestriction_textfield.insets = new Insets(0, 0, 5, 5);
gbc_maxtemporalrestriction_textfield.gridx = 2;
gbc_maxtemporalrestriction_textfield.gridy = 0;
parent.add(maxtemporalrestriction_textfield, gbc_maxtemporalrestriction_textfield);
mintemporalrestriction_textfield = new JTextField();
mintemporalrestriction_textfield.setEnabled(true);
mintemporalrestriction_textfield.setColumns(10);
mintemporalrestriction_textfield.setToolTipText("Enter Minimum Temporal Restriction");
GridBagConstraints gbc_mintemporalrestriction_textfield = new GridBagConstraints();
gbc_mintemporalrestriction_textfield.insets = new Insets(0, 0, 5, 5);
gbc_mintemporalrestriction_textfield.gridx = 2;
gbc_mintemporalrestriction_textfield.gridy = 1;
parent.add(mintemporalrestriction_textfield, gbc_mintemporalrestriction_textfield);
temporalrestriction_ratiobutton = new JRadioButton("Average Temporal Restriction:");
GridBagConstraints gbc_temporalrestriction_ratiobutton = new GridBagConstraints();
gbc_temporalrestriction_ratiobutton.anchor = GridBagConstraints.EAST;
gbc_temporalrestriction_ratiobutton.insets = new Insets(0, 0, 5, 5);
gbc_temporalrestriction_ratiobutton.gridwidth = 2;
gbc_temporalrestriction_ratiobutton.gridx = 0;
gbc_temporalrestriction_ratiobutton.gridy = 2;
parent.add(temporalrestriction_ratiobutton, gbc_temporalrestriction_ratiobutton);
ButtonGroup buttongroup = new ButtonGroup();
buttongroup.add(maxmintemporalrestriction_ratiobutton);
buttongroup.add(temporalrestriction_ratiobutton);
// Add Listener
maxmintemporalrestriction_ratiobutton.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
// Temporal Restriction max/min -> type 0
temporalrestriction_type = 0;
maxtemporalrestriction_textfield.setEnabled(true);
mintemporalrestriction_textfield.setEnabled(true);
temporalrestriction_textfield.setEnabled(false);
temporalrestriction_textfield.setText("");
}
}
});
temporalrestriction_ratiobutton.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
// Temporal Restriction max/min -> type 1
temporalrestriction_type = 1;
maxtemporalrestriction_textfield.setEnabled(false);
mintemporalrestriction_textfield.setEnabled(false);
temporalrestriction_textfield.setEnabled(true);
maxtemporalrestriction_textfield.setText("");
mintemporalrestriction_textfield.setText("");
}
}
});
temporalrestriction_textfield = new JTextField();
temporalrestriction_textfield.setColumns(10);
temporalrestriction_textfield.setEnabled(false);
GridBagConstraints gbc_temporalrestriction_textfield = new GridBagConstraints();
gbc_temporalrestriction_textfield.insets = new Insets(0, 0, 5, 5);
gbc_temporalrestriction_textfield.gridx = 2;
gbc_temporalrestriction_textfield.gridy = 2;
parent.add(temporalrestriction_textfield, gbc_temporalrestriction_textfield);
temporaloperator_label = new JLabel("Temporal Operator:");
GridBagConstraints gbc_temporaloperator_label = new GridBagConstraints();
gbc_temporaloperator_label.anchor = GridBagConstraints.EAST;
gbc_temporaloperator_label.gridwidth = 2;
gbc_temporaloperator_label.insets = new Insets(0, 0, 5, 5);
gbc_temporaloperator_label.gridx = 0;
gbc_temporaloperator_label.gridy = 3;
parent.add(temporaloperator_label, gbc_temporaloperator_label);
temporaloperator_combobox = new JComboBox();
temporaloperator_combobox.addItem("-");
for (OWLNamedIndividual individual : getTemporalOperator()) {
temporaloperator_combobox.addItem(individual.getIRI().getFragment());
}
temporaloperator_combobox.setSelectedIndex(0);
GridBagConstraints gbc_temporaloperator_combobox = new GridBagConstraints();
gbc_temporaloperator_combobox.anchor = GridBagConstraints.NORTH;
gbc_temporaloperator_combobox.fill = GridBagConstraints.HORIZONTAL;
gbc_temporaloperator_combobox.insets = new Insets(0, 0, 5, 5);
gbc_temporaloperator_combobox.gridx = 2;
gbc_temporaloperator_combobox.gridy = 3;
parent.add(temporaloperator_combobox, gbc_temporaloperator_combobox);
temporalunit_label = new JLabel("Temporal Unit:");
GridBagConstraints gbc_temporalunit_label = new GridBagConstraints();
gbc_temporalunit_label.anchor = GridBagConstraints.EAST;
gbc_temporalunit_label.gridwidth = 2;
gbc_temporalunit_label.insets = new Insets(0, 0, 5, 5);
gbc_temporalunit_label.gridx = 0;
gbc_temporalunit_label.gridy = 4;
parent.add(temporalunit_label, gbc_temporalunit_label);
temporalunit_combobox = new JComboBox();
temporalunit_combobox.addItem("-");
for (OWLNamedIndividual individual : getTemporalUnit()) {
temporalunit_combobox.addItem(individual.getIRI().getFragment());
}
temporalunit_combobox.setSelectedIndex(0);
GridBagConstraints gbc_temporalunit_combobox = new GridBagConstraints();
gbc_temporalunit_combobox.insets = new Insets(0, 0, 5, 5);
gbc_temporalunit_combobox.fill = GridBagConstraints.HORIZONTAL;
gbc_temporalunit_combobox.gridx = 2;
gbc_temporalunit_combobox.gridy = 4;
parent.add(temporalunit_combobox, gbc_temporalunit_combobox);
}
public Object getBackPanelDescriptor() {
return EditConditionPage1.ID;
}
public Object getNextPanelDescriptor() {
return WizardPanel.FINISH;
}
@Override
public void aboutToDisplayPanel() {
if (type == 0) {
temporalrestriction_type = 0;
maxmintemporalrestriction_ratiobutton.setSelected(true);
temporalrestriction_ratiobutton.setSelected(false);
maxtemporalrestriction_textfield.setEnabled(true);
mintemporalrestriction_textfield.setEnabled(true);
temporalrestriction_textfield.setEnabled(false);
maxtemporalrestriction_textfield.setText(this.maxtemporalrestrictionvalue);
mintemporalrestriction_textfield.setText(this.mintemporalrestrictionvalue);
} else if (type == 1) {
temporalrestriction_type = 1;
maxmintemporalrestriction_ratiobutton.setSelected(false);
temporalrestriction_ratiobutton.setSelected(true);
maxtemporalrestriction_textfield.setEnabled(false);
mintemporalrestriction_textfield.setEnabled(false);
temporalrestriction_textfield.setEnabled(true);
temporalrestriction_textfield.setText(this.temporalrestrictionvalue);
}
if (!(this.temporaloperator.isEmpty())) {
temporaloperator_combobox.setSelectedItem(this.temporaloperator);
}
if (!(this.temporalunit.isEmpty())) {
temporalunit_combobox.setSelectedItem(this.temporalunit);
}
// TODO Auto-generated method stub
super.aboutToDisplayPanel();
}
public Set<OWLNamedIndividual> getTemporalOperator() {
Set<OWLIndividual> specialities = new HashSet<OWLIndividual>();
Set<OWLNamedIndividual> clinicalspecialities = new HashSet<OWLNamedIndividual>();
OWLOntology ontology = getOWLModelManager().getActiveOntology();
OWLClass cs = getOWLModelManager().getOWLDataFactory().getOWLClass(IRI.create(
getOWLModelManager().getActiveOntology().getOntologyID().getOntologyIRI() + "#TemporalOperator"));
specialities = cs.getIndividuals(ontology);
for (OWLIndividual a : specialities) {
clinicalspecialities.add(a.asOWLNamedIndividual());
}
return clinicalspecialities;
}
public Set<OWLNamedIndividual> getTemporalUnit() {
Set<OWLIndividual> specialities = new HashSet<OWLIndividual>();
Set<OWLNamedIndividual> clinicalspecialities = new HashSet<OWLNamedIndividual>();
OWLOntology ontology = getOWLModelManager().getActiveOntology();
OWLClass cs = getOWLModelManager().getOWLDataFactory().getOWLClass(IRI
.create(getOWLModelManager().getActiveOntology().getOntologyID().getOntologyIRI() + "#TemporalUnit"));
specialities = cs.getIndividuals(ontology);
for (OWLIndividual a : specialities) {
clinicalspecialities.add(a.asOWLNamedIndividual());
}
return clinicalspecialities;
}
public void getCondition_data(String condition_individual_name) {
OWLNamedIndividual condition_individual = getOWLModelManager().getOWLDataFactory().getOWLNamedIndividual(
IRI.create(getOWLModelManager().getActiveOntology().getOntologyID().getOntologyIRI() + "#"
+ condition_individual_name));
// Get Object Property of Temporal Restriction
OWLObjectProperty temporalrestriction_objectexpression = getOWLModelManager().getOWLDataFactory()
.getOWLObjectProperty(
IRI.create(getOWLModelManager().getActiveOntology().getOntologyID().getOntologyIRI()
+ "#hasTemporalRestriction"));
try {
OWLNamedIndividual temporalrestriction_individual = condition_individual
.getObjectPropertyValues(temporalrestriction_objectexpression,
getOWLModelManager().getActiveOntology())
.iterator().next().asOWLNamedIndividual();
Map<OWLDataPropertyExpression, Set<OWLLiteral>> data = temporalrestriction_individual
.getDataPropertyValues(getOWLModelManager().getActiveOntology());
for (Map.Entry<OWLDataPropertyExpression, Set<OWLLiteral>> entry : data.entrySet()) {
try {
if (entry.getKey().asOWLDataProperty().getIRI().getFragment()
.equals("maxTemporalRestrictionValue")) {
this.maxtemporalrestrictionvalue = entry.getValue().iterator().next().getLiteral();
this.type = 0;
} else if (entry.getKey().asOWLDataProperty().getIRI().getFragment()
.equals("minTemporalRestrictionValue")) {
this.mintemporalrestrictionvalue = entry.getValue().iterator().next().getLiteral();
this.type = 0;
} else if (entry.getKey().asOWLDataProperty().getIRI().getFragment()
.equals("temporalRestrictionValue")) {
this.temporalrestrictionvalue = entry.getValue().iterator().next().getLiteral();
this.type = 1;
}
} catch (Exception e) {
}
}
// Get Object Property of TemporalOperator
OWLObjectProperty hasTemporalOperator_objectproperty = getOWLModelManager().getOWLDataFactory()
.getOWLObjectProperty(
IRI.create(getOWLModelManager().getActiveOntology().getOntologyID().getOntologyIRI()
+ "#hasTemporalOperator"));
try {
OWLNamedIndividual temporaloperator_individual = temporalrestriction_individual
.getObjectPropertyValues(hasTemporalOperator_objectproperty,
getOWLModelManager().getActiveOntology())
.iterator().next().asOWLNamedIndividual();
this.temporaloperator = temporaloperator_individual.getIRI().getFragment();
} catch (Exception e) {
}
// Get Object Property of TemporalUnit
OWLObjectProperty hasTemporalUnit_objectproperty = getOWLModelManager().getOWLDataFactory()
.getOWLObjectProperty(
IRI.create(getOWLModelManager().getActiveOntology().getOntologyID().getOntologyIRI()
+ "#hasTemporalUnit"));
try {
OWLNamedIndividual temporalunit_individual = temporalrestriction_individual
.getObjectPropertyValues(hasTemporalUnit_objectproperty,
getOWLModelManager().getActiveOntology())
.iterator().next().asOWLNamedIndividual();
this.temporalunit = temporalunit_individual.getIRI().getFragment();
} catch (Exception e) {
}
} catch (Exception e) {
}
}
}
| [
"fgoncalves@algoritmi.uminho.pt"
] | fgoncalves@algoritmi.uminho.pt |
fb74966388e77cd9eea5d74ec28451dfea99f5a2 | d5ba9d7a4c6b2d0edcb030da9fe34ba2408feaa4 | /src/main/java/com/seckill/dto/SeckillExecution.java | 839b1243b522c27196fa9690e8868919e4be0d0c | [] | no_license | wehappy888/seckill-web | 2ef09e090a699df8a00bbde300299d2cce4e9c14 | e4e83fe9e586077efdfb8d1deccc4accd8e9e1c0 | refs/heads/master | 2021-10-01T18:14:42.323321 | 2018-11-28T06:29:03 | 2018-11-28T06:29:03 | 109,719,660 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,918 | java | package com.seckill.dto;
import com.seckill.entity.SuccessKilled;
import com.seckill.enums.SeckillStatEnum;
/**
* Created by waynewang on 2017/11/3.
*/
public class SeckillExecution {
private long seckillId;
//秒杀执行结果的状态
private int state;
//状态的明文标识
private String stateInfo;
//当秒杀成功时,需要传递秒杀成功的对象回去
private SuccessKilled successKilled;
//秒杀成功返回所有信息
public SeckillExecution(long seckillId, SeckillStatEnum statEnum, SuccessKilled successKilled) {
this.seckillId = seckillId;
this.state = statEnum.getState();
this.stateInfo = statEnum.getInfo();
this.successKilled = successKilled;
}
//秒杀失败
public SeckillExecution(long seckillId, SeckillStatEnum statEnum) {
this.seckillId = seckillId;
this.state = statEnum.getState();
this.stateInfo = statEnum.getInfo();
}
public long getSeckillId() {
return seckillId;
}
public void setSeckillId(long seckillId) {
this.seckillId = seckillId;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getStateInfo() {
return stateInfo;
}
public void setStateInfo(String stateInfo) {
this.stateInfo = stateInfo;
}
public SuccessKilled getSuccessKilled() {
return successKilled;
}
public void setSuccessKilled(SuccessKilled successKilled) {
this.successKilled = successKilled;
}
@Override
public String toString() {
return "SeckillExecution{" +
"seckillId=" + seckillId +
", state=" + state +
", stateInfo='" + stateInfo + '\'' +
", successKilled=" + successKilled +
'}';
}
}
| [
"waynewang@WaynedeMacBook-Air.local"
] | waynewang@WaynedeMacBook-Air.local |
a22eec3748b5eca8b4fa0c856d9faec08bb7f0be | 3e655b1a412a205bf0c6fc4a89cc477d64cd61f3 | /mantis-tests/src/test/java/ru/stqa/pft/mantis/tests/ResetPasswordTests.java | e4b149d3c9673caddd3f4330f0f3a669acd01a3d | [
"Apache-2.0"
] | permissive | ElenaBitneva/java_training | ae5a27a4f14cfdfd1ce4413ec6ee5f8acfa2a490 | 68a2ac9456febaf35b9e3a27c72ca2f8fce6a15a | refs/heads/master | 2021-04-26T23:24:42.376658 | 2018-05-10T21:53:06 | 2018-05-10T21:53:06 | 123,990,224 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,979 | java | package ru.stqa.pft.mantis.tests;
import org.openqa.selenium.By;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.lanwen.verbalregex.VerbalExpression;
import ru.stqa.pft.mantis.appmanager.HttpSession;
import ru.stqa.pft.mantis.model.MailMessage;
import ru.stqa.pft.mantis.model.UserData;
import javax.mail.MessagingException;
import java.io.IOException;
import java.util.List;
import static org.testng.Assert.assertTrue;
/**
* Created by elina_000 on 09.05.2018.
*/
public class ResetPasswordTests extends TestBase{
@BeforeMethod
public void ensurePreconditions() {
app.mail().start();
}
@Test
public void testResetPassword() throws IOException, MessagingException {
HttpSession session = app.newSession();
app.signIn().login(new UserData().withUsername("administrator").withPassword("root"));
UserData testUser = new UserData().withUsername("test").withEmail("test@localhost.localdomain")
.withPassword("root1");
app.signIn().resetPassword(testUser);
List<MailMessage> messages = app.mail().waitForMail(1, 20000);
String confirmationLink = findConfirmationLink(messages, testUser.getEmail());
app.signIn().resetPasswordByConfirmationLink(testUser, confirmationLink);
assertTrue(session.login(testUser.getUsername(),testUser.getPassword()));
assertTrue(session.isLoggedInAs(testUser.getUsername()));
}
private String findConfirmationLink(List<MailMessage>mailMessages,String email){
MailMessage mailMessage = mailMessages.stream().filter((m) -> m.to.equals(email)).findFirst().get();
VerbalExpression regex = VerbalExpression.regex().find("http://").nonSpace().oneOrMore().build();
return regex.getText(mailMessage.text);
}
@AfterMethod(alwaysRun = true)
public void ensureAfterconditions(){
app.mail().stop();
}
}
| [
"elina_336@mail.ru"
] | elina_336@mail.ru |
4e81cd7fd3885d83a74e58bc37ca3395aa778b25 | 23b2845da31fadb72d6d0e8e22c6f47cecc5424f | /domain/src/main/java/com/chat/domain/Participant.java | 416a95df4f2ed070153dd6eea70f422f88146dd5 | [] | no_license | firecat8/chat | 0fd71f8c37d6aac3478f5ef0b7d9e42f12bbbf28 | 1d81954c978bc2860ba7e23cb40b81a39572cbf1 | refs/heads/master | 2022-12-12T08:32:10.105227 | 2020-01-14T18:26:14 | 2020-01-14T18:26:14 | 212,306,505 | 0 | 1 | null | 2022-11-24T09:43:09 | 2019-10-02T10:00:57 | Java | UTF-8 | Java | false | false | 907 | java | package com.chat.domain;
/**
*
* @author gdimitrova
*/
public class Participant extends Entity {
private User user;
private ChatUser userType;
private Chat chat;
public Participant() {
}
public Participant(User user, ChatUser userType) {
this.user = user;
this.userType = userType;
}
public Participant(User user, ChatUser userType, Chat chat) {
this.user = user;
this.userType = userType;
this.chat = chat;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public ChatUser getUserType() {
return userType;
}
public void setUserType(ChatUser userType) {
this.userType = userType;
}
public Chat getChat() {
return chat;
}
public void setChat(Chat chat) {
this.chat = chat;
}
}
| [
"geriii1993@gmail.com"
] | geriii1993@gmail.com |
0ec6789707edde44beb6e8a671ab08bf31c0af91 | b0e782b7d0beb312773dc7d9838d8f48cccb393a | /src/com/mpdeimos/tensation/editpart/GenericTensorEditPart.java | 9646517ba53a00bf416c8fa228218e1880789c02 | [] | no_license | mpdeimos/tensation | ee6cf99f796c452165b48c31cb6f56d3d232c87e | 943bb1128be3d1af87a2651bc364dae0ca532767 | refs/heads/master | 2022-06-16T01:41:03.232680 | 2013-03-01T06:19:39 | 2013-03-01T06:19:39 | 261,000,031 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 518 | java | package com.mpdeimos.tensation.editpart;
import com.mpdeimos.tensation.figure.IFigure;
import com.mpdeimos.tensation.figure.TensorFigure;
import com.mpdeimos.tensation.model.IModelData;
/**
* EditPart representing a generic tensor.
*
* @author mpdeimos
*
*/
public class GenericTensorEditPart extends TensorEditPartBase
{
/** Constructor. */
public GenericTensorEditPart(IModelData modelData)
{
super(modelData);
}
@Override
protected IFigure createFigure()
{
return new TensorFigure(this);
}
}
| [
"martin.deimos@gmx.de"
] | martin.deimos@gmx.de |
4d0695e83ea8249f0eef63ab4a4e04d32a76947f | 178b0c1b77502943cea09db92ac3c5e6022bfbed | /app/src/test/java/com/zyh/basedemo/ExampleUnitTest.java | 037732cc98ca54890e130663e90583488b803a9d | [] | no_license | Founder005/ToolLib | 901ec6f562136643da7ded189e5cd8d99addfbcc | bd5a9d634d0fc0858df4f815cffdf44c859ba7f1 | refs/heads/master | 2020-11-25T06:39:15.464628 | 2019-12-17T06:02:08 | 2019-12-17T06:02:08 | 228,542,770 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 377 | java | package com.zyh.basedemo;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"zyh123"
] | zyh123 |
316b513be2c9baa745f09eb41c2aa59493f9825f | 0ff130ca46f9cf5d72bac001086f5150620ba0fa | /backend/src/main/java/com/project/model/user/FavorEntity.java | 78c243205cb85fb1adcf632e291c8a46bd5ef3e6 | [] | no_license | sorachin/AppleMango | 4825b885162b7f677a0d035f836797c9416e0976 | c9bded836d5521ddb9592886f602e707d7320972 | refs/heads/master | 2023-02-20T21:31:12.780577 | 2021-01-26T12:11:40 | 2021-01-26T12:11:40 | 333,072,261 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,211 | java | package com.project.model.user;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.project.model.restaurant.RestaurantEntity;
import lombok.*;
@Getter
@Setter
@ToString
//@NoArgsConstructor
@Entity
@Table(name = "userfavor")
public class FavorEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "fid")
private int fid;
@Column(name = "uid")
private String uid;
@Column(name = "frid")
private long frid;
// @OneToOne
// @JoinTable(name = "ffff", //조인테이블명
// joinColumns = @JoinColumn(name = "rid"), // 외래키
// inverseJoinColumns = @JoinColumn(name="frid") //반대 엔티티의 외래키
// )
// private Restaurant restaurant;
@OneToOne
@JoinColumn(name = "frid",
insertable = false, updatable = false)
private RestaurantEntity restaurant;
} | [
"sorac725@gmail.com"
] | sorac725@gmail.com |
0d4bd3793f739ec183afde90283203e5af623c6d | 44c5488a816b5cbab47683d60b0bc10507ee6c49 | /app/src/main/java/me/recette/DataBaseHelper.java | d6b177510d89f9f3054df8b953f08b488ee88acf | [] | no_license | ykaaouachi/Recipes | 8e9ee6554a854a0752b37b388b868fe382646a89 | 2f4dab54da3ff88ed11633c65f153959090d3bee | refs/heads/master | 2020-01-23T21:44:39.168927 | 2016-11-24T13:42:30 | 2016-11-24T13:42:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,365 | java | package me.recette;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* Created by Me on 21/10/2016.
*/
public class DataBaseHelper extends SQLiteOpenHelper {
//The Android's default system path the App.
private static String DB_PATH = "/data/data/me.recette/databases/";
private static String DB_NAME = "test";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty test on the system and rewrites it with your own test.
* */
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - Database already exists could be needed in future
}else{
//By calling this method and empty test will be created into the default system path
//of your application so we are gonna be able to overwrite that test with our test.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
//throw new Error("Error copying test");
}
}
this.close();
}
/**
* Check if the test already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
public boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//test does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null;
}
/**
* Copies your test from your local assets-folder to the just created empty test in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
//Open the test
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
public ArrayList<FullRecipe> getAllRecipes(){
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "select _id, name, ingredients, preparation, time, cost, difficulty, image, author, aimer from recipes";
ArrayList recipes = new ArrayList();
final Cursor cursor;
try{
cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
while(!cursor.isAfterLast()) {
FullRecipe recipe = new FullRecipe(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3),
cursor.getInt(4), cursor.getInt(5), cursor.getInt(6), cursor.getString(7), cursor.getString(8), cursor.getInt(9) != 0);
recipes.add(recipe);
cursor.moveToNext();
}
}
} finally {
cursor.close();
}
}
}
catch (SQLiteException e){
return recipes;
}
db.close();
return recipes;
}
public boolean updateRecipe(FullRecipe fullRecipe){
SQLiteDatabase db = this.getWritableDatabase();
SQLiteStatement stmt = db.compileStatement("UPDATE recipes set name = ?, ingredients = ?, preparation = ?, time = ?, cost = ?, difficulty = ?," +
" image = ?, author = ?, AIMER = ? where _id = ?");
if(fullRecipe.getName()!=null) stmt.bindString(1, fullRecipe.getName());
if(fullRecipe.getIngredients()!=null) stmt.bindString(2, fullRecipe.getIngredients());
if(fullRecipe.getPreparation()!=null) stmt.bindString(3, fullRecipe.getPreparation());
if(fullRecipe.getTime()!=0) stmt.bindString(4, String.valueOf(fullRecipe.getTime()));
if(fullRecipe.getCost()!=0) stmt.bindString(5, String.valueOf(fullRecipe.getCost()));
if(fullRecipe.getDifficulty()!=0) stmt.bindString(6, String.valueOf(fullRecipe.getDifficulty()));
if(fullRecipe.getImage()!=null) stmt.bindString(7, fullRecipe.getImage());
if(fullRecipe.getAuthor()!=null) stmt.bindString(8, fullRecipe.getAuthor());
stmt.bindString(9, String.valueOf(fullRecipe.getAimer()? 1 : 0));
stmt.bindString(10, String.valueOf(fullRecipe.getId()));
stmt.execute();
db.close();
return true;
}
//Insert new recipe in DB
public boolean insertRecipe(FullRecipe fullRecipe){
SQLiteDatabase db = this.getWritableDatabase();
SQLiteStatement stmt = db.compileStatement("INSERT INTO recipes (name, ingredients, preparation, time, cost, difficulty, image, author) VALUES " +
"(?, ?, ?, ?, ?, ?, ?, ?)");
if(fullRecipe.getName()!=null) stmt.bindString(1, fullRecipe.getName());
if(fullRecipe.getIngredients()!=null) stmt.bindString(2, fullRecipe.getIngredients());
if(fullRecipe.getPreparation()!=null) stmt.bindString(3, fullRecipe.getPreparation());
if(fullRecipe.getTime()!=0) stmt.bindString(4, String.valueOf(fullRecipe.getTime()));
if(fullRecipe.getCost()!=0) stmt.bindString(5, String.valueOf(fullRecipe.getCost()));
if(fullRecipe.getDifficulty()!=0) stmt.bindString(6, String.valueOf(fullRecipe.getDifficulty()));
if(fullRecipe.getImage()!=null) stmt.bindString(7, fullRecipe.getImage());
if(fullRecipe.getAuthor()!=null) stmt.bindString(8, fullRecipe.getAuthor());
stmt.execute();
db.close();
return true;
}
//Delete recipe from DB by ID
public boolean deleteRecipe(int id){
SQLiteDatabase db = this.getWritableDatabase();
/*String query = "INSERT INTO recipes (name, ingredients, preparation, time, cost, difficulty, image, author)" +
" VALUES ("+fullRecipe.getName()+","+fullRecipe.getIngredients()+","+fullRecipe.getPreparation()+","
+fullRecipe.getTime()+","+fullRecipe.getCost()+","+fullRecipe.getDifficulty()+","
+fullRecipe.getImage()+","+fullRecipe.getAuthor()+","+") where _id = '"+fullRecipe.getId()+"'";
db.execSQL(query);*/
SQLiteStatement stmt = db.compileStatement("delete from recipes where _id=?");
if (id !=0) stmt.bindString(1, String.valueOf(id));
stmt.execute();
db.close();
return true;
}
//Retrieve recipe by ID
public FullRecipe getRecipeById(String id){
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "select _id, name, ingredients, preparation, time, cost, difficulty, image, author, aimer from recipes where _id = '"+id+"'";
FullRecipe fullRecipe = null;
final Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
fullRecipe = new FullRecipe(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3),
cursor.getInt(4), cursor.getInt(5), cursor.getInt(6), cursor.getString(7), cursor.getString(8), cursor.getInt(9) != 0);
cursor.moveToNext();
}
} finally {
cursor.close();
}
}
db.close();
return fullRecipe;
}
@Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
} | [
"chmourihoussam@gmail.com"
] | chmourihoussam@gmail.com |
5664718c8ae910f44e9fe8371f50c6509455f40b | ec143dcb88c954b2a50173f8d143df1f5565957f | /src/com/example/bus_ui_demo/aty_SWP_Circle.java | 7708be43b010a88e04e53265d019d54275311991 | [] | no_license | sheep3652014/bus_ui | b91bacc84626eea0384eb06c0afe34dcec66864d | 37077b6ae47fa581891c38d97b9fd61994d273f4 | refs/heads/master | 2021-01-22T17:22:35.422251 | 2015-09-18T05:42:55 | 2015-09-18T05:42:55 | 39,371,015 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 13,603 | java | package com.example.bus_ui_demo;
import com.example.Alert.myAlert;
import com.example.Alert.myAlert.ShowTwoClickDialog_Interface;
import com.example.application.myApplication;
import com.example.config.Global_Config;
import com.example.database.ChargeHolder;
import com.example.database.CustomTypeException;
import com.example.database.DbManager;
import com.example.database.DbOpenHelper_charge;
import com.example.network.Service_DealCloseReport;
import com.example.network.Service_DealCloseReport.myBinder;
import com.example.network.protocol;
import com.example.nfc.Util;
import com.tybus.swp.UICC_swp;
import com.tybus.swp.UICC_swp.UICC_Interface;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Window;
import android.widget.FrameLayout;
public class aty_SWP_Circle extends FragmentActivity
{
// 805000020B01+czje+12345678 //cmd + 金额 + 终端号
// czje是8位16进制数字,分结尾。充1分钱,是00000001,充1元钱是0000000A
private static final String CIRCLE_INIT = Global_Config.CIRCLE_INIT;
private static final int CONNECT_ERROR = Global_Config.CONNECT_ERROR;
private static final String MONEY_CMD = Global_Config.MONEY_CMD; //读余额
private static final int RESTART_CIRCLE = Global_Config.INNER_MSG_START + 1;
private static final int CIRCLE_COMPELETE = Global_Config.INNER_MSG_START + 2;
private static final String TAG = "aty_SWP_Circle";
private ServiceConnection serconn = null;
private static final String FRG_WAIT_CALL_FROM = Global_Config.FRG_WAIT_CALL_FROM;
private static final String FRG_WAIT_CALL_FROM_SWP = Global_Config.FRG_WAIT_CALL_FROM_SWP;
private UICC_swp m_swp = null;
private FrameLayout frame_notice;
private FragmentManager fm = null;
private FragmentTransaction transaction = null;
private frg_SWP_CircleWait circleWait = null;
private myApplication myApp = null;
private Thread mThread;
final Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
// TODO Auto-generated method stub
// super.handleMessage(msg);
switch (msg.what)
{
case CONNECT_ERROR:
myAlert.ShowToast(aty_SWP_Circle.this, getString(R.string.network_error));
break;
case RESTART_CIRCLE:
//关闭资源,重新发起圈存过程
m_swp.UICCClose();
InitSWP(mHandler);
break;
case CIRCLE_COMPELETE:
//启用服务发送完成报告
BindSerive(aty_SWP_Circle.this);
//添加圈存完成界面
AddCircleCompelete();
break;
default:
break;
}
}
};
/**
* 绑定圈存完成上报服务
* @param context
*/
private void BindSerive(Context context)
{
serconn = new ServiceConnection()
{
@Override
public void onServiceDisconnected(ComponentName name)
{
// TODO Auto-generated method stub
System.out.println("disconnect");
}
@Override
public void onServiceConnected(ComponentName name, IBinder service)
{
// TODO Auto-generated method stub
System.out.println("connect");
Service_DealCloseReport mService = ((myBinder)service).getService();
}
};
Intent intent = new Intent(context, Service_DealCloseReport.class);
bindService(intent, serconn, Context.BIND_AUTO_CREATE);
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.aty_swp_circle_layout);
fm = getSupportFragmentManager();
transaction = fm.beginTransaction();
myApp = (myApplication) getApplicationContext();
FindView();
InitView();
InitSWP(mHandler);
}
private void InitSWP(final Handler mHandler)
{
m_swp = new UICC_swp(aty_SWP_Circle.this, new UICC_Interface()
{
@Override
public void UICCTranSomeCmd()
{
Runnable mRunnable = new Runnable()
{
@Override
public void run()
{
System.out.println("here");
Looper.prepare();
// 圈存初始化
String CircleInitmsg = CircleInit(m_swp, myApp);
myApp.setCircleInitMsg(CircleInitmsg);
// 请求圈存指令
String ack = RequestCircle(aty_SWP_Circle.this, myApp, mHandler);
if(null != ack)
{
String TAC = Circle(m_swp, myApp, ack, mHandler);
if(null != TAC)
{
//更新订单状态
UpdateCircleStatus(myApp.getOrderSeq(), true, TAC);
//保存TAC
myApp.setTAC_CARD(TAC);
//发送msg,
//圈存,更新状态,发送圈存完成报告
//ui线程中加入圈存成功提示
Message msg = mHandler.obtainMessage();
msg.what = CIRCLE_COMPELETE;
mHandler.sendMessage(msg);
}
}
Looper.loop();
}
};
mThread = new Thread(mRunnable);
//mThread.start();
try
{
Thread.sleep(1*1000);
mThread.start();
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("sleep error " + e.getMessage());
}
}
});
if (m_swp.UICCInit())
{
System.out.println("uicc init ok");
}
}
private void FindView()
{
frame_notice = (FrameLayout) findViewById(R.id.frame_notice);
}
/**
* 加入圈存提醒等待
*/
private void InitView()
{
// transaction.replace(R.id.frame_notice, new frg_SWP_CircleWait());
// transaction.commit();
// FragmentTransaction transaction =
// getSupportFragmentManager().beginTransaction();
circleWait = new frg_SWP_CircleWait();
Bundle args = new Bundle();
args.putString(FRG_WAIT_CALL_FROM, FRG_WAIT_CALL_FROM_SWP);
circleWait.setArguments(args);
circleWait.show(transaction, "swp_circle_notice");
}
@Override
protected void onDestroy()
{
// TODO Auto-generated method stub
// 关闭相关资源
if (null != m_swp)
m_swp.UICCClose();
else
{
System.out.println("is null");
}
if(null != serconn)
{
unbindService(serconn);
}
super.onDestroy();
}
/**
* 添加圈存完成后界面
*/
private void AddCircleCompelete()
{
// transaction.remove(circleWait);
circleWait.dismiss();
FragmentTransaction transaction2 = getSupportFragmentManager()
.beginTransaction();
transaction2.replace(R.id.frame_notice,
new frg_NFC_bigCard_CircleComplete_notice());
transaction2.commit();
}
/**
* 圈存初始化
*
* @param m_swp
* @param myApp
* @return
*/
private String CircleInit(UICC_swp m_swp, myApplication myApp)
{
// 805000020B01+czje+12345678 //cmd + 金额 + 终端号
// czje是8位16进制数字,分结尾。充1分钱,是00000001,充1元钱是0000000A
String m = Integer.toHexString(myApp.getChargeMoney());
String money = Util.to8String(m);
String cmd = CIRCLE_INIT + money + myApp.getTerminalCode();
String ack = m_swp.UICC_TRANS(cmd);
if (null == ack)
{
myAlert.ShowToast(aty_SWP_Circle.this,
getString(R.string.swp_circle_init_fail));
BackHomeActivity(aty_SWP_Circle.this);
}
return ack;
}
/**
* 申请圈存指令
* 成功返回圈存指令,否则null
* @param context
* @param myApp
* @param mHandler
*/
private String RequestCircle(Context context, myApplication myApp, final Handler mHandler)
{
String cmd = protocol.RequestCircle(context, myApp, mHandler);
if(null != cmd)
{
return cmd;
}
else
{
myAlert.ShowTwoClickDialog(aty_SWP_Circle.this, getString(R.string.swp_requestcircle_fail_notice),
getString(R.string.swp_circle_cancel), getString(R.string.swp_circle_retry),
new ShowTwoClickDialog_Interface()
{
@Override
public void DoPositive()
{
//再次发送圈存请求
//关闭资源
Message msg = mHandler.obtainMessage();
msg.what = RESTART_CIRCLE;
mHandler.sendMessage(msg);
}
@Override
public void DoNegative()
{
//放弃圈存,返回主界面,给出退款提示
myAlert.ShowToast(aty_SWP_Circle.this, getString(R.string.circle_fail_notice));
BackHomeActivity(aty_SWP_Circle.this);
}
});
}
return null;
}
/**
* 圈存,成功返回TAC,失败返回null
* @param m_swp
* @param myApplication
* @param cmd
* @return
*/
private String Circle(UICC_swp m_swp, myApplication myApp, String cmd, final Handler mHandler)
{
//读取圈存前金额
String before = m_swp.UICC_TRANS(MONEY_CMD);
//圈存
String TAC = m_swp.UICC_TRANS(cmd);
if(null != TAC)
{
//比对充值前后金额,确认是否充值成功
//成功显示充值圈存完成窗口,并尝试方式交易完成报告
//读圈存后金额
String after = m_swp.UICC_TRANS(MONEY_CMD);
//比对精确判断是否圈存成功
int before_money = Integer.parseInt(before, 16);
int after_money = Integer.parseInt(after,16);
int charge_money = myApp.getChargeMoney();
if(charge_money == (after_money - before_money))
{//成功
myApp.setBeforeChargeMoney(before_money);
myApp.setAfterChargeMoney(after_money);
//保存小卡余额
myApp.setSwp_balance(after_money);
return TAC;
}
else {
//失败,给出提示
//重试或取消
myAlert.ShowTwoClickDialog(aty_SWP_Circle.this, getString(R.string.swp_circle_fail),
getString(R.string.swp_circle_cancel), getString(R.string.swp_circle_retry),
new ShowTwoClickDialog_Interface()
{
@Override
public void DoPositive()
{
//再次发送圈存请求
//关闭资源
Message msg = mHandler.obtainMessage();
msg.what = RESTART_CIRCLE;
mHandler.sendMessage(msg);
}
@Override
public void DoNegative()
{
//放弃圈存,返回主界面,给出退款提示
myAlert.ShowToast(aty_SWP_Circle.this, getString(R.string.circle_fail_notice));
BackHomeActivity(aty_SWP_Circle.this);
}
});
return null;
}
}
return null;
}
/**
* 更新圈存状态
* @param OrderSeq 订单流水号
* @param CircleStatus true:圈存成功 false:圈存失败
* @param tac 圈存成功应答TAC
*/
private void UpdateCircleStatus(String OrderSeq, boolean CircleStatus, String tac)
{
String OrderTime = "";
String Order_Seq = "";
String Order_Reqtranse = "";
String Order_Amount = "";
String Order_Publish_CardID = "";
String payMethod = "";
DbManager dm = new DbManager(this);
Cursor c = dm.QueryOrderbyReqTranse(OrderSeq);
c.moveToNext();
if (0 != c.getCount())// 数据库中存在该订单流水号的订单信息
{
OrderTime = c.getString(c
.getColumnIndex(DbOpenHelper_charge.ORDER_TIME));
Order_Seq = c.getString(c
.getColumnIndex(DbOpenHelper_charge.ORDER_SEQ));
Order_Reqtranse = c.getString(c
.getColumnIndex(DbOpenHelper_charge.ORDER_REQTRANSE));
Order_Amount = c.getString(c
.getColumnIndex(DbOpenHelper_charge.ORDER_AMOUNT));
Order_Publish_CardID = c.getString(c
.getColumnIndex(DbOpenHelper_charge.ORDER_PUBLISH_CARDID));
payMethod = c.getString(c
.getColumnIndex(DbOpenHelper_charge.PAYMETHOD));
int Charge_Status = c
.getInt(c
.getColumnIndex(DbOpenHelper_charge.ORDER_CHARGE_STATUS));
// int ChargeNFC_Status =
// c.getInt(c.getColumnIndex(DbOpenHelper_charge.ORDER_CHARGE_NFC_STATUS));
int TransferenceClose_Status = c
.getInt(c
.getColumnIndex(DbOpenHelper_charge.ORDER_TRANSFERENCE_CLOSE_STATUS));
int ChargeNFC_Status = 0;
if (CircleStatus)
{
ChargeNFC_Status = 1;
}
//如果充值状态不对,不允许更新圈存状态
if(ChargeHolder.TRUE_HERE!=Charge_Status)
{
c.close();
dm.closeDB();
return;
}
try
{
ChargeHolder ch = new ChargeHolder(OrderTime, Order_Seq,
Order_Reqtranse, Order_Amount, Order_Publish_CardID,
payMethod, Charge_Status, ChargeNFC_Status,
TransferenceClose_Status, tac);
dm.UpdateOrderbyReqTranse(ch);
} catch (CustomTypeException e)
{
Log.d(TAG, "更新状态出错,onActivityResult");
// 出错先关闭数据库资源
c.close();
dm.closeDB();
e.printStackTrace();
}
}
c.close();
dm.closeDB();
}
/**
* 返回首页面
*
* @param context
*/
private void BackHomeActivity(Context context)
{
Intent intent = new Intent(context, aty_main.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
((Activity) context).finish();
}
}
| [
"sheep3652003@tom.com"
] | sheep3652003@tom.com |
f94bc122d07a8cecd9f8f9029eae4f8ab072a59a | 83b885f3a351f61a482571136b577c15745d3dcc | /src/main/java/com/rubensmello/demo/specification/GenericSpec.java | 5e0ce17ecab76057ca6ae9f3702090eb404b34fb | [] | no_license | rubovisk/spring-boot-template | b6eb3b23e93e4d18b0b96956903261c2b649b87b | ac10c2977c2d135a1d114e3a2bfcc1971c928312 | refs/heads/master | 2022-12-26T13:07:12.998270 | 2020-09-28T22:07:12 | 2020-09-28T22:07:12 | 299,439,677 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 843 | java | package com.rubensmello.demo.specification;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
public class GenericSpec {
private GenericSpec() {}
public static Predicate literalIsNull(CriteriaBuilder cb, Object obj) {
// mantém como parâmetro para performar no banco,
// uma vez que a estrutura da query sempre será a mesma
return cb.equal(cb.nullLiteral(Object.class), obj);
}
private static String toLikeExp(String str) {
return str == null ? null : ("%" + str.toUpperCase() + "%");
}
public static Predicate like(CriteriaBuilder cb, Path<String> path, String like) {
return cb.or(literalIsNull(cb, like),
cb.like(cb.upper(path), toLikeExp(like))
);
}
}
| [
"rubens.mello@fcamara.com.br"
] | rubens.mello@fcamara.com.br |
135b106d7c44074e849768f411d9dc9daa886754 | 33dde579d15ff6cb3b9406ecec56c656ebe9c9de | /Batch/batch-complete-jpa/src/main/java/com/josue/eap/batch/complete/jpa/MyItemWriter.java | 3c97045da20cf3ed0876e1f08661af6a03f04bda | [] | no_license | joshgontijo/Java-EE | 460307f708b81a62818e1d2c530d60c482cc9b05 | 81d28b8c51e4a52c19d8658cde21f0aa4a440d9f | refs/heads/master | 2022-11-06T03:32:07.832562 | 2017-01-22T17:43:14 | 2017-01-22T17:43:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 759 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.josue.eap.batch.complete.jpa;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.batch.api.chunk.AbstractItemWriter;
import javax.inject.Named;
/**
*
* @author Josue
*/
@Named
public class MyItemWriter extends AbstractItemWriter {
private static final Logger LOG = Logger.getLogger(MyItemWriter.class.getName());
@Override
public void writeItems(List<Object> items) throws Exception {
LOG.log(Level.INFO, "Received, list size: {0}", items.size());
}
}
| [
"josue.eduardo206@gmail.com"
] | josue.eduardo206@gmail.com |
5692834baab54de569f74a1f875a030921067363 | 2cf731177a6e130fda94b8eab009bed3072b2f48 | /java_version_20/fireflow-fpdl20/src/main/java/org/fireflow/pdl/fpdl20/diagram/impl/TransitionShapeImpl.java | d421e5f50ef5357c96f25d88bb92b2de5161d759 | [] | no_license | TFMV/fireflow | 3cbaf58ce40d04509d5349928990fe8cffacc46d | 191762ef210fa6b0f326d507ebaeb6fd7d15ae56 | refs/heads/master | 2021-01-10T15:04:26.946562 | 2013-12-15T14:19:04 | 2013-12-15T14:19:04 | 44,412,974 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,374 | java | /**
* Copyright 2007-2010 非也
* All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License v3 as published by the Free Software
* Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with this library; if not, see http://www.gnu.org/licenses/lgpl.html.
*
*/
package org.fireflow.pdl.fpdl20.diagram.impl;
import org.fireflow.pdl.fpdl20.diagram.NodeShape;
import org.fireflow.pdl.fpdl20.diagram.TransitionShape;
import org.fireflow.pdl.fpdl20.diagram.ProcessNodeShape;
import org.fireflow.pdl.fpdl20.diagram.figure.impl.LineImpl;
import org.fireflow.pdl.fpdl20.diagram.figure.part.Label;
import org.fireflow.pdl.fpdl20.diagram.figure.part.LabelImpl;
/**
*
* @author 非也 nychen2000@163.com
* Fire Workflow 官方网站:www.firesoa.com 或者 www.fireflow.org
*
*/
public class TransitionShapeImpl extends AbsConnectorShapeImpl implements
TransitionShape {
public TransitionShapeImpl(String id){
super(id);
}
}
| [
"nychen2000@gmail.com"
] | nychen2000@gmail.com |
a45b5df864ddde57e898d1c691708251ee2ecefd | 4607c7bf825502204b9f26ef156f320aaf4d661e | /src/main/java/hello/hellospring/repository/JpaMemberRepository.java | bd09d48b864f6125d38f011c59a99db95a1f9620 | [] | no_license | shinseok95/Spring-Introduction-Study | 21cb5012173a3b3642e851686bfdcd7e93dc6757 | 1b4e4ee1409d2bcfba3dcdaff8a792d4a3389c9c | refs/heads/main | 2023-05-06T14:17:00.499342 | 2021-06-04T10:11:38 | 2021-06-04T10:11:38 | 373,079,823 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,088 | java | package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.Optional;
public class JpaMemberRepository implements MemberRepository{
private final EntityManager em;
public JpaMemberRepository(EntityManager em) {
this.em = em;
}
@Override
public Member save(Member member) {
em.persist(member);
return member;
}
@Override
public Optional<Member> findById(Long id) {
Member member = em.find(Member.class, id);
return Optional.ofNullable(member);
}
@Override
public Optional<Member> findByName(String name) {
List<Member> result = em.createQuery("select m from Member m where m.name = :name",Member.class)
.setParameter("name",name)
.getResultList();
return result.stream().findAny();
}
@Override
public List<Member> findAll() {
return em.createQuery("select m from Member m", Member.class)
.getResultList();
}
}
| [
"pjjpjj2002@naver.com"
] | pjjpjj2002@naver.com |
af3cdcbf521f02a21d040761cd969fadd8559dbf | f55410b801ca374fff0bf2bb0b2ad1a6cba0834d | /src/main/java/com/toy/springbatch/job/StepNextConditionalJobConfiguration.java | 305174941b3f2164aa7254d625289678a5489cdc | [] | no_license | joojimin/toy_springbatch | 8db00949cc974128d23624a2a76eff1f2a2ded5e | 21c2875fdfc88be4ff5089064367d8c11deccaf9 | refs/heads/master | 2023-08-31T09:38:35.045737 | 2021-10-23T06:22:02 | 2021-10-23T06:22:02 | 401,714,985 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,579 | java | package com.toy.springbatch.job;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Configuration
@RequiredArgsConstructor
public class StepNextConditionalJobConfiguration {
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
@Bean
public Job stepNextConditionalJob() {
return jobBuilderFactory.get("stepNextConditionalJob")
.start(conditionalJobStep1())
.on("FAILED") // conditionalJobStep1이 FAILED 일 경우
.to(conditionalJobStep3()) // step3으로 이동한다.
.on("*") // step3의 결과 관계 없이
.end() // step3으로 이동하면 Flow가 종료한다.
.from(conditionalJobStep1()) // step1로부터
.on("*") // FAILED 외에 모든 경우
.to(conditionalJobStep2()) // step2로 이동한다.
.next(conditionalJobStep3()) // step2가 정상 종료되면 step3으로 이동한다.
.on("*") // step3의 결과 관계 없이
.end() // step3으로 이동하면 Flow가 종료한다.
.end() // Job 종료
.build();
}
@Bean
public Step conditionalJobStep1() {
return stepBuilderFactory.get("step1")
.tasklet((contribution, chunkContext) -> {
log.info(">>>>> This is stepNextConditionalJob Step1");
/**
ExitStatus를 FAILED로 지정한다.
해당 status를 보고 flow가 진행된다.
**/
contribution.setExitStatus(ExitStatus.FAILED);
return RepeatStatus.FINISHED;
})
.build();
}
@Bean
public Step conditionalJobStep2() {
return stepBuilderFactory.get("conditionalJobStep2")
.tasklet((contribution, chunkContext) -> {
log.info(">>>>> This is stepNextConditionalJob Step2");
return RepeatStatus.FINISHED;
})
.build();
}
@Bean
public Step conditionalJobStep3() {
return stepBuilderFactory.get("conditionalJobStep3")
.tasklet((contribution, chunkContext) -> {
log.info(">>>>> This is stepNextConditionalJob Step3");
return RepeatStatus.FINISHED;
})
.build();
}
}
| [
"wnwlals22@naver.com"
] | wnwlals22@naver.com |
d3e699f4967077e1eb23574ae41baa3653b4e0ce | 4e6e06b1fa5fdd173d12df92ab24d12680394df2 | /src/main/java/com/epam/mentoringportal/rest/api/ApiOriginFilter.java | e83bc3c464ab09a459e737839a1c648440d08276 | [] | no_license | timnbv/mentoring | baa27984e9e7050bc9090b5cad5afb55d3b061c5 | 02bf579e8d9a1a345f255532645943ba63acc4d3 | refs/heads/master | 2021-01-21T06:30:45.970244 | 2017-03-01T19:55:52 | 2017-03-01T19:55:52 | 83,245,228 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 968 | java | package com.epam.mentoringportal.rest.api;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2017-02-25T18:51:55.918Z")
public class ApiOriginFilter implements javax.servlet.Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
} | [
"ryzhovtv@gmail.com"
] | ryzhovtv@gmail.com |
964eea1715fc76a27b76c256c2e5be6968652e25 | 265302da0a7cf8c2f06dd0f96970c75e29abc19b | /ar_webapp/src/main/java/org/kuali/kra/common/committee/service/impl/CommitteeNotificationServiceImpl.java | f01ea1e944e70788f242ecfd8b62ae3afe9cc08b | [
"Apache-2.0",
"ECL-2.0"
] | permissive | Ariah-Group/Research | ee7718eaf15b59f526fca6983947c8d6c0108ac4 | e593c68d44176dbbbcdb033c593a0f0d28527b71 | refs/heads/master | 2021-01-23T15:50:54.951284 | 2017-05-05T02:10:59 | 2017-05-05T02:10:59 | 26,879,351 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,011 | java | /*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kra.common.committee.service.impl;
import org.apache.commons.lang.StringUtils;
import org.kuali.kra.common.committee.bo.CommitteeScheduleBase;
import org.kuali.kra.common.committee.meeting.CommScheduleMinuteDocBase;
import org.kuali.kra.common.committee.meeting.ScheduleAgendaBase;
import org.kuali.kra.common.committee.notification.AgendaCreatedNotificationRenderer;
import org.kuali.kra.common.committee.notification.CommitteeNotificationContext;
import org.kuali.kra.common.committee.notification.MinutesCreatedNotificationRenderer;
import org.kuali.kra.common.committee.service.CommonCommitteeNotificationService;
import org.kuali.kra.common.notification.service.KcNotificationService;
import org.kuali.kra.infrastructure.Constants;
/**
*
* This class generates the notifications for committees.
*/
public class CommitteeNotificationServiceImpl implements CommonCommitteeNotificationService {
private String committeeNotificationType;
private KcNotificationService kcNotificationService;
public String getCommitteeNotificationType() {
return committeeNotificationType;
}
public void setCommitteeNotificationType(String committeeNotificationType) {
this.committeeNotificationType = committeeNotificationType;
}
/**
* This method generates Agenda Generated notifications for a committee.
* @throws Exception
*/
public void generateNotification(String notificationType, ScheduleAgendaBase agenda) {
if (StringUtils.equals(notificationType, Constants.COMMITTEE_AGENDA_NOTIFICATION)) {
CommitteeScheduleBase committeeSchedule = agenda.getCommitteeSchedule();
AgendaCreatedNotificationRenderer renderer = new AgendaCreatedNotificationRenderer(agenda, "action taken");
CommitteeNotificationContext context = new CommitteeNotificationContext(committeeSchedule,
notificationType, "Agenda Generated Notification", renderer);
kcNotificationService.sendNotification(context);
} else {
throw new IllegalArgumentException(committeeNotificationType);
}
}
/**
* This method generates Minutes Generated notifications for a committee.
* @throws Exception
*/
public void generateNotification(String notificationType, CommScheduleMinuteDocBase minuteDoc) {
if (StringUtils.equals(notificationType, Constants.COMMITTEE_MINUTES_NOTIFICATION)) {
CommitteeScheduleBase committeeSchedule = minuteDoc.getCommitteeSchedule();
MinutesCreatedNotificationRenderer renderer = new MinutesCreatedNotificationRenderer(minuteDoc, "action taken");
CommitteeNotificationContext context = new CommitteeNotificationContext(committeeSchedule,
notificationType, "Minutes Generated Notification", renderer);
kcNotificationService.sendNotification(context);
} else {
throw new IllegalArgumentException(committeeNotificationType);
}
}
/**
* Populated by Spring Beans.
* @param kcNotificationService
*/
public void setKcNotificationService(KcNotificationService kcNotificationService) {
this.kcNotificationService = kcNotificationService;
}
}
| [
"code@ariahgroup.org"
] | code@ariahgroup.org |
cfaf26ce7e4ca0f494f98ad00769525f9a9b34bd | 91df287bf706e86e3bb2b5effea0420543612a65 | /Composition/src/Main.java | ae1a8f0787454821c5aed231da87f44c2ddfb39d | [] | no_license | Odinasar/Java | e137989b9752c780337bf8fee8279785e4392e16 | 18a1a4126291a7de5e0074ad0f083079e298b17b | refs/heads/master | 2020-04-07T17:54:26.906626 | 2018-11-21T21:18:58 | 2018-11-21T21:18:58 | 158,588,668 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 221 | java |
public class Main {
public static void main(String[] args) {
Engine e1=new Engine();
//Honda h1=new Honda("Red",250,e1);
Honda h1=new Honda("Red",250,new Engine());
h1.CarInfo();
h1.startHonda();
}
}
| [
"xmakiavellix000@gmail.com"
] | xmakiavellix000@gmail.com |
1d68a6af28bb290e72f9d97d50240ddf871ecaa3 | 1824bb355386380cbf8e319645bfbaafe8d3520a | /src/Admin/SQLConnectionAdmin.java | 66b6adf62cf1cd43ba3f6c34e60bc130d112d2d3 | [] | no_license | mamun464/BloodDonor | 2c7e530ff5d93df60e3f0c1a123b80460636b204 | ca932064613afd845d703b853303d1401e675fae | refs/heads/main | 2023-06-16T21:42:15.553923 | 2021-06-29T06:07:18 | 2021-06-29T06:07:18 | 381,245,698 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 539 | java | package Admin;
import Log_In.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLConnectionAdmin {
Connection conn=null;
public static Connection DbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn =DriverManager.getConnection("jdbc:sqlite:AdminData.sqlite");
return conn;
}
catch (ClassNotFoundException | SQLException e) {
System.out.println(e);
System.out.println("YES CONNECT");
}
return null;
}
} | [
"mamunurrashid.s.bd@gmail.com"
] | mamunurrashid.s.bd@gmail.com |
f6e097e5fcaa5d1e8b60e198720347c7cdf3051d | d7774de5c9f5a128d6d1258e4eb8ff1323d59ac1 | /src/main/java/com/mercury/msifinalserver/beans/Application.java | a66c20be9a40628b091984ddddbf1c87ee69e1eb | [] | no_license | kdj842969/insurance-web-app-backend | e0608c5586306767c8d7db7d7519eaeb60f49d10 | 47fd3b32a64a9608fed603436329c48bed48afad | refs/heads/master | 2020-08-17T17:13:47.988039 | 2019-10-17T03:19:30 | 2019-10-17T03:19:30 | 215,691,017 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,491 | java | package com.mercury.msifinalserver.beans;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
@Table(name="msi_application")
public class Application {
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "MSI_CAR_SEQ_GEN")
@SequenceGenerator(name = "MSI_CAR_SEQ_GEN", sequenceName = "MSI_CAR_SEQ", allocationSize = 1)
private int id;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(unique = true)
private Car car;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(unique = true)
private Client client;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(unique = true)
private Policy policy;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
@JsonIgnore
private User user;
@Column
private String applicationStatus;
public Application() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public Policy getPolicy() {
return policy;
}
public void setPolicy(Policy policy) {
this.policy = policy;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getApplicationStatus() {
return applicationStatus;
}
public void setApplicationStatus(String applicationStatus) {
this.applicationStatus = applicationStatus;
}
public Application(int id, Car car, Client client, User user, Policy policy, String applicationStatus) {
super();
this.id = id;
this.car = car;
this.client = client;
this.policy = policy;
this.user = user;
this.applicationStatus = applicationStatus;
}
@Override
public String toString() {
return "Application [id=" + id + ", car=" + car + ", client=" + client + ", policy=" + policy + ", user=" + user
+ ", applicationStatus=" + applicationStatus + "]";
}
}
| [
"kdj842969@gmail.com"
] | kdj842969@gmail.com |
a2a7aeae98d5a3c53620daccd24fa21c9c2d97fd | 86de531e9bd75a4ab54f39e6ccbb7251e08d80f8 | /app/src/main/java/com/sagihatzabi/breakingline/items/FoodExtraState.java | f5bc18d2af69eae63431cad88b47aedbeb0ab42e | [] | no_license | Sagi363/AVDemo | 5ce9654606c9d523866f5e994411a9145683a3d9 | 491c8afcfcd790ab40344a721738d69e70619cbb | refs/heads/master | 2021-01-01T17:54:16.178335 | 2017-03-10T12:10:17 | 2017-03-10T12:10:17 | 98,194,181 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,083 | java | package com.sagihatzabi.breakingline.items;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.view.ContextThemeWrapper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.BounceInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.util.List;
/**
* Created by sagihatzabi on 05/02/2017.
*/
public class FoodExtraState {
public FoodExtra.Type type;
public boolean state;
public FoodExtraState(FoodExtra.Type type, boolean state) {
this.type = type;
this.state = state;
}
}
| [
"Sagi363@gmail.com"
] | Sagi363@gmail.com |
a497ca284ac84342a3cf7b1ab84dcb5f9dd117e8 | 725bb74f0469e03492ed94950480524fc4daabfe | /src/main/java/Selenium/Selenium/ReadPropertiesObj.java | 6cb57e38c82cdaa35584dfbb859fb2f23eb5fb9f | [] | no_license | rkreddy227/selenium | 1cee7a59f89f74ceb6e2014fd3b0614c66cd3d2b | 975179d335cb75100597d58b98ae2c010bff487a | refs/heads/master | 2021-06-28T00:56:08.057976 | 2020-12-01T01:46:23 | 2020-12-01T01:46:23 | 182,613,423 | 0 | 0 | null | 2020-10-13T13:04:39 | 2019-04-22T03:02:08 | Java | UTF-8 | Java | false | false | 1,758 | java | package Selenium.Selenium;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ReadPropertiesObj {
static WebDriver driver;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Properties proper = new Properties();
FileInputStream fisy = new FileInputStream("C:\\Users\\18482\\Selenium\\selenium\\src\\main\\java\\config.properties");
proper.load(fisy);
System.out.println(proper.getProperty("name"));
System.out.println(proper.getProperty("age"));
String url = proper.getProperty("URL");
System.out.println(url);
String browserName = proper.getProperty("browser");
System.out.println(browserName);
if(browserName.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
driver = new ChromeDriver();
}
else if(browserName.equals("ff")) {
System.setProperty("webdriver.chrome.driver", "C:\\geckodriver.exe");
driver = new FirefoxDriver();
}
driver.get(url);
driver.findElement(By.xpath(proper.getProperty("firstname_xpath"))).sendKeys(proper.getProperty("firstName"));
driver.findElement(By.xpath(proper.getProperty("lastname_xpath"))).sendKeys(proper.getProperty("lastName"));
driver.findElement(By.xpath(proper.getProperty("mobilenumber_xpath"))).sendKeys(proper.getProperty("mobileNumber"));
driver.findElement(By.xpath(proper.getProperty("newpassword_xpath"))).sendKeys(proper.getProperty("newPassword"));
}
}
| [
"rkreddy227@gmail.com"
] | rkreddy227@gmail.com |
851ef7f4349f39c875bb53481385cb7ffa41203b | d15803d5b16adab18b0aa43d7dca0531703bac4a | /com/whatsapp/jz.java | 35214c75a7cff97d0285f269a9ebf0732545ce77 | [] | no_license | kenuosec/Decompiled-Whatsapp | 375c249abdf90241be3352aea38eb32a9ca513ba | 652bec1376e6cd201d54262cc1d4e7637c6334ed | refs/heads/master | 2021-12-08T15:09:13.929944 | 2016-03-23T06:04:08 | 2016-03-23T06:04:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 192 | java | package com.whatsapp;
class jz implements Runnable {
final tw a;
jz(tw twVar) {
this.a = twVar;
}
public void run() {
App.b(App.z(), 2131231120, 1);
}
}
| [
"gigalitelk@gmail.com"
] | gigalitelk@gmail.com |
ad5c33a69951caf95c7e33e7470eed0bae18d1a9 | 109ad176c4d3698f76fb01c5d7e13d6fa6bb6308 | /ddd-module-demo/ddd-domain/src/main/java/com/runssnail/ddd/demo/domain/event/policyset/PolicySetActivatedEvent.java | 15977a4beb01698db2524e28cf5dd780f1639af7 | [] | no_license | xudilei/ddd | 66734d00107cb8f178e1cc03cf4fe01b94488a11 | 53e452fcf263cdb6dec3f968d7c74cec6f22ecbf | refs/heads/master | 2022-04-26T01:45:49.469527 | 2020-04-07T03:16:00 | 2020-04-07T03:16:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 479 | java | package com.runssnail.ddd.demo.domain.event.policyset;
import com.runssnail.ddd.common.event.AbstractEvent;
import com.runssnail.ddd.demo.client.dto.domain.policyset.PolicySetId;
import lombok.Getter;
/**
* @author zhengwei
* @date 2019-11-05 15:08
**/
@Getter
public class PolicySetActivatedEvent extends AbstractEvent {
private PolicySetId policySetId;
public PolicySetActivatedEvent(PolicySetId policySetId) {
this.policySetId = policySetId;
}
}
| [
"zhengwei@007fenqi.com.cn"
] | zhengwei@007fenqi.com.cn |
d61dc72fd9bce8a7f668e85a968905b67b805fe1 | 2d46df49ed01ca46f8df1de356989056dffec490 | /app/src/main/java/com/playendlesslistview/fragment/MainFragment.java | d07d4df12884bbf682d7684843f562b090c16bc0 | [] | no_license | Ericliu001/PlayEndlessListView | 8e7160fa120fc53d7f2b33477f5c512d59daa35a | cd900317147974ab2aa58970ea128a10f75445e4 | refs/heads/master | 2020-07-05T03:16:11.922199 | 2015-05-27T05:08:47 | 2015-05-27T05:08:47 | 22,462,275 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,208 | java | package com.playendlesslistview.fragment;
import com.playendlesslistview.endless.StreamAdapter;
import com.playendlesslistview.endless.StreamLoader;
import com.playendlesslistview.endless.parent.EndlessListViewBaseListFragment;
import com.playendlesslistview.endless.parent.GenericAdapter;
import com.playendlesslistview.endless.parent.GenericLoader;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.widget.ListView;
public class MainFragment extends EndlessListViewBaseListFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setLoadItemCount(15);
}
@Override
public ListView getDataListView() {
// TODO Auto-generated method stub
return getListView();
}
@Override
public GenericAdapter getDataListAdapter() {
// TODO Auto-generated method stub
return new StreamAdapter(getActivity(), dataList);
}
@Override
public GenericLoader getGenericLoader() {
// TODO Auto-generated method stub
return new StreamLoader(getActivity());
}
@Override
public String getTabTitle() {
// TODO Auto-generated method stub
return "Endless";
}
}
| [
"eric.liu.developer@gmail.com"
] | eric.liu.developer@gmail.com |
cd2f14b5774ad8d9b45a3bcfc6d44639db4082b5 | b9fdb61cbdf6f0769615ffc1081e894824f8bb61 | /src/test/java/com/duevornHarris/InnerClassSpec.java | 4d3b9222b91d8634fe7231e46b8d6d57f4bd6506 | [] | no_license | Duevorn-Harris/InnerClassesLab | add4c95d4c500fd9e3fa2253365322faa0b635ca | b7f3f9a5c28ed19aff5d51a6485ecfdaeae0b305 | refs/heads/master | 2016-09-13T11:53:22.869015 | 2016-05-19T16:04:51 | 2016-05-19T16:04:51 | 59,220,275 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,599 | java | package com.duevornHarris;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by duevornharris on 5/18/16.
*/
public class InnerClassSpec {
@Test
public void makeConnectionTestObject(){
ConnectionManager connectionManager = new ConnectionManager();
Assert.assertNotNull("The method does not return an Object", connectionManager.makeConnection("127.0.0.1",
"PPP"));
}
@Test
public void makeConnectionTestNull(){
ConnectionManager connectionManager = new ConnectionManager();
connectionManager.numberOfConnectionsLimit = 0;
Assert.assertNull("The method returns an Object ", connectionManager.makeConnection("123", "PPP"));
}
@Test
public void closeConnectionTest(){
ConnectionManager connectionManager = new ConnectionManager();
//connectionManager.makeConnection("192.168.186.252", "TCP");
Connection connection = connectionManager.makeConnection("192.168.186.252", "TCP");
String expectedString = "A connection has been closed";
Assert.assertEquals("Connection was not closed ", expectedString, connection.close());
}
@Test
public void connectConnectionTest(){
ConnectionManager connectionManager = new ConnectionManager();
Connection connection = connectionManager.makeConnection("192.168.186.252", "TCP");
String expectedResult = "A connection has been made.";
String actualResult = connection.connect();
Assert.assertEquals("Connection was not opened ", expectedResult, actualResult);
}
}
| [
"duevorn@gmail.com"
] | duevorn@gmail.com |
4d9917fe3b04831abec342c8f203a6cf583f4f53 | f37e6b3a468581fae960266340164eb2c78b69c7 | /src/main/java/com/marcin/springit/security/SecurityConfiguration.java | c631be7edc285e904c1af55bdfb88cdf49d977c2 | [] | no_license | mzcz/springit | f41f890f212b1eacf9fe02067096dd2c0a48867a | 66bd32efca60885fbdea0eddc3202cdbb9f1a150 | refs/heads/master | 2020-04-14T12:53:29.341089 | 2019-01-10T15:31:22 | 2019-01-10T15:31:22 | 163,853,587 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,816 | java | package com.marcin.springit.security;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private UserDetailsServiceImpl userDetailsService;
public SecurityConfiguration(UserDetailsServiceImpl userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.requestMatchers(EndpointRequest.to("info")).permitAll()
.requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN")
.antMatchers("/actuator/").hasRole("ADMIN")
.antMatchers("/").permitAll()
.antMatchers("/link/submit").hasRole("USER")
.antMatchers("/h2-console/**").permitAll()
.and()
.formLogin()
.loginPage("/login").permitAll()
.usernameParameter("email")
.and()
.logout()
.and()
.rememberMe();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
}
| [
"mzienkiewicz@objectivity.co.uk"
] | mzienkiewicz@objectivity.co.uk |
9b9c01d44f63cd71619a93f5119f95b6d4f0703b | ac2b1c7b26d745bba389cc0de81c28e8e3b01f51 | /poc_nav/android/app/src/main/java/com/poc/generated/BasePackageList.java | 0adaf0025b2c088c4dcb901067f617bf5d2fba63 | [] | no_license | mdsaleem1804/react-native | 4dd03c5a4b9f960cf09f801c697431e31031b5b6 | 56dd762e82aac537a085598b7d0bc6214ddcf8e2 | refs/heads/master | 2023-01-28T08:44:44.611657 | 2020-04-05T13:54:09 | 2020-04-05T13:54:09 | 253,171,932 | 0 | 0 | null | 2023-01-26T18:59:08 | 2020-04-05T06:39:42 | JavaScript | UTF-8 | Java | false | false | 808 | java | package com.poc.generated;
import java.util.Arrays;
import java.util.List;
import org.unimodules.core.interfaces.Package;
public class BasePackageList {
public List<Package> getPackageList() {
return Arrays.<Package>asList(
new expo.modules.constants.ConstantsPackage(),
new expo.modules.errorrecovery.ErrorRecoveryPackage(),
new expo.modules.filesystem.FileSystemPackage(),
new expo.modules.font.FontLoaderPackage(),
new expo.modules.keepawake.KeepAwakePackage(),
new expo.modules.lineargradient.LinearGradientPackage(),
new expo.modules.location.LocationPackage(),
new expo.modules.permissions.PermissionsPackage(),
new expo.modules.sqlite.SQLitePackage(),
new expo.modules.webbrowser.WebBrowserPackage()
);
}
}
| [
"mdsaleem1804@gmail.com"
] | mdsaleem1804@gmail.com |
92340bb5824dfdab5a822eebd7b53ca9d612e3e4 | 9837790eb90ef85ff4c039e849daac02e6b1678f | /cs-vmware/src/test/java/io/cloudslang/content/vmware/actions/cluster/DeleteClusterRuleTest.java | 4feedafbc03969ce6af26670f9ee6af788e062d5 | [
"Apache-2.0"
] | permissive | hathazylaszlojr/cs-actions | 4928e63ba1ecd28780ee0cee7341ec3401407662 | 6f0e75e344b29c03955e4001a8170fbff5f93366 | refs/heads/master | 2021-01-13T14:58:48.531466 | 2016-12-16T10:29:51 | 2016-12-16T10:29:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,899 | java | /*******************************************************************************
* (c) Copyright 2016 Hewlett-Packard Development Company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
*******************************************************************************/
package io.cloudslang.content.vmware.actions.cluster;
import io.cloudslang.content.constants.OutputNames;
import io.cloudslang.content.vmware.entities.VmInputs;
import io.cloudslang.content.vmware.entities.http.HttpInputs;
import io.cloudslang.content.vmware.services.ClusterComputeResourceService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.HashMap;
import java.util.Map;
import static io.cloudslang.content.vmware.constants.ErrorMessages.NOT_ZERO_OR_POSITIVE_NUMBER;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.whenNew;
/**
* Created by pinteae on 10/12/2016.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(DeleteClusterRule.class)
public class DeleteClusterRuleTest {
private DeleteClusterRule deleteClusterRule;
@Before
public void init() {
deleteClusterRule = new DeleteClusterRule();
}
@After
public void tearDown() {
deleteClusterRule = null;
}
@Mock
private ClusterComputeResourceService clusterComputeResourceServiceMock;
@Test
public void testDeleteClusterRule() throws Exception {
Map<String, String> expectedResultMap = new HashMap<>();
whenNew(ClusterComputeResourceService.class).withNoArguments().thenReturn(clusterComputeResourceServiceMock);
when(clusterComputeResourceServiceMock.deleteClusterRule(any(HttpInputs.class), any(VmInputs.class))).thenReturn(expectedResultMap);
Map<String, String> actualResultMap = deleteClusterRule.deleteClusterRule("", "", "", "", "", "", "", "");
verify(clusterComputeResourceServiceMock, times(1)).deleteClusterRule(any(HttpInputs.class), any(VmInputs.class));
assertNotNull(actualResultMap);
assertEquals(expectedResultMap, actualResultMap);
}
@Test
public void testDeleteClusterRuleProtocolException() throws Exception {
Map<String, String> resultMap = deleteClusterRule.deleteClusterRule("", "", "myProtocol", "", "", "", "", "");
verify(clusterComputeResourceServiceMock, never()).deleteClusterRule(any(HttpInputs.class), any(VmInputs.class));
assertNotNull(resultMap);
assertEquals(-1, Integer.parseInt(resultMap.get(OutputNames.RETURN_CODE)));
assertEquals("Unsupported protocol value: [myProtocol]. Valid values are: https, http.", resultMap.get(OutputNames.RETURN_RESULT));
}
@Test
public void testDeleteClusterRulePortException() throws Exception {
Map<String, String> resultMap = deleteClusterRule.deleteClusterRule("", "myPort", "", "", "", "", "", "");
verify(clusterComputeResourceServiceMock, never()).deleteClusterRule(any(HttpInputs.class), any(VmInputs.class));
assertNotNull(resultMap);
assertEquals(-1, Integer.parseInt(resultMap.get(OutputNames.RETURN_CODE)));
assertEquals(NOT_ZERO_OR_POSITIVE_NUMBER, resultMap.get(OutputNames.RETURN_RESULT));
}
}
| [
"eugen.pintea@hpe.com"
] | eugen.pintea@hpe.com |
04962cd518915e45f510f2a34393d29f8de77d61 | 0f50067d1bc2a5dca7f4aa1adb4b29daddabf35e | /app/src/main/java/com/example/appeerciciosemequipamento/Escolher2Activity.java | 2a41cd3926cfa0dcebddef02dfdc3faffa2dddbc | [] | no_license | Nunobill/AppEercicioSemEquipamento-master | 27270c801a4c6f3a85abbf96b1dc6f7bf1aafbd9 | 461e374f85923584191970fc594ee663795b1e88 | refs/heads/master | 2020-05-02T17:05:58.467832 | 2019-04-28T15:58:31 | 2019-04-28T15:58:31 | 178,088,656 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,559 | java | package com.example.appeerciciosemequipamento;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
public class Escolher2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_escolher2);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void escolheractivity(){
Intent intent = getIntent();
String nome = intent.getStringExtra(DefinicoesApp.NOME);
String duracao = intent.getStringExtra(DefinicoesApp.DURACAO);
String nome1 = intent.getStringExtra(DefinicoesApp.NOME);
String duracao1 = intent.getStringExtra(DefinicoesApp.DURACAO);
TextView textViewEscolherC1Corp = (TextView) findViewById(R.id.textViewEscolherC1);
TextView textViewEscolherC2Corp = (TextView) findViewById(R.id.textViewEscolherC2);
textViewEscolherC1Corp.setText(nome);
textViewEscolherC2Corp.setText(duracao);
textViewEscolherC1Corp.setText(nome1);
textViewEscolherC2Corp.setText(duracao1);
}
public void cancelarCorp(View view) {
finish();
}
}
| [
"1012377@sal.ipg.pt"
] | 1012377@sal.ipg.pt |
c01c1e05c26060c41e6c07386693de51f56f583c | ec3061b320513d7c01f39c2508623b150a642ce2 | /app/src/main/java/com/lcworld/tab/Fragment_5.java | 4e0cddb015fa21675e5b1ba34bc9722f6964944d | [] | no_license | LongBro777/SlideTabView | 1b497abbed91565388e1328f80690651a4138e05 | 6e65eedb89c691e7bee1d6eb7e7ae276c6df6b9c | refs/heads/master | 2021-01-20T21:13:19.249705 | 2016-06-23T08:52:06 | 2016-06-23T08:52:06 | 61,799,046 | 1 | 0 | null | 2016-06-23T11:11:18 | 2016-06-23T11:11:18 | null | UTF-8 | Java | false | false | 698 | java | package com.lcworld.tab;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* 创建: dongshuaijun .
* 日期:2016/6/21.
* 注释:
*/
public class Fragment_5 extends Fragment {
TextView textView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container,false);
textView = (TextView) view.findViewById(R.id.text);
textView.setText("这是第5个Fragment");
return view;
}
}
| [
"duke618@163.com"
] | duke618@163.com |
a4405322f93dac66d3b7333a9dc82067bf3c690c | 55f6d42b4c8bb1b3458eb0d8ef419ccbfefedb35 | /src/main/java/kr/co/swingsaver/entity/AdminEntity.java | 2b830589868287693de1cbca0cf2f38b3adbde46 | [] | no_license | minsoub/SwingSaverAdmin | afb17ad7f8deb4031d051bc1f54103c3183e8d4e | 7b6ab5f14f334c4f2398a6307653c3efd5771436 | refs/heads/master | 2023-06-30T02:19:37.697035 | 2021-07-30T08:03:33 | 2021-07-30T08:03:33 | 322,225,245 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 995 | java | package kr.co.swingsaver.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Entity
@Table(name = "SWADM")
@Schema(description = "관리자정보")
public class AdminEntity {
@Schema(description = "관리자No.", example = "123")
@Id
@Column(name = "id")
public long id;
@Schema(description = "메일주소", example = "mjoung@hist.co.kr")
@Column(name = "email")
public String email;
@Schema(description = "패스워드", example = "1234")
@Column(name = "password")
public String password;
@Schema(description = "성명", example = "admin")
@Column(name = "name")
public String name;
@Schema(description = "생성일자", example = "20210101120000")
@Column(name = "createdate")
public String createdate;
}
| [
"mjougn@hist.co.kr"
] | mjougn@hist.co.kr |
fb36d3fa1391a274c48b4bc9426f7f4b0f3329fd | 453ba2f66480998cb5b95c6caacc5dabab239af2 | /src/main/java/com/codeblockacademy/shipbender/exception/not_found/LoginException.java | 64c1d04940040445a3ce5628b1a0aa35c64010f7 | [] | no_license | AvilaMarco/Batleship-Avatar-Aang | 9726ebbe622cdc0f14b016c5d1f822fcdc126a18 | bf83a51359b9792f68bf52f979ddb74a1725970e | refs/heads/master | 2023-01-09T19:02:44.499491 | 2023-01-05T16:06:43 | 2023-01-05T16:06:43 | 210,972,385 | 0 | 0 | null | 2022-07-02T00:31:53 | 2019-09-26T01:24:52 | CSS | UTF-8 | Java | false | false | 229 | java | package com.codeblockacademy.shipbender.exception.not_found;
public class LoginException extends NotFoundException {
public LoginException () {
super("Please check the email or password", "Login Exception");
}
}
| [
"marco6267@hotmail.com"
] | marco6267@hotmail.com |
595d254242dff1ffe1fa89c8d2bd3b505eea8754 | 7596209c942b825a885b4d7a3969bc91c98298f0 | /app/src/main/java/com/example/helenkellercompute/guokun/androidview/SwipeRefreshLayout_banner/BannerCustom.java | d76488cb9327e912efe0edebc9e452186b235c10 | [] | no_license | gkkunguo/Guokun | 283e4df90f47d07bbd809fa543c106008f1661ff | 1b53d5df9a9332358dfa6813abc64abd47f86c1f | refs/heads/master | 2021-07-25T21:06:21.264096 | 2020-02-26T02:09:02 | 2020-02-26T02:09:02 | 156,536,669 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,817 | java | package com.example.helenkellercompute.guokun.androidview.SwipeRefreshLayout_banner;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import com.youth.banner.Banner;
public class BannerCustom extends Banner {
// 分别记录上次滑动的坐标
private int mLastX = 0;
private int mLastY = 0;
public BannerCustom(Context context) {
super(context);
}
public BannerCustom(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BannerCustom(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
requestDisallowInterceptTouchEvent(true);//让控件的父控件不要调用onInterceptTouchEvent方法
// 让控件的父控件不要调用onInterceptTouchEvent方法,并且不要拦截事件,这样子控件就能拿到所有的事件,然后根据自己的逻辑进行处理)
break;
}
case MotionEvent.ACTION_MOVE: {
int deltaX = x - mLastX;
int deltaY = y - mLastY;
if (Math.abs(deltaX) < Math.abs(deltaY)) {//y>x 调用你父控件onInterceptTouchEvent方法
requestDisallowInterceptTouchEvent(false);
}
break;
}
case MotionEvent.ACTION_UP: {
break;
}
default:
break;
}
mLastX = x;
mLastY = y;
return super.dispatchTouchEvent(event);
}
}
| [
"gkkunguo@163.com"
] | gkkunguo@163.com |
b9feb9a2e5c982fb879dc0082976d146c73e65d1 | 146df3b90b9acebffefd6ba90a780f40818c2068 | /ambry-api/src/main/java/com/github/ambry/notification/UpdateType.java | 81a51ce0c688c579d3e5ccf1d51fb7693c5ef47c | [
"Apache-2.0",
"MIT",
"EPL-1.0"
] | permissive | linkedin/ambry | 1658f3dfce0eb8c2165da8220ec459df8b7f5e8e | 0c520d4b9332aeffb4d042e157e326caf8ef54c8 | refs/heads/master | 2023-09-03T12:42:17.852727 | 2023-08-31T23:42:55 | 2023-08-31T23:42:55 | 13,870,893 | 1,845 | 341 | Apache-2.0 | 2023-09-14T21:56:21 | 2013-10-25T20:04:54 | Java | UTF-8 | Java | false | false | 590 | java | /*
* Copyright 2018 LinkedIn Corp. All rights reserved.
*
* 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.
*/
package com.github.ambry.notification;
public enum UpdateType {
TTL_UPDATE
}
| [
"dharju@linkedin.com"
] | dharju@linkedin.com |
b1bf7536c0a0f7a58a01a6438f83b7ab47752828 | 8b91e0a8b6e9cad6c5777ca160bccc05af3f604f | /app/src/main/java/bwie/example/com/demozhou1105fu/utils/OkUtils.java | 0830111ec0790910fcbd3b92812ddeed06bbd141 | [] | no_license | Guilin666/DemoZhou1105Fu3 | c311d593a04c8c6fb86ef1e22fd3d1f3e13675ad | df6d8ee8ed5bf1da832c118519745873e08ac7e4 | refs/heads/master | 2020-04-04T22:40:35.558912 | 2018-11-06T05:52:24 | 2018-11-06T05:52:24 | 156,331,808 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,396 | java | package bwie.example.com.demozhou1105fu.utils;
import android.os.Handler;
import android.os.Message;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkUtils {
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
String data = (String) msg.obj;
lisener.success(data);
}
};
private OkListener lisener;
public OkUtils get(String url) {
OkHttpClient client = new OkHttpClient();
Request build = new Request.Builder().url(url).build();
client.newCall(build).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String data = response.body().string();
Message message = Message.obtain();
message.obj = data;
handler.sendMessage(message);
}
});
return this;
}
public void setOkLisener(OkListener lisener) {
this.lisener = lisener;
}
public interface OkListener {
void success(String data);
}
}
| [
"1753846877@qq.com"
] | 1753846877@qq.com |
542e4902b659a78f73f81b68694de8077fc723bc | 3d145b67d60021dd3909f76d579949ba0fc719e8 | /platform/diff-impl/src/com/intellij/diff/tools/fragmented/UnifiedDiffTool.java | ca1b431fa14f9ef9b2c6d91ea37bcb599d709ca8 | [
"Apache-2.0"
] | permissive | shanyaodan/intellij-community | cfcf2ca6c08034bc0215ba194ecde67a5bd0ad44 | a5cd6ac6102731ea9b557dcc1c684340f7d8432a | refs/heads/master | 2021-01-24T00:53:12.270012 | 2015-08-17T23:55:58 | 2015-08-17T23:58:32 | 40,955,877 | 1 | 0 | null | 2015-08-18T06:53:50 | 2015-08-18T06:53:50 | null | UTF-8 | Java | false | false | 1,733 | java | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.diff.tools.fragmented;
import com.intellij.diff.DiffContext;
import com.intellij.diff.FrameDiffTool;
import com.intellij.diff.requests.DiffRequest;
import com.intellij.diff.tools.simple.SimpleOnesideDiffViewer;
import org.jetbrains.annotations.NotNull;
public class UnifiedDiffTool implements FrameDiffTool {
public static final UnifiedDiffTool INSTANCE = new UnifiedDiffTool();
@NotNull
@Override
public DiffViewer createComponent(@NotNull DiffContext context, @NotNull DiffRequest request) {
if (SimpleOnesideDiffViewer.canShowRequest(context, request)) return new SimpleOnesideDiffViewer(context, request);
if (UnifiedDiffViewer.canShowRequest(context, request)) return new UnifiedDiffViewer(context, request);
throw new IllegalArgumentException(request.toString());
}
@Override
public boolean canShow(@NotNull DiffContext context, @NotNull DiffRequest request) {
return SimpleOnesideDiffViewer.canShowRequest(context, request) || UnifiedDiffViewer.canShowRequest(context, request);
}
@NotNull
@Override
public String getName() {
return "Oneside viewer";
}
}
| [
"AMPivovarov@gmail.com"
] | AMPivovarov@gmail.com |
be3781c20fc04c862074c3a66386c8a506791fd4 | 5bfd5cfbe824feb3ab67831d2c748e3d9ac40c42 | /src/day7/Question7.java | 8124ede9326263684e060ef79f283fac5f462335 | [] | no_license | AsishBohara/Assignment | faf087f69870ab479fad79a97eecd9edeedc894a | e7f89d7ccf7bbfacc5dcae275165a0ed2e8d23c7 | refs/heads/main | 2023-01-15T11:38:00.073589 | 2020-11-27T01:28:10 | 2020-11-27T01:28:10 | 315,796,689 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 451 | java | package day7;
import java.util.Scanner;
public class Question7 {
public static void main(String[] args) {
// volume of cylinder
final double PI = Math.PI;
Scanner input = new Scanner(System.in);
System.out.println("Enter r: ");
double r = input.nextDouble();
System.out.println("Enter h: ");
double h = input.nextDouble();
double v = PI * r * r * h;
System.out.println("volume of cylinder is: " + v);
input.close();
}
}
| [
"asish.bohara1984@gmail.com"
] | asish.bohara1984@gmail.com |
1a3b5c781e1cf47021ed654cc056e64ba47e5b31 | 16d4f9d2195d62323fff3661ef10524e3dd33ecf | /project01/src09/bitcamp/pms/ProjectApp01.java | 25be0842ad681a8f1592a24bc82aec28b775f9f2 | [] | no_license | eomjinyoung/Java80 | c967b761698c30c513e45adad11cc7fc2430f3f1 | e47affad9a4510ff9d13f7afc00de24dd4db2ef4 | refs/heads/master | 2021-01-21T04:40:44.181358 | 2016-06-22T08:59:16 | 2016-06-22T08:59:16 | 51,817,374 | 0 | 3 | null | null | null | null | UTF-8 | Java | false | false | 1,846 | java | /* 목표
- 명령어에 따라 회원 정보를 다룰 수 있도록 변경하라.
명령> add
이름? 홍길동
이메일? hong@test.com
암호? 1111
전화? 111-1111
저장하시겠습니까?(y/n) y
저장하였습니다.
저장하시겠습니까?(y/n) N
저장을 취소하였습니다.
명령> list
0, 홍길동, hong@test.com, 1111, 1111-2222
1, 홍길동, hong@test.com, 1111, 1111-2222
2, 홍길동, hong@test.com, 1111, 1111-2222
3, 홍길동, hong@test.com, 1111, 1111-2222
명령> delete
삭제할 회원의 번호는? 2
정말로 삭제하시겠습니까?(y/n) y
삭제하였습니다.
정말로 삭제하시겠습니까?(y/n) n
삭제를 취소하였습니다.
명령> list
0, 홍길동, hong@test.com, 1111, 1111-2222
1, 홍길동, hong@test.com, 1111, 1111-2222
2,
3, 홍길동, hong@test.com, 1111, 1111-2222
명령> quit
안녕히 가세요!
명령> xxx
올바르지 않은 명령어입니다.
명령>
- 사용 문법:
=> 반복문과 조건문의 활용
*/
package bitcamp.pms;
import java.util.Scanner;
import bitcamp.pms.domain.Member;
public class ProjectApp {
public static void main(String[] args) {
Scanner keyScan = new Scanner(System.in);
String input;
while (true) {
System.out.print("명령> ");
input = keyScan.nextLine();
System.out.println(input);
}
}
static boolean confirm(String message, boolean strictMode) {
Scanner keyScan = new Scanner(System.in);
String input = null;
do {
System.out.printf("%s(y/n) ", message);
input = keyScan.nextLine().toLowerCase();
if (input.equals("y")) {
return true;
} else if (input.equals("n")) {
return false;
} else {
if (!strictMode) {
return false;
}
System.out.println("잘못된 명령어입니다.");
}
} while(true);
}
}
| [
"jinyoung.eom@gmail.com"
] | jinyoung.eom@gmail.com |
c7ca1b2fecceab2e7e905641023f4e38608c9b6d | 05696b1b64a12999c345d14433cacddfb0b8e4f5 | /week6/673_number_of_LIS.java | 0ea5ad9933e42f920aa33c95d8655991603372d3 | [] | no_license | wjzwjh/Leetcode | 7819aa7ddcabee5159d66d46f05e1308756fe7e3 | ccaa1a180750b926c373d7dd640ecf712cca1036 | refs/heads/master | 2023-07-13T09:38:54.250534 | 2021-08-25T13:50:31 | 2021-08-25T13:50:31 | 378,952,923 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,079 | java | class Solution {
public int findNumberOfLIS(int[] nums) {
int N = nums.length;
int[] length = new int[N];
int[] count = new int[N];
Arrays.fill(length,1);//each number is a subsequence
Arrays.fill(count,1);//since each number is a subsequence, the LIS for a single element array is 1
for(int i = 0 ; i < nums.length; ++i){
for(int j = 0; j < i; ++j){
if(nums[i] > nums[j]){
if(1 + length[j] > length[i]){
length[i] = 1 + length[j];
count[i] = count[j];
}else if(1 + length[j] == length[i]){
count[i] += count[j];
}
}
}
}
int max = 0;
for(int i: length){
max = Math.max(i,max);
}
int ans = 0;
for(int i = 0; i < N; ++i){
if(length[i] == max){
ans += count[i];
}
}
return ans;
}
}
| [
"wengjiahong@gmail.com"
] | wengjiahong@gmail.com |
57116d43cb12a2f047458d96906b1104c605b1f4 | 2055c9c3c6531511d29a3ad7ab8f2ad1785ccc8a | /python.django/src/org/netbeans/modules/python/django/project/DjangoProjectUtil.java | bdb41a238fd763ab60f681fa43d82d11f3fbe84f | [] | no_license | Seha16/netbeans-django | 30534cbdc7bbbd5dd82b6e5523a853ee102bee62 | 24c9c359740a9d945afca9214a2606b185f994c1 | refs/heads/master | 2020-05-28T07:42:30.130567 | 2009-03-04T09:21:53 | 2009-03-04T09:21:53 | 40,284,852 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,639 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.netbeans.modules.python.django.project;
import org.netbeans.modules.python.api.PythonPlatform;
import org.netbeans.modules.python.api.PythonPlatformManager;
import org.netbeans.modules.python.project.ui.customizer.PythonProjectProperties;
import org.netbeans.api.project.Project;
import org.netbeans.spi.project.support.ant.AntProjectHelper;
/**
*
* @author Ravi Hingarajiya
*/
public class DjangoProjectUtil {
private DjangoProjectUtil() {}
public static DjangoProject getProject (final Project project) {
assert project != null;
return project.getLookup().lookup(DjangoProject.class);
}
public static AntProjectHelper getProjectHelper (final Project project) {
final DjangoProject djangoProject = getProject(project);
return djangoProject == null ? null : djangoProject.getHelper();
}
public static PythonPlatform getActivePlatform (final Project project) {
final DjangoProject pp = getProject(project);
if (pp == null) {
return null; //No Django project
}
final PythonPlatformManager manager = PythonPlatformManager.getInstance();
String platformId = pp.getEvaluator().getProperty(PythonProjectProperties.ACTIVE_PLATFORM);
if (platformId == null) {
platformId = manager.getDefaultPlatform();
}
if (platformId == null) {
return null; //No Python platform in the IDE
}
return manager.getPlatform(platformId);
}
}
| [
"alberto.paro@53ee0c52-ff2b-11dd-9d1d-173cc1d06e3c"
] | alberto.paro@53ee0c52-ff2b-11dd-9d1d-173cc1d06e3c |
fa350a06f1f5d7fcd5948849909b9cd41e6d137c | 404497d8cb21bb9bcbc71d5ae2fe209a87c75d16 | /entity-service-hrm/entity-service-hrm/src/main/java/com/inkubator/hrm/dao/impl/ApprovalDefinitionDaoImpl.java | 185164d731a5428a71ae4e51e5d48d80dfbb35b0 | [] | no_license | creative-active-technology/entity-service-hrm | 60a6ce4b740db9bf64c96cd4d99c10002158b4f0 | 3bb14b3c902ecc913036f78dae4f43a7b430ec86 | refs/heads/master | 2021-01-19T03:22:04.401125 | 2014-05-07T03:37:53 | 2014-05-07T03:37:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,367 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.inkubator.hrm.dao.impl;
import com.inkubator.datacore.dao.impl.IDAOImpl;
import com.inkubator.hrm.dao.ApprovalDefinitionDao;
import com.inkubator.hrm.entity.ApprovalDefinition;
import com.inkubator.hrm.web.search.ApprovalDefinitionSearchParameter;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
/**
*
* @author Deni Husni FR
*/
@Repository
@Lazy
public class ApprovalDefinitionDaoImpl extends IDAOImpl<ApprovalDefinition> implements ApprovalDefinitionDao {
@Override
public Class<ApprovalDefinition> getEntityClass() {
return ApprovalDefinition.class;
}
@Override
public List<ApprovalDefinition> getByParam(ApprovalDefinitionSearchParameter searchParameter, int firstResult, int maxResults, Order order) {
Criteria criteria = getCurrentSession().createCriteria(getEntityClass());
doSearchApprovalDefinitionByParam(searchParameter, criteria);
criteria.setFetchMode("proscessToApprove", FetchMode.JOIN);
criteria.addOrder(order);
criteria.setFirstResult(firstResult);
criteria.setMaxResults(maxResults);
return criteria.list();
}
@Override
public Long getTotalApprovalDefinitionByParam(ApprovalDefinitionSearchParameter searchParameter) {
Criteria criteria = getCurrentSession().createCriteria(getEntityClass());
doSearchApprovalDefinitionByParam(searchParameter, criteria);
return (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
}
private void doSearchApprovalDefinitionByParam(ApprovalDefinitionSearchParameter searchParameter, Criteria criteria) {
if (searchParameter.getProcessName() != null) {
criteria.createAlias("proscessToApprove", "pa", JoinType.INNER_JOIN);
criteria.add(Restrictions.like("pa.code", searchParameter.getProcessName(), MatchMode.ANYWHERE));
}
if (searchParameter.getApproverPosition() != null) {
criteria.add(Restrictions.like("approverPosition", searchParameter.getApproverPosition(), MatchMode.ANYWHERE));
}
if (searchParameter.getApproverIndividual() != null) {
criteria.add(Restrictions.like("approverIndividual", searchParameter.getApproverIndividual(), MatchMode.ANYWHERE));
}
if (searchParameter.getOnBehalfApproverPosition() != null) {
criteria.add(Restrictions.like("onBehalfIndividual", searchParameter.getOnBehaltAppriverIndividual(), MatchMode.ANYWHERE));
}
if (searchParameter.getOnBehaltAppriverIndividual() != null) {
criteria.add(Restrictions.like("onBehalfPosition", searchParameter.getOnBehalfApproverPosition(), MatchMode.ANYWHERE));
}
criteria.add(Restrictions.isNotNull("id"));
}
}
| [
"Deni Husni FR@Positron"
] | Deni Husni FR@Positron |
bd8ce025413d85f7b2409988f6384dde08078c73 | 543f2ddc6710d9a7682ef96638ee94ada65d82d5 | /src/main/java/com/iyuexian/wechat4j/core/QrUtil.java | c4aa755e784cf3bb3bb132390638128bd87ca803 | [] | no_license | cnflyne/wechat4j | e457b7f67f4eebecefcfcf8ff81e2c131a7728f2 | c2ea481940d84ec121b384806dec54b7bf985a30 | refs/heads/master | 2021-08-24T04:37:42.343813 | 2017-12-08T02:51:25 | 2017-12-08T02:51:25 | 113,454,628 | 0 | 0 | null | 2017-12-07T13:32:52 | 2017-12-07T13:32:51 | null | UTF-8 | Java | false | false | 897 | java | package com.iyuexian.wechat4j.core;
public class QrUtil {
public static OsName getOsName() {
String os = System.getProperty("os.name").toUpperCase();
if (os.indexOf(OsName.DARWIN.toString()) >= 0) {
return OsName.DARWIN;
} else if (os.indexOf(OsName.WINDOWS.toString()) >= 0) {
return OsName.WINDOWS;
} else if (os.indexOf(OsName.LINUX.toString()) >= 0) {
return OsName.LINUX;
} else if (os.indexOf(OsName.MAC.toString()) >= 0) {
return OsName.MAC;
}
return OsName.OTHER;
}
public static void printQr(String qrPath) throws Exception {
String cmd = "";
switch (getOsName()) {
case WINDOWS: {
cmd = " cmd /c start ";
break;
}
case MAC:
cmd = " open ";
break;
default:
throw new RuntimeException("operation not supported");
}
Runtime runtime = Runtime.getRuntime();
runtime.exec(cmd + qrPath);
}
}
| [
"798395170@qq.com"
] | 798395170@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.