hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e1c6875d68f56a26a1732d333bb619d94d9c7e0
8,027
java
Java
erp_desktop_all/src_nomina/com/bydan/erp/nomina/presentation/swing/jinternalframes/report/EvaluacionesBonificacionesBeanSwingJInternalFrameAdditional.java
jarocho105/pre2
f032fc63741b6deecdfee490e23dfa9ef1f42b4f
[ "Apache-2.0" ]
1
2018-01-05T17:50:03.000Z
2018-01-05T17:50:03.000Z
erp_desktop_all/src_nomina/com/bydan/erp/nomina/presentation/swing/jinternalframes/report/EvaluacionesBonificacionesBeanSwingJInternalFrameAdditional.java
jarocho105/pre2
f032fc63741b6deecdfee490e23dfa9ef1f42b4f
[ "Apache-2.0" ]
null
null
null
erp_desktop_all/src_nomina/com/bydan/erp/nomina/presentation/swing/jinternalframes/report/EvaluacionesBonificacionesBeanSwingJInternalFrameAdditional.java
jarocho105/pre2
f032fc63741b6deecdfee490e23dfa9ef1f42b4f
[ "Apache-2.0" ]
null
null
null
40.746193
490
0.807151
12,048
/* *ADVERTENCIA : Este programa esta protegido por la ley de derechos de autor. *La reproducci?n o distribuci?n il?cita de este programa o de cualquiera de *sus partes esta penado por la ley con severas sanciones civiles y penales, *y ser?n objeto de todas las sanciones legales que correspondan. */ package com.bydan.erp.nomina.presentation.swing.jinternalframes.report; import com.bydan.erp.seguridad.business.entity.Usuario; import com.bydan.erp.seguridad.business.entity.PerfilOpcion; import com.bydan.erp.seguridad.business.entity.PerfilCampo; import com.bydan.erp.seguridad.business.entity.PerfilAccion; import com.bydan.erp.seguridad.business.entity.ParametroGeneralSg; import com.bydan.erp.seguridad.business.entity.ParametroGeneralUsuario; import com.bydan.erp.seguridad.business.entity.Modulo; import com.bydan.erp.seguridad.business.entity.Opcion; import com.bydan.framework.erp.business.entity.*; import com.bydan.framework.erp.util.*; //import com.bydan.erp.nomina.util.NominaConstantesFunciones; import com.bydan.erp.nomina.business.entity.report.EvaluacionesBonificaciones; import com.bydan.erp.nomina.business.logic.report.*; //////import com.bydan.erp.nomina.service.ejb.interfaces.NominaAdditionable; //////import com.bydan.erp.nomina.service.ejb.interfaces.NominaAdditionableHome; //import com.bydan.erp.nomina.business.entity.*; //import com.bydan.framework.erp.business.logic.QueryWhereSelectParameters; //import com.bydan.framework.erp.business.logic.*; //import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.HashSet; import java.util.ArrayList; import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.event.*; import javax.swing.GroupLayout.Alignment; //import org.hibernate.collection.PersistentBag; import com.bydan.framework.erp.presentation.desktop.swing.JInternalFrameBase; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeModel; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeSelectionModel; import javax.swing.tree.TreePath; import javax.swing.tree.MutableTreeNode; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import com.bydan.framework.erp.business.entity.DatoGeneral; //import com.bydan.erp.nomina.service.ejb.interfaces.NominaAdditionable; ////import com.bydan.erp.nomina.service.ejb.interfaces.NominaAdditionableHome; //import javax.servlet.http.HttpSession; //import javax.servlet.ServletConfig; //CONTROL_INCLUDE @SuppressWarnings("unused") public class EvaluacionesBonificacionesBeanSwingJInternalFrameAdditional extends JInternalFrameBase//EvaluacionesBonificacionesBeanSwingJInternalFrame { private static final long serialVersionUID = 1L; //public static NominaAdditionable nominaAdditionable= EvaluacionesBonificacionesConstantesFunciones.getEvaluacionesBonificacionesAdditionableEjbReference(EvaluacionesBonificacionesConstantesFunciones.SREMOTEEJBNAMEADDITIONALADDITIONAL_JBOSS81); //public static NominaAdditionableHome nominaAdditionableHome= EvaluacionesBonificacionesConstantesFunciones.getEvaluacionesBonificacionesAdditionableHomeEjbReference(EvaluacionesBonificacionesConstantesFunciones.SLOCALEJBNAMEADDITIONALADDITIONAL_JBOSS81); //CONTROL_INICIO //EvaluacionesBonificacionesLogic evaluacionesbonificacionesLogic; //EvaluacionesBonificacionesLogicAdditional evaluacionesbonificacionesLogicAdditional; Mensaje mensaje; public static int openFrameCount = 0; public static final int xOffset = 10, yOffset = 35; public EvaluacionesBonificacionesBeanSwingJInternalFrameAdditional(PaginaTipo paginaTipo) throws Exception { super(paginaTipo); try { //evaluacionesbonificacionesLogic=new EvaluacionesBonificacionesLogic(); //evaluacionesbonificacionesLogicAdditional=new EvaluacionesBonificacionesLogicAdditional(); } catch(Exception e) { throw e; } } //CONTROL_FUNCION1 public static void RecargarFormEvaluacionesBonificaciones(EvaluacionesBonificacionesBeanSwingJInternalFrame evaluacionesbonificacionesBeanSwingJInternalFrame,String sTipo,Object oValor,ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { //CONTROL_1 } public static void RecargarVentanaSegunOpcion(JInternalFrameBase jInternalFrameBase,Opcion opcionActual) throws Exception { //CONTROL_2 } /* public static void ProcesarAccion(String sProceso,JInternalFrameBase jInternalFrameBase) throws Exception { //CONTROL_3 } */ public static void CargaInicial(JInternalFrameBase jInternalFrameBase,String sTipo,Object objectGeneral) throws Exception { //CONTROL_4 } public static void CargaInicialInicio(JInternalFrameBase jInternalFrameBase,String sTipo,Object objectGeneral) throws Exception { //CONTROL_5 } public static Boolean EsProcesoAccionNormal(String sTipoProceso) throws Exception { //CONTROL_6 Boolean esProcesoAccionNormal=true; if(sTipoProceso.equals("XYZ")) { //esProcesoAccionNormal=false; } return esProcesoAccionNormal; } public static void ProcesarAccion(String sProceso,String sLabelProceso,JInternalFrameBase jInternalFrameBase) throws Exception { //CONTROL_3 Boolean esProcesado=false; EvaluacionesBonificacionesLogicAdditional evaluacionesbonificacionesLogicAdditional=new EvaluacionesBonificacionesLogicAdditional(); EvaluacionesBonificacionesBeanSwingJInternalFrame evaluacionesbonificacionesBeanSwingJInternalFrame=(EvaluacionesBonificacionesBeanSwingJInternalFrame)jInternalFrameBase; if(JOptionPane.showConfirmDialog(jInternalFrameBase, "ESTA SEGURO DE PROCESAR "+sLabelProceso+" EVALUACIONES BONIFICACIONESES SELECCIONADOS?", "MANTENIMIENTO DE ACCION", JOptionPane.OK_CANCEL_OPTION) == 0) { //ARCHITECTURE if(Constantes.ISUSAEJBLOGICLAYER) { //TO_COMMENT esProcesado=evaluacionesbonificacionesLogicAdditional.ProcesarAccion(evaluacionesbonificacionesBeanSwingJInternalFrame.getParametroGeneralUsuario(),evaluacionesbonificacionesBeanSwingJInternalFrame.getModuloActual(),evaluacionesbonificacionesBeanSwingJInternalFrame.getOpcionActual(),evaluacionesbonificacionesBeanSwingJInternalFrame.getUsuarioActual(),sProceso,evaluacionesbonificacionesBeanSwingJInternalFrame.getEvaluacionesBonificacionesLogic().getEvaluacionesBonificacioness()); } else if(Constantes.ISUSAEJBREMOTE) {//TO_COMMENT } else if(Constantes.ISUSAEJBHOME) {//TO_COMMENT }//TO_COMMENT //ARCHITECTURE if(esProcesado) { JOptionPane.showMessageDialog(evaluacionesbonificacionesBeanSwingJInternalFrame,"PROCESO REALIZADO CORRECTAMENTE","PROCESO ",JOptionPane.INFORMATION_MESSAGE); } } } public static GeneralEntityParameterReturnGeneral procesarEventosVista(ParametroGeneralUsuario parametroGeneralUsuario,Modulo modulo,Opcion opcion,Usuario usuario,JInternalFrameBase jInternalFrameBase,FuncionTipo funcionTipo,ControlTipo controlTipo,EventoTipo eventoTipo,EventoSubTipo eventoSubTipo,String sTipo,Object object,Object objects,GeneralEntityParameterReturnGeneral generalEntityParameterGeneral,GeneralEntityParameterReturnGeneral generalEntityReturnGeneral)throws Exception { try { //CONTROL_7 if(controlTipo.equals(ControlTipo.WINDOW)) { } else if(controlTipo.equals(ControlTipo.PANEL)) { } else if(controlTipo.equals(ControlTipo.FORM)) { } else if(controlTipo.equals(ControlTipo.BUTTON)) { } else if(controlTipo.equals(ControlTipo.COMBOBOX)) { } else if(controlTipo.equals(ControlTipo.TEXTBOX)) { } else if(controlTipo.equals(ControlTipo.CHECKBOX)) { } else if(controlTipo.equals(ControlTipo.TEXTAREA)) { } else if(controlTipo.equals(ControlTipo.TREE)) { } return generalEntityReturnGeneral; } catch(Exception e) { throw e; } finally { } } //CONTROL_FUNCION2 }
3e1c6886800a7a9f7d2988e2b69246f2c954f73b
2,615
java
Java
platform/lang-impl/src/com/intellij/largeFilesEditor/editor/LargeFileNotificationProvider.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
platform/lang-impl/src/com/intellij/largeFilesEditor/editor/LargeFileNotificationProvider.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
1
2020-07-30T19:04:47.000Z
2020-07-30T19:04:47.000Z
platform/lang-impl/src/com/intellij/largeFilesEditor/editor/LargeFileNotificationProvider.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
1
2020-10-15T05:56:42.000Z
2020-10-15T05:56:42.000Z
46.696429
140
0.731931
12,049
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.largeFilesEditor.editor; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorBundle; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.EditorNotificationPanel; import com.intellij.ui.EditorNotifications; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class LargeFileNotificationProvider extends EditorNotifications.Provider<EditorNotificationPanel> { private static final Key<EditorNotificationPanel> KEY = Key.create("large.file.editor.notification"); private static final Key<String> HIDDEN_KEY = Key.create("large.file.editor.notification.hidden"); private static final String DISABLE_KEY = "large.file.editor.notification.disabled"; @NotNull @Override public Key<EditorNotificationPanel> getKey() { return KEY; } @Nullable @Override public EditorNotificationPanel createNotificationPanel(@NotNull VirtualFile file, @NotNull FileEditor fileEditor, @NotNull Project project) { if (!(fileEditor instanceof LargeFileEditor)) return null; Editor editor = ((LargeFileEditor)fileEditor).getEditor(); if (editor.getUserData(HIDDEN_KEY) != null || PropertiesComponent.getInstance().isTrueValue(DISABLE_KEY)) { return null; } EditorNotificationPanel panel = new EditorNotificationPanel(); panel.createActionLabel(EditorBundle.message("notification.hide.message"), () -> { editor.putUserData(HIDDEN_KEY, "true"); update(file, project); }); panel.createActionLabel(EditorBundle.message("notification.dont.show.again.message"), () -> { PropertiesComponent.getInstance().setValue(DISABLE_KEY, "true"); update(file, project); }); return panel.text(EditorBundle.message("large.file.editor.notification.text.the.file.is.too.large.so.showing.in.read.only.mode", StringUtil.formatFileSize(file.getLength()))); } private static void update(@NotNull VirtualFile file, @NotNull Project project) { EditorNotifications.getInstance(project).updateNotifications(file); } }
3e1c68b27f7014247b30d83326438227878ce51a
4,003
java
Java
eventsourcing/src/main/java/org/axonframework/eventsourcing/eventstore/jdbc/Oracle11EventTableFactory.java
java-app-scans/AxonFramework
dd222ff4ef69dc2a3a8ced18ffffd50765d01188
[ "ECL-2.0", "Apache-2.0" ]
2,576
2015-01-07T18:25:46.000Z
2022-03-31T11:42:37.000Z
eventsourcing/src/main/java/org/axonframework/eventsourcing/eventstore/jdbc/Oracle11EventTableFactory.java
java-app-scans/AxonFramework
dd222ff4ef69dc2a3a8ced18ffffd50765d01188
[ "ECL-2.0", "Apache-2.0" ]
1,638
2015-01-08T21:19:54.000Z
2022-03-31T12:12:26.000Z
eventsourcing/src/main/java/org/axonframework/eventsourcing/eventstore/jdbc/Oracle11EventTableFactory.java
java-app-scans/AxonFramework
dd222ff4ef69dc2a3a8ced18ffffd50765d01188
[ "ECL-2.0", "Apache-2.0" ]
798
2015-01-04T03:06:46.000Z
2022-03-30T18:23:34.000Z
44.977528
118
0.617537
12,050
/* * Copyright (c) 2010-2018. Axon Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.axonframework.eventsourcing.eventstore.jdbc; import org.axonframework.common.jdbc.Oracle11Utils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Oracle 11 doesn't support the data type BIGINT, so NUMBER(19) is used as a substitute instead. Also Oracle doesn't * seem to like colons in create table statements, so those have been removed. * * @author Rene de Waele * @since 3.0 */ public class Oracle11EventTableFactory extends AbstractEventTableFactory { @Override public PreparedStatement createDomainEventTable(Connection connection, EventSchema schema) throws SQLException { String sql = "CREATE TABLE " + schema.domainEventTable() + " (\n" + schema.globalIndexColumn() + " NUMBER(19) NOT NULL,\n" + schema.aggregateIdentifierColumn() + " VARCHAR(255) NOT NULL,\n" + schema.sequenceNumberColumn() + " NUMBER(19) NOT NULL,\n" + schema.typeColumn() + " VARCHAR(255),\n" + schema.eventIdentifierColumn() + " VARCHAR(255) NOT NULL,\n" + schema.metaDataColumn() + " " + payloadType() + ",\n" + schema.payloadColumn() + " " + payloadType() + " NOT NULL,\n" + schema.payloadRevisionColumn() + " VARCHAR(255),\n" + schema.payloadTypeColumn() + " VARCHAR(255) NOT NULL,\n" + schema.timestampColumn() + " VARCHAR(255) NOT NULL,\n" + "PRIMARY KEY (" + schema.globalIndexColumn() + "),\n" + "UNIQUE (" + schema.aggregateIdentifierColumn() + ", " + schema.sequenceNumberColumn() + "),\n" + "UNIQUE (" + schema.eventIdentifierColumn() + ")\n" + ")"; try (PreparedStatement pst = connection.prepareStatement(sql)) { pst.execute(); } Oracle11Utils.simulateAutoIncrement(connection, schema.domainEventTable(), schema.globalIndexColumn()); return Oracle11Utils.createNullStatement(connection); } @Override public PreparedStatement createSnapshotEventTable(Connection connection, EventSchema schema) throws SQLException { String sql = "CREATE TABLE " + schema.snapshotTable() + " (\n" + schema.aggregateIdentifierColumn() + " VARCHAR(255) NOT NULL,\n" + schema.sequenceNumberColumn() + " NUMBER(19) NOT NULL,\n" + schema.typeColumn() + " VARCHAR(255) NOT NULL,\n" + schema.eventIdentifierColumn() + " VARCHAR(255) NOT NULL,\n" + schema.metaDataColumn() + " " + payloadType() + ",\n" + schema.payloadColumn() + " " + payloadType() + " NOT NULL,\n" + schema.payloadRevisionColumn() + " VARCHAR(255),\n" + schema.payloadTypeColumn() + " VARCHAR(255) NOT NULL,\n" + schema.timestampColumn() + " VARCHAR(255) NOT NULL,\n" + "PRIMARY KEY (" + schema.aggregateIdentifierColumn() + ", " + schema.sequenceNumberColumn() + "),\n" + "UNIQUE (" + schema.eventIdentifierColumn() + ")\n" + ")"; return connection.prepareStatement(sql); } @Override protected String idColumnType() { return ""; // ignored } @Override protected String payloadType() { return "BLOB"; } }
3e1c69100f00f1386086f9b516262958ba5de1c9
1,602
java
Java
perspective-worker/src/test/java/org/meridor/perspective/worker/misc/impl/CloudConfigurationProviderImplTest.java
vania-pooh/perspective-backend
5f98083977a57115988678e97d1642ee83431258
[ "Apache-2.0" ]
19
2015-11-09T19:14:24.000Z
2021-04-24T22:38:17.000Z
perspective-worker/src/test/java/org/meridor/perspective/worker/misc/impl/CloudConfigurationProviderImplTest.java
meridor/perspective-backend
5f98083977a57115988678e97d1642ee83431258
[ "Apache-2.0" ]
206
2015-10-21T11:32:14.000Z
2017-03-03T15:34:28.000Z
perspective-worker/src/test/java/org/meridor/perspective/worker/misc/impl/CloudConfigurationProviderImplTest.java
vania-pooh/perspective-backend
5f98083977a57115988678e97d1642ee83431258
[ "Apache-2.0" ]
6
2015-12-27T08:59:09.000Z
2019-12-20T02:12:32.000Z
34.826087
85
0.774032
12,051
package org.meridor.perspective.worker.misc.impl; import org.junit.Test; import org.junit.runner.RunWith; import org.meridor.perspective.backend.EntityGenerator; import org.meridor.perspective.config.Cloud; import org.meridor.perspective.worker.misc.CloudConfigurationProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.ArrayList; import java.util.List; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; @ContextConfiguration(locations = "/META-INF/spring/mocked-storage-context.xml") @RunWith(SpringJUnit4ClassRunner.class) public class CloudConfigurationProviderImplTest { @Autowired private CloudConfigurationProvider cloudConfigurationProvider; private static final Cloud CLOUD = EntityGenerator.getCloud(); @Test public void testGetCloud() throws Exception { Cloud cloud = cloudConfigurationProvider.getCloud("test-id"); assertThat(cloud, equalTo(CLOUD)); } @Test(expected = IllegalArgumentException.class) public void testGetCloudWithMissingId() throws Exception { cloudConfigurationProvider.getCloud("missing-id"); } @Test public void testGetClouds() throws Exception { List<Cloud> clouds = new ArrayList<>(cloudConfigurationProvider.getClouds()); assertThat(clouds, hasSize(1)); assertThat(clouds.get(0), equalTo(CLOUD)); } }
3e1c697fd8eab18ad0c35314002aaa7778706bd4
468
java
Java
dahlia-core/src/main/java/com/tvd12/dahlia/core/setting/FieldUuidSizeReader.java
youngmonkeys/dahlia
53be1315f65208dd200ce073f66352f7aec48135
[ "Apache-2.0" ]
2
2019-11-08T09:22:11.000Z
2021-05-02T01:09:05.000Z
dahlia-core/src/main/java/com/tvd12/dahlia/core/setting/FieldUuidSizeReader.java
vu-luong/dahlia
717888ced1c84093e263de8f06a827a1bf5dcccf
[ "Apache-2.0" ]
null
null
null
dahlia-core/src/main/java/com/tvd12/dahlia/core/setting/FieldUuidSizeReader.java
vu-luong/dahlia
717888ced1c84093e263de8f06a827a1bf5dcccf
[ "Apache-2.0" ]
2
2019-12-23T16:30:33.000Z
2021-05-02T01:09:09.000Z
23.4
79
0.794872
12,052
package com.tvd12.dahlia.core.setting; import com.tvd12.dahlia.core.constant.Constants; final class FieldUuidSizeReader extends FieldSizeReader<FieldUuidSetting> { private static final FieldUuidSizeReader INSTANCE = new FieldUuidSizeReader(); private FieldUuidSizeReader() {} public static FieldUuidSizeReader getInstance() { return INSTANCE; } @Override protected int readDataSize(FieldUuidSetting setting) { return Constants.MAX_UUID_SIZE; } }
3e1c6b001db3d12f64b6daed18c402ee94f47d75
1,520
java
Java
src-java/grpc-speaker/grpc-api/src/main/java/org/openkilda/messaging/info/grpc/DeleteLogicalPortResponse.java
mfyuce/open-kilda
44f0580c028b8b56aa59536e62003bc416f07180
[ "Apache-2.0" ]
70
2017-10-10T12:59:21.000Z
2022-03-16T13:19:34.000Z
src-java/grpc-speaker/grpc-api/src/main/java/org/openkilda/messaging/info/grpc/DeleteLogicalPortResponse.java
mfyuce/open-kilda
44f0580c028b8b56aa59536e62003bc416f07180
[ "Apache-2.0" ]
2,433
2017-10-09T08:22:14.000Z
2022-03-31T07:57:24.000Z
src-java/grpc-speaker/grpc-api/src/main/java/org/openkilda/messaging/info/grpc/DeleteLogicalPortResponse.java
mfyuce/open-kilda
44f0580c028b8b56aa59536e62003bc416f07180
[ "Apache-2.0" ]
65
2017-10-09T07:53:37.000Z
2022-03-16T12:35:18.000Z
33.777778
90
0.710526
12,053
/* Copyright 2019 Telstra Open Source * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openkilda.messaging.info.grpc; import org.openkilda.messaging.info.InfoData; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Value; @Value public class DeleteLogicalPortResponse extends InfoData { @JsonProperty("switch_address") private String switchAddress; @JsonProperty("logical_port") private int logicalPortNumber; @JsonProperty("deleted") private boolean deleted; @JsonCreator public DeleteLogicalPortResponse(@JsonProperty("switch_address") String switchAddress, @JsonProperty("logical_port") int logicalPortNumber, @JsonProperty("deleted") boolean deleted) { this.switchAddress = switchAddress; this.logicalPortNumber = logicalPortNumber; this.deleted = deleted; } }
3e1c6b3c6ec12b820e2312a593b019fb8b4621f2
3,760
java
Java
src/updater/programs/Program.java
SanjinKurelic/UpdaterJavaFX
e41c4864cedfc85d8aebe4206c5bf9a928c487da
[ "MIT" ]
null
null
null
src/updater/programs/Program.java
SanjinKurelic/UpdaterJavaFX
e41c4864cedfc85d8aebe4206c5bf9a928c487da
[ "MIT" ]
null
null
null
src/updater/programs/Program.java
SanjinKurelic/UpdaterJavaFX
e41c4864cedfc85d8aebe4206c5bf9a928c487da
[ "MIT" ]
null
null
null
27.05036
368
0.599734
12,054
package updater.programs; import java.io.Serializable; import updater.gui.ProgressBarStatus; /** * @author Sanjin Kurelić */ public class Program implements Serializable { static final long serialVersionUID = -6029568751172572559L; // Program info private String name; private String path; // Program version info private int mainVersion; private int minorVersion; private int revisionVersion; // Latest program version info private int latestMainVersion; private int latestMinorVersion; private int latestRevisionVersion; // Additional data private ProgressBarStatus status = ProgressBarStatus.CHECKING_VERSION; private boolean needToBeDownload; public Program(String name, String path, ProgramVersion programVersion) { this.name = name; this.path = path; this.mainVersion = programVersion.getMainVersion(); this.minorVersion = programVersion.getMinorVersion(); this.revisionVersion = programVersion.getRevisionVersion(); this.needToBeDownload = false; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getVersion() { return mainVersion + "." + minorVersion + "." + revisionVersion; } public void setVersion(int mainVersion, int minorVersion, int revisionVersion) { this.mainVersion = mainVersion; this.minorVersion = minorVersion; this.revisionVersion = revisionVersion; } public boolean needsToBeDownloaded() { return this.needToBeDownload; } public void setStatus(ProgressBarStatus status) { this.status = status; } public ProgressBarStatus getStatus() { return status; } public void setDownloaded() { this.needToBeDownload = false; mainVersion = latestMainVersion; minorVersion = latestMinorVersion; revisionVersion = latestRevisionVersion; } /** * Returns true if version from parameter is bigger than this version * * @param mainVersion * @param minorVersion * @param revisionVersion * @return */ public boolean checkVersion(int mainVersion, int minorVersion, int revisionVersion) { if (mainVersion < this.mainVersion) { return false; // can't happen } if (mainVersion == this.mainVersion) { if (minorVersion < this.minorVersion) { return false; // can't happen } if (minorVersion == this.minorVersion) { if (revisionVersion <= this.revisionVersion) { return false; } } } this.latestMainVersion = mainVersion; this.latestMinorVersion = minorVersion; this.latestRevisionVersion = revisionVersion; this.needToBeDownload = true; return true; } @Override public String toString() { return "Program{" + "name=" + name + ", path=" + path + ", mainVersion=" + mainVersion + ", minorVersion=" + minorVersion + ", revisionVersion=" + revisionVersion + ", latestMainVersion=" + latestMainVersion + ", latestMinorVersion=" + latestMinorVersion + ", latestRevisionVersion=" + latestRevisionVersion + ", needToBeDownload=" + needToBeDownload + "}\n"; } }
3e1c6b9d550c3d74f0d9227cfa72cc8df9338d96
1,150
java
Java
src/main/java/org/traccar/api/resource/WorksiteResource.java
esimonm/traccar
e4cb2b735fc432c9adf935c138f3d0febcc311ce
[ "Apache-2.0" ]
null
null
null
src/main/java/org/traccar/api/resource/WorksiteResource.java
esimonm/traccar
e4cb2b735fc432c9adf935c138f3d0febcc311ce
[ "Apache-2.0" ]
null
null
null
src/main/java/org/traccar/api/resource/WorksiteResource.java
esimonm/traccar
e4cb2b735fc432c9adf935c138f3d0febcc311ce
[ "Apache-2.0" ]
null
null
null
31.108108
75
0.75934
12,055
/* * Copyright 2018 Anton Tananaev (anpch@example.com) * Copyright 2018 Andrey Kunitsyn (envkt@example.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.traccar.api.resource; import org.traccar.api.ExtendedObjectResource; import org.traccar.model.Worksite; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("worksites") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class WorksiteResource extends ExtendedObjectResource<Worksite> { public WorksiteResource() { super(Worksite.class); } }
3e1c6bc507af2f354230de6f2cbb56e083a28dbd
9,231
java
Java
app/src/main/java/com/erakk/lnreader/adapter/PageModelAdapter.java
SAM10795/LNReader-Android
d161143d780eff8eef214c01ef9d6b72213c6792
[ "Apache-2.0" ]
72
2015-03-03T02:43:06.000Z
2022-02-09T07:45:27.000Z
app/src/main/java/com/erakk/lnreader/adapter/PageModelAdapter.java
SAM10795/LNReader-Android
d161143d780eff8eef214c01ef9d6b72213c6792
[ "Apache-2.0" ]
127
2015-01-06T00:58:04.000Z
2022-01-17T23:41:58.000Z
app/src/main/java/com/erakk/lnreader/adapter/PageModelAdapter.java
SAM10795/LNReader-Android
d161143d780eff8eef214c01ef9d6b72213c6792
[ "Apache-2.0" ]
24
2015-01-10T10:55:38.000Z
2022-02-17T00:47:01.000Z
36.058594
163
0.575127
12,056
package com.erakk.lnreader.adapter; import android.app.Activity; import android.content.Context; import android.graphics.Typeface; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.erakk.lnreader.Constants; import com.erakk.lnreader.R; import com.erakk.lnreader.UIHelper; import com.erakk.lnreader.dao.NovelsDao; import com.erakk.lnreader.helper.Util; import com.erakk.lnreader.model.PageModel; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class PageModelAdapter extends ArrayAdapter<PageModel> { private static final String TAG = PageModelAdapter.class.toString(); private final Context context; private int layoutResourceId; public List<PageModel> data; private PageModel[] originalData = new PageModel[0]; public PageModelAdapter(Context context, int resourceId, List<PageModel> objects) { super(context, resourceId, objects); this.layoutResourceId = resourceId; this.context = context; this.data = objects; this.originalData = objects.toArray(originalData); filterData(); Log.d(TAG, "created with " + objects.size() + " items"); } public void setLayout(int resourceId) { this.layoutResourceId = resourceId; } @Override public void addAll(PageModel... objects) { synchronized (this) { if (data == null) { data = new ArrayList<PageModel>(); } for (PageModel pageModel : objects) { data.add(pageModel); } } this.notifyDataSetChanged(); } @Override public void addAll(Collection<? extends PageModel> objects) { synchronized (this) { if (data == null) { data = new ArrayList<PageModel>(); } data.addAll(objects); } this.notifyDataSetChanged(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; PageModelHolder holder = null; final PageModel page = data.get(position); if (null == row) { LayoutInflater inflater = ((Activity) context).getLayoutInflater(); row = inflater.inflate(layoutResourceId, parent, false); holder = new PageModelHolder(); holder.txtNovel = (TextView) row.findViewById(R.id.novel_name); holder.txtLastUpdate = (TextView) row.findViewById(R.id.novel_last_update); holder.txtLastCheck = (TextView) row.findViewById(R.id.novel_last_check); holder.chkIsWatched = (CheckBox) row.findViewById(R.id.novel_is_watched); holder.ivExternal = (ImageView) row.findViewById(R.id.is_external); holder.ivHasUpdates = (ImageView) row.findViewById(R.id.novel_has_updates); } else { holder = (PageModelHolder) row.getTag(); } if (holder.txtNovel != null) { holder.txtNovel.setText(page.getTitle()); if (page.isHighlighted()) { holder.txtNovel.setTypeface(null, Typeface.BOLD); holder.txtNovel.setTextSize(20); holder.txtNovel.setText("⇒" + holder.txtNovel.getText()); } // set color holder.txtNovel.setTextColor(Constants.COLOR_UNREAD); if(!Util.isStringNullOrEmpty(page.getStatus())) { if(page.getStatus().equalsIgnoreCase("abandoned")) { holder.txtNovel.setTextColor(Constants.COLOR_ABANDONED); } } if (page.isMissing()) { holder.txtNovel.setTextColor(Constants.COLOR_MISSING); } if (page.isRedlink()) { holder.txtNovel.setTextColor(Constants.COLOR_REDLINK); } if (page.isExternal()) { holder.txtNovel.setTextColor(Constants.COLOR_EXTERNAL); } if (page.isCompleted()) { holder.txtNovel.setTextColor(Constants.COLOR_COMPLETED); } } if (holder.txtLastUpdate != null) { holder.txtLastUpdate.setText(context.getResources().getString(R.string.last_update) + ": " + Util.formatDateForDisplay(context, page.getLastUpdate())); } if (holder.txtLastCheck != null) { holder.txtLastCheck.setText(context.getResources().getString(R.string.last_check) + ": " + Util.formatDateForDisplay(context, page.getLastCheck())); } if (holder.chkIsWatched != null) { // Log.d(TAG, page.getId() + " " + page.getTitle() + " isWatched: " + page.isWatched()); holder.chkIsWatched.setOnCheckedChangeListener(null); holder.chkIsWatched.setChecked(page.isWatched()); holder.chkIsWatched.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { Toast.makeText(context, "Added to watch list: " + page.getTitle(), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, "Removed from watch list: " + page.getTitle(), Toast.LENGTH_SHORT).show(); } // update the db! page.setWatched(isChecked); NovelsDao.getInstance().updatePageModel(page); } }); } if (holder.ivExternal != null) { if (page.isExternal()) { holder.ivExternal.setVisibility(View.VISIBLE); //UIHelper.setColorFilter(holder.ivExternal); } else { holder.ivExternal.setVisibility(View.GONE); } } if (holder.ivHasUpdates != null) { if (page.getUpdateCount() > 0) { holder.ivHasUpdates.setVisibility(View.VISIBLE); //UIHelper.setColorFilter(holder.ivHasUpdates); } else { holder.ivHasUpdates.setVisibility(View.GONE); } } row.setTag(holder); return row; } public List<PageModel> allData; public void filterData(String query) { // keep the original data if(allData == null || allData.size() < data.size()) { allData = new ArrayList<PageModel>(); allData.addAll(data); } if(Util.isStringNullOrEmpty(query)) { // restore data data.clear(); if(allData.size() > data.size()) { data.addAll(allData); } } else { query = query.toLowerCase(); this.clear(); data.clear(); for(PageModel item : allData) { if(item.getTitle().toLowerCase().contains(query)) data.add(item); } } super.notifyDataSetChanged(); Log.d(TAG, "Filtered result : " + data.size()); } public void filterData() { this.clear(); data.clear(); for (PageModel item : originalData) { if (!item.isHighlighted()) { if (!UIHelper.getShowRedlink(getContext()) && item.isRedlink()) continue; if (!UIHelper.getShowMissing(getContext()) && item.isMissing()) continue; if (!UIHelper.getShowExternal(getContext()) && item.isExternal()) continue; } data.add(item); } super.notifyDataSetChanged(); Log.d(TAG, "Filtered result : " + data.size()); } // somehow if enabled, will trigger the db 2x (first load and after load) @Override public void notifyDataSetChanged() { synchronized (this) { // refresh the data Log.d(TAG, "Refreshing data: " + data.size() + " items"); if (!UIHelper.getQuickLoad(context)) { for (int i = 0; i < data.size(); ++i) { try { PageModel temp = NovelsDao.getInstance().getPageModel(data.get(i), null); temp.setUpdateCount(data.get(i).getUpdateCount()); data.set(i, temp); } catch (Exception e) { Log.e(TAG, "Error when refreshing PageModel: " + data.get(i).getPage(), e); } } } super.notifyDataSetChanged(); } } static class PageModelHolder { TextView txtNovel; TextView txtLastUpdate; TextView txtLastCheck; CheckBox chkIsWatched; ImageView ivExternal; ImageView ivHasUpdates; } public void setResourceId(int id) { this.layoutResourceId = id; } }
3e1c6c199ae4e5d582946552ea0c75124545c606
2,707
java
Java
src/main/java/org/jfugue/pattern/Atom.java
bobbotron/mvnbuildbard
87d8d1b70805a084d823524668202bc9ce7926fe
[ "Apache-2.0" ]
4
2019-08-22T06:53:39.000Z
2021-08-05T08:04:49.000Z
src/main/java/org/jfugue/pattern/Atom.java
bobbotron/mvnbuildbard
87d8d1b70805a084d823524668202bc9ce7926fe
[ "Apache-2.0" ]
null
null
null
src/main/java/org/jfugue/pattern/Atom.java
bobbotron/mvnbuildbard
87d8d1b70805a084d823524668202bc9ce7926fe
[ "Apache-2.0" ]
2
2021-07-12T07:07:50.000Z
2021-08-05T08:04:59.000Z
28.494737
88
0.729959
12,057
package org.jfugue.pattern; import org.jfugue.theory.Note; import org.staccato.AtomSubparser; import org.staccato.IVLSubparser; import org.staccato.StaccatoParser; import org.staccato.StaccatoParserContext; /** * An Atom represents a single entity of a Voice+Layer+Instrument+Note * and is useful especially when using the Realtime Player, so all of * the information about a specific note is conveyed at the same time. * Pattern now has an atomize() method that will turn the Pattern into * a collection of atoms. */ public class Atom implements PatternProducer { private byte voice; private byte layer; private byte instrument; private Note note; private String contents; public Atom(byte voice, byte layer, byte instrument, String note) { this(voice, layer, instrument, new Note(note)); } public Atom(byte voice, byte layer, byte instrument, Note note) { createAtom(voice, layer, instrument, note); } public Atom(String voice, String layer, String instrument, String note) { this(voice, layer, instrument, new Note(note)); } public Atom(String voice, String layer, String instrument, Note note) { StaccatoParserContext context = new StaccatoParserContext((StaccatoParser)null); IVLSubparser.populateContext(context); // Need to use toUpperCase() and create a context... this is sounding very parser-ish // and should ideally happen elsewhere! createAtom(IVLSubparser.getInstance().getValue(voice.toUpperCase(), context), IVLSubparser.getInstance().getValue(layer.toUpperCase(), context), IVLSubparser.getInstance().getValue(instrument.toUpperCase(), context), new Note(note)); } private void createAtom(byte voice, byte layer, byte instrument, Note note) { this.voice = voice; this.layer = layer; this.instrument = instrument; this.note = note; StringBuilder buddy = new StringBuilder(); buddy.append(AtomSubparser.ATOM); buddy.append(IVLSubparser.VOICE); buddy.append(voice); buddy.append(AtomSubparser.QUARK_SEPARATOR); buddy.append(IVLSubparser.LAYER); buddy.append(layer); buddy.append(AtomSubparser.QUARK_SEPARATOR); buddy.append(IVLSubparser.INSTRUMENT); buddy.append(instrument); buddy.append(AtomSubparser.QUARK_SEPARATOR); buddy.append(note); this.contents = buddy.toString(); } public byte getVoice() { return this.voice; } public byte getLayer() { return this.layer; } public byte getInstrument() { return this.instrument; } public Note getNote() { return this.note; } @Override public String toString() { return this.contents; } @Override public Pattern getPattern() { return new Pattern(contents); } }
3e1c6c735e2db023726123fd84cf66bfed629adb
3,405
java
Java
app/src/main/java/com/example/moviesearch/QuestionActivity.java
m10singh94/MovieSearch
87426611a174c4307ae9db6362dae6ddd9e62643
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/moviesearch/QuestionActivity.java
m10singh94/MovieSearch
87426611a174c4307ae9db6362dae6ddd9e62643
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/moviesearch/QuestionActivity.java
m10singh94/MovieSearch
87426611a174c4307ae9db6362dae6ddd9e62643
[ "Apache-2.0" ]
null
null
null
37.01087
103
0.618209
12,058
package com.example.moviesearch; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.Html; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; public class QuestionActivity extends AppCompatActivity { private TextView helpQuestion, helpAnswer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_question); helpQuestion = findViewById(R.id.helpQues); helpAnswer = findViewById(R.id.helpAns); // gets the back button ImageButton backButton = findViewById(R.id.backButton); // attempts to set the back button image // sets the image for the logo from the assets. try{ // gets the input stream, loads as drawable InputStream inputStream = getAssets().open("back_arrow.png"); Drawable drawable = Drawable.createFromStream(inputStream, null); // sets the imageView image backButton.setImageDrawable(drawable); inputStream.close(); } catch(IOException ex) { return; } // sets up the back button to go back backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); String textQuestion; String textAnswer = ""; // gets the passed over intent Intent intent = getIntent(); String question = intent.getStringExtra("Question"); ArrayList<String> questionList = intent.getStringArrayListExtra("listOfQuestions"); // based on the extracted question, gets the answer text. textQuestion = question; if(question.compareTo(questionList.get(0)) == 0) { textAnswer = "To use the search, you can input your search as follows:\n\n"+ "Field : Query\n\n"+ "You can use as many fields in the query as you want, all you'll need to do" + "is separate them using a comma! For example, you can use the following to" + "search for a movie that have titles similar to 'super' from 1984 onwards:\n\n" + "movie: super, year >= 1984\n\n" + "Some fields use colons, though some fields use 'quantifiers' like >, = or <= " + "instead. Don't worry if you get mixed up, the system will automatically convert" + "colons to quantifiers and vice-versa."; } if(question.compareTo(questionList.get(1)) == 0) { textAnswer = "You can use the following fields to search for movies:\n\n" + "genre - Searches by a movie's genre, uses colons.\n\n" + "movie - Searches based on a movie's name, uses colons.\n\n" + "year - Searches by a movie's release year, uses quantifiers."; } helpQuestion.setText(textQuestion); helpAnswer.setText(textAnswer); } }
3e1c6cb20d77d373030ad9aa1df00c1677f2c034
1,140
java
Java
springboot-static/src/main/java/com/ctg/test/Async/TaskExecutorConfig.java
yxye/springBoot-demos
c19c4f72d0c373ad6f1051d2074bfb6d1cd45963
[ "Apache-2.0" ]
328
2018-11-22T02:00:37.000Z
2022-03-30T07:33:51.000Z
springboot-static/src/main/java/com/ctg/test/Async/TaskExecutorConfig.java
zzzzxxz/springBoot-demos
142b9bf8434d444ae7ced7a7ae6a68877994aa5a
[ "Apache-2.0" ]
3
2019-07-18T07:27:36.000Z
2022-02-09T22:09:57.000Z
springboot-static/src/main/java/com/ctg/test/Async/TaskExecutorConfig.java
zzzzxxz/springBoot-demos
142b9bf8434d444ae7ced7a7ae6a68877994aa5a
[ "Apache-2.0" ]
371
2019-01-18T06:59:37.000Z
2022-03-30T07:34:01.000Z
31.666667
83
0.789474
12,059
package com.ctg.test.Async; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Component; import java.util.concurrent.Executor; /** * @Description: TODO * @Author: yanhonghai * @Date: 2018/11/8 18:35 */ @Configuration @EnableAsync @Component public class TaskExecutorConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor threadPoolTaskExecutor=new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.setCorePoolSize(10); threadPoolTaskExecutor.setMaxPoolSize(15); threadPoolTaskExecutor.setQueueCapacity(10); threadPoolTaskExecutor.initialize(); return threadPoolTaskExecutor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return null; } }
3e1c6d15c635bb61bc9adf27705077dd2a5e190a
12,574
java
Java
elx-http/src/main/java/org/xbib/elx/http/action/get/HttpMultiGetAction.java
jprante/elx
6efa5e12e838b6c49b9de303bef347066138f75c
[ "Apache-2.0" ]
5
2019-02-12T12:16:26.000Z
2019-08-22T19:28:21.000Z
elx-http/src/main/java/org/xbib/elx/http/action/get/HttpMultiGetAction.java
jprante/elx
6efa5e12e838b6c49b9de303bef347066138f75c
[ "Apache-2.0" ]
null
null
null
elx-http/src/main/java/org/xbib/elx/http/action/get/HttpMultiGetAction.java
jprante/elx
6efa5e12e838b6c49b9de303bef347066138f75c
[ "Apache-2.0" ]
1
2019-04-08T14:46:03.000Z
2019-04-08T14:46:03.000Z
49.117188
137
0.587005
12,060
package org.xbib.elx.http.action.get; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.GenericAction; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.get.MultiGetAction; import org.elasticsearch.action.get.MultiGetItemResponse; import org.elasticsearch.action.get.MultiGetRequest; import org.elasticsearch.action.get.MultiGetResponse; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentLocation; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.get.GetField; import org.elasticsearch.index.get.GetResult; import org.elasticsearch.index.mapper.internal.SourceFieldMapper; import org.xbib.elx.http.HttpAction; import org.xbib.elx.http.action.search.HttpSearchAction; import org.xbib.elx.http.util.CheckedFunction; import org.xbib.netty.http.client.RequestBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.function.Supplier; public class HttpMultiGetAction extends HttpAction<MultiGetRequest, MultiGetResponse> { @Override public GenericAction<MultiGetRequest, MultiGetResponse> getActionInstance() { return MultiGetAction.INSTANCE; } @Override protected RequestBuilder createHttpRequest(String url, MultiGetRequest request) throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder().startObject().startArray("docs"); for (MultiGetRequest.Item item : request.getItems()) { builder.startObject() .field("_index", item.index()) .field("_type", item.type()) .field("_id", item.id()); if (item.fields() != null) { builder.array("fields", item.fields()); } builder.endObject(); } builder.endArray().endObject(); return newPostRequest(url, "_mget", builder.bytes()); } @Override protected CheckedFunction<XContentParser, MultiGetResponse, IOException> entityParser() { return Helper::fromXContent; } static class Helper { private static final ParseField INDEX = new ParseField("_index"); private static final ParseField TYPE = new ParseField("_type"); private static final ParseField ID = new ParseField("_id"); private static final ParseField ERROR = new ParseField("error"); private static final ParseField DOCS = new ParseField("docs"); static final String _INDEX = "_index"; static final String _TYPE = "_type"; static final String _ID = "_id"; private static final String _VERSION = "_version"; private static final String FOUND = "found"; private static final String FIELDS = "fields"; static MultiGetResponse fromXContent(XContentParser parser) throws IOException { String currentFieldName = null; List<MultiGetItemResponse> items = new ArrayList<>(); for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) { switch (token) { case FIELD_NAME: currentFieldName = parser.currentName(); break; case START_ARRAY: if (DOCS.getPreferredName().equals(currentFieldName)) { for (token = parser.nextToken(); token != XContentParser.Token.END_ARRAY; token = parser.nextToken()) { if (token == XContentParser.Token.START_OBJECT) { items.add(parseItem(parser)); } } } break; default: break; } } return new MultiGetResponse(items.toArray(new MultiGetItemResponse[0])); } private static MultiGetItemResponse parseItem(XContentParser parser) throws IOException { String currentFieldName = null; String index = null; String type = null; String id = null; ElasticsearchException exception = null; GetResult getResult = null; ParseFieldMatcher matcher = new ParseFieldMatcher(Settings.EMPTY); for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) { switch (token) { case FIELD_NAME: currentFieldName = parser.currentName(); getResult = fromXContentEmbedded(parser, index, type, id); break; case VALUE_STRING: if (matcher.match(currentFieldName, INDEX)) { index = parser.text(); } else if (matcher.match(currentFieldName, TYPE)) { type = parser.text(); } else if (matcher.match(currentFieldName, ID)) { id = parser.text(); } break; case START_OBJECT: if (matcher.match(currentFieldName, ERROR)) { exception = HttpSearchAction.Helper.elasticsearchExceptionFromXContent(parser); } break; default: // If unknown tokens are encounter then these should be ignored, because // this is parsing logic on the client side. break; } if (getResult != null) { break; } } if (exception != null) { return new MultiGetItemResponse(null, new MultiGetResponse.Failure(index, type, id, exception)); } else { GetResponse getResponse = new GetResponse(getResult); return new MultiGetItemResponse(getResponse, null); } } static void ensureExpectedToken(XContentParser.Token expected, XContentParser.Token actual, Supplier location) { if (actual != expected) { String message = "Failed to parse object: expecting token of type [%s] but found [%s]"; throw new ElasticsearchException(location.get() + ":" + String.format(Locale.ROOT, message, expected, actual)); } } static GetResult fromXContentEmbedded(XContentParser parser) throws IOException { XContentParser.Token token = parser.nextToken(); ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser::getTokenLocation); return fromXContentEmbedded(parser, null, null, null); } static GetResult fromXContentEmbedded(XContentParser parser, String index, String type, String id) throws IOException { XContentParser.Token token = parser.currentToken(); ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser::getTokenLocation); String currentFieldName = parser.currentName(); long version = -1; Boolean found = null; BytesReference source = null; Map<String, GetField> fields = new HashMap<>(); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token.isValue()) { if (_INDEX.equals(currentFieldName)) { index = parser.text(); } else if (_TYPE.equals(currentFieldName)) { type = parser.text(); } else if (_ID.equals(currentFieldName)) { id = parser.text(); } else if (_VERSION.equals(currentFieldName)) { version = parser.longValue(); } else if (FOUND.equals(currentFieldName)) { found = parser.booleanValue(); } else { fields.put(currentFieldName, new GetField(currentFieldName, Collections.singletonList(parser.objectText()))); } } else if (token == XContentParser.Token.START_OBJECT) { if (SourceFieldMapper.NAME.equals(currentFieldName)) { try (XContentBuilder builder = XContentBuilder.builder(parser.contentType().xContent())) { builder.copyCurrentStructure(parser); source = builder.bytes(); } } else if (FIELDS.equals(currentFieldName)) { while(parser.nextToken() != XContentParser.Token.END_OBJECT) { GetField getField = getFieldFromXContent(parser); fields.put(getField.getName(), getField); } } else { parser.skipChildren(); } } else if (token == XContentParser.Token.START_ARRAY) { if ("_ignored".equals(currentFieldName)) { fields.put(currentFieldName, new GetField(currentFieldName, parser.list())); } else { parser.skipChildren(); } } } return new GetResult(index, type, id, version, found, source, fields); } static GetField getFieldFromXContent(XContentParser parser) throws IOException { ensureExpectedToken(XContentParser.Token.FIELD_NAME, parser.currentToken(), parser::getTokenLocation); String fieldName = parser.currentName(); XContentParser.Token token = parser.nextToken(); ensureExpectedToken(XContentParser.Token.START_ARRAY, token, parser::getTokenLocation); List<Object> values = new ArrayList<>(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { values.add(parseFieldsValue(parser)); } return new GetField(fieldName, values); } static Object parseFieldsValue(XContentParser parser) throws IOException { XContentParser.Token token = parser.currentToken(); Object value = null; if (token == XContentParser.Token.VALUE_STRING) { //binary values will be parsed back and returned as base64 strings when reading from json and yaml value = parser.text(); } else if (token == XContentParser.Token.VALUE_NUMBER) { value = parser.numberValue(); } else if (token == XContentParser.Token.VALUE_BOOLEAN) { value = parser.booleanValue(); } else if (token == XContentParser.Token.VALUE_EMBEDDED_OBJECT) { //binary values will be parsed back and returned as BytesArray when reading from cbor and smile value = new BytesArray(parser.binaryValue()); } else if (token == XContentParser.Token.VALUE_NULL) { value = null; } else if (token == XContentParser.Token.START_OBJECT) { value = parser.mapOrdered(); } else if (token == XContentParser.Token.START_ARRAY) { value = parser.listOrderedMap(); } else { throwUnknownToken(token, parser.getTokenLocation()); } return value; } static void throwUnknownToken(XContentParser.Token token, XContentLocation location) { String message = "Failed to parse object: unexpected token [%s] found"; throw new ElasticsearchException(location + ":" + String.format(Locale.ROOT, message, token)); } } }
3e1c6d68d454a1350f58bbf74d975f30402cd7c2
18,466
java
Java
APIJSON-Java-Server/APIJSON-Idea/src/main/java/zuo/biao/apijson/server/Structure.java
xupenghui/APIJSON
2b20ee187852d9f381ff6d795d5fcdd7850fa648
[ "Apache-2.0" ]
2
2021-02-10T10:23:07.000Z
2021-05-18T03:18:01.000Z
APIJSON-Java-Server/APIJSON-Idea/src/main/java/zuo/biao/apijson/server/Structure.java
yuSniper/APIJSON
2b20ee187852d9f381ff6d795d5fcdd7850fa648
[ "Apache-2.0" ]
null
null
null
APIJSON-Java-Server/APIJSON-Idea/src/main/java/zuo/biao/apijson/server/Structure.java
yuSniper/APIJSON
2b20ee187852d9f381ff6d795d5fcdd7850fa648
[ "Apache-2.0" ]
null
null
null
31.139966
157
0.627748
12,061
/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon/APIJSON) 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 zuo.biao.apijson.server; import static zuo.biao.apijson.JSONRequest.KEY_ID; import static zuo.biao.apijson.JSONRequest.KEY_ID_IN; import static zuo.biao.apijson.server.Operation.ADD; import static zuo.biao.apijson.server.Operation.DISALLOW; import static zuo.biao.apijson.server.Operation.NECESSARY; import static zuo.biao.apijson.server.Operation.PUT; import static zuo.biao.apijson.server.Operation.REMOVE; import static zuo.biao.apijson.server.Operation.REPLACE; import static zuo.biao.apijson.server.Operation.UNIQUE; import static zuo.biao.apijson.server.Operation.VERIFY; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Pattern; import javax.activation.UnsupportedDataTypeException; import javax.validation.constraints.NotNull; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import apijson.demo.server.Verifier; import apijson.demo.server.model.BaseModel; import zuo.biao.apijson.JSON; import zuo.biao.apijson.JSONResponse; import zuo.biao.apijson.Log; import zuo.biao.apijson.RequestMethod; import zuo.biao.apijson.RequestRole; import zuo.biao.apijson.StringUtil; import zuo.biao.apijson.model.Test; import zuo.biao.apijson.server.sql.SQLConfig; import zuo.biao.apijson.server.sql.SQLExecutor; //TODO 放到 zuo.biao.apijson 包内,供Android客户端校验请求结构 /**结构类 * 增删改查: operation(add,replace,put,remove) operation:{key0:value0, key1:value1 ...} * 对值校验: verify:{key0:value0, key1:value1 ...} (key{}:range,key$:"%m%"等) * 对值重复性校验: unique:"key0:, key1 ..." (unique:"phone,email" 等) * @author Lemon */ public class Structure { private static final String TAG = "Structure"; private Structure() {} static final String requestString = "{\"Comment\":{\"DISALLOW\": \"id\", \"NECESSARY\": \"userId,momentId,content\"}, \"ADD\":{\"Comment:to\":{}}}"; static final String responseString = "{\"User\":{\"REMOVE\": \"phone\", \"REPLACE\":{\"sex\":2}, \"ADD\":{\"name\":\"api\"}}, \"PUT\":{\"Comment:to\":{}}}"; public static void test() throws Exception { JSONObject request; try { request = JSON.parseObject("{\"Comment\":{\"userId\":0}}"); Log.d(TAG, "test parseRequest = " + parseRequest(RequestMethod.POST, "", JSON.parseObject(requestString), request)); } catch (Exception e) { e.printStackTrace(); } try { request = JSON.parseObject("{\"Comment\":{\"userId\":0, \"momentId\":0, \"content\":\"apijson\"}}"); Log.d(TAG, "test parseRequest = " + parseRequest(RequestMethod.POST, "", JSON.parseObject(requestString), request)); } catch (Exception e) { e.printStackTrace(); } try { request = JSON.parseObject("{\"Comment\":{\"id\":0, \"userId\":0, \"momentId\":0, \"content\":\"apijson\"}}"); Log.d(TAG, "test parseRequest = " + parseRequest(RequestMethod.POST, "", JSON.parseObject(requestString), request)); } catch (Exception e) { e.printStackTrace(); } JSONObject response; try { response = JSON.parseObject("{\"User\":{\"userId\":0}}"); Log.d(TAG, "test parseResponse = " + parseResponse(RequestMethod.GET, "", JSON.parseObject(responseString), response, null)); } catch (Exception e) { e.printStackTrace(); } try { response = JSON.parseObject("{\"User\":{\"userId\":0, \"phone\":\"12345678\"}}"); Log.d(TAG, "test parseResponse = " + parseResponse(RequestMethod.GET, "", JSON.parseObject(responseString), response, null)); } catch (Exception e) { e.printStackTrace(); } try { response = JSON.parseObject("{\"User\":{\"userId\":0, \"phone\":\"12345678\", \"sex\":1}}"); Log.d(TAG, "test parseResponse = " + parseResponse(RequestMethod.GET, "", JSON.parseObject(responseString), response, null)); } catch (Exception e) { e.printStackTrace(); } try { response = JSON.parseObject("{\"User\":{\"id\":0, \"name\":\"tommy\", \"phone\":\"12345678\", \"sex\":1}}"); Log.d(TAG, "test parseResponse = " + parseResponse(RequestMethod.GET, "", JSON.parseObject(responseString), response, null)); } catch (Exception e) { e.printStackTrace(); } } /**从request提取target指定的内容 * @param method * @param name * @param target * @param request * @return * @throws Exception */ public static JSONObject parseRequest(@NotNull final RequestMethod method, final String name , final JSONObject target, final JSONObject request) throws Exception { Log.i(TAG, "parseRequest method = " + method + "; name = " + name + "; target = \n" + JSON.toJSONString(target) + "\n request = \n" + JSON.toJSONString(request)); if (target == null || request == null) {// || request.isEmpty()) { Log.i(TAG, "parseRequest target == null || request == null >> return null;"); return null; } //TODO globleRole要不要改成@role? 只允许服务端Request表中加上可控的ADMIN角色 if (RequestRole.get(request.getString(JSONRequest.KEY_ROLE)) == RequestRole.ADMIN) { throw new IllegalArgumentException("角色设置错误!不允许在写操作Request中传 " + name + ":{ " + JSONRequest.KEY_ROLE + ":admin } !"); } //解析 return parse(name, target, request, new OnParseCallback() { @Override public JSONObject onParseJSONObject(String key, JSONObject tobj, JSONObject robj) throws Exception { // Log.i(TAG, "parseRequest.parse.onParseJSONObject key = " + key + "; robj = " + robj); if (robj == null) { if (tobj != null) {//不允许不传Target中指定的Table throw new IllegalArgumentException(method.name() + "请求,请设置 " + key + " !"); } } else if (zuo.biao.apijson.JSONObject.isTableKey(key)) { if (method == RequestMethod.POST) { if (robj.containsKey(KEY_ID)) { throw new IllegalArgumentException("POST请求, " + key + " 不能设置 " + KEY_ID + " !"); } } else { if (RequestMethod.isQueryMethod(method) == false) { //单个修改或删除 Object id = robj.get(KEY_ID); //如果必须传 id ,可在Request表中配置necessary if (id != null) { if (id instanceof Number == false) { throw new IllegalArgumentException(method.name() + "请求, " + key + " 里面的 " + KEY_ID_IN + ":value 中value的类型只能是Long!"); } } else { //批量修改或删除 Object arr = robj.get(KEY_ID_IN); //如果必须传 id{} ,可在Request表中配置necessary if (arr == null) { throw new IllegalArgumentException(method.name() + "请求, " + key + " 里面 " + KEY_ID + " 和 " + KEY_ID_IN + " 必须传其中一个!"); } if (arr instanceof JSONArray == false) { throw new IllegalArgumentException(method.name() + "请求, " + key + " 里面的 " + KEY_ID_IN + ":value 中value的类型只能是 [Long] !"); } if (((JSONArray)arr).size() > 10) { //不允许一次操作10条以上记录 throw new IllegalArgumentException(method.name() + "请求, " + key + " 里面的 " + KEY_ID_IN + ":[] 中[]的长度不能超过10!"); } } } } } return parseRequest(method, key, tobj, robj); } }); } /**校验并将response转换为指定的内容和结构 * @param method * @param name * @param target * @param response * @param callback * @return * @throws Exception */ public static JSONObject parseResponse(@NotNull final RequestMethod method, final String name , final JSONObject target, final JSONObject response, OnParseCallback callback) throws Exception { Log.i(TAG, "parseResponse method = " + method + "; name = " + name + "; target = \n" + JSON.toJSONString(target) + "\n response = \n" + JSON.toJSONString(response)); if (target == null || response == null) {// || target.isEmpty() { Log.i(TAG, "parseRequest target == null || response == null >> return response;"); return response; } //解析 return parse(name, target, response, callback != null ? callback : new OnParseCallback() {}); } /**对request和response不同的解析用callback返回 * @param target * @param request * @param callback * @return * @throws Exception */ public static JSONObject parse(String name, JSONObject target, JSONObject real , @NotNull OnParseCallback callback) throws Exception { if (target == null) { return null; } //获取配置<<<<<<<<<<<<<<<<<<<<<<<<<<<< JSONObject verify = target.getJSONObject(VERIFY.name()); JSONObject add = target.getJSONObject(ADD.name()); JSONObject put = target.getJSONObject(PUT.name()); JSONObject replace = target.getJSONObject(REPLACE.name()); String unique = StringUtil.getNoBlankString(target.getString(UNIQUE.name())); String remove = StringUtil.getNoBlankString(target.getString(REMOVE.name())); String necessary = StringUtil.getNoBlankString(target.getString(NECESSARY.name())); String disallow = StringUtil.getNoBlankString(target.getString(DISALLOW.name())); //不还原,传进来的target不应该是原来的 target.remove(VERIFY.name()); target.remove(ADD.name()); target.remove(PUT.name()); target.remove(REPLACE.name()); target.remove(UNIQUE.name()); target.remove(REMOVE.name()); target.remove(NECESSARY.name()); target.remove(DISALLOW.name()); //获取配置>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Set<String> tableKeySet = new HashSet<String>(); //移除字段<<<<<<<<<<<<<<<<<<< String[] removes = StringUtil.split(remove); if (removes != null && removes.length > 0) { for (String r : removes) { real.remove(r); } } //移除字段>>>>>>>>>>>>>>>>>>> //判断必要字段是否都有<<<<<<<<<<<<<<<<<<< String[] necessarys = StringUtil.split(necessary); List<String> necessaryList = necessarys == null ? new ArrayList<String>() : Arrays.asList(necessarys); for (String s : necessaryList) { if (real.get(s) == null) {//可能传null进来,这里还会通过 real.containsKey(s) == false) { throw new IllegalArgumentException(name + "不能缺少 " + s + " 等[" + necessary + "]内的任何字段!"); } } //判断必要字段是否都有>>>>>>>>>>>>>>>>>>> Set<String> rkset = real.keySet(); //判断是否都有不允许的字段<<<<<<<<<<<<<<<<<<< List<String> disallowList = new ArrayList<String>(); if ("!".equals(disallow)) {//所有非necessary,改成 !necessary 更好 if (rkset != null) { for (String key : rkset) {//对@key放行,@role,@column,自定义@position等 if (key != null && key.startsWith("@") == false && necessaryList.contains(key) == false) { disallowList.add(key); } } } } else { String[] disallows = StringUtil.split(disallow); if (disallows != null && disallows.length > 0) { disallowList.addAll(Arrays.asList(disallows)); } } for (String s : disallowList) { if (real.containsKey(s)) { throw new IllegalArgumentException(name + "不允许传 " + s + " 等" + StringUtil.getString(disallowList) + "内的任何字段!"); } } //判断是否都有不允许的字段>>>>>>>>>>>>>>>>>>> Set<Entry<String, Object>> set = new LinkedHashSet<>(target.entrySet()); zuo.biao.apijson.server.Entry<String, String> pair; if (set.isEmpty() == false) { String key; Object tvalue; Object rvalue; for (Entry<String, Object> entry : set) { key = entry == null ? null : entry.getKey(); if (key == null) { continue; } tvalue = entry.getValue(); rvalue = real.get(key); if (callback.onParse(key, tvalue, rvalue) == false) { continue; } if (tvalue instanceof JSONObject) {//JSONObject,往下一级提取 tvalue = callback.onParseJSONObject(key, (JSONObject) tvalue, (JSONObject) rvalue); pair = Pair.parseEntry(key, true); if (pair != null && zuo.biao.apijson.JSONObject.isTableKey(pair.getKey())) { tableKeySet.add(key); } } else if (tvalue instanceof JSONArray) {//JSONArray tvalue = callback.onParseJSONArray(key, (JSONArray) tvalue, (JSONArray) rvalue); } else {//其它Object tvalue = callback.onParseObject(key, tvalue, rvalue); } if (tvalue != null) {//可以在target中加上一些不需要客户端传的键值对 real.put(key, tvalue); } } } //不允许操作未指定Table<<<<<<<<<<<<<<<<<<<<<<<<< for (String rk : rkset) { pair = Pair.parseEntry(rk, true);//非GET类操作不允许Table:alias别名 if (pair != null && zuo.biao.apijson.JSONObject.isTableKey(pair.getKey()) && tableKeySet.contains(rk) == false) { throw new UnsupportedOperationException("不允许操作 " + rk + " !"); } } //不允许操作未指定Table>>>>>>>>>>>>>>>>>>>>>>>>> //校验与修改Request<<<<<<<<<<<<<<<<< //在tableKeySet校验后操作,避免 导致put/add进去的Table 被当成原Request的内容 real = operate(VERIFY, verify, real); real = operate(ADD, add, real); real = operate(PUT, put, real); real = operate(REPLACE, replace, real); //校验与修改Request>>>>>>>>>>>>>>>>> //TODO放在operate前?考虑性能、operate修改后再验证的值是否和原来一样 //校验重复<<<<<<<<<<<<<<<<<<< String[] uniques = StringUtil.split(unique); if (BaseModel.isEmpty(uniques) == false) { long exceptId = real.getLongValue(KEY_ID); for (String u : uniques) { Verifier.verifyRepeat(name, u, real.get(u), exceptId); } } //校验重复>>>>>>>>>>>>>>>>>>> Log.i(TAG, "parse return real = " + JSON.toJSONString(real)); return real; } /**执行操作 * @param opt * @param targetChild * @param real * @return * @throws Exception */ private static JSONObject operate(Operation opt, JSONObject targetChild, JSONObject real) throws Exception { if (targetChild == null) { return real; } if (real == null) { throw new IllegalArgumentException("operate real == null!!!"); } Set<Entry<String, Object>> set = new LinkedHashSet<>(targetChild.entrySet()); String tk; Object tv; for (Entry<String, Object> e : set) { tk = e == null ? null : e.getKey(); if (tk == null) { continue; } tv = e.getValue(); if (opt == VERIFY) { verify(tk, tv, real); } else if (opt == PUT) { real.put(tk, tv); } else { if (real.containsKey(tk)) { if (opt == REPLACE) { real.put(tk, tv); } } else { if (opt == ADD) { real.put(tk, tv); } } } } return real; } /**验证值 * @param tk * @param tv * @param real * @throws Exception */ private static void verify(@NotNull String tk, @NotNull Object tv, @NotNull JSONObject real) throws Exception { if (tv == null) { throw new IllegalArgumentException("operate operate == VERIFY " + tk + ":" + tv + " , >> tv == null!!!"); } String rk; Object rv; Logic logic; if (tk.endsWith("$")) { //搜索 sqlVerify("$", real, tk, tv); } else if (tk.endsWith("?")) { //正则表达式 logic = new Logic(tk.substring(0, tk.length() - 1)); rk = logic.getKey(); rv = real.get(rk); if (rv == null) { return; } JSONArray array = SQLConfig.newJSONArray(tv); boolean m; boolean isOr = false; Pattern reg; for (Object r : array) { if (r instanceof String == false) { throw new UnsupportedDataTypeException(rk + ":" + rv + " 中value只支持 String 或 [String] 类型!"); } reg = ObjectParser.COMPILE_MAP.get(r); if (reg == null) { reg = Pattern.compile((String) r); } m = reg.matcher("" + rv).matches(); if (m) { if (logic.isNot()) { throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 " + tk + ":" + tv + " !"); } if (logic.isOr()) { isOr = true; break; } } else { if (logic.isAnd()) { throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 " + tk + ":" + tv + " !"); } } } if (isOr == false && logic.isOr()) { throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 " + tk + ":" + tv + " !"); } } else if (tk.endsWith("{}")) { //rv符合tv条件或在tv内 if (tv instanceof String) {//TODO >= 0, < 10 sqlVerify("{}", real, tk, tv); } else if (tv instanceof JSONArray) { logic = new Logic(tk.substring(0, tk.length() - 2)); rk = logic.getKey(); rv = real.get(rk); if (rv == null) { return; } if (((JSONArray) tv).contains(rv) == logic.isNot()) { throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 " + tk + ":" + tv + " !"); } } else { throw new UnsupportedDataTypeException("服务器Request表verify配置错误!"); } } else if (tk.endsWith("<>")) { //rv包含tv内的值 logic = new Logic(tk.substring(0, tk.length() - 2)); rk = logic.getKey(); rv = real.get(rk); if (rv == null) { return; } if (rv instanceof JSONArray == false) { throw new UnsupportedDataTypeException("服务器Request表verify配置错误!"); } JSONArray array = SQLConfig.newJSONArray(tv); boolean isOr = false; for (Object o : array) { if (((JSONArray) rv).contains(o)) { if (logic.isNot()) { throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 " + tk + ":" + tv + " !"); } if (logic.isOr()) { isOr = true; break; } } else { if (logic.isAnd()) { throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 " + tk + ":" + tv + " !"); } } } if (isOr == false && logic.isOr()) { throw new IllegalArgumentException(rk + ":value 中value不合法!必须匹配 " + tk + ":" + tv + " !"); } } else { throw new IllegalArgumentException("服务器Request表verify配置错误!"); } } /**通过数据库执行SQL语句来验证条件 * @param funChar * @param real * @param tk * @param tv * @throws Exception */ private static void sqlVerify(@NotNull String funChar, JSONObject real, String tk, Object tv) throws Exception { //不能用Parser, 0 这种不符合 StringUtil.isName ! Logic logic = new Logic(tk.substring(0, tk.length() - funChar.length())); String rk = logic.getKey(); Object rv = real.get(rk); if (rv == null) { return; } SQLConfig config = new SQLConfig(RequestMethod.HEAD, 1, 0); config.setTable(Test.class.getSimpleName()); config.setTest(true); config.addWhere("'" + rv + "'" + logic.getChar() + funChar, tv); SQLExecutor executor = new SQLExecutor(); JSONObject result = null; try { result = executor.execute(config); } catch (Exception e) { throw e; } finally { executor.close(); } if (result != null && JSONResponse.isExist(result.getIntValue(JSONResponse.KEY_COUNT)) == false) { throw new IllegalArgumentException(rk + ":" + rv + "中value不合法!必须匹配 " + logic.getChar() + tv + " !"); } } }
3e1c6de5797eae70383a95aa3f89e84b01b4ac76
6,692
java
Java
src/utils/Utility.java
yoriYang/EasyWeather
f1f8cd6c73edfb099126cf82fe1cb53433809d89
[ "Apache-2.0" ]
null
null
null
src/utils/Utility.java
yoriYang/EasyWeather
f1f8cd6c73edfb099126cf82fe1cb53433809d89
[ "Apache-2.0" ]
null
null
null
src/utils/Utility.java
yoriYang/EasyWeather
f1f8cd6c73edfb099126cf82fe1cb53433809d89
[ "Apache-2.0" ]
null
null
null
33.79798
81
0.698745
12,062
package utils; import java.util.ArrayList; import jsonBean.JsonBean; import org.json.JSONObject; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import com.google.gson.Gson; import fragment.City; public class Utility { public static ArrayList<String> dayTemperatureList1 = new ArrayList<String>(); public static ArrayList<String> nightTemperatureList1 = new ArrayList<String>(); public static ArrayList<String> weeklist1 = new ArrayList<String>(); public static ArrayList<String> weatherIdList1 = new ArrayList<String>(); public static ArrayList<String> citylist1 = new ArrayList<String>(); public static ArrayList<String> weatherinfo1 = new ArrayList<String>(); public static ArrayList<String> wind1 = new ArrayList<String>(); // 缓存json文件 public static void saveJson(Context context, String cityname, String jsonData) { // MainActivity.editor.putString(cityname, jsonData); // MainActivity.editor.commit(); SharedPreferences.Editor editor = context.getSharedPreferences( cityname, context.MODE_PRIVATE).edit(); editor.putString("city", jsonData); editor.commit(); } // 建立city数据库 public static void createDatabase(String city) { SQLiteDatabase db = City.dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); // 开始组装数据 if (judgeCityData(city) == 0) { values.put("cityname", city); db.insert("Book", null, values); values.clear(); Log.d("MainActivity", "建立数据库 "); } } // 判断Book表中有无城市 public static int judgeCityData(String city) { int j = 0; ArrayList<String> citylist1 = new ArrayList<String>(); SQLiteDatabase db = City.dbHelper.getWritableDatabase(); Cursor cursor = db.query("Book", null, null, null, null, null, null); if (cursor.moveToFirst()) { do { // 遍历Cursor对象 String cityname = cursor.getString(cursor .getColumnIndex("cityname")); citylist1.add(cityname); } while (cursor.moveToNext()); } for (int i = 0; i < citylist1.size(); i++) { if (citylist1.get(i).equals(city)) { j++; } } cursor.close(); return j; } // 查询Book表中所有的数据 public void queryCityData() { SQLiteDatabase db = City.dbHelper.getWritableDatabase(); Cursor cursor = db.query("Book", null, null, null, null, null, null); if (cursor.moveToFirst()) { do { // 遍历Cursor对象,取出数据并打印 String cityname = cursor.getString(cursor .getColumnIndex("cityname")); Log.d("queryCityData", "db name: " + cityname); } while (cursor.moveToNext()); } cursor.close(); } // 解析 public static Bundle parseJSONWithGSON(String jsonData) { // TODO Auto-generated method stub Bundle bundleData = new Bundle(); try { // jsonobject解析pm2.5 JSONObject jsonObject = new JSONObject(jsonData); String result = jsonObject.getString("result"); JSONObject jsonObject1 = new JSONObject(result); String data = jsonObject1.getString("data"); JSONObject jsonObject2 = new JSONObject(data); String pm25 = jsonObject2.getString("pm25"); JSONObject jsonObject3 = new JSONObject(pm25); String pm251 = jsonObject3.getString("pm25"); JSONObject jsonObject4 = new JSONObject(pm251); String pm252 = jsonObject4.getString("quality"); int curPm = jsonObject4.getInt("curPm"); int pm25index = jsonObject4.getInt("pm25"); int level = jsonObject4.getInt("level"); Gson gson = new Gson(); JsonBean jsonbean = gson.fromJson(jsonData, JsonBean.class); int temperature = jsonbean.getResult().getData().getRealtime() .getWeather().getTemperature(); String t = Integer.toString(temperature); String i = jsonbean.getResult().getData().getRealtime() .getWeather().getInfo(); String city = jsonbean.getResult().getData().getRealtime() .getCity_name(); String time = jsonbean.getResult().getData().getRealtime() .getTime(); for (int m = 0; m <= 4; m++) { String dayTemperature = jsonbean.getResult().getData() .getWeather().get(m).getInfo().getDay().get(2) .toString(); String nightTemperature = jsonbean.getResult().getData() .getWeather().get(m).getInfo().getNight().get(2) .toString(); String week = jsonbean.getResult().getData().getWeather() .get(m).getWeek().toString(); String weatherId = jsonbean.getResult().getData().getWeather() .get(m).getInfo().getDay().get(0).toString(); String weatherinfo = jsonbean.getResult().getData() .getWeather().get(m).getInfo().getDay().get(1) .toString(); String wind = jsonbean.getResult().getData().getWeather() .get(m).getInfo().getDay().get(4).toString(); dayTemperatureList1.add(dayTemperature); nightTemperatureList1.add(nightTemperature); weeklist1.add(week); weatherIdList1.add(weatherId); weatherinfo1.add(weatherinfo); wind1.add(wind); } // 解析生活提示 String ganmao = jsonbean.getResult().getData().getLife().getInfo() .getGanmao().get(0); String yundong = jsonbean.getResult().getData().getLife().getInfo() .getYundong().get(0); String wuran = jsonbean.getResult().getData().getLife().getInfo() .getChuanyi().get(0); String ziwaixian = jsonbean.getResult().getData().getLife() .getInfo().getZiwaixian().get(0); String xiche = jsonbean.getResult().getData().getLife().getInfo() .getXiche().get(0); String kongtiao = jsonbean.getResult().getData().getLife() .getInfo().getKongtiao().get(0); ArrayList<String> gridviewlist = new ArrayList<String>(); gridviewlist.add(xiche + "洗车"); gridviewlist.add("感冒" + ganmao); gridviewlist.add("紫外线强度" + ziwaixian); gridviewlist.add(yundong + "运动"); gridviewlist.add("污染" + wuran); gridviewlist.add("空调" + kongtiao); // 组装数据 bundleData.putString("Temperature", t); bundleData.putString("info", i); bundleData.putString("city_name", city); bundleData.putString("pm25", pm252); bundleData.putInt("curPm", curPm); bundleData.putInt("pm25index", pm25index); bundleData.putInt("level", level); bundleData.putString("time", time); bundleData.putStringArrayList("dayt", dayTemperatureList1); bundleData.putStringArrayList("nightt", nightTemperatureList1); bundleData.putStringArrayList("gvlist", gridviewlist); bundleData.putStringArrayList("week", weeklist1); bundleData.putStringArrayList("weatherid", weatherIdList1); bundleData.putStringArrayList("weatherinfo", weatherinfo1); bundleData.putStringArrayList("wind", wind1); } catch (Exception e) { e.printStackTrace(); } return bundleData; } }
3e1c6e2faeb23fb27dbb4b3660aa6d57363eaca8
1,538
java
Java
kogito-quarkus-parent/kogito-quarkus-rules-extension/kogito-quarkus-rules-integration-test-legacy/src/main/java/io/quarkus/it/kogito/drools/HelloRuleService.java
fjtirado/kogito-runtimes
6b0dfae7c62b6bb3eecce275e9a4a00e5a51ab6a
[ "Apache-2.0" ]
null
null
null
kogito-quarkus-parent/kogito-quarkus-rules-extension/kogito-quarkus-rules-integration-test-legacy/src/main/java/io/quarkus/it/kogito/drools/HelloRuleService.java
fjtirado/kogito-runtimes
6b0dfae7c62b6bb3eecce275e9a4a00e5a51ab6a
[ "Apache-2.0" ]
5
2020-06-17T19:51:41.000Z
2021-01-19T14:55:56.000Z
kogito-quarkus-parent/kogito-quarkus-rules-extension/kogito-quarkus-rules-integration-test-legacy/src/main/java/io/quarkus/it/kogito/drools/HelloRuleService.java
fjtirado/kogito-runtimes
6b0dfae7c62b6bb3eecce275e9a4a00e5a51ab6a
[ "Apache-2.0" ]
1
2020-07-07T18:14:55.000Z
2020-07-07T18:14:55.000Z
29.576923
81
0.697009
12,063
/* * Copyright 2021 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. */ package io.quarkus.it.kogito.drools; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import org.kie.kogito.rules.RuleUnit; import org.kie.kogito.rules.RuleUnitInstance; import org.kie.kogito.rules.units.SessionData; @ApplicationScoped public class HelloRuleService { @Inject @Named("simpleKS") RuleUnit<SessionData> ruleUnit; public String run() { Result result = new Result(); Person mark = new Person("Mark", 37); Person edson = new Person("Edson", 35); Person mario = new Person("Mario", 40); SessionData memory = new SessionData(); memory.add(result); memory.add(mark); memory.add(edson); memory.add(mario); RuleUnitInstance<SessionData> instance = ruleUnit.createInstance(memory); instance.fire(); return result.toString(); } }
3e1c6e706a08fed18ebf9b85e0cd2c3b00b118ed
8,050
java
Java
Internship/T2BLive/app/src/main/java/com/tollywood2bollywood/t2bliveapp/YoutubeFragment.java
alok722/android-code-backup
6ebba5520b8cf7325858314dc5f91b694fee9b0f
[ "MIT" ]
null
null
null
Internship/T2BLive/app/src/main/java/com/tollywood2bollywood/t2bliveapp/YoutubeFragment.java
alok722/android-code-backup
6ebba5520b8cf7325858314dc5f91b694fee9b0f
[ "MIT" ]
null
null
null
Internship/T2BLive/app/src/main/java/com/tollywood2bollywood/t2bliveapp/YoutubeFragment.java
alok722/android-code-backup
6ebba5520b8cf7325858314dc5f91b694fee9b0f
[ "MIT" ]
null
null
null
34.698276
109
0.632795
12,064
package com.tollywood2bollywood.t2bliveapp; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.webkit.JavascriptInterface; import android.webkit.WebChromeClient; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import android.widget.Toast; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link YoutubeFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link YoutubeFragment#newInstance} factory method to * create an instance of this fragment. */ public class YoutubeFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; String URL_CHANNAL = "https://www.youtube.com/channel/UCL6q9wxnfO9vm21FyAQavjw"; // TODO: Rename and change types of parameters private int mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public YoutubeFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment YoutubeFragment. */ // TODO: Rename and change types and number of parameters public static YoutubeFragment newInstance(int param1, String param2) { YoutubeFragment fragment = new YoutubeFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, ""+param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getInt(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } private float m_downX; View view; WebView webView; ProgressBar progressBar; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_youtube, container, false); webView = (WebView) view.findViewById(R.id.webView); progressBar = (ProgressBar) view.findViewById(R.id.progressBar); progressBar.setVisibility(View.GONE); initWebView(); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); webView.addJavascriptInterface(new WebAppInterface(getActivity()), "Android"); webView.loadUrl(URL_CHANNAL); return view; } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (Uri.parse(url).getHost().equals("www.example.com")) { // This is my web site, so do not override; let my WebView load the page return false; } // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } } public class WebAppInterface { Context mContext; /** Instantiate the interface and set the context */ WebAppInterface(Context c) { mContext = c; } /** Show a toast from the web page */ @JavascriptInterface public void showToast(String toast) { Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); } } private class MyWebChromeClient extends WebChromeClient { Context context; public MyWebChromeClient(Context context) { super(); this.context = context; } } private void initWebView() { webView.setWebChromeClient(new MyWebChromeClient(getActivity())); webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); progressBar.setVisibility(View.VISIBLE); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { webView.loadUrl(url); return true; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); progressBar.setVisibility(View.GONE); } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); progressBar.setVisibility(View.GONE); } }); webView.clearCache(true); webView.clearHistory(); webView.getSettings().setJavaScriptEnabled(true); webView.setHorizontalScrollBarEnabled(false); webView.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (event.getPointerCount() > 1) { //Multi touch detected return true; } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { // save the x m_downX = event.getX(); } break; case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: { // set x so that it doesn't move event.setLocation(m_downX, event.getY()); } break; } return false; } }); } /*@Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } }*/ @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
3e1c6e899501a68f0da8760b714df65bb5ca2b03
706
java
Java
compiler/fir/analysis-tests/testData/enhancement/signatureAnnotations/DefaultLongLiteral.java
Dimat112/kotlin
0c463d3260bb78afd8da308849e430162aab6cd9
[ "ECL-2.0", "Apache-2.0" ]
337
2020-05-14T00:40:10.000Z
2022-02-16T23:39:07.000Z
compiler/fir/analysis-tests/testData/enhancement/signatureAnnotations/DefaultLongLiteral.java
Dimat112/kotlin
0c463d3260bb78afd8da308849e430162aab6cd9
[ "ECL-2.0", "Apache-2.0" ]
92
2020-06-10T23:17:42.000Z
2020-09-25T10:50:13.000Z
compiler/fir/analysis-tests/testData/enhancement/signatureAnnotations/DefaultLongLiteral.java
Dimat112/kotlin
0c463d3260bb78afd8da308849e430162aab6cd9
[ "ECL-2.0", "Apache-2.0" ]
44
2020-05-17T10:11:11.000Z
2022-03-11T02:37:20.000Z
19.081081
60
0.644476
12,065
// FILE: A.java // ANDROID_ANNOTATIONS import kotlin.annotations.jvm.internal.*; public class A { public void first(@DefaultValue("0x1F") Long value) { } public void second(@DefaultValue("0X1F") Long value) { } public void third(@DefaultValue("0b1010") Long value) { } public void fourth(@DefaultValue("0B1010") Long value) { } } // FILE: B.java import kotlin.annotations.jvm.internal.*; public class B { public void first(@DefaultValue("0x") Long value) { } public void second(@DefaultValue("0xZZ") Long value) { } public void third(@DefaultValue("0b") Long value) { } public void fourth(@DefaultValue("0B1234") Long value) { } }
3e1c6faa04626419c5b1bb8fcf5826c43b834a17
3,604
java
Java
src/main/java/sibbo/bitmessage/network/protocol/MessageFactory.java
ISibboI/JBitmessage
d316a395839f2cbdb50ded3b0b89254f2342dd4a
[ "MIT" ]
3
2016-03-10T08:41:44.000Z
2018-12-16T07:57:58.000Z
src/main/java/sibbo/bitmessage/network/protocol/MessageFactory.java
ISibboI/JBitmessage
d316a395839f2cbdb50ded3b0b89254f2342dd4a
[ "MIT" ]
null
null
null
src/main/java/sibbo/bitmessage/network/protocol/MessageFactory.java
ISibboI/JBitmessage
d316a395839f2cbdb50ded3b0b89254f2342dd4a
[ "MIT" ]
null
null
null
40.044444
117
0.839345
12,066
package sibbo.bitmessage.network.protocol; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.util.Collection; import org.bouncycastle.jce.interfaces.ECPublicKey; public abstract class MessageFactory { /** * Creates a new message factory that implements the given protocol version. * * @param version * The protocol version. * @return A message factory creating objects fitting to the given protocol * version. */ public static final MessageFactory getFactoryByVersion(int version) { switch (version) { case 1: return new V1MessageFactory(); default: return null; } } public abstract AddrMessage createAddrMessage(Collection<NetworkAddressMessage> addresses); public abstract BaseMessage createBaseMessage(P2PMessage message); public abstract EncryptedMessage createEncryptedMessage(byte[] iv, ECPublicKey key, byte[] encrypted, byte[] mac); public abstract GetdataMessage createGetdataMessage(Collection<InventoryVectorMessage> inv); public abstract InventoryVectorMessage createInventoryVectorMessage(byte[] hash); public abstract InvMessage createInvMessage(Collection<InventoryVectorMessage> inv); public abstract NodeServicesMessage createNodeServicesMessage(long services); public abstract SimpleNetworkAddressMessage createSimpleNetworkAddressMessage(NodeServicesMessage services, InetAddress address, int port); public abstract VariableLengthIntegerListMessage createVariableLengthIntegerListMessage(long[] streams); public abstract VariableLengthIntegerMessage createVariableLengthIntegerMessage(long l); public abstract VariableLengthStringMessage createVariableLengthStringMessage(String userAgent); public abstract VerackMessage createVerackMessage(); public abstract VersionMessage createVersionMessage(NodeServicesMessage services, long time, SimpleNetworkAddressMessage receiver, SimpleNetworkAddressMessage sender, long nonce, String userAgent, long[] streams); public abstract BaseMessage parseBaseMessage(InputStream in, int length) throws IOException, ParsingException; public abstract BehaviorMessage parseBehaviorMessage(InputBuffer b) throws IOException, ParsingException; public abstract EncryptedMessage parseEncryptedMessage(InputBuffer b) throws IOException, ParsingException; public abstract InventoryVectorMessage parseInventoryVectorMessage(InputBuffer b) throws IOException, ParsingException; public abstract MailMessage parseMailMessage(InputBuffer b) throws IOException, ParsingException; public abstract NetworkAddressMessage parseNetworkAddressMessage(InputBuffer b) throws IOException, ParsingException; public abstract NodeServicesMessage parseNodeServicesMessage(InputBuffer b) throws IOException, ParsingException; public abstract P2PMessage parseP2PMessage(String command, InputBuffer buffer) throws ParsingException, IOException; public abstract SimpleNetworkAddressMessage parseSimpleNetworkAddressMessage(InputBuffer b) throws IOException, ParsingException; public abstract UnencryptedMsgMessage parseUnencryptedMsgMessage(InputBuffer b) throws IOException, ParsingException; public abstract VariableLengthIntegerListMessage parseVariableLengthIntegerListMessage(InputBuffer b) throws IOException, ParsingException; public abstract VariableLengthIntegerMessage parseVariableLengthIntegerMessage(InputBuffer b) throws IOException, ParsingException; public abstract VariableLengthStringMessage parseVariableLengthStringMessage(InputBuffer b) throws IOException, ParsingException; }
3e1c7025a2b863127a491dd6498b23b47ac49cb4
7,299
java
Java
_/9290OS_05_code/src/core/src/com/csharks/thrustcopter/MenuScene.java
paullewallencom/libgdx-978-1-7843-9929-0
398b9924abfb6a8c0bf0bbeab033759e6971e216
[ "Apache-2.0" ]
null
null
null
_/9290OS_05_code/src/core/src/com/csharks/thrustcopter/MenuScene.java
paullewallencom/libgdx-978-1-7843-9929-0
398b9924abfb6a8c0bf0bbeab033759e6971e216
[ "Apache-2.0" ]
null
null
null
_/9290OS_05_code/src/core/src/com/csharks/thrustcopter/MenuScene.java
paullewallencom/libgdx-978-1-7843-9929-0
398b9924abfb6a8c0bf0bbeab033759e6971e216
[ "Apache-2.0" ]
null
null
null
30.668067
69
0.705165
12,067
package com.csharks.thrustcopter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.actions.MoveToAction; import com.badlogic.gdx.scenes.scene2d.ui.CheckBox; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Slider; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; public class MenuScene extends BaseScene { private Stage stage; private Image screenBg; private Skin skin; private Image title; private Label helpTip; private Table table; private Table options; private Table exit; private CheckBox muteCheckBox; private Slider volumeSlider; private TextButton backButton; private TextButton playButton; private TextButton optionsButton; private TextButton exitButton; private TextButton yesButton; private TextButton noButton; private boolean menuShown; private boolean exitShown; public MenuScene(ThrustCopter thrustCopter) { super(thrustCopter); stage = new Stage(game.viewport); Gdx.input.setInputProcessor(stage); skin = new Skin(Gdx.files.internal("uiskin.json")); screenBg = new Image(game.atlas.findRegion("background")); title= new Image(game.manager.get("title.png", Texture.class)); helpTip=new Label("Tap around the plane to move it!",skin); helpTip.setColor(Color.NAVY); table=new Table().debug(); playButton=new TextButton("PLAY GAME", skin); table.add(playButton).padBottom(10); table.row(); optionsButton=new TextButton("SOUND OPTIONS", skin); table.add(optionsButton).padBottom(10); table.row(); table.add(new TextButton("LEADERBOARD", skin)).padBottom(10); table.row(); exitButton=new TextButton("EXIT GAME", skin); table.add(exitButton); table.setPosition(400, -200); options=new Table().debug(); Label soundTitle=new Label("SOUND OPTIONS",skin); soundTitle.setColor(Color.NAVY); options.add(soundTitle).padBottom(25).colspan(2); options.row(); muteCheckBox = new CheckBox(" MUTE ALL", skin); options.add(muteCheckBox).padBottom(10).colspan(2); options.row(); options.add(new Label("VOLUME ",skin)).padBottom(10).padRight(10); volumeSlider = new Slider(0, 2, 0.2f, false, skin); options.add(volumeSlider).padTop(10).padBottom(20); options.row(); backButton=new TextButton("BACK", skin); options.add(backButton).colspan(2).padTop(20); options.setPosition(400, -200); muteCheckBox.setChecked(!game.soundEnabled); volumeSlider.setValue(game.soundVolume); exit=new Table().debug(); Label exitTitle=new Label("Confirm Exit",skin); exitTitle.setColor(Color.NAVY); exit.add(exitTitle).padBottom(25).colspan(2); exit.row(); yesButton=new TextButton("YES", skin); exit.add(yesButton).padBottom(20); noButton=new TextButton("NO", skin); exit.add(noButton).padBottom(20); exit.setPosition(400, -200); stage.addActor(screenBg); stage.addActor(title); stage.addActor(helpTip); stage.addActor(table); stage.addActor(options); stage.addActor(exit); playButton.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { game.setScreen(new ThrustCopterScene(game)); } }); optionsButton.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { showMenu(false); } }); exitButton.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { Gdx.app.exit(); // or System.exit(0); } }); yesButton.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { Gdx.app.exit(); // or System.exit(0); } }); noButton.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { showExit(!exitShown); } }); volumeSlider.addListener(new ChangeListener() { public void changed (ChangeEvent event, Actor actor) { game.soundVolume=volumeSlider.getValue(); } }); muteCheckBox.addListener(new ChangeListener() { public void changed (ChangeEvent event, Actor actor) { game.soundEnabled=!muteCheckBox.isChecked(); } }); backButton.addListener(new ClickListener(){ @Override public void clicked(InputEvent event, float x, float y) { showMenu(true); } }); } @Override public void show() { title.setPosition(400-title.getWidth()/2, 450); helpTip.setPosition(400-helpTip.getWidth()/2, 30); MoveToAction actionMove = Actions.action(MoveToAction.class); actionMove.setPosition(400-title.getWidth()/2, 320); actionMove.setDuration(2); actionMove.setInterpolation(Interpolation.elasticOut); title.addAction(actionMove); showMenu(true); } private void showMenu(boolean flag) { MoveToAction actionMove1 = Actions.action(MoveToAction.class);//out actionMove1.setPosition(400, -200); actionMove1.setDuration(1); actionMove1.setInterpolation(Interpolation.swingIn); MoveToAction actionMove2 = Actions.action(MoveToAction.class);//in actionMove2.setPosition(400, 190); actionMove2.setDuration(1.5f); actionMove2.setInterpolation(Interpolation.swing); if(flag){ table.addAction(actionMove2); options.addAction(actionMove1); }else{ options.addAction(actionMove2); table.addAction(actionMove1); } menuShown=flag; exitShown=false; } private void showExit(boolean flag) { MoveToAction actionMove1 = Actions.action(MoveToAction.class);//out actionMove1.setPosition(400, -200); actionMove1.setDuration(1); actionMove1.setInterpolation(Interpolation.swingIn); MoveToAction actionMove2 = Actions.action(MoveToAction.class);//in actionMove2.setPosition(400, 190); actionMove2.setDuration(1.5f); actionMove2.setInterpolation(Interpolation.swing); if(flag){ exit.addAction(actionMove2); table.addAction(actionMove1); }else{ table.addAction(actionMove2); exit.addAction(actionMove1); } exitShown=flag; } @Override public void render(float delta) { // Clear the screen Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Show the loading screen stage.act(); stage.draw(); //Table.drawDebug(stage); super.render(delta); } @Override protected void handleBackPress() { if(!menuShown){ showMenu(!menuShown); }else{ showExit(!exitShown); } } @Override public void dispose () { stage.dispose(); skin.dispose(); } }
3e1c708b74be2cc64b3ca5b9c8d7cec19dc567c2
973
java
Java
MS_LIBRARY/src/org/yeastrc/qc_plots/dao/QCPlotDataDAO.java
yeastrc/msdapl
0239d2dc34a41702eec39ee4cf1de95593044777
[ "Apache-2.0" ]
4
2017-04-13T21:04:57.000Z
2021-07-16T19:42:16.000Z
MS_LIBRARY/src/org/yeastrc/qc_plots/dao/QCPlotDataDAO.java
yeastrc/msdapl
0239d2dc34a41702eec39ee4cf1de95593044777
[ "Apache-2.0" ]
null
null
null
MS_LIBRARY/src/org/yeastrc/qc_plots/dao/QCPlotDataDAO.java
yeastrc/msdapl
0239d2dc34a41702eec39ee4cf1de95593044777
[ "Apache-2.0" ]
2
2016-06-16T17:16:40.000Z
2017-07-27T18:48:45.000Z
23.731707
120
0.676259
12,068
package org.yeastrc.qc_plots.dao; import org.yeastrc.qc_plots.dto.QCPlotDataDTO; /** * * for table qc_plot_data */ public interface QCPlotDataDAO { /** * Save the data or update an existing record with the same experiment id and plot type (primary key) * @param qcPlotDataDTO * @return */ public int saveOrUpdate(QCPlotDataDTO qcPlotDataDTO); /** * @param experimentId * @param plotType * @return */ public QCPlotDataDTO load(int experimentId, String plotType); /** * @param experimentId * @param plotType * @param dataVersion * @return */ public QCPlotDataDTO loadFromExperimentIdPlotTypeAndDataVersion(int experimentId, String plotType, int dataVersion); /** * Delete the records for this experiment Id and this plotType * @param experimentId * @param plotType */ public void deleteForExperimentIdPlotType( int experimentId, String plotType ); }
3e1c70f8629e293039497dcee04afdb82843c798
663
java
Java
src/main/java/org/kpax/winfoom/proxy/ProxyType.java
fvgh/winfoom
ea4d3f3d834956ba56c02600a01a8813b0b95716
[ "Apache-2.0" ]
null
null
null
src/main/java/org/kpax/winfoom/proxy/ProxyType.java
fvgh/winfoom
ea4d3f3d834956ba56c02600a01a8813b0b95716
[ "Apache-2.0" ]
null
null
null
src/main/java/org/kpax/winfoom/proxy/ProxyType.java
fvgh/winfoom
ea4d3f3d834956ba56c02600a01a8813b0b95716
[ "Apache-2.0" ]
null
null
null
18.416667
73
0.547511
12,069
package org.kpax.winfoom.proxy; /** * The contract of any proxy type. */ public interface ProxyType { /** * @return {@code true} iff the proxy type is SOCKS4. */ boolean isSocks4(); /** * @return {@code true} iff the proxy type is SOCKS5. */ boolean isSocks5(); /** * @return {@code true} iff the proxy type is SOCKS (version 4 or 5). */ default boolean isSocks() { return isSocks4() || isSocks5(); } /** * @return {@code true} iff the proxy type is HTTP. */ boolean isHttp(); /** * @return {@code true} iff there is no proxy. */ boolean isDirect(); }
3e1c7100b2bf0a95a03c77e7111448aa709b50a2
1,008
java
Java
with-bai-web-admin/src/main/java/com/with/bai/admin/controller/IndexController.java
slhczxz/withbai
d43da872f136216b5a1e4e120a650e302f66594e
[ "Apache-2.0" ]
null
null
null
with-bai-web-admin/src/main/java/com/with/bai/admin/controller/IndexController.java
slhczxz/withbai
d43da872f136216b5a1e4e120a650e302f66594e
[ "Apache-2.0" ]
null
null
null
with-bai-web-admin/src/main/java/com/with/bai/admin/controller/IndexController.java
slhczxz/withbai
d43da872f136216b5a1e4e120a650e302f66594e
[ "Apache-2.0" ]
null
null
null
30.545455
79
0.763889
12,070
package com.with.bai.admin.controller; import com.with.bai.admin.service.IndexService; import com.with.bai.dto.Info; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; @Controller @RequestMapping(value="info") public class IndexController { @Autowired IndexService indexService; @ModelAttribute public Info getInfo(HttpServletRequest request){ Info info=indexService.getInfo(); request.getSession().setAttribute("fundCount",info.getOrderCount()); request.getSession().setAttribute("registCount",info.getRegistCount()); return info; } @RequestMapping(value="index",method= RequestMethod.GET) public String index(){ return "index"; } }
3e1c71b04ce9f33f379162de7b1c8014bf1d9974
249
java
Java
src/main/java/repositories/ProductRepo.java
MrRisoni/commercify
fed476e4f84d309794add69ab233c684f028dc40
[ "MIT" ]
null
null
null
src/main/java/repositories/ProductRepo.java
MrRisoni/commercify
fed476e4f84d309794add69ab233c684f028dc40
[ "MIT" ]
null
null
null
src/main/java/repositories/ProductRepo.java
MrRisoni/commercify
fed476e4f84d309794add69ab233c684f028dc40
[ "MIT" ]
null
null
null
24.9
69
0.84739
12,071
package repositories; import entity.product.Products; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface ProductRepo extends CrudRepository<Products,Long> { }
3e1c7217a98911b0942e5c6a326eb63f87d6db62
4,172
java
Java
grib/src/main/java/ucar/grib/grib1/Grib1EndSection.java
julienchastang/thredds
f902e5a3573583a9b87f1d3c7d2ff27a121289fe
[ "NetCDF" ]
1
2019-01-22T11:30:51.000Z
2019-01-22T11:30:51.000Z
grib/src/main/java/ucar/grib/grib1/Grib1EndSection.java
julienchastang/thredds
f902e5a3573583a9b87f1d3c7d2ff27a121289fe
[ "NetCDF" ]
null
null
null
grib/src/main/java/ucar/grib/grib1/Grib1EndSection.java
julienchastang/thredds
f902e5a3573583a9b87f1d3c7d2ff27a121289fe
[ "NetCDF" ]
null
null
null
33.111111
95
0.633749
12,072
/* * Copyright 1998-2009 University Corporation for Atmospheric Research/Unidata * * Portions of this software were developed by the Unidata Program at the * University Corporation for Atmospheric Research. * * Access and use of this software shall impose the following obligations * and understandings on the user. The user is granted the right, without * any fee or cost, to use, copy, modify, alter, enhance and distribute * this software, and any derivative works thereof, and its supporting * documentation for any purpose whatsoever, provided that this entire * notice appears in all copies of the software, derivative works and * supporting documentation. Further, UCAR requests that the user credit * UCAR/Unidata in any publications that result from the use of this * software or in any product that includes this software. The names UCAR * and/or Unidata, however, may not be used in any advertising or publicity * to endorse or promote any products or commercial entity unless specific * written permission is obtained from UCAR/Unidata. The user also * understands that UCAR/Unidata is not obligated to provide the user with * any support, consulting, training or assistance of any kind with regard * to the use, operation and performance of this software nor to provide * the user with any updates, revisions, new versions or "bug fixes." * * THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE. */ // $Id: Grib1EndSection.java,v 1.8 2005/12/02 23:53:42 rkambic Exp $ package ucar.grib.grib1; import ucar.grib.*; /* * Grib1EndSection.java 1.0 09/30/2004 * @author Robb Kambic * */ import ucar.unidata.io.RandomAccessFile; import java.io.IOException; /** * A class that represents the EndSection of a GRIB1 product. * */ final class Grib1EndSection { /* * was the grib endding 7777 found. */ /** _more_ */ private boolean endFound = false; /* * how long was the ending, should be 4 bytes. */ /** _more_ */ private int length = 0; // *** constructors ******************************************************* /** * Constructs a <tt>Grib1EndSection</tt> object from a byteBuffer. * * @param raf RandomAccessFile with EndSection content * * @throws IOException */ public Grib1EndSection(RandomAccessFile raf) throws IOException { int match = 0; while (raf.getFilePointer() < raf.length()) { // code must be "7" "7" "7" "7" byte c = raf.readByte(); //System.out.println( "c=" + (char) c ); length++; if (c == '7') { match += 1; //System.out.println( "seekEnd raf.getFilePointer()=" + raf.getFilePointer() ); } else { //System.out.println( "c=" + (char) c ); match = 0; /* Needed to protect against bad ending case. */ } if (match == 4) { endFound = true; //System.out.println( "7777 ending found" ); break; } } } // end Grib1EndSection /** * Get ending flag for Grib record. * * @return true if "7777" found */ public final boolean getEndFound() { return endFound; } // --Commented out by Inspection START (11/17/05 1:32 PM): // /** // * how long was the ending, should be 4 bytes. // * @return int // */ // public static final int getLength() // { // return length; // } // --Commented out by Inspection STOP (11/17/05 1:32 PM) } // end Grib1EndSection
3e1c72e57c83409f3a66107bde0d1ef2eda2acb9
7,990
java
Java
tests/test-loginservice/src/test/java/org/eclipse/jetty/DatabaseLoginServiceTestServer.java
leornado/jetty.project
9b2250c05dcf498d65e3bb1372a74b33b75a3014
[ "Apache-2.0" ]
null
null
null
tests/test-loginservice/src/test/java/org/eclipse/jetty/DatabaseLoginServiceTestServer.java
leornado/jetty.project
9b2250c05dcf498d65e3bb1372a74b33b75a3014
[ "Apache-2.0" ]
1
2022-02-11T03:52:24.000Z
2022-02-11T03:52:24.000Z
tests/test-loginservice/src/test/java/org/eclipse/jetty/DatabaseLoginServiceTestServer.java
mohan-chinnappan-n/jetty.project
1753dec7205784025fbe4d01af4ba9de2b134bfb
[ "Apache-2.0" ]
null
null
null
32.088353
112
0.648561
12,073
// // ======================================================================== // Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // // This program and the accompanying materials are made available under // the terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0 // // This Source Code may also be made available under the following // Secondary Licenses when the conditions for such availability set // forth in the Eclipse Public License, v. 2.0 are satisfied: // the Apache License v2.0 which is available at // https://www.apache.org/licenses/LICENSE-2.0 // // SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 // ======================================================================== // package org.eclipse.jetty; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URI; import java.net.URLDecoder; import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.security.ConstraintMapping; import org.eclipse.jetty.security.ConstraintSecurityHandler; import org.eclipse.jetty.security.LoginService; import org.eclipse.jetty.security.authentication.BasicAuthenticator; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.toolchain.test.FS; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.security.Constraint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.MariaDBContainer; import org.testcontainers.containers.output.Slf4jLogConsumer; /** * DatabaseLoginServiceTestServer */ public class DatabaseLoginServiceTestServer { private static final Logger LOG = LoggerFactory.getLogger(DatabaseLoginServiceTestServer.class); private static final Logger MARIADB_LOG = LoggerFactory.getLogger("org.eclipse.jetty.security.MariaDbLogs"); static MariaDBContainer MARIA_DB; protected static final String MARIA_DB_NAME = "lstest"; protected static final String MARIA_DB_USER = "beer"; protected static final String MARIA_DB_PASSWORD = "pacific_ale"; public static String MARIA_DB_DRIVER_CLASS; public static String MARIA_DB_URL; public static String MARIA_DB_FULL_URL; protected Server _server; protected static String _protocol; protected static URI _baseUri; protected LoginService _loginService; protected String _resourceBase; protected TestHandler _handler; protected static String _requestContent; protected static File _dbRoot; static { try { MARIA_DB = new MariaDBContainer("mariadb:" + System.getProperty("mariadb.docker.version", "10.3.6")) .withUsername(MARIA_DB_USER) .withPassword(MARIA_DB_PASSWORD) .withDatabaseName(MARIA_DB_NAME); MARIA_DB = (MariaDBContainer)MARIA_DB.withInitScript("createdb.sql"); MARIA_DB = (MariaDBContainer)MARIA_DB.withLogConsumer(new Slf4jLogConsumer(MARIADB_LOG)); MARIA_DB.start(); String containerIpAddress = MARIA_DB.getContainerIpAddress(); int mariadbPort = MARIA_DB.getMappedPort(3306); MARIA_DB_URL = MARIA_DB.getJdbcUrl(); MARIA_DB_FULL_URL = MARIA_DB_URL + "?user=" + MARIA_DB_USER + "&password=" + MARIA_DB_PASSWORD; MARIA_DB_DRIVER_CLASS = MARIA_DB.getDriverClassName(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } public static class TestHandler extends AbstractHandler { private final String _resourcePath; private String _requestContent; public TestHandler(String repositoryPath) { _resourcePath = repositoryPath; } @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (baseRequest.isHandled()) { return; } OutputStream out = null; if (baseRequest.getMethod().equals("PUT")) { baseRequest.setHandled(true); File file = new File(_resourcePath, URLDecoder.decode(request.getPathInfo(), "utf-8")); FS.ensureDirExists(file.getParentFile()); out = new FileOutputStream(file); response.setStatus(HttpServletResponse.SC_CREATED); } if (baseRequest.getMethod().equals("POST")) { baseRequest.setHandled(true); out = new ByteArrayOutputStream(); response.setStatus(HttpServletResponse.SC_OK); } if (out != null) { try (ServletInputStream in = request.getInputStream()) { IO.copy(in, out); } finally { out.close(); } if (!(out instanceof FileOutputStream)) _requestContent = out.toString(); } } public String getRequestContent() { return _requestContent; } } public DatabaseLoginServiceTestServer() { _server = new Server(0); } public void setLoginService(LoginService loginService) { _loginService = loginService; } public void setResourceBase(String resourceBase) { _resourceBase = resourceBase; } public void start() throws Exception { configureServer(); _server.start(); //_server.dumpStdErr(); _baseUri = _server.getURI(); } public void stop() throws Exception { _server.stop(); } public URI getBaseUri() { return _baseUri; } public TestHandler getTestHandler() { return _handler; } public Server getServer() { return _server; } protected void configureServer() throws Exception { _protocol = "http"; _server.addBean(_loginService); ConstraintSecurityHandler security = new ConstraintSecurityHandler(); _server.setHandler(security); Constraint constraint = new Constraint(); constraint.setName("auth"); constraint.setAuthenticate(true); constraint.setRoles(new String[]{"user", "admin"}); ConstraintMapping mapping = new ConstraintMapping(); mapping.setPathSpec("/*"); mapping.setConstraint(constraint); Set<String> knownRoles = new HashSet<>(); knownRoles.add("user"); knownRoles.add("admin"); security.setConstraintMappings(Collections.singletonList(mapping), knownRoles); security.setAuthenticator(new BasicAuthenticator()); security.setLoginService(_loginService); ServletContextHandler root = new ServletContextHandler(); root.setContextPath("/"); root.setResourceBase(_resourceBase); ServletHolder servletHolder = new ServletHolder(new DefaultServlet()); servletHolder.setInitParameter("gzip", "true"); root.addServlet(servletHolder, "/*"); _handler = new TestHandler(_resourceBase); security.setHandler(new HandlerList(_handler, root)); } }
3e1c746199b2c75d657b6860ed713c885a7be019
1,504
java
Java
src/main/java/com/boyuyun/base/sso/entity/RoleUserType.java
yunhai281/baseProject
df66786b1a98d7e9c0fdbf009606c46c54706885
[ "Apache-2.0" ]
null
null
null
src/main/java/com/boyuyun/base/sso/entity/RoleUserType.java
yunhai281/baseProject
df66786b1a98d7e9c0fdbf009606c46c54706885
[ "Apache-2.0" ]
null
null
null
src/main/java/com/boyuyun/base/sso/entity/RoleUserType.java
yunhai281/baseProject
df66786b1a98d7e9c0fdbf009606c46c54706885
[ "Apache-2.0" ]
null
null
null
22.117647
63
0.74734
12,074
package com.boyuyun.base.sso.entity; import java.io.Serializable; import java.util.List; import com.boyuyun.common.annotation.ForViewUse; import com.dhcc.common.db.page.Page; /** * 年级 * @author zhy */ public class RoleUserType extends Page implements Serializable{ private String roleId; private String userType; private String goverType; @ForViewUse private String userTypeName; @ForViewUse private List<RoleUser> userList; @ForViewUse private List<RoleUserOrg> orgList; @ForViewUse private String addOrUpdate = "add"; public String getRoleId() { return roleId; } public void setRoleId(String roleId) { this.roleId = roleId; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getGoverType() { return goverType; } public void setGoverType(String goverType) { this.goverType = goverType; } public String getUserTypeName() { return userTypeName; } public void setUserTypeName(String userTypeName) { this.userTypeName = userTypeName; } public List<RoleUser> getUserList() { return userList; } public void setUserList(List<RoleUser> userList) { this.userList = userList; } public String getAddOrUpdate() { return addOrUpdate; } public void setAddOrUpdate(String addOrUpdate) { this.addOrUpdate = addOrUpdate; } public List<RoleUserOrg> getOrgList() { return orgList; } public void setOrgList(List<RoleUserOrg> orgList) { this.orgList = orgList; } }
3e1c74bcc8a1f3ac15f4c9dc5212aa0267d5c587
923
java
Java
smart-cloud-starter/smart-cloud-starter-web/src/main/java/org/smartframework/cloud/starter/web/exception/strategy/HttpMediaTypeNotSupportedExceptionHandlerStrategy.java
widon/smart-cloud
a80f94899c89ac996184a64b6558ba91ec414d9f
[ "Apache-2.0" ]
null
null
null
smart-cloud-starter/smart-cloud-starter-web/src/main/java/org/smartframework/cloud/starter/web/exception/strategy/HttpMediaTypeNotSupportedExceptionHandlerStrategy.java
widon/smart-cloud
a80f94899c89ac996184a64b6558ba91ec414d9f
[ "Apache-2.0" ]
null
null
null
smart-cloud-starter/smart-cloud-starter-web/src/main/java/org/smartframework/cloud/starter/web/exception/strategy/HttpMediaTypeNotSupportedExceptionHandlerStrategy.java
widon/smart-cloud
a80f94899c89ac996184a64b6558ba91ec414d9f
[ "Apache-2.0" ]
1
2022-03-13T12:38:16.000Z
2022-03-13T12:38:16.000Z
34.185185
101
0.832069
12,075
package org.smartframework.cloud.starter.web.exception.strategy; import org.smartframework.cloud.common.pojo.enums.ReturnCodeEnum; import org.smartframework.cloud.common.pojo.vo.RespHeadVO; import org.smartframework.cloud.starter.core.business.util.RespHeadUtil; import org.smartframework.cloud.starter.web.exception.IExceptionHandlerStrategy; import org.smartframework.cloud.utility.spring.I18NUtil; import org.springframework.web.HttpMediaTypeNotSupportedException; /** * @desc http请求数据格式不支持异常转换 * @author liyulin * @date 2019/10/29 */ public class HttpMediaTypeNotSupportedExceptionHandlerStrategy implements IExceptionHandlerStrategy { @Override public boolean match(Throwable e) { return e instanceof HttpMediaTypeNotSupportedException; } @Override public RespHeadVO transRespHead(Throwable e) { return RespHeadUtil.of(ReturnCodeEnum.UNSUPPORTED_MEDIA_TYPE, I18NUtil.getMessage(e.getMessage())); } }
3e1c74ea3759ebdb7f2195e3b9a6520239737e09
6,032
java
Java
webdrivermanager-master/webdrivermanager-master/src/test/java/io/github/bonigarcia/wdm/test/TargetTest.java
reachtomrinal/UI_Automation_Framework
e432486e958d7687a66ab7d1196a93156ff97484
[ "Apache-2.0" ]
1
2021-08-16T17:54:08.000Z
2021-08-16T17:54:08.000Z
webdrivermanager-master/webdrivermanager-master/src/test/java/io/github/bonigarcia/wdm/test/TargetTest.java
reachtomrinal/UI_Automation_Framework
e432486e958d7687a66ab7d1196a93156ff97484
[ "Apache-2.0" ]
null
null
null
webdrivermanager-master/webdrivermanager-master/src/test/java/io/github/bonigarcia/wdm/test/TargetTest.java
reachtomrinal/UI_Automation_Framework
e432486e958d7687a66ab7d1196a93156ff97484
[ "Apache-2.0" ]
1
2021-05-14T04:27:01.000Z
2021-05-14T04:27:01.000Z
38.909677
132
0.592273
12,076
/* * (C) Copyright 2016 Boni Garcia (http://bonigarcia.github.io/) * * 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 io.github.bonigarcia.wdm.test; import static io.github.bonigarcia.wdm.DriverManagerType.CHROME; import static io.github.bonigarcia.wdm.DriverManagerType.EDGE; import static io.github.bonigarcia.wdm.DriverManagerType.FIREFOX; import static io.github.bonigarcia.wdm.DriverManagerType.OPERA; import static io.github.bonigarcia.wdm.DriverManagerType.PHANTOMJS; import static java.lang.invoke.MethodHandles.lookup; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.slf4j.LoggerFactory.getLogger; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import org.slf4j.Logger; import io.github.bonigarcia.wdm.Downloader; import io.github.bonigarcia.wdm.DriverManagerType; /** * Target folder test. * * @author Boni Garcia (envkt@example.com) * @since 1.4.1 */ @RunWith(Parameterized.class) public class TargetTest { final Logger log = getLogger(lookup().lookupClass()); @Parameter(0) public String version; @Parameter(1) public String url; @Parameter(2) public String target; @Parameter(3) public DriverManagerType driverManagerType; @Parameters(name = "{index}: {0}") public static Collection<Object[]> data() { return asList(new Object[][] { // Chrome Linux { "2.21", "http://chromedriver.storage.googleapis.com/2.21/chromedriver_linux64.zip", "/chromedriver/linux64/2.21/chromedriver_linux64.zip", CHROME }, // Opera Linux { "0.2.2", "https://github.com/operasoftware/operachromiumdriver/releases/download/v0.2.2/operadriver_linux64.zip", "/operadriver/linux64/0.2.2/operadriver_linux64.zip", OPERA }, // PhantomJS Linux { "2.1.1", "https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2", "/phantomjs/linux-x86_64/2.1.1/phantomjs-2.1.1-linux-x86_64.tar.bz2", PHANTOMJS }, // PhantomJS Windows { "2.1.1", "https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-windows.zip", "/phantomjs/windows/2.1.1/phantomjs-2.1.1-windows.zip", PHANTOMJS }, // PhantomJS Mac OS X { "2.1.1", "https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-macosx.zip", "/phantomjs/macosx/2.1.1/phantomjs-2.1.1-macosx.zip", PHANTOMJS }, // Edge Windows #1 { "8D0D08CF-790D-4586-B726-C6469A9ED49C", "https://download.microsoft.com/download/1/4/1/14156DA0-D40F-460A-B14D-1B264CA081A5/MicrosoftWebDriver.exe", "/MicrosoftWebDriver/8D0D08CF-790D-4586-B726-C6469A9ED49C/MicrosoftWebDriver.exe", EDGE }, // Edge Windows #2 { "3.14361", "https://download.microsoft.com/download/1/4/1/14156DA0-D40F-460A-B14D-1B264CA081A5/MicrosoftWebDriver.exe", "/MicrosoftWebDriver/3.14361/MicrosoftWebDriver.exe", EDGE }, // Edge Windows #3 { "172.16.58.3", "https://az813057.vo.msecnd.net/webdriver/msedgedriver_x86/msedgedriver.exe", "/msedgedriver/x64/75.0.137.0/msedgedriver.exe", EDGE }, // Firefox Mac OS X { "0.6.2", "https://github.com/jgraham/wires/releases/download/v0.6.2/wires-0.6.2-OSX.gz", "/wires/osx/0.6.2/wires-0.6.2-OSX.gz", FIREFOX }, { "0.3.0", "https://github.com/jgraham/wires/releases/download/0.3.0/wires-0.3.0-osx.tar.gz", "/wires/osx/0.3.0/wires-0.3.0-osx.tar.gz", FIREFOX }, // Firefox Linux { "0.6.2", "https://github.com/jgraham/wires/releases/download/v0.6.2/wires-0.6.2-linux64.gz", "/wires/linux64/0.6.2/wires-0.6.2-linux64.gz", FIREFOX }, // Firefox Linux #2 { "0.8.0", "https://github.com/mozilla/geckodriver/releases/download/v0.8.0/geckodriver-0.8.0-linux64.gz", "/geckodriver/linux64/0.8.0/geckodriver-0.8.0-linux64.gz", FIREFOX } }); } @Test public void testTarget() throws IOException { Downloader downloader = new Downloader(driverManagerType); String targetPath = downloader.getTargetPath(); File result = downloader.getTarget(version, new URL(url)); log.info("{}", result); log.info(targetPath + target); File fileReal = new File(targetPath + target); assertThat(result, equalTo(fileReal)); } }
3e1c75c2542000c304ed6d7d4bebca076615b8cd
844
java
Java
spring-boot-starter-sample/src/main/java/im/spent/sample/mapper/TeacherMapper.java
imspent/spring-boot-starter
38e240bcc41983a9c9ca2d871c6ecac33c211f2b
[ "Apache-2.0" ]
null
null
null
spring-boot-starter-sample/src/main/java/im/spent/sample/mapper/TeacherMapper.java
imspent/spring-boot-starter
38e240bcc41983a9c9ca2d871c6ecac33c211f2b
[ "Apache-2.0" ]
null
null
null
spring-boot-starter-sample/src/main/java/im/spent/sample/mapper/TeacherMapper.java
imspent/spring-boot-starter
38e240bcc41983a9c9ca2d871c6ecac33c211f2b
[ "Apache-2.0" ]
null
null
null
30.142857
98
0.613744
12,077
package im.spent.sample.mapper; import im.spent.sample.entity.Teacher; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper public interface TeacherMapper { @Delete("DELETE FROM teacher\n" + "WHERE id = #{id}") void delete(Long id); @Insert("INSERT INTO teacher(id, name, username, email, sex, create_time, update_time)\n" + "VALUES(#{id}, #{name}, #{username}, #{email}, #{sex}, #{createTime}, #{updateTime})") void insert(Teacher teacher); @Select("SELECT id, name, username, email, sex, create_time, update_time\n" + "FROM teacher") List<Teacher> select(); @Update("UPDATE teacher\n" + "SET name = #{name}, email = #{email}, sex = #{sex}, update_time = #{updateTime}\n" + "WHERE id = #{id}") void update(Teacher teacher); }
3e1c76a43f12d1d51dc4f885e149fa6bdc7637b6
3,229
java
Java
src/main/java/de/domisum/lib/auxiliumspigot/data/container/block/BlockCollection.java
domisum/AuxiliumSpigotLib
8a958f0cbff8d055aa4d16d7c72d21164b5068a6
[ "MIT" ]
1
2017-02-11T10:06:39.000Z
2017-02-11T10:06:39.000Z
src/main/java/de/domisum/lib/auxiliumspigot/data/container/block/BlockCollection.java
domisum/AuxiliumSpigotLib
8a958f0cbff8d055aa4d16d7c72d21164b5068a6
[ "MIT" ]
null
null
null
src/main/java/de/domisum/lib/auxiliumspigot/data/container/block/BlockCollection.java
domisum/AuxiliumSpigotLib
8a958f0cbff8d055aa4d16d7c72d21164b5068a6
[ "MIT" ]
1
2020-01-02T10:19:36.000Z
2020-01-02T10:19:36.000Z
23.064286
105
0.713534
12,078
package de.domisum.lib.auxiliumspigot.data.container.block; import de.domisum.lib.auxilium.data.container.tuple.Duo; import de.domisum.lib.auxilium.util.java.annotations.API; import de.domisum.lib.auxiliumspigot.data.container.abstracts.AbstractBlock; import de.domisum.lib.auxiliumspigot.util.BlockUtil; import org.bukkit.Location; import org.bukkit.Material; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; @API public class BlockCollection { // CONSTANTS private static final AbstractBlock DEFAULT_BLOCK = new AbstractBlock(Material.AIR, (byte) 0); // PROPERTIES private Map<BlockCoordinate, AbstractBlock> blocks = new HashMap<>(); // INIT @API public BlockCollection() { } @API public BlockCollection(Map<BlockCoordinate, AbstractBlock> blocks) { this.blocks = blocks; } // GETTERS @API public Map<BlockCoordinate, AbstractBlock> getBlocks() { return this.blocks; } @API public AbstractBlock get(BlockCoordinate coordinate) { AbstractBlock block = this.blocks.get(coordinate); if(block != null) return block; return DEFAULT_BLOCK; } @API public boolean isSet(BlockCoordinate coordinate) { return this.blocks.containsKey(coordinate); } @API public Duo<BlockCoordinate> getBounds() { int minX = Integer.MAX_VALUE; int minY = Integer.MAX_VALUE; int minZ = Integer.MAX_VALUE; int maxX = Integer.MIN_VALUE; int maxY = Integer.MIN_VALUE; int maxZ = Integer.MIN_VALUE; for(Entry<BlockCoordinate, AbstractBlock> entry : this.blocks.entrySet()) { BlockCoordinate coord = entry.getKey(); if(coord.x < minX) minX = coord.x; if(coord.y < minY) minY = coord.y; if(coord.z < minZ) minZ = coord.z; if(coord.x > maxX) maxX = coord.x; if(coord.y > maxY) maxY = coord.y; if(coord.z > maxZ) maxZ = coord.z; } return new Duo<>(new BlockCoordinate(minX, minY, minZ), new BlockCoordinate(maxX, maxY, maxZ)); } // SETTERS @API public void set(BlockCoordinate coordinate, AbstractBlock block) { if(block == null) { this.blocks.remove(coordinate); return; } this.blocks.put(coordinate, block); } @API public void set(BlockCollection blockCollection) { for(Entry<BlockCoordinate, AbstractBlock> entry : blockCollection.blocks.entrySet()) this.blocks.put(entry.getKey(), entry.getValue()); } // BUILDING @SuppressWarnings("deprecation") @API public void buildAt(Location location) { Map<BlockCoordinate, AbstractBlock> fragileBlocks = new HashMap<>(); for(Entry<BlockCoordinate, AbstractBlock> entry : this.blocks.entrySet()) { if(!entry.getValue().material.isSolid()) { fragileBlocks.put(entry.getKey(), entry.getValue()); continue; } Location loc = location.clone().add(entry.getKey().x, entry.getKey().y, entry.getKey().z); BlockUtil.setMaterialAndData(loc.getBlock(), entry.getValue().material, entry.getValue().data, false); } for(Entry<BlockCoordinate, AbstractBlock> entry : fragileBlocks.entrySet()) { Location loc = location.clone().add(entry.getKey().x, entry.getKey().y, entry.getKey().z); BlockUtil.setMaterialAndData(loc.getBlock(), entry.getValue().material, entry.getValue().data, false); } } }
3e1c76b5fd6a2bad176328a01e696bc2cbc6dcdb
11,050
java
Java
server/eclipse-project/src/main/java/us/freeandfair/corla/model/ContestResult.java
rhelton21/colorado-rla
97b629a0de0d788155e35fce720ec7b207544df0
[ "RSA-MD" ]
1
2022-01-18T03:36:17.000Z
2022-01-18T03:36:17.000Z
server/eclipse-project/src/main/java/us/freeandfair/corla/model/ContestResult.java
rhelton21/colorado-rla
97b629a0de0d788155e35fce720ec7b207544df0
[ "RSA-MD" ]
null
null
null
server/eclipse-project/src/main/java/us/freeandfair/corla/model/ContestResult.java
rhelton21/colorado-rla
97b629a0de0d788155e35fce720ec7b207544df0
[ "RSA-MD" ]
2
2020-11-29T23:09:49.000Z
2022-01-18T03:36:21.000Z
23.866091
88
0.6619
12,079
package us.freeandfair.corla.model; import static us.freeandfair.corla.util.EqualsHashcodeHelper.nullableEquals; import java.io.Serializable; import java.math.BigDecimal; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.persistence.Cacheable; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.MapKeyColumn; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.persistence.Version; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import us.freeandfair.corla.persistence.PersistentEntity; import us.freeandfair.corla.persistence.StringSetConverter; /** * A class representing the results for a contest across counties. * A roll-up of CountyContestResults */ @Entity @Cacheable(true) @Table(name = "contest_result", uniqueConstraints = { @UniqueConstraint(columnNames = {"contest_name"}) }, indexes = { @Index(name = "idx_cr_contest", columnList = "contest_name", unique = true)}) @SuppressWarnings({"PMD.ExcessiveImports"}) // you complain if we import x.y.z.*, so.... public class ContestResult implements PersistentEntity, Serializable { /** * Class-wide logger */ public static final Logger LOGGER = LogManager.getLogger(ContestResult.class); /** * text */ private static final String TEXT = "text"; /** * The "id" string. */ private static final String ID = "id"; /** * The "result_id" string. */ private static final String RESULT_ID = "result_id"; /** * The serialVersionUID. */ private static final long serialVersionUID = 1L; /** * The unique identifier. */ @Id @Column(updatable = false, nullable = false) @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; /** * The version (for optimistic locking). */ @Version private Long version; /** * The winners allowed. */ @Column(name = "winners_allowed") private Integer winnersAllowed; /** * The set of contest winners. */ @Column(name = "winners", columnDefinition = TEXT) @Convert(converter = StringSetConverter.class) private final Set<String> winners = new HashSet<>(); /** * The set of contest losers. */ @Column(name = "losers", columnDefinition = TEXT) @Convert(converter = StringSetConverter.class) private final Set<String> losers = new HashSet<>(); /** * A map from choices to vote totals. */ @ElementCollection(fetch = FetchType.EAGER) @CollectionTable(name = "contest_vote_total", joinColumns = @JoinColumn(name = RESULT_ID, referencedColumnName = ID)) @MapKeyColumn(name = "choice") @Column(name = "vote_total") private Map<String, Integer> vote_totals = new HashMap<>(); /** * A ContestResult has many counties - supporting auditing multi-county * contests. Counties have many ContestResults (and many Contests) **/ @ManyToMany() @JoinTable(name = "counties_to_contest_results", joinColumns = { @JoinColumn(name = "contest_result_id") }, inverseJoinColumns = { @JoinColumn(name = "county_id") }) private final Set<County> counties = new HashSet<>(); /** * A ContestResult has many Contests through "contests_to_contest_results" * Contests are many in the db because each county has their own, just 'cause */ @OneToMany() @JoinTable(name = "contests_to_contest_results", joinColumns = { @JoinColumn(name = "contest_result_id") }, inverseJoinColumns = { @JoinColumn(name = "contest_id") }) private final Set<Contest> contests = new HashSet<>(); /** * The contest name. */ @Column(name = "contest_name", nullable = false) private String contestName; /** * The margin divided by total number of ballots cast. */ @Column(name = "diluted_margin") private BigDecimal dilutedMargin; /** * The smallest margin between any winner and loser of the contest */ @Column(name = "min_margin") private Integer minMargin; /** * The largest margin between any winner and loser of the contest. */ @Column(name = "max_margin") private Integer maxMargin; /** * The number of ballots cast for this contest */ @Column(name = "ballot_count") private Long ballotCount; /** * AuditReason */ @Column(name = "audit_reason") private AuditReason auditReason; /** * Constructs a new empty ContestResult (solely for persistence). */ public ContestResult() { super(); } /** * Constructs a new ContestResult with the specified contestName. The * contestName is what links Contests together (along with one * ContestResult). * * @param contestName The contest. */ public ContestResult(final String contestName) { super(); this.contestName = contestName; } /** * {@inheritDoc} */ @Override public Long id() { return id; } /** * {@inheritDoc} */ @Override public void setID(final Long the_id) { this.id = the_id; } /** * {@inheritDoc} */ @Override public Long version() { return version; } /** * @return the contest name. */ public String getContestName() { return this.contestName; } /** * @return the AuditReason. */ public AuditReason getAuditReason() { return this.auditReason; } /** set it **/ public void setAuditReason(final AuditReason auditReason) { this.auditReason = auditReason; } /** * set the set of counties */ public boolean addCounties(final Set<County> cs) { return this.counties.addAll(cs); } /** * @return the counties related to this contestresult. */ public Set<County> getCounties() { return Collections.unmodifiableSet(this.counties); } /** * set the set of contests */ public boolean addContests(final Set<Contest> cs) { return this.contests.addAll(cs); } /** * @return the contests related to this ContestResult * (should be contests that have the same name as this.contestName) **/ public Set<Contest> getContests() { return Collections.unmodifiableSet(this.contests); } /** * getter */ public int winnersAllowed() { return this.winnersAllowed; } /** * setter */ public void setWinnersAllowed(final int n) { this.winnersAllowed = n; } /** * @param county the county owning the contest you want * @return the contest belonging to county */ public Contest contestFor(final County county) { final Optional<Contest> contestMaybe = getContests().stream() .filter(c -> c.county().id().equals(county.id())) .findFirst(); // should only be one? if (contestMaybe.isPresent()) { return contestMaybe.get(); } else { return null; } } /** * @param winners a set of the choices that won the contest */ public void setWinners(final Set<String> winners) { this.winners.clear(); this.winners.addAll(winners); } /** * @return the winners for thie ContestResult. */ public Set<String> getWinners() { return Collections.unmodifiableSet(this.winners); } /** * @param losers a set of the choices that did not win the contest */ public void setLosers(final Set<String> losers) { this.losers.clear(); this.losers.addAll(losers); } /** * @return the losers for this ContestResult. */ public Set<String> getLosers() { return Collections.unmodifiableSet(this.losers); } /** * @return a map from choices to vote totals. */ public Map<String, Integer> getVoteTotals() { return Collections.unmodifiableMap(this.vote_totals); } /** data access helper **/ public Integer totalVotes() { return getVoteTotals().values().stream().reduce(0, Integer::sum); } /** * @param voteTotals a map from choices to vote totals. */ public void setVoteTotals(final Map<String, Integer> voteTotals) { this.vote_totals = voteTotals; } /** * set dilutedMargin. */ public void setDilutedMargin(final BigDecimal dilutedMargin) { this.dilutedMargin = dilutedMargin; } /** * The diluted margin (μ) of this ContestResult */ public BigDecimal getDilutedMargin() { return this.dilutedMargin; } /** * set minMargin. */ public void setMinMargin(final Integer minMargin) { this.minMargin = minMargin; } /** * The smallest margin between any winner and loser of the contest */ public Integer getMinMargin() { return this.minMargin; } /** * set maxMargin. */ public void setMaxMargin(final Integer maxMargin) { this.maxMargin = maxMargin; } /** * The largest margin between any winner and loser of the contest */ public Integer getMaxMargin() { return this.maxMargin; } /** * set ballotCount */ public void setBallotCount(final Long n) { this.ballotCount = n; } /** * what is the ballotCount? */ public Long getBallotCount() { return this.ballotCount; } /** * The set of county ids related to this ContestResult */ public Set<Long> countyIDs() { return this.getCounties().stream() .map(x -> x.id()) .collect(Collectors.toSet()); } /** * The set of contest ids related to this ContestResult */ public Set<Long> contestIDs() { return this.getContests().stream() .map(x -> x.id()) .collect(Collectors.toSet()); } /** * @return a String representation of this contest. */ @Override public String toString() { return "ContestResult [id=" + id() + " contestName=" + getContestName() + "]"; } /** * Compare this object with another for equivalence. * * @param the_other The other object. * @return true if the objects are equivalent, false otherwise. */ @Override public boolean equals(final Object the_other) { boolean result = true; if (the_other instanceof ContestResult) { final ContestResult other_result = (ContestResult) the_other; // compare by database ID, since that is the only // context in which they can reasonably be compared result &= nullableEquals(other_result.id(), id()); } else { result = false; } return result; } /** * @return a hash code for this object. */ @Override public int hashCode() { return id().hashCode(); } }
3e1c76d7a832937ad934315d21d61a285225689f
521
java
Java
library/src/main/java/com/vinay/library/util/DiskIOThreadExecutor.java
Vinayrraj/MVVMTemplet
9b1e617273410d83d8ea8e8f8bd2d5b1abe1a294
[ "MIT" ]
null
null
null
library/src/main/java/com/vinay/library/util/DiskIOThreadExecutor.java
Vinayrraj/MVVMTemplet
9b1e617273410d83d8ea8e8f8bd2d5b1abe1a294
[ "MIT" ]
null
null
null
library/src/main/java/com/vinay/library/util/DiskIOThreadExecutor.java
Vinayrraj/MVVMTemplet
9b1e617273410d83d8ea8e8f8bd2d5b1abe1a294
[ "MIT" ]
null
null
null
21.708333
56
0.729367
12,080
package com.vinay.library.util; import android.support.annotation.NonNull; import java.util.concurrent.Executor; import java.util.concurrent.Executors; /** * Executor that runs a task on a new background thread. */ public class DiskIOThreadExecutor implements Executor { private final Executor mDiskIO; public DiskIOThreadExecutor() { mDiskIO = Executors.newSingleThreadExecutor(); } @Override public void execute(@NonNull Runnable command) { mDiskIO.execute(command); } }
3e1c76f2d822d05c944ecedccf03162833615717
2,023
java
Java
src/main/java/com/frejdh/util/common/toolbox/FileUtils.java
Frejdh/mvn-lib-common-toolbox
9fa6f954ecb749634b1f0005875d171319716dc0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/frejdh/util/common/toolbox/FileUtils.java
Frejdh/mvn-lib-common-toolbox
9fa6f954ecb749634b1f0005875d171319716dc0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/frejdh/util/common/toolbox/FileUtils.java
Frejdh/mvn-lib-common-toolbox
9fa6f954ecb749634b1f0005875d171319716dc0
[ "Apache-2.0" ]
null
null
null
27.712329
112
0.732575
12,081
package com.frejdh.util.common.toolbox; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; public class FileUtils { /** * Load a file as an InputStream * @param absolutePath The absolute path for the file * @return An InputStream or null */ public static InputStream getFileAsStream(String absolutePath) { try { return new FileInputStream(absolutePath); } catch (FileNotFoundException e) { return null; } } /** * Load a file as an string * @param absolutePath The absolute path for the file * @return A string or null */ public static String getFileAsString(String absolutePath) { return inputStreamToString(getFileAsStream(absolutePath)); } /** * Load a file as an InputStream * @param relativePath The relative path from the resource directory * @return An InputStream or null */ public static InputStream getResourceFileAsStream(String relativePath) { return FileUtils.class.getResourceAsStream(!relativePath.startsWith("/") ? "/" + relativePath : relativePath); } /** * Load a file as a string. * @param relativePath The relative path from the resource directory * @return A string or null if the file couldn't be loaded */ public static String getResourceFileAsString(String relativePath) { return inputStreamToString(getResourceFileAsStream(relativePath)); } // One of the faster ways to convert a stream. public static String inputStreamToString(InputStream inputStream) { if (inputStream == null) { return null; } try { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[4 * 0x400]; // 4KB int length; while ((length = inputStream.read(buffer)) != -1) { result.write(buffer, 0, length); } return result.toString(StandardCharsets.UTF_8.name()); } catch (NullPointerException | IOException e ) { return null; } } }
3e1c76f8a04014175e70c87242603e8075328b01
6,767
java
Java
webapp-example/bookstore-sample/src/main/java/top/magicdevil/example/webapp/sample/bookstore/controller/AdminDegreeController.java
MagicDevilZhang/magicdevil-example
9bc15844ee11024cf5dcb63c23d2f9c1d78363e6
[ "Apache-2.0" ]
1
2021-09-06T02:55:47.000Z
2021-09-06T02:55:47.000Z
webapp-example/bookstore-sample/src/main/java/top/magicdevil/example/webapp/sample/bookstore/controller/AdminDegreeController.java
MagicDevilZhang/magicdevil-example
9bc15844ee11024cf5dcb63c23d2f9c1d78363e6
[ "Apache-2.0" ]
null
null
null
webapp-example/bookstore-sample/src/main/java/top/magicdevil/example/webapp/sample/bookstore/controller/AdminDegreeController.java
MagicDevilZhang/magicdevil-example
9bc15844ee11024cf5dcb63c23d2f9c1d78363e6
[ "Apache-2.0" ]
null
null
null
36.777174
117
0.627457
12,082
package top.magicdevil.example.webapp.sample.bookstore.controller; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import top.magicdevil.example.webapp.sample.bookstore.entity.Degree; import top.magicdevil.example.webapp.sample.bookstore.service.DegreeService; @Controller @RequestMapping("/admin/degree") public class AdminDegreeController implements IController { private static final long serialVersionUID = 1L; @Autowired private DegreeService degreeService; @RequestMapping(method = RequestMethod.GET) public ModelAndView get(HttpSession session, ModelAndView mav) { mav.setViewName("redirect:/admin/degree/list"); return mav; } @RequestMapping(value = "/list", method = RequestMethod.GET) public ModelAndView list( @RequestParam(value = "currentPage", required = false, defaultValue = CURRENT_PAGE) Integer currentPage, @RequestParam(value = "pageSize", required = false, defaultValue = PAGE_SIZE) Integer pageSize, HttpSession session, ModelAndView mav) { try { mav.addObject("degreeList", degreeService.getAllBySpilt(currentPage, pageSize)); mav.addObject("allCount", degreeService.getAllCount()); mav.addObject("currentPage", currentPage); mav.addObject("pageSize", pageSize); } catch (Exception e) { mav.setStatus(HttpStatus.INTERNAL_SERVER_ERROR); } finally { mav.setViewName("admin/degree/degree_list.html"); } return mav; } @RequestMapping(value = "/insert", method = RequestMethod.GET) public ModelAndView insert( @RequestParam(value = "insertState", required = false, defaultValue = DEFAULT_STATE) Integer insertState, HttpSession session, ModelAndView mav) { try { mav.addObject("insertState", insertState); } catch (Exception e) { mav.setStatus(HttpStatus.INTERNAL_SERVER_ERROR); } finally { mav.setViewName("admin/degree/degree_insert.html"); } return mav; } @RequestMapping(value = "/insert", method = RequestMethod.POST) public ModelAndView insert( @RequestParam(value = "dname", required = true) String dname, HttpSession session, ModelAndView mav) { boolean insertFinish = false; try { Degree degree = new Degree(); degree.setDname(dname); insertFinish = degreeService.insert(degree); } catch (Exception e) { mav.setStatus(HttpStatus.INTERNAL_SERVER_ERROR); } finally { mav.addObject("insertState", !insertFinish ? ERROR_STATE : SUCCESS_STATE); mav.setViewName("redirect:/admin/degree/insert"); } return mav; } @RequestMapping(value = "/update", method = RequestMethod.GET) public ModelAndView update( @RequestParam(value = "did", required = true) Long did, @RequestParam(value = "updateState", required = false, defaultValue = DEFAULT_STATE) Integer updateState, HttpSession session, ModelAndView mav) { try { mav.addObject("updateState", updateState); mav.addObject("degree", degreeService.getByID(did)); } catch (Exception e) { mav.setStatus(HttpStatus.INTERNAL_SERVER_ERROR); } finally { mav.setViewName("admin/degree/degree_update.html"); } return mav; } @RequestMapping(value = "/update", method = RequestMethod.POST) public ModelAndView update( @RequestParam(value = "did", required = true) Long did, @RequestParam(value = "dname", required = true) String dname, HttpSession session, ModelAndView mav) { boolean updateFinish = false; try { Degree degree = new Degree(); degree.setDid(did); degree.setDname(dname); updateFinish = degreeService.update(degree); } catch (Exception e) { mav.setStatus(HttpStatus.INTERNAL_SERVER_ERROR); } finally { mav.addObject("did", did); mav.addObject("updateState", !updateFinish ? ERROR_STATE : SUCCESS_STATE); mav.setViewName("redirect:/admin/degree/update"); } return mav; } @RequestMapping(value = "/remove", method = RequestMethod.GET) public ModelAndView remove( @RequestParam(value = "did", required = true) Long[] did, @RequestParam(value = "deleteState", required = false, defaultValue = DEFAULT_STATE) Integer deleteState, HttpSession session, ModelAndView mav) { try { List<Degree> degreeList = new ArrayList<>(); for (Long item : did) { Degree degree = degreeService.getByID(item); if (degree != null) { degreeList.add(degreeService.getByID(item)); } } mav.addObject("degreeList", degreeList); mav.addObject("deleteState", deleteState); } catch (Exception e) { mav.setStatus(HttpStatus.INTERNAL_SERVER_ERROR); } finally { mav.setViewName("admin/degree/degree_remove.html"); } return mav; } @RequestMapping(value = "/remove", method = RequestMethod.POST) public ModelAndView update( @RequestParam(value = "did", required = true) Long[] did, HttpSession session, ModelAndView mav) { boolean deleteFinish = false; try { Set<Degree> deleteDegree = new HashSet<>(); for (Long item : did) { Degree degree = degreeService.getByID(item); if (degree != null) { deleteDegree.add(degree); } } deleteFinish = degreeService.removeBunch(deleteDegree); } catch (Exception e) { mav.setStatus(HttpStatus.INTERNAL_SERVER_ERROR); } finally { mav.addObject("did", did); mav.addObject("deleteState", !deleteFinish ? ERROR_STATE : SUCCESS_STATE); mav.setViewName("redirect:/admin/degree/remove"); } return mav; } }
3e1c7705da914fa0eb7cebcbc9cf119a1f6101fb
1,116
java
Java
common-model/src/main/java/cn/featherfly/common/model/enums/ChineseZodiac.java
featherfly/common
37986eea1763e78dcefb8e820792459f5e7fbbf6
[ "MulanPSL-1.0" ]
1
2020-05-28T03:15:55.000Z
2020-05-28T03:15:55.000Z
common-model/src/main/java/cn/featherfly/common/model/enums/ChineseZodiac.java
featherfly/commons
0dc16519218a65fa00a56ffdada266a66be85442
[ "MulanPSL-1.0" ]
null
null
null
common-model/src/main/java/cn/featherfly/common/model/enums/ChineseZodiac.java
featherfly/commons
0dc16519218a65fa00a56ffdada266a66be85442
[ "MulanPSL-1.0" ]
null
null
null
13.609756
64
0.416667
12,083
/* * All rights Reserved, Designed By zhongj * @Title: ChineseZodiacSigns.java * @Package cn.featherfly.common.model.enums * @Description: ChineseZodiac * @author: zhongj * @date: 2021-12-28 17:02:28 * @Copyright: 2021 www.featherfly.cn Inc. All rights reserved. */ package cn.featherfly.common.model.enums; import cn.featherfly.common.model.Property; /** * ChineseZodiac. * <p> * 十二生肖. * </p> * * @author zhongj */ public enum ChineseZodiac implements Property<Integer> { /** * 鼠 */ RAT, /** * 牛 */ OX, /** * 虎 */ TIGER, /** * 兔 */ RABBIT, /** * 龙 */ DRAGON, /** * 蛇 */ SNAKE, /** * 马 */ HORSE, /** * 羊 */ SHEEP, /** * 猴 */ MONKEY, /** * 鸡 */ ROOSTER, /** * 狗 */ DOG, /** * 猪 */ PIG; /** * {@inheritDoc} */ @Override public Integer value() { return ordinal(); } }
3e1c7829d9a813eb3b4455e04cddba813e6670bb
2,568
java
Java
3-Middlewares/Development/hdfs/src/main/java/com/ervin/middleware/hdfs/hdfs/mapper/WordCountMapper.java
YizheZhang-Ervin/DevOps_Coding
4fee8b1163e9155bfbb516b4c81b78192472c42e
[ "MIT" ]
null
null
null
3-Middlewares/Development/hdfs/src/main/java/com/ervin/middleware/hdfs/hdfs/mapper/WordCountMapper.java
YizheZhang-Ervin/DevOps_Coding
4fee8b1163e9155bfbb516b4c81b78192472c42e
[ "MIT" ]
null
null
null
3-Middlewares/Development/hdfs/src/main/java/com/ervin/middleware/hdfs/hdfs/mapper/WordCountMapper.java
YizheZhang-Ervin/DevOps_Coding
4fee8b1163e9155bfbb516b4c81b78192472c42e
[ "MIT" ]
null
null
null
33.789474
93
0.53271
12,084
package com.ervin.middleware.hdfs.hdfs.mapper; import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; /** * Mapper 原型 : Mapper<KEYIN, VALUEIN, KEYOUT, VALUEOUT> * * KEYIN : 默认情况下,是mr框架所读到的一行文本内容的起始偏移量,Long, * 但是在hadoop中有自己的更精简的序列化接口,所以不直接用Long,而用LongWritable * VALUEIN : 默认情况下,是mr框架所读到的一行文本的内容(Java String 对应 Hadoop中的Text) * KEYOUT : 用户自定义逻辑处理完成之后输出数据中的key,在此处是单词(String),同上用Text * VALUEOUT : 用户自定义逻辑处理完成之后输出数据中的value,在这里是单词的次数:Integer,对应Hadoop中的IntWritable * * mapper的输入输出参数的类型必须和reducer的一致,且mapper的输出是reducer的输入 * */ public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable>{ /** * map实现数据拆分的操作 * 本操作主要进行Map的数据处理 * 在Mapper父类里面接受的内容如下: * LongWritable:文本内容的起始偏移量 * Text:每行的文本数据(行内容) * Text:每个单词分解后的统计结果 * IntWritable:输出记录的结果 */ @Override protected void map(LongWritable key, Text value,Context context) throws IOException, InterruptedException { System.out.println("文本内容的起始偏移量:"+key); String line = value.toString() ;//取出每行的数据 String[] result = line.split(" ");//按照空格进行数据拆分 //循环单词 for (int i = 0 ;i <result.length ; i++){ //针对每一个单词,构造一个key-value System.out.println("key-value : <"+new Text(result[i])+","+new IntWritable(1)+">"); /** * 将每个单词的key-value写入到输入输出上下文对象中 * 并传递给mapper进行shuffle过程,待所有mapper task完成后交由reducer进行对号取走 */ context.write(new Text(result[i]), new IntWritable(1)); } /** map端的shuffle过程(大致简单的描述一下) * | * | 放缓存(默认100M,溢出比是0.8,即80M满进行磁盘写入并清空, * | 剩余20M继续写入缓存,二者结合完美实现边写缓存边溢写(写磁盘)) * V * <b,1>,<c,1>,<a,1>,<a,1> * * | * | 缓存写满了,开始shuffle(洗牌、重组) == 包括分区,排序,以及可进行自定的合并(combine) * V * 写入磁盘文件(not hdfs)并进行文件归并,成一个个的大文件 <a,<1,1>>,<b,1>,<c,1> * * | * | * V * 每一个大文件都有各自的分区,有几个分区就对应几个reducer,随后文件被各自的reducer领走 * * !!! 这就是所谓的mapper的输入即是reducer的输出 !!! */ } }
3e1c784110962494d515c1ff0adfb52ff49aafaa
2,886
java
Java
com.sap.cloud.lm.sl.cf.core/src/main/java/com/sap/cloud/lm/sl/cf/core/helpers/MtaDescriptorMerger.java
nictas/cf-mta-deploy-service
ae55b4c53fab9fa27202c3627c4112274c01f3b3
[ "Apache-2.0" ]
null
null
null
com.sap.cloud.lm.sl.cf.core/src/main/java/com/sap/cloud/lm/sl/cf/core/helpers/MtaDescriptorMerger.java
nictas/cf-mta-deploy-service
ae55b4c53fab9fa27202c3627c4112274c01f3b3
[ "Apache-2.0" ]
null
null
null
com.sap.cloud.lm.sl.cf.core/src/main/java/com/sap/cloud/lm/sl/cf/core/helpers/MtaDescriptorMerger.java
nictas/cf-mta-deploy-service
ae55b4c53fab9fa27202c3627c4112274c01f3b3
[ "Apache-2.0" ]
null
null
null
45.09375
130
0.724186
12,085
package com.sap.cloud.lm.sl.cf.core.helpers; import java.util.List; import com.sap.cloud.lm.sl.cf.core.cf.HandlerFactory; import com.sap.cloud.lm.sl.cf.core.message.Messages; import com.sap.cloud.lm.sl.cf.core.security.serialization.SecureSerializationFacade; import com.sap.cloud.lm.sl.cf.core.util.UserMessageLogger; import com.sap.cloud.lm.sl.mta.handlers.v2.DescriptorMerger; import com.sap.cloud.lm.sl.mta.handlers.v2.DescriptorValidator; import com.sap.cloud.lm.sl.mta.model.DeploymentDescriptor; import com.sap.cloud.lm.sl.mta.model.ExtensionDescriptor; import com.sap.cloud.lm.sl.mta.model.Platform; public class MtaDescriptorMerger { private final HandlerFactory handlerFactory; private final Platform platform; private final UserMessageLogger userMessageLogger; private final SecureSerializationFacade secureSerializer = new SecureSerializationFacade(); public MtaDescriptorMerger(HandlerFactory handlerFactory, Platform platform) { this(handlerFactory, platform, null); } public MtaDescriptorMerger(HandlerFactory handlerFactory, Platform platform, UserMessageLogger userMessageLogger) { this.handlerFactory = handlerFactory; this.platform = platform; this.userMessageLogger = userMessageLogger; } public DeploymentDescriptor merge(DeploymentDescriptor deploymentDescriptor, List<ExtensionDescriptor> extensionDescriptors) { DescriptorValidator validator = handlerFactory.getDescriptorValidator(); validator.validateDeploymentDescriptor(deploymentDescriptor, platform); validator.validateExtensionDescriptors(extensionDescriptors, deploymentDescriptor); DescriptorMerger merger = handlerFactory.getDescriptorMerger(); // Merge the passed set of descriptors into one deployment descriptor. The deployment descriptor at the root of // the chain is merged in as well: DeploymentDescriptor mergedDescriptor = merger.merge(deploymentDescriptor, extensionDescriptors); validator.validateMergedDescriptor(mergedDescriptor); handlerFactory.getPlatformMerger(platform) .mergeInto(mergedDescriptor); DeploymentDescriptor validatedDescriptor = handlerFactory.getDescriptorParametersCompatabilityValidator(mergedDescriptor, userMessageLogger) .validate(); deploymentDescriptor = validatedDescriptor; logDebug(Messages.MERGED_DESCRIPTOR, secureSerializer.toJson(deploymentDescriptor)); return deploymentDescriptor; } private void logDebug(String pattern, Object... arguments) { if (userMessageLogger != null) { userMessageLogger.debug(pattern, arguments); } } }
3e1c7a24c0cdada5f73201c4e1eda4377cc2b613
1,604
java
Java
extendz-spring-boot-example/src/main/java/club/extendz/spring/example/modules/hr/master/department/DepartmentRepository.java
Techsfinity/extendz-boot
96e2763a33828b2a3ba362fd9b66cce4d3a69261
[ "Apache-2.0" ]
2
2018-02-16T03:50:45.000Z
2018-02-21T09:26:13.000Z
extendz-spring-boot-example/src/main/java/club/extendz/spring/example/modules/hr/master/department/DepartmentRepository.java
extendz/extend-spring-boot-starter
96e2763a33828b2a3ba362fd9b66cce4d3a69261
[ "Apache-2.0" ]
1
2018-02-16T10:49:41.000Z
2018-02-21T10:06:11.000Z
extendz-spring-boot-example/src/main/java/club/extendz/spring/example/modules/hr/master/department/DepartmentRepository.java
extendz/extend-spring-boot-starter
96e2763a33828b2a3ba362fd9b66cce4d3a69261
[ "Apache-2.0" ]
1
2020-08-26T06:19:04.000Z
2020-08-26T06:19:04.000Z
39.121951
103
0.795511
12,086
/* * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 club.extendz.spring.example.modules.hr.master.department; import org.springframework.data.querydsl.QueryDslPredicateExecutor; import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; import org.springframework.data.querydsl.binding.QuerydslBindings; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.history.RevisionRepository; import org.springframework.stereotype.Repository; import com.querydsl.core.types.dsl.StringPath; /*** * @author Asitha Niranjan (efpyi@example.com) */ // @Repository public interface DepartmentRepository extends PagingAndSortingRepository<Department, Long>, QueryDslPredicateExecutor<Department>, QuerydslBinderCustomizer<QDepartment> { @Override default void customize(QuerydslBindings bindings, QDepartment department) { bindings.bind(String.class).first((StringPath path, String value) -> path.containsIgnoreCase(value)); }// customize() }// class
3e1c7a2e3820c829b5b98b9f237d12088c088b3f
415
java
Java
springHibernateStruts/src/java/dao/DaoCategorias.java
jhingx1/Spring-ExamplesCibertec
9e107c906acbfa155d3c222741fce1859a68c7a4
[ "MIT" ]
null
null
null
springHibernateStruts/src/java/dao/DaoCategorias.java
jhingx1/Spring-ExamplesCibertec
9e107c906acbfa155d3c222741fce1859a68c7a4
[ "MIT" ]
null
null
null
springHibernateStruts/src/java/dao/DaoCategorias.java
jhingx1/Spring-ExamplesCibertec
9e107c906acbfa155d3c222741fce1859a68c7a4
[ "MIT" ]
null
null
null
19.761905
57
0.766265
12,087
package dao; import hibernate.domain.Categorias; import java.util.List; public interface DaoCategorias { public List<Categorias> categoriasQry(); public String categoriasIns(Categorias categorias); public String categoriasDel(List<Integer> ids); public Categorias categoriasGet(Integer idcategoria); public String categoriasUpd(Categorias categorias); public String getMessage(); }
3e1c7a7e171b6d24522a9bd6c2e327550b4b0c64
30,286
java
Java
core/src/main/java/org/apache/calcite/avatica/AvaticaStatement.java
manu6909/calcite-avatica
e1d7a93013bf89440f2d894801f5f50a9207d6bd
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/apache/calcite/avatica/AvaticaStatement.java
manu6909/calcite-avatica
e1d7a93013bf89440f2d894801f5f50a9207d6bd
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/apache/calcite/avatica/AvaticaStatement.java
manu6909/calcite-avatica
e1d7a93013bf89440f2d894801f5f50a9207d6bd
[ "Apache-2.0" ]
null
null
null
33.354626
98
0.68738
12,088
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.calcite.avatica; import net.sf.jsqlparser.util.SelectUtils; import org.apache.calcite.avatica.remote.TypedValue; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.expression.Alias; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.statement.select.*; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Implementation of {@link java.sql.Statement} * for the Avatica engine. */ public abstract class AvaticaStatement implements Statement { /** The default value for {@link Statement#getFetchSize()}. */ public static final int DEFAULT_FETCH_SIZE = 100; public final AvaticaConnection connection; /** Statement id; unique within connection. */ public Meta.StatementHandle handle; protected boolean closed; /** Support for {@link #cancel()} method. */ protected final AtomicBoolean cancelFlag; /** * Support for {@link #closeOnCompletion()} method. */ protected boolean closeOnCompletion; /** * Current result set, or null if the statement is not executing anything. * Any method which modifies this member must synchronize * on the AvaticaStatement. */ protected AvaticaResultSet openResultSet; /** Current update count. Same lifecycle as {@link #openResultSet}. */ protected long updateCount; private int queryTimeoutMillis; final int resultSetType; final int resultSetConcurrency; final int resultSetHoldability; private int fetchSize = DEFAULT_FETCH_SIZE; private int fetchDirection; protected long maxRowCount = 0; private Meta.Signature signature; private final List<String> batchedSql; protected void setSignature(Meta.Signature signature) { this.signature = signature; } protected Meta.Signature getSignature() { return signature; } public Meta.StatementType getStatementType() { return signature.statementType; } /** * Creates an AvaticaStatement. * * @param connection Connection * @param h Statement handle * @param resultSetType Result set type * @param resultSetConcurrency Result set concurrency * @param resultSetHoldability Result set holdability */ protected AvaticaStatement(AvaticaConnection connection, Meta.StatementHandle h, int resultSetType, int resultSetConcurrency, int resultSetHoldability) { this(connection, h, resultSetType, resultSetConcurrency, resultSetHoldability, null); } protected AvaticaStatement(AvaticaConnection connection, Meta.StatementHandle h, int resultSetType, int resultSetConcurrency, int resultSetHoldability, Meta.Signature signature) { this.connection = Objects.requireNonNull(connection); this.resultSetType = resultSetType; this.resultSetConcurrency = resultSetConcurrency; this.resultSetHoldability = resultSetHoldability; this.signature = signature; this.closed = false; if (h == null) { final Meta.ConnectionHandle ch = connection.handle; h = connection.meta.createStatement(ch); } connection.statementMap.put(h.id, this); this.handle = h; this.batchedSql = new ArrayList<>(); try { this.cancelFlag = connection.getCancelFlag(h); } catch (NoSuchStatementException e) { throw new AssertionError("no statement", e); } } /** Returns the identifier of the statement, unique within its connection. */ public int getId() { return handle.id; } protected void checkOpen() throws SQLException { if (isClosed()) { throw AvaticaConnection.HELPER.createException("Statement closed"); } } private void checkNotPreparedOrCallable(String s) throws SQLException { if (this instanceof PreparedStatement || this instanceof CallableStatement) { throw AvaticaConnection.HELPER.createException("Cannot call " + s + " on prepared or callable statement"); } } protected void executeInternal(String sql) throws SQLException { // reset previous state before moving forward. this.updateCount = -1; try { // In JDBC, maxRowCount = 0 means no limit; in prepare it means LIMIT 0 final long maxRowCount1 = maxRowCount <= 0 ? -1 : maxRowCount; for (int i = 0; i < connection.maxRetriesPerExecute; i++) { try { @SuppressWarnings("unused") Meta.ExecuteResult x = connection.prepareAndExecuteInternal(this, sql, maxRowCount1); return; } catch (NoSuchStatementException e) { resetStatement(); } } } catch (RuntimeException e) { throw AvaticaConnection.HELPER.createException("Error while executing SQL \"" + sql + "\": " + e.getMessage(), e); } throw new RuntimeException("Failed to successfully execute query after " + connection.maxRetriesPerExecute + " attempts."); } /** * Executes a collection of updates in a single batch RPC. * * @return an array of long mapping to the update count per SQL command. */ protected long[] executeBatchInternal() throws SQLException { for (int i = 0; i < connection.maxRetriesPerExecute; i++) { try { return connection.prepareAndUpdateBatch(this, batchedSql).updateCounts; } catch (NoSuchStatementException e) { resetStatement(); } } throw new RuntimeException("Failed to successfully execute batch update after " + connection.maxRetriesPerExecute + " attempts"); } protected void resetStatement() { // Invalidate the old statement connection.statementMap.remove(handle.id); connection.flagMap.remove(handle.id); // Get a new one final Meta.ConnectionHandle ch = new Meta.ConnectionHandle(connection.id); Meta.StatementHandle h = connection.meta.createStatement(ch); // Cache it in the connection connection.statementMap.put(h.id, this); // Update the local state and try again this.handle = h; } /** * Re-initialize the ResultSet on the server with the given state. * @param state The ResultSet's state. * @param offset Offset into the desired ResultSet * @return True if the ResultSet has more results, false if there are no more results. */ protected boolean syncResults(QueryState state, long offset) throws NoSuchStatementException { return connection.meta.syncResults(handle, state, offset); } // implement Statement public boolean execute(String sql) throws SQLException { checkOpen(); /** * Prealent AI update dated 12/23/2019 * Updates for using Avatica jdbc jar with Tableau * 1. Replacing 'POSITION' clause with LIKE clause for pattern matching * 2. Drop DDL statements ("CREATE", "DROP") which will avoid failures while pushing to * Calcite query planner * 3. Intercept INNER JOIN queries fired by Tableau for Ton N results and push * corrected queries to calcite query planner for better performance * 4. Supporting methods added at bottom of the file */ String sql_upt = ""; if (sql.contains("CREATE LOCAL TEMPORARY TABLE") || sql.contains("DROP TABLE") || sql.contains("INSERT INTO") || sql.contains("CREATE INDEX")) { openResultSet = null; } else { //Find queries with INNER JOIN and LIMIT clause for updation. These queries can be fired by //tableau when trying to visualize Top N chart if (sql.contains("INNER JOIN") && sql.contains("LIMIT")) { String sql_inner = changeQuery(sql); sql_upt = getFinalQueryWithoutJoin(sql,sql_inner); } else { sql_upt = getFinalQuery(sql); } String sql_final = sql_upt.replaceAll("POSITION\\(\\'([^']*+)\\' IN (.+?)\\) > 0", "$2 LIKE LOWER('%$1%')"); //Fix for LIKE query // PAI Debugging. Capture logs to validate proper query updation. // Below file path will only work in Tableau Desktop. So careful before uncommenting // this section and creating the jar file to deploy in Tableau server // File file = new File("C:\\tmp\\tableau_custom.log"); // FileWriter fr = null; // try { // fr = new FileWriter(file, true); // fr.write("Org SQL : "+sql+"\n"+"Upd SQL : "+sql_final+"\n\n"); // fr.close(); // } catch (IOException e) { // throw AvaticaConnection.HELPER.createException(e.getMessage()); // } checkNotPreparedOrCallable("execute(String)"); executeInternal(sql_final); } // Result set is null for DML or DDL. // Result set is closed if user cancelled the query. return openResultSet != null && !openResultSet.isClosed(); } public ResultSet executeQuery(String sql) throws SQLException { checkOpen(); checkNotPreparedOrCallable("executeQuery(String)"); try { executeInternal(sql); if (openResultSet == null) { throw AvaticaConnection.HELPER.createException( "Statement did not return a result set"); } return openResultSet; } catch (RuntimeException e) { throw AvaticaConnection.HELPER.createException("Error while executing SQL \"" + sql + "\": " + e.getMessage(), e); } } public final int executeUpdate(String sql) throws SQLException { return AvaticaUtils.toSaturatedInt(executeLargeUpdate(sql)); } public long executeLargeUpdate(String sql) throws SQLException { checkOpen(); checkNotPreparedOrCallable("executeUpdate(String)"); executeInternal(sql); return updateCount; } public synchronized void close() throws SQLException { try { close_(); } catch (RuntimeException e) { throw AvaticaConnection.HELPER.createException("While closing statement", e); } } protected void close_() { if (!closed) { closed = true; if (openResultSet != null) { AvaticaResultSet c = openResultSet; openResultSet = null; c.close(); } try { // inform the server to close the resource connection.meta.closeStatement(handle); } finally { // make sure we don't leak on our side connection.statementMap.remove(handle.id); connection.flagMap.remove(handle.id); } // If onStatementClose throws, this method will throw an exception (later // converted to SQLException), but this statement still gets closed. connection.driver.handler.onStatementClose(this); } } public int getMaxFieldSize() throws SQLException { checkOpen(); return 0; } public void setMaxFieldSize(int max) throws SQLException { checkOpen(); if (max != 0) { throw AvaticaConnection.HELPER.createException( "illegal maxField value: " + max); } } public final int getMaxRows() throws SQLException { return AvaticaUtils.toSaturatedInt(getLargeMaxRows()); } public long getLargeMaxRows() throws SQLException { checkOpen(); return maxRowCount; } public final void setMaxRows(int maxRowCount) throws SQLException { setLargeMaxRows(maxRowCount); } public void setLargeMaxRows(long maxRowCount) throws SQLException { checkOpen(); if (maxRowCount < 0) { throw AvaticaConnection.HELPER.createException( "illegal maxRows value: " + maxRowCount); } this.maxRowCount = maxRowCount; } public void setEscapeProcessing(boolean enable) throws SQLException { throw AvaticaConnection.HELPER.unsupported(); } public int getQueryTimeout() throws SQLException { checkOpen(); long timeoutSeconds = getQueryTimeoutMillis() / 1000; if (timeoutSeconds > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } if (timeoutSeconds == 0 && getQueryTimeoutMillis() > 0) { // Don't return timeout=0 if e.g. timeoutMillis=500. 0 is special. return 1; } return (int) timeoutSeconds; } int getQueryTimeoutMillis() { return queryTimeoutMillis; } public void setQueryTimeout(int seconds) throws SQLException { checkOpen(); if (seconds < 0) { throw AvaticaConnection.HELPER.createException( "illegal timeout value " + seconds); } setQueryTimeoutMillis(seconds * 1000); } void setQueryTimeoutMillis(int millis) { this.queryTimeoutMillis = millis; } public synchronized void cancel() throws SQLException { checkOpen(); if (openResultSet != null) { openResultSet.cancel(); } // If there is an open result set, it probably just set the same flag. cancelFlag.compareAndSet(false, true); } public SQLWarning getWarnings() throws SQLException { checkOpen(); return null; // no warnings, since warnings are not supported } public void clearWarnings() throws SQLException { checkOpen(); // no-op since warnings are not supported } public void setCursorName(String name) throws SQLException { throw AvaticaConnection.HELPER.unsupported(); } public ResultSet getResultSet() throws SQLException { checkOpen(); // NOTE: result set becomes visible in this member while // executeQueryInternal is still in progress, and before it has // finished executing. Its internal state may not be ready for API // calls. JDBC never claims to be thread-safe! (Except for calls to the // cancel method.) It is not possible to synchronize, because it would // block 'cancel'. return openResultSet; } public int getUpdateCount() throws SQLException { checkOpen(); return AvaticaUtils.toSaturatedInt(updateCount); } public long getLargeUpdateCount() throws SQLException { checkOpen(); return updateCount; } public boolean getMoreResults() throws SQLException { checkOpen(); return getMoreResults(CLOSE_CURRENT_RESULT); } public void setFetchDirection(int direction) throws SQLException { checkOpen(); this.fetchDirection = direction; } public int getFetchDirection() throws SQLException { checkOpen(); return fetchDirection; } public void setFetchSize(int rows) throws SQLException { checkOpen(); this.fetchSize = rows; } public int getFetchSize() throws SQLException { checkOpen(); return fetchSize; } public int getResultSetConcurrency() throws SQLException { checkOpen(); return resultSetConcurrency; } public int getResultSetType() throws SQLException { checkOpen(); return resultSetType; } public void addBatch(String sql) throws SQLException { checkOpen(); checkNotPreparedOrCallable("addBatch(String)"); this.batchedSql.add(Objects.requireNonNull(sql)); } public void clearBatch() throws SQLException { checkOpen(); checkNotPreparedOrCallable("clearBatch()"); this.batchedSql.clear(); } public int[] executeBatch() throws SQLException { return AvaticaUtils.toSaturatedInts(executeLargeBatch()); } public long[] executeLargeBatch() throws SQLException { checkOpen(); try { return executeBatchInternal(); } finally { // If we failed to send this batch, that's a problem for the user to handle, not us. // Make sure we always clear the statements we collected to submit in one RPC. clearBatch(); } } public AvaticaConnection getConnection() throws SQLException { checkOpen(); return connection; } public boolean getMoreResults(int current) throws SQLException { checkOpen(); switch (current) { case KEEP_CURRENT_RESULT: case CLOSE_ALL_RESULTS: throw AvaticaConnection.HELPER.unsupported(); case CLOSE_CURRENT_RESULT: break; default: throw AvaticaConnection.HELPER.createException("value " + current + " is not one of CLOSE_CURRENT_RESULT, KEEP_CURRENT_RESULT or CLOSE_ALL_RESULTS"); } if (openResultSet != null) { openResultSet.close(); } return false; } public ResultSet getGeneratedKeys() throws SQLException { throw AvaticaConnection.HELPER.unsupported(); } public int executeUpdate( String sql, int autoGeneratedKeys) throws SQLException { throw AvaticaConnection.HELPER.unsupported(); } public int executeUpdate( String sql, int[] columnIndexes) throws SQLException { throw AvaticaConnection.HELPER.unsupported(); } public int executeUpdate( String sql, String[] columnNames) throws SQLException { throw AvaticaConnection.HELPER.unsupported(); } public boolean execute( String sql, int autoGeneratedKeys) throws SQLException { throw AvaticaConnection.HELPER.unsupported(); } public boolean execute( String sql, int[] columnIndexes) throws SQLException { throw AvaticaConnection.HELPER.unsupported(); } public boolean execute( String sql, String[] columnNames) throws SQLException { throw AvaticaConnection.HELPER.unsupported(); } public int getResultSetHoldability() throws SQLException { checkOpen(); return resultSetHoldability; } public boolean isClosed() throws SQLException { return closed; } public void setPoolable(boolean poolable) throws SQLException { throw AvaticaConnection.HELPER.unsupported(); } public boolean isPoolable() throws SQLException { checkOpen(); return false; } // implements java.sql.Statement.closeOnCompletion (added in JDK 1.7) public void closeOnCompletion() throws SQLException { checkOpen(); closeOnCompletion = true; } // implements java.sql.Statement.isCloseOnCompletion (added in JDK 1.7) public boolean isCloseOnCompletion() throws SQLException { checkOpen(); return closeOnCompletion; } // implement Wrapper public <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isInstance(this)) { return iface.cast(this); } throw AvaticaConnection.HELPER.createException( "does not implement '" + iface + "'"); } public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isInstance(this); } /** * Executes a prepared statement. * * @param signature Parsed statement * @param isUpdate if the execute is for an update * * @return as specified by {@link java.sql.Statement#execute(String)} * @throws java.sql.SQLException if a database error occurs */ protected boolean executeInternal(Meta.Signature signature, boolean isUpdate) throws SQLException { ResultSet resultSet = executeQueryInternal(signature, isUpdate); // user may have cancelled the query if (resultSet.isClosed()) { return false; } return true; } /** * Executes a prepared query, closing any previously open result set. * * @param signature Parsed query * @param isUpdate If the execute is for an update * @return Result set * @throws java.sql.SQLException if a database error occurs */ protected ResultSet executeQueryInternal(Meta.Signature signature, boolean isUpdate) throws SQLException { return connection.executeQueryInternal(this, signature, null, null, isUpdate); } /** * Called by each child result set when it is closed. * * @param resultSet Result set or cell set */ void onResultSetClose(ResultSet resultSet) { if (closeOnCompletion) { close_(); } } /** Returns the list of values of this statement's parameters. * * <p>Called at execute time. Not a public API.</p> * * <p>The default implementation returns the empty list, because non-prepared * statements have no parameters.</p> * * @see org.apache.calcite.avatica.AvaticaConnection.Trojan#getParameterValues(AvaticaStatement) */ protected List<TypedValue> getParameterValues() { return Collections.emptyList(); } /** Returns a list of bound parameter values. * * <p>If any of the parameters have not been bound, throws. * If parameters have been bound to null, the value in the list is null. */ protected List<TypedValue> getBoundParameterValues() throws SQLException { final List<TypedValue> parameterValues = getParameterValues(); for (Object parameterValue : parameterValues) { if (parameterValue == null) { throw new SQLException("unbound parameter"); } } return parameterValues; } /** * * PAI changes for Tableau Druid integration */ /** * Method to get return properly formatted inner query from a SQL statement with JOIN statement. * @param mainQuery sql query string * @return formatted inner query */ private String changeQuery(String mainQuery) { Select statement = null; Map<String, String> outerAliasMap = null; try { statement = (Select) CCJSqlParserUtil.parse(mainQuery); } catch (JSQLParserException e) { e.printStackTrace(); } PlainSelect plainSelect = (PlainSelect) statement.getSelectBody(); outerAliasMap = getOuterAliasMap(plainSelect); PlainSelect plainInnerQuery = getInnerQuery(plainSelect); if (plainInnerQuery == null) { return mainQuery; } else { // Handling second level in case we have queries inside FROM clause. FromItem from = plainInnerQuery.getFromItem(); String inQuery = from.toString().split(from.getAlias().toString())[0]; plainInnerQuery = handleSecondLevel(inQuery) != null ? handleSecondLevel(inQuery) : plainInnerQuery; return changeAlias(plainInnerQuery, outerAliasMap).toString(); } } /** * Check wheather the from clause having inner query by parsing it and checking for exceptions. * @param sql sql query string * @return */ private PlainSelect handleSecondLevel(String sql) { Select newmt = null; try { newmt = (Select) CCJSqlParserUtil.parse(sql); } catch (JSQLParserException e) { return null; } return (PlainSelect) newmt.getSelectBody(); } /** * Utility function to create Map of select column as keys and values as alias names. * @param query sql query string * @return */ private Map<String, String> getOuterAliasMap(PlainSelect query) { Map<String, String> selectAliasMap = new HashMap<String, String>(); for (SelectItem item:query.getSelectItems()) { SelectExpressionItem sei = (SelectExpressionItem) item; selectAliasMap.put(sei.getExpression().toString(), sei.getAlias().getName()); } return selectAliasMap; } /** * Function to get inner query from main query if join is found.Only handles one Join. * @param query sql query string * @return */ private PlainSelect getInnerQuery(PlainSelect query) { List<Join> joins = query.getJoins(); Select innerQuery = null; if (joins != null) { try { for (Join jo : joins) { String[] arrays = jo.getRightItem().toString().split(jo.getRightItem().getAlias() .toString()); innerQuery = (Select) CCJSqlParserUtil.parse(arrays[0]); } } catch (JSQLParserException e) { e.printStackTrace(); return null; } } return (innerQuery == null) ? null : (PlainSelect) innerQuery.getSelectBody(); } private PlainSelect changeAlias(PlainSelect query, Map<String, String> outerAliasMap) { for (SelectItem item:query.getSelectItems()) { SelectExpressionItem sei = (SelectExpressionItem) item; if (outerAliasMap.containsKey(sei.getExpression().toString())) { sei.setAlias(new Alias(outerAliasMap.get(sei.getExpression().toString()))); } } return query; } /** * Method to handle incorrect query pushed by Tableau when applying LIMIT using particular * metrics (like SUM, AVG, etc). Tableau creates an improper query with INNER JOIN, which causes * performance issues in Druid. This function handles multiple conditions and corrects all the * issues. SELECT columns, GROUP BY columns will be picked from main query. * ORDER BY columns, LIMIT clause will be picked from inner query. WHERE clause will be picked * from main query if available or else from inner query * @param sql Original SQL query * @param sql_inner Sub-query inside the JOIN clause * @return Corrected SQL query */ private static String getFinalQueryWithoutJoin(String sql, String sql_inner) { String order_by = ""; String group_by = ""; String select = ""; String where = ""; String limit = ""; String from = ""; String output = ""; List<OrderByElement> orderByElementList = new ArrayList<OrderByElement>(); List<SelectItem> selectElementList_full_query = new ArrayList<SelectItem>(); List<SelectItem> selectElementList_inner_query = new ArrayList<SelectItem>(); List<String> select_columns_full_query = new ArrayList<String>(); Expression where_clause_full_query = null; Expression where_clause_inner_query = null; try { Select stmnt_inner_query = (Select) CCJSqlParserUtil.parse(sql_inner); PlainSelect inner_query = (PlainSelect) stmnt_inner_query.getSelectBody(); Select stmnt_main_query = (Select) CCJSqlParserUtil.parse(sql); PlainSelect main_query = (PlainSelect) stmnt_main_query.getSelectBody(); //Get WHERE clause from both the queries where_clause_full_query = main_query.getWhere(); where_clause_inner_query = inner_query.getWhere(); //Get columns in SELECT statements from both the queries selectElementList_full_query = main_query.getSelectItems(); selectElementList_inner_query = inner_query.getSelectItems(); orderByElementList = inner_query.getOrderByElements(); if (orderByElementList != null && !orderByElementList.isEmpty()) { //Only pick first column from ORDER BY CLAUSE String col_alias = ""; String col = orderByElementList.get(0).getExpression().toString(); String col_name = selectElementList_inner_query.get((Integer.parseInt(col))-1).toString(); Pattern pattern = Pattern.compile(".*AS(.*)"); Matcher matcher = pattern.matcher(col_name); if (matcher.find()) { //Get the alias for using in the ORDER by clause col_alias = matcher.group(1).trim(); } else { col_alias = col_name; } if (orderByElementList.get(0).isAsc()) { order_by = col_alias + " ASC"; } else { order_by = col_alias + " DESC"; } } //So far WHERE clause will be always present in outer query. But keeping a condition to //get the WHERE clause from inner query in case it is missing from outer query if (null != where_clause_full_query) { where = where_clause_full_query.toString(); } else if (null != where_clause_inner_query) { where = where_clause_inner_query.toString(); } else { where = ""; } selectElementList_full_query.forEach(x -> select_columns_full_query.add(x.toString())); select = select_columns_full_query.stream().collect(Collectors.joining(", ")); from = main_query.getFromItem().toString(); limit = inner_query.getLimit().toString(); group_by = main_query.getGroupBy().toString(); output = ("" != where) ? "SELECT " + select + " FROM "+ from + " WHERE " + where + " " + group_by + " " + "ORDER BY " + order_by + " " + limit : "SELECT " + select + " FROM " + from + " " + group_by + " " + "ORDER BY " + order_by + " " + limit; } catch (JSQLParserException e) { e.printStackTrace(); } return output; } /** * Method to fix problems in SQL query due to incorrect query parameters pushed by Tablbeau. * Tableau pushes two orderBy columns eventhough user asks for only one column. This is fixed * in this method. This method is used all queries except the one with INNER JOIN clause * @param sql Original SQL query * @return Corrected SQL query */ private String getFinalQuery(String sql) { String order_by = ""; String output = ""; try { Select statement = (Select) CCJSqlParserUtil.parse(sql); String sql_cleaned = statement.toString(); //Removing newlines for avoiding Regex issues PlainSelect plainSelect = (PlainSelect) statement.getSelectBody(); List<OrderByElement> orderByElementList = new ArrayList<OrderByElement>(); orderByElementList = plainSelect.getOrderByElements(); if (orderByElementList != null && !orderByElementList.isEmpty()) { //Only pick first column from ORDER BY CLAUSE String col = orderByElementList.get(0).getExpression().toString(); if (orderByElementList.get(0).isAsc()) { order_by = col + " ASC"; } else { order_by = col + " DESC"; } output = sql_cleaned.replaceAll("ORDER BY.*(ASC|DESC)", "ORDER BY " + order_by); } else { output = sql_cleaned; } } catch (JSQLParserException e) { e.printStackTrace(); } return output; } /** * * PAI changes for Tableau Druid integration end */ } // End AvaticaStatement.java
3e1c7b1d9e05ec7ebbf676e79db768412895b33d
18,671
java
Java
drools-compiler/src/main/java/org/drools/compiler/compiler/xml/XmlDumper.java
cuijulian/drools
31b4dacd07ad962592dfb5ae6eee5cb825acce14
[ "Apache-2.0" ]
3,631
2017-03-14T08:54:05.000Z
2022-03-31T19:59:10.000Z
drools-compiler/src/main/java/org/drools/compiler/compiler/xml/XmlDumper.java
cuijulian/drools
31b4dacd07ad962592dfb5ae6eee5cb825acce14
[ "Apache-2.0" ]
2,274
2017-03-13T14:02:17.000Z
2022-03-28T17:23:17.000Z
drools-compiler/src/main/java/org/drools/compiler/compiler/xml/XmlDumper.java
cuijulian/drools
31b4dacd07ad962592dfb5ae6eee5cb825acce14
[ "Apache-2.0" ]
1,490
2017-03-14T11:37:37.000Z
2022-03-31T08:50:22.000Z
44.035377
243
0.615661
12,089
/* * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.compiler.compiler.xml; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.drools.core.util.ReflectiveVisitor; import org.drools.core.util.StringUtils; import org.drools.compiler.lang.descr.AccumulateDescr; import org.drools.compiler.lang.descr.AccumulateDescr.AccumulateFunctionCallDescr; import org.drools.compiler.lang.descr.AndDescr; import org.drools.compiler.lang.descr.AttributeDescr; import org.drools.compiler.lang.descr.BindingDescr; import org.drools.compiler.lang.descr.CollectDescr; import org.drools.compiler.lang.descr.EvalDescr; import org.drools.compiler.lang.descr.ExistsDescr; import org.drools.compiler.lang.descr.ExprConstraintDescr; import org.drools.compiler.lang.descr.ForallDescr; import org.drools.compiler.lang.descr.FromDescr; import org.drools.compiler.lang.descr.FunctionDescr; import org.drools.compiler.lang.descr.FunctionImportDescr; import org.drools.compiler.lang.descr.GlobalDescr; import org.drools.compiler.lang.descr.ImportDescr; import org.drools.compiler.lang.descr.LiteralRestrictionDescr; import org.drools.compiler.lang.descr.NotDescr; import org.drools.compiler.lang.descr.OrDescr; import org.drools.compiler.lang.descr.PackageDescr; import org.drools.compiler.lang.descr.PackageDescrDumper; import org.drools.compiler.lang.descr.PatternDescr; import org.drools.compiler.lang.descr.PredicateDescr; import org.drools.compiler.lang.descr.QualifiedIdentifierRestrictionDescr; import org.drools.compiler.lang.descr.QueryDescr; import org.drools.compiler.lang.descr.ReturnValueRestrictionDescr; import org.drools.compiler.lang.descr.RuleDescr; import org.drools.compiler.lang.descr.VariableRestrictionDescr; /** * This utility will take a AST of a rule package, and emit XML. * This can be used in porting from DRL to XML. */ public class XmlDumper extends ReflectiveVisitor implements PackageDescrDumper { private StringBuilder xmlDump; private boolean patternContext; private final static String eol = System.getProperty( "line.separator" ); private String template; public synchronized String dump(final PackageDescr packageDescr) { this.xmlDump = new StringBuilder(); visitPackageDescr( packageDescr ); return this.xmlDump.toString(); } public void visitAndDescr(final AndDescr descr) { this.template = new String(); if ( descr.getDescrs() != Collections.EMPTY_LIST ) { if ( !this.patternContext ) this.template = "<and-conditional-element>" + processDescrList( descr.getDescrs() ) + "</and-conditional-element>"; else this.template = "<and-constraint-connective>" + processDescrList( descr.getDescrs() ) + "</and-constraint-connective>"; } } public void visitAttributeDescr(final AttributeDescr attributeDescr) { this.template = new String(); this.template = "<rule-attribute name=\"" + attributeDescr.getName() + "\" value=\"" + attributeDescr.getValue() + "\" />" + XmlDumper.eol; } public void visitVariableRestrictionDescr(final VariableRestrictionDescr descr) { this.template = new String(); this.template = "<variable-restriction evaluator=\"" + replaceIllegalChars( descr.getEvaluator() ) + "\" identifier=\"" + descr.getIdentifier() + "\" />" + XmlDumper.eol; } public void visitPatternDescr(final PatternDescr descr) { this.patternContext = true; this.template = new String(); StringBuilder localString = new StringBuilder(); if ( descr.getDescrs() != Collections.EMPTY_LIST ) { if ( descr.getIdentifier() != null ) { localString.append( "<pattern identifier=\"" + descr.getIdentifier() + "\" object-type=\"" + descr.getObjectType() + "\" >" + XmlDumper.eol + processDescrList( descr.getDescrs() ) + XmlDumper.eol ); } else { localString.append( "<pattern object-type=\"" + descr.getObjectType() + "\" >" + XmlDumper.eol + processDescrList( descr.getDescrs() ) + XmlDumper.eol ); } } else { if ( descr.getIdentifier() != null ) { localString.append( "<pattern identifier=\"" + descr.getIdentifier() + "\" object-type=\"" + descr.getObjectType() + "\" >" + XmlDumper.eol );; } else { localString.append( "<pattern object-type=\"" + descr.getObjectType() + "\" >" + XmlDumper.eol ); } } if ( descr.getSource() != null ) { visit( descr.getSource() ); localString.append( this.template ); } localString.append( "</pattern>" + XmlDumper.eol ); this.template = localString.toString(); this.patternContext = false; } public void visitExprConstraintDescr(final ExprConstraintDescr descr) { this.template = "<expr>" + XmlDumper.eol + StringUtils.escapeXmlString(descr.getExpression()) + XmlDumper.eol + "</expr>"; // if ( !descr.getRestrictions().isEmpty() ) { // this.template = "<field-constraint field-name=\"" + descr.getFieldName() + "\"> " + XmlDumper.eol + processFieldConstraint( descr.getRestrictions() ) + XmlDumper.eol + "</field-constraint>"; // } } public void visitCollectDescr(final CollectDescr descr) { StringBuilder tmpstr = new StringBuilder(); tmpstr.append( "<from> <collect>" ); visit( descr.getInputPattern() ); tmpstr.append( this.template ); tmpstr.append( " </collect> </from> " ); this.template = tmpstr.toString(); } public void visitAccumulateDescr(final AccumulateDescr descr) { String tmpstr = new String(); tmpstr += this.template + " <from> <accumulate> "; if ( descr.isSinglePattern() ) { visitPatternDescr( descr.getInputPattern() ); } else { this.patternContext = false; visit( descr.getInput() ); } tmpstr += this.template; if ( descr.isExternalFunction() ) { AccumulateFunctionCallDescr func = descr.getFunctions().get( 0 ); tmpstr += "<external-function evaluator=\"" + func.getFunction() + "\" expression=\"" + func.getParams()[0] + "\"/>"; } else tmpstr += "<init>" + descr.getInitCode() + "</init><action>" + descr.getActionCode() + "</action><result>" + descr.getResultCode() + "</result>"; this.template = tmpstr + " </accumulate> </from> "; } public void visitFromDescr(final FromDescr descr) { String tmpstr = new String(); tmpstr += this.template + " <from> <expression> "; tmpstr += descr.getDataSource(); this.template = tmpstr + " </expression> </from> "; } public void visitForallDescr(final ForallDescr descr) { this.template = "<forall>" + processDescrList( descr.getDescrs() ) + "</forall>"; } public void visitEvalDescr(final EvalDescr descr) { this.template = new String(); this.template = "<eval>" + replaceIllegalChars( (String) descr.getContent() ) + "</eval>" + XmlDumper.eol; } public void visitExistsDescr(final ExistsDescr descr) { this.template = new String(); if ( descr.getDescrs() != Collections.EMPTY_LIST ) { this.template = "<exists>" + processDescrList( descr.getDescrs() ) + "</exists>"; } else { this.template = "<exists> </exists>"; } } public void visitBindingDescr(final BindingDescr descr) { this.template = new String(); this.template = "<field-binding field-name=\"" + descr.getExpression() + "\" identifier=\"" + descr.getVariable() + "\" />" + XmlDumper.eol; } public void visitFunctionDescr(final FunctionDescr functionDescr) { this.template = new String(); final String parameterTemplate = processParameters( functionDescr.getParameterNames(), functionDescr.getParameterTypes() ); this.template = "<function return-type=\"" + functionDescr.getReturnType() + "\" name=\"" + functionDescr.getName() + "\">" + XmlDumper.eol + parameterTemplate + "<body>" + XmlDumper.eol + replaceIllegalChars( functionDescr.getText() ) + XmlDumper.eol + "</body>" + XmlDumper.eol + "</function>" + XmlDumper.eol; } public void visitLiteralRestrictionDescr(final LiteralRestrictionDescr descr) { this.template = new String(); this.template = "<literal-restriction evaluator=\"" + replaceIllegalChars( descr.getEvaluator() ) + "\" value=\"" + replaceIllegalChars( descr.getText() ) + "\" />" + XmlDumper.eol; } public void visitQualifiedIdentifierRestrictionDescr(final QualifiedIdentifierRestrictionDescr descr) { this.template = new String(); this.template = "<qualified-identifier-restriction evaluator=\"" + replaceIllegalChars( descr.getEvaluator() ) + "\">" + replaceIllegalChars( descr.getText() ) + " </qualified-identifier-restriction>" + XmlDumper.eol; } public void visitNotDescr(final NotDescr descr) { this.template = new String(); if ( descr.getDescrs() != Collections.EMPTY_LIST ) { this.template = "<not>" + processDescrList( descr.getDescrs() ) + "</not>"; } else { this.template = "<not> </not>"; } } public void visitOrDescr(final OrDescr descr) { this.template = new String(); if ( descr.getDescrs() != Collections.EMPTY_LIST ) { if ( !this.patternContext ) this.template = "<or-conditional-element>" + processDescrList( descr.getDescrs() ) + "</or-conditional-element>"; else this.template = "<or-constraint-connective>" + processDescrList( descr.getDescrs() ) + "</or-constraint-connective>"; } } public void visitPackageDescr(final PackageDescr packageDescr) { final String packageName = packageDescr.getName(); final String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> " + XmlDumper.eol + " <package name=\"" + packageName + "\" " + XmlDumper.eol + "\txmlns=\"http://drools.org/drools-5.2\" " + XmlDumper.eol + "\txmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\" " + XmlDumper.eol + "\txs:schemaLocation=\"http://drools.org/drools-5.2 drools.org/drools-5.2.xsd\"> " + XmlDumper.eol; appendXmlDump( xmlString ); appendXmlDump( processImportsList( packageDescr.getImports() ) ); appendXmlDump( processGlobalsList( packageDescr.getGlobals() ) ); appendXmlDump( processFunctionImportsList( packageDescr.getFunctionImports() )); appendXmlDump( processFunctionsList( packageDescr.getFunctions() ) ); appendXmlDump( processRules( packageDescr.getRules() ) ); appendXmlDump( "</package>" ); } public void visitPredicateDescr(final PredicateDescr descr) { this.template = new String(); this.template = "<predicate>" + replaceIllegalChars( (String) descr.getContent() ) + "</predicate>" + XmlDumper.eol; } public void visitReturnValueRestrictionDescr(final ReturnValueRestrictionDescr descr) { this.template = new String(); this.template = "<return-value-restriction evaluator=\"" + replaceIllegalChars( descr.getEvaluator() ) + "\" >" + replaceIllegalChars( (String) descr.getContent() ) + "</return-value-restriction>" + XmlDumper.eol; } public void visitQueryDescr(final QueryDescr descr) { this.template = new String(); this.template = "<query name=\"" + descr.getName() + "\">" + "<lhs>" + processDescrList( descr.getLhs().getDescrs() ) + "</lhs>" + "</query>"; } private String processRules(final List rules) { String ruleList = ""; for ( final Iterator iterator = rules.iterator(); iterator.hasNext(); ) { final RuleDescr ruleDescr = (RuleDescr) iterator.next(); String rule = "<rule name=\"" + ruleDescr.getName() + "\">" + XmlDumper.eol; final String attribute = processAttribute( ruleDescr.getAttributes().values() ); String lhs = ""; if ( ruleDescr.getLhs().getDescrs() != Collections.EMPTY_LIST ) { lhs = "<lhs>" + processDescrList( ruleDescr.getLhs().getDescrs() ) + "</lhs>"; } else { lhs = "<lhs> </lhs>"; } final String rhs = "<rhs>" + replaceIllegalChars( (String) ruleDescr.getConsequence() ) + "</rhs>" + XmlDumper.eol; rule += attribute; rule += lhs; rule += rhs; rule += "</rule>"; ruleList += rule; } return ruleList + XmlDumper.eol; } // private String processFieldConstraint(final List list) { // String descrString = ""; // for ( final Iterator it = list.iterator(); it.hasNext(); ) { // final Object temp = it.next(); // visit( temp ); // descrString += this.template; // } // return descrString; // } // // public void visitRestrictionConnectiveDescr(final RestrictionConnectiveDescr descr) { // this.template = new String(); // final List restrictions = descr.getRestrictions(); // final String xmlTag = descr.getConnective() == RestrictionConnectiveDescr.OR ? RestrictionConnectiveHandler.OR : RestrictionConnectiveHandler.AND; // // if ( restrictions != Collections.EMPTY_LIST ) { // this.template = "<" + xmlTag + ">"; // this.template += processDescrList( restrictions ); // this.template += "</" + xmlTag + ">"; // } // } private String processDescrList(final List descr) { String descrString = ""; for ( final Iterator iterator = descr.iterator(); iterator.hasNext(); ) { visit( iterator.next() ); descrString += this.template; descrString += XmlDumper.eol; } return descrString + XmlDumper.eol; } private String processFunctionsList(final List functions) { String functionList = ""; for ( final Iterator iterator = functions.iterator(); iterator.hasNext(); ) { visit( iterator.next() ); functionList += this.template; } return functionList + XmlDumper.eol; } private String processAttribute(final Collection<AttributeDescr> attributes ) { String attributeList = ""; for ( final AttributeDescr attributeDescr : attributes) { visit( attributeDescr ); attributeList += this.template; } return attributeList + XmlDumper.eol; } private String processParameters(final List parameterNames, final List parameterTypes) { String paramList = ""; int i = 0; for ( final Iterator iterator = parameterNames.iterator(); iterator.hasNext(); i++ ) { final String paramName = (String) iterator.next(); final String paramType = (String) parameterTypes.get( i ); final String paramTemplate = "<parameter identifier=\"" + paramName + "\" type=\"" + paramType + "\" />" + XmlDumper.eol; paramList += paramTemplate; } return paramList + XmlDumper.eol; } private String processFunctionImportsList(final List imports) { String importList = ""; for ( final Iterator it = imports.iterator(); it.hasNext(); ) { final String importString = ((FunctionImportDescr) it.next()).getTarget(); final String importTemplate = "<importfunction name=\"" + importString + "\"/>" + XmlDumper.eol; importList += importTemplate; } return importList + XmlDumper.eol; } private String processGlobalsList(final List globals) { String globalList = ""; for ( final Iterator iterator = globals.iterator(); iterator.hasNext(); ) { final GlobalDescr global = (GlobalDescr) iterator.next(); final String identifier = global.getIdentifier(); final String type = global.getType(); final String globalTemplate = "<global identifier=\"" + identifier + "\" type=\"" + type + "\" />" + XmlDumper.eol; globalList += globalTemplate; } return globalList + XmlDumper.eol; } private String processImportsList(final List imports) { String importList = ""; for ( final Iterator iterator = imports.iterator(); iterator.hasNext(); ) { final String importString = ((ImportDescr) iterator.next()).getTarget(); final String importTemplate = "<import name=\"" + importString + "\" /> " + XmlDumper.eol; importList += importTemplate; } return importList + XmlDumper.eol; } private void appendXmlDump(final String temp) { this.xmlDump.append( temp ); } /** * Replace illegal xml characters with their escaped equivalent * <P>The escaped characters are : * <ul> * <li> < * <li> > * <li> & * </ul> * </p> */ public static String replaceIllegalChars(final String code) { final StringBuilder sb = new StringBuilder(); if ( code != null ) { final int n = code.length(); for ( int i = 0; i < n; i++ ) { final char c = code.charAt( i ); switch ( c ) { case '<' : sb.append( "&lt;" ); break; case '>' : sb.append( "&gt;" ); break; case '&' : sb.append( "&amp;" ); break; default : sb.append( c ); break; } } } else { sb.append( "null" ); } return sb.toString(); } }
3e1c7b9db742ae1a60b22e9cd6b0497708642bb3
1,731
java
Java
blueprint/plugin/blueprint-maven-plugin/src/main/java/org/apache/aries/blueprint/plugin/handlers/javax/PreDestroyHandler.java
aguibert/aries
f8a242901ef5b43074786ef8a6a3cd5742398a96
[ "Apache-2.0" ]
75
2015-01-09T20:20:37.000Z
2022-03-22T13:22:30.000Z
blueprint/plugin/blueprint-maven-plugin/src/main/java/org/apache/aries/blueprint/plugin/handlers/javax/PreDestroyHandler.java
aguibert/aries
f8a242901ef5b43074786ef8a6a3cd5742398a96
[ "Apache-2.0" ]
77
2015-02-06T11:24:25.000Z
2022-03-18T17:41:52.000Z
blueprint/plugin/blueprint-maven-plugin/src/main/java/org/apache/aries/blueprint/plugin/handlers/javax/PreDestroyHandler.java
coheigea/aries
457551c4dda9ceca2e57572c121c605afb52db36
[ "Apache-2.0" ]
157
2015-01-12T20:43:13.000Z
2022-01-31T12:11:40.000Z
40.255814
138
0.753322
12,090
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.blueprint.plugin.handlers.javax; import org.apache.aries.blueprint.plugin.spi.BeanEnricher; import org.apache.aries.blueprint.plugin.spi.ContextEnricher; import org.apache.aries.blueprint.plugin.spi.MethodAnnotationHandler; import javax.annotation.PreDestroy; import java.lang.reflect.Method; import java.util.List; public class PreDestroyHandler implements MethodAnnotationHandler<PreDestroy> { @Override public Class<PreDestroy> getAnnotation() { return PreDestroy.class; } @Override public void handleMethodAnnotation(Class<?> clazz, List<Method> methods, ContextEnricher contextEnricher, BeanEnricher beanEnricher) { if(methods.size() > 1){ throw new IllegalArgumentException("There can be only one method annotated with @PreDestroy in bean"); } beanEnricher.addAttribute("destroy-method", methods.get(0).getName()); } }
3e1c7c094eb7cc95226d6c1688caa627847f392e
521
java
Java
UserManager/src/com/yh/service/account/AccountService.java
wenzi712/YHSEM
36568fff47ba6c9362d7fa9f04578610f9eff77c
[ "MIT" ]
null
null
null
UserManager/src/com/yh/service/account/AccountService.java
wenzi712/YHSEM
36568fff47ba6c9362d7fa9f04578610f9eff77c
[ "MIT" ]
1
2019-02-21T04:51:51.000Z
2019-02-21T04:51:51.000Z
UserManager/src/com/yh/service/account/AccountService.java
young-er/YHSEM
5136f0d87709cb4a6a7c5343441b90a5a6932e0a
[ "MIT" ]
2
2019-02-20T15:48:22.000Z
2019-02-24T08:53:54.000Z
14.081081
56
0.767754
12,091
package com.yh.service.account; import java.util.List; import java.util.Map; import com.yh.pojo.account.Account; public interface AccountService { Map<String, Object> queryUserInfo(Account account); void insertUserInfo(Account account); Account selectUserByID(Account account); void updateUserInfo(Account account); void deleteUser(Account account); Map<String, Object> queryDisabledlist(Account account); List<Account> queryAccountType(); void updateEnabledInfoFlow(Account account); }
3e1c7c1b286535a45baabde836f5bb4e1fa09d35
2,044
java
Java
open_serv/open_serv_backstage/src/main/java/com/dc/city/vo/config/ServeConfigQueryVo.java
pnoker/serv
c92b273e6ae0dbb15ef954a29ca79b3697ae57a1
[ "Apache-2.0" ]
null
null
null
open_serv/open_serv_backstage/src/main/java/com/dc/city/vo/config/ServeConfigQueryVo.java
pnoker/serv
c92b273e6ae0dbb15ef954a29ca79b3697ae57a1
[ "Apache-2.0" ]
null
null
null
open_serv/open_serv_backstage/src/main/java/com/dc/city/vo/config/ServeConfigQueryVo.java
pnoker/serv
c92b273e6ae0dbb15ef954a29ca79b3697ae57a1
[ "Apache-2.0" ]
1
2022-02-19T14:04:16.000Z
2022-02-19T14:04:16.000Z
21.072165
75
0.643836
12,092
/** * Copyright (DigitalChina) 2016-2020, DigitalChina. * * 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.dc.city.vo.config; import javax.ws.rs.FormParam; import org.codehaus.jackson.annotate.JsonIgnore; import com.dc.city.pojo.serve.config.ServeConfigQueryPo; /** * 服务列表查询参数封住类 * * @author zhongdt * @version V1.0 创建时间:2016年3月24日 下午5:30:27 * Copyright 2016 by DigitalChina */ public class ServeConfigQueryVo extends ServeConfigQueryPo { public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } /** * */ private static final long serialVersionUID = 1L; /** * 每页记录数 */ @JsonIgnore @FormParam("pageSize") private int pageSize; //datatables 分页字段 @JsonIgnore @FormParam("start") private int start; //datatables 分页字段 @JsonIgnore @FormParam("length") private int length; /** * 当前页码 */ @JsonIgnore @FormParam("currentPage") private int currentPage; public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } }
3e1c7d2cf32227a27307691301fc30d4cec71705
1,118
java
Java
src/test/java/edu/wvu/ferl/store/impl/SimpleStoredRuleImplTest.java
jbunting/ferl
6436b2c1f3974df10d7258abb390f4218e737316
[ "Apache-2.0" ]
null
null
null
src/test/java/edu/wvu/ferl/store/impl/SimpleStoredRuleImplTest.java
jbunting/ferl
6436b2c1f3974df10d7258abb390f4218e737316
[ "Apache-2.0" ]
null
null
null
src/test/java/edu/wvu/ferl/store/impl/SimpleStoredRuleImplTest.java
jbunting/ferl
6436b2c1f3974df10d7258abb390f4218e737316
[ "Apache-2.0" ]
1
2019-04-01T09:24:48.000Z
2019-04-01T09:24:48.000Z
32.882353
158
0.742397
12,093
/** * Copyright 2008 West Virginia University * * 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 edu.wvu.ferl.store.impl; import java.util.Map; /** * @author jbunting * @TODO Document Me! * Created by IntelliJ IDEA. * Date: Feb 29, 2008 * Time: 8:02:32 AM */ public class SimpleStoredRuleImplTest extends AbstractStoredRuleImplTest { protected StoredRuleImpl createStoredRuleImpl(String uri, String name, String description, String language, String script, Map<Object, Object> properties) { return new StoredRuleImpl(uri, name, description, language, script, properties); } }
3e1c7db1cdcd35e6e4be8526c1d9866e9b3b7321
435
java
Java
matrix/core/src/main/java/com/cobee/core/common/persistence/annotation/CreatedDate.java
litterforest/cobee
f2bfa594cb9b31c3b6533d0780a0c3e6dfd87d99
[ "Apache-2.0" ]
2
2017-03-30T11:06:55.000Z
2019-05-28T13:33:06.000Z
matrix/core/src/main/java/com/cobee/core/common/persistence/annotation/CreatedDate.java
litterforest/cobee
f2bfa594cb9b31c3b6533d0780a0c3e6dfd87d99
[ "Apache-2.0" ]
null
null
null
matrix/core/src/main/java/com/cobee/core/common/persistence/annotation/CreatedDate.java
litterforest/cobee
f2bfa594cb9b31c3b6533d0780a0c3e6dfd87d99
[ "Apache-2.0" ]
null
null
null
24.166667
60
0.795402
12,094
package com.cobee.core.common.persistence.annotation; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Documented @Retention(RUNTIME) @Target(FIELD) @Inherited public @interface CreatedDate { }
3e1c8023447fc16df156d816075cb6107b3b521a
33,184
java
Java
data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/AbstractPatternBasedMethod.java
henriquelsmti/micronaut-data
66e990847a17c02c3e4d0fcbe7f98bde408f6702
[ "Apache-2.0" ]
null
null
null
data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/AbstractPatternBasedMethod.java
henriquelsmti/micronaut-data
66e990847a17c02c3e4d0fcbe7f98bde408f6702
[ "Apache-2.0" ]
null
null
null
data-processor/src/main/java/io/micronaut/data/processor/visitors/finders/AbstractPatternBasedMethod.java
henriquelsmti/micronaut-data
66e990847a17c02c3e4d0fcbe7f98bde408f6702
[ "Apache-2.0" ]
null
null
null
44.542282
278
0.600078
12,095
/* * Copyright 2017-2020 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.micronaut.data.processor.visitors.finders; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import io.micronaut.core.annotation.AnnotationMetadata; import io.micronaut.core.annotation.AnnotationValue; import io.micronaut.core.annotation.Introspected; import io.micronaut.core.async.annotation.SingleResult; import io.micronaut.core.naming.NameUtils; import io.micronaut.core.reflect.ClassUtils; import io.micronaut.core.util.CollectionUtils; import io.micronaut.core.util.StringUtils; import io.micronaut.data.annotation.*; import io.micronaut.data.intercept.*; import io.micronaut.data.intercept.async.*; import io.micronaut.data.intercept.reactive.*; import io.micronaut.data.model.Association; import io.micronaut.data.model.PersistentProperty; import io.micronaut.data.model.Sort; import io.micronaut.data.model.query.AssociationQuery; import io.micronaut.data.model.query.QueryModel; import io.micronaut.data.model.query.builder.QueryBuilder; import io.micronaut.data.model.query.factory.Projections; import io.micronaut.data.processor.model.SourcePersistentEntity; import io.micronaut.data.processor.model.SourcePersistentProperty; import io.micronaut.data.processor.visitors.MatchContext; import io.micronaut.data.processor.visitors.MethodMatchContext; import io.micronaut.inject.ast.ClassElement; import io.micronaut.inject.ast.MethodElement; import io.micronaut.inject.ast.ParameterElement; import io.micronaut.inject.ast.PropertyElement; import org.reactivestreams.Publisher; import javax.annotation.Nonnull; import java.lang.reflect.Array; import java.lang.reflect.Modifier; import java.util.*; import java.util.concurrent.CompletionStage; import java.util.concurrent.Future; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; /** * A method candidate based on pattern matching. * * @author graemerocher * @since 1.1.0 */ public abstract class AbstractPatternBasedMethod implements MethodCandidate { private static final Pattern ORDER_BY_PATTERN = Pattern.compile("(.*)OrderBy([\\w\\d]+)"); private static final Pattern FOR_UPDATE_PATTERN = Pattern.compile("(.*)ForUpdate$"); private static final String DELETE = "delete"; private static final String UPDATE = "update"; private static final String VOID = "void"; protected final Pattern pattern; /** * Default constructor. * * @param pattern The pattern to match */ protected AbstractPatternBasedMethod(@NonNull Pattern pattern) { this.pattern = pattern; } @Override public boolean isMethodMatch(@NonNull MethodElement methodElement, @NonNull MatchContext matchContext) { return pattern.matcher(methodElement.getName()).find(); } /** * Matches order by definitions in the query sequence. * * @param querySequence The query sequence * @param orders A list or orders to populate * @return The new query sequence minus any order by definitions */ protected String matchOrder(String querySequence, List<Sort.Order> orders) { if (ORDER_BY_PATTERN.matcher(querySequence).matches()) { Matcher matcher = ORDER_BY_PATTERN.matcher(querySequence); StringBuffer buffer = new StringBuffer(); if (matcher.find()) { matcher.appendReplacement(buffer, "$1"); String orderDefGroup = matcher.group(2); if (StringUtils.isNotEmpty(orderDefGroup)) { String[] orderDefItems = orderDefGroup.split("And"); for (String orderDef : orderDefItems) { String prop = NameUtils.decapitalize(orderDef); if (prop.endsWith("Desc")) { orders.add(Sort.Order.desc(prop.substring(0, prop.length() - 4))); } else if (prop.endsWith("Asc")) { orders.add(Sort.Order.asc(prop.substring(0, prop.length() - 3))); } else { orders.add(Sort.Order.asc(prop)); } } } } matcher.appendTail(buffer); return buffer.toString(); } return querySequence; } /** * Matches for update definitions in the query sequence. * * * @param matchContext * @param querySequence The query sequence * @return The new query sequence without the for update definitions */ protected String matchForUpdate(MethodMatchContext matchContext, String querySequence) { if (matchContext.getQueryBuilder().supportsForUpdate()) { Matcher matcher = FOR_UPDATE_PATTERN.matcher(querySequence); if (matcher.matches()) { return matcher.group(1); } } return querySequence; } /** * Matches projections. * * @param matchContext The match context * @param projectionExpressions the projection expressions * @param projectionSequence The sequence */ protected void matchProjections(@NonNull MethodMatchContext matchContext, List<ProjectionMethodExpression> projectionExpressions, String projectionSequence) { ProjectionMethodExpression currentExpression = ProjectionMethodExpression.matchProjection( matchContext, projectionSequence ); if (currentExpression != null) { // add to list of expressions projectionExpressions.add(currentExpression); } } /** * Build the {@link MethodMatchInfo}. * * @param matchContext The match context * @param queryResultType The query result type * @param query The query * @return The info or null if it can't be built */ @Nullable protected MethodMatchInfo buildInfo( @NonNull MethodMatchContext matchContext, @NonNull ClassElement queryResultType, @Nullable QueryModel query) { ClassElement returnType = matchContext.getReturnType(); ClassElement typeArgument = returnType.getFirstTypeArgument().orElse(null); if (!returnType.getName().equals(VOID)) { if (query instanceof RawQuery) { final AnnotationMetadata annotationMetadata = matchContext.getAnnotationMetadata(); String q = annotationMetadata.stringValue(Query.class).orElse(null); if (q != null) { final boolean readOnly = annotationMetadata .booleanValue(Query.class, "readOnly").orElse(true); q = q.trim().toLowerCase(Locale.ENGLISH); Class<? extends DataInterceptor> interceptorType = null; if (q.startsWith(DELETE)) { interceptorType = resolveInterceptorTypeByOperationType(MethodMatchInfo.OperationType.DELETE, returnType); } else if (q.startsWith(UPDATE) || !readOnly) { interceptorType = resolveInterceptorTypeByOperationType(MethodMatchInfo.OperationType.UPDATE, returnType); } if (interceptorType != null) { return new MethodMatchInfo(queryResultType, query, getInterceptorElement(matchContext, interceptorType)); } } } if (isValidResultType(returnType)) { if (TypeUtils.areTypesCompatible(returnType, queryResultType)) { if (isFindByIdQuery(matchContext, queryResultType, query)) { final Class<FindByIdInterceptor> type = FindByIdInterceptor.class; return new MethodMatchInfo(matchContext.getReturnType(), query, getInterceptorElement(matchContext, type)); } else { return new MethodMatchInfo(queryResultType, query, getInterceptorElement(matchContext, FindOneInterceptor.class)); } } else { if (query != null && returnType.hasStereotype(Introspected.class) && queryResultType.hasStereotype(MappedEntity.class)) { if (!ignoreAttemptProjection(query) && !attemptProjection(matchContext, queryResultType, query, returnType)) { return null; } return new MethodMatchInfo(returnType, query, getInterceptorElement(matchContext, FindOneInterceptor.class), true); } else { matchContext.fail("Query results in a type [" + queryResultType.getName() + "] whilst method returns an incompatible type: " + returnType.getName()); return null; } } } else if (typeArgument != null) { boolean isPage = isPage(matchContext, typeArgument); boolean isSlice = isSlice(matchContext, typeArgument); if (returnType.isAssignable(CompletionStage.class) || returnType.isAssignable(Future.class)) { ClassElement firstTypeArgument; if (typeArgument.isAssignable(Iterable.class) || isSlice || isPage) { firstTypeArgument = typeArgument.getFirstTypeArgument().orElse(null); if (firstTypeArgument == null) { matchContext.fail("Async return type missing type argument"); return null; } } else { firstTypeArgument = typeArgument; } Class<? extends DataInterceptor> interceptorType = resolveInterceptorType(matchContext, typeArgument, queryResultType, query, isPage, isSlice); if (interceptorType == null) { matchContext.fail("Unsupported Async return type: " + firstTypeArgument.getName()); return null; } ClassElement finalResultType = firstTypeArgument; if (TypeUtils.isObjectClass(finalResultType)) { finalResultType = matchContext.getRootEntity().getType(); } boolean dto = resolveDtoIfNecessary(matchContext, queryResultType, query, finalResultType); if (matchContext.isFailing()) { return null; } else { return new MethodMatchInfo(finalResultType, query, getInterceptorElement(matchContext, interceptorType), dto); } } else if (returnType.isAssignable(Publisher.class) || returnType.getPackageName().equals("io.reactivex")) { ClassElement finalResultType = TypeUtils.isObjectClass(typeArgument) ? matchContext.getRootEntity().getType() : typeArgument; boolean isContainerType = isSlice || isPage; if (isContainerType) { finalResultType = typeArgument.getFirstTypeArgument().orElse(matchContext.getRootEntity().getType()); } Class<? extends DataInterceptor> interceptorType = resolveReactiveInterceptorType(matchContext, returnType, queryResultType, query, isPage, isSlice); boolean dto = resolveDtoIfNecessary(matchContext, queryResultType, query, finalResultType); if (matchContext.isFailing()) { return null; } else { return new MethodMatchInfo(finalResultType, query, getInterceptorElement(matchContext, interceptorType), dto); } } else { boolean dto = false; if (!TypeUtils.areTypesCompatible(typeArgument, queryResultType)) { if ((typeArgument.hasStereotype(Introspected.class) && queryResultType.hasStereotype(MappedEntity.class))) { QueryModel projectionQuery = query != null ? query : QueryModel.from(matchContext.getRootEntity()); if (!ignoreAttemptProjection(query) && !attemptProjection(matchContext, queryResultType, projectionQuery, typeArgument)) { return null; } query = projectionQuery; dto = true; } else { matchContext.fail("Query results in a type [" + queryResultType.getName() + "] whilst method returns an incompatible type: " + typeArgument.getName()); return null; } } Class<? extends DataInterceptor> interceptor = resolveFindInterceptor(matchContext); if (interceptor != null) { return new MethodMatchInfo(typeArgument, query, getInterceptorElement(matchContext, interceptor), dto); } } } } matchContext.fail("Unsupported Repository method return type"); return null; } /** * @param matchContext The match context * @return The resolved {@link DataInterceptor} or {@literal null}. */ @Nullable protected Class<? extends DataInterceptor> resolveFindInterceptor(@NonNull MethodMatchContext matchContext) { ClassElement returnType = matchContext.getReturnType(); if (isPage(matchContext, returnType)) { return FindPageInterceptor.class; } else if (isSlice(matchContext, returnType)) { return FindSliceInterceptor.class; } else if (returnType.isAssignable(Iterable.class)) { return FindAllInterceptor.class; } else if (returnType.isAssignable(Stream.class)) { return FindStreamInterceptor.class; } else if (returnType.isAssignable(Optional.class)) { return FindOptionalInterceptor.class; } else if (returnType.isAssignable(Publisher.class)) { return FindAllReactiveInterceptor.class; } return null; } /** * * @param operationType Operation Type * @param returnType Return Type * @return The resolved {@link DataInterceptor} or {@literal null}. */ @Nullable protected Class<? extends DataInterceptor> resolveInterceptorTypeByOperationType(MethodMatchInfo.OperationType operationType, ClassElement returnType) { if (operationType == MethodMatchInfo.OperationType.DELETE) { if (TypeUtils.isReactiveType(returnType)) { return DeleteAllReactiveInterceptor.class; } else if (TypeUtils.isFutureType(returnType)) { return DeleteAllAsyncInterceptor.class; } else { return DeleteAllInterceptor.class; } } if (operationType == MethodMatchInfo.OperationType.UPDATE) { if (TypeUtils.isReactiveType(returnType)) { return UpdateReactiveInterceptor.class; } else if (TypeUtils.isFutureType(returnType)) { return UpdateAsyncInterceptor.class; } else { return UpdateInterceptor.class; } } return null; } /** * * @param matchContext The match context * @param returnType Return Type * @param queryResultType Query Result Type * @param query Query * @param isPage {@literal true} if the type argument performs the {@link TypeRole#PAGE} role. * @param isSlice {@literal true} if the type argument performs the {@link TypeRole#SLICE} role. * @return The resolved {@link DataInterceptor} or {@literal null}. */ @NonNull protected Class<? extends DataInterceptor> resolveReactiveInterceptorType(@NonNull MethodMatchContext matchContext, @NonNull ClassElement returnType, @NonNull ClassElement queryResultType, @Nullable QueryModel query, boolean isPage, boolean isSlice) { if (isPage) { return FindPageReactiveInterceptor.class; } else if (isSlice) { return FindSliceReactiveInterceptor.class; } else { if (isReactiveSingleResult(returnType)) { if (isFindByIdQuery(matchContext, queryResultType, query)) { return FindByIdReactiveInterceptor.class; } else { return FindOneReactiveInterceptor.class; } } else { return FindAllReactiveInterceptor.class; } } } /** * * @param matchContext The match context * @param typeArgument Type Argument * @param queryResultType Query Result Type * @param query Query * @param isPage {@literal true} if the type argument performs the {@link TypeRole#PAGE} role. * @param isSlice {@literal true} if the type argument performs the {@link TypeRole#SLICE} role. * @return The resolved {@link DataInterceptor} or {@literal null}. */ @Nullable protected Class<? extends DataInterceptor> resolveInterceptorType(@NonNull MethodMatchContext matchContext, @NonNull ClassElement typeArgument, @NonNull ClassElement queryResultType, @Nullable QueryModel query, boolean isPage, boolean isSlice) { if (isPage) { return FindPageAsyncInterceptor.class; } else if (isSlice) { return FindSliceAsyncInterceptor.class; } else if (typeArgument.isAssignable(Iterable.class)) { return FindAllAsyncInterceptor.class; } else if (isValidResultType(typeArgument)) { if (isFindByIdQuery(matchContext, queryResultType, query)) { return FindByIdAsyncInterceptor.class; } else { return FindOneAsyncInterceptor.class; } } return null; } /** * * @param matchContext The match context * @param typeArgument Type argument * @return {@literal true} if the type argument performs the {@link TypeRole#PAGE} role. */ protected boolean isPage(@NonNull MethodMatchContext matchContext, @NonNull ClassElement typeArgument) { return matchContext.isTypeInRole( typeArgument, TypeRole.PAGE ); } /** * * @param matchContext The match context * @param typeArgument type argument * @return {@literal true} if the type argument performs the {@link TypeRole#SLICE} role. */ protected boolean isSlice(@NonNull MethodMatchContext matchContext, @NonNull ClassElement typeArgument) { return matchContext.isTypeInRole( typeArgument, TypeRole.SLICE ); } /** * Obtain the interceptor element for the given class. * * @param matchContext The match context * @param type The type * @return The element */ protected ClassElement getInterceptorElement(@NonNull MethodMatchContext matchContext, Class<? extends DataInterceptor> type) { return matchContext.getVisitorContext().getClassElement(type).orElseGet(() -> new DynamicClassElement(type)); } /** * Obtain the interceptor element for the given class name. * * @param matchContext The match context * @param type The type * @return The element */ protected ClassElement getInterceptorElement(@NonNull MethodMatchContext matchContext, String type) { return matchContext.getVisitorContext().getClassElement(type).orElseThrow(() -> new IllegalStateException("Unable to apply interceptor of type: " + type + ". The interceptor was not found on the classpath. Check your annotation processor configuration and try again.")); } private boolean isFindByIdQuery(@NonNull MethodMatchContext matchContext, @NonNull ClassElement queryResultType, @Nullable QueryModel query) { return matchContext.supportsImplicitQueries() && query != null && queryResultType.getName().equals(matchContext.getRootEntity().getName()) && isIdEquals(query); } private Boolean isIdEquals(@NonNull QueryModel query) { List<QueryModel.Criterion> criteria = query.getCriteria().getCriteria(); return criteria.size() == 1 && criteria.stream().findFirst().map(c -> c instanceof QueryModel.IdEquals).orElse(false); } private boolean resolveDtoIfNecessary( @NonNull MethodMatchContext matchContext, @NonNull ClassElement queryResultType, @Nullable QueryModel query, @NonNull ClassElement returnType) { if (!TypeUtils.areTypesCompatible(returnType, queryResultType)) { if (query != null && returnType.hasStereotype(Introspected.class) && queryResultType.hasStereotype(MappedEntity.class)) { if (ignoreAttemptProjection(query)) { return true; } if (attemptProjection(matchContext, queryResultType, query, returnType)) { return true; } } else { matchContext.fail("Query results in a type [" + queryResultType.getName() + "] whilst method returns an incompatible type: " + returnType.getName()); } } return false; } private boolean isValidResultType(ClassElement returnType) { return returnType.hasStereotype(Introspected.class) || ClassUtils.isJavaBasicType(returnType.getName()) || returnType.isPrimitive(); } private boolean isReactiveSingleResult(ClassElement returnType) { return returnType.hasStereotype(SingleResult.class) || returnType.isAssignable("io.reactivex.Single") || returnType.isAssignable("reactor.core.publisher.Mono"); } /** * * @param matchContext Match Context * @param queryResultType Query Result Type * @param query Query * @param returnType Return Type * @return returns {@literal false} if the attempt to create the projection fails. */ private boolean attemptProjection(@NonNull MethodMatchContext matchContext, @NonNull ClassElement queryResultType, @NonNull QueryModel query, ClassElement returnType) { List<PropertyElement> beanProperties = returnType.getBeanProperties(); SourcePersistentEntity entity = matchContext.getEntity(queryResultType); for (PropertyElement beanProperty : beanProperties) { String propertyName = beanProperty.getName(); if ("metaClass".equals(propertyName) && beanProperty.getType().isAssignable("groovy.lang.MetaClass")) { // ignore Groovy meta class continue; } SourcePersistentProperty pp = entity.getPropertyByName(propertyName); if (pp == null) { pp = entity.getIdOrVersionPropertyByName(propertyName); } if (pp == null) { matchContext.fail("Property " + propertyName + " is not present in entity: " + entity.getName()); return false; } if (!TypeUtils.areTypesCompatible(beanProperty.getType(), pp.getType())) { matchContext.fail("Property [" + propertyName + "] of type [" + beanProperty.getType().getName() + "] is not compatible with equivalent property declared in entity: " + entity.getName()); return false; } // add an alias projection for each property final QueryBuilder queryBuilder = matchContext.getQueryBuilder(); if (queryBuilder.shouldAliasProjections()) { query.projections().add(Projections.property(propertyName).aliased()); } else { query.projections().add(Projections.property(propertyName)); } } return true; } /** * Apply ordering. * * @param context The context * @param query The query * @param orderList The list mutate * @return True if an error occurred applying the order */ protected boolean applyOrderBy(@NonNull MethodMatchContext context, @NonNull QueryModel query, @NonNull List<Sort.Order> orderList) { if (CollectionUtils.isNotEmpty(orderList)) { SourcePersistentEntity entity = context.getRootEntity(); for (Sort.Order order : orderList) { String prop = order.getProperty(); if (!entity.getPath(prop).isPresent()) { context.fail("Cannot order by non-existent property: " + prop); return true; } } query.sort(Sort.of(orderList)); } return false; } /** * Apply for update. * * @param query The query */ protected void applyForUpdate(QueryModel query) { query.forUpdate(); } /** * * @param matchContext The match context * @return a List of annotations values for {@Join} annotation. */ @NonNull protected List<AnnotationValue<Join>> joinSpecsAtMatchContext(@NonNull MethodMatchContext matchContext) { final MethodMatchInfo.OperationType operationType = getOperationType(); if (operationType != MethodMatchInfo.OperationType.QUERY) { return matchContext.getAnnotationMetadata().getDeclaredAnnotationValuesByType(Join.class); } return matchContext.getAnnotationMetadata().getAnnotationValuesByType(Join.class); } /** * Apply the configured join specifications to the given query. * * @param matchContext The match context * @param query The query * @param rootEntity the root entity * @param joinSpecs The join specs * @return True if an error occurred applying the specs */ protected boolean applyJoinSpecs( @NonNull MethodMatchContext matchContext, @NonNull QueryModel query, @Nonnull SourcePersistentEntity rootEntity, @NonNull List<AnnotationValue<Join>> joinSpecs) { for (AnnotationValue<Join> joinSpec : joinSpecs) { String path = joinSpec.stringValue().orElse(null); Join.Type type = joinSpec.enumValue("type", Join.Type.class).orElse(Join.Type.FETCH); String alias = joinSpec.stringValue("alias").orElse(null); if (path != null) { PersistentProperty prop = rootEntity.getPropertyByPath(path).orElse(null); if (!(prop instanceof Association)) { matchContext.fail("Invalid join spec [" + path + "]. Property is not an association!"); return true; } else { boolean hasExisting = query.getCriteria().getCriteria().stream().anyMatch(c -> { if (c instanceof AssociationQuery) { AssociationQuery aq = (AssociationQuery) c; return aq.getAssociation().equals(prop); } return false; }); if (!hasExisting) { query.add(new AssociationQuery(path, (Association) prop)); } query.join(path, (Association) prop, type, alias); } } } return false; } /** * Builds a raw query for the given match context. Should be called for methods annotated with {@link Query} explicitly. * * @param matchContext The match context * @return The raw query or null if an error occurred */ protected RawQuery buildRawQuery(@NonNull MethodMatchContext matchContext) { MethodElement methodElement = matchContext.getMethodElement(); String queryString = methodElement.stringValue(Query.class).orElseThrow(() -> new IllegalStateException("Should only be called if Query has value!") ); List<ParameterElement> parameters = Arrays.asList(matchContext.getParameters()); Map<String, String> parameterBinding = new LinkedHashMap<>(parameters.size()); boolean namedParameters = matchContext.getRepositoryClass() .booleanValue(RepositoryConfiguration.class, "namedParameters").orElse(true); if (namedParameters) { Matcher matcher = QueryBuilder.VARIABLE_PATTERN.matcher(queryString); while (matcher.find()) { String name = matcher.group(3); Optional<ParameterElement> element = parameters.stream().filter(p -> p.getName().equals(name)).findFirst(); if (element.isPresent()) { parameterBinding.put(name, element.get().getName()); } else { matchContext.fail( "No method parameter found for named Query parameter : " + name ); return null; } } } else { Matcher matcher = QueryBuilder.VARIABLE_PATTERN.matcher(queryString); int index = 1; while (matcher.find()) { String name = matcher.group(3); Optional<ParameterElement> element = parameters.stream().filter(p -> p.getName().equals(name)).findFirst(); if (element.isPresent()) { parameterBinding.put(String.valueOf(index++), element.get().getName()); } else { matchContext.fail( "No method parameter found for named Query parameter : " + name ); return null; } } } return new RawQuery(matchContext.getRootEntity(), parameterBinding); } /** * @return The operation type */ protected @NonNull MethodMatchInfo.OperationType getOperationType() { return MethodMatchInfo.OperationType.QUERY; } private boolean ignoreAttemptProjection(@Nullable QueryModel query) { return query instanceof RawQuery; } /** * Internally used for dynamically defining a class element. */ private static class DynamicClassElement implements ClassElement { private final Class<? extends DataInterceptor> type; DynamicClassElement(Class<? extends DataInterceptor> type) { this.type = type; } @Override public boolean isAssignable(String type) { return false; } @Override public ClassElement toArray() { return new DynamicClassElement((Class<? extends DataInterceptor>) Array.newInstance(type, 0).getClass()); } @Override public ClassElement fromArray() { return new DynamicClassElement((Class<? extends DataInterceptor>) type.getComponentType()); } @Nonnull @Override public String getName() { return type.getName(); } @Override public boolean isProtected() { return Modifier.isProtected(type.getModifiers()); } @Override public boolean isPublic() { return Modifier.isPublic(type.getModifiers()); } @Nonnull @Override public Object getNativeType() { return type; } } }
3e1c806a4ff4172ccf36e50e529af35d1edfde8b
1,861
java
Java
app/src/main/java/us/shiroyama/android/firebaserealtimechat/widget/ScrollEdgeListener.java
kuwako/firebasePrac
52ed94679d3ce5d65224970399743e72736b7781
[ "Apache-2.0" ]
1
2021-07-24T10:55:34.000Z
2021-07-24T10:55:34.000Z
app/src/main/java/us/shiroyama/android/firebaserealtimechat/widget/ScrollEdgeListener.java
kuwako/firebasePrac
52ed94679d3ce5d65224970399743e72736b7781
[ "Apache-2.0" ]
null
null
null
app/src/main/java/us/shiroyama/android/firebaserealtimechat/widget/ScrollEdgeListener.java
kuwako/firebasePrac
52ed94679d3ce5d65224970399743e72736b7781
[ "Apache-2.0" ]
null
null
null
28.707692
90
0.63612
12,096
package us.shiroyama.android.firebaserealtimechat.widget; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; /** * RecyclerViewのtop/bottomに到達したことを知らせるリスナ * * @author Fumihiko Shiroyama (upchh@example.com) */ public class ScrollEdgeListener extends RecyclerView.OnScrollListener { private LinearLayoutManager linearLayoutManager; private int firstVisibleBackUp = 0; private int lastVisibleBackUp = 0; public ScrollEdgeListener(LinearLayoutManager linearLayoutManager) { this.linearLayoutManager = linearLayoutManager; } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int visibleItemCount = recyclerView.getChildCount(); int totalItemCount = linearLayoutManager.getItemCount(); int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition(); int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition(); if (totalItemCount <= visibleItemCount) { return; } // swipe down(つまり上スクロール) if (dy < 0) { if (firstVisibleBackUp != firstVisibleItemPosition) { if (firstVisibleItemPosition == 0) { onTop(); } firstVisibleBackUp = firstVisibleItemPosition; } return; } // swipe up(つまり下スクロール) if (dy > 0) { if (lastVisibleBackUp != lastVisibleItemPosition) { if (lastVisibleItemPosition == (totalItemCount - 1)) { onBottom(); } lastVisibleBackUp = lastVisibleItemPosition; } } } public void onTop() { } public void onBottom() { } }
3e1c80d5c60d6583d5f7186ddca9275785edb263
427
java
Java
Deck 1/Zick-Zack-Lauf.java
juliusrickert/rwth-codescape
be2a3deedd6ca41743ff37fda0ea8060373a7f98
[ "MIT" ]
5
2017-11-14T14:45:08.000Z
2020-11-18T01:26:10.000Z
Deck 1/Zick-Zack-Lauf.java
juliusrickert/rwth-codescape
be2a3deedd6ca41743ff37fda0ea8060373a7f98
[ "MIT" ]
null
null
null
Deck 1/Zick-Zack-Lauf.java
juliusrickert/rwth-codescape
be2a3deedd6ca41743ff37fda0ea8060373a7f98
[ "MIT" ]
5
2017-10-14T12:32:32.000Z
2020-11-10T22:25:25.000Z
18.565217
55
0.47541
12,097
import codescape.Dogbot; public class MyDogbot extends Dogbot { public void run() { String moves = "011101011100101110101110010111010"; for (int i = 0; i < moves.length(); i++) { char n = moves.charAt(i); switch (n) { case '0': move(); break; case '1': turnLeft(); break; case '2': pickUp(); break; } } } }
3e1c811b75f96a9a1f3621e057db07a56d11bf24
550
java
Java
25-01-2020/KBA1/src/Collections/ListstoArray.java
saikrishna2409/My-First-Repo
b58c09dc083ed55777ef77a1c536f76df09e60d9
[ "Apache-2.0" ]
null
null
null
25-01-2020/KBA1/src/Collections/ListstoArray.java
saikrishna2409/My-First-Repo
b58c09dc083ed55777ef77a1c536f76df09e60d9
[ "Apache-2.0" ]
27
2020-06-15T21:05:41.000Z
2022-03-02T09:29:43.000Z
25-01-2020/KBA1/src/Collections/ListstoArray.java
saikrishna2409/My-First-Repo
b58c09dc083ed55777ef77a1c536f76df09e60d9
[ "Apache-2.0" ]
null
null
null
22.916667
46
0.692727
12,098
package Collections; import java.util.Arrays; import java.util.ArrayList; import java.util.List; public class ListstoArray { public static void main(String[] args) { // TODO Auto-generated method stub List<String> l1 = new ArrayList<String>(); l1.add("a"); l1.add("ab"); String[] array =new String[l1.size()]; l1.toArray(array); System.out.println(Arrays.toString(array)); l1.add("adb"); System.out.println(l1); String[] array1 =new String[l1.size()]; l1.toArray(array1); System.out.println(Arrays.toString(array1)); } }
3e1c818ab9252dfdffd34935d571594b84e3d7de
80,322
java
Java
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateIntervalFormat.java
gaybro8777/j2objc
9234ca9bed5d16a2f9914d55001ce1ec2e84dc9d
[ "Apache-2.0" ]
4,901
2015-01-02T09:29:18.000Z
2022-03-29T06:51:04.000Z
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateIntervalFormat.java
1Crazymoney/j2objc
444f387445b3f22fd807b7c72eca484ea8823c8e
[ "Apache-2.0" ]
853
2015-01-03T08:13:19.000Z
2022-03-22T18:51:24.000Z
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateIntervalFormat.java
1Crazymoney/j2objc
444f387445b3f22fd807b7c72eca484ea8823c8e
[ "Apache-2.0" ]
964
2015-01-08T08:52:00.000Z
2022-03-23T16:36:47.000Z
43.02196
176
0.59132
12,099
/* GENERATED SOURCE. DO NOT MODIFY. */ // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html#License /* * Copyright (C) 2008-2016, International Business Machines * Corporation and others. All Rights Reserved. */ package android.icu.text; import java.io.IOException; import java.io.ObjectInputStream; import java.text.FieldPosition; import java.text.ParsePosition; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; import android.icu.impl.ICUCache; import android.icu.impl.ICUData; import android.icu.impl.ICUResourceBundle; import android.icu.impl.SimpleCache; import android.icu.impl.SimpleFormatterImpl; import android.icu.text.DateIntervalInfo.PatternInfo; import android.icu.util.Calendar; import android.icu.util.DateInterval; import android.icu.util.Output; import android.icu.util.TimeZone; import android.icu.util.ULocale; import android.icu.util.ULocale.Category; import android.icu.util.UResourceBundle; /** * DateIntervalFormat is a class for formatting and parsing date * intervals in a language-independent manner. * Only formatting is supported. Parsing is not supported. * * <P> * Date interval means from one date to another date, * for example, from "Jan 11, 2008" to "Jan 18, 2008". * We introduced class DateInterval to represent it. * DateInterval is a pair of UDate, which is * the standard milliseconds since 24:00 GMT, Jan 1, 1970. * * <P> * DateIntervalFormat formats a DateInterval into * text as compactly as possible. * For example, the date interval format from "Jan 11, 2008" to "Jan 18,. 2008" * is "Jan 11-18, 2008" for English. * And it parses text into DateInterval, * although initially, parsing is not supported. * * <P> * There is no structural information in date time patterns. * For any punctuations and string literals inside a date time pattern, * we do not know whether it is just a separator, or a prefix, or a suffix. * Without such information, so, it is difficult to generate a sub-pattern * (or super-pattern) by algorithm. * So, formatting a DateInterval is pattern-driven. It is very * similar to formatting in SimpleDateFormat. * We introduce class DateIntervalInfo to save date interval * patterns, similar to date time pattern in SimpleDateFormat. * * <P> * Logically, the interval patterns are mappings * from (skeleton, the_largest_different_calendar_field) * to (date_interval_pattern). * * <P> * A skeleton * <ol> * <li> * only keeps the field pattern letter and ignores all other parts * in a pattern, such as space, punctuations, and string literals. * <li> * hides the order of fields. * <li> * might hide a field's pattern letter length. * * For those non-digit calendar fields, the pattern letter length is * important, such as MMM, MMMM, and MMMMM; EEE and EEEE, * and the field's pattern letter length is honored. * * For the digit calendar fields, such as M or MM, d or dd, yy or yyyy, * the field pattern length is ignored and the best match, which is defined * in date time patterns, will be returned without honor the field pattern * letter length in skeleton. * </ol> * * <P> * The calendar fields we support for interval formatting are: * year, month, date, day-of-week, am-pm, hour, hour-of-day, minute, and * second (though we do not currently have specific intervalFormat data for * skeletons with seconds). * Those calendar fields can be defined in the following order: * year &gt; month &gt; date &gt; hour (in day) &gt; minute &gt; second * * The largest different calendar fields between 2 calendars is the * first different calendar field in above order. * * For example: the largest different calendar fields between "Jan 10, 2007" * and "Feb 20, 2008" is year. * * <P> * For other calendar fields, the compact interval formatting is not * supported. And the interval format will be fall back to fall-back * patterns, which is mostly "{date0} - {date1}". * * <P> * There is a set of pre-defined static skeleton strings in DateFormat, * There are pre-defined interval patterns for those pre-defined skeletons * in locales' resource files. * For example, for a skeleton YEAR_ABBR_MONTH_DAY, which is "yMMMd", * in en_US, if the largest different calendar field between date1 and date2 * is "year", the date interval pattern is "MMM d, yyyy - MMM d, yyyy", * such as "Jan 10, 2007 - Jan 10, 2008". * If the largest different calendar field between date1 and date2 is "month", * the date interval pattern is "MMM d - MMM d, yyyy", * such as "Jan 10 - Feb 10, 2007". * If the largest different calendar field between date1 and date2 is "day", * the date interval pattern is ""MMM d-d, yyyy", such as "Jan 10-20, 2007". * * For date skeleton, the interval patterns when year, or month, or date is * different are defined in resource files. * For time skeleton, the interval patterns when am/pm, or hour, or minute is * different are defined in resource files. * * <P> * If a skeleton is not found in a locale's DateIntervalInfo, which means * the interval patterns for the skeleton is not defined in resource file, * the interval pattern will falls back to the interval "fallback" pattern * defined in resource file. * If the interval "fallback" pattern is not defined, the default fall-back * is "{date0} - {data1}". * * <P> * For the combination of date and time, * The rule to genearte interval patterns are: * <ol> * <li> * when the year, month, or day differs, falls back to fall-back * interval pattern, which mostly is the concatenate the two original * expressions with a separator between, * For example, interval pattern from "Jan 10, 2007 10:10 am" * to "Jan 11, 2007 10:10am" is * "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am" * <li> * otherwise, present the date followed by the range expression * for the time. * For example, interval pattern from "Jan 10, 2007 10:10 am" * to "Jan 10, 2007 11:10am" is "Jan 10, 2007 10:10 am - 11:10am" * </ol> * * * <P> * If two dates are the same, the interval pattern is the single date pattern. * For example, interval pattern from "Jan 10, 2007" to "Jan 10, 2007" is * "Jan 10, 2007". * * Or if the presenting fields between 2 dates have the exact same values, * the interval pattern is the single date pattern. * For example, if user only requests year and month, * the interval pattern from "Jan 10, 2007" to "Jan 20, 2007" is "Jan 2007". * * <P> * DateIntervalFormat needs the following information for correct * formatting: time zone, calendar type, pattern, date format symbols, * and date interval patterns. * It can be instantiated in several ways: * <ol> * <li> * create an instance using default or given locale plus given skeleton. * Users are encouraged to created date interval formatter this way and * to use the pre-defined skeleton macros, such as * YEAR_NUM_MONTH, which consists the calendar fields and * the format style. * </li> * <li> * create an instance using default or given locale plus given skeleton * plus a given DateIntervalInfo. * This factory method is for powerful users who want to provide their own * interval patterns. * Locale provides the timezone, calendar, and format symbols information. * Local plus skeleton provides full pattern information. * DateIntervalInfo provides the date interval patterns. * </li> * </ol> * * <P> * For the calendar field pattern letter, such as G, y, M, d, a, h, H, m, s etc. * DateIntervalFormat uses the same syntax as that of * DateTime format. * * <P> * Code Sample: general usage * <pre> * * // the date interval object which the DateIntervalFormat formats on * // and parses into * DateInterval dtInterval = new DateInterval(1000*3600*24L, 1000*3600*24*2L); * DateIntervalFormat dtIntervalFmt = DateIntervalFormat.getInstance( * YEAR_MONTH_DAY, Locale("en", "GB", "")); * StringBuffer str = new StringBuffer(""); * FieldPosition pos = new FieldPosition(0); * // formatting * dtIntervalFmt.format(dtInterval, dateIntervalString, pos); * * </pre> * * <P> * Code Sample: for powerful users who wants to use their own interval pattern * <pre> * * import android.icu.text.DateIntervalInfo; * import android.icu.text.DateIntervalFormat; * .................... * * // Get DateIntervalFormat instance using default locale * DateIntervalFormat dtitvfmt = DateIntervalFormat.getInstance(YEAR_MONTH_DAY); * * // Create an empty DateIntervalInfo object, which does not have any interval patterns inside. * dtitvinf = new DateIntervalInfo(); * * // a series of set interval patterns. * // Only ERA, YEAR, MONTH, DATE, DAY_OF_MONTH, DAY_OF_WEEK, AM_PM, HOUR, HOUR_OF_DAY, * MINUTE and SECOND are supported. * dtitvinf.setIntervalPattern("yMMMd", Calendar.YEAR, "'y ~ y'"); * dtitvinf.setIntervalPattern("yMMMd", Calendar.MONTH, "yyyy 'diff' MMM d - MMM d"); * dtitvinf.setIntervalPattern("yMMMd", Calendar.DATE, "yyyy MMM d ~ d"); * dtitvinf.setIntervalPattern("yMMMd", Calendar.HOUR_OF_DAY, "yyyy MMM d HH:mm ~ HH:mm"); * * // Set fallback interval pattern. Fallback pattern is used when interval pattern is not found. * // If the fall-back pattern is not set, falls back to {date0} - {date1} if interval pattern is not found. * dtitvinf.setFallbackIntervalPattern("{0} - {1}"); * * // Set above DateIntervalInfo object as the interval patterns of date interval formatter * dtitvfmt.setDateIntervalInfo(dtitvinf); * * // Prepare to format * pos = new FieldPosition(0); * str = new StringBuffer(""); * * // The 2 calendars should be equivalent, otherwise, IllegalArgumentException will be thrown by format() * Calendar fromCalendar = (Calendar) dtfmt.getCalendar().clone(); * Calendar toCalendar = (Calendar) dtfmt.getCalendar().clone(); * fromCalendar.setTimeInMillis(....); * toCalendar.setTimeInMillis(...); * * //Formatting given 2 calendars * dtitvfmt.format(fromCalendar, toCalendar, str, pos); * * * </pre> * <h3>Synchronization</h3> * * The format methods of DateIntervalFormat may be used concurrently from multiple threads. * Functions that alter the state of a DateIntervalFormat object (setters) * may not be used concurrently with any other functions. */ public class DateIntervalFormat extends UFormat { private static final long serialVersionUID = 1; /** * Used to save the information for a skeleton's best match skeleton. * It is package accessible since it is used in DateIntervalInfo too. */ static final class BestMatchInfo { // the best match skeleton final String bestMatchSkeleton; // 0 means the best matched skeleton is the same as input skeleton // 1 means the fields are the same, but field width are different // 2 means the only difference between fields are v/z, // -1 means there are other fields difference final int bestMatchDistanceInfo; BestMatchInfo(String bestSkeleton, int difference) { bestMatchSkeleton = bestSkeleton; bestMatchDistanceInfo = difference; } } /* * Used to save the information on a skeleton and its best match. */ private static final class SkeletonAndItsBestMatch { final String skeleton; final String bestMatchSkeleton; SkeletonAndItsBestMatch(String skeleton, String bestMatch) { this.skeleton = skeleton; bestMatchSkeleton = bestMatch; } } // Cache for the locale interval pattern private static ICUCache<String, Map<String, PatternInfo>> LOCAL_PATTERN_CACHE = new SimpleCache<String, Map<String, PatternInfo>>(); /* * The interval patterns for this locale. */ private DateIntervalInfo fInfo; /* * The DateFormat object used to format single pattern. * Because fDateFormat is modified during format operations, all * access to it from logically const, thread safe functions must be synchronized. */ private SimpleDateFormat fDateFormat; /* * The 2 calendars with the from and to date. * could re-use the calendar in fDateFormat, * but keeping 2 calendars make it clear and clean. * Because these Calendars are modified during format operations, all * access to them from logically const, thread safe functions must be synchronized. */ private Calendar fFromCalendar; private Calendar fToCalendar; /* * Following are transient interval information * relevant (locale) to this formatter. */ private String fSkeleton = null; /* * Needed for efficient deserialization. If set, it means we can use the * cache to initialize fIntervalPatterns. */ private boolean isDateIntervalInfoDefault; /** * Interval patterns for this instance's locale. */ private transient Map<String, PatternInfo> fIntervalPatterns = null; /* * Patterns for fallback formatting. */ private String fDatePattern = null; private String fTimePattern = null; private String fDateTimeFormat = null; /* * default constructor; private because we don't want anyone to use */ @SuppressWarnings("unused") private DateIntervalFormat() { } /** * Construct a DateIntervalFormat from DateFormat, * a DateIntervalInfo, and skeleton. * DateFormat provides the timezone, calendar, * full pattern, and date format symbols information. * It should be a SimpleDateFormat object which * has a pattern in it. * the DateIntervalInfo provides the interval patterns. * * @param skeleton the skeleton of the date formatter * @param dtItvInfo the DateIntervalInfo object to be adopted. * @param simpleDateFormat will be used for formatting * * @deprecated This API is ICU internal only. * @hide original deprecated declaration * @hide draft / provisional / internal are hidden on Android */ @Deprecated public DateIntervalFormat(String skeleton, DateIntervalInfo dtItvInfo, SimpleDateFormat simpleDateFormat) { fDateFormat = simpleDateFormat; // freeze date interval info dtItvInfo.freeze(); fSkeleton = skeleton; fInfo = dtItvInfo; isDateIntervalInfoDefault = false; fFromCalendar = (Calendar) fDateFormat.getCalendar().clone(); fToCalendar = (Calendar) fDateFormat.getCalendar().clone(); initializePattern(null); } private DateIntervalFormat(String skeleton, ULocale locale, SimpleDateFormat simpleDateFormat) { fDateFormat = simpleDateFormat; fSkeleton = skeleton; fInfo = new DateIntervalInfo(locale).freeze(); isDateIntervalInfoDefault = true; fFromCalendar = (Calendar) fDateFormat.getCalendar().clone(); fToCalendar = (Calendar) fDateFormat.getCalendar().clone(); initializePattern(LOCAL_PATTERN_CACHE); } /** * Construct a DateIntervalFormat from skeleton and the default <code>FORMAT</code> locale. * * This is a convenient override of * getInstance(String skeleton, ULocale locale) * with the value of locale as default <code>FORMAT</code> locale. * * @param skeleton the skeleton on which interval format based. * @return a date time interval formatter. * @see Category#FORMAT */ public static final DateIntervalFormat getInstance(String skeleton) { return getInstance(skeleton, ULocale.getDefault(Category.FORMAT)); } /** * Construct a DateIntervalFormat from skeleton and a given locale. * * This is a convenient override of * getInstance(String skeleton, ULocale locale) * * <p>Example code:{@sample external/icu/android_icu4j/src/samples/java/android/icu/samples/text/dateintervalformat/DateIntervalFormatSample.java dtitvfmtPreDefinedExample} * @param skeleton the skeleton on which interval format based. * @param locale the given locale * @return a date time interval formatter. */ public static final DateIntervalFormat getInstance(String skeleton, Locale locale) { return getInstance(skeleton, ULocale.forLocale(locale)); } /** * Construct a DateIntervalFormat from skeleton and a given locale. * <P> * In this factory method, * the date interval pattern information is load from resource files. * Users are encouraged to created date interval formatter this way and * to use the pre-defined skeleton macros. * * <P> * There are pre-defined skeletons in DateFormat, * such as MONTH_DAY, YEAR_MONTH_WEEKDAY_DAY etc. * * Those skeletons have pre-defined interval patterns in resource files. * Users are encouraged to use them. * For example: * DateIntervalFormat.getInstance(DateFormat.MONTH_DAY, false, loc); * * The given Locale provides the interval patterns. * For example, for en_GB, if skeleton is YEAR_ABBR_MONTH_WEEKDAY_DAY, * which is "yMMMEEEd", * the interval patterns defined in resource file to above skeleton are: * "EEE, d MMM, yyyy - EEE, d MMM, yyyy" for year differs, * "EEE, d MMM - EEE, d MMM, yyyy" for month differs, * "EEE, d - EEE, d MMM, yyyy" for day differs, * @param skeleton the skeleton on which interval format based. * @param locale the given locale * @return a date time interval formatter. */ public static final DateIntervalFormat getInstance(String skeleton, ULocale locale) { DateTimePatternGenerator generator = DateTimePatternGenerator.getInstance(locale); return new DateIntervalFormat(skeleton, locale, new SimpleDateFormat(generator.getBestPattern(skeleton), locale)); } /** * Construct a DateIntervalFormat from skeleton * DateIntervalInfo, and the default <code>FORMAT</code> locale. * * This is a convenient override of * getInstance(String skeleton, ULocale locale, DateIntervalInfo dtitvinf) * with the locale value as default <code>FORMAT</code> locale. * * @param skeleton the skeleton on which interval format based. * @param dtitvinf the DateIntervalInfo object to be adopted. * @return a date time interval formatter. * @see Category#FORMAT */ public static final DateIntervalFormat getInstance(String skeleton, DateIntervalInfo dtitvinf) { return getInstance(skeleton, ULocale.getDefault(Category.FORMAT), dtitvinf); } /** * Construct a DateIntervalFormat from skeleton * a DateIntervalInfo, and the given locale. * * This is a convenient override of * getInstance(String skeleton, ULocale locale, DateIntervalInfo dtitvinf) * * <p>Example code:{@sample external/icu/android_icu4j/src/samples/java/android/icu/samples/text/dateintervalformat/DateIntervalFormatSample.java dtitvfmtCustomizedExample} * @param skeleton the skeleton on which interval format based. * @param locale the given locale * @param dtitvinf the DateIntervalInfo object to be adopted. * @return a date time interval formatter. */ public static final DateIntervalFormat getInstance(String skeleton, Locale locale, DateIntervalInfo dtitvinf) { return getInstance(skeleton, ULocale.forLocale(locale), dtitvinf); } /** * Construct a DateIntervalFormat from skeleton * a DateIntervalInfo, and the given locale. * * <P> * In this factory method, user provides its own date interval pattern * information, instead of using those pre-defined data in resource file. * This factory method is for powerful users who want to provide their own * interval patterns. * * <P> * There are pre-defined skeleton in DateFormat, * such as MONTH_DAY, YEAR_MONTH_WEEKDAY_DAY etc. * * Those skeletons have pre-defined interval patterns in resource files. * Users are encouraged to use them. * For example: * DateIntervalFormat.getInstance(DateFormat.MONTH_DAY, false, loc,itvinf); * * the DateIntervalInfo provides the interval patterns. * * User are encouraged to set default interval pattern in DateIntervalInfo * as well, if they want to set other interval patterns ( instead of * reading the interval patterns from resource files). * When the corresponding interval pattern for a largest calendar different * field is not found ( if user not set it ), interval format fallback to * the default interval pattern. * If user does not provide default interval pattern, it fallback to * "{date0} - {date1}" * * @param skeleton the skeleton on which interval format based. * @param locale the given locale * @param dtitvinf the DateIntervalInfo object to be adopted. * @return a date time interval formatter. */ public static final DateIntervalFormat getInstance(String skeleton, ULocale locale, DateIntervalInfo dtitvinf) { // clone. If it is frozen, clone returns itself, otherwise, clone // returns a copy. dtitvinf = (DateIntervalInfo)dtitvinf.clone(); DateTimePatternGenerator generator = DateTimePatternGenerator.getInstance(locale); return new DateIntervalFormat(skeleton, dtitvinf, new SimpleDateFormat(generator.getBestPattern(skeleton), locale)); } /** * Clone this Format object polymorphically. * @return A copy of the object. */ public synchronized Object clone() { DateIntervalFormat other = (DateIntervalFormat) super.clone(); other.fDateFormat = (SimpleDateFormat) fDateFormat.clone(); other.fInfo = (DateIntervalInfo) fInfo.clone(); other.fFromCalendar = (Calendar) fFromCalendar.clone(); other.fToCalendar = (Calendar) fToCalendar.clone(); other.fDatePattern = fDatePattern; other.fTimePattern = fTimePattern; other.fDateTimeFormat = fDateTimeFormat; return other; } /** * Format an object to produce a string. This method handles Formattable * objects with a DateInterval type. * If a the Formattable object type is not a DateInterval, * IllegalArgumentException is thrown. * * @param obj The object to format. * Must be a DateInterval. * @param appendTo Output parameter to receive result. * Result is appended to existing contents. * @param fieldPosition On input: an alignment field, if desired. * On output: the offsets of the alignment field. * There may be multiple instances of a given field type * in an interval format; in this case the fieldPosition * offsets refer to the first instance. * @return Reference to 'appendTo' parameter. * @throws IllegalArgumentException if the formatted object is not * DateInterval object */ public final StringBuffer format(Object obj, StringBuffer appendTo, FieldPosition fieldPosition) { if ( obj instanceof DateInterval ) { return format( (DateInterval)obj, appendTo, fieldPosition); } else { throw new IllegalArgumentException("Cannot format given Object (" + obj.getClass().getName() + ") as a DateInterval"); } } /** * Format a DateInterval to produce a string. * * @param dtInterval DateInterval to be formatted. * @param appendTo Output parameter to receive result. * Result is appended to existing contents. * @param fieldPosition On input: an alignment field, if desired. * On output: the offsets of the alignment field. * There may be multiple instances of a given field type * in an interval format; in this case the fieldPosition * offsets refer to the first instance. * @return Reference to 'appendTo' parameter. */ public final synchronized StringBuffer format(DateInterval dtInterval, StringBuffer appendTo, FieldPosition fieldPosition) { fFromCalendar.setTimeInMillis(dtInterval.getFromDate()); fToCalendar.setTimeInMillis(dtInterval.getToDate()); return format(fFromCalendar, fToCalendar, appendTo, fieldPosition); } /** * @deprecated This API is ICU internal only. * @hide original deprecated declaration * @hide draft / provisional / internal are hidden on Android */ @Deprecated public String getPatterns(Calendar fromCalendar, Calendar toCalendar, Output<String> part2) { // First, find the largest different calendar field. int field; if ( fromCalendar.get(Calendar.ERA) != toCalendar.get(Calendar.ERA) ) { field = Calendar.ERA; } else if ( fromCalendar.get(Calendar.YEAR) != toCalendar.get(Calendar.YEAR) ) { field = Calendar.YEAR; } else if ( fromCalendar.get(Calendar.MONTH) != toCalendar.get(Calendar.MONTH) ) { field = Calendar.MONTH; } else if ( fromCalendar.get(Calendar.DATE) != toCalendar.get(Calendar.DATE) ) { field = Calendar.DATE; } else if ( fromCalendar.get(Calendar.AM_PM) != toCalendar.get(Calendar.AM_PM) ) { field = Calendar.AM_PM; } else if ( fromCalendar.get(Calendar.HOUR) != toCalendar.get(Calendar.HOUR) ) { field = Calendar.HOUR; } else if ( fromCalendar.get(Calendar.MINUTE) != toCalendar.get(Calendar.MINUTE) ) { field = Calendar.MINUTE; } else if ( fromCalendar.get(Calendar.SECOND) != toCalendar.get(Calendar.SECOND) ) { field = Calendar.SECOND; } else { return null; } PatternInfo intervalPattern = fIntervalPatterns.get( DateIntervalInfo.CALENDAR_FIELD_TO_PATTERN_LETTER[field]); part2.value = intervalPattern.getSecondPart(); return intervalPattern.getFirstPart(); } /** * Format 2 Calendars to produce a string. * * @param fromCalendar calendar set to the from date in date interval * to be formatted into date interval string * @param toCalendar calendar set to the to date in date interval * to be formatted into date interval string * @param appendTo Output parameter to receive result. * Result is appended to existing contents. * @param pos On input: an alignment field, if desired. * On output: the offsets of the alignment field. * There may be multiple instances of a given field type * in an interval format; in this case the fieldPosition * offsets refer to the first instance. * @return Reference to 'appendTo' parameter. * @throws IllegalArgumentException if the two calendars are not equivalent. */ public final synchronized StringBuffer format(Calendar fromCalendar, Calendar toCalendar, StringBuffer appendTo, FieldPosition pos) { // not support different calendar types and time zones if ( !fromCalendar.isEquivalentTo(toCalendar) ) { throw new IllegalArgumentException("can not format on two different calendars"); } // First, find the largest different calendar field. int field = -1; //init with an invalid value. if ( fromCalendar.get(Calendar.ERA) != toCalendar.get(Calendar.ERA) ) { field = Calendar.ERA; } else if ( fromCalendar.get(Calendar.YEAR) != toCalendar.get(Calendar.YEAR) ) { field = Calendar.YEAR; } else if ( fromCalendar.get(Calendar.MONTH) != toCalendar.get(Calendar.MONTH) ) { field = Calendar.MONTH; } else if ( fromCalendar.get(Calendar.DATE) != toCalendar.get(Calendar.DATE) ) { field = Calendar.DATE; } else if ( fromCalendar.get(Calendar.AM_PM) != toCalendar.get(Calendar.AM_PM) ) { field = Calendar.AM_PM; } else if ( fromCalendar.get(Calendar.HOUR) != toCalendar.get(Calendar.HOUR) ) { field = Calendar.HOUR; } else if ( fromCalendar.get(Calendar.MINUTE) != toCalendar.get(Calendar.MINUTE) ) { field = Calendar.MINUTE; } else if ( fromCalendar.get(Calendar.SECOND) != toCalendar.get(Calendar.SECOND) ) { field = Calendar.SECOND; } else { /* ignore the millisecond etc. small fields' difference. * use single date when all the above are the same. */ return fDateFormat.format(fromCalendar, appendTo, pos); } boolean fromToOnSameDay = (field==Calendar.AM_PM || field==Calendar.HOUR || field==Calendar.MINUTE || field==Calendar.SECOND); // get interval pattern PatternInfo intervalPattern = fIntervalPatterns.get( DateIntervalInfo.CALENDAR_FIELD_TO_PATTERN_LETTER[field]); if ( intervalPattern == null ) { if ( fDateFormat.isFieldUnitIgnored(field) ) { /* the largest different calendar field is small than * the smallest calendar field in pattern, * return single date format. */ return fDateFormat.format(fromCalendar, appendTo, pos); } return fallbackFormat(fromCalendar, toCalendar, fromToOnSameDay, appendTo, pos); } // If the first part in interval pattern is empty, // the 2nd part of it saves the full-pattern used in fall-back. // For a 'real' interval pattern, the first part will never be empty. if ( intervalPattern.getFirstPart() == null ) { // fall back return fallbackFormat(fromCalendar, toCalendar, fromToOnSameDay, appendTo, pos, intervalPattern.getSecondPart()); } Calendar firstCal; Calendar secondCal; if ( intervalPattern.firstDateInPtnIsLaterDate() ) { firstCal = toCalendar; secondCal = fromCalendar; } else { firstCal = fromCalendar; secondCal = toCalendar; } // break the interval pattern into 2 parts // first part should not be empty, String originalPattern = fDateFormat.toPattern(); fDateFormat.applyPattern(intervalPattern.getFirstPart()); fDateFormat.format(firstCal, appendTo, pos); if ( intervalPattern.getSecondPart() != null ) { fDateFormat.applyPattern(intervalPattern.getSecondPart()); FieldPosition otherPos = new FieldPosition(pos.getField()); fDateFormat.format(secondCal, appendTo, otherPos); if (pos.getEndIndex() == 0 && otherPos.getEndIndex() > 0) { pos.setBeginIndex(otherPos.getBeginIndex()); pos.setEndIndex(otherPos.getEndIndex()); } } fDateFormat.applyPattern(originalPattern); return appendTo; } private void adjustPosition(String combiningPattern, // has {0} and {1} in it String pat0, FieldPosition pos0, // pattern and pos corresponding to {0} String pat1, FieldPosition pos1, // pattern and pos corresponding to {1} FieldPosition posResult) { int index0 = combiningPattern.indexOf("{0}"); int index1 = combiningPattern.indexOf("{1}"); if (index0 < 0 || index1 < 0) { return; } int placeholderLen = 3; // length of "{0}" or "{1}" if (index0 < index1) { if (pos0.getEndIndex() > 0) { posResult.setBeginIndex(pos0.getBeginIndex() + index0); posResult.setEndIndex(pos0.getEndIndex() + index0); } else if (pos1.getEndIndex() > 0) { // here index1 >= 3 index1 += pat0.length() - placeholderLen; // adjust for pat0 replacing {0} posResult.setBeginIndex(pos1.getBeginIndex() + index1); posResult.setEndIndex(pos1.getEndIndex() + index1); } } else { if (pos1.getEndIndex() > 0) { posResult.setBeginIndex(pos1.getBeginIndex() + index1); posResult.setEndIndex(pos1.getEndIndex() + index1); } else if (pos0.getEndIndex() > 0) { // here index0 >= 3 index0 += pat1.length() - placeholderLen; // adjust for pat1 replacing {1} posResult.setBeginIndex(pos0.getBeginIndex() + index0); posResult.setEndIndex(pos0.getEndIndex() + index0); } } } /* * Format 2 Calendars to using fall-back interval pattern * * The full pattern used in this fall-back format is the * full pattern of the date formatter. * * @param fromCalendar calendar set to the from date in date interval * to be formatted into date interval string * @param toCalendar calendar set to the to date in date interval * to be formatted into date interval string * @param appendTo Output parameter to receive result. * Result is appended to existing contents. * @param pos On input: an alignment field, if desired. * On output: the offsets of the alignment field. * @return Reference to 'appendTo' parameter. */ private final StringBuffer fallbackFormat(Calendar fromCalendar, Calendar toCalendar, boolean fromToOnSameDay, StringBuffer appendTo, FieldPosition pos) { String fullPattern = null; // for saving the pattern in fDateFormat boolean formatDatePlusTimeRange = (fromToOnSameDay && fDatePattern != null && fTimePattern != null); // the fall back if (formatDatePlusTimeRange) { fullPattern = fDateFormat.toPattern(); // save current pattern, restore later fDateFormat.applyPattern(fTimePattern); } FieldPosition otherPos = new FieldPosition(pos.getField()); StringBuffer earlierDate = new StringBuffer(64); earlierDate = fDateFormat.format(fromCalendar, earlierDate, pos); StringBuffer laterDate = new StringBuffer(64); laterDate = fDateFormat.format(toCalendar, laterDate, otherPos); String fallbackPattern = fInfo.getFallbackIntervalPattern(); adjustPosition(fallbackPattern, earlierDate.toString(), pos, laterDate.toString(), otherPos, pos); String fallbackRange = SimpleFormatterImpl.formatRawPattern( fallbackPattern, 2, 2, earlierDate, laterDate); if (formatDatePlusTimeRange) { // fallbackRange has just the time range, need to format the date part and combine that fDateFormat.applyPattern(fDatePattern); StringBuffer datePortion = new StringBuffer(64); otherPos.setBeginIndex(0); otherPos.setEndIndex(0); datePortion = fDateFormat.format(fromCalendar, datePortion, otherPos); adjustPosition(fDateTimeFormat, fallbackRange, pos, datePortion.toString(), otherPos, pos); fallbackRange = SimpleFormatterImpl.formatRawPattern( fDateTimeFormat, 2, 2, fallbackRange, datePortion); } appendTo.append(fallbackRange); if (formatDatePlusTimeRange) { // restore full pattern fDateFormat.applyPattern(fullPattern); } return appendTo; } /* * Format 2 Calendars to using fall-back interval pattern * * This fall-back pattern is generated on a given full pattern, * not the full pattern of the date formatter. * * @param fromCalendar calendar set to the from date in date interval * to be formatted into date interval string * @param toCalendar calendar set to the to date in date interval * to be formatted into date interval string * @param appendTo Output parameter to receive result. * Result is appended to existing contents. * @param pos On input: an alignment field, if desired. * On output: the offsets of the alignment field. * @param fullPattern the full pattern need to apply to date formatter * @return Reference to 'appendTo' parameter. */ private final StringBuffer fallbackFormat(Calendar fromCalendar, Calendar toCalendar, boolean fromToOnSameDay, StringBuffer appendTo, FieldPosition pos, String fullPattern) { String originalPattern = fDateFormat.toPattern(); fDateFormat.applyPattern(fullPattern); fallbackFormat(fromCalendar, toCalendar, fromToOnSameDay, appendTo, pos); fDateFormat.applyPattern(originalPattern); return appendTo; } /** * Date interval parsing is not supported. * <P> * This method should handle parsing of * date time interval strings into Formattable objects with * DateInterval type, which is a pair of UDate. * <P> * Before calling, set parse_pos.index to the offset you want to start * parsing at in the source. After calling, parse_pos.index is the end of * the text you parsed. If error occurs, index is unchanged. * <P> * When parsing, leading whitespace is discarded (with a successful parse), * while trailing whitespace is left as is. * <P> * See Format.parseObject() for more. * * @param source The string to be parsed into an object. * @param parse_pos The position to start parsing at. Since no parsing * is supported, upon return this param is unchanged. * @return A newly created Formattable* object, or NULL * on failure. * @deprecated This API is ICU internal only. * @hide original deprecated declaration * @hide draft / provisional / internal are hidden on Android */ @Deprecated public Object parseObject(String source, ParsePosition parse_pos) { throw new UnsupportedOperationException("parsing is not supported"); } /** * Gets the date time interval patterns. * @return a copy of the date time interval patterns associated with * this date interval formatter. */ public DateIntervalInfo getDateIntervalInfo() { return (DateIntervalInfo)fInfo.clone(); } /** * Set the date time interval patterns. * @param newItvPattern the given interval patterns to copy. */ public void setDateIntervalInfo(DateIntervalInfo newItvPattern) { // clone it. If it is frozen, the clone returns itself. // Otherwise, clone returns a copy fInfo = (DateIntervalInfo)newItvPattern.clone(); this.isDateIntervalInfoDefault = false; fInfo.freeze(); // freeze it if ( fDateFormat != null ) { initializePattern(null); } } /** * Get the TimeZone * @return A copy of the TimeZone associated with this date interval formatter. */ public TimeZone getTimeZone() { if ( fDateFormat != null ) { // Here we clone, like other getters here, but unlike // DateFormat.getTimeZone() and Calendar.getTimeZone() // which return the TimeZone from the Calendar's zone variable return (TimeZone)(fDateFormat.getTimeZone().clone()); } // If fDateFormat is null (unexpected), return default timezone. return TimeZone.getDefault(); } /** * Set the TimeZone for the calendar used by this DateIntervalFormat object. * @param zone The new TimeZone, will be cloned for use by this DateIntervalFormat. */ public void setTimeZone(TimeZone zone) { // zone is cloned once for all three usages below: TimeZone zoneToSet = (TimeZone)zone.clone(); if (fDateFormat != null) { fDateFormat.setTimeZone(zoneToSet); } // fDateFormat has the master calendar for the DateIntervalFormat; // fFromCalendar and fToCalendar are internal work clones of that calendar. if (fFromCalendar != null) { fFromCalendar.setTimeZone(zoneToSet); } if (fToCalendar != null) { fToCalendar.setTimeZone(zoneToSet); } } /** * Gets the date formatter * @return a copy of the date formatter associated with * this date interval formatter. */ public synchronized DateFormat getDateFormat() { return (DateFormat)fDateFormat.clone(); } /* * Below are for generating interval patterns locale to the formatter */ /* * Initialize interval patterns locale to this formatter. */ private void initializePattern(ICUCache<String, Map<String, PatternInfo>> cache) { String fullPattern = fDateFormat.toPattern(); ULocale locale = fDateFormat.getLocale(); String key = null; Map<String, PatternInfo> patterns = null; if (cache != null) { if ( fSkeleton != null ) { key = locale.toString() + "+" + fullPattern + "+" + fSkeleton; } else { key = locale.toString() + "+" + fullPattern; } patterns = cache.get(key); } if (patterns == null) { Map<String, PatternInfo> intervalPatterns = initializeIntervalPattern(fullPattern, locale); patterns = Collections.unmodifiableMap(intervalPatterns); if (cache != null) { cache.put(key, patterns); } } fIntervalPatterns = patterns; } /* * Initialize interval patterns locale to this formatter * * This code is a bit complicated since * 1. the interval patterns saved in resource bundle files are interval * patterns based on date or time only. * It does not have interval patterns based on both date and time. * Interval patterns on both date and time are algorithm generated. * * For example, it has interval patterns on skeleton "dMy" and "hm", * but it does not have interval patterns on skeleton "dMyhm". * * The rule to generate interval patterns for both date and time skeleton are * 1) when the year, month, or day differs, concatenate the two original * expressions with a separator between, * For example, interval pattern from "Jan 10, 2007 10:10 am" * to "Jan 11, 2007 10:10am" is * "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am" * * 2) otherwise, present the date followed by the range expression * for the time. * For example, interval pattern from "Jan 10, 2007 10:10 am" * to "Jan 10, 2007 11:10am" is * "Jan 10, 2007 10:10 am - 11:10am" * * 2. even a pattern does not request a certain calendar field, * the interval pattern needs to include such field if such fields are * different between 2 dates. * For example, a pattern/skeleton is "hm", but the interval pattern * includes year, month, and date when year, month, and date differs. * * * @param fullPattern formatter's full pattern * @param locale the given locale. * @return interval patterns' hash map */ private Map<String, PatternInfo> initializeIntervalPattern(String fullPattern, ULocale locale) { DateTimePatternGenerator dtpng = DateTimePatternGenerator.getInstance(locale); if ( fSkeleton == null ) { // fSkeleton is already set by getDateIntervalInstance() // or by getInstance(String skeleton, .... ) fSkeleton = dtpng.getSkeleton(fullPattern); } String skeleton = fSkeleton; HashMap<String, PatternInfo> intervalPatterns = new HashMap<String, PatternInfo>(); /* Check whether the skeleton is a combination of date and time. * For the complication reason 1 explained above. */ StringBuilder date = new StringBuilder(skeleton.length()); StringBuilder normalizedDate = new StringBuilder(skeleton.length()); StringBuilder time = new StringBuilder(skeleton.length()); StringBuilder normalizedTime = new StringBuilder(skeleton.length()); /* the difference between time skeleton and normalizedTimeSkeleton are: * 1. (Formerly, normalized time skeleton folded 'H' to 'h'; no longer true) * 2. 'a' is omitted in normalized time skeleton. * 3. there is only one appearance for 'h', 'm','v', 'z' in normalized * time skeleton * * The difference between date skeleton and normalizedDateSkeleton are: * 1. both 'y' and 'd' appear only once in normalizeDateSkeleton * 2. 'E' and 'EE' are normalized into 'EEE' * 3. 'MM' is normalized into 'M' */ getDateTimeSkeleton(skeleton, date, normalizedDate, time, normalizedTime); String dateSkeleton = date.toString(); String timeSkeleton = time.toString(); String normalizedDateSkeleton = normalizedDate.toString(); String normalizedTimeSkeleton = normalizedTime.toString(); // move this up here since we need it for fallbacks if (time.length() != 0 && date.length() != 0) { // Need the Date/Time pattern for concatenating the date with // the time interval. // The date/time pattern ( such as {0} {1} ) is saved in // calendar, that is why need to get the CalendarData here. fDateTimeFormat = getConcatenationPattern(locale); } boolean found = genSeparateDateTimePtn(normalizedDateSkeleton, normalizedTimeSkeleton, intervalPatterns, dtpng); // for skeletons with seconds, found is false and we enter this block if ( found == false ) { // use fallback // TODO: if user asks "m", but "d" differ //StringBuffer skeleton = new StringBuffer(skeleton); if ( time.length() != 0 ) { //genFallbackForNotFound(Calendar.MINUTE, skeleton); //genFallbackForNotFound(Calendar.HOUR, skeleton); //genFallbackForNotFound(Calendar.AM_PM, skeleton); if ( date.length() == 0 ) { // prefix with yMd timeSkeleton = DateFormat.YEAR_NUM_MONTH_DAY + timeSkeleton; String pattern =dtpng.getBestPattern(timeSkeleton); // for fall back interval patterns, // the first part of the pattern is empty, // the second part of the pattern is the full-pattern // should be used in fall-back. PatternInfo ptn = new PatternInfo(null, pattern, fInfo.getDefaultOrder()); intervalPatterns.put(DateIntervalInfo. CALENDAR_FIELD_TO_PATTERN_LETTER[Calendar.DATE], ptn); // share interval pattern intervalPatterns.put(DateIntervalInfo. CALENDAR_FIELD_TO_PATTERN_LETTER[Calendar.MONTH], ptn); // share interval pattern intervalPatterns.put(DateIntervalInfo. CALENDAR_FIELD_TO_PATTERN_LETTER[Calendar.YEAR], ptn); } else { //genFallbackForNotFound(Calendar.DATE, skeleton); //genFallbackForNotFound(Calendar.MONTH, skeleton); //genFallbackForNotFound(Calendar.YEAR, skeleton); } } else { //genFallbackForNotFound(Calendar.DATE, skeleton); //genFallbackForNotFound(Calendar.MONTH, skeleton); //genFallbackForNotFound(Calendar.YEAR, skeleton); } return intervalPatterns; } // end of skeleton not found // interval patterns for skeleton are found in resource if ( time.length() == 0 ) { // done } else if ( date.length() == 0 ) { // need to set up patterns for y/M/d differ /* result from following looks confusing. * for example: 10 10:10 - 11 10:10, it is not * clear that the first 10 is the 10th day time.insert(0, 'd'); genFallbackPattern(Calendar.DATE, time); time.insert(0, 'M'); genFallbackPattern(Calendar.MONTH, time); time.insert(0, 'y'); genFallbackPattern(Calendar.YEAR, time); */ // prefix with yMd timeSkeleton = DateFormat.YEAR_NUM_MONTH_DAY + timeSkeleton; String pattern =dtpng.getBestPattern(timeSkeleton); // for fall back interval patterns, // the first part of the pattern is empty, // the second part of the pattern is the full-pattern // should be used in fall-back. PatternInfo ptn = new PatternInfo( null, pattern, fInfo.getDefaultOrder()); intervalPatterns.put(DateIntervalInfo. CALENDAR_FIELD_TO_PATTERN_LETTER[Calendar.DATE], ptn); intervalPatterns.put(DateIntervalInfo. CALENDAR_FIELD_TO_PATTERN_LETTER[Calendar.MONTH], ptn); intervalPatterns.put(DateIntervalInfo. CALENDAR_FIELD_TO_PATTERN_LETTER[Calendar.YEAR], ptn); } else { /* if both present, * 1) when the year, month, or day differs, * concatenate the two original expressions with a separator between, * 2) otherwise, present the date followed by the * range expression for the time. */ /* * 1) when the year, month, or day differs, * concatenate the two original expressions with a separator between, */ // if field exists, use fall back if ( !fieldExistsInSkeleton(Calendar.DATE, dateSkeleton) ) { // prefix skeleton with 'd' skeleton = DateIntervalInfo. CALENDAR_FIELD_TO_PATTERN_LETTER[Calendar.DATE] + skeleton; genFallbackPattern(Calendar.DATE, skeleton, intervalPatterns, dtpng); } if ( !fieldExistsInSkeleton(Calendar.MONTH, dateSkeleton) ) { // then prefix skeleton with 'M' skeleton = DateIntervalInfo. CALENDAR_FIELD_TO_PATTERN_LETTER[Calendar.MONTH] + skeleton; genFallbackPattern(Calendar.MONTH, skeleton, intervalPatterns, dtpng); } if ( !fieldExistsInSkeleton(Calendar.YEAR, dateSkeleton) ) { // then prefix skeleton with 'y' skeleton = DateIntervalInfo. CALENDAR_FIELD_TO_PATTERN_LETTER[Calendar.YEAR] + skeleton; genFallbackPattern(Calendar.YEAR, skeleton, intervalPatterns, dtpng); } /* * 2) otherwise, present the date followed by the * range expression for the time. */ if (fDateTimeFormat == null) { fDateTimeFormat = "{1} {0}"; } String datePattern =dtpng.getBestPattern(dateSkeleton); concatSingleDate2TimeInterval(fDateTimeFormat, datePattern, Calendar.AM_PM, intervalPatterns); concatSingleDate2TimeInterval(fDateTimeFormat, datePattern, Calendar.HOUR, intervalPatterns); concatSingleDate2TimeInterval(fDateTimeFormat, datePattern, Calendar.MINUTE, intervalPatterns); } return intervalPatterns; } /** * Retrieves the concatenation DateTime pattern from the resource bundle. * @param locale Locale to retrieve. * @return Concatenation DateTime pattern. */ private String getConcatenationPattern(ULocale locale) { ICUResourceBundle rb = (ICUResourceBundle) UResourceBundle.getBundleInstance(ICUData.ICU_BASE_NAME, locale); ICUResourceBundle dtPatternsRb = rb.getWithFallback("calendar/gregorian/DateTimePatterns"); ICUResourceBundle concatenationPatternRb = (ICUResourceBundle) dtPatternsRb.get(8); if (concatenationPatternRb.getType() == UResourceBundle.STRING) { return concatenationPatternRb.getString(); } else { return concatenationPatternRb.getString(0); } } /* * Generate fall back interval pattern given a calendar field, * a skeleton, and a date time pattern generator * @param field the largest different calendar field * @param skeleton a skeleton * @param dtpng date time pattern generator * @param intervalPatterns interval patterns */ private void genFallbackPattern(int field, String skeleton, Map<String, PatternInfo> intervalPatterns, DateTimePatternGenerator dtpng) { String pattern = dtpng.getBestPattern(skeleton); // for fall back interval patterns, // the first part of the pattern is empty, // the second part of the pattern is the full-pattern // should be used in fall-back. PatternInfo ptn = new PatternInfo( null, pattern, fInfo.getDefaultOrder()); intervalPatterns.put( DateIntervalInfo.CALENDAR_FIELD_TO_PATTERN_LETTER[field], ptn); } /* private void genFallbackForNotFound(String field, StringBuffer skeleton) { if ( SimpleDateFormat.isFieldUnitIgnored(skeleton.toString(), field) ) { // single date DateIntervalInfo.PatternInfo ptnInfo = new DateIntervalInfo.PatternInfo(null, fDateFormat.toPattern(), fInfo.getDefaultOrder()); fIntervalPatterns.put(field, ptnInfo); return; } else if ( skeleton.indexOf(field) == -1 ) { skeleton.insert(0,field); genFallbackPattern(field, skeleton, dtpng); } } */ /* * get separated date and time skeleton from a combined skeleton. * * The difference between date skeleton and normalizedDateSkeleton are: * 1. both 'y' and 'd' are appeared only once in normalizeDateSkeleton * 2. 'E' and 'EE' are normalized into 'EEE' * 3. 'MM' is normalized into 'M' * ** the difference between time skeleton and normalizedTimeSkeleton are: * 1. both 'H' and 'h' are normalized as 'h' in normalized time skeleton, * 2. 'a' is omitted in normalized time skeleton. * 3. there is only one appearance for 'h', 'm','v', 'z' in normalized time * skeleton * * * @param skeleton given combined skeleton. * @param date Output parameter for date only skeleton. * @param normalizedDate Output parameter for normalized date only * * @param time Output parameter for time only skeleton. * @param normalizedTime Output parameter for normalized time only * skeleton. */ private static void getDateTimeSkeleton(String skeleton, StringBuilder dateSkeleton, StringBuilder normalizedDateSkeleton, StringBuilder timeSkeleton, StringBuilder normalizedTimeSkeleton) { // dateSkeleton follows the sequence of y*M*E*d* // timeSkeleton follows the sequence of hm*[v|z]? int i; int ECount = 0; int dCount = 0; int MCount = 0; int yCount = 0; int hCount = 0; int HCount = 0; int mCount = 0; int vCount = 0; int zCount = 0; for (i = 0; i < skeleton.length(); ++i) { char ch = skeleton.charAt(i); switch ( ch ) { case 'E': dateSkeleton.append(ch); ++ECount; break; case 'd': dateSkeleton.append(ch); ++dCount; break; case 'M': dateSkeleton.append(ch); ++MCount; break; case 'y': dateSkeleton.append(ch); ++yCount; break; case 'G': case 'Y': case 'u': case 'Q': case 'q': case 'L': case 'l': case 'W': case 'w': case 'D': case 'F': case 'g': case 'e': case 'c': case 'U': case 'r': normalizedDateSkeleton.append(ch); dateSkeleton.append(ch); break; case 'a': // 'a' is implicitly handled timeSkeleton.append(ch); break; case 'h': timeSkeleton.append(ch); ++hCount; break; case 'H': timeSkeleton.append(ch); ++HCount; break; case 'm': timeSkeleton.append(ch); ++mCount; break; case 'z': ++zCount; timeSkeleton.append(ch); break; case 'v': ++vCount; timeSkeleton.append(ch); break; case 'V': case 'Z': case 'k': case 'K': case 'j': case 's': case 'S': case 'A': timeSkeleton.append(ch); normalizedTimeSkeleton.append(ch); break; } } /* generate normalized form for date*/ if ( yCount != 0 ) { for (i = 0; i < yCount; i++) { normalizedDateSkeleton.append('y'); } } if ( MCount != 0 ) { if ( MCount < 3 ) { normalizedDateSkeleton.append('M'); } else { for ( i = 0; i < MCount && i < 5; ++i ) { normalizedDateSkeleton.append('M'); } } } if ( ECount != 0 ) { if ( ECount <= 3 ) { normalizedDateSkeleton.append('E'); } else { for ( i = 0; i < ECount && i < 5; ++i ) { normalizedDateSkeleton.append('E'); } } } if ( dCount != 0 ) { normalizedDateSkeleton.append('d'); } /* generate normalized form for time */ if ( HCount != 0 ) { normalizedTimeSkeleton.append('H'); } else if ( hCount != 0 ) { normalizedTimeSkeleton.append('h'); } if ( mCount != 0 ) { normalizedTimeSkeleton.append('m'); } if ( zCount != 0 ) { normalizedTimeSkeleton.append('z'); } if ( vCount != 0 ) { normalizedTimeSkeleton.append('v'); } } /* * Generate date or time interval pattern from resource. * * It needs to handle the following: * 1. need to adjust field width. * For example, the interval patterns saved in DateIntervalInfo * includes "dMMMy", but not "dMMMMy". * Need to get interval patterns for dMMMMy from dMMMy. * Another example, the interval patterns saved in DateIntervalInfo * includes "hmv", but not "hmz". * Need to get interval patterns for "hmz' from 'hmv' * * 2. there might be no pattern for 'y' differ for skeleton "Md", * in order to get interval patterns for 'y' differ, * need to look for it from skeleton 'yMd' * * @param dateSkeleton normalized date skeleton * @param timeSkeleton normalized time skeleton * @param intervalPatterns interval patterns * @return whether there is interval patterns for the skeleton. * true if there is, false otherwise */ private boolean genSeparateDateTimePtn(String dateSkeleton, String timeSkeleton, Map<String, PatternInfo> intervalPatterns, DateTimePatternGenerator dtpng) { String skeleton; // if both date and time skeleton present, // the final interval pattern might include time interval patterns // ( when, am_pm, hour, minute, second differ ), // but not date interval patterns ( when year, month, day differ ). // For year/month/day differ, it falls back to fall-back pattern. if ( timeSkeleton.length() != 0 ) { skeleton = timeSkeleton; } else { skeleton = dateSkeleton; } /* interval patterns for skeleton "dMMMy" (but not "dMMMMy") * are defined in resource, * interval patterns for skeleton "dMMMMy" are calculated by * 1. get the best match skeleton for "dMMMMy", which is "dMMMy" * 2. get the interval patterns for "dMMMy", * 3. extend "MMM" to "MMMM" in above interval patterns for "dMMMMy" * getBestSkeleton() is step 1. */ // best skeleton, and the difference information BestMatchInfo retValue = fInfo.getBestSkeleton(skeleton); String bestSkeleton = retValue.bestMatchSkeleton; int differenceInfo = retValue.bestMatchDistanceInfo; // Set patterns for fallback use, need to do this // before returning if differenceInfo == -1 if (dateSkeleton.length() != 0 ) { fDatePattern = dtpng.getBestPattern(dateSkeleton); } if (timeSkeleton.length() != 0 ) { fTimePattern = dtpng.getBestPattern(timeSkeleton); } // difference: // 0 means the best matched skeleton is the same as input skeleton // 1 means the fields are the same, but field width are different // 2 means the only difference between fields are v/z, // -1 means there are other fields difference // (this will happen, for instance, if the supplied skeleton has seconds, // but no skeletons in the intervalFormats data do) if ( differenceInfo == -1 ) { // skeleton has different fields, not only v/z difference return false; } if ( timeSkeleton.length() == 0 ) { // only has date skeleton genIntervalPattern(Calendar.DATE, skeleton, bestSkeleton, differenceInfo, intervalPatterns); SkeletonAndItsBestMatch skeletons = genIntervalPattern( Calendar.MONTH, skeleton, bestSkeleton, differenceInfo, intervalPatterns); if ( skeletons != null ) { bestSkeleton = skeletons.skeleton; skeleton = skeletons.bestMatchSkeleton; } genIntervalPattern(Calendar.YEAR, skeleton, bestSkeleton, differenceInfo, intervalPatterns); } else { genIntervalPattern(Calendar.MINUTE, skeleton, bestSkeleton, differenceInfo, intervalPatterns); genIntervalPattern(Calendar.HOUR, skeleton, bestSkeleton, differenceInfo, intervalPatterns); genIntervalPattern(Calendar.AM_PM, skeleton, bestSkeleton, differenceInfo, intervalPatterns); } return true; } /* * Generate interval pattern from existing resource * * It not only save the interval patterns, * but also return the skeleton and its best match skeleton. * * @param field largest different calendar field * @param skeleton skeleton * @param bestSkeleton the best match skeleton which has interval pattern * defined in resource * @param differenceInfo the difference between skeleton and best skeleton * 0 means the best matched skeleton is the same as input skeleton * 1 means the fields are the same, but field width are different * 2 means the only difference between fields are v/z, * -1 means there are other fields difference * * @param intervalPatterns interval patterns * * @return an extended skeleton or extended best skeleton if applicable. * null otherwise. */ private SkeletonAndItsBestMatch genIntervalPattern( int field, String skeleton, String bestSkeleton, int differenceInfo, Map<String, PatternInfo> intervalPatterns) { SkeletonAndItsBestMatch retValue = null; PatternInfo pattern = fInfo.getIntervalPattern( bestSkeleton, field); if ( pattern == null ) { // single date if ( SimpleDateFormat.isFieldUnitIgnored(bestSkeleton, field) ) { PatternInfo ptnInfo = new PatternInfo(fDateFormat.toPattern(), null, fInfo.getDefaultOrder()); intervalPatterns.put(DateIntervalInfo. CALENDAR_FIELD_TO_PATTERN_LETTER[field], ptnInfo); return null; } // for 24 hour system, interval patterns in resource file // might not include pattern when am_pm differ, // which should be the same as hour differ. // add it here for simplicity if ( field == Calendar.AM_PM ) { pattern = fInfo.getIntervalPattern(bestSkeleton, Calendar.HOUR); if ( pattern != null ) { // share intervalPatterns.put(DateIntervalInfo. CALENDAR_FIELD_TO_PATTERN_LETTER[field], pattern); } return null; } // else, looking for pattern when 'y' differ for 'dMMMM' skeleton, // first, get best match pattern "MMMd", // since there is no pattern for 'y' differs for skeleton 'MMMd', // need to look for it from skeleton 'yMMMd', // if found, adjust field width in interval pattern from // "MMM" to "MMMM". String fieldLetter = DateIntervalInfo.CALENDAR_FIELD_TO_PATTERN_LETTER[field]; bestSkeleton = fieldLetter + bestSkeleton; skeleton = fieldLetter + skeleton; // for example, looking for patterns when 'y' differ for // skeleton "MMMM". pattern = fInfo.getIntervalPattern(bestSkeleton, field); if ( pattern == null && differenceInfo == 0 ) { // if there is no skeleton "yMMMM" defined, // look for the best match skeleton, for example: "yMMM" BestMatchInfo tmpRetValue = fInfo.getBestSkeleton(skeleton); String tmpBestSkeleton = tmpRetValue.bestMatchSkeleton; differenceInfo = tmpRetValue.bestMatchDistanceInfo; if ( tmpBestSkeleton.length() != 0 && differenceInfo != -1 ) { pattern = fInfo.getIntervalPattern(tmpBestSkeleton, field); bestSkeleton = tmpBestSkeleton; } } if ( pattern != null ) { retValue = new SkeletonAndItsBestMatch(skeleton, bestSkeleton); } } if ( pattern != null ) { if ( differenceInfo != 0 ) { String part1 = adjustFieldWidth(skeleton, bestSkeleton, pattern.getFirstPart(), differenceInfo); String part2 = adjustFieldWidth(skeleton, bestSkeleton, pattern.getSecondPart(), differenceInfo); pattern = new PatternInfo(part1, part2, pattern.firstDateInPtnIsLaterDate()); } else { // pattern is immutable, no need to clone; // pattern = (PatternInfo)pattern.clone(); } intervalPatterns.put( DateIntervalInfo.CALENDAR_FIELD_TO_PATTERN_LETTER[field], pattern); } return retValue; } /* * Adjust field width in best match interval pattern to match * the field width in input skeleton. * * TODO (xji) make a general solution * The adjusting rule can be: * 1. always adjust * 2. never adjust * 3. default adjust, which means adjust according to the following rules * 3.1 always adjust string, such as MMM and MMMM * 3.2 never adjust between string and numeric, such as MM and MMM * 3.3 always adjust year * 3.4 do not adjust 'd', 'h', or 'm' if h presents * 3.5 do not adjust 'M' if it is numeric(?) * * Since date interval format is well-formed format, * date and time skeletons are normalized previously, * till this stage, the adjust here is only "adjust strings, such as MMM * and MMMM, EEE and EEEE. * * @param inputSkeleton the input skeleton * @param bestMatchSkeleton the best match skeleton * @param bestMatchIntervalpattern the best match interval pattern * @param differenceInfo the difference between 2 skeletons * 1 means only field width differs * 2 means v/z exchange * @return the adjusted interval pattern */ private static String adjustFieldWidth(String inputSkeleton, String bestMatchSkeleton, String bestMatchIntervalPattern, int differenceInfo ) { if ( bestMatchIntervalPattern == null ) { return null; // the 2nd part could be null } int[] inputSkeletonFieldWidth = new int[58]; int[] bestMatchSkeletonFieldWidth = new int[58]; /* initialize as following { // A B C D E F G H I J K L M N O 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // P Q R S T U V W X Y Z 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // a b c d e f g h i j k l m n o 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // p q r s t u v w x y z 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; */ DateIntervalInfo.parseSkeleton(inputSkeleton, inputSkeletonFieldWidth); DateIntervalInfo.parseSkeleton(bestMatchSkeleton, bestMatchSkeletonFieldWidth); if ( differenceInfo == 2 ) { bestMatchIntervalPattern = bestMatchIntervalPattern.replace('v', 'z'); } StringBuilder adjustedPtn = new StringBuilder(bestMatchIntervalPattern); boolean inQuote = false; char prevCh = 0; int count = 0; int PATTERN_CHAR_BASE = 0x41; // loop through the pattern string character by character int adjustedPtnLength = adjustedPtn.length(); for (int i = 0; i < adjustedPtnLength; ++i) { char ch = adjustedPtn.charAt(i); if (ch != prevCh && count > 0) { // check the repeativeness of pattern letter char skeletonChar = prevCh; if ( skeletonChar == 'L' ) { // for skeleton "M+", the pattern is "...L..." skeletonChar = 'M'; } int fieldCount = bestMatchSkeletonFieldWidth[skeletonChar - PATTERN_CHAR_BASE]; int inputFieldCount = inputSkeletonFieldWidth[skeletonChar - PATTERN_CHAR_BASE]; if ( fieldCount == count && inputFieldCount > fieldCount ) { count = inputFieldCount - fieldCount; for ( int j = 0; j < count; ++j ) { adjustedPtn.insert(i, prevCh); } i += count; adjustedPtnLength += count; } count = 0; } if (ch == '\'') { // Consecutive single quotes are a single quote literal, // either outside of quotes or between quotes if ((i+1) < adjustedPtn.length() && adjustedPtn.charAt(i+1) == '\'') { ++i; } else { inQuote = ! inQuote; } } else if ( ! inQuote && ((ch >= 0x0061 /*'a'*/ && ch <= 0x007A /*'z'*/) || (ch >= 0x0041 /*'A'*/ && ch <= 0x005A /*'Z'*/))) { // ch is a date-time pattern character prevCh = ch; ++count; } } if ( count > 0 ) { // last item // check the repeativeness of pattern letter char skeletonChar = prevCh; if ( skeletonChar == 'L' ) { // for skeleton "M+", the pattern is "...L..." skeletonChar = 'M'; } int fieldCount = bestMatchSkeletonFieldWidth[skeletonChar - PATTERN_CHAR_BASE]; int inputFieldCount = inputSkeletonFieldWidth[skeletonChar - PATTERN_CHAR_BASE]; if ( fieldCount == count && inputFieldCount > fieldCount ) { count = inputFieldCount - fieldCount; for ( int j = 0; j < count; ++j ) { adjustedPtn.append(prevCh); } } } return adjustedPtn.toString(); } /* * Concat a single date pattern with a time interval pattern, * set it into the intervalPatterns, while field is time field. * This is used to handle time interval patterns on skeleton with * both time and date. Present the date followed by * the range expression for the time. * @param dtfmt date and time format * @param datePattern date pattern * @param field time calendar field: AM_PM, HOUR, MINUTE * @param intervalPatterns interval patterns */ private void concatSingleDate2TimeInterval(String dtfmt, String datePattern, int field, Map<String, PatternInfo> intervalPatterns) { PatternInfo timeItvPtnInfo = intervalPatterns.get(DateIntervalInfo.CALENDAR_FIELD_TO_PATTERN_LETTER[field]); if ( timeItvPtnInfo != null ) { String timeIntervalPattern = timeItvPtnInfo.getFirstPart() + timeItvPtnInfo.getSecondPart(); String pattern = SimpleFormatterImpl.formatRawPattern( dtfmt, 2, 2, timeIntervalPattern, datePattern); timeItvPtnInfo = DateIntervalInfo.genPatternInfo(pattern, timeItvPtnInfo.firstDateInPtnIsLaterDate()); intervalPatterns.put( DateIntervalInfo.CALENDAR_FIELD_TO_PATTERN_LETTER[field], timeItvPtnInfo); } // else: fall back // it should not happen if the interval format defined is valid } /* * check whether a calendar field present in a skeleton. * @param field calendar field need to check * @param skeleton given skeleton on which to check the calendar field * @return true if field present in a skeleton. */ private static boolean fieldExistsInSkeleton(int field, String skeleton) { String fieldChar = DateIntervalInfo.CALENDAR_FIELD_TO_PATTERN_LETTER[field]; return ( (skeleton.indexOf(fieldChar) == -1) ? false : true ) ; } /* * readObject. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); initializePattern(isDateIntervalInfoDefault ? LOCAL_PATTERN_CACHE : null); } /** * Get the internal patterns for the skeleton * @deprecated This API is ICU internal only. * @hide original deprecated declaration * @hide draft / provisional / internal are hidden on Android */ @Deprecated public Map<String, PatternInfo> getRawPatterns() { // this is unmodifiable, so ok to return directly return fIntervalPatterns; } }
3e1c820a6d87f7874f670a0e28c400abf889e9a2
20,434
java
Java
hedera-node/src/test/java/com/hedera/services/ServicesMainTest.java
amckay7777/hedera-services
61c337d926d2f31b05b8dfa0094c88ef0b208db5
[ "Apache-2.0" ]
null
null
null
hedera-node/src/test/java/com/hedera/services/ServicesMainTest.java
amckay7777/hedera-services
61c337d926d2f31b05b8dfa0094c88ef0b208db5
[ "Apache-2.0" ]
null
null
null
hedera-node/src/test/java/com/hedera/services/ServicesMainTest.java
amckay7777/hedera-services
61c337d926d2f31b05b8dfa0094c88ef0b208db5
[ "Apache-2.0" ]
null
null
null
32.642173
99
0.77371
12,100
package com.hedera.services; /*- * ‌ * Hedera Services Node * ​ * Copyright (C) 2018 - 2021 Hedera Hashgraph, 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 * * 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. * ‍ */ import com.hedera.services.context.CurrentPlatformStatus; import com.hedera.services.context.NodeInfo; import com.hedera.services.context.ServicesContext; import com.hedera.services.context.properties.GlobalDynamicProperties; import com.hedera.services.context.properties.NodeLocalProperties; import com.hedera.services.context.properties.Profile; import com.hedera.services.context.properties.PropertySource; import com.hedera.services.context.properties.PropertySources; import com.hedera.services.fees.FeeCalculator; import com.hedera.services.fees.FeeMultiplierSource; import com.hedera.services.grpc.GrpcServerManager; import com.hedera.services.ledger.accounts.BackingStore; import com.hedera.services.records.AccountRecordsHistorian; import com.hedera.services.state.exports.AccountsExporter; import com.hedera.services.state.exports.BalancesExporter; import com.hedera.services.state.forensics.IssListener; import com.hedera.services.state.initialization.SystemAccountsCreator; import com.hedera.services.state.initialization.SystemFilesManager; import com.hedera.services.state.logic.NetworkCtxManager; import com.hedera.services.state.merkle.MerkleAccount; import com.hedera.services.state.merkle.MerkleNetworkContext; import com.hedera.services.state.migration.StateMigrations; import com.hedera.services.state.validation.LedgerValidator; import com.hedera.services.stats.ServicesStatsManager; import com.hedera.services.stream.RecordStreamManager; import com.hedera.services.throttling.FunctionalityThrottling; import com.hedera.services.utils.Pause; import com.hedera.services.utils.SystemExits; import com.hederahashgraph.api.proto.java.AccountID; import com.swirlds.common.Address; import com.swirlds.common.AddressBook; import com.swirlds.common.Console; import com.swirlds.common.NodeId; import com.swirlds.common.Platform; import com.swirlds.common.PlatformStatus; import com.swirlds.common.SwirldState; import com.swirlds.common.notification.NotificationEngine; import com.swirlds.common.notification.NotificationFactory; import com.swirlds.common.notification.listeners.ReconnectCompleteListener; import com.swirlds.common.notification.listeners.ReconnectCompleteNotification; import com.swirlds.fcmap.FCMap; import org.apache.commons.lang3.RandomUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InOrder; import java.io.PrintStream; import java.nio.charset.StandardCharsets; import java.time.Instant; import static com.hedera.services.context.SingletonContextsManager.CONTEXTS; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.inOrder; import static org.mockito.BDDMockito.intThat; import static org.mockito.BDDMockito.mock; import static org.mockito.BDDMockito.never; import static org.mockito.BDDMockito.verify; import static org.mockito.BDDMockito.verifyNoInteractions; import static org.mockito.BDDMockito.willThrow; public class ServicesMainTest { private final long NODE_ID = 1L; private final String PATH = "/this/was/mr/bleaneys/room"; private FCMap topics; private FCMap accounts; private FCMap storage; private Pause pause; private Console console; private Platform platform; private SystemExits systemExits; private AddressBook addressBook; private PrintStream consoleOut; private FeeCalculator fees; private ServicesMain subject; private ServicesContext ctx; private PropertySource properties; private LedgerValidator ledgerValidator; private AccountsExporter accountsExporter; private PropertySources propertySources; private BalancesExporter balancesExporter; private StateMigrations stateMigrations; private MerkleNetworkContext networkCtx; private FeeMultiplierSource feeMultiplierSource; private ServicesStatsManager statsManager; private GrpcServerManager grpc; private NodeLocalProperties nodeLocalProps; private SystemFilesManager systemFilesManager; private SystemAccountsCreator systemAccountsCreator; private CurrentPlatformStatus platformStatus; private AccountRecordsHistorian recordsHistorian; private GlobalDynamicProperties globalDynamicProperties; private BackingStore<AccountID, MerkleAccount> backingAccounts; private RecordStreamManager recordStreamManager; private NetworkCtxManager networkCtxManager; private NodeInfo nodeInfo; @BeforeEach private void setup() { fees = mock(FeeCalculator.class); grpc = mock(GrpcServerManager.class); pause = mock(Pause.class); accounts = mock(FCMap.class); topics = mock(FCMap.class); storage = mock(FCMap.class); console = mock(Console.class); consoleOut = mock(PrintStream.class); platform = mock(Platform.class); systemExits = mock(SystemExits.class); recordStreamManager = mock(RecordStreamManager.class); backingAccounts = (BackingStore<AccountID, MerkleAccount>) mock(BackingStore.class); statsManager = mock(ServicesStatsManager.class); stateMigrations = mock(StateMigrations.class); balancesExporter = mock(BalancesExporter.class); nodeLocalProps = mock(NodeLocalProperties.class); recordsHistorian = mock(AccountRecordsHistorian.class); ledgerValidator = mock(LedgerValidator.class); accountsExporter = mock(AccountsExporter.class); platformStatus = mock(CurrentPlatformStatus.class); properties = mock(PropertySource.class); propertySources = mock(PropertySources.class); addressBook = mock(AddressBook.class); systemFilesManager = mock(SystemFilesManager.class); systemAccountsCreator = mock(SystemAccountsCreator.class); globalDynamicProperties = mock(GlobalDynamicProperties.class); networkCtx = mock(MerkleNetworkContext.class); feeMultiplierSource = mock(FeeMultiplierSource.class); networkCtxManager = mock(NetworkCtxManager.class); nodeInfo = mock(NodeInfo.class); given(nodeInfo.hasSelfAccount()).willReturn(true); ctx = mock(ServicesContext.class); given(nodeLocalProps.devListeningAccount()).willReturn("0.0.3"); given(nodeLocalProps.port()).willReturn(50211); given(nodeLocalProps.tlsPort()).willReturn(50212); given(ctx.fees()).willReturn(fees); given(ctx.grpc()).willReturn(grpc); given(ctx.globalDynamicProperties()).willReturn(globalDynamicProperties); given(ctx.pause()).willReturn(pause); given(ctx.nodeLocalProperties()).willReturn(nodeLocalProps); given(ctx.accounts()).willReturn(accounts); given(ctx.id()).willReturn(new NodeId(false, NODE_ID)); given(ctx.nodeInfo()).willReturn(nodeInfo); given(ctx.console()).willReturn(console); given(ctx.consoleOut()).willReturn(consoleOut); given(ctx.addressBook()).willReturn(addressBook); given(ctx.platform()).willReturn(platform); given(ctx.recordStreamManager()).willReturn(recordStreamManager); given(ctx.platformStatus()).willReturn(platformStatus); given(ctx.ledgerValidator()).willReturn(ledgerValidator); given(ctx.propertySources()).willReturn(propertySources); given(ctx.properties()).willReturn(properties); given(ctx.recordStreamManager()).willReturn(recordStreamManager); given(ctx.stateMigrations()).willReturn(stateMigrations); given(ctx.recordsHistorian()).willReturn(recordsHistorian); given(ctx.backingAccounts()).willReturn(backingAccounts); given(ctx.systemFilesManager()).willReturn(systemFilesManager); given(ctx.systemAccountsCreator()).willReturn(systemAccountsCreator); given(ctx.accountsExporter()).willReturn(accountsExporter); given(ctx.balancesExporter()).willReturn(balancesExporter); given(ctx.statsManager()).willReturn(statsManager); given(ctx.consensusTimeOfLastHandledTxn()).willReturn(Instant.ofEpochSecond(33L, 0)); given(ctx.networkCtx()).willReturn(networkCtx); given(ctx.networkCtxManager()).willReturn(networkCtxManager); given(ctx.feeMultiplierSource()).willReturn(feeMultiplierSource); given(ledgerValidator.hasExpectedTotalBalance(any())).willReturn(true); given(properties.getIntProperty("timer.stats.dump.value")).willReturn(123); subject = new ServicesMain(); subject.systemExits = systemExits; subject.defaultCharset = () -> StandardCharsets.UTF_8; CONTEXTS.store(ctx); } @Test void failsFastOnNonUtf8DefaultCharset() { // setup: subject.defaultCharset = () -> StandardCharsets.US_ASCII; // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verify(systemExits).fail(1); } @Test void failsFastOnMissingNodeAccountIdIfNotSkippingExits() { given(nodeInfo.hasSelfAccount()).willReturn(false); // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verify(systemExits).fail(1); } @Test void exitsOnAddressBookCreationFailure() { willThrow(IllegalStateException.class) .given(systemFilesManager).createAddressBookIfMissing(); // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verify(systemExits).fail(1); } @Test void exitsOnCreationFailure() { willThrow(IllegalStateException.class) .given(systemAccountsCreator).ensureSystemAccounts(any(), any()); // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verify(systemExits).fail(1); } @Test void initializesSanelyGivenPreconditions() { var throttling = mock(FunctionalityThrottling.class); // given: InOrder inOrder = inOrder( systemFilesManager, networkCtxManager, platform, stateMigrations, ledgerValidator, recordsHistorian, fees, grpc, statsManager, ctx, networkCtx, feeMultiplierSource); given(ctx.handleThrottling()).willReturn(throttling); // when: subject.init(null, new NodeId(false, NODE_ID)); // then: inOrder.verify(networkCtxManager).loadObservableSysFilesIfNeeded(); inOrder.verify(stateMigrations).runAllFor(ctx); inOrder.verify(ledgerValidator).assertIdsAreValid(accounts); inOrder.verify(ledgerValidator).hasExpectedTotalBalance(accounts); inOrder.verify(platform).setSleepAfterSync(0L); inOrder.verify(platform).addSignedStateListener(any(IssListener.class)); inOrder.verify(statsManager).initializeFor(platform); inOrder.verify(ctx).initRecordStreamManager(); } @Test void runsOnDefaultPortInProduction() { given(nodeLocalProps.activeProfile()).willReturn(Profile.PROD); // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verify(grpc).start(intThat(i -> i == 50211), intThat(i -> i == 50212), any()); } @Test void runsOnDefaultPortInDevIfBlessedInSingleNodeListeningNode() { // setup: Address address = mock(Address.class); given(nodeLocalProps.activeProfile()).willReturn(Profile.DEV); given(address.getMemo()).willReturn("0.0.3"); given(addressBook.getAddress(NODE_ID)).willReturn(address); given(nodeLocalProps.devOnlyDefaultNodeListens()).willReturn(true); // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verify(grpc).start(intThat(i -> i == 50211), intThat(i -> i == 50212), any()); } @Test void doesntRunInDevIfNotBlessedInSingleNodeListeningNode() { // setup: Address address = mock(Address.class); given(nodeLocalProps.activeProfile()).willReturn(Profile.DEV); given(address.getMemo()).willReturn("0.0.4"); given(addressBook.getAddress(NODE_ID)).willReturn(address); given(nodeLocalProps.devOnlyDefaultNodeListens()).willReturn(true); // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verifyNoInteractions(grpc); } @Test void runsOnDefaultPortInDevIfNotInSingleNodeListeningNodeAndDefault() { // setup: Address address = mock(Address.class); given(nodeLocalProps.activeProfile()).willReturn(Profile.DEV); given(address.getMemo()).willReturn("0.0.3"); given(address.getPortExternalIpv4()).willReturn(50001); given(addressBook.getAddress(NODE_ID)).willReturn(address); given(nodeLocalProps.devOnlyDefaultNodeListens()).willReturn(false); // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verify(grpc).start(intThat(i -> i == 50211), intThat(i -> i == 50212), any()); } @Test void runsOnOffsetPortInDevIfNotInSingleNodeListeningNodeAndNotDefault() { // setup: Address address = mock(Address.class); given(nodeLocalProps.activeProfile()).willReturn(Profile.DEV); given(address.getMemo()).willReturn("0.0.4"); given(address.getPortExternalIpv4()).willReturn(50001); given(addressBook.getAddress(NODE_ID)).willReturn(address); given(nodeLocalProps.devOnlyDefaultNodeListens()).willReturn(false); // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verify(grpc).start(intThat(i -> i == 50212), intThat(i -> i == 50213), any()); } @Test void loadsSystemFilesIfNotAlreadyDone() { given(systemFilesManager.areObservableFilesLoaded()).willReturn(true); // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verify(systemFilesManager).createAddressBookIfMissing(); verify(systemFilesManager).createNodeDetailsIfMissing(); verify(systemFilesManager).createUpdateZipFileIfMissing(); // and: verify(systemFilesManager, never()).loadObservableSystemFiles(); } @Test void managesSystemFiles() { given(systemFilesManager.areObservableFilesLoaded()).willReturn(false); // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verify(systemFilesManager).createAddressBookIfMissing(); verify(systemFilesManager).createNodeDetailsIfMissing(); verify(systemFilesManager).createUpdateZipFileIfMissing(); // and: verify(networkCtxManager).loadObservableSysFilesIfNeeded(); } @Test void createsSystemAccountsIfRequested() { // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verify(systemAccountsCreator).ensureSystemAccounts(backingAccounts, addressBook); verify(pause).forMs(ServicesMain.SUGGESTED_POST_CREATION_PAUSE_MS); } @Test void rethrowsAccountsCreationFailureAsIse() { given(ctx.systemAccountsCreator()).willReturn(null); // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verify(systemExits).fail(1); } @Test void exportsAccountsIfRequested() throws Exception { given(nodeLocalProps.accountsExportPath()).willReturn(PATH); given(nodeLocalProps.exportAccountsOnStartup()).willReturn(true); // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verify(accountsExporter).toFile(PATH, accounts); } @Test void rethrowsAccountsExportFailureAsIse() { given(nodeLocalProps.accountsExportPath()).willReturn(PATH); given(nodeLocalProps.exportAccountsOnStartup()).willReturn(true); given(ctx.accountsExporter()).willReturn(null); // when: subject.init(null, new NodeId(false, NODE_ID)); // then: verify(systemExits).fail(1); } @Test void updatesCurrentStatusOnChangeOnlyIfBehind() { // given: subject.ctx = ctx; PlatformStatus newStatus = PlatformStatus.BEHIND; // when: subject.platformStatusChange(newStatus); // then: verify(platformStatus).set(newStatus); verifyNoInteractions(recordStreamManager); } @Test void updatesCurrentStatusAndFreezesRecordStreamOnMaintenance() { // given: subject.ctx = ctx; PlatformStatus newStatus = PlatformStatus.MAINTENANCE; // when: subject.platformStatusChange(newStatus); // then: verify(platformStatus).set(newStatus); verify(recordStreamManager).setInFreeze(true); } @Test void updatesCurrentStatusAndFreezesRecordStreamOnActive() { // given: subject.ctx = ctx; PlatformStatus newStatus = PlatformStatus.ACTIVE; // when: subject.platformStatusChange(newStatus); // then: verify(platformStatus).set(newStatus); verify(recordStreamManager).setInFreeze(false); } @Test void doesLogSummaryIfNotInMaintenance() { // setup: subject.ctx = ctx; var signedState = mock(ServicesState.class); var currentPlatformStatus = mock(CurrentPlatformStatus.class); given(currentPlatformStatus.get()).willReturn(PlatformStatus.DISCONNECTED); given(ctx.platformStatus()).willReturn(currentPlatformStatus); // when: subject.newSignedState(signedState, Instant.now(), 1L); // then: verify(signedState, never()).logSummary(); } @Test void onlyLogsSummary() { // setup: subject.ctx = ctx; var signedState = mock(ServicesState.class); var currentPlatformStatus = mock(CurrentPlatformStatus.class); given(currentPlatformStatus.get()).willReturn(PlatformStatus.MAINTENANCE); given(ctx.platformStatus()).willReturn(currentPlatformStatus); // when: subject.newSignedState(signedState, Instant.now(), 1L); // then: verify(signedState).logSummary(); } @Test void doesntExportBalanceIfNotTime() throws Exception { // setup: subject.ctx = ctx; Instant when = Instant.now(); ServicesState signedState = mock(ServicesState.class); given(properties.getBooleanProperty("hedera.exportBalancesOnNewSignedState")).willReturn(true); given(balancesExporter.isTimeToExport(when)).willReturn(false); // when: subject.newSignedState(signedState, when, 1L); // then: verify(balancesExporter, never()).exportBalancesFrom(any(), any(), any()); } @Test void exportsBalancesIfPropertySet() throws Exception { // setup: subject.ctx = ctx; Instant when = Instant.now(); ServicesState signedState = mock(ServicesState.class); given(globalDynamicProperties.shouldExportBalances()).willReturn(true); given(balancesExporter.isTimeToExport(when)).willReturn(true); // when: subject.newSignedState(signedState, when, 1L); // then: verify(balancesExporter).exportBalancesFrom(signedState, when, ctx.id()); } @Test void doesntExportBalancesIfPropertyNotSet() { // setup: subject.ctx = ctx; Instant when = Instant.now(); ServicesState signedState = mock(ServicesState.class); given(globalDynamicProperties.shouldExportBalances()).willReturn(false); // when: subject.newSignedState(signedState, when, 1L); // then: verifyNoInteractions(balancesExporter); } @Test void failsFastIfBalanceExportDetectedInvalidState() throws Exception { // setup: subject.ctx = ctx; var nodeId = ctx.id(); Instant when = Instant.now(); ServicesState signedState = mock(ServicesState.class); given(globalDynamicProperties.shouldExportBalances()).willReturn(true); given(balancesExporter.isTimeToExport(when)).willReturn(true); willThrow(IllegalStateException.class) .given(balancesExporter) .exportBalancesFrom(signedState, when, nodeId); // when: subject.newSignedState(signedState, when, 1L); // then: verify(systemExits).fail(1); } @Test void noOpsRun() { // expect: assertDoesNotThrow(() -> { subject.run(); subject.preEvent(); }); } @Test void returnsAppState() { // expect: assertTrue(subject.newState() instanceof ServicesState); } @Test void registerReconnectCompleteListenerTest() { NotificationEngine engineMock = mock(NotificationEngine.class); subject.registerReconnectCompleteListener(engineMock); verify(engineMock).register(eq(ReconnectCompleteListener.class), any()); } @Test void reconnectCompleteListenerTest() { // setup subject.ctx = ctx; // register subject.registerReconnectCompleteListener(NotificationFactory.getEngine()); final long roundNumber = RandomUtils.nextLong(); final Instant consensusTimestamp = Instant.now(); final SwirldState state = mock(ServicesState.class); // dispatch a notification final ReconnectCompleteNotification notification = new ReconnectCompleteNotification(roundNumber, consensusTimestamp, state); NotificationFactory.getEngine().dispatch(ReconnectCompleteListener.class, notification); // should receive this notification verify(recordStreamManager).setStartWriteAtCompleteWindow(true); } }
3e1c828dcf041dce12c5b944ba6d8970b180022f
533
java
Java
jeecg-boot/jeecg-boot-module-ilang/src/main/java/org/jeecg/modules/ilang/mapper/SysParamsItemMapper.java
Senriot/ilang-boot
9e7f7732d2eb0689621a61f694c24a0332bfc53c
[ "Apache-2.0" ]
null
null
null
jeecg-boot/jeecg-boot-module-ilang/src/main/java/org/jeecg/modules/ilang/mapper/SysParamsItemMapper.java
Senriot/ilang-boot
9e7f7732d2eb0689621a61f694c24a0332bfc53c
[ "Apache-2.0" ]
null
null
null
jeecg-boot/jeecg-boot-module-ilang/src/main/java/org/jeecg/modules/ilang/mapper/SysParamsItemMapper.java
Senriot/ilang-boot
9e7f7732d2eb0689621a61f694c24a0332bfc53c
[ "Apache-2.0" ]
null
null
null
26.65
75
0.763602
12,101
package org.jeecg.modules.ilang.mapper; import java.util.List; import org.jeecg.modules.ilang.entity.SysParamsItem; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Param; /** * @Description: 参数详情 * @Author: jeecg-boot * @Date: 2021-01-02 * @Version: V1.0 */ public interface SysParamsItemMapper extends BaseMapper<SysParamsItem> { public boolean deleteByMainId(@Param("mainId") String mainId); public List<SysParamsItem> selectByMainId(@Param("mainId") String mainId); }
3e1c82a190cc9f4b5e8b12f86c2daa483ade9081
2,850
java
Java
src/main/java/technology/tabula/TextStripper.java
datNurd/tabula-java
295b81c35052186f343c3728b4b9893d85b611f2
[ "MIT" ]
1
2017-09-12T12:46:03.000Z
2017-09-12T12:46:03.000Z
src/main/java/technology/tabula/TextStripper.java
datNurd/tabula-java
295b81c35052186f343c3728b4b9893d85b611f2
[ "MIT" ]
4
2018-03-24T00:10:36.000Z
2020-05-14T23:00:11.000Z
src/main/java/technology/tabula/TextStripper.java
datNurd/tabula-java
295b81c35052186f343c3728b4b9893d85b611f2
[ "MIT" ]
1
2019-04-24T08:54:56.000Z
2019-04-24T08:54:56.000Z
34.756098
119
0.616842
12,102
package technology.tabula; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.apache.pdfbox.text.TextPosition; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class TextStripper extends PDFTextStripper { private static final String NBSP = "\u00A0"; private PDDocument document; public ArrayList<TextElement> textElements; public RectangleSpatialIndex<TextElement> spatialIndex; public float minCharWidth = Float.MAX_VALUE; public float minCharHeight = Float.MAX_VALUE; public TextStripper(PDDocument document, int pageNumber) throws IOException { super(); this.document = document; this.setStartPage(pageNumber); this.setEndPage(pageNumber); this.textElements = new ArrayList<>(); this.spatialIndex = new RectangleSpatialIndex<>(); } public void process() throws IOException { this.getText(this.document); } @Override protected void writeString(String string, List<TextPosition> textPositions) throws IOException { for (TextPosition textPosition: textPositions) { if (textPosition == null) { continue; } String c = textPosition.getUnicode(); // if c not printable, return if (!isPrintable(c)) { continue; } Float h = textPosition.getHeightDir(); if (c.equals(NBSP)) { // replace non-breaking space for space c = " "; } float wos = textPosition.getWidthOfSpace(); TextElement te = new TextElement(Utils.round(textPosition.getYDirAdj() - h, 2), Utils.round(textPosition.getXDirAdj(), 2), Utils.round(textPosition.getWidthDirAdj(), 2), Utils.round(textPosition.getHeightDir(), 2), textPosition.getFont(), textPosition.getFontSize(), c, // workaround a possible bug in PDFBox: // https://issues.apache.org/jira/browse/PDFBOX-1755 wos, textPosition.getDir()); this.minCharWidth = (float) Math.min(this.minCharWidth, te.getWidth()); this.minCharHeight = (float) Math.min(this.minCharHeight, te.getHeight()); this.spatialIndex.add(te); this.textElements.add(te); } } private boolean isPrintable(String s) { Character c; Character.UnicodeBlock block; boolean printable = false; for (int i = 0; i < s.length(); i++) { c = s.charAt(i); block = Character.UnicodeBlock.of(c); printable |= !Character.isISOControl(c) && block != null && block != Character.UnicodeBlock.SPECIALS; } return printable; } }
3e1c82c0b7d0cd158316690a0bfe8f507e63e0fa
1,927
java
Java
test/org/traccar/protocol/Tlt2hProtocolDecoderTest.java
hallmark9/traccar-contrib
991369f349d0b8d360e43d6a3a4821e2364ca987
[ "Apache-2.0" ]
3
2015-06-22T15:49:39.000Z
2016-10-07T19:41:12.000Z
test/org/traccar/protocol/Tlt2hProtocolDecoderTest.java
hallmark9/traccar-contrib
991369f349d0b8d360e43d6a3a4821e2364ca987
[ "Apache-2.0" ]
null
null
null
test/org/traccar/protocol/Tlt2hProtocolDecoderTest.java
hallmark9/traccar-contrib
991369f349d0b8d360e43d6a3a4821e2364ca987
[ "Apache-2.0" ]
2
2016-03-22T14:50:45.000Z
2021-01-18T09:43:09.000Z
43.795455
103
0.606642
12,103
package org.traccar.protocol; import org.traccar.helper.TestIdentityManager; import static org.traccar.helper.DecoderVerifier.verify; import org.junit.Test; public class Tlt2hProtocolDecoderTest extends ProtocolDecoderTest { @Test public void testDecode() throws Exception { Tlt2hProtocolDecoder decoder = new Tlt2hProtocolDecoder(new Tlt2hProtocol()); verify(decoder.decode(null, null, "#357671030946351#V500#0000#AUTO#1\r\n" + "#$GPRMC,223835.000,A,0615.3545,S,10708.5779,E,14.62,97.41,070313,,,D*70\r\n")); verify(decoder.decode(null, null, "\r\n#357671030946351#V500#0000#AUTO#1\r\n" + "#$GPRMC,223835.000,A,0615.3545,S,10708.5779,E,14.62,97.41,070313,,,D*70\r\n")); verify(decoder.decode(null, null, "#357671030938911#V500#0000#AUTOSTOP#1\r\n" + "#00b34d3c$GPRMC,140026.000,A,2623.6452,S,02828.8990,E,0.00,65.44,130213,,,A*4B\r\n")); verify(decoder.decode(null, null, "#123456789000001#V3338#0000#SMS#3\r\n" + "#25ee0dff$GPRMC,083945.180,A,2233.4249,N,11406.0046,E,0.00,315.00,251207,,,A*6E\r\n" + "#25ee0dff$GPRMC,083950.180,A,2233.4249,N,11406.0046,E,0.00,315.00,251207,,,A*6E\r\n" + "#25ee0dff$GPRMC,083955.180,A,2233.4249,N,11406.0046,E,0.00,315.00,251207,,,A*6E")); verify(decoder.decode(null, null, "#353686009063310#353686009063310#0000#AUTO#2\r\n" + "#239757a9$GPRMC,150252.001,A,2326.6856,S,4631.8154,W,,,260513,,,A*52\r\n" + "#239757a9$GPRMC,150322.001,A,2326.6854,S,4631.8157,W,,,260513,,,A*55")); verify(decoder.decode(null, null, "#357671031289215#V600#0000#AUTOLOW#1\r\n" + "#00735e1c$GPRMC,115647.000,A,5553.6524,N,02632.3128,E,0.00,0.0,130614,0.0,W,A*28")); } }
3e1c8331d741ef80c46253f3638ac1fc77fadbed
1,051
java
Java
src/com/dc/test/entity/Student.java
xiuyouxu/spring-mvc-hibernate
c1efa6a53007b8b0e421f45be5e6b7bf5b958ea7
[ "Apache-2.0" ]
null
null
null
src/com/dc/test/entity/Student.java
xiuyouxu/spring-mvc-hibernate
c1efa6a53007b8b0e421f45be5e6b7bf5b958ea7
[ "Apache-2.0" ]
null
null
null
src/com/dc/test/entity/Student.java
xiuyouxu/spring-mvc-hibernate
c1efa6a53007b8b0e421f45be5e6b7bf5b958ea7
[ "Apache-2.0" ]
null
null
null
20.211538
53
0.694577
12,104
package com.dc.test.entity; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import org.hibernate.annotations.Table; @Entity(name="student") @Table(appliesTo = "student") public class Student implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) private Integer id; @Column(name = "name") private String user; @Column(name = "psw") private String psw; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPsw() { return psw; } public void setPsw(String psw) { this.psw = psw; } }
3e1c8393ba59bf14fbc0b78a457814bac22e09ca
10,537
java
Java
src/main/java/com/github/xsavikx/androidscreencast/api/recording/DataAtomOutputStream.java
brunodles/AndroidScreencast
4727d31ed30766e9f88f867bd229e8e4165e723a
[ "Apache-2.0" ]
2
2018-12-05T12:44:57.000Z
2019-06-27T12:01:39.000Z
src/main/java/com/github/xsavikx/androidscreencast/api/recording/DataAtomOutputStream.java
sighttviewliu/AndroidScreencast
327a06624c170d594f4617d320a0244d79897c94
[ "Apache-2.0" ]
1
2016-08-15T13:31:54.000Z
2016-08-15T13:31:54.000Z
src/main/java/com/github/xsavikx/androidscreencast/api/recording/DataAtomOutputStream.java
brunodles/AndroidScreencast
4727d31ed30766e9f88f867bd229e8e4165e723a
[ "Apache-2.0" ]
null
null
null
30.991176
151
0.572079
12,105
package com.github.xsavikx.androidscreencast.api.recording; import com.github.xsavikx.androidscreencast.api.recording.atom.AtomType; import com.github.xsavikx.androidscreencast.exception.IORuntimeException; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public class DataAtomOutputStream extends FilterOutputStream { protected static final long MAC_TIMESTAMP_EPOCH = new GregorianCalendar(1904, Calendar.JANUARY, 1).getTimeInMillis(); /** * The number of bytes written to the data output stream so far. If this counter overflows, it will be wrapped to Integer.MAX_VALUE. */ protected long written; public DataAtomOutputStream(OutputStream out) { super(out); } /** * Increases the written counter by the specified value until it reaches Long.MAX_VALUE. */ protected void incCount(int value) { long temp = written + value; if (temp < 0) { temp = Long.MAX_VALUE; } written = temp; } /** * Returns the current value of the counter <code>written</code>, the number of bytes written to this data output stream so far. If the counter * overflows, it will be wrapped to Integer.MAX_VALUE. * * @return the value of the <code>written</code> field. * @see java.io.DataOutputStream#written */ public final long size() { return written; } /** * Writes <code>len</code> bytes from the specified byte array starting at offset <code>off</code> to the underlying output stream. If no exception * is thrown, the counter <code>written</code> is incremented by <code>len</code> . * * @param b the data. * @param off the start offset in the data. * @param len the number of bytes to write. * @throws IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ @Override public synchronized void write(byte b[], int off, int len) throws IOException { out.write(b, off, len); incCount(len); } /** * Writes the specified byte (the low eight bits of the argument <code>b</code>) to the underlying output stream. If no exception is thrown, the * counter <code>written</code> is incremented by <code>1</code> . * <p> * Implements the <code>write</code> method of <code>OutputStream</code>. * * @param b the <code>byte</code> to be written. * @throws IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ @Override public synchronized void write(int b) throws IOException { out.write(b); incCount(1); } /** * Writes a <code>BCD2</code> to the underlying output stream. * * @param v an <code>int</code> to be written. * @throws IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public void writeBCD2(int v) throws IOException { out.write(((v % 100 / 10) << 4) | (v % 10)); incCount(1); } /** * Writes a <code>BCD4</code> to the underlying output stream. * * @param v an <code>int</code> to be written. * @throws IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public void writeBCD4(int v) throws IOException { out.write(((v % 10000 / 1000) << 4) | (v % 1000 / 100)); out.write(((v % 100 / 10) << 4) | (v % 10)); incCount(2); } /** * Writes out a <code>byte</code> to the underlying output stream as a 1-byte value. If no exception is thrown, the counter <code>written</code> is * incremented by <code>1</code>. * * @param v a <code>byte</code> value to be written. * @throws IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public final void writeByte(int v) throws IOException { out.write(v); incCount(1); } /** * Writes 32-bit fixed-point number divided as 16.16. * * @param f an <code>int</code> to be written. * @throws IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public void writeFixed16D16(double f) throws IOException { double v = (f >= 0) ? f : -f; int wholePart = (int) v; int fractionPart = (int) ((v - wholePart) * 65536); int t = (wholePart << 16) + fractionPart; if (f < 0) { t = t - 1; } writeInt(t); } /** * Writes 32-bit fixed-point number divided as 2.30. * * @param f an <code>int</code> to be written. * @throws IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public void writeFixed2D30(double f) throws IOException { double v = (f >= 0) ? f : -f; int wholePart = (int) v; int fractionPart = (int) ((v - wholePart) * 1073741824); int t = (wholePart << 30) + fractionPart; if (f < 0) { t = t - 1; } writeInt(t); } /** * Writes 16-bit fixed-point number divided as 8.8. * * @param f an <code>int</code> to be written. * @throws IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public void writeFixed8D8(float f) throws IOException { float v = (f >= 0) ? f : -f; int wholePart = (int) v; int fractionPart = (int) ((v - wholePart) * 256); int t = (wholePart << 8) + fractionPart; if (f < 0) { t = t - 1; } writeUShort(t); } /** * Writes an <code>int</code> to the underlying output stream as four bytes, high byte first. If no exception is thrown, the counter * <code>written</code> is incremented by <code>4</code>. * * @param v an <code>int</code> to be written. * @throws IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public void writeInt(int v) throws IOException { out.write((v >>> 24) & 0xff); out.write((v >>> 16) & 0xff); out.write((v >>> 8) & 0xff); out.write((v >>> 0) & 0xff); incCount(4); } public void writeLong(long v) throws IOException { out.write((int) (v >>> 56) & 0xff); out.write((int) (v >>> 48) & 0xff); out.write((int) (v >>> 40) & 0xff); out.write((int) (v >>> 32) & 0xff); out.write((int) (v >>> 24) & 0xff); out.write((int) (v >>> 16) & 0xff); out.write((int) (v >>> 8) & 0xff); out.write((int) (v >>> 0) & 0xff); incCount(8); } /** * Writes a 32-bit Mac timestamp (seconds since 1902). * * @param date * @throws java.io.IOException */ public void writeMacTimestamp(Date date) throws IOException { long millis = date.getTime(); long qtMillis = millis - MAC_TIMESTAMP_EPOCH; long qtSeconds = qtMillis / 1000; writeUInt(qtSeconds); } /** * Writes a Pascal String. * * @param s * @throws java.io.IOException */ public void writePString(String s) throws IOException { if (s.length() > 0xffff) { throw new IllegalArgumentException("String too long for PString"); } if (s.length() < 256) { out.write(s.length()); } else { out.write(0); writeShort(s.length()); // increments +2 } for (int i = 0; i < s.length(); i++) { out.write(s.charAt(i)); } incCount(1 + s.length()); } /** * Writes a Pascal String padded to the specified fixed size in bytes * * @param s * @param length the fixed size in bytes * @throws java.io.IOException */ public void writePString(String s, int length) throws IOException { if (s.length() > length) { throw new IllegalArgumentException("String too long for PString of length " + length); } if (s.length() < 256) { out.write(s.length()); } else { out.write(0); writeShort(s.length()); // increments +2 } for (int i = 0; i < s.length(); i++) { out.write(s.charAt(i)); } // write pad bytes for (int i = 1 + s.length(); i < length; i++) { out.write(0); } incCount(length); } /** * Writes a signed 16 bit integer value. * * @param v The value * @throws java.io.IOException */ public void writeShort(int v) throws IOException { out.write((v >> 8) & 0xff); out.write((v >>> 0) & 0xff); incCount(2); } /** * Writes an Atom Type identifier (4 bytes). * * @param type A string with a length of 4 characters. */ private void writeType(String type) throws IOException { checkArgument(type.length() == 4, "Type string must have exactly 4 characters. type=%s", type); try { out.write(type.getBytes("ASCII"), 0, 4); incCount(4); } catch (UnsupportedEncodingException e) { throw new InternalError(e.toString()); } } /** * Writes an Atom Type identifier (4 bytes). * * @param atomType AtomType to be written */ public void writeType(AtomType atomType) throws IOException { checkNotNull(atomType, "AtomType should not be null"); writeType(atomType.toStringRepresentation()); } /** * Writes an unsigned 32 bit integer value. * * @param v The value * @throws java.io.IOException */ public void writeUInt(long v) throws IOException { out.write((int) ((v >>> 24) & 0xff)); out.write((int) ((v >>> 16) & 0xff)); out.write((int) ((v >>> 8) & 0xff)); out.write((int) ((v >>> 0) & 0xff)); incCount(4); } public void writeUShort(int v) throws IOException { out.write((v >> 8) & 0xff); out.write((v >>> 0) & 0xff); incCount(2); } @Override public void close() { try { flush(); } catch (IOException e) { throw new IORuntimeException(e); } } }
3e1c84192878313970f88bcc151f71597067ec5f
530
java
Java
src/hirondelle/stocks/table/SortOrder.java
adabalaravi/StockMonitor
873d4588df828bc3309a7ea65c8ee3606db67af4
[ "CC-BY-1.0" ]
null
null
null
src/hirondelle/stocks/table/SortOrder.java
adabalaravi/StockMonitor
873d4588df828bc3309a7ea65c8ee3606db67af4
[ "CC-BY-1.0" ]
null
null
null
src/hirondelle/stocks/table/SortOrder.java
adabalaravi/StockMonitor
873d4588df828bc3309a7ea65c8ee3606db67af4
[ "CC-BY-1.0" ]
null
null
null
19.62963
66
0.654717
12,106
package hirondelle.stocks.table; /** * Enumeration class for the two directions which a sort may take. */ public enum SortOrder { DESCENDING("Descending"), ASCENDING("Ascending"); @Override public String toString() { return fName; } /** * Return the opposite <tt>SortOrder</tt> from <tt>this</tt> one. */ public SortOrder toggle(){ return (this == ASCENDING ? DESCENDING : ASCENDING); } // PRIVATE private final String fName; private SortOrder(String aName){ fName = aName; } }
3e1c8462a7c3fd0fe4fec6f7acc2c88d675e7984
820
java
Java
src/main/java/com/forum/forum/swagger2/SpringFoxConfig.java
levelopers/community
d719971fcd6691f447efaef61860197b668dc605
[ "MIT" ]
2
2020-06-16T05:20:11.000Z
2020-09-17T12:49:36.000Z
src/main/java/com/forum/forum/swagger2/SpringFoxConfig.java
levelopers/community
d719971fcd6691f447efaef61860197b668dc605
[ "MIT" ]
1
2022-02-20T05:48:59.000Z
2022-02-20T05:48:59.000Z
src/main/java/com/forum/forum/swagger2/SpringFoxConfig.java
levelopers/community
d719971fcd6691f447efaef61860197b668dc605
[ "MIT" ]
null
null
null
30.37037
67
0.734146
12,107
package com.forum.forum.swagger2; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author :Zack * @date :Created in 2020/3/29 0:27 */ @Configuration @EnableSwagger2 public class SpringFoxConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } }
3e1c852bda71bfb21ca69511f0c17db3c0935f33
1,750
java
Java
src/com/facebook/buck/cxx/toolchain/SymbolNameTool.java
zhangshuai930822/BUCK
296a5355e3209b409b729035f7724680d2be6f84
[ "Apache-2.0" ]
1
2018-04-11T08:06:37.000Z
2018-04-11T08:06:37.000Z
src/com/facebook/buck/cxx/toolchain/SymbolNameTool.java
zhangshuai930822/BUCK
296a5355e3209b409b729035f7724680d2be6f84
[ "Apache-2.0" ]
1
2018-12-10T15:54:22.000Z
2018-12-10T19:30:37.000Z
src/com/facebook/buck/cxx/toolchain/SymbolNameTool.java
ttsugriy/buck
655d4e3271d04adf231bb343314378e55027d646
[ "Apache-2.0" ]
null
null
null
36.458333
97
0.755429
12,108
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.cxx.toolchain; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathRuleFinder; /** * Provides methods to extract symbol names from native formats (e.g. binaries, shared libraries, * object files). */ public interface SymbolNameTool { /** * Creates a {@link BuildRule} which extracts all undefined symbols from the given inputs. * * @param target the name to use when creating the rule which extracts the symbols. * @return a {@link SourcePath} referring to a file containing all undefined symbols, one per * line, in the given inputs. */ SourcePath createUndefinedSymbolsFile( ProjectFilesystem projectFilesystem, BuildRuleParams baseParams, BuildRuleResolver ruleResolver, SourcePathRuleFinder ruleFinder, BuildTarget target, Iterable<? extends SourcePath> linkerInputs); }
3e1c852ee9d3ceda0ddefebcdf1d5d46ca3e213a
1,673
java
Java
oscm-extsvc-internal/javasrc/org/oscm/internal/types/exception/beans/SessionIndexNotFoundExceptionBean.java
srinathjiinfotach/billingdevelopment
564e66593c9d272b8e04804410b633bc089aa203
[ "Apache-2.0" ]
56
2015-10-06T15:09:39.000Z
2021-08-09T01:18:03.000Z
oscm-extsvc-internal/javasrc/org/oscm/internal/types/exception/beans/SessionIndexNotFoundExceptionBean.java
srinathjiinfotach/billingdevelopment
564e66593c9d272b8e04804410b633bc089aa203
[ "Apache-2.0" ]
845
2016-02-10T14:06:17.000Z
2020-10-20T07:44:09.000Z
oscm-extsvc-internal/javasrc/org/oscm/internal/types/exception/beans/SessionIndexNotFoundExceptionBean.java
srinathjiinfotach/billingdevelopment
564e66593c9d272b8e04804410b633bc089aa203
[ "Apache-2.0" ]
41
2015-10-22T14:22:23.000Z
2022-03-18T07:55:15.000Z
26.140625
85
0.536163
12,109
/******************************************************************************* * * Copyright FUJITSU LIMITED 2017 * * Creation Date: Jun 14, 2013 * *******************************************************************************/ package org.oscm.internal.types.exception.beans; import org.oscm.internal.types.exception.SessionIndexNotFoundException.ReasonEnum; /** * @author dchojnacki * */ public class SessionIndexNotFoundExceptionBean extends ApplicationExceptionBean { private static final long serialVersionUID = 5936767140334626354L; private ReasonEnum reason; /** * Default constructor. */ public SessionIndexNotFoundExceptionBean() { super(); } /** * Instantiates a <code>SessionNotFoundExceptionBean</code> based on the * specified <code>ApplicationExceptionBean</code> and sets the given * reason. * * @param sup * the <code>ApplicationExceptionBean</code> to use as the base * @param reason * the reason for the exception */ public SessionIndexNotFoundExceptionBean(ApplicationExceptionBean sup, ReasonEnum reason) { super(sup); setReason(reason); } /** * Returns the reason for the exception. * * @return the reason */ public ReasonEnum getReason() { return reason; } /** * Sets the reason for the exception. * * @param reason * the reason */ public void setReason(ReasonEnum reason) { this.reason = reason; } }
3e1c8532cfd2ec9937f9334b3a9c25e136ac539c
3,897
java
Java
net.menthor.editor/src/net/menthor/editor/v2/ui/palette/PaletteColors.java
tgoprince/menthor-editor
1618b272d8976688dff46fc9e9e35eb9371cd0f4
[ "MIT" ]
28
2016-09-26T13:27:57.000Z
2022-01-19T10:01:37.000Z
net.menthor.editor/src/net/menthor/editor/v2/ui/palette/PaletteColors.java
tgoprince/menthor-editor
1618b272d8976688dff46fc9e9e35eb9371cd0f4
[ "MIT" ]
16
2016-09-19T16:43:48.000Z
2021-03-10T20:47:23.000Z
net.menthor.editor/src/net/menthor/editor/v2/ui/palette/PaletteColors.java
tgoprince/menthor-editor
1618b272d8976688dff46fc9e9e35eb9371cd0f4
[ "MIT" ]
6
2016-09-27T20:55:04.000Z
2022-03-20T15:52:22.000Z
57.308824
177
0.744932
12,110
package net.menthor.editor.v2.ui.palette; /** * ============================================================================================ * Menthor Editor -- Copyright (c) 2015 * * This file is part of Menthor Editor. Menthor Editor is based on TinyUML and as so it is * distributed under the same license terms. * * Menthor Editor 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, or (at your option) any later version. * * Menthor Editor 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 Menthor Editor; * if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301 USA * ============================================================================================ */ import java.awt.Color; import javax.swing.BorderFactory; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.LineBorder; import net.menthor.editor.v2.ui.color.ColorMap; import net.menthor.editor.v2.ui.color.ColorType; public class PaletteColors { private static Border resetBorder = BorderFactory.createEmptyBorder(0, 0, 0, 0); private static Color resetBackground = Color.WHITE; private static Color resetForeground = Color.BLACK; private static Border selectedItemBorder = new LineBorder(ColorMap.getInstance().getColor(ColorType.MENTHOR_ORANGE), 1, true); private static Color selectedItemBackground = ColorMap.getInstance().getColor(ColorType.MENTHOR_ORANGE); private static Color selectedItemForeground = Color.WHITE; private static Border hoverItemBorder = new LineBorder(ColorMap.getInstance().getColor(ColorType.MENTHOR_BLUE_DARK), 1, true); private static Color hoverItemBackground = ColorMap.getInstance().getColor(ColorType.MENTHOR_BLUE_LIGHT); private static Border selectedGroupingBorder = UIManager.getBorder("Panel.border"); //new LineBorder(ColorPalette.getInstance().getColor(ThemeColor.MENTHOR_GREY), 1, true); private static Color selectedGroupingBackground = Color.LIGHT_GRAY; //UIManager.getColor("Panel.background");//ColorMap.getInstance().getColor(ColorType.MENTHOR_GREY_MEDIUM); private static Border unselectedGroupingBorder = UIManager.getBorder("Panel.border"); //new LineBorder(ColorPalette.getInstance().getColor(ThemeColor.MENTHOR_GREY), 1, true); private static Color unselectedGroupingBackground = Color.LIGHT_GRAY; //UIManager.getColor("Panel.background"); //ColorPalette.getInstance().getColor(ThemeColor.MENTHOR_GREY); public static Border getResetBorder() { return resetBorder; } public static Color getResetBackground() { return resetBackground; } public static Color getResetForeground() { return resetForeground; } public static Border getSelectedItemBorder() { return selectedItemBorder; } public static Color getSelectedItemBackground() { return selectedItemBackground; } public static Border getHoverItemBorder() { return hoverItemBorder; } public static Color getHoverItemBackground() { return hoverItemBackground; } public static Color getSelectedItemForeground() { return selectedItemForeground; } public static Border getSelectedGroupingBorder() { return selectedGroupingBorder; } public static Color getSelectedGroupingBackground() { return selectedGroupingBackground; } public static Border getUnselectedGroupingBorder() { return unselectedGroupingBorder; } public static Color getUnselectedGroupingBackground() { return unselectedGroupingBackground; } }
3e1c85b35ad039b19cf77b0ab8b705c63e440d16
4,753
java
Java
common-library/src/main/java/com/taxiao/cn/commonlibrary/view/edittext/ClearEditText.java
taxiao213/common_library
d83d60d78d992a5399128de00aa5956ac6cc3b17
[ "Apache-2.0" ]
null
null
null
common-library/src/main/java/com/taxiao/cn/commonlibrary/view/edittext/ClearEditText.java
taxiao213/common_library
d83d60d78d992a5399128de00aa5956ac6cc3b17
[ "Apache-2.0" ]
null
null
null
common-library/src/main/java/com/taxiao/cn/commonlibrary/view/edittext/ClearEditText.java
taxiao213/common_library
d83d60d78d992a5399128de00aa5956ac6cc3b17
[ "Apache-2.0" ]
null
null
null
32.77931
121
0.602356
12,111
package com.taxiao.cn.commonlibrary.view.edittext; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v7.widget.AppCompatEditText; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.taxiao.cn.commonlibrary.R; /** * 带删除功能的 edittext * Created by Han on 2017/4/24. */ public class ClearEditText extends AppCompatEditText implements View.OnFocusChangeListener, TextWatcher { //EditText右侧的删除按钮 private Drawable mClearDrawable; private boolean hasFoucs; private boolean isNeed = true; public ClearEditText(Context context) { this(context, null); } public ClearEditText(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.editTextStyle); } public ClearEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { // 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片,获取图片的顺序是左上右下(0,1,2,3,) mClearDrawable = getCompoundDrawables()[2]; if (mClearDrawable == null) { mClearDrawable = getResources().getDrawable(R.mipmap.library_search_clear); } mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight()); // 默认设置隐藏图标 setClearIconVisible(false); // 设置焦点改变的监听 setOnFocusChangeListener(this); // 设置输入框里面内容发生改变的监听 addTextChangedListener(this); // 监听软键盘的高度来控制光标的显示 // getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { // @Override // public void onGlobalLayout() { // if (isNeed) { // Rect r = new Rect(); // getWindowVisibleDisplayFrame(r); // int screenHeight = getRootView().getHeight(); // int heightDifference = screenHeight - (r.bottom); // if (heightDifference > 200) { // //软键盘显示 // setCursorVisible(true); // } else { // //软键盘隐藏 // setCursorVisible(false); // } // } // } // }); } /* @说明:isInnerWidth, isInnerHeight为ture,触摸点在删除图标之内,则视为点击了删除图标 * event.getX() 获取相对应自身左上角的X坐标 * event.getY() 获取相对应自身左上角的Y坐标 * getWidth() 获取控件的宽度 * getHeight() 获取控件的高度 * getTotalPaddingRight() 获取删除图标左边缘到控件右边缘的距离 * getPaddingRight() 获取删除图标右边缘到控件右边缘的距离 * isInnerWidth: * etWidth() - getTotalPaddingRight() 计算删除图标左边缘到控件左边缘的距离 * getWidth() - getPaddingRight() 计算删除图标右边缘到控件左边缘的距离 * isInnerHeight: * distance 删除图标顶部边缘到控件顶部边缘的距离 * distance + height 删除图标底部边缘到控件顶部边缘的距离 */ @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { if (getCompoundDrawables()[2] != null) { int x = (int) event.getX(); int y = (int) event.getY(); Rect rect = getCompoundDrawables()[2].getBounds(); int height = rect.height(); int distance = (getHeight() - height) / 2; boolean isInnerWidth = x > (getWidth() - getTotalPaddingRight()) && x < (getWidth() - getPaddingRight()); boolean isInnerHeight = y > distance && y < (distance + height); if (isInnerWidth && isInnerHeight) { this.setText(""); } } } return super.onTouchEvent(event); } /** * 当ClearEditText焦点发生变化的时候, * 输入长度为零,隐藏删除图标,否则,显示删除图标 */ @Override public void onFocusChange(View v, boolean hasFocus) { this.hasFoucs = hasFocus; if (hasFocus) { setClearIconVisible(getText().length() > 0); } else { setClearIconVisible(false); } } protected void setClearIconVisible(boolean visible) { Drawable right = visible ? mClearDrawable : null; setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]); } @Override public void onTextChanged(CharSequence s, int start, int count, int after) { if (hasFoucs) { setClearIconVisible(s.length() > 0); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }
3e1c8696427ce4435eec9aaf57ca53faec1110d5
334
java
Java
src/org/ice1000/compare/data/NameCodeDataHolder.java
ice1000/CodeCompare
a5bb99bb71eac7c24e9c39ce716dfd999565821c
[ "Apache-2.0" ]
null
null
null
src/org/ice1000/compare/data/NameCodeDataHolder.java
ice1000/CodeCompare
a5bb99bb71eac7c24e9c39ce716dfd999565821c
[ "Apache-2.0" ]
null
null
null
src/org/ice1000/compare/data/NameCodeDataHolder.java
ice1000/CodeCompare
a5bb99bb71eac7c24e9c39ce716dfd999565821c
[ "Apache-2.0" ]
null
null
null
18.555556
71
0.712575
12,112
package org.ice1000.compare.data; /** * Created by ice1000 on 2016/11/14. * * @author ice1000 */ public class NameCodeDataHolder { public String code, name; public String language; public NameCodeDataHolder(String code, String name, String language) { this.code = code; this.name = name; this.language = language; } }
3e1c86e40ee0f2120aae93a44275e692e6d89321
3,021
java
Java
bloom-filter/src/test/java/io/nixer/bloom/FileBasedBloomFilterTest.java
smifun/nixer-spring-plugin
b323866583bc40f1f75829186df30d24c34d1582
[ "Apache-2.0" ]
null
null
null
bloom-filter/src/test/java/io/nixer/bloom/FileBasedBloomFilterTest.java
smifun/nixer-spring-plugin
b323866583bc40f1f75829186df30d24c34d1582
[ "Apache-2.0" ]
null
null
null
bloom-filter/src/test/java/io/nixer/bloom/FileBasedBloomFilterTest.java
smifun/nixer-spring-plugin
b323866583bc40f1f75829186df30d24c34d1582
[ "Apache-2.0" ]
null
null
null
26.973214
111
0.598808
12,113
package io.nixer.bloom; import java.io.File; import java.io.IOException; import com.google.common.hash.Funnels; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link FileBasedBloomFilter}. * <br> * Created on 24/08/2018. * * @author cezary */ public class FileBasedBloomFilterTest { @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); @Test public void shouldCreate() throws IOException { // given final File file = temporaryFolder.newFile("test.bloom"); delete(file); // when final BloomFilter<Integer> filter = FileBasedBloomFilter.create( file.toPath(), Funnels.integerFunnel(), 100, 0.1 ); // then assertThat(filter).isNotNull(); assertThat(file).exists(); } @Test public void shouldNotFindAnythingBeforeInserting() throws IOException { // given final File file = temporaryFolder.newFile("test.bloom"); delete(file); final BloomFilter<Integer> filter = FileBasedBloomFilter.create( file.toPath(), Funnels.integerFunnel(), 100, 0.1 ); // then final boolean checkOne = filter.mightContain(1); final boolean checkTwo = filter.mightContain(1); // then assertThat(checkOne).isFalse(); assertThat(checkTwo).isFalse(); } @Test public void shouldFindAfterInserting() throws IOException { // given final File file = temporaryFolder.newFile("test.bloom"); delete(file); final BloomFilter<Integer> filter = FileBasedBloomFilter.create( file.toPath(), Funnels.integerFunnel(), 100, 0.1 ); // then final boolean changed = filter.put(1); final boolean found = filter.mightContain(1); // then assertThat(changed).isTrue(); assertThat(found).isTrue(); } @Test public void shouldFindAfterInsertingReopening() throws IOException { // given final File file = temporaryFolder.newFile("test.bloom"); delete(file); final BloomFilter<Integer> filter = FileBasedBloomFilter.create( file.toPath(), Funnels.integerFunnel(), 100, 0.1 ); // then final boolean changed = filter.put(1); final BloomFilter<Integer> filter2 = FileBasedBloomFilter.open(file.toPath(), Funnels.integerFunnel()); final boolean found = filter2.mightContain(1); // then assertThat(changed).isTrue(); assertThat(found).isTrue(); } private static void delete(final File file) throws IOException { if (!file.delete()) { throw new IOException("Failed to delete: " + file); } } }
3e1c88b4eb205630d5feecdf2baaa3de0bb0a854
994
java
Java
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/model/Contacts.java
Gavrilova/java_pft_ftp
7ac30af0821075aed521e6f3e9640435cfa8a826
[ "Apache-2.0" ]
1
2016-06-23T10:15:02.000Z
2016-06-23T10:15:02.000Z
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/model/Contacts.java
Gavrilova/java_pft_ftp
7ac30af0821075aed521e6f3e9640435cfa8a826
[ "Apache-2.0" ]
null
null
null
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/model/Contacts.java
Gavrilova/java_pft_ftp
7ac30af0821075aed521e6f3e9640435cfa8a826
[ "Apache-2.0" ]
null
null
null
21.608696
66
0.720322
12,114
package ru.stqa.pft.addressbook.model; import com.google.common.collect.ForwardingSet; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * Created by irinagavrilova on 5/11/16. */ public class Contacts extends ForwardingSet<ContactData> { private Set<ContactData> delegate; public Contacts(Contacts contacts) { this.delegate = new HashSet<ContactData>(contacts.delegate()); } public Contacts() { this.delegate = new HashSet<ContactData>(); } public Contacts(Collection<ContactData> contacts) { this.delegate = new HashSet<ContactData>(contacts); } @Override protected Set<ContactData> delegate() { return delegate; } public Contacts withAdded(ContactData contact) { Contacts contacts = new Contacts(this); contacts.add(contact); return contacts; } public Contacts without(ContactData contact) { Contacts contacts = new Contacts(this); contacts.remove(contact); return contacts; } }
3e1c89723870e8d25077f6a2656c1c6a442da2d4
2,114
java
Java
protocal/src/main/java/com/thjhsoft/protocal/UserPrivacySafeDialog.java
vv1024/PrivacyProtocol
828f1279953dadcd871bf8996716f437b4d2a142
[ "MIT" ]
17
2019-10-29T14:36:36.000Z
2022-02-17T05:50:56.000Z
protocal/src/main/java/com/thjhsoft/protocal/UserPrivacySafeDialog.java
lgb020/PrivacyProtocol
828f1279953dadcd871bf8996716f437b4d2a142
[ "MIT" ]
null
null
null
protocal/src/main/java/com/thjhsoft/protocal/UserPrivacySafeDialog.java
lgb020/PrivacyProtocol
828f1279953dadcd871bf8996716f437b4d2a142
[ "MIT" ]
5
2019-11-19T01:20:31.000Z
2021-11-12T09:31:43.000Z
30.2
133
0.663671
12,115
package com.thjhsoft.protocal; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import java.util.Objects; /** * 权限申请说明对话框 */ public class UserPrivacySafeDialog extends DialogFragment { private static final String TAG = UserPrivacySafeDialog.class.getSimpleName(); private String content; public static UserPrivacySafeDialog newInstance(String content) { UserPrivacySafeDialog dialog = new UserPrivacySafeDialog(); if(content != null){ Bundle bundle = new Bundle(); bundle.putString("content", content); dialog.setArguments(bundle); } return dialog; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(STYLE_NO_FRAME, R.style.Pro_Round_Dialog); content = getArguments().getString("content", getString(R.string.pro_privacy_safe_tip)); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.dialog_privacy_safe, container); TextView tv = rootView.findViewById(R.id.tv); tv.setText(content); rootView.findViewById(R.id.btn_ok).setOnClickListener(view -> { if(listener!=null){ listener.ok(); Objects.requireNonNull(getDialog()).dismiss(); } }); Objects.requireNonNull(getDialog()).setCanceledOnTouchOutside(false); getDialog().setCancelable(false); return rootView; } private IListener listener; public void setListener(IListener listener){ this.listener = listener; } public interface IListener{ public void ok(); } }
3e1c8a6b331f64ef77329bcd18f4c12b98992076
685
java
Java
strongbox-security/strongbox-authentication-registry/src/main/java/org/carlspring/strongbox/authentication/registry/support/xml/AuthenticatorList.java
vamvindev/strongbox
0006a6872476b92055406de2ce889219dcdb0f91
[ "Apache-2.0" ]
1
2018-10-15T20:49:56.000Z
2018-10-15T20:49:56.000Z
strongbox-security/strongbox-authentication-registry/src/main/java/org/carlspring/strongbox/authentication/registry/support/xml/AuthenticatorList.java
ror6ax/strongbox
2ed4571a508bfbfc75359cda6595a9208a266de0
[ "Apache-2.0" ]
null
null
null
strongbox-security/strongbox-authentication-registry/src/main/java/org/carlspring/strongbox/authentication/registry/support/xml/AuthenticatorList.java
ror6ax/strongbox
2ed4571a508bfbfc75359cda6595a9208a266de0
[ "Apache-2.0" ]
null
null
null
26.346154
72
0.779562
12,116
package org.carlspring.strongbox.authentication.registry.support.xml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; /** * @author Przemyslaw Fusik */ @XmlRootElement(name = "authenticator-list") @XmlAccessorType(XmlAccessType.FIELD) public class AuthenticatorList { @XmlElement(name = "authenticator") private List<AuthenticatorListElement> elements = new ArrayList<>(); public void addElement(AuthenticatorListElement element) { elements.add(element); } }
3e1c8bb3d27fadbaf6701555e13f56605cc71fdd
1,606
java
Java
deep-commons/src/main/java/com/stratio/deep/commons/exception/DeepIOException.java
xsir/stratio-deep
b9621c9b7a6d996f80fce1d073d696a157bed095
[ "Apache-2.0" ]
185
2015-01-05T10:18:38.000Z
2022-01-20T01:52:58.000Z
deep-commons/src/main/java/com/stratio/deep/commons/exception/DeepIOException.java
xsir/stratio-deep
b9621c9b7a6d996f80fce1d073d696a157bed095
[ "Apache-2.0" ]
14
2015-01-30T04:08:48.000Z
2016-01-26T11:27:12.000Z
deep-commons/src/main/java/com/stratio/deep/commons/exception/DeepIOException.java
xsir/stratio-deep
b9621c9b7a6d996f80fce1d073d696a157bed095
[ "Apache-2.0" ]
37
2015-01-19T18:54:25.000Z
2020-04-02T07:35:35.000Z
23.955224
116
0.671651
12,117
/* * Copyright 2014, Stratio. * * 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.stratio.deep.commons.exception; import java.io.IOException; /** * Unchecked variant of {@link IOException}. * * @author Luca Rosellini <hzdkv@example.com> */ public class DeepIOException extends RuntimeException { private static final long serialVersionUID = 6496798210905077525L; /** * Default constructor. */ public DeepIOException() { super(); } /** * Public constructor. */ public DeepIOException(String msg) { super(msg); } /** * Public constructor. */ public DeepIOException(String message, Throwable cause) { super(message, cause); } /** * Public constructor. */ public DeepIOException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } /** * Public constructor. */ public DeepIOException(Throwable cause) { super(cause); } }
3e1c8c835f38c0f0c19104c8c8eab243b187a902
3,414
java
Java
aTalk/src/main/java/org/xmpp/extensions/health/HealthStatusExtension.java
pirujo/atalk-android
94ca72782e9f923209d69ac77235a152aa727bfc
[ "Apache-2.0" ]
120
2018-01-07T12:31:45.000Z
2022-03-30T13:36:58.000Z
aTalk/src/main/java/org/xmpp/extensions/health/HealthStatusExtension.java
pirujo/atalk-android
94ca72782e9f923209d69ac77235a152aa727bfc
[ "Apache-2.0" ]
176
2018-02-10T18:04:04.000Z
2022-03-07T05:02:35.000Z
aTalk/src/main/java/org/xmpp/extensions/health/HealthStatusExtension.java
pirujo/atalk-android
94ca72782e9f923209d69ac77235a152aa727bfc
[ "Apache-2.0" ]
72
2018-01-07T12:23:37.000Z
2022-03-30T04:53:50.000Z
30.756757
98
0.655243
12,118
/* * Copyright @ 2018 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.xmpp.extensions.health; import org.apache.commons.lang3.StringUtils; import org.xmpp.extensions.AbstractExtensionElement; import org.xmpp.extensions.DefaultExtensionElementProvider; import org.jivesoftware.smack.provider.ProviderManager; /** * A generic extension for a component to represent its current health. * NOTE: 'component' here does not refer to XMPP component, but any logical component of a system. * One of: * <li>healthy</li> - the component is healthy and can be considered as usable (other, * component-specific factors should of course also be considered. A component may be * healthy but perhaps busy/unavailable to handle further requests at the moment). * <li>unhealthy</li> - the component is not in a healthy state and should not be considered * usable (despite what any other component-specific statuses may say). * * @author bbaldino * @author Eng Chong Meng */ public class HealthStatusExtension extends AbstractExtensionElement { /** * XML namespace name for health check IQs. */ final static public String NAMESPACE = "http://jitsi.org/protocol/health"; public static final String ELEMENT = "health-status"; private static final String HEALTH_ATTRIBUTE = "status"; public HealthStatusExtension() { super(ELEMENT, NAMESPACE); } static public void registerExtensionProvider() { ProviderManager.addExtensionProvider( ELEMENT, NAMESPACE, new DefaultExtensionElementProvider<>(HealthStatusExtension.class) ); } public Health getStatus() { return Health.parse(getAttributeAsString(HEALTH_ATTRIBUTE)); } public void setStatus(Health health) { setAttribute(HEALTH_ATTRIBUTE, String.valueOf(health)); } public enum Health { HEALTHY("healthy"), UNHEALTHY("unhealthy"), UNDEFINED("undefined"); private String health; Health(String health) { this.health = health; } @Override public String toString() { return health; } /** * Parses <tt>Health</tt> from given string. * * @param health the string representation of <tt>Health</tt>. * @return <tt>Health</tt> value for given string or * {@link #UNDEFINED} if given string does not reflect any of valid values. */ public static Health parse(String health) { if (StringUtils.isEmpty(health)) { return UNDEFINED; } try { return Health.valueOf(health.toUpperCase()); } catch (IllegalArgumentException e) { return UNDEFINED; } } } }
3e1c8d266aa8de48a1372d30231c4d21a7fb5937
632
java
Java
jpa ver00.01/SportShoes-01/src/main/java/org/tain/controller/TbShoesRestController.java
yeswon9874/mybatis
001777449278c7cc1ac5be5a180a532cab954191
[ "Apache-2.0" ]
null
null
null
jpa ver00.01/SportShoes-01/src/main/java/org/tain/controller/TbShoesRestController.java
yeswon9874/mybatis
001777449278c7cc1ac5be5a180a532cab954191
[ "Apache-2.0" ]
null
null
null
jpa ver00.01/SportShoes-01/src/main/java/org/tain/controller/TbShoesRestController.java
yeswon9874/mybatis
001777449278c7cc1ac5be5a180a532cab954191
[ "Apache-2.0" ]
null
null
null
25.28
62
0.813291
12,119
package org.tain.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.tain.jpa.domain.TbShoes; import org.tain.jpa.repository.TbShoesRepository; @RestController @RequestMapping("/shoes") public class TbShoesRestController { @Autowired private TbShoesRepository tbShoesRepository; @GetMapping("/list") public List<TbShoes> list() { return this.tbShoesRepository.findAll(); } }
3e1c9059cf880469afec5d03f9c3cab7069f43db
2,248
java
Java
src/main/java/com/github/iarellano/rest_client/configuration/SSLInfo.java
iarellano/iad-rest-client-maven-plugin
a3994fe405cd9e8af28d1097307b265516bdbe46
[ "MIT" ]
null
null
null
src/main/java/com/github/iarellano/rest_client/configuration/SSLInfo.java
iarellano/iad-rest-client-maven-plugin
a3994fe405cd9e8af28d1097307b265516bdbe46
[ "MIT" ]
null
null
null
src/main/java/com/github/iarellano/rest_client/configuration/SSLInfo.java
iarellano/iad-rest-client-maven-plugin
a3994fe405cd9e8af28d1097307b265516bdbe46
[ "MIT" ]
null
null
null
20.252252
66
0.644128
12,120
package com.github.iarellano.rest_client.configuration; import org.apache.maven.plugins.annotations.Parameter; import java.io.File; public class SSLInfo { @Parameter private String type; @Parameter private File keystore; @Parameter private String keystorePassword; @Parameter private File truststore; @Parameter private String truststorePassword; @Parameter private String clientAlias; @Parameter private String serverAlias; @Parameter private String protocol; public String getType() { return type; } public void setType(String type) { this.type = type; } public File getKeystore() { return keystore; } public void setKeystore(File keystore) { this.keystore = keystore; } public String getKeystorePassword() { return keystorePassword; } public void setKeystorePassword(String keystorePassword) { this.keystorePassword = keystorePassword; } public File getTruststore() { return truststore; } public void setTruststore(File truststore) { this.truststore = truststore; } public String getTruststorePassword() { return truststorePassword; } public void setTruststorePassword(String truststorePassword) { this.truststorePassword = truststorePassword; } public String getClientAlias() { return clientAlias; } public void setClientAlias(String clientAlias) { this.clientAlias = clientAlias; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public String getServerAlias() { return serverAlias; } public void setServerAlias(String serverAlias) { this.serverAlias = serverAlias; } public char[] getKeystorePasswordAsCharArray() { return keystorePassword == null ? null : keystorePassword.toCharArray(); } public char[] getTrustStorePasswordAsCharArray() { return truststorePassword == null ? null : truststorePassword.toCharArray(); } }
3e1c91095fc70ec62de476b797878ad344e2ed63
6,486
java
Java
src/main/java/com/romanysik/util/DistanceFinder.java
Romm17/MRNMF
1fb1773a0a900193649f98efc22a9f323087477d
[ "MIT" ]
4
2017-05-18T11:12:08.000Z
2019-09-29T15:29:36.000Z
src/main/java/com/romanysik/util/DistanceFinder.java
Romm17/MRNMF
1fb1773a0a900193649f98efc22a9f323087477d
[ "MIT" ]
null
null
null
src/main/java/com/romanysik/util/DistanceFinder.java
Romm17/MRNMF
1fb1773a0a900193649f98efc22a9f323087477d
[ "MIT" ]
2
2019-01-23T06:09:57.000Z
2021-05-30T13:10:06.000Z
33.261538
130
0.637373
12,121
package com.romanysik.util; import com.romanysik.MRNMF; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * Calculates Frobenius Norm : F(X, X') = sqrt(sum((X - X') ^ 2)) * for given matrices using 2 MR jobs * * Created by romm on 04.04.17. */ public class DistanceFinder { private static class DFMapper1 extends Mapper<LongWritable, Text, LongWritable, Text> { @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] vals = value.toString().split("\\t", 2); context.write(new LongWritable(Long.parseLong(vals[0])), new Text(vals[1])); } } private static class DFReducer1 extends Reducer<LongWritable, Text, LongWritable, Text> { @Override protected void reduce(LongWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException { int m = context.getConfiguration().getInt("mw", -1); double[] ai = new double[m]; double[] bi = new double[m]; int i = (int)key.get() - 1; for (Text value : values) { if (value.toString().contains("\t")) { String[] keyVal = value.toString().split("\\t"); ai[Integer.parseInt(keyVal[0]) - 1] = Double.parseDouble(keyVal[1]); } else { String[] vals = value.toString().split(","); for (int j = 0; j < m; j++) { bi[j] = Double.parseDouble(vals[j]); } } } double difference = 0d; for (int j = 0; j < m; j++) { difference += Math.pow(ai[j] - bi[j], 2d); } context.write(new LongWritable(i + 1), new Text(difference + "")); } } private static class DFMapper2 extends Mapper<LongWritable, Text, LongWritable, Text> { @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] vals = value.toString().split("\\t", 2); context.write(new LongWritable(1), new Text(vals[1])); } } private static class DFReducer2 extends Reducer<LongWritable, Text, LongWritable, Text> { @Override protected void reduce(LongWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException { double sum = 0d; for (Text value : values) { sum += Double.parseDouble(value.toString()); } double result = Math.sqrt(sum); context.write(new LongWritable(1), new Text(result + "")); } } private Configuration configuration; private String Xpath; private String FGPath; private String outputDir; private String resultFileName; /** * * @param configuration with required params * { * mw: matrix column number * } * @param XPath - should be sparse * @param X1Path - should be dense * @param outputDir - where to file with result * @param resultFileName - name of file with result */ public DistanceFinder(Configuration configuration, String XPath, String X1Path, String outputDir, String resultFileName) { this.configuration = configuration; this.Xpath = XPath; this.FGPath = X1Path; this.outputDir = outputDir; this.resultFileName = resultFileName; } private Double getResult(FileSystem fileSystem, Path file) throws IOException { FSDataInputStream input = fileSystem.open(file); String line = new BufferedReader(new InputStreamReader(input)).readLine(); return Double.parseDouble(line.split("\t")[1]); } /** * * @return result - Frobenius Norm * @throws IOException * @throws ClassNotFoundException * @throws InterruptedException */ public Double run() throws IOException, ClassNotFoundException, InterruptedException { String wd = configuration.get("wd"); Path wdPath = new Path(wd); Job job = Job.getInstance(configuration, "DF1"); Path tmpPath = new Path(configuration.get("wd"), "dftmp"); job.setJarByClass(MRNMF.class); FileInputFormat.addInputPath(job, new Path(Xpath)); MatrixUpdater.addInpuPath(job, new Path(FGPath)); FileOutputFormat.setOutputPath(job, tmpPath); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); job.setMapOutputKeyClass(LongWritable.class); job.setMapOutputValueClass(Text.class); job.setMapperClass(DFMapper1.class); job.setReducerClass(DFReducer1.class); job.waitForCompletion(true); job = Job.getInstance(configuration, "DF2"); job.setJarByClass(MRNMF.class); MatrixUpdater.addInpuPath(job, tmpPath); FileOutputFormat.setOutputPath(job, new Path(wdPath, outputDir)); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); job.setMapOutputKeyClass(LongWritable.class); job.setMapOutputValueClass(Text.class); job.setMapperClass(DFMapper2.class); job.setReducerClass(DFReducer2.class); job.waitForCompletion(true); FileSystem wdfs = wdPath.getFileSystem(new Configuration()); FileUtil.copyMerge(wdfs, new Path(wd, outputDir), wdfs, new Path(wd, resultFileName), false, new Configuration(), ""); return getResult(wdfs, new Path(wd, resultFileName)); } }
3e1c91173265cb332dcbae594a9dd98e4dd7d71c
1,321
java
Java
atlasdb-container-test-utils/src/main/java/com/palantir/atlasdb/containers/CassandraVersion.java
shibsankaras/atlasdb
cd4f33dfcaa95acb90374f698158a4aae8c28945
[ "BSD-3-Clause" ]
null
null
null
atlasdb-container-test-utils/src/main/java/com/palantir/atlasdb/containers/CassandraVersion.java
shibsankaras/atlasdb
cd4f33dfcaa95acb90374f698158a4aae8c28945
[ "BSD-3-Clause" ]
null
null
null
atlasdb-container-test-utils/src/main/java/com/palantir/atlasdb/containers/CassandraVersion.java
shibsankaras/atlasdb
cd4f33dfcaa95acb90374f698158a4aae8c28945
[ "BSD-3-Clause" ]
null
null
null
32.219512
109
0.700227
12,122
/* * Copyright 2016 Palantir Technologies, Inc. All rights reserved. * * Licensed under the BSD-3 License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/BSD-3-Clause * * 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.palantir.atlasdb.containers; import java.util.regex.Pattern; public interface CassandraVersion { static CassandraVersion fromEnvironment() { String version = CassandraEnvironment.getVersion(); return from(version); } static CassandraVersion from(String version) { if (version.startsWith("2.2.")) { return new Cassandra22XVersion(); } else if (version.startsWith("3.")) { return new Cassandra3XVersion(); } else { throw new IllegalArgumentException(String.format("Cassandra version %s not supported", version)); } } Pattern replicationFactorRegex(); String getAllKeyspacesCql(); }
3e1c91471c2b61552e3b634d1cf9a9ab12e00119
5,096
java
Java
tests/test-integration/src/test/java/org/eclipse/jetty/test/AllowedResourceAliasCheckerTest.java
lujiefsi/jetty.project
1984d2de11241508ac1bb622c79b34d1cb7fe824
[ "Apache-2.0" ]
3,353
2015-01-06T13:30:21.000Z
2022-03-31T08:33:56.000Z
tests/test-integration/src/test/java/org/eclipse/jetty/test/AllowedResourceAliasCheckerTest.java
lujiefsi/jetty.project
1984d2de11241508ac1bb622c79b34d1cb7fe824
[ "Apache-2.0" ]
6,018
2015-01-30T17:42:33.000Z
2022-03-31T22:37:40.000Z
tests/test-integration/src/test/java/org/eclipse/jetty/test/AllowedResourceAliasCheckerTest.java
lujiefsi/jetty.project
1984d2de11241508ac1bb622c79b34d1cb7fe824
[ "Apache-2.0" ]
1,997
2015-01-05T03:35:02.000Z
2022-03-29T02:47:56.000Z
33.973333
91
0.671507
12,123
// // ======================================================================== // Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License v. 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 // which is available at https://www.apache.org/licenses/LICENSE-2.0. // // SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 // ======================================================================== // package org.eclipse.jetty.test; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URI; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.AllowedResourceAliasChecker; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.util.IO; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; public class AllowedResourceAliasCheckerTest { private static Server _server; private static ServerConnector _connector; private static HttpClient _client; private static ServletContextHandler _context; private static File _baseDir; private static Path getResourceDir() throws Exception { URL url = AllowedResourceAliasCheckerTest.class.getClassLoader().getResource("."); assertNotNull(url); return new File(url.toURI()).toPath(); } public void start() throws Exception { _server.start(); _client.start(); } @BeforeAll public static void beforeAll() throws Exception { _client = new HttpClient(); _server = new Server(); _connector = new ServerConnector(_server); _server.addConnector(_connector); _context = new ServletContextHandler(); _context.setContextPath("/"); _context.addServlet(DefaultServlet.class, "/"); _server.setHandler(_context); _baseDir = getResourceDir().resolve("baseDir").toFile(); _baseDir.deleteOnExit(); assertFalse(_baseDir.exists()); _context.setResourceBase(_baseDir.getAbsolutePath()); } @AfterAll public static void afterAll() throws Exception { _client.stop(); _server.stop(); } @AfterEach public void afterEach() { IO.delete(_baseDir); } public void createBaseDir() throws IOException { assertFalse(_baseDir.exists()); assertTrue(_baseDir.mkdir()); // Create a file in the baseDir. File file = _baseDir.toPath().resolve("file.txt").toFile(); file.deleteOnExit(); assertTrue(file.createNewFile()); try (FileWriter fileWriter = new FileWriter(file)) { fileWriter.write("this is a file in the baseDir"); } // Create a symlink to that file. // Symlink to a directory inside of the webroot. File symlink = _baseDir.toPath().resolve("symlink").toFile(); symlink.deleteOnExit(); Files.createSymbolicLink(symlink.toPath(), file.toPath()); assertTrue(symlink.exists()); } @Test public void testCreateBaseDirBeforeStart() throws Exception { _context.clearAliasChecks(); _context.addAliasCheck(new AllowedResourceAliasChecker(_context)); createBaseDir(); start(); assertThat(_context.getAliasChecks().size(), equalTo(1)); URI uri = URI.create("http://localhost:" + _connector.getLocalPort() + "/symlink"); ContentResponse response = _client.GET(uri); assertThat(response.getStatus(), is(HttpStatus.OK_200)); assertThat(response.getContentAsString(), is("this is a file in the baseDir")); } @Test public void testCreateBaseDirAfterStart() throws Exception { _context.clearAliasChecks(); _context.addAliasCheck(new AllowedResourceAliasChecker(_context)); start(); createBaseDir(); assertThat(_context.getAliasChecks().size(), equalTo(1)); URI uri = URI.create("http://localhost:" + _connector.getLocalPort() + "/symlink"); ContentResponse response = _client.GET(uri); assertThat(response.getStatus(), is(HttpStatus.OK_200)); assertThat(response.getContentAsString(), is("this is a file in the baseDir")); } }
3e1c91dbcf3e57c831036c2ae57cfa2b54ca322b
88
java
Java
src/main/java/com/education/repository/projection/ScoreSemesterProjection.java
CleristonLincoln/Education-api
e51569d89534122ca52ebbb60624e24310914dcb
[ "Apache-2.0" ]
null
null
null
src/main/java/com/education/repository/projection/ScoreSemesterProjection.java
CleristonLincoln/Education-api
e51569d89534122ca52ebbb60624e24310914dcb
[ "Apache-2.0" ]
null
null
null
src/main/java/com/education/repository/projection/ScoreSemesterProjection.java
CleristonLincoln/Education-api
e51569d89534122ca52ebbb60624e24310914dcb
[ "Apache-2.0" ]
null
null
null
14.666667
44
0.829545
12,124
package com.education.repository.projection; public class ScoreSemesterProjection { }
3e1c920ed331a5c392acd4e6c7fd3d55253e4da8
13,039
java
Java
apptbook/src/Misc./Project2IT.java
psannecy/PortlandStateJavaSummer2019
fbc1b28e342fcddec5629999a7bfafc40485f056
[ "Apache-2.0" ]
null
null
null
apptbook/src/Misc./Project2IT.java
psannecy/PortlandStateJavaSummer2019
fbc1b28e342fcddec5629999a7bfafc40485f056
[ "Apache-2.0" ]
null
null
null
apptbook/src/Misc./Project2IT.java
psannecy/PortlandStateJavaSummer2019
fbc1b28e342fcddec5629999a7bfafc40485f056
[ "Apache-2.0" ]
null
null
null
37.794203
157
0.626505
12,125
package edu.pdx.cs410J.prathik; import edu.pdx.cs410J.InvokeMainTestCase; import org.junit.Test; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import java.nio.file.Files; import java.nio.file.Paths; import java.io.File; import java.util.Scanner; /** * Integration tests for the {@link Project2} main class. */ public class Project2IT extends InvokeMainTestCase { /** * Invokes the main method of {@link Project2} with the given arguments. */ private MainMethodResult invokeMain(String... args) { return invokeMain( Project2.class, args ); } private void DeleteFile(String fileName){ File f = new File(fileName); if(f.isFile()){ f.delete(); } } /** * Tests that invoking the main method with no arguments issues an error */ @Test public void testNoCommandLineArguments() { MainMethodResult result = invokeMain(); assertThat(result.getExitCode(), equalTo(1)); assertThat(result.getTextWrittenToStandardError(), containsString("Missing command line arguments")); } /** * Test that invoking the main method with -README first flag */ @Test public void testREADMEFirstFlag() { MainMethodResult result = invokeMain("-README"); assertThat(result.getExitCode(), equalTo(0)); assertThat(result.getTextWrittenToStandardOut(), containsString("implements an appointment book")); } /** * Test that invoking the main method with -README first flag, dummy data after */ @Test public void testREADMEFirstFlagWithDummyAfter() { MainMethodResult result = invokeMain("-README", "Dummy", "Data"); assertThat(result.getExitCode(), equalTo(0)); assertThat(result.getTextWrittenToStandardOut(), containsString("implements an appointment book")); } /** * Test that invoking the main method with -README second flag */ @Test public void testREADMESecondFlag() { MainMethodResult result = invokeMain("-print", "-README"); assertThat(result.getExitCode(), equalTo(0)); assertThat(result.getTextWrittenToStandardOut(), containsString("implements an appointment book")); } /** * Tests that gives valid command line format gives no error */ @Test public void testInvalidCommandLineArguments() { MainMethodResult result = invokeMain("\"Bob Swan Jr.\"", "\"Eating\"", "7/15/2019", "14:39", "7/16/2019", "14:39"); assertThat(result.getExitCode(), equalTo(0)); } /** * Tests that gives -print statement still gives correct missing argument */ @Test public void testPrintOptionWithMissingArgument() { MainMethodResult result = invokeMain("-print", "\"Bob Swan Jr.\""); assertThat(result.getExitCode(), equalTo(1)); assertThat(result.getTextWrittenToStandardError(), containsString("Missing appointment description")); } /** * Tests that tells the correct missing argument */ @Test public void testMissingArguments() { MainMethodResult result = invokeMain( "\"Bob Swan Jr.\""); assertThat(result.getExitCode(), equalTo(1)); assertThat(result.getTextWrittenToStandardError(), containsString("Missing appointment description")); } /** * Tests for too many argugments */ @Test public void testTooManyArguments() { MainMethodResult result = invokeMain( "\"Bob Swan Jr.\"", "\"Eating\"", "7/15/2019" ,"14:39", "7/16/2019", "14:39", "dummy"); assertThat(result.getExitCode(), equalTo(1)); assertThat(result.getTextWrittenToStandardError(), containsString("Too many arguments")); } /** * Print option provides appointment in correct format */ @Test public void testPrintOption() { MainMethodResult result = invokeMain("-print", "\"Bob Swan Jr.\"", "\"Eating\"", "7/15/2019" ,"14:39", "7/16/2019", "14:39"); assertThat(result.getExitCode(), equalTo(0)); assertThat(result.getTextWrittenToStandardOut(), containsString("Eating from 7/15/2019 14:39 until 7/16/2019 14:39")); } /** * Using the textfile option doesn't break */ @Test public void testTextFileOptionDoesNotBreak() { String fileName = "file"; DeleteFile(fileName); MainMethodResult result = invokeMain("-textFile", fileName, "\"Bob Swan Jr.\"", "\"Eating\"", "7/15/2019" ,"14:39", "7/16/2019", "14:39"); assertThat(result.getExitCode(), equalTo(0)); } /** * Using the textfile option doesn't break with print option */ @Test public void testTextFileOptionDoesNotBreakOtherOptions() { String fileName = "file"; DeleteFile(fileName); MainMethodResult result = invokeMain("-textFile", fileName, "-print", "\"Bob Swan Jr.\"", "\"Eating\"", "7/15/2019" ,"14:39", "7/16/2019", "14:39"); assertThat(result.getExitCode(), equalTo(0)); assertThat(result.getTextWrittenToStandardOut(), containsString("Eating from 7/15/2019 14:39 until 7/16/2019 14:39")); } /** * Using the textfile option doesn't break with print option regardless of order */ @Test public void testTextFileOptionOrderDoesNotMatter() { String fileName = "file"; DeleteFile(fileName); MainMethodResult result = invokeMain("-print", "-textFile", fileName, "\"Bob Swan Jr.\"", "\"Eating\"", "7/15/2019" ,"14:39", "7/16/2019", "14:39"); assertThat(result.getExitCode(), equalTo(0)); assertThat(result.getTextWrittenToStandardOut(), containsString("Eating from 7/15/2019 14:39 until 7/16/2019 14:39")); } /** * README option still works with textfile option */ @Test public void testTextFileOptionDoesNotBreakReadme() { String fileName = "file"; DeleteFile(fileName); MainMethodResult result = invokeMain("-textFile", fileName, "-README", "\"Bob Swan Jr.\"", "\"Eating\"", "7/15/2019" ,"14:39", "7/16/2019", "14:39"); assertThat(result.getExitCode(), equalTo(0)); assertThat(result.getTextWrittenToStandardOut(), containsString("implements an appointment book")); } /** * texfile option creates new textFile */ @Test public void testTextFileOptionCreatesFile() { String fileName = "file"; DeleteFile(fileName); MainMethodResult result = invokeMain("-textFile", fileName, "\"Bob Swan Jr.\"", "\"Eating\"", "7/15/2019" ,"14:39", "7/16/2019", "14:39"); assertThat(result.getExitCode(), equalTo(0)); assertThat(new File(fileName).isFile(), equalTo(true)); // File contains appointment } /** * texfile option adds appointment to new appointment book */ @Test public void testTextFileOptionCreatesNewAppointmentToAppointmentBook() { String fileName = "file"; DeleteFile(fileName); String owner = "Bob"; String description = "eating burger"; String beginTime = "03/17/1996 03:43"; String endTime = "03/17/1997 03:44"; MainMethodResult result = invokeMain("-textFile", fileName, owner, "\"eating burger\"", "03/17/1996" ,"03:43", "03/17/1997", "03:44"); assertThat(result.getExitCode(), equalTo(0)); File file = new File(fileName); try { Scanner scanner = new Scanner(file); scanner.useDelimiter("[\\t\\n]"); String scannerOwner = scanner.next(); String descriptionString = scanner.next(); String beginTimeString = scanner.next(); String endTimeString = scanner.next(); assertThat(owner, equalTo(scannerOwner)); assertThat(description, equalTo(descriptionString)); assertThat(beginTime, equalTo(beginTimeString)); assertThat(endTime, equalTo(endTimeString)); assertThat(scanner.hasNext(), equalTo(false)); scanner.close(); } catch (Exception e){ } } /** * texfile option adds appointment to existing appointment book */ @Test public void testTextFileOptionCreatesAdditionalAppointmentToExistingAppointmentBook() { String fileName = "file"; DeleteFile(fileName); String owner = "Bob"; String description1 = "eating burger"; String beginTime1 = "03/17/1996 03:43"; String endTime1 = "03/17/1997 03:44"; String description2 = "taking nap"; String beginTime2 = "01/6/1946 23:43"; String endTime2 = "05/13/4447 03:48"; MainMethodResult result = invokeMain("-textFile", fileName, owner, "\"eating burger\"", "03/17/1996" ,"03:43", "03/17/1997", "03:44"); assertThat(result.getExitCode(), equalTo(0)); result = invokeMain("-textFile", fileName, owner, "\"taking nap\"", "01/6/1946" ,"23:43", "05/13/4447", "03:48"); assertThat(result.getExitCode(), equalTo(0)); File file = new File(fileName); try { Scanner scanner = new Scanner(file); scanner.useDelimiter("[\\t\\n]"); String scannerOwner = scanner.next(); String descriptionString1 = scanner.next(); String beginTimeString1 = scanner.next(); String endTimeString1 = scanner.next(); String descriptionString2 = scanner.next(); String beginTimeString2 = scanner.next(); String endTimeString2 = scanner.next(); assertThat(owner, equalTo(scannerOwner)); assertThat(description1, equalTo(descriptionString1)); assertThat(beginTime1, equalTo(beginTimeString1)); assertThat(endTime1, equalTo(endTimeString1)); assertThat(description2, equalTo(descriptionString2)); assertThat(beginTime2, equalTo(beginTimeString2)); assertThat(endTime2, equalTo(endTimeString2)); assertThat(scanner.hasNext(), equalTo(false)); scanner.close(); } catch (Exception e){ } } // Owner Mismatch @Test public void testTextFileOptionOwnerMismatchCreatesError() { String fileName = "file"; DeleteFile(fileName); String owner1 = "Bob"; String owner2 = "John"; MainMethodResult result = invokeMain("-textFile", fileName, owner1, "\"eating burger\"", "03/17/1996" ,"03:43", "03/17/1997", "03:44"); assertThat(result.getExitCode(), equalTo(0)); result = invokeMain("-textFile", fileName, owner2, "\"taking nap\"", "01/6/1946" ,"23:43", "05/13/4447", "03:48"); assertThat(result.getExitCode(), equalTo(1)); assertThat(result.getTextWrittenToStandardError(), containsString("Owner mismatch")); } // Different file directories @Test public void testTextFileOptionFileInAnotherFolder() { String fileName1 = "file"; String fileName2 = "../file"; DeleteFile(fileName1); String owner = "Bob"; String description1 = "eating burger"; String beginTime1 = "03/17/1996 03:43"; String endTime1 = "03/17/1997 03:44"; String description2 = "taking nap"; String beginTime2 = "01/6/1946 23:43"; String endTime2 = "05/13/4447 03:48"; MainMethodResult result = invokeMain("-textFile", fileName1, owner, "\"eating burger\"", "03/17/1996" ,"03:43", "03/17/1997", "03:44"); assertThat(result.getExitCode(), equalTo(0)); try { Files.move(Paths.get(fileName1), Paths.get(fileName2)); } catch (Exception e){ } result = invokeMain("-textFile", fileName2, owner, "\"taking nap\"", "01/6/1946" ,"23:43", "05/13/4447", "03:48"); assertThat(result.getExitCode(), equalTo(0)); File file = new File(fileName1); try { Scanner scanner = new Scanner(file); scanner.useDelimiter("[\\t\\n]"); String scannerOwner = scanner.next(); String descriptionString1 = scanner.next(); String beginTimeString1 = scanner.next(); String endTimeString1 = scanner.next(); String descriptionString2 = scanner.next(); String beginTimeString2 = scanner.next(); String endTimeString2 = scanner.next(); assertThat(owner, equalTo(scannerOwner)); assertThat(description1, equalTo(descriptionString1)); assertThat(beginTime1, equalTo(beginTimeString1)); assertThat(endTime1, equalTo(endTimeString1)); assertThat(description2, equalTo(descriptionString2)); assertThat(beginTime2, equalTo(beginTimeString2)); assertThat(endTime2, equalTo(endTimeString2)); assertThat(scanner.hasNext(), equalTo(false)); scanner.close(); } catch (Exception e){ } DeleteFile(fileName2); } }
3e1c94069157cd0c4d30de7ba12a4da1631af293
3,507
java
Java
src/main/java/ca/jonathanfritz/aoc2020/day5/Part2.java
MusikPolice/AdventOfCode2020
a91ad29451ee2b564674adf64e9d8c222fcb0933
[ "Apache-2.0" ]
null
null
null
src/main/java/ca/jonathanfritz/aoc2020/day5/Part2.java
MusikPolice/AdventOfCode2020
a91ad29451ee2b564674adf64e9d8c222fcb0933
[ "Apache-2.0" ]
null
null
null
src/main/java/ca/jonathanfritz/aoc2020/day5/Part2.java
MusikPolice/AdventOfCode2020
a91ad29451ee2b564674adf64e9d8c222fcb0933
[ "Apache-2.0" ]
null
null
null
33.4
117
0.546621
12,126
package ca.jonathanfritz.aoc2020.day5; import ca.jonathanfritz.aoc2020.Utils; import java.util.*; import java.util.stream.Collectors; public class Part2 { private int solve(List<String> input) { final List<Integer> allPossibleSeatIds = new ArrayList<>(); for (int row = 0; row < 128; row++) { for (int col = 0; col < 8; col++) { allPossibleSeatIds.add((row * 8) + col); } } final List<Integer> takenSeatIds = input.stream() .map(boardingPass -> { final String rowPortion = boardingPass.substring(0, 7); final String colPortion = boardingPass.substring(7); final int row = partition(rowPortion, 127); final int col = partition(colPortion, 7); int seatId = (row * 8) + col; System.out.printf("%s: row %d, col %d, seatId %d%n", boardingPass, row, col, seatId); return seatId; }) .collect(Collectors.toList()); allPossibleSeatIds.removeAll(takenSeatIds); // remove consecutive missing seats from the front for (int seatId = 0; seatId < 1024; seatId++) { if (!allPossibleSeatIds.remove(Integer.valueOf(seatId))) { break; } } // remove consecutive missing seats from the back for (int seatId = 1023; seatId >= 0; seatId--) { if (!allPossibleSeatIds.remove(Integer.valueOf(seatId))) { break; } } // only one seat is remaining return allPossibleSeatIds.get(0); } private int partition(String boardingPass, int upperBound) { Range range = new Range(0, upperBound); for (char indicator : boardingPass.toCharArray()) { final Direction d = Direction.fromChar(indicator); range = range.halve(d); } return range.lowerBound; } private enum Direction { upper('B','R'), lower('F','L'); private final Set<Character> indicators = new HashSet<>(); Direction(char ...indicators) { for (char c : indicators) { this.indicators.add(c); } } static Direction fromChar(char indicator) { return Arrays.stream(Direction.values()) .filter(d -> d.indicators.contains(indicator)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Invalid indicator " + indicator + " supplied")); } } private static class Range { private final int lowerBound; private final int upperBound; Range(int lowerBound, int upperBound) { this.lowerBound = lowerBound; this.upperBound = upperBound; } Range halve(Direction d) { final double half = (upperBound - lowerBound) / 2.0; if (d == Direction.upper) { return new Range(lowerBound + (int)Math.ceil(half), upperBound); } else { return new Range(lowerBound, lowerBound + (int)Math.floor(half)); } } } public static void main (String[] args) { final List<String> input = Utils.loadFromFile("day5.txt").collect(Collectors.toList()); final Part2 part2 = new Part2(); System.out.println("Your seatId is: " + part2.solve(input)); } }
3e1c94249fc6edff19231f1d945d068021da5570
166
java
Java
app/src/main/java/cn/finalteam/loadingviewfinal/sample/event/RestartLoadMoreFragmentEvent.java
JerryIreya/LoadingViewFinal
762a931c639a30de3dc5cbfebab449d7ed84207e
[ "Apache-2.0" ]
338
2016-03-18T09:59:22.000Z
2022-03-31T09:50:42.000Z
app/src/main/java/cn/finalteam/loadingviewfinal/sample/event/RestartLoadMoreFragmentEvent.java
JerryIreya/LoadingViewFinal
762a931c639a30de3dc5cbfebab449d7ed84207e
[ "Apache-2.0" ]
19
2016-03-23T02:23:24.000Z
2018-06-07T10:36:48.000Z
app/src/main/java/cn/finalteam/loadingviewfinal/sample/event/RestartLoadMoreFragmentEvent.java
JerryIreya/LoadingViewFinal
762a931c639a30de3dc5cbfebab449d7ed84207e
[ "Apache-2.0" ]
88
2016-03-18T10:06:15.000Z
2021-02-08T02:31:33.000Z
16.6
51
0.740964
12,127
package cn.finalteam.loadingviewfinal.sample.event; /** * Desction: * Author:pengjianbo * Date:16/3/17 上午11:01 */ public class RestartLoadMoreFragmentEvent { }
3e1c94a2044a48c1eadf3ec1c69204aa0248effd
1,710
java
Java
ccri-fhirserver/src/main/java/uk/nhs/careconnect/ccri/fhirserver/stu3/provider/ResourcePermissionProvider.java
nhsconnect/careconnect-reference-implementation
6965c161c8df185b7fa785b4282fdf01166dbaa7
[ "Apache-2.0" ]
24
2017-10-05T15:07:35.000Z
2022-03-15T13:10:00.000Z
ccri-fhirserver/src/main/java/uk/nhs/careconnect/ccri/fhirserver/stu3/provider/ResourcePermissionProvider.java
nhsconnect/careconnect-reference-implementation
6965c161c8df185b7fa785b4282fdf01166dbaa7
[ "Apache-2.0" ]
41
2017-10-11T14:44:12.000Z
2022-02-16T00:55:50.000Z
ccri-fhirserver/src/main/java/uk/nhs/careconnect/ccri/fhirserver/stu3/provider/ResourcePermissionProvider.java
nhsconnect/careconnect-reference-implementation
6965c161c8df185b7fa785b4282fdf01166dbaa7
[ "Apache-2.0" ]
16
2018-02-10T01:37:08.000Z
2022-03-15T04:39:59.000Z
31.666667
93
0.784211
12,128
package uk.nhs.careconnect.ccri.fhirserver.stu3.provider; import ca.uhn.fhir.rest.server.exceptions.NotImplementedOperationException; import org.hl7.fhir.dstu3.model.OperationOutcome; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import uk.nhs.careconnect.ccri.fhirserver.HapiProperties; import uk.nhs.careconnect.ccri.fhirserver.support.OperationOutcomeFactory; @Component public class ResourcePermissionProvider { private static final Logger log = LoggerFactory.getLogger(ResourcePermissionProvider.class); public void checkPermission(String operation) { log.trace("Check "+operation); if(!HapiProperties.getServerCrudRead() && operation.equals("read")) { throw OperationOutcomeFactory.buildOperationOutcomeException( new NotImplementedOperationException("Not implemented GET"), OperationOutcome.IssueType.INVALID); } if(!HapiProperties.getServerCrudUpdate() && operation.equals("update")) { throw OperationOutcomeFactory.buildOperationOutcomeException( new NotImplementedOperationException("Not implemented PUT"), OperationOutcome.IssueType.INVALID); } if(!HapiProperties.getServerCrudDelete() && operation.equals("delete")) { throw OperationOutcomeFactory.buildOperationOutcomeException( new NotImplementedOperationException("Not implemented DEL"), OperationOutcome.IssueType.INVALID); } if(!HapiProperties.getServerCrudCreate() && operation.equals("create")) { throw OperationOutcomeFactory.buildOperationOutcomeException( new NotImplementedOperationException("Not implemented POST"), OperationOutcome.IssueType.INVALID); } } }
3e1c94c4a934e858861a9193c053634496b283f8
1,927
java
Java
nabl2.terms/src/main/java/mb/nabl2/terms/matching/ConsPattern.java
Taeir/nabl
820b2c1086eb301e5775706782db0d506ee62ee8
[ "Apache-2.0" ]
null
null
null
nabl2.terms/src/main/java/mb/nabl2/terms/matching/ConsPattern.java
Taeir/nabl
820b2c1086eb301e5775706782db0d506ee62ee8
[ "Apache-2.0" ]
null
null
null
nabl2.terms/src/main/java/mb/nabl2/terms/matching/ConsPattern.java
Taeir/nabl
820b2c1086eb301e5775706782db0d506ee62ee8
[ "Apache-2.0" ]
null
null
null
30.587302
107
0.633627
12,129
package mb.nabl2.terms.matching; import static mb.nabl2.terms.matching.TermMatch.M; import java.util.Set; import org.metaborg.util.iterators.Iterables2; import com.google.common.collect.ImmutableSet; import mb.nabl2.terms.ITerm; import mb.nabl2.terms.ITermVar; import mb.nabl2.terms.ListTerms; import mb.nabl2.terms.substitution.ISubstitution.Transient; import mb.nabl2.terms.unification.IUnifier; class ConsPattern extends Pattern { private static final long serialVersionUID = 1L; private final Pattern head; private final Pattern tail; public ConsPattern(Pattern head, Pattern tail) { this.head = head; this.tail = tail; } public Pattern getHead() { return head; } public Pattern getTail() { return tail; } @Override public Set<ITermVar> getVars() { ImmutableSet.Builder<ITermVar> vars = ImmutableSet.builder(); vars.addAll(head.getVars()); vars.addAll(tail.getVars()); return vars.build(); } @Override protected MaybeNotInstantiatedBool matchTerm(ITerm term, Transient subst, IUnifier unifier) { // @formatter:off return M.list(listTerm -> { return listTerm.match(ListTerms.<MaybeNotInstantiatedBool>cases() .cons(consTerm -> { return matchTerms(Iterables2.from(head, tail), Iterables2.from(consTerm.getHead(), consTerm.getTail()), subst, unifier); }).var(v -> { return MaybeNotInstantiatedBool.ofNotInstantiated(v); }).otherwise(t -> { return MaybeNotInstantiatedBool.ofResult(false); }) ); }).match(unifier.findTerm(term)).orElse(MaybeNotInstantiatedBool.ofResult(false)); } @Override public String toString() { return "[" + head.toString() + "|" + tail.toString() + "]"; } }
3e1c94d423b397a24145f0e73d62ad5248168a14
1,309
java
Java
study-parent/rw-splitting/src/main/java/org/lxp/rw/service/UserService.java
hivsuper/study
775ac5e639d6f751186a55a01a5e19ed62dc1996
[ "MIT" ]
null
null
null
study-parent/rw-splitting/src/main/java/org/lxp/rw/service/UserService.java
hivsuper/study
775ac5e639d6f751186a55a01a5e19ed62dc1996
[ "MIT" ]
8
2020-11-29T07:41:15.000Z
2022-03-31T18:36:38.000Z
study-parent/rw-splitting/src/main/java/org/lxp/rw/service/UserService.java
hivsuper/study
775ac5e639d6f751186a55a01a5e19ed62dc1996
[ "MIT" ]
null
null
null
28.456522
81
0.673033
12,130
package org.lxp.rw.service; import java.util.Calendar; import javax.annotation.Resource; import org.lxp.rw.mapper.UserMapper; import org.lxp.rw.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service public class UserService { private static final Logger LOG = LoggerFactory.getLogger(UserService.class); @Resource private UserMapper userMapper; public User add(String name) { User user = new User(); user.setName(name); user.setCreateTime(Calendar.getInstance().getTime()); userMapper.insert(user); LOG.info("add user name={} userId={}", name, user.getId()); return user; } public User queryByUserId(int userId) { return userMapper.selectById(userId); } public boolean deleteByUserId(int userId) { LOG.info("delete userId={}", userId); return userMapper.deleteById(userId) > 0; } public User updateNameByUserId(int userId, String name) { User user = queryByUserId(userId); user.setName(name); user.setModifyTime(Calendar.getInstance().getTime()); userMapper.updateById(user); LOG.info("update userId={}'s name to {}", userId, name); return queryByUserId(userId); } }
3e1c95392ca8a1ffe15b5bd4153fc666e6163878
1,153
java
Java
Lab3/IntentsLabSkeleton/app/src/main/java/mobiledev/unb/ca/lab3intents/ExternalActivityCalls.java
RThomasWhittaker/cs2063-winter-2021-labs
b584893b19e15bff8fa51461ec52bbac613a905d
[ "Apache-2.0" ]
2
2021-01-28T04:54:17.000Z
2021-03-25T00:13:02.000Z
Lab3/IntentsLabSkeleton/app/src/main/java/mobiledev/unb/ca/lab3intents/ExternalActivityCalls.java
RThomasWhittaker/cs2063-winter-2021-labs
b584893b19e15bff8fa51461ec52bbac613a905d
[ "Apache-2.0" ]
null
null
null
Lab3/IntentsLabSkeleton/app/src/main/java/mobiledev/unb/ca/lab3intents/ExternalActivityCalls.java
RThomasWhittaker/cs2063-winter-2021-labs
b584893b19e15bff8fa51461ec52bbac613a905d
[ "Apache-2.0" ]
8
2021-01-26T18:49:22.000Z
2021-04-26T01:28:07.000Z
30.342105
80
0.694709
12,131
package mobiledev.unb.ca.lab3intents; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import androidx.appcompat.app.AppCompatActivity; public class ExternalActivityCalls extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.external_activity_calls); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_activity_two, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
3e1c95d699488a2a840afc63b2f1979908fc7ca0
452
java
Java
chapter_004/src/test/java/ru/job4j/stream/TransformTest.java
takmazian/job4j
2aef5d0daf13fb5d3a11ffd0d70bf2256802945d
[ "Apache-2.0" ]
null
null
null
chapter_004/src/test/java/ru/job4j/stream/TransformTest.java
takmazian/job4j
2aef5d0daf13fb5d3a11ffd0d70bf2256802945d
[ "Apache-2.0" ]
null
null
null
chapter_004/src/test/java/ru/job4j/stream/TransformTest.java
takmazian/job4j
2aef5d0daf13fb5d3a11ffd0d70bf2256802945d
[ "Apache-2.0" ]
null
null
null
25.111111
87
0.683628
12,132
package ru.job4j.stream; import org.junit.Test; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class TransformTest { @Test public void transformTest() { Integer[][] arr = new Integer[][]{{1, 2}, {3, 4}}; Transform transform = new Transform(); assertThat(transform.transofrmMatrixToList(arr), equalTo(List.of(1, 2, 3, 4))); } }
3e1c95fa5244b96a3ab989c89cadcb96ae3c8702
8,490
java
Java
sample/src/main/java/com/leinardi/android/speeddial/sample/MainActivity.java
kiewietn/FloatingActionButtonSpeedDial
3d3b12efc965cc8b9e436555677a7c5ef31905af
[ "Apache-2.0" ]
1
2019-09-13T09:57:06.000Z
2019-09-13T09:57:06.000Z
sample/src/main/java/com/leinardi/android/speeddial/sample/MainActivity.java
ahmeddeveloper55/FloatingActionButtonSpeedDial
dc7396d62f134dd4044f1ce0123af4dad0fcb45a
[ "Apache-2.0" ]
null
null
null
sample/src/main/java/com/leinardi/android/speeddial/sample/MainActivity.java
ahmeddeveloper55/FloatingActionButtonSpeedDial
dc7396d62f134dd4044f1ce0123af4dad0fcb45a
[ "Apache-2.0" ]
1
2020-04-13T09:48:47.000Z
2020-04-13T09:48:47.000Z
43.762887
118
0.60318
12,133
/* * Copyright 2018 Roberto Leinardi. * * 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.leinardi.android.speeddial.sample; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import androidx.appcompat.content.res.AppCompatResources; import androidx.core.content.res.ResourcesCompat; import com.leinardi.android.speeddial.FabWithLabelView; import com.leinardi.android.speeddial.SpeedDialActionItem; import com.leinardi.android.speeddial.SpeedDialView; import com.leinardi.android.speeddial.sample.usecases.BaseUseCaseActivity; import com.leinardi.android.speeddial.sample.usecases.UseCasesActivity; /** * Sample project */ @SuppressWarnings("PMD") // sample project with long methods public class MainActivity extends BaseUseCaseActivity { private static final String TAG = MainActivity.class.getSimpleName(); private static final int ADD_ACTION_POSITION = 4; private SpeedDialView mSpeedDialView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initSpeedDial(savedInstanceState == null); } private void initSpeedDial(boolean addActionItems) { mSpeedDialView = findViewById(R.id.speedDial); if (addActionItems) { mSpeedDialView.addActionItem(new SpeedDialActionItem.Builder(R.id.fab_no_label, R.drawable .ic_link_white_24dp) .create()); Drawable drawable = AppCompatResources.getDrawable(MainActivity.this, R.drawable.ic_custom_color); FabWithLabelView fabWithLabelView = mSpeedDialView.addActionItem(new SpeedDialActionItem.Builder(R.id .fab_custom_color, drawable) .setFabImageTintColor(ResourcesCompat.getColor(getResources(), R.color.inbox_primary, getTheme())) .setLabel(R.string.label_custom_color) .setLabelColor(Color.WHITE) .setLabelBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.inbox_primary, getTheme())) .create()); if (fabWithLabelView != null) { fabWithLabelView.setSpeedDialActionItem(fabWithLabelView.getSpeedDialActionItemBuilder() .setFabBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.material_white_1000, getTheme())) .create()); } mSpeedDialView.addActionItem(new SpeedDialActionItem.Builder(R.id.fab_long_label, R.drawable .ic_lorem_ipsum) .setLabel("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " + "incididunt ut labore et dolore magna aliqua.") .create()); drawable = AppCompatResources.getDrawable(MainActivity.this, R.drawable.ic_add_white_24dp); mSpeedDialView.addActionItem(new SpeedDialActionItem.Builder(R.id.fab_add_action, drawable) .setFabBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.material_green_500, getTheme())) .setLabel(R.string.label_add_action) .setLabelBackgroundColor(Color.TRANSPARENT) .create()); mSpeedDialView.addActionItem(new SpeedDialActionItem.Builder(R.id.fab_custom_theme, R.drawable .ic_theme_white_24dp) .setLabel(getString(R.string.label_custom_theme)) .setTheme(R.style.AppTheme_Purple) .create()); } //Set main action clicklistener. mSpeedDialView.setOnChangeListener(new SpeedDialView.OnChangeListener() { @Override public boolean onMainActionSelected() { showToast("Main action clicked!"); return false; // True to keep the Speed Dial open } @Override public void onToggleChanged(boolean isOpen) { Log.d(TAG, "Speed dial toggle state changed. Open = " + isOpen); } }); //Set option fabs clicklisteners. mSpeedDialView.setOnActionSelectedListener(new SpeedDialView.OnActionSelectedListener() { @Override public boolean onActionSelected(SpeedDialActionItem actionItem) { switch (actionItem.getId()) { case R.id.fab_no_label: showToast("No label action clicked!\nClosing with animation"); mSpeedDialView.close(); // To close the Speed Dial with animation return true; // false will close it without animation case R.id.fab_long_label: showSnackbar(actionItem.getLabel(MainActivity.this) + " clicked!"); break; case R.id.fab_custom_color: showToast(actionItem.getLabel(MainActivity.this) + " clicked!\nClosing without animation."); return false; // closes without animation (same as mSpeedDialView.close(false); return false;) case R.id.fab_custom_theme: showToast(actionItem.getLabel(MainActivity.this) + " clicked!"); break; case R.id.fab_add_action: mSpeedDialView.addActionItem(new SpeedDialActionItem.Builder(R.id.fab_replace_action, R.drawable.ic_replace_white_24dp) .setFabBackgroundColor(ResourcesCompat.getColor(getResources(), R.color .material_orange_500, getTheme())) .setLabel(getString(R.string.label_replace_action)) .create(), ADD_ACTION_POSITION); break; case R.id.fab_replace_action: mSpeedDialView.replaceActionItem(new SpeedDialActionItem.Builder(R.id .fab_remove_action, R.drawable.ic_delete_white_24dp) .setLabel(getString(R.string.label_remove_action)) .setFabBackgroundColor(ResourcesCompat.getColor(getResources(), R.color.inbox_accent, getTheme())) .create(), ADD_ACTION_POSITION); break; case R.id.fab_remove_action: mSpeedDialView.removeActionItemById(R.id.fab_remove_action); break; default: break; } return true; // To keep the Speed Dial open } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public void onBackPressed() { //Closes menu if its opened. if (mSpeedDialView.isOpen()) { mSpeedDialView.close(); } else { super.onBackPressed(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_use_cases) { startActivity(new Intent(MainActivity.this, UseCasesActivity.class)); return true; } return super.onOptionsItemSelected(item); } @Override protected int getLayoutRes() { return R.layout.activity_main; } }
3e1c9601bc85e31d7c836f625438608bfe65792b
4,311
java
Java
modules/math/src/test/java/com/opengamma/strata/math/impl/linearalgebra/QRDecompositionCommonsResultTest.java
LALAYANG/Strata
7a3f9613913b383446d862c4606b5fbf59aaa213
[ "Apache-2.0" ]
696
2015-07-15T12:09:50.000Z
2022-03-27T15:05:05.000Z
modules/math/src/test/java/com/opengamma/strata/math/impl/linearalgebra/QRDecompositionCommonsResultTest.java
LALAYANG/Strata
7a3f9613913b383446d862c4606b5fbf59aaa213
[ "Apache-2.0" ]
562
2015-07-17T11:31:08.000Z
2022-03-29T16:15:39.000Z
modules/math/src/test/java/com/opengamma/strata/math/impl/linearalgebra/QRDecompositionCommonsResultTest.java
LALAYANG/Strata
7a3f9613913b383446d862c4606b5fbf59aaa213
[ "Apache-2.0" ]
315
2015-07-18T20:53:45.000Z
2022-03-06T02:04:13.000Z
46.354839
125
0.736024
12,134
/* * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.math.impl.linearalgebra; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.QRDecomposition; import org.apache.commons.math3.linear.RealMatrix; import org.junit.jupiter.api.Test; import com.opengamma.strata.collect.array.DoubleArray; import com.opengamma.strata.collect.array.DoubleMatrix; import com.opengamma.strata.math.impl.FuzzyEquals; /** * Tests the QR decomposition result */ public class QRDecompositionCommonsResultTest { private static final double[][] RAW_AOK = new double[][] { {100.0000000000000000, 9.0000000000000000, 10.0000000000000000, 1.0000000000000000}, {9.0000000000000000, 50.0000000000000000, 19.0000000000000000, 15.0000000000000000}, {10.0000000000000000, 11.0000000000000000, 29.0000000000000000, 21.0000000000000000}, {8.0000000000000000, 10.0000000000000000, 20.0000000000000000, 28.0000000000000000}}; private static final double[] RAW_RHS_VECT = new double[] {1, 2, 3, 4}; private static final double[][] RAW_RHS_MAT = new double[][] {{1, 2}, {3, 4}, {5, 6}, {7, 8}}; private static final RealMatrix CONDOK = new Array2DRowRealMatrix(RAW_AOK); private static final QRDecomposition QR = new QRDecomposition(CONDOK); private static final QRDecompositionCommonsResult RESULT = new QRDecompositionCommonsResult(QR); @Test public void testThrowOnNull() { assertThatIllegalArgumentException() .isThrownBy(() -> new QRDecompositionCommonsResult(null)); } @Test public void testGetQ() { double[][] expectedRaw = new double[][] { {-0.9879705944808324, 0.1189683945357854, 0.0984381737009301, 0.0083994941034602}, {-0.0889173535032749, -0.9595057553635415, 0.2632608647546777, 0.0462182513606091}, {-0.0987970594480833, -0.1873133740004731, -0.8116464267094188, 0.5444106161481449}, {-0.0790376475584666, -0.1735192394127411, -0.5120876107238650, -0.8375024792591188}}; assertThat(FuzzyEquals.ArrayFuzzyEquals(RESULT.getQ().toArray(), expectedRaw)).isTrue(); } @Test public void testGetR() { double[][] expectedRaw = new double[][] { {-101.2175874045612574, -15.2147471550048152, -16.0150033365342956, -6.6095232770767698}, {0.0000000000000000, -50.7002117254876197, -25.9433980408179785, -23.0657374934840220}, {0.0000000000000000, 0.0000000000000000, -27.7931604217022681, -27.3356769161449193}, {0.0000000000000000, 0.0000000000000000, 0.0000000000000000, -11.3157732156316868}}; assertThat(FuzzyEquals.ArrayFuzzyEquals(RESULT.getR().toArray(), expectedRaw)).isTrue(); } @Test public void testGetQT() { double[][] expectedRaw = new double[][] { {-0.9879705944808324, -0.0889173535032749, -0.0987970594480833, -0.0790376475584666}, {0.1189683945357854, -0.9595057553635415, -0.1873133740004731, -0.1735192394127411}, {0.0984381737009301, 0.2632608647546777, -0.8116464267094188, -0.5120876107238650}, {0.0083994941034602, 0.0462182513606091, 0.5444106161481449, -0.8375024792591188}}; assertThat(FuzzyEquals.ArrayFuzzyEquals(RESULT.getQT().toArray(), expectedRaw)).isTrue(); } @Test public void testSolveForVector() { double[] expectedRaw = new double[] {0.0090821107573878, -0.0038563963265099, -0.0016307897061976, 0.1428043882617839}; assertThat(FuzzyEquals.ArrayFuzzyEquals(RESULT.solve(RAW_RHS_VECT), expectedRaw)).isTrue(); assertThat(FuzzyEquals.ArrayFuzzyEquals(RESULT.solve(DoubleArray.copyOf(RAW_RHS_VECT)).toArray(), expectedRaw)).isTrue(); } @Test public void testSolveForMatrix() { double[][] expectedRaw = new double[][] { {0.0103938059732010, 0.0181642215147756}, {-0.0147149030138629, -0.0077127926530197}, {-0.0171480759531631, -0.0032615794123952}, {0.2645342893362958, 0.2856087765235678}}; assertThat(FuzzyEquals.ArrayFuzzyEquals(RESULT.solve(DoubleMatrix.copyOf(RAW_RHS_MAT)).toArray(), expectedRaw)).isTrue(); } }
3e1c99a601066de68106d6189af4a085b6c167c7
2,106
java
Java
component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentsExtension.java
fviolette/component-runtime
3d9af38a2ea81e9ce7ace4406fb34ffde9e99817
[ "Apache-2.0" ]
null
null
null
component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentsExtension.java
fviolette/component-runtime
3d9af38a2ea81e9ce7ace4406fb34ffde9e99817
[ "Apache-2.0" ]
null
null
null
component-runtime-testing/component-runtime-junit/src/main/java/org/talend/sdk/component/junit5/environment/EnvironmentsExtension.java
fviolette/component-runtime
3d9af38a2ea81e9ce7ace4406fb34ffde9e99817
[ "Apache-2.0" ]
null
null
null
45.782609
120
0.760209
12,135
/** * Copyright (C) 2006-2018 Talend Inc. - www.talend.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.talend.sdk.component.junit5.environment; import static org.junit.platform.commons.util.AnnotationUtils.findAnnotation; import static org.junit.platform.commons.util.AnnotationUtils.isAnnotated; import java.util.stream.Stream; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.TestTemplateInvocationContext; import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider; import org.talend.sdk.component.junit.environment.DecoratingEnvironmentProvider; import org.talend.sdk.component.junit.environment.EnvironmentsConfigurationParser; class EnvironmentsExtension implements TestTemplateInvocationContextProvider { @Override public boolean supportsTestTemplate(final ExtensionContext context) { return isAnnotated(context.getTestMethod(), EnvironmentalTest.class); } @Override public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(final ExtensionContext context) { final String format = findAnnotation(context.getRequiredTestMethod(), EnvironmentalTest.class).get().format(); return new EnvironmentsConfigurationParser(context.getRequiredTestClass()) .stream() .map(e -> new EnvironmentalContext(e, format.replace("${displayName}", context.getDisplayName()).replace("${environment}", DecoratingEnvironmentProvider.class.cast(e).getName()))); } }
3e1c9a38f4a260955f4ac73b871cea0d031d0e2b
4,573
java
Java
core/src/test/java/io/doov/core/dsl/meta/ast/ToStringOrTest.java
raghav-deepsource/doov
8098c82ddff3e4354a7cb17d6d012ac9c45cdff2
[ "Apache-2.0" ]
55
2018-08-19T14:25:48.000Z
2020-07-16T05:47:11.000Z
core/src/test/java/io/doov/core/dsl/meta/ast/ToStringOrTest.java
raghav-deepsource/doov
8098c82ddff3e4354a7cb17d6d012ac9c45cdff2
[ "Apache-2.0" ]
39
2018-08-28T13:26:30.000Z
2020-06-30T08:35:10.000Z
core/src/test/java/io/doov/core/dsl/meta/ast/ToStringOrTest.java
raghav-deepsource/doov
8098c82ddff3e4354a7cb17d6d012ac9c45cdff2
[ "Apache-2.0" ]
8
2018-09-05T09:00:36.000Z
2020-03-30T14:02:21.000Z
33.137681
123
0.630877
12,136
/* * Copyright 2018 Courtanet * * 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 io.doov.core.dsl.meta.ast; import static io.doov.core.dsl.DOOV.alwaysFalse; import static io.doov.core.dsl.DOOV.alwaysTrue; import static io.doov.core.dsl.DOOV.when; import static org.assertj.core.api.Assertions.assertThat; import java.time.LocalDate; import java.util.Locale; import org.junit.jupiter.api.*; import io.doov.core.dsl.field.types.*; import io.doov.core.dsl.lang.StepCondition; import io.doov.core.dsl.lang.ValidationRule; import io.doov.core.dsl.runtime.GenericModel; import io.doov.core.dsl.time.LocalDateSuppliers; public class ToStringOrTest { private static final Locale LOCALE = Locale.US; GenericModel model = new GenericModel(); private StepCondition A, B, C, D; private ValidationRule rule; private IntegerFieldInfo zero; private LocalDateFieldInfo yesterday; private StringFieldInfo bob; private BooleanFieldInfo is_true; @BeforeEach void beforeEach() { zero = model.intField(0, "zero"); yesterday = model.localDateField(LocalDate.now().minusDays(1), "yesterday"); bob = model.stringField("Bob", "name"); is_true = model.booleanField(false, "is True"); } @Test void or_true_false_complex() { A = alwaysTrue("A"); B = alwaysFalse("B"); C = alwaysTrue("C"); rule = when(A.or(B.or(C))).validate(); assertThat(rule.readable(LOCALE)) .isEqualTo("rule when (always true A or (always false B or always true C)) validate"); } @Test void or_false_true_complex() { A = alwaysFalse("A"); B = alwaysTrue("B"); C = alwaysTrue("C"); rule = when(A.or(B.and(C))).validate(); assertThat(rule.readable(LOCALE)) .isEqualTo("rule when (always false A or (always true B and always true C)) validate"); } @Test void or_false_false() { A = alwaysFalse("A"); B = alwaysFalse("B"); rule = when(A.or(B)).validate(); assertThat(rule.readable(LOCALE)).isEqualTo("rule when (always false A or always false B) validate"); } @Test void or_false_false_complex() { A = alwaysFalse("A"); B = alwaysFalse("B"); C = alwaysTrue("C"); rule = when(A.or(B.and(C))).validate(); assertThat(rule.readable(LOCALE)) .isEqualTo("rule when (always false A or (always false B and always true C)) validate"); } @Test void or_true_false() { A = alwaysTrue("A"); B = alwaysFalse("B"); rule = when(A.or(B)).validate(); assertThat(rule.readable(LOCALE)).isEqualTo("rule when (always true A or always false B) validate"); } @Test void or_false_true() { A = alwaysFalse("A"); B = alwaysTrue("B"); rule = when(A.or(B)).validate(); assertThat(rule.readable(LOCALE)).isEqualTo("rule when (always false A or always true B) validate"); } @Test void or_true_true() { A = alwaysTrue("A"); B = alwaysTrue("B"); rule = when(A.or(B)).validate(); assertThat(rule.readable(LOCALE)).isEqualTo("rule when (always true A or always true B) validate"); } @Test void or_or_or() { A = zero.lesserThan(4); B = yesterday.before(LocalDateSuppliers.today()); C = bob.startsWith("B"); D = is_true.isFalse(); rule = when(A.or(B).or(C).or(D)).validate(); assertThat(rule.readable(LOCALE)).isEqualTo( "rule when (((zero < 4 or yesterday before today) or name starts with 'B') or is True is false) validate"); } @Test void or_field_true_true() { A = zero.lesserThan(4); B = yesterday.before(LocalDateSuppliers.today()); rule = when(A.or(B)).validate(); assertThat(rule.readable(LOCALE)).isEqualTo("rule when (zero < 4 or yesterday before today) validate"); } @AfterEach void afterEach() { System.out.println(rule); } }
3e1c9b63b2668f21e48a99ec01dbb60231ecdfa9
7,400
java
Java
old-external/odftoolkit/odfdom/src/main/java/org/odftoolkit/odfdom/dom/element/presentation/PresentationPlaceholderElement.java
veriktig/scandium
17b22f29d70b1a972271071f62017880e8e0b5c7
[ "Apache-2.0" ]
39
2015-01-01T12:36:45.000Z
2021-11-10T16:10:26.000Z
old-external/odftoolkit/odfdom/src/main/java/org/odftoolkit/odfdom/dom/element/presentation/PresentationPlaceholderElement.java
veriktig/scandium
17b22f29d70b1a972271071f62017880e8e0b5c7
[ "Apache-2.0" ]
1
2021-11-04T12:36:56.000Z
2021-11-04T12:36:56.000Z
old-external/odftoolkit/odfdom/src/main/java/org/odftoolkit/odfdom/dom/element/presentation/PresentationPlaceholderElement.java
veriktig/scandium
17b22f29d70b1a972271071f62017880e8e0b5c7
[ "Apache-2.0" ]
42
2015-03-14T18:48:33.000Z
2021-11-10T16:10:19.000Z
35.613527
145
0.726262
12,137
/************************************************************************ * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved. * * Use is subject to license terms. * * 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. You can also * obtain a copy of the License at http://odftoolkit.org/docs/license.txt * * 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. * ************************************************************************/ /* * This file is automatically generated. * Don't edit manually. */ package org.odftoolkit.odfdom.dom.element.presentation; import org.odftoolkit.odfdom.pkg.OdfElement; import org.odftoolkit.odfdom.pkg.ElementVisitor; import org.odftoolkit.odfdom.pkg.OdfFileDom; import org.odftoolkit.odfdom.pkg.OdfName; import org.odftoolkit.odfdom.dom.OdfDocumentNamespace; import org.odftoolkit.odfdom.dom.DefaultElementVisitor; import org.odftoolkit.odfdom.dom.attribute.presentation.PresentationObjectAttribute; import org.odftoolkit.odfdom.dom.attribute.svg.SvgHeightAttribute; import org.odftoolkit.odfdom.dom.attribute.svg.SvgWidthAttribute; import org.odftoolkit.odfdom.dom.attribute.svg.SvgXAttribute; import org.odftoolkit.odfdom.dom.attribute.svg.SvgYAttribute; /** * DOM implementation of OpenDocument element hzdkv@example.com presentation:placeholder}. * */ public class PresentationPlaceholderElement extends OdfElement { public static final OdfName ELEMENT_NAME = OdfName.newName(OdfDocumentNamespace.PRESENTATION, "placeholder"); /** * Create the instance of <code>PresentationPlaceholderElement</code> * * @param ownerDoc The type is <code>OdfFileDom</code> */ public PresentationPlaceholderElement(OdfFileDom ownerDoc) { super(ownerDoc, ELEMENT_NAME); } /** * Get the element name * * @return return <code>OdfName</code> the name of element hzdkv@example.com presentation:placeholder}. */ public OdfName getOdfName() { return ELEMENT_NAME; } /** * Receives the value of the ODFDOM attribute representation <code>PresentationObjectAttribute</code> , See efpyi@example.com presentation:object} * * Attribute is mandatory. * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getPresentationObjectAttribute() { PresentationObjectAttribute attr = (PresentationObjectAttribute) getOdfAttribute(OdfDocumentNamespace.PRESENTATION, "object"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>PresentationObjectAttribute</code> , See efpyi@example.com presentation:object} * * @param presentationObjectValue The type is <code>String</code> */ public void setPresentationObjectAttribute(String presentationObjectValue) { PresentationObjectAttribute attr = new PresentationObjectAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(presentationObjectValue); } /** * Receives the value of the ODFDOM attribute representation <code>SvgHeightAttribute</code> , See efpyi@example.com svg:height} * * Attribute is mandatory. * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getSvgHeightAttribute() { SvgHeightAttribute attr = (SvgHeightAttribute) getOdfAttribute(OdfDocumentNamespace.SVG, "height"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>SvgHeightAttribute</code> , See efpyi@example.com svg:height} * * @param svgHeightValue The type is <code>String</code> */ public void setSvgHeightAttribute(String svgHeightValue) { SvgHeightAttribute attr = new SvgHeightAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(svgHeightValue); } /** * Receives the value of the ODFDOM attribute representation <code>SvgWidthAttribute</code> , See efpyi@example.com svg:width} * * Attribute is mandatory. * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getSvgWidthAttribute() { SvgWidthAttribute attr = (SvgWidthAttribute) getOdfAttribute(OdfDocumentNamespace.SVG, "width"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>SvgWidthAttribute</code> , See efpyi@example.com svg:width} * * @param svgWidthValue The type is <code>String</code> */ public void setSvgWidthAttribute(String svgWidthValue) { SvgWidthAttribute attr = new SvgWidthAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(svgWidthValue); } /** * Receives the value of the ODFDOM attribute representation <code>SvgXAttribute</code> , See efpyi@example.com svg:x} * * Attribute is mandatory. * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getSvgXAttribute() { SvgXAttribute attr = (SvgXAttribute) getOdfAttribute(OdfDocumentNamespace.SVG, "x"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>SvgXAttribute</code> , See efpyi@example.com svg:x} * * @param svgXValue The type is <code>String</code> */ public void setSvgXAttribute(String svgXValue) { SvgXAttribute attr = new SvgXAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(svgXValue); } /** * Receives the value of the ODFDOM attribute representation <code>SvgYAttribute</code> , See efpyi@example.com svg:y} * * Attribute is mandatory. * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getSvgYAttribute() { SvgYAttribute attr = (SvgYAttribute) getOdfAttribute(OdfDocumentNamespace.SVG, "y"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>SvgYAttribute</code> , See efpyi@example.com svg:y} * * @param svgYValue The type is <code>String</code> */ public void setSvgYAttribute(String svgYValue) { SvgYAttribute attr = new SvgYAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(svgYValue); } @Override public void accept(ElementVisitor visitor) { if (visitor instanceof DefaultElementVisitor) { DefaultElementVisitor defaultVisitor = (DefaultElementVisitor) visitor; defaultVisitor.visit(this); } else { visitor.visit(this); } } }
3e1c9c975a31ea5166ea97590a17d8c240948bc1
1,621
java
Java
src/main/java8/net/finmath/time/daycount/DayCountConvention_ACT_360.java
xiayingfeng/finmath-lib
49b71c512775b786f54d33dc828c2e0d1e701883
[ "Apache-2.0" ]
373
2015-01-01T11:27:51.000Z
2022-03-29T21:51:49.000Z
src/main/java8/net/finmath/time/daycount/DayCountConvention_ACT_360.java
xiayingfeng/finmath-lib
49b71c512775b786f54d33dc828c2e0d1e701883
[ "Apache-2.0" ]
67
2015-01-21T08:52:23.000Z
2021-09-22T20:13:11.000Z
src/main/java8/net/finmath/time/daycount/DayCountConvention_ACT_360.java
xiayingfeng/finmath-lib
49b71c512775b786f54d33dc828c2e0d1e701883
[ "Apache-2.0" ]
184
2015-01-05T17:30:18.000Z
2022-03-28T10:55:29.000Z
28.068966
209
0.743243
12,138
/* * (c) Copyright Christian P. Fries, Germany. Contact: anpch@example.com. * * Created on 07.09.2013 */ package net.finmath.time.daycount; import java.io.Serializable; import java.time.LocalDate; /** * Implementation of ACT/360. * * Calculates the day count by calculating the actual number of days between startDate and endDate. * * A fractional day is rounded to the approximately nearest day. * * The day count fraction is calculated using ACT/360 convention, that is, the * day count divided by 360. * * This day count convention is sometime called <i>Money Market basis</i>. * * <ul> * <li> * The method {@link #getDaycountFraction(LocalDate, LocalDate) getDaycountFraction} corresponds to the implementation of the "ACT/360 method" of Excel function YEARFRAC, i.e., YEARFRAC(startDate,endDate,2). * </li> * </ul> * * @author Christian Fries * @version 1.0 */ public class DayCountConvention_ACT_360 extends DayCountConvention_ACT implements DayCountConvention, Serializable { private static final long serialVersionUID = -2141383519298897543L; /** * Create an ACT/360 day count convention. */ public DayCountConvention_ACT_360() { } /* (non-Javadoc) * @see net.finmath.time.daycount.DayCountConvention#getDaycountFraction(java.time.LocalDate, java.time.LocalDate) */ @Override public double getDaycountFraction(final LocalDate startDate, final LocalDate endDate) { if(startDate.isAfter(endDate)) { return -getDaycountFraction(endDate,startDate); } final double daycountFraction = getDaycount(startDate, endDate) / 360.0; return daycountFraction; } }
3e1c9cae396ce017a495cf3e90a098d28fa53669
962
java
Java
codingmore-mbg/src/main/java/com/codingmore/util/DateUtil.java
itwanger/coding-more
783e12c5414588f14d96c005515a451239d2aad3
[ "Apache-2.0" ]
17
2022-01-12T08:14:38.000Z
2022-03-28T17:36:19.000Z
codingmore-mbg/src/main/java/com/codingmore/util/DateUtil.java
itwanger/coding-more
783e12c5414588f14d96c005515a451239d2aad3
[ "Apache-2.0" ]
null
null
null
codingmore-mbg/src/main/java/com/codingmore/util/DateUtil.java
itwanger/coding-more
783e12c5414588f14d96c005515a451239d2aad3
[ "Apache-2.0" ]
10
2022-02-08T15:47:23.000Z
2022-03-24T00:57:34.000Z
27.485714
72
0.504158
12,139
package com.codingmore.util; import cn.hutool.core.date.DateTime; import java.util.Date; /** * 微信搜索「沉默王二」,回复 Java * * @author 沉默王二 * @date 4/28/22 */ public class DateUtil { public static String getShortTime(Date time) { String shortString = ""; long now = DateTime.now().getTime(); long delTime = (now - time.getTime()) / 1000; if (delTime > 365 * 24 * 60 * 60) { shortString = (int) (delTime / (365 * 24 * 60 * 60)) + "年前"; } else if (delTime > 24 * 60 * 60) { shortString = (int) (delTime / (24 * 60 * 60)) + "天前"; } else if (delTime > 60 * 60) { shortString = (int) (delTime / (60 * 60)) + "小时前"; } else if (delTime > 60) { shortString = (int) (delTime / (60)) + "分前"; } else if (delTime > 1) { shortString = delTime + "秒前"; } else { shortString = "1秒前"; } return shortString; } }
3e1c9d2cb456b94f945faafa12f0ec4095607335
3,325
java
Java
guns-film/src/main/java/com/stylefeng/guns/rest/persistence/model/MtimeFilmInfoT.java
wangdiskater/project3_9527
7a7777008738526a52028408a4352c2386d54d9f
[ "Apache-2.0" ]
3
2019-10-12T11:26:31.000Z
2019-10-12T12:04:20.000Z
guns-film/src/main/java/com/stylefeng/guns/rest/persistence/model/MtimeFilmInfoT.java
wangdiskater/project3_9527
7a7777008738526a52028408a4352c2386d54d9f
[ "Apache-2.0" ]
null
null
null
guns-film/src/main/java/com/stylefeng/guns/rest/persistence/model/MtimeFilmInfoT.java
wangdiskater/project3_9527
7a7777008738526a52028408a4352c2386d54d9f
[ "Apache-2.0" ]
1
2019-10-12T15:52:58.000Z
2019-10-12T15:52:58.000Z
20.652174
59
0.602707
12,140
package com.stylefeng.guns.rest.persistence.model; import com.baomidou.mybatisplus.enums.IdType; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.activerecord.Model; import com.baomidou.mybatisplus.annotations.TableName; import java.io.Serializable; /** * <p> * 影片主表 * </p> * * @author So9rry * @since 2019-10-14 */ @TableName("mtime_film_info_t") public class MtimeFilmInfoT extends Model<MtimeFilmInfoT> { private static final long serialVersionUID = 1L; /** * 主键编号 */ @TableId(value = "UUID", type = IdType.AUTO) private Integer uuid; /** * 影片编号 */ @TableField("film_id") private String filmId; /** * 影片英文名称 */ @TableField("film_en_name") private String filmEnName; /** * 影片评分 */ @TableField("film_score") private String filmScore; /** * 评分人数,以万为单位 */ @TableField("film_score_num") private Integer filmScoreNum; /** * 播放时长,以分钟为单位,不足取整 */ @TableField("film_length") private Integer filmLength; /** * 影片介绍 */ private String biography; /** * 导演编号 */ @TableField("director_id") private Integer directorId; /** * 影片图片集地址,多个图片以逗号分隔 */ @TableField("film_imgs") private String filmImgs; public Integer getUuid() { return uuid; } public void setUuid(Integer uuid) { this.uuid = uuid; } public String getFilmId() { return filmId; } public void setFilmId(String filmId) { this.filmId = filmId; } public String getFilmEnName() { return filmEnName; } public void setFilmEnName(String filmEnName) { this.filmEnName = filmEnName; } public String getFilmScore() { return filmScore; } public void setFilmScore(String filmScore) { this.filmScore = filmScore; } public Integer getFilmScoreNum() { return filmScoreNum; } public void setFilmScoreNum(Integer filmScoreNum) { this.filmScoreNum = filmScoreNum; } public Integer getFilmLength() { return filmLength; } public void setFilmLength(Integer filmLength) { this.filmLength = filmLength; } public String getBiography() { return biography; } public void setBiography(String biography) { this.biography = biography; } public Integer getDirectorId() { return directorId; } public void setDirectorId(Integer directorId) { this.directorId = directorId; } public String getFilmImgs() { return filmImgs; } public void setFilmImgs(String filmImgs) { this.filmImgs = filmImgs; } @Override protected Serializable pkVal() { return this.uuid; } @Override public String toString() { return "MtimeFilmInfoT{" + "uuid=" + uuid + ", filmId=" + filmId + ", filmEnName=" + filmEnName + ", filmScore=" + filmScore + ", filmScoreNum=" + filmScoreNum + ", filmLength=" + filmLength + ", biography=" + biography + ", directorId=" + directorId + ", filmImgs=" + filmImgs + "}"; } }
3e1c9d79ba174d695be19654674f3ffe6675ff60
2,691
java
Java
sources/p320f/p321a/p327d/p332e/p334b/C13518f.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
1
2019-10-01T11:34:10.000Z
2019-10-01T11:34:10.000Z
sources/p320f/p321a/p327d/p332e/p334b/C13518f.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
null
null
null
sources/p320f/p321a/p327d/p332e/p334b/C13518f.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
1
2020-05-26T05:10:33.000Z
2020-05-26T05:10:33.000Z
28.326316
80
0.520996
12,141
package p320f.p321a.p327d.p332e.p334b; import p024io.reactivex.exceptions.C13980a; import p320f.p321a.C13802r; import p320f.p321a.C13804t; import p320f.p321a.p325b.C13194b; import p320f.p321a.p326c.C13214p; import p320f.p321a.p327d.p328a.C13218c; import p320f.p321a.p343g.C13774a; /* renamed from: f.a.d.e.b.f */ /* compiled from: ObservableAll */ public final class C13518f<T> extends C13485a<T, Boolean> { /* renamed from: b */ final C13214p<? super T> f41115b; /* renamed from: f.a.d.e.b.f$a */ /* compiled from: ObservableAll */ static final class C13519a<T> implements C13804t<T>, C13194b { /* renamed from: a */ final C13804t<? super Boolean> f41116a; /* renamed from: b */ final C13214p<? super T> f41117b; /* renamed from: c */ C13194b f41118c; /* renamed from: d */ boolean f41119d; C13519a(C13804t<? super Boolean> actual, C13214p<? super T> predicate) { this.f41116a = actual; this.f41117b = predicate; } public void onSubscribe(C13194b s) { if (C13218c.m43149a(this.f41118c, s)) { this.f41118c = s; this.f41116a.onSubscribe(this); } } public void onNext(T t) { if (!this.f41119d) { try { if (!this.f41117b.test(t)) { this.f41119d = true; this.f41118c.dispose(); this.f41116a.onNext(Boolean.valueOf(false)); this.f41116a.onComplete(); } } catch (Throwable e) { C13980a.m44462b(e); this.f41118c.dispose(); onError(e); } } } public void onError(Throwable t) { if (this.f41119d) { C13774a.m43836b(t); return; } this.f41119d = true; this.f41116a.onError(t); } public void onComplete() { if (!this.f41119d) { this.f41119d = true; this.f41116a.onNext(Boolean.valueOf(true)); this.f41116a.onComplete(); } } public void dispose() { this.f41118c.dispose(); } } public C13518f(C13802r<T> source, C13214p<? super T> predicate) { super(source); this.f41115b = predicate; } /* access modifiers changed from: protected */ public void subscribeActual(C13804t<? super Boolean> t) { this.f41005a.subscribe(new C13519a(t, this.f41115b)); } }
3e1c9de04259ac152013a8624821ad8c39f46ec6
1,053
java
Java
appservice/resource-manager/v2016_08_01/src/main/java/com/microsoft/azure/management/appservice/v2016_08_01/Snapshot.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
3
2021-09-15T16:25:19.000Z
2021-12-17T05:41:00.000Z
appservice/resource-manager/v2016_08_01/src/main/java/com/microsoft/azure/management/appservice/v2016_08_01/Snapshot.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
306
2019-09-27T06:41:56.000Z
2019-10-14T08:19:57.000Z
appservice/resource-manager/v2016_08_01/src/main/java/com/microsoft/azure/management/appservice/v2016_08_01/Snapshot.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
1
2019-10-05T04:59:12.000Z
2019-10-05T04:59:12.000Z
22.891304
94
0.681861
12,142
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.appservice.v2016_08_01; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.management.appservice.v2016_08_01.implementation.SnapshotInner; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.appservice.v2016_08_01.implementation.AppServiceManager; /** * Type representing Snapshot. */ public interface Snapshot extends HasInner<SnapshotInner>, HasManager<AppServiceManager> { /** * @return the id value. */ String id(); /** * @return the kind value. */ String kind(); /** * @return the name value. */ String name(); /** * @return the time value. */ String time(); /** * @return the type value. */ String type(); }
3e1c9e2d39daed94983156f49e0bcfe419e66e3a
1,194
java
Java
src/main/java/com/bitmovin/api/sdk/model/NexGuardABWatermarkingFeature.java
mcherif/bitmovinexp
d4d746794f26c8e9692c834e63d5d19503693bbf
[ "MIT" ]
7
2019-10-03T05:24:47.000Z
2022-03-04T14:46:15.000Z
src/main/java/com/bitmovin/api/sdk/model/NexGuardABWatermarkingFeature.java
mcherif/bitmovinexp
d4d746794f26c8e9692c834e63d5d19503693bbf
[ "MIT" ]
3
2020-04-15T15:35:45.000Z
2020-11-09T18:53:38.000Z
src/main/java/com/bitmovin/api/sdk/model/NexGuardABWatermarkingFeature.java
mcherif/bitmovinexp
d4d746794f26c8e9692c834e63d5d19503693bbf
[ "MIT" ]
2
2020-04-21T13:48:56.000Z
2022-02-14T00:58:09.000Z
22.961538
84
0.734506
12,143
package com.bitmovin.api.sdk.model; import java.util.Objects; import java.util.Arrays; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum NexGuardABWatermarkingFeature { /** * For video streams with NexGuard FileMarker OTT Watermarking */ OTT("OTT"), /** * For audio streams that have been duplicated for NexGuard A/B Watermarking */ DUPLICATED("DUPLICATED"); private String value; NexGuardABWatermarkingFeature(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static NexGuardABWatermarkingFeature fromValue(String text) { for (NexGuardABWatermarkingFeature b : NexGuardABWatermarkingFeature.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } }
3e1ca03da99593a75a68949a6e6dd8141bd610b7
1,051
java
Java
src/main/java/com/tesco/crypt/kmip/ttlv/model/enums/enumerations/QueryFunction.java
Tesco/kmip-binary-protocol
37a8790a3e1664390548c5a90796dde8a3ad12ee
[ "Apache-2.0" ]
1
2021-04-13T09:58:00.000Z
2021-04-13T09:58:00.000Z
src/main/java/com/tesco/crypt/kmip/ttlv/model/enums/enumerations/QueryFunction.java
Tesco/kmip-binary-protocol
37a8790a3e1664390548c5a90796dde8a3ad12ee
[ "Apache-2.0" ]
null
null
null
src/main/java/com/tesco/crypt/kmip/ttlv/model/enums/enumerations/QueryFunction.java
Tesco/kmip-binary-protocol
37a8790a3e1664390548c5a90796dde8a3ad12ee
[ "Apache-2.0" ]
null
null
null
25.02381
70
0.632731
12,144
package com.tesco.crypt.kmip.ttlv.model.enums.enumerations; import com.tesco.crypt.kmip.ttlv.model.enums.ByteEnum; import java.math.BigInteger; public enum QueryFunction implements ByteEnum<QueryFunction> { QUERY_OPERATIONS("1"), QUERY_OBJECTS("2"), QUERY_SERVER_INFORMATION("3"), QUERY_APPLICATION_NAMESPACES("4"), QUERY_EXTENSION_LIST("5"), QUERY_EXTENSION_MAP("6"), EXTENSIONS("8XXXXXXX"); private final BigInteger start; private final BigInteger end; QueryFunction(String hexValue) { if (hexValue.contains("X")) { start = new BigInteger(hexValue.replaceAll("X", "0"), 16); end = new BigInteger(hexValue.replaceAll("X", "F"), 16); } else { start = new BigInteger(hexValue, 16); end = start; } } @Override public Class<QueryFunction> getType() { return this.getDeclaringClass(); } public BigInteger getStart() { return start; } public BigInteger getEnd() { return end; } }
3e1ca0cabe8aa57365842e7eda618841b5b1280c
1,448
java
Java
driver/src/test/java/org/apache/tinkerpop/gremlin/orientdb/GremlinScriptFromOrientDBTest.java
karkusviktor/orientdb-gremlin
c0658c3fc4c11c715afee09a765b17598b88cebc
[ "Apache-2.0" ]
null
null
null
driver/src/test/java/org/apache/tinkerpop/gremlin/orientdb/GremlinScriptFromOrientDBTest.java
karkusviktor/orientdb-gremlin
c0658c3fc4c11c715afee09a765b17598b88cebc
[ "Apache-2.0" ]
null
null
null
driver/src/test/java/org/apache/tinkerpop/gremlin/orientdb/GremlinScriptFromOrientDBTest.java
karkusviktor/orientdb-gremlin
c0658c3fc4c11c715afee09a765b17598b88cebc
[ "Apache-2.0" ]
null
null
null
35.317073
82
0.741713
12,145
package org.apache.tinkerpop.gremlin.orientdb; import com.orientechnologies.orient.core.db.ODatabaseSession; import com.orientechnologies.orient.core.db.ODatabaseType; import com.orientechnologies.orient.core.db.OrientDB; import com.orientechnologies.orient.core.db.OrientDBConfig; import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.orientechnologies.orient.core.sql.executor.OResultSet; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; public class GremlinScriptFromOrientDBTest { @Test public void scriptMapParametersTest() { OrientDB orientDB = new OrientDB("embedded:", OrientDBConfig.defaultConfig()); orientDB.create("test", ODatabaseType.MEMORY); ODatabaseSession session = orientDB.open("test", "admin", "admin"); session.save(session.newVertex("v")); OResultSet res = session.execute("gremlin", "g.V()", new HashMap<>()); Assert.assertTrue(res.hasNext()); session.close(); orientDB.close(); } @Test public void scriptArrayParametersTest() { OrientDB orientDB = new OrientDB("embedded:", OrientDBConfig.defaultConfig()); orientDB.create("test", ODatabaseType.MEMORY); ODatabaseSession session = orientDB.open("test", "admin", "admin"); session.save(session.newVertex("v")); OResultSet res = session.execute("gremlin", "g.V()"); Assert.assertTrue(res.hasNext()); session.close(); orientDB.close(); } }
3e1ca10352ff324f59f44ac02531a4974e3aa7d7
586
java
Java
java-basic/projekty/ex4_polymorphism/src/com/company/Cube.java
sGrys/it-academy
df3d3de06d70c71f406e543923e6f490fc5526ab
[ "MIT" ]
1
2019-03-07T08:52:53.000Z
2019-03-07T08:52:53.000Z
java-basic/projekty/ex4_polymorphism/src/com/company/Cube.java
sGrys/it-academy
df3d3de06d70c71f406e543923e6f490fc5526ab
[ "MIT" ]
3
2022-01-21T23:25:18.000Z
2022-02-16T00:57:16.000Z
java-basic/projekty/ex4_polymorphism/src/com/company/Cube.java
sGrys/it-academy
df3d3de06d70c71f406e543923e6f490fc5526ab
[ "MIT" ]
1
2019-03-26T11:16:35.000Z
2019-03-26T11:16:35.000Z
18.3125
54
0.546075
12,146
package com.company; public class Cube implements Item { double side; double density; Cube(double side, double density) { this.side = side; this.density = density; } @Override public double getWeight() { return getVolume() * density; } @Override public double getVolume() { return side * side * side; } @Override public boolean equals(Object obj) { Cube c = (Cube)obj; if(c == null) { return false; } return c.side == side && c.density == density; } }
3e1ca19a4cec5c5abda03737069883f6091fd381
160
java
Java
app/src/main/java/com/gradle/ide/build/exception/LauncherException.java
asm-blahblah/GradleIDE2
1c6ad4b94edc06e441f18380c34520d5275e507f
[ "Apache-2.0" ]
12
2021-12-01T13:48:23.000Z
2021-12-18T17:48:07.000Z
app/src/main/java/com/gradle/ide/build/exception/LauncherException.java
asm-blahblah/GradleIDE2
1c6ad4b94edc06e441f18380c34520d5275e507f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/gradle/ide/build/exception/LauncherException.java
asm-blahblah/GradleIDE2
1c6ad4b94edc06e441f18380c34520d5275e507f
[ "Apache-2.0" ]
3
2022-01-10T04:14:22.000Z
2022-02-13T11:12:15.000Z
17.777778
50
0.78125
12,147
package com.gradle.ide.build.exception; public class LauncherException extends Exception { public LauncherException(String message) { super(message); } }