blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
a3e01fd4684c1da947ebd2c6543012f963d05d04
7f39ed9e0d20cf9c111040ba39b3d946ee8b6911
/src/test/java/nl/surfnet/bod/search/VirtualPortIndexAndSearchTest.java
1bf7d166da35f7795077f714d865d2025551a617
[]
no_license
rlnbpr/bandwidth-on-demand-os
3bb6784078c6c0d6836fbe0a7b823a278392550f
9ebe8e6edc7e3b667de3fe895fc09df4c419edf9
refs/heads/master
2021-01-18T20:57:18.504104
2013-03-26T15:50:12
2013-03-26T15:50:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,102
java
/** * Copyright (c) 2012, SURFnet BV * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the SURFnet BV nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package nl.surfnet.bod.search; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import java.util.List; import nl.surfnet.bod.domain.*; import nl.surfnet.bod.support.*; import org.apache.lucene.queryParser.ParseException; import org.junit.Before; import org.junit.Test; public class VirtualPortIndexAndSearchTest extends AbstractIndexAndSearch<VirtualPort> { public VirtualPortIndexAndSearchTest() { super(VirtualPort.class); } @Before public void insertTestData() { Institute institute = new InstituteFactory().create(); PhysicalResourceGroup prg = new PhysicalResourceGroupFactory().setInstitute(institute).withNoIds().create(); PhysicalPort pp = new PhysicalPortFactory().setPhysicalResourceGroup(prg).withNoIds().create(); VirtualResourceGroup vrg = new VirtualResourceGroupFactory().setName("unit-test-vrg").withNoIds().create(); VirtualPort virtualPort = new VirtualPortFactory().setUserLabel("unit-test-label").setVirtualResourceGroup(vrg).setPhysicalPort(pp).withNodIds().create(); persist(institute, prg, pp, vrg, virtualPort); } @Test public void searchVirtualPortByName() throws ParseException { List<VirtualPort> result = searchFor("userLabel:\"unit-test-label\""); assertThat(result, hasSize(1)); } @Test public void searchVirtualPortByNameOfVirtualResourceGroup() throws ParseException { List<VirtualPort> result = searchFor("virtualResourceGroup.name:\"unit-test-vrg\""); assertThat(result, hasSize(1)); } }
ed9790362131647cc5b1bfe9928b43d22a31611b
58e100e3b16479b4f0c45750945a03274f4ea114
/formation-programmation-java/projets/java/Chifoumi/src/chifoumi/JeuUnTour.java
7779313af5606d147f3430e72122ccb4bb8c459d
[]
no_license
ltearno/formations
73bc5180610c345bc8170d1d15a96f33e684a1ab
7e13403928b8538a371b3cdfb0bacd2f830ef849
refs/heads/master
2023-06-29T00:14:27.801517
2022-06-06T06:32:08
2022-06-06T06:32:08
110,226,568
2
4
null
2023-06-14T20:19:05
2017-11-10T09:08:37
JavaScript
UTF-8
Java
false
false
1,629
java
package chifoumi; public class JeuUnTour { private Joueur joueur1; private Joueur joueur2; public JeuUnTour( String nomJoueur1, String nomJoueur2 ) { joueur1 = new Joueur( nomJoueur1 ); joueur2 = new Joueur( nomJoueur2 ); } public void jouer() { tour(); joueur1.ecrireScore(); joueur2.ecrireScore(); conclure(); } @SuppressWarnings( "incomplete-switch" ) private void tour() { Choix choixJoueur1 = joueur1.choisir(); Choix choixJoueur2 = joueur2.choisir(); Joueur joueurGagnant = null; switch( choixJoueur1 ) { case CAILLOU: switch( choixJoueur2 ) { case CISEAUX: joueurGagnant = joueur2; break; case PAPIER: joueurGagnant = joueur2; break; } break; case CISEAUX: switch( choixJoueur2 ) { case CAILLOU: joueurGagnant = joueur2; break; case PAPIER: joueurGagnant = joueur1; break; } break; case PAPIER: switch( choixJoueur2 ) { case CAILLOU: joueurGagnant = joueur1; break; case CISEAUX: joueurGagnant = joueur2; break; } break; } if( joueurGagnant != null ) joueurGagnant.crediter(); } private void conclure() { int scoreJoueur1 = joueur1.getScore(); int scoreJoueur2 = joueur2.getScore(); if( scoreJoueur1 == scoreJoueur2 ) { System.out.println( "Les deux joueurs font égalité" ); } else if( scoreJoueur1 > scoreJoueur2 ) { System.out.println( "Le joueur " + joueur1.getNom() + " a gagné !" ); } else { System.out.println( "Le joueur " + joueur2.getNom() + " a gagné !" ); } } }
aee489070a981726e7e7fd60796305c368d1c981
2037d79b28ed4a028cb8ac0e36252919b513a61d
/HBase/hbase2/src/main/java/com/zxw/hbase2/filter/ColumnValueComparators.java
0d638024d7c6c1c9090228ff88fc1698133ee4cb
[]
no_license
CoptimT/NoSQL
f65ae0cece1ef1aa46bc3532017efabdd1ec6e00
dcfd3f9d75762e159935db49636bc71f26a55f59
refs/heads/master
2021-06-04T00:50:15.492878
2019-01-28T12:53:55
2019-01-28T12:53:55
58,100,006
1
1
null
null
null
null
UTF-8
Java
false
false
1,734
java
package com.zxw.hbase2.filter; import java.io.IOException; import org.apache.hadoop.hbase.CompareOperator; import org.apache.hadoop.hbase.filter.BinaryComparator; import org.apache.hadoop.hbase.filter.BinaryPrefixComparator; import org.apache.hadoop.hbase.filter.ByteArrayComparable; import org.apache.hadoop.hbase.filter.RegexStringComparator; import org.apache.hadoop.hbase.filter.SingleColumnValueFilter; import org.apache.hadoop.hbase.filter.SubstringComparator; import org.apache.hadoop.hbase.util.Bytes; import com.zxw.hbase2.PrepareData; public class ColumnValueComparators { public static void main(String[] args) { try { RegexStringComparator regexStringComparator = new RegexStringComparator("value0.");// any value that starts with 'my' testColumnValueComparators("key2",regexStringComparator); SubstringComparator substringComparator = new SubstringComparator("value3");// looking for 'my value' testColumnValueComparators("key2",substringComparator); BinaryPrefixComparator binaryPrefixComparator = new BinaryPrefixComparator(Bytes.toBytes("value3")); testColumnValueComparators("key2",binaryPrefixComparator); BinaryComparator binaryComparator=new BinaryComparator(Bytes.toBytes("value3")); testColumnValueComparators("key2",binaryComparator); } catch (IOException e) { e.printStackTrace(); } } public static void testColumnValueComparators(String columnQualifier,ByteArrayComparable comp) throws IOException { byte[] cf = Bytes.toBytes(PrepareData.CF_DEFAULT); byte[] column = Bytes.toBytes(columnQualifier); SingleColumnValueFilter filter = new SingleColumnValueFilter(cf,column,CompareOperator.EQUAL,comp); PrepareData.scanWithFilter(filter); } }
[ "Author Email" ]
Author Email
690f98f11b2e699ff1e2ca883b3bd3676d26e6aa
c95c03f659007f347cc02e293faeb339eff85a59
/Coverage/commons-functor-FUNCTOR_1_0_RC1/src/main/java/org/apache/commons/functor/BinaryPredicate.java
8262431dd16245006def99194497a1e04dd7b797
[ "Apache-2.0" ]
permissive
dormaayan/TestsReposirotry
e2bf6c247d933b278fcc47082afa7282dd916baa
75520c8fbbbd5f721f4c216ae7f142ec861e2c67
refs/heads/master
2020-04-11T21:34:56.287920
2019-02-06T13:34:31
2019-02-06T13:34:31
162,110,352
0
2
null
null
null
null
UTF-8
Java
false
false
1,568
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.functor; /** * A functor that takes two arguments and returns a <code>boolean</code> value. * <p> * Implementors are encouraged but not required to make their functors * {@link java.io.Serializable Serializable}. * </p> * * @param <L> the left argument type. * @param <R> the right argument type. * @since 1.0 * @version $Revision$ $Date$ * @author Rodney Waldhoff */ public interface BinaryPredicate<L, R> extends BinaryFunctor<L, R> { /** * Evaluate this predicate. * * @param left the L element of the ordered pair of arguments * @param right the R element of the ordered pair of arguments * @return the result of this test for the given arguments */ boolean test(L left, R right); }
ad31ee540e7feecdee874901b25c477cb39d5641
7ee0bf9a6fe59e08c54b1b9b3582c3198e62a77f
/DesafioConcreteSolutions/app/src/main/java/br/com/desafio/ui/adapter/bind/PullRequestItemView.java
20db94dea75ec3ee0481da7f0a7e7277c7eb025e
[]
no_license
tiagocasemiro/desafio-android
658599668428b5713997340acfef1cec6d78b6d9
ebf2cb82c11fcc129b957ac1d7bbe8c527f3d60a
refs/heads/master
2020-06-01T01:43:33.846273
2019-06-06T13:15:18
2019-06-06T13:15:18
190,582,468
0
0
null
2019-06-06T13:03:11
2019-06-06T13:03:10
null
UTF-8
Java
false
false
1,737
java
package br.com.desafio.ui.adapter.bind; import android.content.Context; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.picasso.Picasso; import org.androidannotations.annotations.EViewGroup; import org.androidannotations.annotations.ViewById; import br.com.desafio.R; import br.com.desafio.domain.PullRequest; import jp.wasabeef.picasso.transformations.CropCircleTransformation; @EViewGroup(R.layout.pull_request_item) public class PullRequestItemView extends LinearLayout { private Context context; @ViewById TextView title; @ViewById TextView description; @ViewById TextView fullName; @ViewById TextView userName; @ViewById ImageView photo; public PullRequestItemView(Context context) { super(context); this.context = context; } public void bind(PullRequest pullRequest) { setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); title.setText(pullRequest.getTitle()); description.setText(pullRequest.getBody()); if(pullRequest != null && pullRequest.getHead() != null && pullRequest.getHead().getRepo() != null) fullName.setText(pullRequest.getHead().getRepo().getFullName()); userName.setText(pullRequest.getUser().getName()); if(pullRequest.getUser() != null && pullRequest.getUser().getPhoto() != null) Picasso.with(context).load(pullRequest.getUser().getPhoto()).transform(new CropCircleTransformation()).placeholder(R.drawable.user).into(photo); else Picasso.with(context).load(R.drawable.user).transform(new CropCircleTransformation()).into(photo); } }
55bfeae0f2ff2f4849a8b1e48da571cde36c59bf
7e1af1ecbaeb6126e685a9910707bf7127431ee2
/ovr/src/generated/java/org/lwjgl/ovr/OVRPoseStatef.java
893b91e89c307ac81ccc7563021d2868cc12bf09
[]
no_license
LWJGL/lwjgl3-generated
8172eb75f4e727289af76c503d29ef0e8627fc9f
3358e2faea6a26e1b11e22e9147590cfb4e291c1
refs/heads/master
2023-08-20T06:02:52.111217
2018-04-21T15:48:09
2018-04-21T15:48:09
8,824,326
14
9
null
2014-07-10T22:02:40
2013-03-16T19:35:27
Java
UTF-8
Java
false
false
14,133
java
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.ovr; import javax.annotation.*; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.MemoryStack.*; /** * A full pose (rigid body) configuration with first and second derivatives. * * <p>Body refers to any object for which ovrPoseStatef is providing data. It can be the HMD, Touch controller, sensor or something else. The context * depends on the usage of the struct.</p> * * <h3>Member documentation</h3> * * <ul> * <li>{@code ThePose} &ndash; position and orientation</li> * <li>{@code AngularVelocity} &ndash; angular velocity in radians per second</li> * <li>{@code LinearVelocity} &ndash; velocity in meters per second</li> * <li>{@code AngularAcceleration} &ndash; angular acceleration in radians per second per second</li> * <li>{@code LinearAcceleration} &ndash; acceleration in meters per second per second</li> * <li>{@code TimeInSeconds} &ndash; absolute time that this pose refers to. See {@link OVR#ovr_GetTimeInSeconds GetTimeInSeconds}</li> * </ul> * * <h3>Layout</h3> * * <code><pre> * struct ovrPoseStatef { * {@link OVRPosef ovrPosef} ThePose; * {@link OVRVector3f ovrVector3f} AngularVelocity; * {@link OVRVector3f ovrVector3f} LinearVelocity; * {@link OVRVector3f ovrVector3f} AngularAcceleration; * {@link OVRVector3f ovrVector3f} LinearAcceleration; * char[4]; * double TimeInSeconds; * }</pre></code> */ @NativeType("struct ovrPoseStatef") public class OVRPoseStatef extends Struct implements NativeResource { /** The struct size in bytes. */ public static final int SIZEOF; public static final int ALIGNOF; /** The struct member offsets. */ public static final int THEPOSE, ANGULARVELOCITY, LINEARVELOCITY, ANGULARACCELERATION, LINEARACCELERATION, TIMEINSECONDS; static { Layout layout = __struct( __member(OVRPosef.SIZEOF, OVRPosef.ALIGNOF), __member(OVRVector3f.SIZEOF, OVRVector3f.ALIGNOF), __member(OVRVector3f.SIZEOF, OVRVector3f.ALIGNOF), __member(OVRVector3f.SIZEOF, OVRVector3f.ALIGNOF), __member(OVRVector3f.SIZEOF, OVRVector3f.ALIGNOF), __padding(4, true), __member(8) ); SIZEOF = layout.getSize(); ALIGNOF = layout.getAlignment(); THEPOSE = layout.offsetof(0); ANGULARVELOCITY = layout.offsetof(1); LINEARVELOCITY = layout.offsetof(2); ANGULARACCELERATION = layout.offsetof(3); LINEARACCELERATION = layout.offsetof(4); TIMEINSECONDS = layout.offsetof(6); } OVRPoseStatef(long address, @Nullable ByteBuffer container) { super(address, container); } /** * Creates a {@link OVRPoseStatef} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be * visible to the struct instance and vice versa. * * <p>The created instance holds a strong reference to the container object.</p> */ public OVRPoseStatef(ByteBuffer container) { this(memAddress(container), __checkContainer(container, SIZEOF)); } @Override public int sizeof() { return SIZEOF; } /** Returns a {@link OVRPosef} view of the {@code ThePose} field. */ @NativeType("ovrPosef") public OVRPosef ThePose() { return nThePose(address()); } /** Returns a {@link OVRVector3f} view of the {@code AngularVelocity} field. */ @NativeType("ovrVector3f") public OVRVector3f AngularVelocity() { return nAngularVelocity(address()); } /** Returns a {@link OVRVector3f} view of the {@code LinearVelocity} field. */ @NativeType("ovrVector3f") public OVRVector3f LinearVelocity() { return nLinearVelocity(address()); } /** Returns a {@link OVRVector3f} view of the {@code AngularAcceleration} field. */ @NativeType("ovrVector3f") public OVRVector3f AngularAcceleration() { return nAngularAcceleration(address()); } /** Returns a {@link OVRVector3f} view of the {@code LinearAcceleration} field. */ @NativeType("ovrVector3f") public OVRVector3f LinearAcceleration() { return nLinearAcceleration(address()); } /** Returns the value of the {@code TimeInSeconds} field. */ public double TimeInSeconds() { return nTimeInSeconds(address()); } // ----------------------------------- /** Returns a new {@link OVRPoseStatef} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */ public static OVRPoseStatef malloc() { return create(nmemAllocChecked(SIZEOF)); } /** Returns a new {@link OVRPoseStatef} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */ public static OVRPoseStatef calloc() { return create(nmemCallocChecked(1, SIZEOF)); } /** Returns a new {@link OVRPoseStatef} instance allocated with {@link BufferUtils}. */ public static OVRPoseStatef create() { return new OVRPoseStatef(BufferUtils.createByteBuffer(SIZEOF)); } /** Returns a new {@link OVRPoseStatef} instance for the specified memory address. */ public static OVRPoseStatef create(long address) { return new OVRPoseStatef(address, null); } /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static OVRPoseStatef createSafe(long address) { return address == NULL ? null : create(address); } /** * Returns a new {@link OVRPoseStatef.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static OVRPoseStatef.Buffer malloc(int capacity) { return create(__malloc(capacity, SIZEOF), capacity); } /** * Returns a new {@link OVRPoseStatef.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static OVRPoseStatef.Buffer calloc(int capacity) { return create(nmemCallocChecked(capacity, SIZEOF), capacity); } /** * Returns a new {@link OVRPoseStatef.Buffer} instance allocated with {@link BufferUtils}. * * @param capacity the buffer capacity */ public static OVRPoseStatef.Buffer create(int capacity) { return new Buffer(__create(capacity, SIZEOF)); } /** * Create a {@link OVRPoseStatef.Buffer} instance at the specified memory. * * @param address the memory address * @param capacity the buffer capacity */ public static OVRPoseStatef.Buffer create(long address, int capacity) { return new Buffer(address, capacity); } /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static OVRPoseStatef.Buffer createSafe(long address, int capacity) { return address == NULL ? null : create(address, capacity); } // ----------------------------------- /** Returns a new {@link OVRPoseStatef} instance allocated on the thread-local {@link MemoryStack}. */ public static OVRPoseStatef mallocStack() { return mallocStack(stackGet()); } /** Returns a new {@link OVRPoseStatef} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */ public static OVRPoseStatef callocStack() { return callocStack(stackGet()); } /** * Returns a new {@link OVRPoseStatef} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate */ public static OVRPoseStatef mallocStack(MemoryStack stack) { return create(stack.nmalloc(ALIGNOF, SIZEOF)); } /** * Returns a new {@link OVRPoseStatef} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate */ public static OVRPoseStatef callocStack(MemoryStack stack) { return create(stack.ncalloc(ALIGNOF, 1, SIZEOF)); } /** * Returns a new {@link OVRPoseStatef.Buffer} instance allocated on the thread-local {@link MemoryStack}. * * @param capacity the buffer capacity */ public static OVRPoseStatef.Buffer mallocStack(int capacity) { return mallocStack(capacity, stackGet()); } /** * Returns a new {@link OVRPoseStatef.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. * * @param capacity the buffer capacity */ public static OVRPoseStatef.Buffer callocStack(int capacity) { return callocStack(capacity, stackGet()); } /** * Returns a new {@link OVRPoseStatef.Buffer} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static OVRPoseStatef.Buffer mallocStack(int capacity, MemoryStack stack) { return create(stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity); } /** * Returns a new {@link OVRPoseStatef.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static OVRPoseStatef.Buffer callocStack(int capacity, MemoryStack stack) { return create(stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity); } // ----------------------------------- /** Unsafe version of {@link #ThePose}. */ public static OVRPosef nThePose(long struct) { return OVRPosef.create(struct + OVRPoseStatef.THEPOSE); } /** Unsafe version of {@link #AngularVelocity}. */ public static OVRVector3f nAngularVelocity(long struct) { return OVRVector3f.create(struct + OVRPoseStatef.ANGULARVELOCITY); } /** Unsafe version of {@link #LinearVelocity}. */ public static OVRVector3f nLinearVelocity(long struct) { return OVRVector3f.create(struct + OVRPoseStatef.LINEARVELOCITY); } /** Unsafe version of {@link #AngularAcceleration}. */ public static OVRVector3f nAngularAcceleration(long struct) { return OVRVector3f.create(struct + OVRPoseStatef.ANGULARACCELERATION); } /** Unsafe version of {@link #LinearAcceleration}. */ public static OVRVector3f nLinearAcceleration(long struct) { return OVRVector3f.create(struct + OVRPoseStatef.LINEARACCELERATION); } /** Unsafe version of {@link #TimeInSeconds}. */ public static double nTimeInSeconds(long struct) { return memGetDouble(struct + OVRPoseStatef.TIMEINSECONDS); } // ----------------------------------- /** An array of {@link OVRPoseStatef} structs. */ public static class Buffer extends StructBuffer<OVRPoseStatef, Buffer> implements NativeResource { /** * Creates a new {@link OVRPoseStatef.Buffer} instance backed by the specified container. * * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided * by {@link OVRPoseStatef#SIZEOF}, and its mark will be undefined. * * <p>The created buffer instance holds a strong reference to the container object.</p> */ public Buffer(ByteBuffer container) { super(container, container.remaining() / SIZEOF); } public Buffer(long address, int cap) { super(address, null, -1, 0, cap, cap); } Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) { super(address, container, mark, pos, lim, cap); } @Override protected Buffer self() { return this; } @Override protected Buffer newBufferInstance(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) { return new Buffer(address, container, mark, pos, lim, cap); } @Override protected OVRPoseStatef newInstance(long address) { return new OVRPoseStatef(address, container); } @Override public int sizeof() { return SIZEOF; } /** Returns a {@link OVRPosef} view of the {@code ThePose} field. */ @NativeType("ovrPosef") public OVRPosef ThePose() { return OVRPoseStatef.nThePose(address()); } /** Returns a {@link OVRVector3f} view of the {@code AngularVelocity} field. */ @NativeType("ovrVector3f") public OVRVector3f AngularVelocity() { return OVRPoseStatef.nAngularVelocity(address()); } /** Returns a {@link OVRVector3f} view of the {@code LinearVelocity} field. */ @NativeType("ovrVector3f") public OVRVector3f LinearVelocity() { return OVRPoseStatef.nLinearVelocity(address()); } /** Returns a {@link OVRVector3f} view of the {@code AngularAcceleration} field. */ @NativeType("ovrVector3f") public OVRVector3f AngularAcceleration() { return OVRPoseStatef.nAngularAcceleration(address()); } /** Returns a {@link OVRVector3f} view of the {@code LinearAcceleration} field. */ @NativeType("ovrVector3f") public OVRVector3f LinearAcceleration() { return OVRPoseStatef.nLinearAcceleration(address()); } /** Returns the value of the {@code TimeInSeconds} field. */ public double TimeInSeconds() { return OVRPoseStatef.nTimeInSeconds(address()); } } }
9225834f1ab9c6d0df805e212b2e430ab308a8e9
bd7b2f839e76e37bf8a3fd841a7451340f7df7a9
/archunit-example/example-plain/src/main/java/com/tngtech/archunit/example/onionarchitecture_by_annotations/onion/order/PaymentMethod.java
3e27ac4a2c3550ab63a65323d74ac6ec4750778c
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
TNG/ArchUnit
ee7a1cb280360481a004c46f9861c5db181d7335
87cc595a281f84c7be6219714b22fbce337dd8b1
refs/heads/main
2023-09-01T14:18:52.601280
2023-08-29T09:15:13
2023-08-29T09:15:13
88,962,042
2,811
333
Apache-2.0
2023-09-14T08:11:13
2017-04-21T08:39:20
Java
UTF-8
Java
false
false
223
java
package com.tngtech.archunit.example.onionarchitecture_by_annotations.onion.order; import com.tngtech.archunit.example.onionarchitecture_by_annotations.annotations.DomainModel; @DomainModel public class PaymentMethod { }
11837207984ffb40628e2ef9a3166d2c09441b2b
b1fe0e476e436eb60b30378d4d06ad01196553b6
/app/src/main/java/kr/hs/emirim/chaehyeon/tabhosttest/MainActivity.java
d50d7a82bb19a237687bcc1b0f499ec92977a36c
[]
no_license
chaehyeon7/TabHostTest
f5e8d61a0e44d1f5238e50851c1e677430668f1e
14600137b947232ff959aef2b69ac469d6d7c328
refs/heads/master
2023-06-26T18:44:11.208927
2021-07-27T01:10:22
2021-07-27T01:10:22
374,980,461
0
0
null
null
null
null
UTF-8
Java
false
false
892
java
package kr.hs.emirim.chaehyeon.tabhosttest; import android.app.TabActivity; import android.os.Bundle; import android.widget.TabHost; public class MainActivity extends TabActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TabHost tabHost = getTabHost(); TabHost.TabSpec tabSpec1 = tabHost.newTabSpec("song").setIndicator("음악별"); tabHost.addTab(tabSpec1); TabHost.TabSpec tabSpec2 = tabHost.newTabSpec("artist").setIndicator("가수별"); tabSpec2.setContent(R.id.linear2); tabHost.addTab(tabSpec2); TabHost.TabSpec tabSpec3 = tabHost.newTabSpec("album").setIndicator("앨범별"); tabSpec2.setContent(R.id.linear3); tabHost.addTab(tabSpec3); tabHost.setCurrentTab(2); } }
358398701f1d5149a33219c2bb1607eaf0a08a1a
497561d75ed26cf74214c48b62a5178268d3bffb
/src/test/java/hello/core/beenfind/ApplicationContextInfoTest.java
f5d99bfa60b353bdefe64f06043b4d0ae53ef45d
[]
no_license
HyoungUkJJang/spring_basic1
263ff2d764820dacd7b16f9dec7c4d25f01ee0e1
2c0f0f6603ded2187ab9298da7b955cecb544a8a
refs/heads/master
2023-04-22T16:27:34.109605
2021-05-16T07:36:48
2021-05-16T07:36:48
363,868,857
0
0
null
null
null
null
UTF-8
Java
false
false
1,691
java
package hello.core.beenfind; import hello.core.AppConfig; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.AnnotationConfigApplicationContext; class ApplicationContextInfoTest { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class); @Test @DisplayName("모든 빈 출력하기") void findAllBean(){ String[] be = ac.getBeanDefinitionNames(); //iter 하고 탭 for (String s : be) { Object object = ac.getBean(s); // 타입을 모르기때문에 오브젝트로 꺼내진다. System.out.println("object = " + object); } } @Test @DisplayName("애플리케이션 빈 출력하기") void findApplicationBean(){ String[] beanDefinitionNames = ac.getBeanDefinitionNames(); //iter 하고 탭 for (String beanDefinitionName : beanDefinitionNames) { BeanDefinition beanDefinition = ac.getBeanDefinition(beanDefinitionName); // Role은 내가 생성한 애플리케이션을 개발하기위해 생성한것들만 나타내줌 // ROLE_APPLICATION > 직접 등록한 애플리케이션 빈 // ROLE_INFRASTRUCTURE > 스프링 내부에서 사용하는 빈 if (beanDefinition.getRole() == BeanDefinition.ROLE_APPLICATION) { Object bean = ac.getBean(beanDefinitionName); System.out.println("name = " + beanDefinitionName + " object = " + bean); } } } }
dabf2209d994bc690bca583e80939b218366beb3
e0f0a19ddf74b9d2c51b45b6f75588ee8ae469d9
/src/lab9/prob7b/Main.java
edb4925a487c6c6695f374c92118d0004c39061c
[]
no_license
cuongdd2/CS401
179e92e546124344e8afcec8c0e244da399d8d3f
e51584f86aa3efcf4ecca9efa32f6df2dd8fe8c2
refs/heads/master
2021-07-04T22:07:09.615473
2017-09-26T17:00:11
2017-09-26T17:00:11
104,913,575
0
0
null
null
null
null
UTF-8
Java
false
false
661
java
package lab9.prob7b; import java.util.*; public class Main { public static void main(String[] args) { List<Employee> list = Arrays.asList(new Employee("Joe", "Davis", 120000), new Employee("John", "Sims", 110000), new Employee("Joe", "Stevens", 200000), new Employee("Andrew", "Reardon", 80000), new Employee("Joe", "Cummings", 760000), new Employee("Steven", "Walters", 135000), new Employee("Thomas", "Blake", 111000), new Employee("Alice", "Richards", 101000), new Employee("Donald", "Trump", 100000)); System.out.println(LambdaLibrary.RUN.apply(list, 100000, "[N-Z].*")); } }
b8318051a207f409bc516d684f25cd9ae3a03323
f2c8b25b6a63cd26a211f60fcf598c84d1f743c9
/Android21/android-5.0.2_r1/src/com/android/okhttp/internal/http/HttpDate.java
38705a293ae433cf4e3921235e3dffea718aa122
[]
no_license
EnSoftCorp/AnalyzableAndroid
1ba0d5db531025e517e5e4fbb7e455bbb2bb2191
d9b29a11308eb8e6511335b24a44d0388eb7b068
refs/heads/master
2022-10-17T22:52:32.933849
2015-05-01T18:17:48
2015-05-01T18:17:48
21,949,091
1
0
null
null
null
null
UTF-8
Java
false
false
3,352
java
/* * Copyright (C) 2011 The Android Open Source Project * * 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.android.okhttp.internal.http; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * Best-effort parser for HTTP dates. */ public final class HttpDate { /** * Most websites serve cookies in the blessed format. Eagerly create the parser to ensure such * cookies are on the fast path. */ private static final ThreadLocal<DateFormat> STANDARD_DATE_FORMAT = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { DateFormat rfc1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); rfc1123.setTimeZone(TimeZone.getTimeZone("GMT")); return rfc1123; } }; /** If we fail to parse a date in a non-standard format, try each of these formats in sequence. */ private static final String[] BROWSER_COMPATIBLE_DATE_FORMAT_STRINGS = new String[] { "EEEE, dd-MMM-yy HH:mm:ss zzz", // RFC 1036 "EEE MMM d HH:mm:ss yyyy", // ANSI C asctime() "EEE, dd-MMM-yyyy HH:mm:ss z", "EEE, dd-MMM-yyyy HH-mm-ss z", "EEE, dd MMM yy HH:mm:ss z", "EEE dd-MMM-yyyy HH:mm:ss z", "EEE dd MMM yyyy HH:mm:ss z", "EEE dd-MMM-yyyy HH-mm-ss z", "EEE dd-MMM-yy HH:mm:ss z", "EEE dd MMM yy HH:mm:ss z", "EEE,dd-MMM-yy HH:mm:ss z", "EEE,dd-MMM-yyyy HH:mm:ss z", "EEE, dd-MM-yyyy HH:mm:ss z", /* RI bug 6641315 claims a cookie of this format was once served by www.yahoo.com */ "EEE MMM d yyyy HH:mm:ss z", }; private static final DateFormat[] BROWSER_COMPATIBLE_DATE_FORMATS = new DateFormat[BROWSER_COMPATIBLE_DATE_FORMAT_STRINGS.length]; /** Returns the date for {@code value}. Returns null if the value couldn't be parsed. */ public static Date parse(String value) { try { return STANDARD_DATE_FORMAT.get().parse(value); } catch (ParseException ignored) { } synchronized (BROWSER_COMPATIBLE_DATE_FORMAT_STRINGS) { for (int i = 0, count = BROWSER_COMPATIBLE_DATE_FORMAT_STRINGS.length; i < count; i++) { DateFormat format = BROWSER_COMPATIBLE_DATE_FORMATS[i]; if (format == null) { format = new SimpleDateFormat(BROWSER_COMPATIBLE_DATE_FORMAT_STRINGS[i], Locale.US); BROWSER_COMPATIBLE_DATE_FORMATS[i] = format; } try { return format.parse(value); } catch (ParseException ignored) { } } } return null; } /** Returns the string for {@code value}. */ public static String format(Date value) { return STANDARD_DATE_FORMAT.get().format(value); } private HttpDate() { } }
205c5632a449e68d842e579b1e0688f4068dd18e
d65f07352ee73347d6932e35c0f27a9c89bfa97f
/src/main/java/com/holly/dao/FileMapper.java
22814585fc2c5dc8a17a91c8ba199f72646a1fdb
[]
no_license
huyang489264/666
7a557efdea9f98a7f3a948737d802f5c454dbad7
a88fb74989046a8495913d34ed319af2b0f1b161
refs/heads/master
2022-07-04T20:43:31.669424
2019-07-15T05:16:03
2019-07-15T05:16:03
196,928,826
0
0
null
2022-06-17T02:19:52
2019-07-15T05:18:25
JavaScript
UTF-8
Java
false
false
291
java
package com.holly.dao; import com.holly.model.FileEntity; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface FileMapper { void saveFile(FileEntity entity); FileEntity findByid(long id); List<FileEntity> findAll(); void del(long fileId); }
23e96b87bfd706db3cd8e0163c33c6f474d34ada
50b9bffeba673e2f1acbd0686da0c4cafb073d29
/Stefan/Week1/Day 4/ShirtShop/ShirtCRUD.java
d4dab752d2679e8d218111e80a06148ed7f77751
[]
no_license
CodegileTraining/Work
54e89acfdabb8400b460d127fd9553fc9604951f
dfa0c2dd3b241ec8d2d9d7b55f946cce3f6be21e
refs/heads/master
2016-08-13T01:56:11.851127
2016-03-17T09:16:39
2016-03-17T09:16:39
51,749,987
0
3
null
null
null
null
UTF-8
Java
false
false
901
java
import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Contains a list of Shirt objects * @author Stefan * */ public class ShirtCRUD implements CRUD { public List<Shirt> shirtList = new ArrayList<Shirt>(); @Override public void create(Shirt s) { // TODO Auto-generated method stub shirtList.add(s); } @Override public Shirt read(Scanner input) { // TODO Auto-generated method stub String myLine = input.nextLine(); String[] words = myLine.split(","); Shirt myShirt = new Shirt(Integer.parseInt(words[0]), words[1], words[2], words[3], Integer.parseInt(words[4])); return myShirt; } @Override public void update(int index, int nrBucati) { // TODO Auto-generated method stub shirtList.get(index).setNrBucati(nrBucati); } @Override public void delete(int index) { // TODO Auto-generated method stub shirtList.remove(index); } }
a0cfc31be2294bcd939a1bf75d78b2ce63f28c96
c90391ff047de0cdbd7821bbbc8f9d795ff94b08
/tpcompiladores/src/java/tp/procesadores/analizador/sintactico/producciones/funcionesrequeridas/PAUX0.java
2ac4b3cfe9443a45c77eaea246648ef28520bcfc
[]
no_license
chalo2812/chalo-2812
88c7c1224dacc1841d9fe8945d181ecf05bb00a7
67e034e5a5cdd3824b7c6e4b9dbf47ca302e8866
refs/heads/master
2022-06-28T17:23:13.094578
2014-12-15T05:13:08
2014-12-15T05:13:08
33,846,463
1
0
null
2022-06-07T23:11:25
2015-04-13T03:46:54
Java
UTF-8
Java
false
false
1,408
java
package tp.procesadores.analizador.sintactico.producciones.funcionesrequeridas; import tp.procesadores.analizador.lexico.LexicAnalyzer; import tp.procesadores.analizador.lexico.tokens.visitor.TokensVisitor; import tp.procesadores.analizador.semantico.arbol.ArbolHandler; import tp.procesadores.analizador.semantico.arbol.expresiones.ClaseNodo; import tp.procesadores.analizador.semantico.arbol.tabla.simbolos.TablaDeSimbolos; import tp.procesadores.analizador.sintactico.SintacticAnalyzer; import tp.procesadores.analizador.sintactico.producciones.Produccion; public class PAUX0 extends Produccion { public PAUX0() { PAUX1 paux1 = null; producciones.add(paux1); } // PAUX -> [ EXP ] | lambda @Override public boolean reconocer(LexicAnalyzer lexic, TokensVisitor visitor, SintacticAnalyzer sintactic, ClaseNodo arbolH, ArbolHandler arbolS, TablaDeSimbolos tablaH) { boolean reconoce = false; if (sintactic.siguiente.accept(visitor).equals("[")) { ArbolHandler arbolSp = new ArbolHandler(); producciones.set(0, new PAUX1()); reconoce = producciones.get(0).reconocer(lexic, visitor, sintactic, arbolH, arbolSp, tablaH); arbolS.setArbol(arbolSp.getArbol()); } else { reconoce = true; arbolS.setArbol(arbolH); } return reconoce; } }
[ "[email protected]@e290e524-dcc9-e6dd-992a-3a6b9c64af2b" ]
[email protected]@e290e524-dcc9-e6dd-992a-3a6b9c64af2b
e93fb481aa8d1ec47918da93d9530288e7c59545
3582ecbf48986c872191b4c4ff9ce6de00432cff
/src/main/java/com/netcracker/edu/distancestudyweb/dto/homework/AssignmentRequestDto.java
c359eb1b5058b14d6cf8761a5c0ce79dfe6bf7f4
[]
no_license
russnewman/distance-study-platform-ui
b9995bf423b10f3029db5731f35135b00a3101b4
984d68127e47ef1a707e2dc862054b22cd4d0283
refs/heads/main
2023-04-22T05:16:19.039018
2021-04-26T08:02:03
2021-04-26T08:02:03
360,105,559
0
0
null
null
null
null
UTF-8
Java
false
false
222
java
package com.netcracker.edu.distancestudyweb.dto.homework; import lombok.Data; @Data public class AssignmentRequestDto { private Long studentId; private String commentary; private DatabaseFileDto dbFileDto; }
976795ca4e92d2c183abe83c97472fc9428a1bce
56f2a6ce9eae4ac2b367c933fc7fbb6e3a66d8bf
/netstuitetimereporting/src/main/java/nsCommon/nsCommon.java
5bc03ad746800281648bca8ccbe2c713687c7ee6
[]
no_license
gazi-salahuddin/testGH
83b1f66a5f955e912507001b0b9afffecb9ab88d
0973e5dfe1c21f4eb314b784f9084b3ed929d44c
refs/heads/master
2020-04-02T14:16:35.513352
2018-10-25T17:34:31
2018-10-25T17:34:31
154,518,101
0
0
null
null
null
null
UTF-8
Java
false
false
149
java
package nsCommon; //this is a test public class nsCommon { public static void main(String[] args) { System.out.println("Hi"); } }
b171e11b4a94c81edb1bcb013dc86e1e4c0d26a0
0ff34c432967a6d4a2f2e7878dcb2e1fdd170a7a
/app/src/main/java/com/jardinbotanico/jbplandelalaguna/UI/Zone/Main/IZoneActivity.java
9c3675dc7a38d0fff7f80459a0361acd325455ca
[]
no_license
moizest89/JardinBotanico
5b4c9f9da8b48ce0e3c404decb2d80ee9118cd7d
3afc729d7c34149dde7b6d4cca51aaa8f873bec0
refs/heads/master
2021-01-01T05:09:36.450698
2016-05-19T01:09:38
2016-05-19T01:09:38
59,079,730
0
0
null
null
null
null
UTF-8
Java
false
false
219
java
package com.jardinbotanico.jbplandelalaguna.UI.Zone.Main; import java.util.List; /** * Created by @moizest89 in SV on 4/11/16. */ public interface IZoneActivity { void setDataInSpinner(List<String> mData); }
d54ca49037ec5ac0e5841253993ea44f85c5f0d2
5d3e0445122cc111ae319e081bdb5ac8920585f7
/HomeWork2/Lapices.java
da02c16919b6643ea9226fcae847344fd7aaf76b
[]
no_license
lorenaGr0/Trabajos
8cab253443863f8a4a394dd39c845d9e3208f6c3
0e342a549c566f736a94ad2bfb76294581797492
refs/heads/master
2021-08-07T04:33:18.960309
2018-12-10T23:06:34
2018-12-10T23:06:34
147,432,484
0
0
null
null
null
null
UTF-8
Java
false
false
379
java
import java.util.Scanner; public class Lapices{ public static void main (String [] args){ Scanner input = new Scanner(System.in); System.out.println("Ingrese la cantidad de lapices: "); int x= input.nextInt(); double pag; if ( x >= 1000){ pag= x * 0.85; } else{ pag= x * 0.90; } System.out.println("Pago a realizar " + pag); } }
b87c04908a6c849a2386f297f4f1c16c23470e20
0d3a280a54ab71e415146939d58d368542dda9cc
/Reddit-Backend/src/main/java/com/RedditClone/SpringBootAngular/Controllers/CommentsController.java
767f26cbfd54feed6dc2fbd800f017074ffc52c9
[ "MIT" ]
permissive
JeevanMahesha/Spring
27905f32ec73505b54c78e9de448b810a9feff42
6d42ed3b48df5cdb9c294048880e1796776dad05
refs/heads/main
2023-08-31T11:12:29.577075
2021-10-02T12:30:23
2021-10-02T12:30:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,680
java
package com.RedditClone.SpringBootAngular.Controllers; import com.RedditClone.SpringBootAngular.DTO.CommentFlag; import com.RedditClone.SpringBootAngular.DTO.CommentRequest; import com.RedditClone.SpringBootAngular.Services.CommentsServices; import lombok.AllArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/comments") @AllArgsConstructor @CrossOrigin(origins = "http://localhost:4200") public class CommentsController { private final CommentsServices commentsServices; @PostMapping public ResponseEntity<String> createComment(@RequestBody CommentRequest commentRequest){ try { commentsServices.addNewComment(commentRequest); }catch (Exception e){ return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity<String>("Comment added successfully",HttpStatus.CREATED); } @GetMapping("/postid/{id}") public Object getCommentsByPostId(@PathVariable String id){ return commentsServices.getAllCommentsByPostId(id); } @GetMapping("/username/{name}") public List<CommentRequest> getCommentsByUserId(@PathVariable String name){ return commentsServices.getAllCommentsByUser(name); } @PostMapping("/flag/{id}") public ResponseEntity<String> addFlagToComment(@PathVariable String id , @RequestBody CommentFlag commentFlag){ return new ResponseEntity<String>( commentsServices.addFlagToComment(id,commentFlag),HttpStatus.OK); } }
a59ce2c1e038b4c7c047759b2aba2606051bacf1
8db46d59fd114c46ad8ff0c6d2a51c000af3c985
/superman-demo-model/src/main/java/com/h2t/test/dto/BaseDTO.java
18c8ce11bafd5d2d05c50119641a67218ed3f530
[]
no_license
TiantianUpup/superman-demo
13dfcf0849e389fb17c8fbd5a763939ec0389f7e
c5440fceb969baddc335a9760acfad1a93746780
refs/heads/master
2022-07-17T00:08:16.720363
2019-08-13T07:47:51
2019-08-13T07:47:51
202,088,519
7
4
null
2022-06-21T01:39:24
2019-08-13T07:25:44
Java
UTF-8
Java
false
false
146
java
package com.h2t.test.dto; /** * 基本DTO字段 * * @author hetiantian * @version 1.0 * @Date 2019/08/12 19:01 */ public class BaseDTO { }
3b0687843c0a155fa3cc1c69f0998cc9ab8a7d16
c8a4972bcb6e501b9db7c4299ce4b70d10eef9ce
/src/test/java/com/crud/tasks/mapper/TaskMapperTestSuite.java
187d6e8e5e0092014da7e5837eb0c6771170859d
[]
no_license
rogal92/kodilla-project
8a7cb38f6e575a61733d701fa1609e9cdfd9ed78
fdb9276d8ee289708a864b59c5a15330735cf4c0
refs/heads/master
2021-09-10T09:21:05.567462
2018-03-23T12:51:41
2018-03-23T12:51:41
114,742,315
0
0
null
null
null
null
UTF-8
Java
false
false
1,658
java
package com.crud.tasks.mapper; import com.crud.tasks.domain.Task; import com.crud.tasks.domain.TaskDto; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoJUnitRunner; import java.util.ArrayList; import java.util.List; @RunWith(MockitoJUnitRunner.class) public class TaskMapperTestSuite { @InjectMocks private TaskMapper taskMapper; @Test public void testMapToTask() { //given Task task = new Task(1L,"title","content"); TaskDto taskDto = new TaskDto(1L,"title","content"); //when boolean isEqual = taskMapper.mapToTask(taskDto).equals(task); //then Assert.assertTrue(isEqual); } @Test public void testMapToTaskDto() { //given Task task = new Task(2L,"title","content"); TaskDto taskDto = new TaskDto(2L,"title","content"); //when boolean isEqual = taskMapper.mapToTaskDto(task).equals(taskDto); //then Assert.assertTrue(isEqual); } @Test public void testMapToTaskListDto() { //given List<Task> tasks = new ArrayList<>(); List<TaskDto> taskDtos = new ArrayList<>(); TaskDto taskDto = new TaskDto(3L,"title","content"); Task task = new Task(3L,"title","content"); //when List<TaskDto> taskDtoList = new ArrayList<>(); tasks.add(task); taskDtos.add(taskDto); taskDtoList = taskMapper.mapToTaskDtoList(tasks); //then Assert.assertEquals(taskDtoList,taskDtos); } }
0d8ef0e7157ffd2f569d5c070b601390ba764851
5456663349ace1b3553735c5178f806e7f08b765
/algorithm/src/com/queue/MyPriorityQueue.java
8baf680b781c35f88426f68f51a7b96e0b933541
[]
no_license
zhuweiwu/J2SE
6753d0846962dd74a35751aecd001ef922df4d22
9b110b36491ab68d571ff6a4332bd45be7e98f6f
refs/heads/master
2021-01-20T04:11:52.097207
2014-03-17T05:40:50
2014-03-17T05:40:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
56
java
package com.queue; public class MyPriorityQueue { }
3a5fc1670541a0feafeb65cb85b5da3e3e692114
833d4b7b1a5907afcf1fca1b657676a06daf6689
/app/src/main/java/com/servabosafe/shadow/ble/BarometerCalibrationCoefficients.java
374d1b5010157fea0868064ea4e22931cb7cea5d
[]
no_license
mariusbloemhof/shadow-archive
d43ad0a7e28d6246723dc317bd0fbe74f2502b9c
3be4b5a2b765022c0678b2f651ff50f6d0b267a6
refs/heads/master
2021-01-10T23:07:41.975165
2016-10-11T16:52:10
2016-10-11T16:52:10
70,615,073
0
0
null
null
null
null
UTF-8
Java
false
false
3,671
java
/************************************************************************************************** Filename: BarometerCalibrationCoefficients.java Revised: $Date: 2013-08-30 11:44:31 +0200 (fr, 30 aug 2013) $ Revision: $Revision: 27454 $ Copyright (c) 2013 - 2014 Texas Instruments Incorporated All rights reserved not granted herein. Limited License. Texas Instruments Incorporated grants a world-wide, royalty-free, non-exclusive license under copyrights and patents it now or hereafter owns or controls to make, have made, use, import, offer to sell and sell ("Utilize") this software subject to the terms herein. With respect to the foregoing patent license, such license is granted solely to the extent that any such patent is necessary to Utilize the software alone. The patent license shall not apply to any combinations which include this software, other than combinations with devices manufactured by or for TI (�TI Devices�). No hardware patent is licensed hereunder. Redistributions must preserve existing copyright notices and reproduce this license (including the above copyright notice and the disclaimer and (if applicable) source code license limitations below) in the documentation and/or other materials provided with the distribution Redistribution and use in binary form, without modification, are permitted provided that the following conditions are met: * No reverse engineering, decompilation, or disassembly of this software is permitted with respect to any software provided in binary form. * any redistribution and use are licensed by TI for use only with TI Devices. * Nothing shall obligate TI to provide you with source code for the software licensed and provided to you in object code. If software source code is provided to you, modification and redistribution of the source code are permitted provided that the following conditions are met: * any redistribution and use of the source code, including any resulting derivative works, are licensed by TI for use only with TI Devices. * any redistribution and use of any object code compiled from the source code and any resulting derivative works, are licensed by TI for use only with TI Devices. Neither the name of Texas Instruments Incorporated nor the names of its suppliers may be used to endorse or promote products derived from this software without specific prior written permission. DISCLAIMER. THIS SOFTWARE IS PROVIDED BY TI AND TI�S LICENSORS "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 TI AND TI�S LICENSORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **************************************************************************************************/ package com.servabosafe.shadow.ble; import java.util.List; /** * As a last-second hack i'm storing the barometer coefficients in a global. */ public enum BarometerCalibrationCoefficients { INSTANCE; volatile public List<Integer> barometerCalibrationCoefficients; volatile public double heightCalibration; }
[ "Marius Bloemhof" ]
Marius Bloemhof
40c45e07b195ba3d84343e17270a519f810e1276
7c8899cbd88bc76430488b806251436136ae4085
/src/java/dt/persistent/xml/Task.java
8b249e12f93e59272b39b27bf6c6e03e58ee6aaa
[]
no_license
surajsharmaa/DeepTutorAdmin
6280bcecf9bb3ba93fe834e9282ac526a3a4fb07
1dc39fb80e5883795e9202700cf28af8d5891999
refs/heads/main
2023-05-28T23:36:16.880774
2021-06-14T00:22:06
2021-06-14T00:22:06
376,665,761
0
0
null
null
null
null
UTF-8
Java
false
false
11,635
java
package dt.persistent.xml; import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import dt.config.ConfigManager; public class Task { private String fileName = ""; private String creator = ""; private String taskID = ""; private String problemText1 = ""; private String problemText2 = ""; private String image = ""; private String multimedia = ""; private String introduction = ""; private String summary = ""; private Expectation[] expectations = new Expectation[0]; private Expectation[] misconceptions = new Expectation[0]; public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public String getTaskID() { return taskID; } public void setTaskID(String taskID) { this.taskID = taskID; } public String getProblemText1() { return problemText1; } public void setProblemText1(String problemText1) { this.problemText1 = problemText1; } public String getProblemText2() { return problemText2; } public void setProblemText2(String problemText2) { this.problemText2 = problemText2; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getMultimedia() { return multimedia; } public void setMultimedia(String multimedia) { this.multimedia = multimedia; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public Expectation[] getExpectations() { return expectations; } public void setExpectations(Expectation[] expectations) { this.expectations = expectations; } public Expectation[] getMisconceptions() { return misconceptions; } public void setMisconceptions(Expectation[] misconceptions) { this.misconceptions = misconceptions; } public String CreateXML() { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("Tasks"); doc.appendChild(rootElement); // staff elements Element task = doc.createElement("Task"); Attr attr = doc.createAttribute("id"); attr.setValue(this.taskID); task.setAttributeNode(attr); attr = doc.createAttribute("description"); attr.setValue(""); task.setAttributeNode(attr); attr = doc.createAttribute("level"); attr.setValue("1"); task.setAttributeNode(attr); Element elem = doc.createElement("Text"); elem.appendChild(doc.createTextNode(this.problemText1)); task.appendChild(elem); elem = doc.createElement("Text2"); elem.appendChild(doc.createTextNode(this.problemText2)); task.appendChild(elem); elem = doc.createElement("Intro"); elem.appendChild(doc.createTextNode(this.introduction)); task.appendChild(elem); if (this.image!=null && this.image.trim().length()>0) { elem = doc.createElement("Image"); attr = doc.createAttribute("source"); attr.setValue(this.image); elem.setAttributeNode(attr); attr = doc.createAttribute("width"); attr.setValue("100"); elem.setAttributeNode(attr); attr = doc.createAttribute("height"); attr.setValue("100"); elem.setAttributeNode(attr); task.appendChild(elem); } if (this.multimedia!=null && this.multimedia.trim().length()>0) { elem = doc.createElement("Multimedia"); attr = doc.createAttribute("source"); attr.setValue(this.multimedia); elem.setAttributeNode(attr); attr = doc.createAttribute("width"); attr.setValue("100"); elem.setAttributeNode(attr); attr = doc.createAttribute("height"); attr.setValue("100"); elem.setAttributeNode(attr); task.appendChild(elem); } //expectations Element expectationList = doc.createElement("ExpectationList"); for(int i=0; i<this.expectations.length;i++) { expectationList.appendChild(CreateExpectationNode(doc, this.expectations[i])); } task.appendChild(expectationList); //misconceptions Element misconceptionList = doc.createElement("MisconceptionList"); for(int i=0; i<this.misconceptions.length;i++) { misconceptionList.appendChild(CreateExpectationNode(doc, this.misconceptions[i])); } task.appendChild(misconceptionList); rootElement.appendChild(task); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(doc); // OutputStream outres = new ByteArrayBuffer(); // StreamResult result = new StreamResult(outres); // transformer.transform(source, result); // return outres.toString(); StreamResult result = new StreamResult(new FileWriter(new File(ConfigManager.GetEditedTasksPath() + ConfigManager.GetTaskFileName(taskID)))); transformer.transform(source, result); return "OK"; } catch (ParserConfigurationException pce) { pce.printStackTrace(); return "Error creating the XML script."; } catch (TransformerException tfe) { tfe.printStackTrace(); return "Error creating the XML script."; } catch (IOException e) { e.printStackTrace(); return "Error creating the XML script."; } } Element CreateExpectationNode(Document doc, Expectation e) { Element exp = e.isMisconception?doc.createElement("Misconception"):doc.createElement("Expectation"); Element elem = null; Attr attr = doc.createAttribute("id"); attr.setValue(e.id); exp.setAttributeNode(attr); if (!e.isMisconception) { attr = doc.createAttribute("order"); attr.setValue(String.valueOf(e.getOrder())); exp.setAttributeNode(attr); attr = doc.createAttribute("type"); attr.setValue(e.type.toString().toLowerCase()); exp.setAttributeNode(attr); elem = doc.createElement("Description"); elem.appendChild(doc.createTextNode(e.description)); exp.appendChild(elem); if (e.postImage != null && e.postImage.trim().length()>0) { elem = doc.createElement("PostImage"); attr = doc.createAttribute("source"); attr.setValue(e.postImage); elem.setAttributeNode(attr); attr = doc.createAttribute("width"); attr.setValue(""+e.postImageSizeWidth); elem.setAttributeNode(attr); attr = doc.createAttribute("height"); attr.setValue(""+e.postImageSizeHeight); elem.setAttributeNode(attr); exp.appendChild(elem); } if (e.prompt != null && e.prompt.trim().length()>0) { Element promptElem = doc.createElement("Prompt"); elem = doc.createElement("Text"); elem.appendChild(doc.createTextNode(e.prompt)); promptElem.appendChild(elem); if (e.promptAnswer!=null && e.promptAnswer.acceptedAnswer.trim().length()>0) promptElem.appendChild(BuildNodeExpectAnswer("Answer", doc,e.promptAnswer)); if (e.promptCorrection!=null) { elem = doc.createElement("Negative"); elem.appendChild(doc.createTextNode(e.promptCorrection)); promptElem.appendChild(elem); } exp.appendChild(promptElem); } if (e.hints != null && e.hints.length > 0) { Element hsElem = doc.createElement("HintSequence"); Element hintElem = null; for(int i=0;i<e.hints.length;i++) { hintElem = doc.createElement("Hint"); attr = doc.createAttribute("type"); attr.setValue(e.hintsType[i]); hintElem.setAttributeNode(attr); elem = doc.createElement("Text"); elem.appendChild(doc.createTextNode(e.hints[i])); hintElem.appendChild(elem); if (e.hintsAnswer[i]!=null && e.hintsAnswer[i].acceptedAnswer.trim().length()>0) hintElem.appendChild(BuildNodeExpectAnswer("Answer", doc,e.hintsAnswer[i])); if (e.hintsCorrection[i]!=null) { elem = doc.createElement("Negative"); elem.appendChild(doc.createTextNode(e.hintsCorrection[i])); hintElem.appendChild(elem); } hsElem.appendChild(hintElem); } exp.appendChild(hsElem); } } else { if (e.yokedExpectation != null && e.yokedExpectation.trim().length()>0) { elem = doc.createElement("YokedExpectation"); elem.appendChild(doc.createTextNode(e.yokedExpectation)); exp.appendChild(elem); } } //save the text variants for (int i=0;i<e.variants.length;i++) { elem = doc.createElement("Text"); attr = doc.createAttribute("id"); attr.setValue(""+(i+1)); elem.setAttributeNode(attr); elem.appendChild(doc.createTextNode(e.variants[i])); exp.appendChild(elem); } if (e.assertion != null && e.assertion.trim().length()>0) { elem = doc.createElement("Assertion"); elem.appendChild(doc.createTextNode(e.assertion)); exp.appendChild(elem); } if (e.pump != null && e.pump.trim().length()>0) { elem = doc.createElement("Pump"); elem.appendChild(doc.createTextNode(e.pump)); exp.appendChild(elem); } if (e.getAlternatePump() != null && e.getAlternatePump().trim().length()>0) { elem = doc.createElement("AltPump"); elem.appendChild(doc.createTextNode(e.getAlternatePump().trim())); exp.appendChild(elem); } if (e.bonus != null && e.bonus.trim().length()>0) { elem = doc.createElement("Bonus"); elem.appendChild(doc.createTextNode(e.bonus)); exp.appendChild(elem); } if (e.required != null && e.required.acceptedAnswer.trim().length()>0) exp.appendChild(BuildNodeExpectAnswer("Required", doc, e.required)); if (e.forbidden != null && e.forbidden.trim().length()>0) { elem = doc.createElement("Forbidden"); elem.appendChild(doc.createTextNode(e.forbidden)); exp.appendChild(elem); } return exp; } Element BuildNodeExpectAnswer(String name, Document doc, ExpectAnswer e) { Element result = doc.createElement(name); Element elem = doc.createElement("Text"); elem.appendChild(doc.createTextNode(e.acceptedAnswer)); result.appendChild(elem); if (e.wrongAnswer!= null && e.wrongAnswer.trim().length()>0){ elem = doc.createElement("Wrong"); elem.appendChild(doc.createTextNode(e.wrongAnswer)); result.appendChild(elem); } if (e.goodAnswerVariants != null) { for (int i=0;i<e.goodAnswerVariants.length;i++) { Element elemGwF = doc.createElement("GoodWithFeedback"); elem = doc.createElement("Text"); elem.appendChild(doc.createTextNode(e.goodAnswerVariants[i])); elemGwF.appendChild(elem); elem = doc.createElement("Feedback"); elem.appendChild(doc.createTextNode(e.goodFeedbackVariants[i])); elemGwF.appendChild(elem); result.appendChild(elemGwF); } } return result; } }
565f40fdac33a867de9d9ec9554adf2a82f82570
a4b23a681d3fd519475100e08a86dc2c5d2c96b2
/src/main/java/com/automation/platform/api/HttpClientApi.java
0ca8869d35417c2ef23ca6ef34a035f6beaedb67
[ "Apache-2.0" ]
permissive
manivannanpannerselvam/Canvas
fd1e43276808cc40a9871ed9422eca436be5990a
a01e2e3f841bd41ae8a10e6602cbc9630c7be21f
refs/heads/master
2023-07-12T10:21:40.945820
2021-08-13T08:25:51
2021-08-13T08:25:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,378
java
package com.automation.platform.api; import com.automation.platform.config.Configvariable; import com.automation.platform.exception.TapException; import com.automation.platform.exception.TapExceptionType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.JsonPath; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.EntityBuilder; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Component public class HttpClientApi { private static final Logger logger = LoggerFactory.getLogger(HttpClientApi.class); @Autowired private Configvariable configvariable; private MultipartEntityBuilder multipartEntityBuilder = null; private HttpResponse httpresponse = null; private String responseBody = null; private CloseableHttpClient httpClient = null; private Map<String, String> sendHeaders = new HashMap<String, String>(); private HttpPost httpPost = null; private HttpGet httpGet = null; private String endpointUrl; private String requestBody = null; private static String PROXY_USER = System.getProperty("proxy.user"); private static String PROXY_PASS = System.getProperty("proxy.pass"); private static String PROXY_HOST = System.getProperty("proxy.host"); private static int PROXY_PORT = 8080; public String getUrl() { return endpointUrl; } public void setUrl(String endpointUrl) { logger.info("Endpoint url is " + endpointUrl); this.endpointUrl = endpointUrl; } public String getRequestBody() { return requestBody; } public void setRequestBody(String requestBody) { logger.info("Request body is " + requestBody); this.requestBody = requestBody; } public void setResponseBody(String responseBody) { this.responseBody = responseBody; } public Map<String, String> getSendHeaders() { return sendHeaders; } public void setSendHeaders(Map<String, String> sendHeaders) { logger.info("Header map is " + sendHeaders); this.sendHeaders = sendHeaders; } public void setSendHeaders(String key, String value) { logger.info("Set header key as " + key + " and value as " + value); if (sendHeaders == null) { sendHeaders = new HashMap<String, String>(); } if (sendHeaders.containsKey(key)) { sendHeaders.remove(key); } sendHeaders.put(key, value); } public CloseableHttpClient createHttpClient(String targetHostUser, String targetHostPassword) { CredentialsProvider result = new BasicCredentialsProvider(); result.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT), new UsernamePasswordCredentials(targetHostUser, targetHostPassword)); // result.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(targetHostUser, targetHostPassword)); CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(result).build(); return httpClient; } public CloseableHttpClient createHttpClient1() { if (httpClient != null) { closeHttpClent(); resetVariables(); sendHeaders = null; } httpClient = HttpClients.createDefault(); return httpClient; } public void closeHttpClent() { httpClient.getConnectionManager().shutdown(); httpresponse = null; } public RequestConfig setProxyConfig() { HttpHost proxyHost = new HttpHost(PROXY_HOST, PROXY_PORT, "http"); //Setting the proxy RequestConfig.Builder reqconfigconbuilder = RequestConfig.custom(); reqconfigconbuilder = reqconfigconbuilder.setProxy(proxyHost); return reqconfigconbuilder.build(); } public HttpPost createHttpPost() { RequestConfig config = null; if (configvariable.isProxyRequired()) { config = setProxyConfig(); } httpPost = new HttpPost(getUrl()); if (sendHeaders != null) { for (Map.Entry<String, String> e : sendHeaders.entrySet()) { httpPost.addHeader(configvariable.expandValue(e.getKey()), configvariable.expandValue(e.getValue())); } } httpPost.setConfig(config); return httpPost; } public HttpGet createHttpGet() { RequestConfig config = null; if (configvariable.isProxyRequired()) { config = setProxyConfig(); } httpGet = new HttpGet(endpointUrl); httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"); if (sendHeaders != null) { for (Map.Entry<String, String> e : sendHeaders.entrySet()) { httpGet.setHeader(configvariable.expandValue(e.getKey()), configvariable.expandValue(e.getValue())); } } //Setting the config to the request httpGet.setConfig(config); return httpGet; } public void setBodyParameters() { //Set the request post body StringEntity userEntity = null; if (requestBody != null) { try { userEntity = new StringEntity(requestBody); } catch (IOException e) { throw new TapException(TapExceptionType.IO_ERROR, "Failed to set body parameter"); } httpPost.setEntity(userEntity); } } public HttpResponse getHTTPPostResponse() { //Send the request; It will immediately return the response in HttpResponse object if any try { httpresponse = httpClient.execute(httpPost); responseBody = EntityUtils.toString(httpresponse.getEntity()); logger.info("Receiving:" + responseBody); } catch (IOException e) { throw new TapException(TapExceptionType.IO_ERROR, "Failed to get response from post request"); } return httpresponse; } public HttpResponse getHTTPGetResponse() { //Send the request; It will immediately return the response in HttpResponse object if any try { httpresponse = httpClient.execute(httpGet); responseBody = EntityUtils.toString(httpresponse.getEntity()); logger.info("Receiving:" + responseBody); } catch (IOException e) { throw new TapException(TapExceptionType.IO_ERROR, "Failed to get response from get request"); } return httpresponse; } public int getResponseCode() { //verify the valid error code first int statusCode = 0; String responseBody = null; try { statusCode = httpresponse.getStatusLine().getStatusCode(); } catch (Exception e) { logger.error("error: ", e); throw new TapException(TapExceptionType.PROCESSING_FAILED, "API call failed with status [{}]", statusCode); } return statusCode; } public void addMultiPartAsFile(String keyName, File file) { if (multipartEntityBuilder == null) { multipartEntityBuilder = MultipartEntityBuilder.create(); //Setting the mode multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); } //Adding a file multipartEntityBuilder.addBinaryBody(keyName, file); } public void addMultiPartAsText(String keyName, String text) { if (multipartEntityBuilder == null) { multipartEntityBuilder = MultipartEntityBuilder.create(); //Setting the mode multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); } //Adding text multipartEntityBuilder.addTextBody(keyName, text); } public HttpEntity getHttpEntity() { //Building a single entity using the parts if (requestBody != null) { HttpEntity httpEntity = EntityBuilder.create() .setText(requestBody) .build(); return httpEntity; } else if (multipartEntityBuilder != null) { return multipartEntityBuilder.build(); } return null; } public HttpUriRequest createMultiPartPostRequest(String method, String url) { //Building the RequestBuilder request object RequestBuilder reqbuilder = RequestBuilder.create(method.toUpperCase()).setUri(url); if (configvariable.isProxyRequired()) { reqbuilder.setConfig(setProxyConfig()); } if (sendHeaders != null) { for (Map.Entry<String, String> e : sendHeaders.entrySet()) { reqbuilder.addHeader(configvariable.expandValue(e.getKey()), configvariable.expandValue(e.getValue())); } } //Set the entity object to the RequestBuilder if (getHttpEntity() != null) { reqbuilder.setEntity(getHttpEntity()); } //Building the request return reqbuilder.build(); } public String executeRequestAndGetResponse(String method) { try { HttpUriRequest multipartRequest = createMultiPartPostRequest(method, getUrl()); //Executing the request httpresponse = httpClient.execute(multipartRequest); responseBody = EntityUtils.toString(httpresponse.getEntity()); logger.info("Receiving:" + responseBody); } catch (IOException e) { throw new TapException(TapExceptionType.IO_ERROR, "Failed to send request and get response {}", e.getMessage()); } return responseBody; } public String getResponseBody() { return responseBody; } public JsonNode getJsonNodeFromResponse() { JsonNode jsonNode = null; String jsonData = ""; try { jsonData = responseBody; jsonNode = (new ObjectMapper()).readTree(jsonData); return jsonNode; } catch (Exception var4) { throw new TapException(TapExceptionType.PROCESSING_FAILED, "Not able to convert response json data into json node [{}]", new Object[]{jsonData}); } } public String getJsonPathStringValue(String path) { String val = ""; try { val = JsonPath.read(responseBody, path).toString(); logger.info("Value for node " + path + " is " + val); } catch (Exception e) { throw new TapException(TapExceptionType.PROCESSING_FAILED, "Please provide correct Json Path to get data [{}]", path); } return val; } public List<Object> getJsonPathListValue(String path) { List<Object> val = new ArrayList<Object>(); try { val = JsonPath.read(responseBody, path); logger.info("Value for node " + path + " is " + val); } catch (Exception e) { throw new TapException(TapExceptionType.PROCESSING_FAILED, "Please provide correct Json Path to get data [{}]", path); } return val; } public void resetVariables() { multipartEntityBuilder = null; // sendHeaders = null; requestBody = null; } }
b2f2d12dc82444dc35f672d42ed8c80aba27b701
8b957b326f8206206c24b88cca8a947c9c13bc36
/Java/Triangle.java
873a99e4d32897a799bc650eabd9be89b815e125
[]
no_license
ZachAlanMueller/COSC
86b7d1d2e705859e04215d79fb8a064eec58f1f9
c70e9f0ff9e9c253984e8376bbf5a86007a9282b
refs/heads/master
2020-07-29T01:03:19.603426
2019-09-19T17:14:35
2019-09-19T17:14:35
209,608,433
0
0
null
null
null
null
UTF-8
Java
false
false
428
java
import java.util.Scanner; import java.lang.Math; public class Triangle { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.printf("Please enter side x: "); int x = sc.nextInt(); System.out.printf("Please enter side y: "); int y = sc.nextInt(); System.out.printf("Side Z is: " + (Math.sqrt(x*x+y*y)) + "\n"); } }
624e09ceb07b3414f9d072fdd5560c2d69386213
20587842c0fdf6097ce1b8f36eae851f2a40cd32
/HomeWork/Tests/JacksonObjectMapperToListTest.java
bd88548939f22f2fc2aeb694cc9d19347e3cce68
[]
no_license
LubomirJagos/java-testing-unit-tests
3d04c8dfefb1dae0edd2d524c0dfa4c3e6b1ef2b
7817224e81419f0c75c7bd3f36ef51ea34701ce6
refs/heads/master
2021-06-07T13:56:26.041708
2016-09-21T12:12:50
2016-09-21T12:12:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
897
java
import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class JacksonObjectMapperToListTest { public JacksonObjectMapperToList myTestMapper; @Before public void setUp() throws Exception { myTestMapper=new JacksonObjectMapperToList(); } @Test public void JsonToListTest() { String expected; String actual; myTestMapper.jacksonToList( "[{\"name\": \"David\",\"myMessage\": \"Hello\"},{\"name\": \"Lukas\",\"myMessage\": \"Hello world\"}]"); expected="David"; actual=myTestMapper.myList.get(0).getName(); assertEquals(expected,actual); assertEquals("David",myTestMapper.myList.get(0).getName()); assertEquals("Lukas",myTestMapper.myList.get(1).getName()); assertEquals("Hello",myTestMapper.myList.get(0).getMyMessage()); assertEquals("Hello world",myTestMapper.myList.get(1).getMyMessage()); } }
6cf54d6d314318c0f734fcad9771b7cf5ed910a4
40dd2c2ba934bcbc611b366cf57762dcb14c48e3
/RI_Stack/java/src/base/org/cablelabs/impl/manager/ResourceReclamationManager.java
16f7e97a3fcad9d54b125636f8f57e289fa20282
[]
no_license
amirna2/OCAP-RI
afe0d924dcf057020111406b1d29aa2b3a796e10
254f0a8ebaf5b4f09f4a7c8f4961e9596c49ccb7
refs/heads/master
2020-03-10T03:22:34.355822
2018-04-11T23:08:49
2018-04-11T23:08:49
129,163,048
0
0
null
null
null
null
UTF-8
Java
false
false
7,401
java
// COPYRIGHT_BEGIN // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER // // Copyright (C) 2008-2013, Cable Television Laboratories, Inc. // // This software is available under multiple licenses: // // (1) BSD 2-clause // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // ·Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // ·Redistributions in binary form must reproduce the above copyright notice, this list of conditions // and the following disclaimer in the documentation and/or other materials provided with the // distribution. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "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 THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // (2) GPL Version 2 // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 2. This program is distributed // in the hope that it will be useful, but WITHOUT ANY WARRANTY; without // even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program.If not, see<http:www.gnu.org/licenses/>. // // (3)CableLabs License // If you or the company you represent has a separate agreement with CableLabs // concerning the use of this code, your rights and obligations with respect // to this code shall be as set forth therein. No license is granted hereunder // for any other purpose. // // Please contact CableLabs if you need additional information or // have any questions. // // CableLabs // 858 Coal Creek Cir // Louisville, CO 80027-9750 // 303 661-9100 // COPYRIGHT_END package org.cablelabs.impl.manager; import org.dvb.application.AppID; import org.ocap.system.event.ResourceDepletionEvent; /** * The purpose of the <code>ResourceReclamationManager</code> is to implement a * subset of the overall <i>resource reclamation</i> policy for the OCAP stack. * In particular it is responsible for implementing support for requested * resource reclamations within the Java space. This includes: * <ul> * <li>Forced garbage collection and finalization cycles as a form of * non-destructive resource reclamation. * <li>Allowing the <i>Monitor Application</i> to be notified of low resource * situations via {@link ResourceDepletionEvent} delivery, giving it the chance * to reclaim resources. * <li>Forced destruction of lower-priority applications in an attempt to make * additional resources available. * </ul> * * @author Aaron Kamienski */ public interface ResourceReclamationManager extends Manager { // Currently, no externally accessible methods are exposed via this // interface // This may change. Some possibilities include: // * Allowing registration of callback routines for cache cleanup. // * Allowing instigation of resource reclamation. // * Retrieval of statistics. /** * This utility class can be used to manipulate an application's <i>context * identifier</i>. It is meant to be used within the context of OCAP * resource reclamation. * * @author Aaron Kamienski */ public static class ContextID { /** * Create a <i>context id</i> for the application specified by the given * parameters. * * @param id * the <code>AppID</code> for the given app or * <code>null</code> * @param priority * the application priority * @return a <i>context id</i> for the given parameters; <code>0L</code> * is returned if <i>id</i> is <code>null</code> */ public static long create(AppID id, int priority) { if (id == null) return 0L; return id.getAID() | (((long) id.getOID() & 0xFFFFFFFF) << 16) | ((long) priority << 48); } /** * Returns the <code>AppID</code> encoded in the given <i>contextId</i>. * * @param contextId * the given <i>contextId</i> * @return the <code>AppID</code> encoded in the given <i>contextId</i>; * if the <i>contextId</i> is zero, then <code>AppID(0,0)</code> * is still returned */ public static AppID getAppID(long contextId) { int OID = (int) (contextId >> 16); int AID = (int) (contextId & 0xFFFF); return new AppID(OID, AID); } /** * Returns the <i>priority</i> encoded in the given <i>contextId</i>. * * @param contextId * the given <i>contextId</i> * @return the <i>priority</i> encoded in the given <i>contextId</i>; if * the <i>contextId</i> is zero, then a priority of zero is * still returned */ public static int getPriority(long contextId) { return (short) (contextId >>> 48); } /** * Sets the <i>context id</i> for the {@link Thread#currentThread() * current thread}. * <p> * The <i>context id</i> for all threads defaults to zero unless * explicitly set. * <p> * This would generally be used as follows: * * <pre> * long oldId = ContextID.set(newId); * try * { * //... * } * finally * { * ContextID.set(oldId); * } * </pre> * <p> * This method is not intended for general-purpose use, but is intended * for use by the {@link CallerContextManager} and {@link CallerContext} * implementations. * * @param contextId * @return the previous <i>context id</i> for the current thread */ public static long set(long contextId) { return nSet(contextId); } /** * Native method used to implement {@link #set(long)}. Sets the * <i>context id</i> for the current thread. * * @param contextId * the new contextId * @return the old contextId */ private static native long nSet(long contextId); } }
37ef31108e2de138c60dbcf486f25ddf0b2bc539
36cd110fbe0bf7ffde780c4e71c1033c0a9756b0
/src/main/java/recording/RecordedJoystick.java
a7c37369bc3f413ccfd24cb71b85da077536582e
[]
no_license
2181Robotics/2019DeepSpace
bbec4682f34ced17fa04928f8f02a5d2e57bc93d
b2e3f3385031c54b9f08b2d25a5e770ccf64b4d4
refs/heads/master
2020-04-03T17:42:24.281453
2019-08-03T04:47:36
2019-08-03T04:47:36
155,456,283
1
0
null
2018-11-13T21:16:29
2018-10-30T21:06:39
Java
UTF-8
Java
false
false
6,461
java
package recording; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.buttons.Button; import edu.wpi.first.wpilibj.command.Command; public class RecordedJoystick { private Joystick j; private SpecialButton jb; public boolean replay = false; private Timer clock = new Timer(); private Saved last; public Saved start; public boolean recording = false; public String currFile = ""; public int total = 0; private boolean[] joys; public Joystick getJoystick() { return j; } public void startReplay() { int b = j.getButtonCount(); int jo = j.getAxisCount(); boolean[] buttons = new boolean[b]; for (int i = 0; i<b; i++) buttons[i] = true; boolean[] joys = new boolean[jo]; for (int i = 0; i<jo; i++) joys[i] = true; startReplay(buttons, joys); } public void startReplay(boolean[] buttons, boolean[] joys) { if (jb != null) jb.configure(buttons); this.joys = joys; clock.reset(); clock.start(); replay = true; } public void stopReplay() { if (jb != null) jb.configure(new boolean[j.getButtonCount()]); joys = new boolean[j.getAxisCount()]; replay = false; clock.stop(); } public void startRecord() { if (!recording) { total = 1; recording = true; clock.reset(); clock.start(); last = new Saved(j, clock.get()); start = last; } } public Saved makePlaceHolder() { return new Saved(j, 0); } public void stepRecord() { if (recording) { last.next = new Saved(j, clock.get()); last = last.next; total++; } } public void stopRecord() { recording = false; clock.stop(); //Save(currFile+part, true); } public boolean isDone() { return (start.next==null); } public double getTime() { return clock.get(); } public RecordedJoystick(int port) { j = new Joystick(port); start = makePlaceHolder(); head = new BinaryNode("", null); joys = new boolean[j.getAxisCount()]; } public double getRawAxis(int axis) { if (!joys[axis]) { return j.getRawAxis(axis); } else { while (start.next!=null && start.next.time<clock.get()) { start = start.next; } return start.joys[axis]; } } public void whenPressed(int button, Command command) { jb = new SpecialButton(j, button, jb, this); jb.whenPressed(command); } public void whenReleased(int button, Command command) { jb = new SpecialButton(j, button, jb, this); jb.whenReleased(command); } public void whileHeld(int button, Command command) { jb = new SpecialButton(j, button, jb, this); jb.whileHeld(command); //command is started repeatedly while button is held, possibly interrupting itself } public void toggleWhenPressed(int button, Command command) { jb = new SpecialButton(j, button, jb, this); jb.toggleWhenPressed(command); } public void cancelWhenPressed(int button, Command command) { jb = new SpecialButton(j, button, jb, this); jb.cancelWhenPressed(command); } private class SpecialButton extends Button { private Joystick j; private int button; private SpecialButton jb; private RecordedJoystick rj; private boolean replay = false; public SpecialButton(Joystick j, int button, SpecialButton jb, RecordedJoystick rj) { this.j = j; this.button = button; this.jb = jb; this.rj = rj; } public boolean get() { // returns true when button is supposed to be active if (!replay) { return j.getRawButton(button); } else { while (rj.start.next!=null && rj.start.next.time<rj.clock.get()) { rj.start = rj.start.next; } return (rj.start.butts&(1 << button-1)) != 0; } } public void configure(boolean[] buttons) { replay = buttons[button-1]; if (jb != null) jb.configure(buttons); } } private class BinaryNode { private String key; private Saved value; private BinaryNode left; private BinaryNode right; public BinaryNode(String key, Saved value) { this.key = key; this.value = value; } public void add(BinaryNode node) { int val = key.compareTo(node.key); if (val>0) { if (right==null) { right = node; } else { right.add(node); } } else { if (left==null) { left = node; } else { left.add(node); } } } public BinaryNode find(String name) { if (key.equals(name)) { return this; } else { int val = key.compareTo(name); if (val>0) { if (right!=null) { return right.find(name); } else { return null; } } else { if (left!=null) { return left.find(name); } else { return null; } } } } } private BinaryNode head; public void add(String name, Saved value) { BinaryNode node = new BinaryNode(name, value); head.add(node); } public void updateReplay(String name, Saved start) { BinaryNode toUpdate = head.find(name); if (toUpdate!=null) { toUpdate.value.next = start; } } public boolean exists(String name) { return (head.find(name)!=null); } public void set(String name) { BinaryNode thing = head.find(name); if (thing!=null) { start = thing.value.next; } } }
fb66f9f8e2f40b63e911aa6966d467b2e7f0b31b
b7ba8f1521ae155b5dd880c6e49222f63acbab00
/SE2_tut10_1701040079_TranThiMaiHuong/adapter/square/SquarePeg.java
74186bf5c279762affd985f7b626845e4db25374
[]
no_license
MaiHuong-hanu/SE2
ed91393a29c0dfa2f91212641232dd5720df26ac
aa2981710d0f6d0ecd15b6771525240d14170c77
refs/heads/master
2022-09-26T06:28:52.016456
2020-06-05T15:39:35
2020-06-05T15:39:35
269,672,444
0
0
null
null
null
null
UTF-8
Java
false
false
752
java
package tuts.tut10.to_dos.adapter.square; /** * SquarePegs are not compatible with RoundHoles (they were implemented by * previous development team). But we have to integrate them into our program. */ public class SquarePeg { //TO-DO: Declare an attribute: name = width, type = double protected double width; //TO-DO: Declare the constructor with a parameter public SquarePeg(double width) { this.width = width; } //TO-DO: Implement getWidth() method public double getWidth() { return width; } //TO-DO: Implement getSquare() method public double getSquare() { double result; //TO-DO: result = width^2 result = Math.pow(width, 2); return result; } }
3d89a80b1b09b1c6032e0ede0d3c43aa7a321b05
3b473afc657926b5ec78b6acc5ade578c4c35345
/org.pdtextensions.server.ui/src/org/pdtextensions/server/ui/internal/lhttpd/ServerConfigurationEditorPart.java
aae13609658ad784c507cc16091b1ddb87d328d5
[]
no_license
pdt-eg/Core-Plugin
80f5dede757b3aea8581590098f8a76eadfa53a8
f393923be5c8c0de300e8a72c0e49843328aff39
refs/heads/master
2021-12-22T11:32:22.212223
2021-12-17T16:39:21
2021-12-17T16:39:21
5,639,261
29
13
null
2018-03-23T13:55:23
2012-09-01T12:03:13
Java
UTF-8
Java
false
false
1,619
java
/******************************************************************************* * Copyright (c) 2012 The PDT Extension Group (https://github.com/pdt-eg) * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.pdtextensions.server.ui.internal.lhttpd; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.ScrolledForm; import org.eclipse.wst.server.ui.editor.ServerEditorPart; /** * Editor part for configuration of local httpd runtime. * * @author mepeisen */ public class ServerConfigurationEditorPart extends ServerEditorPart { @Override public void createPartControl(Composite parent) { FormToolkit toolkit = getFormToolkit(parent.getDisplay()); ScrolledForm form = toolkit.createScrolledForm(parent); toolkit.decorateFormHeading(form.getForm()); form.setText(Messages.ServerConfigurationEditorPart_FormTitle); /* TODO form.setImage(TomcatUIPlugin.getImage(TomcatUIPlugin.IMG_WEB_MODULE));*/ GridLayout layout = new GridLayout(); layout.marginTop = 6; layout.marginLeft = 6; form.getBody().setLayout(layout); // TODO Auto-generated method stub } @Override public void setFocus() { // TODO Auto-generated method stub } }
9e6308e9a44ff26be6056984f124e5f811a9a6ff
5b9e623ef0dfedbd865923fe5709ff7e363581b9
/gulimall-order/src/main/java/com/atguigu/gulimall/order/vo/OrderSubmitResponseVo.java
e50cc9912d6bebcae4fce89133da285a8e5696e1
[]
no_license
lywcode/gulimallFinally
d56a010883eded374575a191b144bd1b63d77893
1f14b9c5f4050f266e264a04a227ca1ff3094fe6
refs/heads/master
2022-10-20T15:53:06.551028
2019-09-08T00:47:10
2019-09-08T00:47:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
159
java
package com.atguigu.gulimall.order.vo; import lombok.Data; @Data public class OrderSubmitResponseVo { private String msg; private Integer code; }
956878c3f3aaea51b8dc570e358070ebf16639a3
8f2dcfa7c95bf8adf5044ac8d65671c23f5ffcc8
/Source Code ShopBusters/workspace/Bookstore/src/main/java/com/bookstore/domain/CartItem.java
34b85e7116bedc5419c33ba221fec7044e3be89f
[]
no_license
mdfaisal8055/ShopBuster
37f24cbdb0e1f96153f90dde40b332595d8cd85f
54abe2bb526902d2702032b4994ed6c765d2f1d5
refs/heads/master
2021-01-11T13:39:02.782349
2017-06-21T23:57:12
2017-06-21T23:57:12
95,056,023
2
0
null
null
null
null
UTF-8
Java
false
false
1,790
java
package com.bookstore.domain; import java.math.BigDecimal; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity public class CartItem { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private int qty; private BigDecimal subtotal; @OneToOne private Book book; @OneToMany(mappedBy = "cartItem") @JsonIgnore private List<BookToCartItem> bookToCartItemList; @ManyToOne @JoinColumn(name="shopping_cart_id") private ShoppingCart shoppingCart; @ManyToOne @JoinColumn(name="order_id") private Order order; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getQty() { return qty; } public void setQty(int qty) { this.qty = qty; } public BigDecimal getSubtotal() { return subtotal; } public void setSubtotal(BigDecimal subtotal) { this.subtotal = subtotal; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public List<BookToCartItem> getBookToCartItemList() { return bookToCartItemList; } public void setBookToCartItemList(List<BookToCartItem> bookToCartItemList) { this.bookToCartItemList = bookToCartItemList; } public ShoppingCart getShoppingCart() { return shoppingCart; } public void setShoppingCart(ShoppingCart shoppingCart) { this.shoppingCart = shoppingCart; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } }
d745aa2d8bf1bace302c7bc6ec398281a4e6980c
4cc2354c2f85e6c2bc4b45162416e9a7e4c074d5
/app/src/test/java/nitkkr/minor/gofit/ExampleUnitTest.java
0a882ef6c4c8418eccec0be64c5b4e9342602b76
[]
no_license
saurabhsaini2k/GoFit
7b35bc38ed1429b873c50ff213244f81412c20be
836733c55ed64a2a31de702d6652187b91ade332
refs/heads/master
2021-05-04T01:03:49.633261
2016-11-23T07:06:21
2016-11-23T07:06:21
71,138,272
0
0
null
null
null
null
UTF-8
Java
false
false
396
java
package nitkkr.minor.gofit; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
01d2ffb500aa42574108cba89b7899b4e04eb8ce
6a9e414a6b2d7613eaf93cdcd46b359503f92629
/app/src/main/java/fitbit/common/model/units/VolumeUnits.java
a40b4c33065eedfd3fcaf0355d4ab435b95fe73a
[]
no_license
teamcovello/smartbaton
e600b2a8070fe498c5d7eac70c2aa90f29750c01
9fa217436feceb4588d958228bc581e0bc65a627
refs/heads/master
2020-03-29T22:37:49.794126
2014-08-26T03:21:50
2014-08-26T03:21:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
256
java
package fitbit.common.model.units; public enum VolumeUnits { ML("ml"), FL_OZ("fl oz"), CUP("cup"); String text; VolumeUnits(String text) { this.text = text; } public String getText() { return text; } }
0abc3072b47d86fcb59e16274301991db22f0d0f
4d4c6ea29c68868fd64894eb6859c3f2cad6f275
/register_client/src/RegisterWorker.java
aab3808632e117991d8ce38beb5a2412dcedb0db
[]
no_license
z14633/MyThreadPool
298e46ad45a7bedea902816e8feb520a9722b403
fc759c42522988e7d74a30b269b138ff5900ba89
refs/heads/master
2021-10-20T14:07:48.331271
2021-10-19T11:10:11
2021-10-19T11:10:11
222,216,450
0
0
null
null
null
null
UTF-8
Java
false
false
2,112
java
public class RegisterWorker extends Thread { public static final String SERVICE_NAME = "inventory-service"; public static final String IP = "192.168.31.204"; public static final String HOSTNAME = "inventory01"; public static final int PORT = 9000; /** * 判断是否注册成功 */ private Boolean finishedRegister = false; /** * 服务实例ID */ private String serviceInstanceId; /** * http通信组件 */ private HttpSender httpSender; public RegisterWorker(String serviceInstanceId){ this.serviceInstanceId = serviceInstanceId; this.httpSender = new HttpSender(); } @Override public void run() { if(!finishedRegister){ // 去做注册的业务 RegisterRequest request = new RegisterRequest(); request.setHostName(HOSTNAME); request.setPort(PORT); request.setIp(IP); request.setServiceName(SERVICE_NAME); request.setServiceInstanceId(serviceInstanceId); RegisterResponse response = httpSender.register(request); if(response.getStatus().equals(RegisterResponse.SUCCESS)){ finishedRegister = true; } else { return; } } if(finishedRegister) { // 去做发送心跳的业务 HeartbeatRequest request = new HeartbeatRequest(); request.setServiceInstanceId(serviceInstanceId); request.setServiceName(SERVICE_NAME); HeartbeatResponse heartbeatResponse = null; // 这里老师就特别注意,防止在循环内创建对象。以免给jvm回收带来压力。 while (true) { try { heartbeatResponse = httpSender.heartbeat(request); System.out.println("心跳的结果为: "+heartbeatResponse.getStatus()+"......"); Thread.sleep(30 * 1000); } catch (Exception e) { e.printStackTrace(); } } } } }
2d8ef8d98b3452ccdec7b0c740a6ef14f75916c7
020e4044dbd3b13ca605b9d89a2cd458c9f37fae
/algods/src/main/java/com/leetcode/bst/r01/BinaryTreeZigZagOrder.java
86c13bea4ec1d88f6ce6b562397aaeec1eb0c2d7
[]
no_license
partha0mishra/GetReady
6bb8b4afa10ecd6d5cb5c40bdfe3f2fe9844e03d
86e7894b17eadb9f1fcf6159ca47822f51b35a54
refs/heads/master
2023-05-28T09:26:44.465961
2021-06-03T22:57:46
2021-06-03T22:57:46
280,206,774
1
0
null
2020-11-20T20:12:51
2020-07-16T16:43:58
Java
UTF-8
Java
false
false
3,922
java
package com.leetcode.bst.r01; /** TODO Anki * 103. Binary Tree Zigzag Level Order Traversal * Given a binary tree, return the zigzag level order traversal of its nodes' values. * (ie, from left to right, then right to left for the next level and alternate between). * For example: * Given binary tree [3,9,20,null,null,15,7] * 3 / \ 9 20 / \ 15 7 * return its zigzag level order traversal as: * [ * [3], * [20,9], * [15,7] * ] */ import java.util.*; public class BinaryTreeZigZagOrder { //Definition for a binary tree node. class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } /** * BFS, with a flag to toggle ordering * Use a Deque and to be TRULY used as a Double-ended one * * if(toggle) current=pollLast(), offerFirst(current.right), offerFirst(current.left) * else current=pollFirst(), offerLast(current.left), offerLast(current.right) * * O(N)/ O(leaves)=> O(N/2) => O(N) */ public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> result=new ArrayList<List<Integer>>(); if(root == null) return result; Deque<TreeNode> queue=new ArrayDeque<>();// use as a queue/ stack boolean right=true; queue.offerLast(root); while(!queue.isEmpty()) { int size=queue.size(); ArrayList<Integer> thisLevel=new ArrayList<>(); right=!right; for(int s=0; s< size; s++) { TreeNode current; if(right) { current=queue.pollLast(); if(current.right != null) queue.offerFirst(current.right); if(current.left != null) queue.offerFirst(current.left); }else { current=queue.pollFirst(); if(current.left != null) queue.offerLast(current.left); if(current.right != null) queue.offerLast(current.right); } thisLevel.add(current.val); } result.add(thisLevel); } return result; } /** * Approach 01: similar one, but didn't know about Deque */ // public List<List<Integer>> zigzagLevelOrder(TreeNode root) { // if(root == null) return new ArrayList<List<Integer>>(); // boolean moveRight=false; // false- right, true- left. We start with Left // List<List<Integer>> result = new ArrayList<List<Integer>>(); // Queue<TreeNode> nodeQueue= new LinkedList<TreeNode>(); // nodeQueue.add(root); // // while(!nodeQueue.isEmpty()) { // int nodeCount= nodeQueue.size(); // ArrayList<Integer> thisLevelNodes= new ArrayList<Integer>(); // Stack<Integer> thisLevelStack= new Stack<Integer>(); // while(nodeCount -- >0) { // TreeNode thisNode=nodeQueue.remove(); // // if(thisNode !=null) { // nodeQueue.add(thisNode.left); // nodeQueue.add(thisNode.right); // // if(moveRight) { // // push to stack // thisLevelStack.add(thisNode.val); // }else { // // push to this level ArrayList // thisLevelNodes.add(thisNode.val); // } // } // } // if(moveRight) {// get from stack // while(!thisLevelStack.isEmpty()) { //// System.out.println(thisLevelStack.peek()); // thisLevelNodes.add(thisLevelStack.pop()); // } // } // if(!thisLevelNodes.isEmpty()) { // result.add(thisLevelNodes); // } // moveRight= moveRight? false: true;// flip it // } // // return result; // } public static void main(String[] args) { BinaryTreeZigZagOrder instance = new BinaryTreeZigZagOrder(); TreeNode root= instance.new TreeNode(3); root.left= instance.new TreeNode(9); root.right=instance.new TreeNode(20); root.right.left=instance.new TreeNode(15); root.right.right=instance.new TreeNode(7); System.out.println(instance.zigzagLevelOrder(root).toString()); System.out.println(instance.zigzagLevelOrder(null).toString());// null returns [] } }
240fad0a246b65d2b00ffc4f1fb3aba8d804f566
3d9bb79caedfcf01ec8adf9967df3f798d44bd82
/src/main/java/gzrd/wsclient/login/LoginCheckValidResponse.java
49edddfc4b0b804382dbd5b25869438841fe2694
[]
no_license
toohand/my-platform
3a921fa5da1a2481e7f54867d805a6cce8b14574
5e19ad8b53ac66a9cad3f26854e8bce07dc98e6c
refs/heads/master
2020-06-03T00:19:03.634080
2015-08-19T16:02:28
2015-08-19T16:02:28
40,395,193
1
0
null
null
null
null
GB18030
Java
false
false
1,405
java
package gzrd.wsclient.login; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>loginCheckValidResponse complex type的 Java 类。 * * <p>以下模式片段指定包含在此类中的预期内容。 * * <pre> * &lt;complexType name="loginCheckValidResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="return" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "loginCheckValidResponse", propOrder = { "_return" }) public class LoginCheckValidResponse { @XmlElement(name = "return") protected String _return; /** * 获取return属性的值。 * * @return * possible object is * {@link String } * */ public String getReturn() { return _return; } /** * 设置return属性的值。 * * @param value * allowed object is * {@link String } * */ public void setReturn(String value) { this._return = value; } }
b7057c16d60c35d7b32746600e3b7e2ac29ea704
c1db3f2b738f8093b3a6768aea75a6dd81e9a2af
/src/main/java/com/endava/internship/codesolver/model/entities/TestForTask.java
a70ae26a0a3d4253e5b9d259d849694c4ac6fe00
[]
no_license
ababus/codesolwer
bd205984bd7ef4956e5e99410590d1a8082475b1
944aea210a05f892b1f220fab966649e0b96faae
refs/heads/master
2023-02-13T17:39:18.731705
2020-06-23T06:15:54
2020-06-23T06:15:54
263,133,617
0
0
null
2021-01-15T08:18:39
2020-05-11T19:09:20
Java
UTF-8
Java
false
false
737
java
package com.endava.internship.codesolver.model.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Entity @Table(name = "tests") @Getter @Setter @ToString(of = "testBody") @EqualsAndHashCode(of = "testId") public class TestForTask { @Id @Column(name = "test_id", updatable = false, nullable = false) private String testId; @ManyToOne @JoinColumn(name = "task_id") private Task task; @Column(name = "test_file") private String testBody; }
838de94b889ed6e53078335091bd526b8b7481f2
f95db62c5be9baa1c53e339e4ee2af55e87e0335
/Membermanager-SpringMvc/src/main/java/com/bitcamp/mm/member/service/MemberRegService.java
35d9a1639baa0a2452304ee25e1a878e4d5cdf10
[]
no_license
JungGeon1/spring
43e96f1c036b9164dd3f54aaceada80d97ef5c68
3f172400b6943b39c389e4b70235bd483ff9bc2f
refs/heads/master
2022-12-23T19:03:15.411715
2020-03-05T00:20:15
2020-03-05T00:20:15
199,386,840
0
0
null
2022-12-16T09:45:12
2019-07-29T05:50:37
Java
UTF-8
Java
false
false
2,980
java
package com.bitcamp.mm.member.service; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.SQLException; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.bitcamp.mm.jdbc.ConnectionProvider; import com.bitcamp.mm.member.dao.MemberDao; import com.bitcamp.mm.member.dao.MemberJdbcTempleteDao; import com.bitcamp.mm.member.dao.memberSessionDao; import com.bitcamp.mm.member.domain.MemberInfo; import com.bitcamp.mm.member.domain.RequestMemberRegist; @Service("regsitService") public class MemberRegService implements MemberService { // @Autowired // private MemberJdbcTempleteDao templeteDao; @Autowired private SqlSessionTemplate sessionTemplate; @Autowired private MailSenderService mailService; private memberSessionDao sessionDao; public int memberInsert(HttpServletRequest request, RequestMemberRegist regist) { sessionDao = sessionTemplate.getMapper(memberSessionDao.class); // 서버경로 String path = "/uploadfile/userphoto"; // 절대경로 String dir = request.getSession().getServletContext().getRealPath(path); MemberInfo memberInfo = regist.toMemInfo(); String newFileName = ""; int resultCnt = 0; try { if (regist.getuPhoto() != null) { // 새로운 파일을 생성 newFileName = memberInfo.getuId() + "_" + regist.getuPhoto().getOriginalFilename(); // 파일을 서버의 지정 경로에 저장 System.out.println(dir); regist.getuPhoto().transferTo(new File(dir, newFileName)); // 데이터 베이스 저장을 하기우ㅏ한 파일 이름 set memberInfo.setuPhoto(newFileName); } resultCnt = sessionDao.insertMember(memberInfo); mailService.send(memberInfo.getuId(),memberInfo.getCode()); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO: handle exception System.out.println("구아악 이곳은 !!회워가입사진!"); } return resultCnt; } /* * public char idCheck(String id) { * * char chk = sessionDao.selectMemberById(id) == null ? 'Y' : 'N'; * * return chk; } */ public String idCheck1(String id) { sessionDao = sessionTemplate.getMapper(memberSessionDao.class); System.out.println(id); String chk = sessionDao.selectMemberById2(id) == null ? "Y" : "N" ; return chk; } }
c0358091fa68a4677ff9ba0ba291133b51f01a90
9115b714187a5478167969a07f22637031f1fbd1
/src/main/java/ru/itis/biology/config/LocalizationConfig.java
24035c17d87856aaa5c27a8d22de4848357ae813
[]
no_license
EminAliev/Rest-Biology-study
f15699cff51cfbd0e73d8a83d6eabe7093a93c30
f8fa7738834c464b79f6f2d804d1bd4570349b2a
refs/heads/master
2021-05-24T12:30:14.508506
2020-05-17T12:52:59
2020-05-17T12:52:59
253,543,154
0
0
null
null
null
null
UTF-8
Java
false
false
2,715
java
package ru.itis.biology.config; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.validation.DefaultMessageCodesResolver; import org.springframework.validation.MessageCodesResolver; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; @Configuration public class LocalizationConfig implements WebMvcConfigurer { // добавили в наше приложение перехватчик запросов для локализации @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } // храним информацию о выбранном языке в куках @Bean public LocaleResolver localeResolver() { CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); cookieLocaleResolver.setCookieName("localeInfo"); cookieLocaleResolver.setCookieMaxAge(60 * 60 * 24 * 365); return cookieLocaleResolver; } // перехватчик настроек языка // то есть если на сервер пришел запрос localhost:8080/login?lang=ru или ?lang=en, то этот перехватчик // установит куку с нужным значением @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("lang"); return localeChangeInterceptor; } // откуда читать ключи с языками @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:messages/messages"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; } @Override public MessageCodesResolver getMessageCodesResolver() { DefaultMessageCodesResolver codesResolver = new DefaultMessageCodesResolver(); codesResolver.setMessageCodeFormatter(DefaultMessageCodesResolver.Format.POSTFIX_ERROR_CODE); return codesResolver; } }
ab0d7139f25f2675bfc3655130a702f15c1f31d7
12724f7273b4266917df365fdeaa0139c4e70556
/jsc-sqlite/src/main/java/com/zzm/sqlite/utils/ImsiUtils.java
d7b328faec7997231e38edae933629c059724de6
[]
no_license
zhuzhaoman/jsc-parent
4c44fa8e803862ae5124f0c2689c37912154ef1a
7f4ec3783a99ff9001635641d618228526580d82
refs/heads/master
2023-07-31T13:06:19.129253
2021-09-24T06:52:19
2021-09-24T06:52:19
323,591,785
0
0
null
null
null
null
UTF-8
Java
false
false
963
java
package com.zzm.sqlite.utils; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang.StringUtils; import java.util.Set; /** * @author: zhuzhaoman * @date: 2021-01-04 * @description: **/ public class ImsiUtils { public static JSONObject queryFieldCast(String criteria) { JSONObject result = new JSONObject(); JSONObject jsonObject = JSONObject.parseObject("{" + criteria + "}"); Set<String> keys = jsonObject.keySet(); keys.forEach(k -> { if (jsonObject.get(k) instanceof String) { if (jsonObject.get(k).equals("")) { return; } } if(k.equals("ruleId")) { result.put(k, jsonObject.get(k)); return; } if (k.equals("imsi")) { result.put(k,jsonObject.get(k)); return; } }); return result; } }
15117ae4223bd80425910fb3da4e8994336e1910
43d3a0ec07ecb7a5ba2ef44688a0d1b6e6195c1d
/src/minisql/Record.java
94a846ec5e0e2ad0f19eddac019b871969adef05
[]
no_license
czxrrr/mini_czr
d03c245e2521a1fab2fd5599593791dc581e4a36
af1a845707a746dfdf6045e7a62bf9d8df4ef429
refs/heads/master
2021-01-10T12:44:47.025816
2015-11-09T10:11:59
2015-11-09T10:11:59
44,801,248
0
2
null
null
null
null
UTF-8
Java
false
false
216
java
package minisql; import java.util.ArrayList; public class Record { public ArrayList<String> attr=new ArrayList<String>(); public Record(ArrayList<String> a){ attr=a; } public Record(){ } }
31d54cbff138a50be7846dd734eb5e5e2948f1a3
f1abb45d71978a1c6c5622fb2e5941b2765c8656
/Java man exp2/Exp89.java
09a09e95042bf018adbc9cb1ed4cb8679b17456a
[]
no_license
DevaGaneshB/Java
b0aa21364cb4c63033826079e0ea9fb9a277557a
45bb30aff12757731e994b889156285689d67755
refs/heads/master
2020-03-23T19:07:03.914043
2019-05-20T13:30:56
2019-05-20T13:30:56
141,954,066
0
2
null
null
null
null
UTF-8
Java
false
false
237
java
//insert() class Exp89{ public static void main(String args[]){ StringBuilder sb=new StringBuilder("Hello "); sb.insert(1,"Java");//now original string is changed System.out.println(sb);//prints HJavaello } }
298c308558aa6932834656ffa8ff8b1f82f5af8e
6505de5cc40f15a8892626ce0eab595b2901f073
/Java/workshop/day09/src/company/Employee.java
a69f959fee8a298fb12c70d915462fa7151d2170
[]
no_license
gwang920/TIL
31a2a3ca7c56963f2077a0cc01fbe9be71866da0
e0d4ee023915c840f3e115e5462ab85592b0ca54
refs/heads/master
2022-12-24T23:35:48.107120
2021-05-24T13:45:22
2021-05-24T13:45:22
187,792,785
2
2
null
2022-12-16T07:48:36
2019-05-21T08:17:21
Java
UHC
Java
false
false
1,281
java
package company; public class Employee { protected String id; // private String id; protected String name; protected double salary; protected String dept; //자유롭게 접근 가능 + 하위 클래스에서 접근가능 public Employee() { } public Employee(String id, String name, double salary, String dept) { this.id = id; this.name = name; this.salary = salary; this.dept = dept; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + ", dept=" + dept + "]"; } public double salaryM() { double money=0; double temp =0; // 4대 보험료 8.4% // 세금 3.2% 공제 temp+=this.salary*0.084; temp+=this.salary*0.032; money = this.salary-temp; return money; } public double annSalary() { double ann=this.salaryM()*12; return ann; } }
62cfae7d68791637ec13b89d61f586329606c48e
c43c5df12e5098607b78cd9e57ea3814df27a3f3
/st1206/src/main/java/org/jmisb/st1206/SARMIEnumeration.java
47e60138104dfc3102f4e522627e8ee37d059a15
[ "MIT" ]
permissive
bradh/jmisb
a3ef77165b8bca404d73769cebb7b4cdd781be1f
f307aa1055362564811a881b73cd4f19c76f64a6
refs/heads/2.x
2023-06-30T23:57:12.700196
2022-12-19T16:19:29
2022-12-19T16:19:29
178,493,855
0
0
MIT
2023-06-14T22:54:24
2019-03-30T00:53:40
Java
UTF-8
Java
false
false
1,829
java
package org.jmisb.st1206; import java.util.Collections; import java.util.Map; /** Abstract base class for single-byte enumeration values in ST 1206. */ public abstract class SARMIEnumeration implements ISARMIMetadataValue { /** Implementing value for this enumeration. */ protected byte value; /** * Get a map of all possible values. * * @return Map of all enumeration values */ abstract Map<Integer, String> getDisplayValues(); /** * Create from value. * * @param enumeratedValue The value of the enumeration */ public SARMIEnumeration(byte enumeratedValue) { if (enumeratedValue < Collections.min(getDisplayValues().keySet()) || enumeratedValue > Collections.max(getDisplayValues().keySet())) { throw new IllegalArgumentException( getDisplayName() + " must be in range [" + Collections.min(getDisplayValues().keySet()) + ", " + Collections.max(getDisplayValues().keySet()) + "]"); } value = enumeratedValue; } /** * Create from encoded bytes. * * @param bytes The byte array of length 1 */ public SARMIEnumeration(byte[] bytes) { if (bytes.length != 1) { throw new IllegalArgumentException( getDisplayName() + " encoding is a 1-byte enumeration"); } value = bytes[0]; } @Override public byte[] getBytes() { byte[] bytes = new byte[Byte.BYTES]; bytes[0] = value; return bytes; } @Override public String getDisplayableValue() { return getDisplayValues().getOrDefault((int) value, "Unknown"); } }
9ebf27ada537e324a7c7ad969a18074f3aca023d
6daf06145547e1d1d8e7ca2872755e58191be12d
/src/com/tmh/dao/impl/StudentDaoImpl.java
0b03697816532dffc78942cc884b8a8e53ddd17b
[]
no_license
snowflake1997/teachmanage
d627130c5fddfedb9d65d19687cb1123464bcc30
6d7ce4ee0624c5a8696253cc3b7fdcf35501cb5c
refs/heads/master
2020-08-11T15:42:59.224784
2019-10-22T10:13:43
2019-10-22T10:13:43
214,589,930
0
0
null
null
null
null
UTF-8
Java
false
false
2,038
java
package com.tmh.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.util.LinkedList; import java.util.List; import org.apache.commons.beanutils.BeanUtils; import org.junit.Test; import com.tmh.bean.Clazz; import com.tmh.bean.Grade; import com.tmh.bean.Page; import com.tmh.bean.Student; import com.tmh.dao.inter.BaseDaoInter; import com.tmh.dao.inter.StudentDaoInter; import com.tmh.tools.MysqlTool; public class StudentDaoImpl extends BaseDaoImpl implements StudentDaoInter { public List<Student> getStudentList(String sql, List<Object> param) { //数据集合 List<Student> list = new LinkedList<>(); try { //获取数据库连接 Connection conn = MysqlTool.getConnection(); //预编译 PreparedStatement ps = conn.prepareStatement(sql); //设置参数 if(param != null && param.size() > 0){ for(int i = 0;i < param.size();i++){ ps.setObject(i+1, param.get(i)); } } //执行sql语句 ResultSet rs = ps.executeQuery(); //获取元数据 ResultSetMetaData meta = rs.getMetaData(); //遍历结果集 while(rs.next()){ //创建对象 Student stu = new Student(); //遍历每个字段 for(int i=1;i <= meta.getColumnCount();i++){ String field = meta.getColumnName(i); BeanUtils.setProperty(stu, field, rs.getObject(field)); } //查询班级 Clazz clazz = (Clazz) getObject(Clazz.class, "SELECT * FROM clazz WHERE id=?", new Object[]{stu.getClazzid()}); //查询年级 Grade grade = (Grade) getObject(Grade.class, "SELECT * FROM grade WHERE id=?", new Object[]{stu.getGradeid()}); //添加 stu.setClazz(clazz); stu.setGrade(grade); //添加到集合 list.add(stu); } //关闭连接 MysqlTool.closeConnection(); MysqlTool.close(ps); MysqlTool.close(rs); } catch (Exception e) { e.printStackTrace(); } return list; } }
bb80f38f1d6d6b5b8f891ca2ad9ec3ea4b696511
2302cb5a6a8c59e55848d62d772982c16748e16f
/students/soft1714080902209/HR管理系统/app/src/main/java/edu/hzuapps/androidlabs/Soft1714080902209_Reg.java
569a48d2d442a27041c12e8eccd2861fbcc0d86f
[]
no_license
anceker/android-labs-2019
7ad34f8b6792ad509ada625beeadbfc220074679
ff5ab315cfe4198c2ac57b2218074ff37c5cb0f2
refs/heads/master
2020-05-04T08:13:58.060047
2019-04-21T06:39:34
2019-04-21T06:39:34
179,042,578
1
0
null
2019-04-02T09:20:58
2019-04-02T09:20:57
null
UTF-8
Java
false
false
1,639
java
package edu.hzuapps.androidlabs; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Soft1714080902209_Reg extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.soft1714080902209_reg); Reg_RegButton=(Button)findViewById(R.id.Main_Reg); Reg_RegButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String username=((EditText)findViewById(R.id.UserName_TextEdit)).getText().toString(); String password=((EditText)findViewById(R.id.Passcode_TextEdit)).getText().toString(); if(username.equals("") && password.equals("")){ Toast.makeText(Soft1714080902209_Reg.this,"请输入账号密码",Toast.LENGTH_SHORT).show(); }else { dbhelper = new Soft1714080902209_UPSQL(Soft1714080902209_Reg.this); db = dbhelper.getReadableDatabase(); db.execSQL("insert into username (name,password) values(?,?)",new String[]{username,password}); Toast.makeText(Soft1714080902209_Reg.this,"注册成功",Toast.LENGTH_SHORT).show(); } } }); } private Button Reg_RegButton; private Soft1714080902209_UPSQL dbhelper; private SQLiteDatabase db; }
006fee844dfeeac8cfeee5bd04cc6c1623e1109b
57e9721a045a1a5e127bb1ed061095170b706f23
/Priya.java
f814c77f49f67c7b10227fcf06d3b4e139a6da89
[]
no_license
ashraf-kabir/Java-Basic-Practices
5fd19b875995761bd528e0c135fb0e08e91d09d8
74bdabfc9aeb23639706063c27c2c1913f958a1d
refs/heads/master
2020-04-23T07:01:48.805424
2019-11-03T17:09:41
2019-11-03T17:09:41
170,994,289
0
0
null
null
null
null
UTF-8
Java
false
false
147
java
public class Priya { public static void main(String[] args) { for (;;) { System.out.println("Priya"); } } }
50e5d15b43ee0c58d5bfe5f3d3f10d12d38b5845
701980910117b797b5f7ca5a61a7262ccbc3ee7b
/core/src/main/java/com/matthewmitchell/peercoinj/protocols/payments/package-info.java
dcd505349f807a5e4ef8c9c00a364a191e9ac69d
[ "Apache-2.0" ]
permissive
MatthewLM/peercoinj
c76f356e8cfa5b0cdc133a3bc91df867468e9c28
c385a2347dfad73fa8959362c115970b62e0e8de
refs/heads/master
2023-04-06T19:27:20.008332
2023-03-20T16:07:05
2023-03-20T16:07:05
22,102,786
11
30
null
2015-07-27T16:57:10
2014-07-22T12:19:41
Java
UTF-8
Java
false
false
207
java
/** * The BIP70 payment protocol wraps Bitcoin transactions and adds various useful features like memos, refund addresses * and authentication. */ package com.matthewmitchell.peercoinj.protocols.payments;
b80584438fc4ccd7051e2384f62c1fb023ec268c
9be67fa88a962c18f56a1d26ca2b6553c60e57a8
/app/src/main/java/com/example/fragment/ItemModel.java
03b592c080345e3d35ee956247d66ec01b63f8df
[]
no_license
Romifd20/lesson_2_2
61f6eeac5eb78609086dde9f90e446afea314f93
7c87d78ac0a018b2c957960e3197b8702dcec5ae
refs/heads/master
2023-04-03T05:45:47.361180
2021-04-13T16:10:43
2021-04-13T16:10:43
357,614,102
0
0
null
null
null
null
UTF-8
Java
false
false
776
java
package com.example.fragment; import android.widget.TextView; import java.io.Serializable; public class ItemModel implements Serializable { private String titleTitle, lastText; private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitleTitle() { return titleTitle; } public void setTitleTitle(String titleTitle) { this.titleTitle = titleTitle; } public String getLastText() { return lastText; } public void setLastText(String lastText) { this.lastText = lastText; } public ItemModel(String titleTitle, String lastText) { this.titleTitle = titleTitle; this.lastText = lastText; } }
7a8cae66b4c7cd2bfdbfbee2b7e5a57e37405373
1728b057967f2d21e43417b99b01874c081306cd
/src/main/java/uz/controllers/Keyboard.java
4ab68f661bc3324afc17acc0830e2a51cc9a4d5c
[]
no_license
sam6699/Shop-master
43f4afa3d5f1ddd5e49d814c3fb4deb322a546ae
48f431df613b782046ef62210dca927ba0776652
refs/heads/master
2022-12-27T20:58:52.649981
2019-08-11T16:07:26
2019-08-11T16:07:26
201,784,561
0
0
null
2022-12-16T01:53:48
2019-08-11T15:50:13
Java
UTF-8
Java
false
false
11,687
java
package uz.controllers; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.stage.Stage; import uz.print.Print; import uz.print.PrintModel; import java.math.BigDecimal; import java.net.URL; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; public class Keyboard implements Initializable { @FXML private Button exitBtn; @FXML private Button one; @FXML private Button two; @FXML private Button three; @FXML private Button four; @FXML private Button five; @FXML private Button six; @FXML private Button seven; @FXML private Button eight; @FXML private Button nine; @FXML private Button zero; @FXML private Button one1; @FXML private Button two1; @FXML private Button three1; @FXML private Button four1; @FXML private Button five1; @FXML private Button six1; @FXML private Button seven1; @FXML private Button eight1; @FXML private Button nine1; @FXML private Button zero1; @FXML private Button zero2; @FXML private Button zero3; @FXML private Button zero4; @FXML private Button zero5; @FXML private Button back; @FXML private Button back1; @FXML private Button purchase; @FXML private TextField cash; @FXML private TextField card; @FXML private Label pays; @FXML private Label pays1; @FXML private Label pays2; @FXML private Label toPurchase; private String cashValue; private String cardValue; private int selectedInput=0; @Override public void initialize(URL location, ResourceBundle resources) { toPurchase.setText(Controller.instance.getSumma()+""); initInputs(); initDigits(); initDigits1(); initBack(); initConfirm(); initExit(); } private void initInputs(){ card.setOnMouseClicked(event -> { selectedInput=2; if (card.getText().equals("0")) card.setText(""); }); card.focusedProperty().addListener((observable, oldValue, newValue) -> { if (newValue){ selectedInput=2; if (card.getText().equals("0")) card.setText(""); }else{ if (card.getText().equals("")) card.setText("0"); } }); cash.setOnMouseClicked(event -> { selectedInput=1; if (cash.getText().equals("0")) cash.setText(""); }); cash.focusedProperty().addListener((observable, oldValue, newValue) -> { if (newValue){ selectedInput=1; if (cash.getText().equals("0")) cash.setText(""); }else{ if (cash.getText().equals("")) cash.setText("0"); } }); } private void calculate(int number){ if (cash.getText().equals("0")) cash.setText(""); if (selectedInput==1){ cash.setText(cash.getText()+number); }else if (selectedInput==2){ selectedInput=1; cash.setText(number+""); }else if (selectedInput==0){ selectedInput=1; cash.setText(number+""); } pays.setText(cash.getText()); int p = Integer.parseInt(pays.getText()); int p2 = Integer.parseInt(toPurchase.getText()); int p1=p2-p; pays1.setText(p1+""); card.setText(pays1.getText()); } private void calculate2(int number){ if (card.getText().equals("0")) card.setText(""); if (selectedInput==2){ card.setText(card.getText()+number); }else if (selectedInput==1){ selectedInput=2; card.setText(number+""); }else if (selectedInput==0){ selectedInput=2; card.setText(number+""); } pays1.setText(card.getText()); int p1 = Integer.parseInt(pays1.getText()); int p2 = Integer.parseInt(toPurchase.getText()); int p=p2-p1; pays.setText(p+""); cash.setText(pays.getText()); } private void calcZeroCash(int number){ if(number==3){ if (cash.getText().charAt(0)>'0'){ cash.setText(cash.getText()+"000"); pays.setText(cash.getText()); int r = Integer.parseInt(cash.getText()); int rr=Integer.parseInt(toPurchase.getText()); card.setText(rr-r+""); pays1.setText(card.getText()); } } if (number==2){ if (cash.getText().charAt(0)>'0'){ cash.setText(cash.getText()+"00"); pays.setText(cash.getText()); int r = Integer.parseInt(cash.getText()); int rr = Integer.parseInt(toPurchase.getText()); card.setText(rr-r+""); pays1.setText(card.getText()); } } } private void calcZeroCard(int number){ if(number==3){ if (card.getText().charAt(0)>'0'){ card.setText(card.getText()+"000"); pays1.setText(card.getText()); int r = Integer.parseInt(card.getText()); int rr = Integer.parseInt(toPurchase.getText()); cash.setText(rr-r+""); pays.setText(cash.getText()); } } if (number==2){ if (card.getText().charAt(0)>'0'){ card.setText(card.getText()+"00"); pays1.setText(card.getText()); int r = Integer.parseInt(card.getText()); int rr = Integer.parseInt(toPurchase.getText()); cash.setText(rr-r+""); pays.setText(cash.getText()); } } } private void initDigits(){ one.setOnMouseClicked(event -> { calculate(1); }); two.setOnMouseClicked(event -> { calculate(2); }); three.setOnMouseClicked(event -> { calculate(3); }); four.setOnMouseClicked(event -> { calculate(4); }); five.setOnMouseClicked(event -> { calculate(5); }); six.setOnMouseClicked(event -> { calculate(6); }); seven.setOnMouseClicked(event -> { calculate(7); }); eight.setOnMouseClicked(event -> { calculate(8); }); nine.setOnMouseClicked(event -> { calculate(9); }); zero.setOnMouseClicked(event -> { calculate(0); }); zero2.setOnMouseClicked(event -> { calcZeroCash(2); }); zero3.setOnMouseClicked(event -> { calcZeroCash(3); }); } private void initDigits1(){ one1.setOnMouseClicked(event -> { calculate2(1); }); two1.setOnMouseClicked(event -> { calculate2(2); }); three1.setOnMouseClicked(event -> { calculate2(3); }); four1.setOnMouseClicked(event -> { calculate2(4); }); five1.setOnMouseClicked(event -> { calculate2(5); }); six1.setOnMouseClicked(event -> { calculate2(6); }); seven1.setOnMouseClicked(event -> { calculate2(7); }); eight1.setOnMouseClicked(event -> { calculate2(8); }); nine1.setOnMouseClicked(event -> { calculate2(9); }); zero1.setOnMouseClicked(event -> { calculate2(0); }); zero4.setOnMouseClicked(event -> { calcZeroCard(2); }); zero5.setOnMouseClicked(event -> { calcZeroCard(3); }); } private void initBack(){ String temp="./resources/img/back.png"; back.setId("back-btn"); back.setOnMouseClicked(event -> { selectedInput=1; if (cash.getText().length()==1){ if (cash.getText().charAt(0)!='0'){ card.setText(toPurchase.getText()); pays1.setText(toPurchase.getText()); cash.setText("0"); } }else { cashValue = cash.getText(0,cash.getText().length()-1); cash.setText(cashValue); int rr = Integer.parseInt(cash.getText()); int r = Integer.parseInt(toPurchase.getText()); card.setText(r-rr+""); pays1.setText(card.getText()); pays.setText(cash.getText()); } }); back1.setId("back-btn"); back1.setOnMouseClicked(event -> { selectedInput=2; if (card.getText().length()==1){ if (card.getText().charAt(0)!='0'){ cash.setText(toPurchase.getText()); pays.setText(toPurchase.getText()); card.setText("0"); } }else { cardValue=card.getText(0,card.getText().length()-1); card.setText(cardValue); int rr = Integer.parseInt(card.getText()); int r = Integer.parseInt(toPurchase.getText()); cash.setText(r-rr+""); pays.setText(cash.getText()); pays1.setText(card.getText()); } }); } private void initConfirm(){ purchase.setOnMouseClicked(event -> { DecimalFormat format = new DecimalFormat("0.#####"); List<PrintModel> list = new ArrayList<>(); for(int i=0;i<Controller.list.size();i++){ PrintModel printModel = new PrintModel(); printModel.setId(i+1); printModel.setName(Controller.list.get(i).getName()); printModel.setDimension(Controller.list.get(i).getMeasureType()); printModel.setMeasureType(Controller.list.get(i).getMeasureType()); printModel.setQuantity(format.format(Controller.list.get(i).getQuantity())); int fun = Integer.parseInt(Controller.list.get(i).getTotal_price().toString()); printModel.setSumma(fun); printModel.setPrice(new BigDecimal(format.format(Controller.list.get(i).getTotal_quantity()))); printModel.setJami(new BigDecimal(toPurchase.getText())); list.add(printModel); } Controller.instance.prepareToPurchase(Integer.parseInt(cash.getText()),Integer.parseInt(card.getText()),null); Print print = new Print(list); Stage stage = (Stage)((Button)(event).getSource()).getScene().getWindow(); stage.close(); Controller.instance.getUpdate(); }); } private void initExit(){ exitBtn.setOnMouseClicked(event -> { Stage stage = (Stage)((Button)event.getSource()).getScene().getWindow(); stage.close(); }); } }
a453553c2bf72217cd190f192d519f558b42b780
dbec52bb53d8276e9175e4fe27038f6a12d35b5b
/com/taobao/tomcat/digester/ServerListenerSetNextRule.java
9c97f46c990c2f81c244c75b5d556b3bcaaafabf
[]
no_license
dingjun84/taobao-tomcat-catalina
78f5727c221c8e32b7c037202d4fdb2919c8f54f
46ad54aac50b6441943363e0e8de100edaa3f767
refs/heads/master
2021-01-23T12:57:03.276977
2016-06-05T14:09:45
2016-06-05T14:09:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,041
java
package com.taobao.tomcat.digester; import org.apache.catalina.LifecycleListener; import org.apache.tomcat.util.IntrospectionUtils; import org.apache.tomcat.util.digester.Digester; import org.apache.tomcat.util.digester.SetNextRule; public class ServerListenerSetNextRule extends SetNextRule { public ServerListenerSetNextRule(String methodName, String paramType) { super(methodName, paramType); } public void end(String namespace, String name) throws Exception { Object child = this.digester.peek(0); if ((child instanceof LifecycleListener)) { Object parent = this.digester.peek(1); IntrospectionUtils.callMethod1(parent, this.methodName, child, this.paramType, this.digester.getClassLoader()); } } } /* Location: D:\F\阿里云架构开发\taobao-tomcat-7.0.59\taobao-tomcat-7.0.59\lib\catalina.jar!\com\taobao\tomcat\digester\ServerListenerSetNextRule.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
a37719d508204cfcb07d2a4481fc1f5181e0fed1
28a7ad687e83e4e8c1b46e280acdba97ab56f3e3
/src/MMGenerator.java
6dca4a73ce19da445d433e9d468fbfade0efb729
[]
no_license
ToraKaji/NumGen
c16285cc61b1a3f761036ac47903a49ad15080ce
592ed0ae8ffb61c790c9bee9f6d7b1164795350d
refs/heads/master
2020-04-02T10:40:08.814017
2018-10-23T15:08:23
2018-10-23T15:08:23
154,349,176
0
0
null
null
null
null
UTF-8
Java
false
false
984
java
package edu.cnm.deepdive; import java.util.Arrays; import java.util.Random; import java.util.stream.IntStream; public class MMGenerator implements Generator { private static final int POOL_UPPER_LIMIT = 70; private static final int BONUS_UPPER_LIMIT = 25; private static final int POOL_PICK_SIZE = 5; private Random rng; private int[] pool; public MMGenerator(Random rng) { this.rng = rng; pool = IntStream.rangeClosed(1, POOL_UPPER_LIMIT).toArray(); } @Override public int[] generate() { int[] pick = new int[POOL_PICK_SIZE + 1]; for (int target = pool.length - 1; target >= pool.length - POOL_PICK_SIZE; target--) { int source = rng.nextInt(target + 1); int temp = pool[target]; pool[target] = pool[source]; pool[source] = temp; pick[pool.length - 1 - target] = pool[target]; } pick[POOL_PICK_SIZE] = 1 + rng.nextInt(BONUS_UPPER_LIMIT); Arrays.sort(pick, 0, POOL_PICK_SIZE); return pick; } }
2330f040235e5dd11d1730b5ed9e2bafd7129b6b
b2f517a674528795273648a4b3f5211f1df60eaa
/summer-db/src/main/java/cn/cerc/db/mysql/MysqlConnection.java
5b93a102e207cae42a3db91a22e0434449bf5be5
[]
permissive
15218057878/summer-server-1
07c15d7fba28af97ce68a7f4d78d0f0284fce860
fc1e8d410843821df550591ec2df9d04b5cf2fed
refs/heads/main
2023-04-06T19:15:05.827271
2021-03-11T01:18:59
2021-03-11T01:18:59
355,827,435
0
0
Apache-2.0
2021-04-08T08:41:33
2021-04-08T08:41:33
null
UTF-8
Java
false
false
1,631
java
package cn.cerc.db.mysql; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class MysqlConnection extends SqlConnection { // IHandle中识别码 public static final String sessionId = "sqlSession"; // Properties中识别码 public static final String rds_site = "rds.site"; public static final String rds_database = "rds.database"; public static final String rds_username = "rds.username"; public static final String rds_password = "rds.password"; public static String dataSource = "dataSource"; private String database; @Override public String getClientId() { return sessionId; } @Override protected String getConnectUrl() { String host = config.getProperty(MysqlConnection.rds_site, "127.0.0.1:3306"); database = config.getProperty(MysqlConnection.rds_database, "appdb"); user = config.getProperty(MysqlConnection.rds_username, "appdb_user"); pwd = config.getProperty(MysqlConnection.rds_password, "appdb_password"); if (host == null || user == null || pwd == null || database == null) { throw new RuntimeException("mysql connection error"); } return String.format("jdbc:mysql://%s/%s?useSSL=false&autoReconnect=true&autoCommit=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai", host, database); } public String getDatabase() { return this.database; } }
e67749edab4f596efba2e1f8de97e625081904ac
61a6276c304c2793bbfa08338e878dfcc85615ec
/src/datastruct/interfaces/Strategy.java
c38328add004c17d20b704464cea3b1dc91cc452
[]
no_license
chmodke/DataStruct
8224bb013b29f972ccaab80da96d6858b53c706c
59407921a9173af8b280a3d2c9ba22b8857ad47e
refs/heads/master
2021-01-12T14:53:58.060684
2016-08-05T10:45:56
2016-08-05T10:45:56
64,824,349
0
0
null
null
null
null
UTF-8
Java
false
false
473
java
package datastruct.interfaces; /** * 元素比较接口 * @author KeHao * */ public interface Strategy{ /** * 比较两个元素是否相同 * @param o1 元素1 * @param o2 元素2 * @return true 相同 false 不相同 */ public boolean equal(Object o1,Object o2); /** * @param o1 元素1 * @param o2 元素2 * @return 如果o1<o2,返回-1;如果o1=o2,返回0;如果o1=o2,返回1 */ public int compare(Object o1,Object o2); }
e53f7f01e3952cb292671d2be7664a2c4e13ef73
938a19bfd0a636890543d0ef082ecc1096694c6f
/PlayerPanel.java
526e874c1dde87870a597ac929a8e2ddada4f9a5
[]
no_license
ACzapor/Blackjack
239cba6b30a3e2ea048cd5f122fe8f795a250adc
e1e1c2b328cdb0d25132da8c52873d80475f4990
refs/heads/master
2020-09-14T18:08:58.380868
2019-11-21T15:56:03
2019-11-21T15:56:03
223,197,582
1
0
null
null
null
null
UTF-8
Java
false
false
866
java
package BlackJack; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; @SuppressWarnings("serial") public class PlayerPanel extends JPanel { private JLabel textLabel = new JLabel(); private JLabel winnerLabel = new JLabel(); private final Color backgroundColor = Color.white; public PlayerPanel(int w, int h) { setPreferredSize(new Dimension(w,h)); setBackground(backgroundColor); setBorder(new EmptyBorder(10, 10, 10, 10)); setLayout(new BorderLayout()); add(textLabel, BorderLayout.NORTH); add(winnerLabel, BorderLayout.SOUTH); } public void setText(String text) { textLabel.setText(text); } public void setWinnerLabelText(String text) { winnerLabel.setText(text); } }
4692b6bbd24546b7593e5054083a5313ca50a300
979bfc766cf2b73db2fc714667b8652a2d6dcacf
/Projects/Connecture - Completed/src/com/connecture/performance/pages/stateadvantage/YourInformationPage.java
7f2b23094a79245cfccedd1e27c16620dad04017
[]
no_license
messaoudi-mounir/AvanticaPC
936536c00fd287638fb43bdce9a67c039aa8e68c
1c1ab806d63ecca0ce898676a273d4f951608239
refs/heads/master
2020-06-17T07:45:46.092223
2017-07-27T19:46:22
2017-07-27T19:46:22
195,850,038
1
0
null
2019-07-08T16:32:45
2019-07-08T16:32:44
null
UTF-8
Java
false
false
1,480
java
package com.connecture.performance.pages.stateadvantage; import org.apache.log.Logger; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import com.connecture.performance.pages.BasePage; public class YourInformationPage extends BasePage { public YourInformationPage(WebDriver driver){ super (driver); } public static YourInformationPage getPage(WebDriver driver, Logger logHandler) { YourInformationPage page = PageFactory.initElements(driver, YourInformationPage.class); page.setLogHandler(logHandler); return page; } @FindBy (xpath="//a[@class = 'buttonNext']") public WebElement ContinueButton; public void checkContinueButtonClickable(){ logInfo("Checking Continue Button to be clickable"); WebDriverWait wait = new WebDriverWait(driver, timeOut); wait.until(ExpectedConditions.visibilityOf(ContinueButton)); wait.until(ExpectedConditions.elementToBeClickable(ContinueButton)); logInfo("Continue button is clickable now"); } public ConfirmationAndSignaturePage goToConfirmationAndSignaturePage(){ logInfo("Clicking Continue Button..."); ContinueButton.click(); logInfo("Continue button clicked..."); return ConfirmationAndSignaturePage.getPage(driver, logHandler); } }
0655d422a384bf625057071fd5d7f1880066d873
9b2711551d39bdb83c14b341e8c021d41c170eaf
/app/src/main/java/com/petzm/training/module/player/view/tipsview/NetChangeView.java
276d14b273a526129829722a951161e29c2958ca
[]
no_license
P79N6A/train
c83d2766e99384a138cc94734caef508166a1f5d
3f1f139a4aead427c4b01381ba61b660502d612c
refs/heads/master
2020-04-12T18:26:05.333245
2018-12-21T06:56:36
2018-12-21T06:56:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,175
java
package com.petzm.training.module.player.view.tipsview; import android.content.Context; import android.content.res.Resources; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import com.petzm.training.R; import com.petzm.training.module.player.theme.ITheme; import com.petzm.training.module.player.widget.AliyunVodPlayerView; /* * Copyright (C) 2010-2018 Alibaba Group Holding Limited. */ /** * 网络变化提示对话框。当网络由wifi变为4g的时候会显示。 */ public class NetChangeView extends RelativeLayout implements ITheme { //结束播放的按钮 private TextView mStopPlayBtn; //界面上的操作按钮事件监听 private OnNetChangeClickListener mOnNetChangeClickListener = null; public NetChangeView(Context context) { super(context); init(); } public NetChangeView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public NetChangeView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { LayoutInflater inflater = (LayoutInflater) getContext() .getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); Resources resources = getContext().getResources(); View view = inflater.inflate(R.layout.alivc_dialog_netchange, null); int viewWidth = resources.getDimensionPixelSize(R.dimen.alivc_dialog_netchange_width); int viewHeight = resources.getDimensionPixelSize(R.dimen.alivc_dialog_netchange_height); LayoutParams params = new LayoutParams(viewWidth, viewHeight); addView(view, params); //继续播放的点击事件 view.findViewById(R.id.continue_play).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mOnNetChangeClickListener != null) { mOnNetChangeClickListener.onContinuePlay(); } } }); //停止播放的点击事件 mStopPlayBtn = (TextView) view.findViewById(R.id.stop_play); mStopPlayBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mOnNetChangeClickListener != null) { mOnNetChangeClickListener.onStopPlay(); } } }); } @Override public void setTheme(AliyunVodPlayerView.Theme theme) { //更新停止播放按钮的主题 if (theme == AliyunVodPlayerView.Theme.Blue) { mStopPlayBtn.setBackgroundResource(R.drawable.alivc_rr_bg_blue); mStopPlayBtn.setTextColor(ContextCompat.getColor(getContext(), R.color.alivc_blue)); } else if (theme == AliyunVodPlayerView.Theme.Green) { mStopPlayBtn.setBackgroundResource(R.drawable.alivc_rr_bg_green); mStopPlayBtn.setTextColor(ContextCompat.getColor(getContext(), R.color.alivc_green)); } else if (theme == AliyunVodPlayerView.Theme.Orange) { mStopPlayBtn.setBackgroundResource(R.drawable.alivc_rr_bg_orange); mStopPlayBtn.setTextColor(ContextCompat.getColor(getContext(), R.color.alivc_orange)); } else if (theme == AliyunVodPlayerView.Theme.Red) { mStopPlayBtn.setBackgroundResource(R.drawable.alivc_rr_bg_red); mStopPlayBtn.setTextColor(ContextCompat.getColor(getContext(), R.color.alivc_red)); } } /** * 界面中的点击事件 */ public interface OnNetChangeClickListener { /** * 继续播放 */ void onContinuePlay(); /** * 停止播放 */ void onStopPlay(); } /** * 设置界面的点击监听 * * @param l 点击监听 */ public void setOnNetChangeClickListener(OnNetChangeClickListener l) { mOnNetChangeClickListener = l; } }
ef947e6562d068fb06aa2bf0f2fe44cf7b6d5f4f
c1d0ff85ed003d3efdd3c6a1dea5e4b89dbd52ea
/src/main/java/admin/service/face/AdminService.java
7f3460c2453e99085a540fb81fa3b0532be6ad0b
[]
no_license
mkang415/Final_Diary_1.0.2
55f172964b6c628f38fbd8556c63be0d3188a3ef
9060110bf15dcf20d2c58ec28105a9a322d82e85
refs/heads/master
2022-11-21T06:11:06.719294
2019-07-12T10:05:07
2019-07-12T10:05:07
196,549,930
0
0
null
null
null
null
UTF-8
Java
false
false
99
java
package admin.service.face; import dto.Board; public interface AdminService { Board test(); }
bdc2358217b792de745cd9b2aa9e98a8f6986ec8
124e1ed661612964a8b4a37fb799791cc3205835
/src/test/java/testbaseclass/WebDriverFactory.java
4f14bc1708bfaf5752a2e6ebebce3f9bf5f2fb25
[]
no_license
amgainpramod/nopCommerceV0.1_Cucumber
cd37585513e31681ca86d85d82c0854822db7f00
4ff1e3b95b9b1ed78476a5f96222b0f00383edff
refs/heads/master
2023-05-08T02:24:19.328293
2021-05-30T12:34:51
2021-05-30T12:34:51
372,204,826
0
0
null
null
null
null
UTF-8
Java
false
false
4,998
java
package testbaseclass; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.ie.InternetExplorerOptions; import org.openqa.selenium.remote.CapabilityType; import utilities.Constants; import java.util.concurrent.TimeUnit; public class WebDriverFactory { private static WebDriver driver = null; //Singleton //Only one instance of the class can exist at a time private static final WebDriverFactory instance = new WebDriverFactory(); private WebDriverFactory() { } public static WebDriverFactory getInstance() { return instance; } private static ThreadLocal<WebDriver> threadedDriver = new ThreadLocal<>(); private static ThreadLocal<String> threadedBrowser = new ThreadLocal<>(); public WebDriver getDriver(String browser) { if(driver != null){ return driver; } setDriver(browser); threadedBrowser.set(browser); if (threadedDriver.get() == null) { try { if (browser.equalsIgnoreCase(Constants.FIREFOX)) { FirefoxOptions options = setFirefoxOptions(); driver = new FirefoxDriver(options); threadedDriver.set(driver); } if (browser.equalsIgnoreCase(Constants.CHROME)) { ChromeOptions options = setChromeOptions(); driver = new ChromeDriver(options); threadedDriver.set(driver); } if (browser.equalsIgnoreCase(Constants.IExplorer)) { InternetExplorerOptions options = setInternetExplorerOptions(); driver = new InternetExplorerDriver(options); threadedDriver.set(driver); } } catch (Exception e) { e.printStackTrace(); } threadedDriver.get().manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); threadedDriver.get().manage().window().maximize(); } return threadedDriver.get(); } public String getBrowser(){ return threadedBrowser.get(); } public void quitDriver() { threadedDriver.get().quit(); threadedDriver.set(null); driver = null; } private void setDriver(String browser) { String driverPath = ""; String os = Constants.OS_NAME.toLowerCase().substring(0, 3); System.out.println("OS name from system property :: " + os); String directory = Constants.USER_DIRECTORY + Constants.DRIVERS_DIRECTORY; String driverKey = ""; String driverValue = ""; if (browser.equalsIgnoreCase(Constants.FIREFOX)) { driverKey = Constants.GECKO_DRIVER_KEY; driverValue = Constants.GECKO_DRIVER_VALUE; } else if (browser.equalsIgnoreCase(Constants.CHROME)) { driverKey = Constants.CHROME_DRIVER_KEY; driverValue = Constants.CHROME_DRIVER_VALUE; } else if(browser.equalsIgnoreCase(Constants.IExplorer)){ driverKey = Constants.IE_DRIVER_KEY; driverValue = Constants.IE_DRIVER_VALUE; } else { System.out.println("Browser type not supported"); } driverPath = directory + driverValue + (os.equals("win") ? ".exe" : ""); System.out.println("Driver Binary :: " + driverPath); System.setProperty(driverKey, driverPath); } private ChromeOptions setChromeOptions(){ ChromeOptions options = new ChromeOptions(); //This is to disable info-bar at the start of every test // options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation")); // options.setExperimentalOption("useAutomationExtension", false); return options; } private FirefoxOptions setFirefoxOptions(){ FirefoxOptions options = new FirefoxOptions(); options.setCapability(CapabilityType.HAS_NATIVE_EVENTS, false); return options; } private InternetExplorerOptions setInternetExplorerOptions(){ InternetExplorerOptions options = new InternetExplorerOptions(); options.setCapability(InternetExplorerDriver.NATIVE_EVENTS, false); options.setCapability(InternetExplorerDriver.ENABLE_PERSISTENT_HOVERING, false); options.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, false); options.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true); options.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, false); options.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, false); return options; } }
13258c8ee43572c3bc72c166dbb8b3402c235b61
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/14/14_47f59ae611bbbafdf611698feb6f91db9d332eb3/LuperLoginActivity/14_47f59ae611bbbafdf611698feb6f91db9d332eb3_LuperLoginActivity_t.java
37abd36558ff0f9f3e14efb86e5a2a397c3f23a8
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
6,307
java
package com.teamluper.luper; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import android.widget.TextView; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.facebook.Response; import com.facebook.Session; import com.facebook.SessionState; import com.facebook.UiLifecycleHelper; import com.facebook.Request; import com.facebook.model.GraphUser; import com.googlecode.androidannotations.annotations.Background; import com.googlecode.androidannotations.annotations.EActivity; import com.googlecode.androidannotations.annotations.UiThread; import com.googlecode.androidannotations.annotations.rest.RestService; import com.teamluper.luper.rest.LuperRestClient; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Activity which displays a login screen to the user, offering registration as * well. */ @EActivity public class LuperLoginActivity extends SherlockFragmentActivity { ViewPager mViewPager; TabsAdapter mTabsAdapter; // Facebook Login Session private Session session; private String accessToken; protected void loadActiveSession() { session = Session.getActiveSession(); accessToken = session.getAccessToken(); } @RestService LuperRestClient restClient; private SQLiteDataSource dataSource; @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode,resultCode,data); Session.getActiveSession().onActivityResult(this,requestCode,resultCode,data); } // How Luper should behave when user logs into or out of facebook protected void onSessionStateChange(Session sesh, SessionState seshState, Exception e) { if (seshState.isOpened()) { /** usr logged in **/ // Create new request to facebook API Request.executeMeRequestAsync(session, new Request.GraphUserCallback() { // callback after Graph API response with user object @Override public void onCompleted(GraphUser user, Response response) { String email = ""; //if (user != null) { // TextView welcome = (TextView) findViewById(R.id.welcome); // welcome.setText("Hello " + user.getName() + "!"); // } } }); } else if (seshState.isClosed()) { // usr logged out } else { // probably shouldn't be here } } private Session.StatusCallback callback = new Session.StatusCallback() { @Override public void call(Session sesh, SessionState seshState, Exception e) { onSessionStateChange(sesh,seshState,e); } }; private UiLifecycleHelper uiHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // enable tabs in the ActionBar final ActionBar bar = getSupportActionBar(); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); bar.setTitle(R.string.login_title); bar.setDisplayHomeAsUpEnabled(false); // set up the ViewPager and Tabs mViewPager = new ViewPager(this); mViewPager.setId(R.id.tabcontentpager); setContentView(mViewPager); mTabsAdapter = new TabsAdapter(this, mViewPager); mTabsAdapter.addTab(bar.newTab().setText(""+"Log In"), TabLoginFragment_.class, null); mTabsAdapter.addTab(bar.newTab().setText(""+"Register"), TabRegisterFragment_.class, null); // connect to the database dataSource = new SQLiteDataSource(this); dataSource.open(); // UI handler - Facebook login uiHelper = new UiLifecycleHelper(this,callback); uiHelper.onCreate(savedInstanceState); } @Override protected void onStop() { if(dataSource.isOpen()) dataSource.close(); super.onStop(); } @Override public void onDestroy() { super.onDestroy(); uiHelper.onDestroy(); } @Override protected void onResume() { if(!dataSource.isOpen()) dataSource.open(); session = Session.getActiveSession(); super.onResume(); uiHelper.onResume(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); uiHelper.onSaveInstanceState(outState); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.luper_login, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.action_forgot_password) { Intent intent = new Intent(this, LuperForgotPasswordActivity_.class); startActivity(intent); } return true; } public SQLiteDataSource getDataSource() { return dataSource; } @Background public void skipLogin(View v) { User dummyUser = dataSource.getUserById(1); dataSource.setActiveUser(dummyUser); startMainActivity(); } @UiThread public void startMainActivity() { Intent intent = new Intent(this, LuperMainActivity_.class); startActivity(intent); } @UiThread public void prefillLoginForm(String email) { getSupportActionBar().setSelectedNavigationItem(0); // switch to login tab EditText emailField = (EditText) findViewById(R.id.login_email); EditText passwordField = (EditText) findViewById(R.id.login_password); emailField.setText(email); passwordField.setText(""); passwordField.requestFocus(); } public static String sha1(String input) throws NoSuchAlgorithmException { MessageDigest mDigest = MessageDigest.getInstance("SHA1"); byte[] result = mDigest.digest(input.getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < result.length; i++) { sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } }
814e80f602738271f73b60ce35858ea429dd7c46
a773a12e019864b5f0e1fe01ee6f6b47d8bac0c4
/src/main/java/com/guilin/java/designpattern/strategy/s1/ConcreteStrategy1.java
aff713e8b72bbadff7da5dc822aaf713c2245a36
[]
no_license
dongguilin/JavaTest
cba4bf2630065b1b8f1b682c3698fc7eb8fcdad6
71e4d1afd6e5fc6d837ef538d8ad00148297b729
refs/heads/master
2022-05-02T10:18:09.556459
2022-03-14T07:44:24
2022-03-14T07:44:24
40,651,915
3
1
null
2022-03-14T08:11:05
2015-08-13T10:00:57
Java
UTF-8
Java
false
false
283
java
package com.guilin.java.designpattern.strategy.s1; /** * Created by T57 on 2016/9/11 0011. * 具体策略角色 */ public class ConcreteStrategy1 implements Strategy { @Override public void doString() { System.out.println("具体策略1的运算法则"); } }
bd48b0c539a494de12296b52a369aa5ebd857e03
098d0b1ed92cfb0442a5debe6af47089d0fc4e8f
/src/main/java/com/fufulong/quarzbean/QuarzbeanJob.java
c9b977332c6a76933860e24ca66903d245021361
[]
no_license
fufulong/quartz_demo
8b9454e41c6c3f0f91b2e5e9e65e33b2401b5f97
647a9c4ec83ec6a62f24c974344152fe89a9d842
refs/heads/master
2022-12-23T07:12:20.960381
2019-12-29T11:42:12
2019-12-29T11:42:12
230,742,087
1
0
null
2022-12-16T06:44:53
2019-12-29T11:41:44
Java
UTF-8
Java
false
false
2,878
java
package com.fufulong.quarzbean; import com.fufulong.service.UserService; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.Trigger; import org.quartz.impl.triggers.CronTriggerImpl; import org.quartz.impl.triggers.SimpleTriggerImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.quartz.QuartzJobBean; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component public class QuarzbeanJob extends QuartzJobBean { @Autowired private UserService userService; private Integer timeout; private Integer age; public void setTimeout(Integer timeout){ this.timeout = timeout; } public void setAge(Integer age){ this.age = age; } /** * 重写的任务逻辑方法 * @param jobExecutionContext * @throws JobExecutionException */ @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { if (userService == null){ System.out.println("引入的userService == null"); }else{ userService.query(); } SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /*Calendar calendar = jobExecutionContext.getCalendar(); System.out.println("calendar:" + calendar.getDescription());*/ String fireInstanceId = jobExecutionContext.getFireInstanceId(); System.out.println("fireInstanceId\t" + fireInstanceId); Date fireTime = jobExecutionContext.getFireTime(); System.out.println("fireTime\t" + format.format(fireTime)); Integer timeout = jobExecutionContext.getJobDetail().getJobDataMap().getIntegerFromString("timeout"); Integer age = jobExecutionContext.getJobDetail().getJobDataMap().getIntegerFromString("age"); System.out.println("jobdateMap中的key= 'timeout',value = " + timeout + ", key='age' 的 value = " + age); int refireCount = jobExecutionContext.getRefireCount(); System.out.println("refireCount: " + refireCount ); Trigger trigger = jobExecutionContext.getTrigger(); System.out.println("trigger的getDescription: "+ trigger.getDescription() + ",trigger的key: " + trigger.getKey().getName() ); if (trigger instanceof CronTriggerImpl){ System.out.println("QuarzbeanJob 的触发器是 cron触发器, cron expression = " +((CronTriggerImpl) trigger).getCronExpression()); }else if (trigger instanceof SimpleTriggerImpl){ System.out.println("QuarzbeanJob 的触发器是 simpleTrigger,repeatInterval = " + ((SimpleTriggerImpl)trigger).getRepeatInterval()); } System.out.println("当前时间\t" + format.format(new Date())); } }
4dac57a27393b99b36e5cb0d39bc3e1ed7c2ef35
5ca998ddcf2bdfc6a3483c923101d8ce2f329116
/src/api/org/jzy3d/chart/factories/ChartComponentFactory.java
0316c1a0537a88abcafaf3688d56ae860b2ee279
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
fendres/jzy3d-api
2a42d5e43e232f751cbcf66d2fe04c2f139bc58f
de0b6646e54a6dd52d76b4397396cd48653e33bc
refs/heads/master
2021-01-18T10:38:06.537200
2013-02-13T21:37:45
2013-02-13T21:37:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,248
java
package org.jzy3d.chart.factories; import java.awt.Rectangle; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLProfile; import org.jzy3d.bridge.IFrame; import org.jzy3d.bridge.awt.FrameAWT; import org.jzy3d.bridge.swing.FrameSwing; import org.jzy3d.chart.Chart; import org.jzy3d.chart.ChartScene; import org.jzy3d.chart.ChartView; import org.jzy3d.chart.controllers.keyboard.camera.CameraKeyController; import org.jzy3d.chart.controllers.keyboard.camera.CameraKeyControllerNewt; import org.jzy3d.chart.controllers.keyboard.camera.ICameraKeyController; import org.jzy3d.chart.controllers.keyboard.screenshot.IScreenshotKeyController; import org.jzy3d.chart.controllers.keyboard.screenshot.IScreenshotKeyController.IScreenshotEventListener; import org.jzy3d.chart.controllers.keyboard.screenshot.ScreenshotKeyController; import org.jzy3d.chart.controllers.keyboard.screenshot.ScreenshotKeyControllerNewt; import org.jzy3d.chart.controllers.mouse.camera.CameraMouseController; import org.jzy3d.chart.controllers.mouse.camera.CameraMouseControllerNewt; import org.jzy3d.chart.controllers.mouse.camera.ICameraMouseController; import org.jzy3d.maths.BoundingBox3d; import org.jzy3d.maths.Coord3d; import org.jzy3d.maths.Utils; import org.jzy3d.plot3d.primitives.axes.AxeBox; import org.jzy3d.plot3d.primitives.axes.IAxe; import org.jzy3d.plot3d.rendering.canvas.CanvasAWT; import org.jzy3d.plot3d.rendering.canvas.CanvasNewt; import org.jzy3d.plot3d.rendering.canvas.CanvasSwing; import org.jzy3d.plot3d.rendering.canvas.ICanvas; import org.jzy3d.plot3d.rendering.canvas.OffscreenCanvas; import org.jzy3d.plot3d.rendering.canvas.Quality; import org.jzy3d.plot3d.rendering.ordering.AbstractOrderingStrategy; import org.jzy3d.plot3d.rendering.ordering.BarycentreOrderingStrategy; import org.jzy3d.plot3d.rendering.scene.Scene; import org.jzy3d.plot3d.rendering.view.Camera; import org.jzy3d.plot3d.rendering.view.Renderer3d; import org.jzy3d.plot3d.rendering.view.View; public class ChartComponentFactory implements IChartComponentFactory { /* (non-Javadoc) * @see org.jzy3d.factories.IChartComponentFactory#newScene(boolean) */ @Override public ChartScene newScene(boolean sort){ return new ChartScene(sort, this); } /* (non-Javadoc) * @see org.jzy3d.factories.IChartComponentFactory#newView(org.jzy3d.plot3d.rendering.scene.Scene, org.jzy3d.plot3d.rendering.canvas.ICanvas, org.jzy3d.plot3d.rendering.canvas.Quality) */ @Override public View newView(Scene scene, ICanvas canvas, Quality quality){ return new ChartView(this, scene, canvas, quality); } /* (non-Javadoc) * @see org.jzy3d.factories.IChartComponentFactory#newCamera(org.jzy3d.maths.Coord3d) */ @Override public Camera newCamera(Coord3d center) { return new Camera(center); } /* (non-Javadoc) * @see org.jzy3d.factories.IChartComponentFactory#newAxe(org.jzy3d.maths.BoundingBox3d, org.jzy3d.plot3d.rendering.view.View) */ @Override public IAxe newAxe(BoundingBox3d box, View view) { AxeBox axe = new AxeBox(box); axe.setView(view); return axe; } /* (non-Javadoc) * @see org.jzy3d.factories.IChartComponentFactory#newRenderer(org.jzy3d.plot3d.rendering.view.View, boolean, boolean) */ @Override public Renderer3d newRenderer(View view, boolean traceGL, boolean debugGL){ return new Renderer3d(view, traceGL, debugGL); } /* (non-Javadoc) * @see org.jzy3d.factories.IChartComponentFactory#newOrderingStrategy() */ @Override public AbstractOrderingStrategy newOrderingStrategy() { return new BarycentreOrderingStrategy(); } /* (non-Javadoc) * @see org.jzy3d.factories.IChartComponentFactory#newCanvas(org.jzy3d.plot3d.rendering.scene.Scene, org.jzy3d.plot3d.rendering.canvas.Quality, java.lang.String, javax.media.opengl.GLCapabilities) */ @Override public ICanvas newCanvas(Scene scene, Quality quality, String chartType, GLCapabilities capabilities){ if("awt".compareTo(chartType)==0) return new CanvasAWT(this, scene, quality, capabilities); else if("swing".compareTo(chartType)==0) return new CanvasSwing(this, scene, quality, capabilities); else if("newt".compareTo(chartType)==0) return new CanvasNewt(this, scene, quality, capabilities); else if(chartType.startsWith("offscreen")){ Pattern pattern = Pattern.compile("offscreen,(\\d+),(\\d+)"); Matcher matcher = pattern.matcher(chartType); if(matcher.matches()){ int width = Integer.parseInt(matcher.group(1)); int height = Integer.parseInt(matcher.group(2)); return new OffscreenCanvas(this, scene, quality, GLProfile.getDefault(), width, height); } else return new OffscreenCanvas(this, scene, quality, GLProfile.getDefault(), 500, 500); } else throw new RuntimeException("unknown chart type:" + chartType); } @Override public ICameraMouseController newMouseController(Chart chart){ ICameraMouseController mouse = null; if(!chart.getWindowingToolkit().equals("newt")) mouse = new CameraMouseController(chart); else mouse = new CameraMouseControllerNewt(chart); return mouse; } @Override public IScreenshotKeyController newScreenshotKeyController(Chart chart){ // trigger screenshot on 's' letter String file = SCREENSHOT_FOLDER + "capture-" + Utils.dat2str(new Date()) + ".png"; IScreenshotKeyController screenshot; if(!chart.getWindowingToolkit().equals("newt")) screenshot = new ScreenshotKeyController(chart, file); else screenshot = new ScreenshotKeyControllerNewt(chart, file); screenshot.addListener(new IScreenshotEventListener() { @Override public void failedScreenshot(String file, Exception e) { System.out.println("Failed to save screenshot:"); e.printStackTrace(); } @Override public void doneScreenshot(String file) { System.out.println("Screenshot: " + file); } }); return screenshot; } public static String SCREENSHOT_FOLDER = "./data/screenshots/"; @Override public ICameraKeyController newKeyController(Chart chart) { ICameraKeyController key = null; if(!chart.getWindowingToolkit().equals("newt")) key = new CameraKeyController(chart); else key = new CameraKeyControllerNewt(chart); return key; } public IFrame newFrame(Chart chart, Rectangle bounds, String title){ Object canvas = chart.getCanvas(); if(canvas instanceof CanvasAWT) return new FrameAWT(chart, bounds, title); // FrameSWT works as well else if(canvas instanceof CanvasNewt) return new FrameAWT(chart, bounds, title, "[Newt]"); // FrameSWT works as well else if(canvas instanceof CanvasSwing) return new FrameSwing(chart, bounds, title); else throw new RuntimeException("No default frame could be found for the given Chart canvas: " + canvas.getClass()); } }
51ec1e282b8f7b4fb51b87bba9ce5e2105865867
77eabfb69056924f2a471cc47670d3c9314e2531
/eInventory/src/sprint2/US10_PhysicalInventoryRawItemLongDescription.java
4eca9e6c26111b71f623aa62d1b1d7c82cc83552
[]
no_license
QsrSoftAutomation/QsrSoftAutomation
5f915ad70beba94cf3ed3ee62bf7f64e874fd6da
a09d80572daf5157176493015d395e00c57c2c4b
refs/heads/master
2021-01-10T16:08:28.299400
2016-01-22T16:49:08
2016-01-22T16:49:08
50,193,687
0
0
null
null
null
null
UTF-8
Java
false
false
4,922
java
package sprint2; import java.io.IOException; import jxl.read.biff.BiffException; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.Test; import common.Base; import common.GlobalVariable; import common.ReadTestData; import common.Reporter; import eInventoryPageClasses.HomePage; import eInventoryPageClasses.PhysicalInventoryPage; public class US10_PhysicalInventoryRawItemLongDescription extends AbstractTest { String TestCaseName = ""; // TC1971: Verify that the user is able to view long description corresponding to the WRIN number for the correct Raw Item. @Test() public void sprint2_US10_TC1971() throws RowsExceededException, BiffException, WriteException, IOException, InterruptedException { /** Variable Section : **/ PhysicalInventoryPage physicalInventoryPage; TestCaseName = "sprint2_US10_TC1971"; String storeId = GlobalVariable.StoreId; String userId = GlobalVariable.userId; HSSFSheet physicalInventoryPageSheet = ReadTestData.getTestDataSheet("sprint2_US10_TC1971", "Object1"); String wrinId = ReadTestData.getTestData(physicalInventoryPageSheet, "WRINId"); String description = ReadTestData.getTestData(physicalInventoryPageSheet, "Description"); String inventoryType = ReadTestData.getTestData(physicalInventoryPageSheet, "ListType"); /***********************************/ HomePage homePage = PageFactory.initElements(driver, HomePage.class); System.out.println(TestCaseName + " START"); // Navigate to physical inventory Page >> Save a physical inventory physicalInventoryPage = homePage.selectUser(userId).selectLocation(storeId).navigateToInventoryManagement() .goToPhysicalInventoryPage().saveANewInventory(inventoryType); // Get the time for the inventory String time = physicalInventoryPage.InventoryTime_Label.getText().split("Time: ")[1]; //Click on Menu Btn homePage.Menu_DD_BT.click(); // Navigate to physical Inventory and click on the saved inventory with status "In-Progress". physicalInventoryPage.goToPhysicalInventoryPage().clickOnInProgressInventory(Base.returnTodayDate(), time); if (physicalInventoryPage.verifyWrinNumberAndDescriptionIsDisplayedForARawItem(wrinId, description)) { Reporter.reportPassResult( browser,TestCaseName, "User should be able to view long description=x corresponding to the WRIN number=y for the correct Raw Item.", "Pass"); } else { Reporter.reportTestFailure( browser,TestCaseName,TestCaseName, "User should be able to view long description=x corresponding to the WRIN number=y for the correct Raw Item.", "Fail"); AbstractTest.takeSnapShot(TestCaseName); } System.out.println(TestCaseName + " END"); } // TC1973: Verify that the user is able to view the description with mixed case. @Test() public void sprint2_US10_TC1973() throws RowsExceededException, BiffException, WriteException, IOException, InterruptedException { /** Variable Section : **/ PhysicalInventoryPage physicalInventoryPage; TestCaseName = "sprint2_US10_TC1973"; String storeId = GlobalVariable.StoreId; String userId = GlobalVariable.userId; HSSFSheet physicalInventoryPageSheet = ReadTestData.getTestDataSheet("sprint2_US10_TC1973", "Object1"); String wrinId = ReadTestData.getTestData(physicalInventoryPageSheet,"WRINId"); String description = ReadTestData.getTestData(physicalInventoryPageSheet, "Description"); String inventoryType = ReadTestData.getTestData(physicalInventoryPageSheet, "ListType"); /***********************************/ HomePage homePage = PageFactory.initElements(driver, HomePage.class); System.out.println(TestCaseName + " START"); // Navigate to physical inventory Page >> Save a physical inventory physicalInventoryPage = homePage.selectUser(userId).selectLocation(storeId).navigateToInventoryManagement() .goToPhysicalInventoryPage().saveANewInventory(inventoryType); // Get the time for the inventory String time = physicalInventoryPage.InventoryTime_Label.getText().split("Time: ")[1]; //Click on Menu Btn homePage.Menu_DD_BT.click(); // Navigate to physical Inventory and click on the saved inventory with status "In-Progress". physicalInventoryPage.goToPhysicalInventoryPage().clickOnInProgressInventory(Base.returnTodayDate(), time); if (physicalInventoryPage.verifyWrinNumberAndDescriptionIsDisplayedForARawItem(wrinId,description)) { Reporter.reportPassResult( browser,TestCaseName, "User should be able to view the description with mixed case", "Pass"); } else { Reporter.reportTestFailure( browser,TestCaseName,TestCaseName, "User should be able to view the description with mixed case", "Fail"); AbstractTest.takeSnapShot(TestCaseName); } System.out.println(TestCaseName + " END"); } }
53a964ec9391ee8a95aa922e6e317b9836f01332
2043bfd8ede5cdf585a4b53aa926bcd5262acd79
/jdbc_examples/Mainclass9.java
e52eced5f7ec899271bb473717146cf59e4c6890
[]
no_license
dreamerzeus/MyJdbcWorkSpace
69c2a70991875e843584bc24ffb26460d5fa6919
4cb181e5b5c896ed06170cf28dfe65234e9abb0b
refs/heads/master
2021-01-19T17:33:25.629751
2017-04-20T09:39:34
2017-04-20T09:39:34
88,329,547
0
0
null
null
null
null
UTF-8
Java
false
false
2,547
java
//use of callable statemnt studentupdate() package jdbc_examples; import java.io.FileReader; import java.io.IOException; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import java.sql.ResultSet; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.CallableStatement; import com.mysql.jdbc.Driver; public class Mainclass9 { public static void main(String[] args) { Connection con=null; ResultSet rs=null; CallableStatement clstm=null; PreparedStatement ps=null; try { Driver drf = new Driver(); DriverManager.registerDriver(drf); String dburl="jdbc:mysql://localhost:3306/BECM8?"; String filepath="F:/jdbc/JDBC PROGRAMS/new.properties"; FileReader reader=new FileReader(filepath); Properties pr=new Properties(); pr.load(reader); con=DriverManager.getConnection(dburl, pr); String query="call studentUpdateA(?,?,?,?)"; clstm=con.prepareCall(query); clstm.setInt(1,Integer.parseInt(args[0])); clstm.setString(2,args[1]); clstm.setString(3,args[2]); clstm.setString(4,args[3]); int count=clstm.executeUpdate(); System.out.println("row affected "+count); if(count>0) { clstm.close(); String query1="select * from student where reg_no=?"; ps=con.prepareStatement(query1); ps.setInt(1,Integer.parseInt(args[0])); rs=ps.executeQuery(); while(rs.next()) { int reg=rs.getInt("reg_no"); String first=rs.getString("first_name"); String last_name=rs.getString("last_name"); String job=rs.getString("job"); System.out.println("the registration nos is .."+reg); System.out.println("the first name is ...."+first); System.out.println("last name "+last_name); System.out.println("job "+job); System.out.println("========="); } } } catch (SQLException | IOException e) { e.printStackTrace(); } finally { { try { if(con!=null) { con.close(); } if(clstm!=null) { clstm.close(); } if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch (SQLException e) { e.printStackTrace(); } } } } }
75ecc72baf63e1d26273d03e26abac265c7655bc
b7b2be8e6f4781e356de7831549e4610edd4119d
/app/src/main/java/com/example/cleanapp/ViewHolder/TenantTaskListViewAdapter.java
661d1bcbb29c91e325c32ab16d12f8081576f88f
[]
no_license
royfa28/CleanApp
d45d83216cbd20421c33127ee5ce1ec4544c13a9
9bd0e98c83da655de3e2145b0892c7a9c835c5ec
refs/heads/master
2020-09-09T15:12:47.657426
2020-02-14T04:47:39
2020-02-14T04:47:39
221,479,188
0
0
null
null
null
null
UTF-8
Java
false
false
4,207
java
package com.example.cleanapp.ViewHolder; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import com.example.cleanapp.Fragment.TenantHomeFragment; import com.example.cleanapp.Model.TaskAssignCardModel; import com.example.cleanapp.R; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.ArrayList; public class TenantTaskListViewAdapter extends RecyclerView.Adapter<TenantTaskListViewAdapter.TenantListViewHolder> { ArrayList<TaskAssignCardModel> taskArrayList; String ownerid, houseid; Context context; public TenantTaskListViewAdapter(TenantHomeFragment mContext, ArrayList<TaskAssignCardModel> tasks, String ownerID, String houseID) { mContext = mContext; taskArrayList = tasks; ownerid = ownerID; houseid = houseID; } @NonNull @Override public TenantListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.listview_rooms, parent, false); return new TenantListViewHolder(view); } @Override public void onBindViewHolder(@NonNull TenantListViewHolder holder, int position) { String roomName = taskArrayList.get(position).getRoomName(); String room_desc = taskArrayList.get(position).getRoomDescription(); Boolean taskComplete = taskArrayList.get(position).getisDone(); String roomID = taskArrayList.get(position).getRoomID(); Log.d("Room id", roomID); holder.room_name.setText(roomName); holder.room_description.setText("Task completed: " + taskComplete.toString()); holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { context = v.getContext(); // Make a dialog box to show more detail AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(roomName + "\n\nTask to do: \n" + room_desc) .setTitle("VERIFY") .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setPositiveButton("Finish", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { taskArrayList.clear(); DatabaseReference changeStatus = FirebaseDatabase.getInstance().getReference() .child("House").child(ownerid).child(houseid).child("TaskAssign").child(roomID); changeStatus.child("isDone").setValue(true); } }); builder.show(); builder.create(); } }); } @Override public int getItemCount() { return taskArrayList.size(); } public class TenantListViewHolder extends RecyclerView.ViewHolder { public TextView room_name; public CardView cardView; public TextView room_description; public TenantListViewHolder(@NonNull View itemView) { super(itemView); room_name = (TextView) itemView.findViewById(R.id.room_name_Textview); room_description = (TextView) itemView.findViewById(R.id.room_description_TextView); cardView = (CardView) itemView.findViewById(R.id.room_cardview); } } }
fe2b1e12f266f138d9bb64ef87443ea041977e65
3d0a12a94dfc7a95769277181450e99174efe06d
/src/com/derson/pumelo/network/volley/toolbox/HttpStack.java
3efd49b41114a110a7dd019201eb953d9f0fc570
[]
no_license
gitgzw/Pumelo
9fe1ef11c9b111357b1381534361fbdbd17e786e
9f4932972dbdf2eedc9bb97f4f225ef39c470076
refs/heads/master
2021-01-13T07:31:56.558847
2015-08-10T04:01:09
2015-08-10T04:01:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,510
java
/* * Copyright (C) 2011 The Android Open Source Project * * 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.derson.pumelo.network.volley.toolbox; import com.derson.pumelo.network.volley.AuthFailureError; import com.derson.pumelo.network.volley.Request; import org.apache.http.HttpResponse; import java.io.IOException; import java.util.Map; /** * An HTTP stack abstraction. */ public interface HttpStack { /** * Performs an HTTP request with the given parameters. * * <p>A GET request is sent if request.getPostBody() == null. A POST request is sent otherwise, * and the Content-Type header is set to request.getPostBodyContentType().</p> * * @param request the request to perform * @param additionalHeaders additional headers to be sent together with * @return the HTTP response */ public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError; }
dd14ae9528abbd82a8c2d7629a520e898bfc96e1
ae211514a675219402318e51e20c2f3526098fef
/app/src/main/java/com/yeslurbags/varun/mybagapplication/model/Users.java
c079715fad036a15118644f94a6dfb4a02daf7cc
[]
no_license
varunyeslur/My-bagApplication
d16413b8a399feda2a98fff7cc4cfb0663fb173e
0f44259032035548067723e51fdaf9ba45751c1b
refs/heads/master
2021-06-13T15:55:30.351930
2020-04-09T17:43:10
2020-04-09T17:43:10
254,436,844
0
0
null
null
null
null
UTF-8
Java
false
false
734
java
package com.yeslurbags.varun.mybagapplication.model; public class Users { private String name, password, phone; public Users() { } public Users(String name, String password, String phone) { this.name = name; this.password = password; this.phone = phone; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
d8e34b5217181600cc714232db3e475bd78231f1
30445cd49f7c55b9f8aece26f6585f8c38d2209f
/shell/platform/android/io/flutter/embedding/engine/systemchannels/PlatformChannel.java
06833cbe2c225fa205e5645508da8a43db929d7e
[ "BSD-3-Clause" ]
permissive
guangbin79/engine
4c214954c444b60ecc73175e78b4faa32b9a06ca
80e9a3fc2f770e011704ba919ecaae2f71db0f15
refs/heads/master
2021-07-06T03:24:17.445622
2020-11-10T09:14:02
2020-11-10T09:14:02
185,117,684
1
3
BSD-3-Clause
2019-05-06T03:30:25
2019-05-06T03:30:25
null
UTF-8
Java
false
false
25,029
java
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.embedding.engine.systemchannels; import android.content.pm.ActivityInfo; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import io.flutter.Log; import io.flutter.embedding.engine.dart.DartExecutor; import io.flutter.plugin.common.JSONMethodCodec; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * System channel that receives requests for host platform behavior, e.g., haptic and sound effects, * system chrome configurations, and clipboard interaction. */ public class PlatformChannel { private static final String TAG = "PlatformChannel"; @NonNull public final MethodChannel channel; @Nullable private PlatformMessageHandler platformMessageHandler; @NonNull @VisibleForTesting final MethodChannel.MethodCallHandler parsingMethodCallHandler = new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) { if (platformMessageHandler == null) { // If no explicit PlatformMessageHandler has been registered then we don't // need to forward this call to an API. Return. return; } String method = call.method; Object arguments = call.arguments; Log.v(TAG, "Received '" + method + "' message."); try { switch (method) { case "SystemSound.play": try { SoundType soundType = SoundType.fromValue((String) arguments); platformMessageHandler.playSystemSound(soundType); result.success(null); } catch (NoSuchFieldException exception) { // The desired sound type does not exist. result.error("error", exception.getMessage(), null); } break; case "HapticFeedback.vibrate": try { HapticFeedbackType feedbackType = HapticFeedbackType.fromValue((String) arguments); platformMessageHandler.vibrateHapticFeedback(feedbackType); result.success(null); } catch (NoSuchFieldException exception) { // The desired feedback type does not exist. result.error("error", exception.getMessage(), null); } break; case "SystemChrome.setPreferredOrientations": try { int androidOrientation = decodeOrientations((JSONArray) arguments); platformMessageHandler.setPreferredOrientations(androidOrientation); result.success(null); } catch (JSONException | NoSuchFieldException exception) { // JSONException: One or more expected fields were either omitted or referenced an // invalid type. // NoSuchFieldException: One or more expected fields were either omitted or // referenced an invalid type. result.error("error", exception.getMessage(), null); } break; case "SystemChrome.setApplicationSwitcherDescription": try { AppSwitcherDescription description = decodeAppSwitcherDescription((JSONObject) arguments); platformMessageHandler.setApplicationSwitcherDescription(description); result.success(null); } catch (JSONException exception) { // One or more expected fields were either omitted or referenced an invalid type. result.error("error", exception.getMessage(), null); } break; case "SystemChrome.setEnabledSystemUIOverlays": try { List<SystemUiOverlay> overlays = decodeSystemUiOverlays((JSONArray) arguments); platformMessageHandler.showSystemOverlays(overlays); result.success(null); } catch (JSONException | NoSuchFieldException exception) { // JSONException: One or more expected fields were either omitted or referenced an // invalid type. // NoSuchFieldException: One or more of the overlay names are invalid. result.error("error", exception.getMessage(), null); } break; case "SystemChrome.restoreSystemUIOverlays": platformMessageHandler.restoreSystemUiOverlays(); result.success(null); break; case "SystemChrome.setSystemUIOverlayStyle": try { SystemChromeStyle systemChromeStyle = decodeSystemChromeStyle((JSONObject) arguments); platformMessageHandler.setSystemUiOverlayStyle(systemChromeStyle); result.success(null); } catch (JSONException | NoSuchFieldException exception) { // JSONException: One or more expected fields were either omitted or referenced an // invalid type. // NoSuchFieldException: One or more of the brightness names are invalid. result.error("error", exception.getMessage(), null); } break; case "SystemNavigator.pop": platformMessageHandler.popSystemNavigator(); result.success(null); break; case "Clipboard.getData": { String contentFormatName = (String) arguments; ClipboardContentFormat clipboardFormat = null; if (contentFormatName != null) { try { clipboardFormat = ClipboardContentFormat.fromValue(contentFormatName); } catch (NoSuchFieldException exception) { // An unsupported content format was requested. Return failure. result.error( "error", "No such clipboard content format: " + contentFormatName, null); } } CharSequence clipboardContent = platformMessageHandler.getClipboardData(clipboardFormat); if (clipboardContent != null) { JSONObject response = new JSONObject(); response.put("text", clipboardContent); result.success(response); } else { result.success(null); } break; } case "Clipboard.setData": { String clipboardContent = ((JSONObject) arguments).getString("text"); platformMessageHandler.setClipboardData(clipboardContent); result.success(null); break; } case "Clipboard.hasStrings": { boolean hasStrings = platformMessageHandler.clipboardHasStrings(); JSONObject response = new JSONObject(); response.put("value", hasStrings); result.success(response); break; } default: result.notImplemented(); break; } } catch (JSONException e) { result.error("error", "JSON error: " + e.getMessage(), null); } } }; /** * Constructs a {@code PlatformChannel} that connects Android to the Dart code running in {@code * dartExecutor}. * * <p>The given {@code dartExecutor} is permitted to be idle or executing code. * * <p>See {@link DartExecutor}. */ public PlatformChannel(@NonNull DartExecutor dartExecutor) { channel = new MethodChannel(dartExecutor, "flutter/platform", JSONMethodCodec.INSTANCE); channel.setMethodCallHandler(parsingMethodCallHandler); } /** * Sets the {@link PlatformMessageHandler} which receives all events and requests that are parsed * from the underlying platform channel. */ public void setPlatformMessageHandler(@Nullable PlatformMessageHandler platformMessageHandler) { this.platformMessageHandler = platformMessageHandler; } // TODO(mattcarroll): add support for IntDef annotations, then add @ScreenOrientation /** * Decodes a series of orientations to an aggregate desired orientation. * * @throws JSONException if {@code encodedOrientations} does not contain expected keys and value * types. * @throws NoSuchFieldException if any given encoded orientation is not a valid orientation name. */ private int decodeOrientations(@NonNull JSONArray encodedOrientations) throws JSONException, NoSuchFieldException { int requestedOrientation = 0x00; int firstRequestedOrientation = 0x00; for (int index = 0; index < encodedOrientations.length(); index += 1) { String encodedOrientation = encodedOrientations.getString(index); DeviceOrientation orientation = DeviceOrientation.fromValue(encodedOrientation); switch (orientation) { case PORTRAIT_UP: requestedOrientation |= 0x01; break; case PORTRAIT_DOWN: requestedOrientation |= 0x04; break; case LANDSCAPE_LEFT: requestedOrientation |= 0x02; break; case LANDSCAPE_RIGHT: requestedOrientation |= 0x08; break; } if (firstRequestedOrientation == 0x00) { firstRequestedOrientation = requestedOrientation; } } switch (requestedOrientation) { case 0x00: return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; case 0x01: return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; case 0x02: return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; case 0x04: return ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; case 0x05: return ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT; case 0x08: return ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; case 0x0a: return ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE; case 0x0b: return ActivityInfo.SCREEN_ORIENTATION_USER; case 0x0f: return ActivityInfo.SCREEN_ORIENTATION_FULL_USER; case 0x03: // portraitUp and landscapeLeft case 0x06: // portraitDown and landscapeLeft case 0x07: // portraitUp, portraitDown, and landscapeLeft case 0x09: // portraitUp and landscapeRight case 0x0c: // portraitDown and landscapeRight case 0x0d: // portraitUp, portraitDown, and landscapeRight case 0x0e: // portraitDown, landscapeLeft, and landscapeRight // Android can't describe these cases, so just default to whatever the first // specified value was. switch (firstRequestedOrientation) { case 0x01: return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; case 0x02: return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; case 0x04: return ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; case 0x08: return ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; } } // Execution should never get this far, but if it does then we default // to a portrait orientation. return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; } @NonNull private AppSwitcherDescription decodeAppSwitcherDescription( @NonNull JSONObject encodedDescription) throws JSONException { int color = encodedDescription.getInt("primaryColor"); if (color != 0) { // 0 means color isn't set, use system default color = color | 0xFF000000; // color must be opaque if set } String label = encodedDescription.getString("label"); return new AppSwitcherDescription(color, label); } /** * Decodes a list of JSON-encoded overlays to a list of {@link SystemUiOverlay}. * * @throws JSONException if {@code encodedSystemUiOverlay} does not contain expected keys and * value types. * @throws NoSuchFieldException if any of the given encoded overlay names are invalid. */ @NonNull private List<SystemUiOverlay> decodeSystemUiOverlays(@NonNull JSONArray encodedSystemUiOverlay) throws JSONException, NoSuchFieldException { List<SystemUiOverlay> overlays = new ArrayList<>(); for (int i = 0; i < encodedSystemUiOverlay.length(); ++i) { String encodedOverlay = encodedSystemUiOverlay.getString(i); SystemUiOverlay overlay = SystemUiOverlay.fromValue(encodedOverlay); switch (overlay) { case TOP_OVERLAYS: overlays.add(SystemUiOverlay.TOP_OVERLAYS); break; case BOTTOM_OVERLAYS: overlays.add(SystemUiOverlay.BOTTOM_OVERLAYS); break; } } return overlays; } /** * Decodes a JSON-encoded {@code encodedStyle} to a {@link SystemChromeStyle}. * * @throws JSONException if {@code encodedStyle} does not contain expected keys and value types. * @throws NoSuchFieldException if any provided brightness name is invalid. */ @NonNull private SystemChromeStyle decodeSystemChromeStyle(@NonNull JSONObject encodedStyle) throws JSONException, NoSuchFieldException { Brightness systemNavigationBarIconBrightness = null; // TODO(mattcarroll): add color annotation Integer systemNavigationBarColor = null; // TODO(mattcarroll): add color annotation Integer systemNavigationBarDividerColor = null; Brightness statusBarIconBrightness = null; // TODO(mattcarroll): add color annotation Integer statusBarColor = null; if (!encodedStyle.isNull("systemNavigationBarIconBrightness")) { systemNavigationBarIconBrightness = Brightness.fromValue(encodedStyle.getString("systemNavigationBarIconBrightness")); } if (!encodedStyle.isNull("systemNavigationBarColor")) { systemNavigationBarColor = encodedStyle.getInt("systemNavigationBarColor"); } if (!encodedStyle.isNull("statusBarIconBrightness")) { statusBarIconBrightness = Brightness.fromValue(encodedStyle.getString("statusBarIconBrightness")); } if (!encodedStyle.isNull("statusBarColor")) { statusBarColor = encodedStyle.getInt("statusBarColor"); } if (!encodedStyle.isNull("systemNavigationBarDividerColor")) { systemNavigationBarDividerColor = encodedStyle.getInt("systemNavigationBarDividerColor"); } return new SystemChromeStyle( statusBarColor, statusBarIconBrightness, systemNavigationBarColor, systemNavigationBarIconBrightness, systemNavigationBarDividerColor); } /** * Handler that receives platform messages sent from Flutter to Android through a given {@link * PlatformChannel}. * * <p>To register a {@code PlatformMessageHandler} with a {@link PlatformChannel}, see {@link * PlatformChannel#setPlatformMessageHandler(PlatformMessageHandler)}. */ public interface PlatformMessageHandler { /** The Flutter application would like to play the given {@code soundType}. */ void playSystemSound(@NonNull SoundType soundType); /** The Flutter application would like to play the given haptic {@code feedbackType}. */ void vibrateHapticFeedback(@NonNull HapticFeedbackType feedbackType); /** The Flutter application would like to display in the given {@code androidOrientation}. */ // TODO(mattcarroll): add @ScreenOrientation annotation void setPreferredOrientations(int androidOrientation); /** * The Flutter application would like to be displayed in Android's app switcher with the visual * representation described in the given {@code description}. * * <p>See the related Android documentation: * https://developer.android.com/guide/components/activities/recents */ void setApplicationSwitcherDescription(@NonNull AppSwitcherDescription description); /** * The Flutter application would like the Android system to display the given {@code overlays}. * * <p>{@link SystemUiOverlay#TOP_OVERLAYS} refers to system overlays such as the status bar, * while {@link SystemUiOverlay#BOTTOM_OVERLAYS} refers to system overlays such as the * back/home/recents navigation on the bottom of the screen. * * <p>An empty list of {@code overlays} should hide all system overlays. */ void showSystemOverlays(@NonNull List<SystemUiOverlay> overlays); /** * The Flutter application would like to restore the visibility of system overlays to the last * set of overlays sent via {@link #showSystemOverlays(List)}. * * <p>If {@link #showSystemOverlays(List)} has yet to be called, then a default system overlay * appearance is desired: * * <p>{@code View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN } */ void restoreSystemUiOverlays(); /** * The Flutter application would like the system chrome to present itself with the given {@code * systemUiOverlayStyle}, i.e., the given status bar and navigation bar colors and brightness. */ void setSystemUiOverlayStyle(@NonNull SystemChromeStyle systemUiOverlayStyle); /** * The Flutter application would like to pop the top item off of the Android app's navigation * back stack. */ void popSystemNavigator(); /** * The Flutter application would like to receive the current data in the clipboard and have it * returned in the given {@code format}. */ @Nullable CharSequence getClipboardData(@Nullable ClipboardContentFormat format); /** * The Flutter application would like to set the current data in the clipboard to the given * {@code text}. */ void setClipboardData(@NonNull String text); /** * The Flutter application would like to know if the clipboard currently contains a string that * can be pasted. */ boolean clipboardHasStrings(); } /** Types of sounds the Android OS can play on behalf of an application. */ public enum SoundType { CLICK("SystemSoundType.click"), ALERT("SystemSoundType.alert"); @NonNull static SoundType fromValue(@NonNull String encodedName) throws NoSuchFieldException { for (SoundType soundType : SoundType.values()) { if (soundType.encodedName.equals(encodedName)) { return soundType; } } throw new NoSuchFieldException("No such SoundType: " + encodedName); } @NonNull private final String encodedName; SoundType(@NonNull String encodedName) { this.encodedName = encodedName; } } /** The types of haptic feedback that the Android OS can generate on behalf of an application. */ public enum HapticFeedbackType { STANDARD(null), LIGHT_IMPACT("HapticFeedbackType.lightImpact"), MEDIUM_IMPACT("HapticFeedbackType.mediumImpact"), HEAVY_IMPACT("HapticFeedbackType.heavyImpact"), SELECTION_CLICK("HapticFeedbackType.selectionClick"); @NonNull static HapticFeedbackType fromValue(@Nullable String encodedName) throws NoSuchFieldException { for (HapticFeedbackType feedbackType : HapticFeedbackType.values()) { if ((feedbackType.encodedName == null && encodedName == null) || (feedbackType.encodedName != null && feedbackType.encodedName.equals(encodedName))) { return feedbackType; } } throw new NoSuchFieldException("No such HapticFeedbackType: " + encodedName); } @Nullable private final String encodedName; HapticFeedbackType(@Nullable String encodedName) { this.encodedName = encodedName; } } /** The possible desired orientations of a Flutter application. */ public enum DeviceOrientation { PORTRAIT_UP("DeviceOrientation.portraitUp"), PORTRAIT_DOWN("DeviceOrientation.portraitDown"), LANDSCAPE_LEFT("DeviceOrientation.landscapeLeft"), LANDSCAPE_RIGHT("DeviceOrientation.landscapeRight"); @NonNull static DeviceOrientation fromValue(@NonNull String encodedName) throws NoSuchFieldException { for (DeviceOrientation orientation : DeviceOrientation.values()) { if (orientation.encodedName.equals(encodedName)) { return orientation; } } throw new NoSuchFieldException("No such DeviceOrientation: " + encodedName); } @NonNull private String encodedName; DeviceOrientation(@NonNull String encodedName) { this.encodedName = encodedName; } } /** * The set of Android system UI overlays as perceived by the Flutter application. * * <p>Android includes many more overlay options and flags than what is provided by {@code * SystemUiOverlay}. Flutter only requires control over a subset of the overlays and those * overlays are represented by {@code SystemUiOverlay} values. */ public enum SystemUiOverlay { TOP_OVERLAYS("SystemUiOverlay.top"), BOTTOM_OVERLAYS("SystemUiOverlay.bottom"); @NonNull static SystemUiOverlay fromValue(@NonNull String encodedName) throws NoSuchFieldException { for (SystemUiOverlay overlay : SystemUiOverlay.values()) { if (overlay.encodedName.equals(encodedName)) { return overlay; } } throw new NoSuchFieldException("No such SystemUiOverlay: " + encodedName); } @NonNull private String encodedName; SystemUiOverlay(@NonNull String encodedName) { this.encodedName = encodedName; } } /** * The color and label of an application that appears in Android's app switcher, AKA recents * screen. */ public static class AppSwitcherDescription { // TODO(mattcarroll): add color annotation public final int color; @NonNull public final String label; public AppSwitcherDescription(int color, @NonNull String label) { this.color = color; this.label = label; } } /** The color and brightness of system chrome, e.g., status bar and system navigation bar. */ public static class SystemChromeStyle { // TODO(mattcarroll): add color annotation @Nullable public final Integer statusBarColor; @Nullable public final Brightness statusBarIconBrightness; // TODO(mattcarroll): add color annotation @Nullable public final Integer systemNavigationBarColor; @Nullable public final Brightness systemNavigationBarIconBrightness; // TODO(mattcarroll): add color annotation @Nullable public final Integer systemNavigationBarDividerColor; public SystemChromeStyle( @Nullable Integer statusBarColor, @Nullable Brightness statusBarIconBrightness, @Nullable Integer systemNavigationBarColor, @Nullable Brightness systemNavigationBarIconBrightness, @Nullable Integer systemNavigationBarDividerColor) { this.statusBarColor = statusBarColor; this.statusBarIconBrightness = statusBarIconBrightness; this.systemNavigationBarColor = systemNavigationBarColor; this.systemNavigationBarIconBrightness = systemNavigationBarIconBrightness; this.systemNavigationBarDividerColor = systemNavigationBarDividerColor; } } public enum Brightness { LIGHT("Brightness.light"), DARK("Brightness.dark"); @NonNull static Brightness fromValue(@NonNull String encodedName) throws NoSuchFieldException { for (Brightness brightness : Brightness.values()) { if (brightness.encodedName.equals(encodedName)) { return brightness; } } throw new NoSuchFieldException("No such Brightness: " + encodedName); } @NonNull private String encodedName; Brightness(@NonNull String encodedName) { this.encodedName = encodedName; } } /** Data formats of clipboard content. */ public enum ClipboardContentFormat { PLAIN_TEXT("text/plain"); @NonNull static ClipboardContentFormat fromValue(@NonNull String encodedName) throws NoSuchFieldException { for (ClipboardContentFormat format : ClipboardContentFormat.values()) { if (format.encodedName.equals(encodedName)) { return format; } } throw new NoSuchFieldException("No such ClipboardContentFormat: " + encodedName); } @NonNull private String encodedName; ClipboardContentFormat(@NonNull String encodedName) { this.encodedName = encodedName; } } }
a16a7226c13b35842b050ba8e622a8c35dcb222a
5a474f4bb0bf3981d3b282e6c028ef6b2472f170
/node-plugin/node-plugin-rcra54-outbound/src/generated/com/windsor/node/plugin/rcra54/domain/generated/GISFacilitySubmissionDataType.java
fb9625711c98b21bf7f6ec6919ad6efd82d2e3c4
[]
no_license
jhulick/opennode2-java
deaf72b954516590a38e33953e2025759c33e6ae
37618871d4124c510887acef1cd1e17228d91ab2
refs/heads/master
2021-07-12T04:48:22.245571
2017-10-11T14:20:48
2017-10-11T14:20:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,148
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.06.15 at 06:46:14 PM EDT // package com.windsor.node.plugin.rcra54.domain.generated; import java.util.ArrayList; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.jvnet.jaxb2_commons.lang.Equals; import org.jvnet.jaxb2_commons.lang.EqualsStrategy; import org.jvnet.jaxb2_commons.lang.HashCode; import org.jvnet.jaxb2_commons.lang.HashCodeStrategy; import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy; import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy; import org.jvnet.jaxb2_commons.locator.ObjectLocator; import org.jvnet.jaxb2_commons.locator.util.LocatorUtils; /** * Facility GIS submission. * * <p>Java class for GISFacilitySubmissionDataType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="GISFacilitySubmissionDataType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.exchangenetwork.net/schema/RCRA/5}HandlerID"/> * &lt;element ref="{http://www.exchangenetwork.net/schema/RCRA/5}GeographicInformation" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "GISFacilitySubmissionDataType", propOrder = { "handlerID", "geographicInformation" }) @Entity(name = "GISFacilitySubmissionDataType") @Table(name = "RCRA_GISFACSUB") @Inheritance(strategy = InheritanceType.JOINED) public class GISFacilitySubmissionDataType implements Equals, HashCode { @XmlElement(name = "HandlerID", required = true) protected String handlerID; @XmlElement(name = "GeographicInformation") protected List<GeographicInformationDataType> geographicInformation; @XmlAttribute(name = "Id") protected Long id; /** * Gets the value of the handlerID property. * * @return * possible object is * {@link String } * */ @Basic @Column(name = "HANDLERID", length = 12) public String getHandlerID() { return handlerID; } /** * Sets the value of the handlerID property. * * @param value * allowed object is * {@link String } * */ public void setHandlerID(String value) { this.handlerID = value; } /** * Gets the value of the geographicInformation property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the geographicInformation property. * * <p> * For example, to add a new item, do as follows: * <pre> * getGeographicInformation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link GeographicInformationDataType } * * */ @OneToMany(targetEntity = GeographicInformationDataType.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "GISFACSUBID") public List<GeographicInformationDataType> getGeographicInformation() { if (geographicInformation == null) { geographicInformation = new ArrayList<GeographicInformationDataType>(); } return this.geographicInformation; } /** * * */ public void setGeographicInformation(List<GeographicInformationDataType> geographicInformation) { this.geographicInformation = geographicInformation; } /** * Gets the value of the id property. * * @return * possible object is * {@link Long } * */ @Id @Column(name = "ID") @GeneratedValue(generator = "ColSequence", strategy = GenerationType.AUTO) @SequenceGenerator(name = "ColSequence", sequenceName = "COLUMN_ID_SEQUENCE", allocationSize = 1) public Long getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link Long } * */ public void setId(Long value) { this.id = value; } public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy strategy) { if (!(object instanceof GISFacilitySubmissionDataType)) { return false; } if (this == object) { return true; } final GISFacilitySubmissionDataType that = ((GISFacilitySubmissionDataType) object); { String lhsHandlerID; lhsHandlerID = this.getHandlerID(); String rhsHandlerID; rhsHandlerID = that.getHandlerID(); if (!strategy.equals(LocatorUtils.property(thisLocator, "handlerID", lhsHandlerID), LocatorUtils.property(thatLocator, "handlerID", rhsHandlerID), lhsHandlerID, rhsHandlerID)) { return false; } } { List<GeographicInformationDataType> lhsGeographicInformation; lhsGeographicInformation = (((this.geographicInformation!= null)&&(!this.geographicInformation.isEmpty()))?this.getGeographicInformation():null); List<GeographicInformationDataType> rhsGeographicInformation; rhsGeographicInformation = (((that.geographicInformation!= null)&&(!that.geographicInformation.isEmpty()))?that.getGeographicInformation():null); if (!strategy.equals(LocatorUtils.property(thisLocator, "geographicInformation", lhsGeographicInformation), LocatorUtils.property(thatLocator, "geographicInformation", rhsGeographicInformation), lhsGeographicInformation, rhsGeographicInformation)) { return false; } } return true; } public boolean equals(Object object) { final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE; return equals(null, null, object, strategy); } public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) { int currentHashCode = 1; { String theHandlerID; theHandlerID = this.getHandlerID(); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "handlerID", theHandlerID), currentHashCode, theHandlerID); } { List<GeographicInformationDataType> theGeographicInformation; theGeographicInformation = (((this.geographicInformation!= null)&&(!this.geographicInformation.isEmpty()))?this.getGeographicInformation():null); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "geographicInformation", theGeographicInformation), currentHashCode, theGeographicInformation); } return currentHashCode; } public int hashCode() { final HashCodeStrategy strategy = JAXBHashCodeStrategy.INSTANCE; return this.hashCode(null, strategy); } }
a8b7ef2f4782be2bf1230625354de6fdc259b9c7
13a226507a750228f209d823a397e2fc779d6070
/app/src/main/java/com/example/projectapp/TownAdapter.java
8b799774b7a376fdac08f478439804c69ae2fdfe
[]
no_license
AlyNaRahim/tourist-guide-app
2a61abeef52c13c1bea1837e2fd8274ae19a42d2
4734c8788f71b6acc33197396c8b04a80ac95e77
refs/heads/master
2023-02-01T10:29:15.502735
2020-12-09T22:20:52
2020-12-09T22:20:52
316,164,765
1
0
null
null
null
null
UTF-8
Java
false
false
2,291
java
package com.example.projectapp; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class TownAdapter extends RecyclerView.Adapter <TownAdapter.ViewHolder>{ private LayoutInflater layoutInflater; private List<TownCardItem> items; TownAdapter(Context context, List<TownCardItem> items){ this.layoutInflater = LayoutInflater.from(context); this.items = items; } /*HotelAdapter(List<HotelCardItem> items) { //this.layoutInflater = LayoutInflater.from(context); this.items = items; */ @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_view_towns,parent,false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder viewHolder, final int position) { final TownCardItem town = items.get(position); viewHolder.textTitle.setText(town.getTitle()); viewHolder.image.setBackgroundResource(town.getImage()); } @Override public int getItemCount() { return items.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ private TextView textTitle; private ImageView image; public ViewHolder(@NonNull View itemView) { super(itemView); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(v.getContext(),DetailActivity.class); i.putExtra("title", items.get(getAdapterPosition()).getTitle()); i.putExtra("image", items.get(getAdapterPosition()).getImage()); v.getContext().startActivity(i); } }); textTitle = itemView.findViewById(R.id.textView5); image = itemView.findViewById(R.id.view); } } }
7892b02c066a2eb88d72b6af6047aa1231d84da3
ef43ba5205c06e4e38818ede8a2fb986d35c5ed4
/automation/src/org/drait/system/boot/ApplicationBooter.java
52ca562b8d3ee7fc0efc7b1ad8eddbad58406fc2
[]
no_license
shankardeepak22/automation
dbb4aa0b1902b0f03c7451522fe37637328cd928
3d3cd04d906ff6439cb9a2de43bad3af4f73e9fa
refs/heads/master
2021-01-10T21:58:18.610091
2014-09-12T19:39:39
2014-09-12T19:39:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
989
java
/** * */ package org.drait.system.boot; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; /** * @author DEEPAK * */ public class ApplicationBooter implements WebApplicationInitializer { String[] contexts = new String[] { "classpath:automation/appContext/applicationContext.xml", "classpath:automation/appContext/root-context.xml" }; @Override public void onStartup(ServletContext container) { XmlWebApplicationContext appContext = new XmlWebApplicationContext(); appContext.setConfigLocations(contexts); ServletRegistration.Dynamic registration = container.addServlet( "automationDispatcher", new DispatcherServlet(appContext)); registration.setLoadOnStartup(1); registration.addMapping("/"); } }
ff2fcdab1fa472586db4b5687770efdef0dffd30
c71acaa4098623649bd7e8763b0ed3143b5df4c3
/saga-eventsourcing/saga-eventsourcing-api/src/test/java/com/ust/sagaeventsourcing/test/TestSagaPart.java
c3f45b7449e532da7794cb74a4c3a183898a1649
[]
no_license
Fernison/laboratory
1ec2561072d0000433bcf5dd921abc342c55a745
b8410da4b3ddecb6b5128df3706fc43326f39a25
refs/heads/master
2021-09-27T12:15:25.804921
2018-11-08T10:35:53
2018-11-08T10:35:53
117,216,692
2
3
null
null
null
null
UTF-8
Java
false
false
607
java
package com.ust.sagaeventsourcing.test; import com.ust.sagaeventsourcing.event.Eventide; import com.ust.sagaeventsourcing.saga.InitSaga; import com.ust.sagaeventsourcing.saga.SagaInitiator; public class TestSagaPart extends SagaInitiator<Eventide<TestSimpleData>,TestSimpleData> { @Override @InitSaga(application="mi app", saga="mi saga") public Eventide<TestSimpleData> initiateSaga(TestSimpleData simpleData) { TestEvent myEvent=new TestEvent("event name", simpleData); myEvent.setId_transaccion("MY ID TRANSACTION"); myEvent.setStatus("COMMITED"); return myEvent; } }
a9d5dcf914b59390de695dc1a3a52e3a96d9ee13
62c3cd403881840a3ed99d7e52ebb40cf7302eda
/src/main/java/at/austriapro/ebinterface/ubl/from/AbstractToEbInterfaceConverter.java
125bca8543591d1c95c297feb9e18bdf1da11a62
[ "Apache-2.0" ]
permissive
austriapro/ebinterface-ubl-mapping
49166bb6ea4a1e0b447829b4f43772c5ba3bd40e
2647680524cab5b4f0a69ba9518454491efc4e38
refs/heads/master
2023-08-11T12:03:32.169426
2023-08-01T11:27:53
2023-08-01T11:27:53
42,768,560
4
2
null
null
null
null
UTF-8
Java
false
false
29,746
java
/* * Copyright (c) 2010-2015 Bundesrechenzentrum GmbH - www.brz.gv.at * Copyright (c) 2015-2023 AUSTRIAPRO - www.austriapro.at * * 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 at.austriapro.ebinterface.ubl.from; import java.util.List; import java.util.Locale; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.Translatable; import com.helger.commons.error.SingleError; import com.helger.commons.error.list.ErrorList; import com.helger.commons.string.StringHelper; import com.helger.commons.text.IMultilingualText; import com.helger.commons.text.display.IHasDisplayTextWithArgs; import com.helger.commons.text.resolve.DefaultTextResolver; import com.helger.commons.text.util.TextHelper; import com.helger.peppolid.IProcessIdentifier; import at.austriapro.ebinterface.ubl.AbstractConverter; import oasis.names.specification.ubl.schema.xsd.commonaggregatecomponents_21.AllowanceChargeType; import oasis.names.specification.ubl.schema.xsd.commonaggregatecomponents_21.TaxCategoryType; import oasis.names.specification.ubl.schema.xsd.commonaggregatecomponents_21.TaxSubtotalType; import oasis.names.specification.ubl.schema.xsd.commonaggregatecomponents_21.TaxTotalType; import oasis.names.specification.ubl.schema.xsd.commonbasiccomponents_21.AllowanceChargeReasonType; import oasis.names.specification.ubl.schema.xsd.commonbasiccomponents_21.InvoiceTypeCodeType; import oasis.names.specification.ubl.schema.xsd.commonbasiccomponents_21.ProfileIDType; import oasis.names.specification.ubl.schema.xsd.commonbasiccomponents_21.UBLVersionIDType; import oasis.names.specification.ubl.schema.xsd.creditnote_21.CreditNoteType; import oasis.names.specification.ubl.schema.xsd.invoice_21.InvoiceType; /** * Base class for Peppol UBL to ebInterface converter * * @author philip */ @Immutable public abstract class AbstractToEbInterfaceConverter extends AbstractConverter { @Translatable public enum EText implements IHasDisplayTextWithArgs { OR ("oder", "or"), NO_UBL_VERSION_ID ("Die UBLVersionID fehlt. Es wird der Wert ''{0}'', ''{1}'', ''{2}'' oder ''{3}'' erwartet.", "No UBLVersionID present. It must be ''{0}'', ''{1}'', ''{2}'' or ''{3}''."), INVALID_UBL_VERSION_ID ("Die UBLVersionID ''{0}'' ist ungültig. Diese muss den Wert ''{1}'', ''{2}'', ''{3}'' oder ''{4}'' haben.", "Invalid UBLVersionID value ''{0}'' present. It must be ''{1}'', ''{2}'', ''{3}'' or ''{4}''."), NO_PROFILE_ID ("Die ProfileID fehlt", "No ProfileID present."), INVALID_PROFILE_ID ("Die ProfileID ''{0}'' ist ungültig.", "Invalid ProfileID value ''{0}'' present."), NO_CUSTOMIZATION_ID ("Die CustomizationID fehlt", "No CustomizationID present."), INVALID_CUSTOMIZATION_SCHEME_ID ("Die CustomizationID schemeID ''{0}'' ist ungültig. Diese muss den Wert ''{1}'' haben.", "Invalid CustomizationID schemeID value ''{0}'' present. It must be ''{1}''."), INVALID_CUSTOMIZATION_ID ("Die angegebene CustomizationID ''{0}'' ist ungültig. Sie wird vom angegebenen Profil nicht unterstützt.", "Invalid CustomizationID value ''{0}'' present. It is not supported by the passed profile."), NO_INVOICE_TYPECODE ("Der InvoiceTypeCode fehlt. Es wird einer der folgenden Werte erwartet: {0}", "No InvoiceTypeCode present. It must be one of the following values: {0}"), INVALID_INVOICE_TYPECODE ("Der InvoiceTypeCode ''{0}'' ist ungültig.Es wird einer der folgenden Werte erwartet: {1}", "Invalid InvoiceTypeCode value ''{0}'' present. It must be one of the following values: {1}"), ADDRESS_NO_STREET ("In der Adresse fehlt die Straße.", "Address is missing a street name."), ADDRESS_NO_CITY ("In der Adresse fehlt der Name der Stadt.", "Address is missing a city name."), ADDRESS_NO_ZIPCODE ("In der Adresse fehlt die PLZ.", "Address is missing a ZIP code."), ADDRESS_INVALID_COUNTRY ("Der angegebene Ländercode ''{0}'' ist ungültig.", "The provided country code ''{0}'' is invalid."), ADDRESS_NO_COUNTRY ("In der Adresse fehlt der Name des Landes.", "Address is missing a country."), CONTACT_NO_NAME ("Im Kontakt fehlr der Name.", "Contact is missing a name."), MULTIPLE_PARTIES ("Es sind mehrere Partynamen vorhanden - nur der erste wird verwendet.", "Multiple party names present - only the first one is used."), PARTY_NO_NAME ("Der Name der Party fehlt.", "Party name is missing."), PARTY_UNSUPPORTED_ENDPOINT ("Ignoriere den Enpunkt ''{0}'' des Typs ''{1}''.", "Ignoring endpoint ID ''{0}'' of type ''{1}''."), PARTY_UNSUPPORTED_ADDRESS_IDENTIFIER ("Ignoriere die ID ''{0}'' des Typs ''{1}''.", "Ignoring identification ''{0}'' of type ''{1}''."), ORDERLINE_REF_ID_EMPTY ("Es muss ein Wert für die Bestellpositionsnummer angegeben werden.", "A value must be provided for the order line reference ID."), ALPHANUM_ID_TYPE_CHANGE ("''{0}'' ist ein ungültiger Typ und wurde auf ''{1}'' geändert.", "''{0}'' is an invalid value and was changed to ''{1}''."), INVALID_CURRENCY_CODE ("Der angegebene Währungscode ''{0}'' ist ungültig.", "Invalid currency code ''{0}'' provided."), MISSING_INVOICE_NUMBER ("Es wurde keine Rechnungsnummer angegeben.", "No invoice number was provided."), MISSING_INVOICE_DATE ("Es wurde keine Rechnungsdatum angegeben.", "No invoice date was provided."), BILLER_VAT_MISSING ("Die UID-Nummer des Rechnungsstellers fehlt. Verwenden Sie 'ATU00000000' für österreichische Rechnungssteller an wenn keine UID-Nummer notwendig ist.", "Failed to get biller VAT identification number. Use 'ATU00000000' for Austrian invoice recipients if no VAT identification number is required."), ERB_CUSTOMER_ASSIGNED_ACCOUNTID_MISSING ("Die ID des Rechnungsstellers beim Rechnungsempfänger fehlt.", "Failed to get customer assigned account ID for supplier."), INVOICE_RECIPIENT_VAT_MISSING ("Die UID-Nummer des Rechnungsempfängers fehlt. Verwenden Sie 'ATU00000000' für österreichische Empfänger an wenn keine UID-Nummer notwendig ist.", "Failed to get invoice recipient VAT identification number. Use 'ATU00000000' for Austrian invoice recipients if no VAT identification number is required."), INVOICE_RECIPIENT_PARTY_MISSING ("Die Adressdaten des Rechnungsempfängers fehlen.", "The party information of the invoice recipient are missing."), INVOICE_RECIPIENT_PARTY_SUPPLIER_ASSIGNED_ACCOUNT_ID_MISSING ("Die ID des Auftraggebers im System des Rechnungsstellers fehlt.", "Failed to get supplier assigned account ID."), ORDERING_PARTY_VAT_MISSING ("Die UID-Nummer des Auftraggebers fehlt. Verwenden Sie 'ATU00000000' für österreichische Empfänger an wenn keine UID-Nummer notwendig ist.", "Failed to get ordering party VAT identification number. Use 'ATU00000000' for Austrian invoice recipients if no VAT identification number is required."), ORDERING_PARTY_PARTY_MISSING ("Die Adressdaten des Auftraggebers fehlen.", "The party information of the ordering party are missing."), ORDERING_PARTY_SUPPLIER_ASSIGNED_ACCOUNT_ID_MISSING ("Die ID des Auftraggebers im System des Rechnungsstellers fehlt.", "Failed to get supplier assigned account ID."), ORDER_REFERENCE_MISSING ("Die Auftragsreferenz fehlt.", "The order reference is missing."), ORDER_REFERENCE_MISSING_IGNORE_ORDER_POS ("Die Auftragsreferenz fehlt, daher kann auch die Bestellpositionsnummer nicht übernommen werden.", "The order reference is missing and therefore the order position number cannot be used."), ORDER_REFERENCE_TOO_LONG ("Die Auftragsreferenz ''{0}'' ist zu lang und wurde nach {1} Zeichen abgeschnitten.", "Order reference value ''{0}'' is too long and was cut to {1} characters."), UNSUPPORTED_TAX_SCHEME_ID ("Die Steuerschema ID ''{0}'' ist ungültig.", "The tax scheme ID ''{0}'' is invalid."), TAX_PERCENT_MISSING ("Es konnte kein Steuersatz für diese Steuerkategorie ermittelt werden.", "No tax percentage could be determined for this tax category."), TAXABLE_AMOUNT_MISSING ("Es konnte kein Steuerbasisbetrag (der Betrag auf den die Steuer anzuwenden ist) für diese Steuerkategorie ermittelt werden.", "No taxable amount could be determined for this tax category."), UNSUPPORTED_TAX_SCHEME ("Nicht unterstütztes Steuerschema gefunden: ''{0}'' und ''{1}''.", "Other tax scheme found and ignored: ''{0}'' and ''{1}''."), DETAILS_TAX_PERCENTAGE_NOT_FOUND ("Der Steuersatz der Rechnungszeile konnte nicht ermittelt werden. Verwende den Standardwert {0}%.", "Failed to resolve tax percentage for invoice line. Defaulting to {0}%."), DETAILS_INVALID_POSITION ("Die Rechnungspositionsnummer ''{0}'' ist ungültig, sie muss größer als 0 sein.", "The UBL invoice line ID ''{0}'' is invalid. The ID must be bigger than 0."), DETAILS_INVALID_POSITION_SET_TO_INDEX ("Die Rechnungspositionsnummer ''{0}'' ist nicht numerisch. Es wird der Index {1} verwendet.", "The UBL invoice line ID ''{0}'' is not numeric. Defaulting to index {1}."), DETAILS_INVALID_UNIT ("Die Rechnungszeile hat keine Mengeneinheit. Verwende den Standardwert ''{0}''.", "The UBL invoice line has no unit of measure. Defaulting to ''{0}''."), DETAILS_INVALID_QUANTITY ("Die Rechnungszeile hat keine Menge. Verwende den Standardwert ''{0}''.", "The UBL invoice line has no quantity. Defaulting to ''{0}''."), VAT_ITEM_MISSING ("Keine einzige Steuersumme gefunden", "No single VAT item found."), ALLOWANCE_CHARGE_NO_TAXRATE ("Die Steuerprozentrate für den globalen Zuschlag/Abschlag konnte nicht ermittelt werden.", "Failed to resolve tax rate percentage for global AllowanceCharge."), PAYMENTMEANS_CODE_INVALID ("Der PaymentMeansCode ''{0}'' ist ungültig. Für Überweisungen muss {1} verwenden werden und für Lastschriftverfahren {2}.", "The PaymentMeansCode ''{0}'' is invalid. For credit/debit transfer use {1} and for direct debit use {2}."), PAYMENT_ID_TOO_LONG_CUT ("Die Zahlungsreferenz ''{0}'' ist zu lang und wird abgeschnitten.", "The payment reference ''{0}'' is too long and therefore cut."), BIC_INVALID ("Der BIC ''{0}'' ist ungültig.", "The BIC ''{0}'' is invalid."), IBAN_TOO_LONG_STRIPPING ("Der IBAN ''{0}'' ist zu lang. Er wurde nach {1} Zeichen abgeschnitten.", "The IBAN ''{0}'' is too long and was cut to {1} characters."), PAYMENTMEANS_UNSUPPORTED_CHANNELCODE ("Die Zahlungsart mit dem ChannelCode ''{0}'' wird ignoriert.", "The payment means with ChannelCode ''{0}'' are ignored."), ERB_NO_PAYMENT_METHOD ("Es muss eine Zahlungsart angegeben werden.", "A payment method must be provided."), PAYMENT_DUE_DATE_ALREADY_CONTAINED ("Es wurde mehr als ein Zahlungsziel gefunden.", "More than one payment due date was found."), SETTLEMENT_PERIOD_MISSING ("Für Skontoeinträge muss mindestens ein Endedatum angegeben werden.", "Discount items require a settlement end date."), PENALTY_NOT_ALLOWED ("Strafzuschläge werden in ebInterface nicht unterstützt.", "Penalty surcharges are not supported in ebInterface."), DISCOUNT_WITHOUT_DUEDATE ("Skontoeinträge können nur angegeben werden, wenn auch ein Zahlungsziel angegeben wurde.", "Discount items can only be provided if a payment due date is present."), DELIVERY_WITHOUT_NAME ("Wenn eine Delivery/DeliveryLocation/Address angegeben ist muss auch ein Delivery/DeliveryParty/PartyName/Name angegeben werden.", "If a Delivery/DeliveryLocation/Address is present, a Delivery/DeliveryParty/PartyName/Name must also be present."), ERB_NO_DELIVERY_DATE ("Ein Lieferdatum oder ein Leistungszeitraum muss vorhanden sein.", "A Delivery/DeliveryDate or an InvoicePeriod must be present."), PREPAID_NOT_SUPPORTED ("Das Element <PrepaidAmount> wird nicht unterstützt.", "The <PrepaidAmount> element is not supported!"), MISSING_TAXCATEGORY_ID ("Das Element <ID> fehlt.", "Element <ID> is missing."), MISSING_TAXCATEGORY_ID_VALUE ("Das Element <ID> hat keinen Wert.", "Element <ID> has no value."), MISSING_TAXCATEGORY_TAXSCHEME_ID ("Das Element <ID> fehlt.", "Element <ID> is missing."), MISSING_TAXCATEGORY_TAXSCHEME_ID_VALUE ("Das Element <ID> hat keinen Wert.", "Element <ID> has no value."), EBI40_CANNOT_MIX_VAT_EXEMPTION ("In ebInterface 4.0 können nicht USt-Informationen und Steuerbefreiungen gemischt werden", "ebInterface 4.0 cannot mix VAT information and tax exemptions"); private final IMultilingualText m_aTP; EText (@Nonnull final String sDE, @Nonnull final String sEN) { m_aTP = TextHelper.create_DE_EN (sDE, sEN); } @Nullable public String getDisplayText (@Nonnull final Locale aContentLocale) { return DefaultTextResolver.getTextStatic (this, m_aTP, aContentLocale); } } public static final String EBI_GENERATING_SYSTEM_40 = "UBL 2.1 to ebInterface 4.0 converter"; public static final String EBI_GENERATING_SYSTEM_41 = "UBL 2.1 to ebInterface 4.1 converter"; public static final String EBI_GENERATING_SYSTEM_42 = "UBL 2.1 to ebInterface 4.2 converter"; public static final String EBI_GENERATING_SYSTEM_43 = "UBL 2.1 to ebInterface 4.3 converter"; public static final String EBI_GENERATING_SYSTEM_50 = "UBL 2.1 to ebInterface 5.0 converter"; public static final String EBI_GENERATING_SYSTEM_60 = "UBL 2.1 to ebInterface 6.0 converter"; public static final String EBI_GENERATING_SYSTEM_61 = "UBL 2.1 to ebInterface 6.1 converter"; protected final IToEbinterfaceSettings m_aSettings; /** * Constructor * * @param aDisplayLocale * The locale for error messages. May not be <code>null</code>. * @param aContentLocale * The locale for the created ebInterface files. May not be * <code>null</code>. * @param aSettings * Conversion settings to be used. May not be <code>null</code>. */ protected AbstractToEbInterfaceConverter (@Nonnull final Locale aDisplayLocale, @Nonnull final Locale aContentLocale, @Nonnull final IToEbinterfaceSettings aSettings) { super (aDisplayLocale, aContentLocale); m_aSettings = ValueEnforcer.notNull (aSettings, "Settings"); } @Nonnull protected static String getAllowanceChargeComment (@Nonnull final AllowanceChargeType aUBLAllowanceCharge) { // AllowanceChargeReason to Comment final StringBuilder aSB = new StringBuilder (); for (final AllowanceChargeReasonType aUBLReason : aUBLAllowanceCharge.getAllowanceChargeReason ()) { final String sReason = StringHelper.trim (aUBLReason.getValue ()); if (StringHelper.hasText (sReason)) { if (aSB.length () > 0) aSB.append ('\n'); aSB.append (sReason); } } return aSB.toString (); } /** * Check if the passed UBL invoice is transformable * * @param aUBLInvoice * The UBL invoice to check. May not be <code>null</code>. * @param aTransformationErrorList * The error list to be filled. May not be <code>null</code>. */ protected final void checkInvoiceConsistency (@Nonnull final InvoiceType aUBLInvoice, @Nonnull final ErrorList aTransformationErrorList) { // Check UBLVersionID final UBLVersionIDType aUBLVersionID = aUBLInvoice.getUBLVersionID (); if (aUBLVersionID == null) { // E.g. optional for EN invoices if (m_aSettings.isUBLVersionIDMandatory ()) aTransformationErrorList.add (SingleError.builderError () .errorFieldName ("UBLVersionID") .errorText (EText.NO_UBL_VERSION_ID.getDisplayTextWithArgs (m_aDisplayLocale, UBL_VERSION_20, UBL_VERSION_21, UBL_VERSION_22, UBL_VERSION_23)) .build ()); } else { final String sUBLVersionID = StringHelper.trim (aUBLVersionID.getValue ()); if (!UBL_VERSION_20.equals (sUBLVersionID) && !UBL_VERSION_21.equals (sUBLVersionID) && !UBL_VERSION_22.equals (sUBLVersionID) && !UBL_VERSION_23.equals (sUBLVersionID)) { aTransformationErrorList.add (SingleError.builderError () .errorFieldName ("UBLVersionID") .errorText (EText.INVALID_UBL_VERSION_ID.getDisplayTextWithArgs (m_aDisplayLocale, sUBLVersionID, UBL_VERSION_20, UBL_VERSION_21, UBL_VERSION_22, UBL_VERSION_23)) .build ()); } } // Check ProfileID final ProfileIDType aProfileID = aUBLInvoice.getProfileID (); if (aProfileID == null) { if (m_aSettings.isUBLProfileIDMandatory ()) aTransformationErrorList.add (SingleError.builderWarn () .errorFieldName ("ProfileID") .errorText (EText.NO_PROFILE_ID.getDisplayText (m_aDisplayLocale)) .build ()); } else { final String sProfileID = StringHelper.trim (aProfileID.getValue ()); final IProcessIdentifier aProcID = m_aSettings.getProfileIDResolver ().apply (sProfileID); if (aProcID == null) { aTransformationErrorList.add (SingleError.builderWarn () .errorFieldName ("ProfileID") .errorText (EText.INVALID_PROFILE_ID.getDisplayTextWithArgs (m_aDisplayLocale, sProfileID)) .build ()); } } // The CustomizationID can be basically anything - we don't care here // Invoice type code final InvoiceTypeCodeType aInvoiceTypeCode = aUBLInvoice.getInvoiceTypeCode (); if (aInvoiceTypeCode == null) { // None present aTransformationErrorList.add (SingleError.builderWarn () .errorFieldName ("InvoiceTypeCode") .errorText (EText.NO_INVOICE_TYPECODE.getDisplayTextWithArgs (m_aDisplayLocale, StringHelper.getImploded (", ", INVOICE_TYPE_CODES))) .build ()); } else { // If one is present, it must match final String sInvoiceTypeCode = StringHelper.trim (aInvoiceTypeCode.getValue ()); if (!INVOICE_TYPE_CODES.contains (sInvoiceTypeCode)) { aTransformationErrorList.add (SingleError.builderError () .errorFieldName ("InvoiceTypeCode") .errorText (EText.INVALID_INVOICE_TYPECODE.getDisplayTextWithArgs (m_aDisplayLocale, sInvoiceTypeCode, StringHelper.getImploded (", ", INVOICE_TYPE_CODES))) .build ()); } } } /** * Check if the passed UBL invoice is transformable * * @param aUBLCreditNote * The UBL invoice to check. May not be <code>null</code>. * @param aTransformationErrorList * The error list to be filled. May not be <code>null</code>. */ protected final void checkCreditNoteConsistency (@Nonnull final CreditNoteType aUBLCreditNote, @Nonnull final ErrorList aTransformationErrorList) { // Check UBLVersionID final UBLVersionIDType aUBLVersionID = aUBLCreditNote.getUBLVersionID (); if (aUBLVersionID == null) { // For EN invoices if (m_aSettings.isUBLVersionIDMandatory ()) aTransformationErrorList.add (SingleError.builderError () .errorFieldName ("UBLVersionID") .errorText (EText.NO_UBL_VERSION_ID.getDisplayTextWithArgs (m_aDisplayLocale, UBL_VERSION_20, UBL_VERSION_21, UBL_VERSION_22, UBL_VERSION_23)) .build ()); } else { final String sUBLVersionID = StringHelper.trim (aUBLVersionID.getValue ()); if (!UBL_VERSION_20.equals (sUBLVersionID) && !UBL_VERSION_21.equals (sUBLVersionID) && !UBL_VERSION_22.equals (sUBLVersionID) && !UBL_VERSION_23.equals (sUBLVersionID)) { aTransformationErrorList.add (SingleError.builderError () .errorFieldName ("UBLVersionID") .errorText (EText.INVALID_UBL_VERSION_ID.getDisplayTextWithArgs (m_aDisplayLocale, sUBLVersionID, UBL_VERSION_20, UBL_VERSION_21, UBL_VERSION_22, UBL_VERSION_23)) .build ()); } } // Check ProfileID final ProfileIDType aProfileID = aUBLCreditNote.getProfileID (); if (aProfileID == null) { if (m_aSettings.isUBLProfileIDMandatory ()) aTransformationErrorList.add (SingleError.builderWarn () .errorFieldName ("ProfileID") .errorText (EText.NO_PROFILE_ID.getDisplayText (m_aDisplayLocale)) .build ()); } else { final String sProfileID = StringHelper.trim (aProfileID.getValue ()); final IProcessIdentifier aProcID = m_aSettings.getProfileIDResolver ().apply (sProfileID); if (aProcID == null) { aTransformationErrorList.add (SingleError.builderWarn () .errorFieldName ("ProfileID") .errorText (EText.INVALID_PROFILE_ID.getDisplayTextWithArgs (m_aDisplayLocale, sProfileID)) .build ()); } } // The CustomizationID can be basically anything - we don't care here } protected static final boolean isTaxExemptionCategoryID (@Nullable final String sUBLTaxCategoryID) { // https://www.unece.org/fileadmin/DAM/trade/untdid/d16b/tred/tred5305.htm // AE = VAT Reverse Charge // E = Exempt from tax // O = Services outside scope of tax return "AE".equals (sUBLTaxCategoryID) || "E".equals (sUBLTaxCategoryID) || "O".equals (sUBLTaxCategoryID); } protected static boolean isVATSchemeID (final String sScheme) { // Peppol if (SUPPORTED_TAX_SCHEME_ID.equals (sScheme)) return true; // EN invoices if ("VA".equals (sScheme)) return true; return false; } @Nullable protected static TaxCategoryType findTaxCategory (@Nonnull final List <TaxTotalType> aUBLTaxTotals) { // No direct tax category -> check if it is somewhere in the tax total for (final TaxTotalType aUBLTaxTotal : aUBLTaxTotals) { for (final TaxSubtotalType aUBLTaxSubTotal : aUBLTaxTotal.getTaxSubtotal ()) { // Only handle VAT items if (isVATSchemeID (aUBLTaxSubTotal.getTaxCategory ().getTaxScheme ().getIDValue ())) { // We found one -> just use it return aUBLTaxSubTotal.getTaxCategory (); } } } return null; } /** * Get a string in the form * [string][sep][string][sep][string][or][last-string]. So the last and the * second last entries are separated by " or " whereas the other entries are * separated by the provided separator. * * @param sSep * Separator to use. May not be <code>null</code>. * @param aValues * Values to be combined. * @return The combined string. Never <code>null</code>. */ @Nonnull protected final String getOrString (@Nonnull final String sSep, @Nullable final String... aValues) { final StringBuilder aSB = new StringBuilder (); if (aValues != null) { final int nSecondLast = aSB.length () - 2; for (int i = 0; i < aValues.length; ++i) { if (i > 0) { if (i == nSecondLast) aSB.append (EText.OR.getDisplayText (m_aDisplayLocale)); else aSB.append (sSep); } aSB.append (aValues[i]); } } return aSB.toString (); } protected static boolean isUniversalBankTransaction (@Nullable final String sPaymentMeansCode) { // 30 = Credit transfer // 31 = Debit transfer // 42 = Payment to bank account // 58 = SEPA credit transfer return "30".equals (sPaymentMeansCode) || "31".equals (sPaymentMeansCode) || "42".equals (sPaymentMeansCode) || "58".equals (sPaymentMeansCode); } protected static boolean isDirectDebit (@Nullable final String sPaymentMeansCode) { // 49 = Direct debit return "49".equals (sPaymentMeansCode); } protected static boolean isSEPADirectDebit (@Nullable final String sPaymentMeansCode) { // 59 = SEPA direct debit return "59".equals (sPaymentMeansCode); } protected static boolean isIBAN (@Nullable final String sPaymentChannelCode) { // null/empty for standard Peppol BIS return StringHelper.hasNoText (sPaymentChannelCode) || PAYMENT_CHANNEL_CODE_IBAN.equals (sPaymentChannelCode); } protected static boolean isBIC (@Nullable final String sScheme) { return StringHelper.hasNoText (sScheme) || SCHEME_BIC.equalsIgnoreCase (sScheme); } }
cd68dc56c530471fa60d5e049765954a98c9192c
c4d8d3eae30ad0452c6e4c286a9e61b9894807ba
/volleydongnao/src/main/java/com/example/administrator/volleydongnao/http/download/enums/DownloadStopMode.java
8e2897228af7363db0e21c66434b1647b4f871eb
[]
no_license
keeponZhang/DongNaoSystemArchitect
8b79e2e5e4bfd7a63921ef1a816ad1c000fe85d2
13d6888bffe69d74ab74c17eb064c25eded23097
refs/heads/master
2020-05-05T11:24:54.173863
2019-05-26T16:17:25
2019-05-26T16:17:25
179,988,471
0
0
null
null
null
null
UTF-8
Java
false
false
883
java
package com.example.administrator.volleydongnao.http.download.enums; /** * Created by Administrator on 2017/1/17 0017. */ public enum DownloadStopMode { /** * 后台根据下载优先级调度自动停止下载任务 */ auto(0), /** * 手动停止下载任务 */ hand(1); DownloadStopMode(Integer value) { this.value = value; } /** * 值 */ private Integer value; public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } public static DownloadStopMode getInstance(int value) { for (DownloadStopMode mode : DownloadStopMode.values()) { if (mode.getValue() == value) { return mode; } } return DownloadStopMode.auto; } }
0f12990db23ff0db5d52a7f5bd7ae10652a9a2d8
1259ea795e4d44d59977dd337c7b7d04d72bd061
/src/com/DesignPattern/facade/package-info.java
bbbc38f31f16e983ddf44441918c3238e4d60f41
[]
no_license
sophistcn/designPattern
c51f98a0ecfaf06f225a6eeacd884b3fc56ed613
3e8b685893056bf39a5923283cfc23cd73e76ac5
refs/heads/master
2021-01-21T13:11:49.646461
2016-04-29T14:40:07
2016-04-29T14:40:07
49,003,979
0
0
null
null
null
null
UTF-8
Java
false
false
88
java
/** * */ /** * @author Administrator * */ package com.DesignPattern.facade;
676dcac014e1a0021dc2216a8a0b62126893f963
723db10ca7a0b99683c2ff1e00b0775f8f0c3daa
/validator-web/src/main/java/no/difi/vefa/validator/controller/HomeController.java
f611434a4ebb374e5cfc693afb6c1bbcdc5f50cd
[]
no_license
tengvig/vefa-validator
1a296aa54375224998c0f935cbea34870ef9e20f
7ba75c6ca7482d2e21d26b2add7fe9627e4b18c8
refs/heads/master
2020-12-25T20:31:20.393631
2016-01-04T14:56:42
2016-01-04T14:56:42
49,002,037
0
0
null
2016-01-04T14:29:27
2016-01-04T14:29:26
null
UTF-8
Java
false
false
1,545
java
package no.difi.vefa.validator.controller; import no.difi.vefa.validator.service.PiwikService; import no.difi.vefa.validator.service.ValidatorService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; 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.multipart.MultipartFile; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.zip.GZIPInputStream; @Controller @RequestMapping("/") public class HomeController { @Autowired private ValidatorService validatorService; @Autowired private PiwikService piwikService; @RequestMapping public String view(ModelMap modelMap) { modelMap.put("packages", validatorService.getPackages()); piwikService.update(modelMap); return "home"; } @RequestMapping(method = RequestMethod.POST) public String upload(@RequestParam("file") MultipartFile file) throws Exception { InputStream inputStream = new ByteArrayInputStream(file.getBytes()); if ("application/x-gzip".equals(file.getContentType())) inputStream = new GZIPInputStream(inputStream); String identifier = validatorService.validateWorkspace(inputStream); return "redirect:/v/" + identifier; } }
d241207b195a612088827d1df780f42bf734274e
d0f4ed921d35fbf0b499872e1bfdc1562a5207d3
/src/main/java/com/ywsoftware/oa/modules/sys/domain/PaginatedFilter.java
6e9e65bd7bbfa580ed86ea7c7b891369d74897f6
[]
no_license
XAlison/redcat-manage-service
41dda2385768acecee3e90f48676bd05169d4c16
7464b07cd8cac3cd50040f7539fd02368163333d
refs/heads/master
2020-04-06T22:14:32.284291
2018-11-22T07:27:38
2018-11-22T07:27:38
157,829,235
0
0
null
null
null
null
UTF-8
Java
false
false
1,442
java
package com.ywsoftware.oa.modules.sys.domain; import java.util.HashMap; import java.util.Map; public class PaginatedFilter { private int index; private int size; private String sort; private String order; private Map<String, String> filters; public PaginatedFilter() { index = 0; size = 10; filters = new HashMap<>(); } public int getIndex() { return index; } public void setIndex(int index) { this.index = index > 0 ? index - 1 : index; } public int getStart() { return getIndex() * getSize(); } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public String getSort() { return sort; } public void setSort(String sort) { this.sort = sort; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } public Map<String, String> getFilters() { return filters; } public void setFilters(Map<String, String> filters) { this.filters = filters; } public boolean containsFilter(String key) { return filters.containsKey(key); } public String getFilter(String key) { return filters.get(key); } public void setFilter(String key, String value) { filters.put(key, value); } }
[ "s123456" ]
s123456
3d8f005374f9eee0a9cd6ab76597e05f5ebd7b89
e06b2253a56377d9c76255a7833a8eb32abf20ad
/src/main/java/com/mingsoft/cms/parser/impl/ArticleIdParser.java
024db6e568fa6e0293355938b8f0303df23ce8d9
[ "MIT" ]
permissive
tom110/MyMcms
0e7a19bb7dca96c06132e4e520609ed6bc99bee7
ad57678cdb8eac21856df9e7f4338bfed732d8b3
refs/heads/master
2020-06-30T23:38:26.260482
2018-10-09T05:50:55
2018-10-09T05:50:55
74,343,526
0
0
null
null
null
null
UTF-8
Java
false
false
1,930
java
/** The MIT License (MIT) * Copyright (c) 2016 铭飞科技(mingsoft.net) * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mingsoft.cms.parser.impl; import com.mingsoft.parser.IParser; /** * 内容标题(单标签) * 文章内容标签 * {ms:field.title/} * @author 成卫雄 * QQ:330216230 * 技术支持:景德镇铭飞科技 * 官网:www.ming-soft.com */ public class ArticleIdParser extends IParser { /** * 文章标题标签 */ private final static String ARTICLE_TITLE_FIELD="\\{ms:field.id/\\}"; /** * 构造标签的属性 * @param htmlContent原HTML代码 * @param newContent替换的内容 */ public ArticleIdParser(String htmlContent,String newContent){ super.htmlCotent = htmlContent; super.newCotent = newContent; } @Override public String parse() { // TODO Auto-generated method stub return super.replaceAll(ARTICLE_TITLE_FIELD); } }
f4b6f99c8be53bf95e14524409b2550bff874168
b584b1837e523cd7f297c7568191b65a822252cf
/medium/Count-Complete-Tree-Nodes_medium/Solution.java
c0017ca544ce25c549a9801b2aab50658f96ec73
[]
no_license
wanglei828/leetcode
cc6dbda00c9277fa2be87bf4bc5a0de89a41a8b6
cfacf3bdbf1e18b656b698a81028f40061a78340
refs/heads/master
2022-05-27T14:12:41.643526
2022-05-23T00:27:38
2022-05-23T00:27:38
61,846,401
1
0
null
2016-07-30T06:31:48
2016-06-24T00:56:30
Java
UTF-8
Java
false
false
1,307
java
/* Given a complete binary tree, count the number of nodes. Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int countNodes(TreeNode root) { if(root == null) return 0; int left = leftHeight(root.left); int right = rightHeight(root.right); if(left == right) { return (1<<(left+1)) -1; } else { return countNodes(root.left) + countNodes(root.right) + 1; } } private int leftHeight(TreeNode root) { if(root == null) return 0; int h=1; while(root.left != null) { h++; root = root.left; } return h; } private int rightHeight(TreeNode root) { if(root == null) return 0; int h=1; while(root.right != null) { h++; root = root.right; } return h; } }
7bc1a4f3c55d5b2018431cc20d7178038648d1b5
07338fc736932b07dddab132df375d3112257559
/src/com/lyy/entity/Fenye.java
016e2d0d5ed11425c279b30f947e81960b50db2a
[]
no_license
X-Peace/green
803a7f64b489527f35e849cd7c972b267acbf034
bbb6c24fbcfc3e4c3efde4826509c21fd5a72ff9
refs/heads/master
2021-07-15T04:52:14.774032
2020-10-20T03:24:33
2020-10-20T03:24:33
219,441,990
0
0
null
null
null
null
GB18030
Java
false
false
924
java
package com.lyy.entity; import java.util.List; import org.springframework.stereotype.Component; @Component public class Fenye<T> { private Integer page;//当前页 private Integer pageSize; private Integer total;//总条数 private List<T> rows; private Book book; public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getTotal() { return total; } public void setTotal(Integer total) { this.total = total; } public List<T> getRows() { return rows; } public void setRows(List<T> rows) { this.rows = rows; } }
1270d88f841fbd431219ea828c89720bc9df50af
bead5c9388e0d70156a08dfe86d48f52cb245502
/MyNotes/better_write/Java_performance_tuning/A5/test/LinkedListTest.java
ea2790e1ecdd15009e360a270c6eae66a92eed3a
[]
no_license
LinZiYU1996/Learning-Java
bd96e2af798c09bc52a56bf21e13f5763bb7a63d
a0d9f538c9d373c3a93ccd890006ce0e5e1f2d5d
refs/heads/master
2020-11-28T22:22:56.135760
2020-05-03T01:24:57
2020-05-03T01:24:57
229,930,586
0
0
null
null
null
null
UTF-8
Java
false
false
4,800
java
package better_write.Java_performance_tuning.A5.test; import java.util.Iterator; import java.util.LinkedList; /** * \* Created with IntelliJ IDEA. * \* User: LinZiYu * \* Date: 2020/3/25 * \* Time: 11:19 * \* Description: * \ */ public class LinkedListTest { /** * * @param DataNum */ public static void addFromHeaderTest(int DataNum) { LinkedList<String> list=new LinkedList<String>(); int i=0; long timeStart=System.currentTimeMillis(); while(i<DataNum) { list.addFirst(i+"aaavvv"); i++; } long timeEnd=System.currentTimeMillis(); System.out.println("LinkedList从集合头部位置新增元素花费的时间"+(timeEnd-timeStart)); } /** * * @param DataNum */ public static void addFromMidTest(int DataNum) { LinkedList<String> list=new LinkedList<String>(); int i=0; long timeStart=System.currentTimeMillis(); while(i<DataNum) { int temp = list.size(); list.add(temp/2, i+"aaavvv"); i++; } long timeEnd=System.currentTimeMillis(); System.out.println("LinkedList从集合中间位置新增元素花费的时间"+(timeEnd-timeStart)); } /** * * @param DataNum */ public static void addFromTailTest(int DataNum) { LinkedList<String> list=new LinkedList<String>(); int i=0; long timeStart=System.currentTimeMillis(); while(i<DataNum) { list.add(i+"aaavvv"); i++; } long timeEnd=System.currentTimeMillis(); System.out.println("LinkedList从集合尾部位置新增元素花费的时间"+(timeEnd-timeStart)); } /** * * @param DataNum */ public static void deleteFromHeaderTest(int DataNum) { LinkedList<String> list=new LinkedList<String>(); int i=0; while(i<DataNum) { list.add(i+"aaavvv"); i++; } long timeStart=System.currentTimeMillis(); i=0; while(i<DataNum) { list.removeFirst(); i++; } long timeEnd=System.currentTimeMillis(); System.out.println("LinkedList从集合头部位置删除元素花费的时间"+(timeEnd-timeStart)); } /** * * @param DataNum */ public static void deleteFromMidTest(int DataNum) { LinkedList<String> list=new LinkedList<String>(); int i=0; while(i<DataNum) { list.add(i+"aaavvv"); i++; } long timeStart=System.currentTimeMillis(); i=0; while(i<DataNum) { int temp = list.size(); list.remove(temp/2); i++; } long timeEnd=System.currentTimeMillis(); System.out.println("LinkedList从集合中间位置删除元素花费的时间"+(timeEnd-timeStart)); } /** * * @param DataNum */ public static void deleteFromTailTest(int DataNum) { LinkedList<String> list=new LinkedList<String>(); int i=0; while(i<DataNum) { list.add(i+"aaavvv"); i++; } long timeStart=System.currentTimeMillis(); i=0; while(i<DataNum) { list.removeLast(); i++; } long timeEnd=System.currentTimeMillis(); System.out.println("LinkedList从集合尾部位置删除元素花费的时间"+(timeEnd-timeStart)); } /** * * @param DataNum */ public static void getByForTest(int DataNum) { LinkedList<String> list = new LinkedList<String>(); int i = 0; while (i < DataNum) { list.add(i + "aaavvv"); i++; } long timeStart = System.currentTimeMillis(); for (int j=0; j < DataNum ; j++) { list.get(j); } long timeEnd = System.currentTimeMillis(); System.out.println("LinkedList for(;;)循环花费的时间" + (timeEnd - timeStart)); } /** * * @param DataNum */ public static void getByIteratorTest(int DataNum) { LinkedList<String> list = new LinkedList<String>(); int i = 0; while (i < DataNum) { list.add(i + "aaavvv"); i++; } long timeStart = System.currentTimeMillis(); for (Iterator<String> it = list.iterator(); it.hasNext();) { it.next(); } long timeEnd = System.currentTimeMillis(); System.out.println("LinkedList 迭代器迭代循环花费的时间" + (timeEnd - timeStart)); } }
626fd1f06c04cc648e8f28fa53fc76e2398fc332
de8761d8a247e5b99a334585c872cebf95da404a
/Argh/src/logic/logicMozos.java
57fe34b1dfc269c048032520f8f19a7e73855cb9
[]
no_license
AdrielIdeidani/tpWeb
441d27e44bc7d345ad86d7e7f0887d21388cedb1
b105b0ea92834146dc8ec4f46d9eab4b2d07aa01
refs/heads/master
2020-06-10T00:29:21.461969
2020-04-15T23:41:39
2020-04-15T23:41:39
193,535,683
0
1
null
null
null
null
UTF-8
Java
false
false
1,971
java
package logic; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.http.HttpSession; public class logicMozos { Connection C=null; PreparedStatement pstmt =null; ResultSet rs=null; HttpSession miSesion=null; String resultado=null; public String agregar(String user, String contra, String apellido, String nombre, String evento) { if(nombre.isEmpty()) { resultado="Ingrese un nombre para el Mozo"; } else { try { C = DriverManager.getConnection("jdbc:mysql://localhost:3306/tparg?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", user,contra); String query = "Insert into tparg.mozo (apellido,nombre,mozoIdEvento) values (?,?,?);"; PreparedStatement pstmt = C.prepareStatement(query); pstmt.setString(1, apellido); pstmt.setString(2, nombre); pstmt.setString(3, evento );//request.getParameter("idEventoActivo") pstmt.executeUpdate(); pstmt.close(); C.close(); } catch (SQLException e) { resultado= e.getMessage(); e.printStackTrace(); } } return resultado; } public String eliminar (String user, String contra, String id) { try { C = DriverManager.getConnection("jdbc:mysql://localhost:3306/tparg?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", user,contra); //System.out.println("llega al borrar mesa! " + request.getParameter("aux")); String query = "delete from tparg.mozo where idMozo=?;"; PreparedStatement pstmt = C.prepareStatement(query); pstmt.setString(1, id); pstmt.executeUpdate(); pstmt.close(); C.close(); } catch (SQLException e) { resultado= e.getMessage(); e.printStackTrace(); } return resultado; } }
18d295f19524ad110a812a3e4349bdf355756a83
5aa1c53541b234576315b5ffb78e9303b31f12a4
/KnowledgeTree/src/com/Tree/implementation/CustomerBookImpl.java
cda1b03ebfa23e515930f50a4b925e6e464a779d
[]
no_license
lovely1419/BookShoppingSite
4f22764df1e5eb07a34e202c00874c9fa33aa501
c181ed4f663824703972b480f12662782c6f106e
refs/heads/master
2020-03-31T08:26:32.924111
2018-10-18T10:42:29
2018-10-18T10:42:29
152,057,158
0
0
null
null
null
null
UTF-8
Java
false
false
7,008
java
package com.Tree.implementation; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.Tree.dao.CustomerBook; import com.Tree.database.ConnectionProvider; import com.Tree.model.Customer; public class CustomerBookImpl implements CustomerBook { private Connection con=null; @Override public boolean addCustomer(Customer customer) { try { System.out.println(customer); con=ConnectionProvider.getConnection(); System.out.println("connection"); PreparedStatement statement=con.prepareStatement("insert into customer values(?,?,?,?,?,?)"); statement.setString(1,customer.getCustomerId()); statement.setString(2,customer.getCustomerName()); statement.setString(3,customer.getCustomerPassword()); statement.setString(4,customer.getCustomerEmail()); statement.setLong(5,customer.getCustomerContact()); statement.setString(6,customer.getCustomerGender()); int result=statement.executeUpdate(); if(result>0) { System.out.println(customer.getCustomerName()+"Successfully inserted."); return true; } } catch(SQLException e) { System.out.println(e); return true; } return false; } @Override public boolean updateCustomer(Customer customer) { try { con=ConnectionProvider.getConnection(); System.out.println("connection "); PreparedStatement statement= con.prepareStatement("insert into customer values(?,?,?,?,?,?)"); statement.setString(1,customer.getCustomerId()); statement.setString(2,customer.getCustomerName()); statement.setString(3,customer.getCustomerPassword()); statement.setString(4,customer.getCustomerEmail()); statement.setLong(5,customer.getCustomerContact()); statement.setString(6,customer.getCustomerGender()); int result=statement.executeUpdate(); if(result>0) { System.out.println(customer.getCustomerName()+"Successfully inserted."); return true; } } catch(SQLException ex) { System.out.println("Customer detail could not be updated"); System.out.println(ex); } System.out.println("Customer detail could not be updated"); return false; } @Override public boolean deleteCustomer(Customer customer) { try { con=ConnectionProvider.getConnection(); PreparedStatement statement=con.prepareStatement("delete from customer where customerId=?"); statement.setString(1,customer.getCustomerId()); int result=statement.executeUpdate(); if(result>0) { System.out.println(customer.getCustomerName()+"Your data is successfully deleted."); return true; } } catch(SQLException ee) { System.out.println("Could not be deleted"); System.out.println(ee); } System.out.println("could not be deleted"); return false; } @Override public List<Customer> getAllCustomer() { try { List <Customer> list=new ArrayList<Customer>(); con=ConnectionProvider.getConnection(); Statement statement=con.createStatement(); ResultSet result=statement.executeQuery("select * from customer"); System.out.println("#-------Customer Details-------#"); while(result.next()) { System.out.println("Id:-" +result.getString(1)+ "\nName:-" +result.getString(2)+ "\nPassword:-" +result.getString(3)+ "\nEmail:-" +result.getString(4)+ "\nContact:-" +result.getLong(5)+ "\nGender:-" +result.getString(6)); //editable Customer customer=new Customer(); customer.setCustomerId(result.getString(1)); customer.setCustomerName(result.getString(2)); customer.setCustomerPassword(result.getString(3)); customer.setCustomerEmail(result.getString(4)); customer.setCustomerContact(result.getLong(5)); customer.setCustomerGender(result.getString(6)); list.add(customer); } return list; } catch(SQLException ed) { System.out.println("Sorry Data could not be retreieved"); System.out.println(ed); } System.out.println("Sorry Data could not be retreieved"); return null; } @Override public Customer getCustomerById(String customerId) { try { con=ConnectionProvider.getConnection(); PreparedStatement statement=con.prepareStatement("select * from customer where customerId=?"); ResultSet result=statement.executeQuery(); if(result.next()) { System.out.println("Id:-" +result.getString(1)+ "\nName:-" +result.getString(2)+ "\nPassword:-" +result.getString(3)+ "\nEmail:-" +result.getString(4)+ "\nContact:-" +result.getLong(5)+ "\nGender:-" +result.getString(6)); //editable Customer customer=new Customer(); customer.setCustomerId(result.getString(1)); customer.setCustomerName(result.getString(2)); customer.setCustomerPassword(result.getString(3)); customer.setCustomerEmail(result.getString(4)); customer.setCustomerContact(result.getLong(5)); customer.setCustomerGender(result.getString(6)); return customer; } } catch(SQLException se) { System.out.println("Sorry invalid customerId."); System.out.println(se); } return null; } @Override public Customer getCustomerByCustomerEmail(String email) { try { con=ConnectionProvider.getConnection(); PreparedStatement statement=con.prepareStatement("select * from customer where customerEmail=?"); statement.setString(1,email); ResultSet result=statement.executeQuery(); if(result.next()) { System.out.println("Id:-" +result.getString(1)+ "Name:-" +result.getString(2)+ "Password:-" +result.getString(3) + "Email:-" +result.getString(4)+ "Contact:-" +result.getLong(5)+ "Gender:-" +result.getString(6) ); Customer customer=new Customer(); customer.setCustomerId(result.getString(1)); customer.setCustomerName(result.getString(2)); customer.setCustomerPassword(result.getString(3)); customer.setCustomerEmail(result.getString(4)); customer.setCustomerContact(result.getLong(5)); customer.setCustomerGender(result.getString(6)); return customer; } } catch(SQLException ew) { System.out.println("Sorry Customer data could not be retreived."); System.out.println(ew); } return null; } @Override public boolean validate(String email, String password) { try { con=ConnectionProvider.getConnection(); PreparedStatement statement=con.prepareStatement("select * from customer where customerEmail=? and customerPassword=?"); statement.setString(1,email); statement.setString(2,password); ResultSet result=statement.executeQuery(); if(result.next()) { System.out.println("Successfully validate."); return true; } } catch(SQLException se) { System.out.println(se); } return false; } }
e67e3d794a7e618d2dab3fb5cf6850e14e0b0e0c
bfc415982464a70cc254d922c03f8de6aa31ece0
/app/src/main/java/com/example/myapplication/database/model/ActivityLog.java
2751846a0473195123b7abdf1ea103f90b6f4f79
[]
no_license
InfiniteChaos248/ExpenseTracker
f69ca7e4170cb61a618a20dc9850dffbf76f315b
30d7cc99a2b57418c17d106b1ea6f9df7cf727ab
refs/heads/master
2023-04-10T04:18:12.834966
2023-03-29T18:53:15
2023-03-29T18:53:15
201,807,978
0
1
null
null
null
null
UTF-8
Java
false
false
3,567
java
package com.example.myapplication.database.model; import android.database.Cursor; import java.io.Serializable; public class ActivityLog implements Serializable { private Integer id; private String logDate; private String logTime; private Float amount; private Integer category; private Integer categoryS; private Integer type; private Integer wallet; private Integer walletS; private String comments; public static final String TABLE_NAME = "logs"; public static final String COLUMN_ID = "id"; public static final String COLUMN_LOG_DATE = "log_date"; public static final String COLUMN_LOG_TIME = "log_time"; public static final String COLUMN_AMOUNT = "amount"; public static final String COLUMN_CATEGORY = "category"; public static final String COLUMN_NEW = "new"; public static final String COLUMN_TYPE = "type"; public static final String COLUMN_WALLET_1 = "wallet1"; public static final String COLUMN_WALLET_2 = "wallet2"; public static final String COLUMN_COMMENTS = "comments"; public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_LOG_DATE + " TEXT, " + COLUMN_LOG_TIME + " TEXT, " + COLUMN_AMOUNT + " REAL, " + COLUMN_CATEGORY + " INTEGER, " + COLUMN_NEW + " TEXT, " + COLUMN_TYPE + " INTEGER, " + COLUMN_WALLET_1 + " INTEGER, " + COLUMN_WALLET_2 + " INTEGER, " + COLUMN_COMMENTS + " TEXT" + ")"; public ActivityLog() { } public ActivityLog(Cursor cursor) { this.id = cursor.getInt(0); this.logDate = cursor.getString(1); this.logTime = cursor.getString(2); this.amount = cursor.getFloat(3); this.category = cursor.getInt(4); this.categoryS = cursor.getInt(5); this.type = cursor.getInt(6); this.wallet = cursor.getInt(7); this.walletS = cursor.getInt(8); this.comments = cursor.getString(9); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLogDate() { return logDate; } public void setLogDate(String logDate) { this.logDate = logDate; } public String getLogTime() { return logTime; } public void setLogTime(String logTime) { this.logTime = logTime; } public Float getAmount() { return amount; } public void setAmount(Float amount) { this.amount = amount; } public Integer getCategory() { return category; } public void setCategory(Integer category) { this.category = category; } public Integer getCategoryS() { return categoryS; } public void setCategoryS(Integer categoryS) { this.categoryS = categoryS; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getWallet() { return wallet; } public void setWallet(Integer wallet) { this.wallet = wallet; } public Integer getWalletS() { return walletS; } public void setWalletS(Integer walletS) { this.walletS = walletS; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } }
ae10a92062c6884f5c6c71973c8ae432b28f222f
098fd0f2c4456699af3d72bb2d6f748c45cd3031
/src/com/tj/beans/Sophie.java
9d0bae889818ecbebebdd0b4771616b7b4478474
[]
no_license
HardSoft2023/root-report
787d1eec41aff0fe279d380dceadac8e6baa7e76
fb059199a81270d83eaf74577ceab0873857214a
refs/heads/master
2023-05-10T20:46:24.266972
2015-11-10T10:47:10
2015-11-10T10:47:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,221
java
package com.tj.beans; public class Sophie { private String record_time; private String which_log; private int cnt_lns; private int cnt_vld; private int cnt_scs; private int cnt_flt; private int cnt_err; private int cnt_csv; private int cnt_jsn; private int cnt_dstrbt; private int vld_spc_cnt; private String vld_info; private int flt_spc_cnt; private String flt_info; private int err_spc_cnt; private String err_info; private String db_log; private String db_err; private String db_bad; private int cnt_db_prc; private int cnt_db_insrt; public String getRecord_time() { return record_time; } public void setRecord_time(String record_time) { this.record_time = record_time; } public String getWhich_log() { return which_log; } public void setWhich_log(String which_log) { this.which_log = which_log; } public int getCnt_lns() { return cnt_lns; } public void setCnt_lns(int cnt_lns) { this.cnt_lns = cnt_lns; } public int getCnt_vld() { return cnt_vld; } public void setCnt_vld(int cnt_vld) { this.cnt_vld = cnt_vld; } public int getCnt_scs() { return cnt_scs; } public void setCnt_scs(int cnt_scs) { this.cnt_scs = cnt_scs; } public int getCnt_flt() { return cnt_flt; } public void setCnt_flt(int cnt_flt) { this.cnt_flt = cnt_flt; } public int getCnt_err() { return cnt_err; } public void setCnt_err(int cnt_err) { this.cnt_err = cnt_err; } public int getCnt_csv() { return cnt_csv; } public void setCnt_csv(int cnt_csv) { this.cnt_csv = cnt_csv; } public int getCnt_jsn() { return cnt_jsn; } public void setCnt_jsn(int cnt_jsn) { this.cnt_jsn = cnt_jsn; } public int getCnt_dstrbt() { return cnt_dstrbt; } public void setCnt_dstrbt(int cnt_dstrbt) { this.cnt_dstrbt = cnt_dstrbt; } public int getVld_spc_cnt() { return vld_spc_cnt; } public void setVld_spc_cnt(int vld_spc_cnt) { this.vld_spc_cnt = vld_spc_cnt; } public String getVld_info() { return vld_info; } public void setVld_info(String vld_info) { this.vld_info = vld_info; } public int getFlt_spc_cnt() { return flt_spc_cnt; } public void setFlt_spc_cnt(int flt_spc_cnt) { this.flt_spc_cnt = flt_spc_cnt; } public String getFlt_info() { return flt_info; } public void setFlt_info(String flt_info) { this.flt_info = flt_info; } public int getErr_spc_cnt() { return err_spc_cnt; } public void setErr_spc_cnt(int err_spc_cnt) { this.err_spc_cnt = err_spc_cnt; } public String getErr_info() { return err_info; } public void setErr_info(String err_info) { this.err_info = err_info; } public String getDb_log() { return db_log; } public void setDb_log(String db_log) { this.db_log = db_log; } public String getDb_err() { return db_err; } public void setDb_err(String db_err) { this.db_err = db_err; } public String getDb_bad() { return db_bad; } public void setDb_bad(String db_bad) { this.db_bad = db_bad; } public int getCnt_db_prc() { return cnt_db_prc; } public void setCnt_db_prc(int cnt_db_prc) { this.cnt_db_prc = cnt_db_prc; } public int getCnt_db_insrt() { return cnt_db_insrt; } public void setCnt_db_insrt(int cnt_db_insrt) { this.cnt_db_insrt = cnt_db_insrt; } }
4ade26dfdecd2ca6bad5c50a6defa1f0b193101c
46b78045ff3c7df3468bb2d5c5c2d1f46c19fed9
/hkprogrammer.core/src/main/java/com/shadows/hkprogrammer/core/messages/ParameterMessage.java
16a7dfea40167e03e9133953f3b0c86b7b3bb282
[]
no_license
ShadowSteps/HKProgrammer
4376d28629d6b2a9a9e6845b144fc9480135822b
d5256cba1ca69cfd0817a2c7192de3399f7b3897
refs/heads/master
2021-01-10T15:40:29.399692
2016-03-19T18:04:43
2016-03-19T18:04:43
52,709,574
0
0
null
null
null
null
UTF-8
Java
false
false
10,504
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.shadows.hkprogrammer.core.messages; import com.shadows.hkprogrammer.core.messages.enums.ControlChannel; import com.shadows.hkprogrammer.core.messages.enums.CraftType; import com.shadows.hkprogrammer.core.messages.enums.DRChannel; import com.shadows.hkprogrammer.core.messages.enums.HeliEndPoint; import com.shadows.hkprogrammer.core.messages.enums.MixDestination; import com.shadows.hkprogrammer.core.messages.enums.MixSource; import com.shadows.hkprogrammer.core.messages.enums.MixSwitch; import com.shadows.hkprogrammer.core.messages.enums.SwashChannel; import com.shadows.hkprogrammer.core.messages.enums.SwitchFunction; import com.shadows.hkprogrammer.core.messages.enums.SwitchType; import com.shadows.hkprogrammer.core.messages.enums.TXModel; import com.shadows.hkprogrammer.core.messages.enums.VRFunction; import com.shadows.hkprogrammer.core.messages.enums.VRType; import com.shadows.hkprogrammer.core.messages.values.MixSetting; import com.shadows.hkprogrammer.core.messages.values.ParameterDRValue; import com.shadows.hkprogrammer.core.messages.values.PitchCurve; import com.shadows.hkprogrammer.core.messages.values.PotmeterEndPoint; import com.shadows.hkprogrammer.core.messages.values.ThrottleCurve; import java.io.Serializable; import java.util.Arrays; import java.util.Objects; /** * * @author John */ public class ParameterMessage implements Serializable { private TXModel TXModelType = TXModel.Model1; private CraftType CraftTypeNum = CraftType.Acro; private Boolean[] ReverseBitmask = new Boolean[6]; private final ParameterDRValue[] DRValues = new ParameterDRValue[3]; private final int[] Swash = new int[3]; private final PotmeterEndPoint[] EndPoints = new PotmeterEndPoint[6]; private final ThrottleCurve[] ThrottleCurves = new ThrottleCurve[5]; private final PitchCurve[] PitchCurves = new PitchCurve[5]; private final int[] Subtrim = new int[6]; private final MixSetting[] Mixes = new MixSetting[3]; private final SwitchFunction[] SwitchFunctions = new SwitchFunction[2]; private final VRFunction[] VRModes = new VRFunction[2]; public ParameterMessage() { Arrays.fill(DRValues, new ParameterDRValue()); Arrays.fill(EndPoints, new PotmeterEndPoint()); Arrays.fill(Swash, 0); Arrays.fill(ThrottleCurves, new ThrottleCurve()); Arrays.fill(PitchCurves, new PitchCurve()); Arrays.fill(Subtrim, 0); Arrays.fill(Mixes, new MixSetting()); Arrays.fill(SwitchFunctions, SwitchFunction.Unassigned); Arrays.fill(VRModes, VRFunction.Unassigned); } @Override public int hashCode() { int hash = 7; hash = 47 * hash + Objects.hashCode(this.TXModelType); hash = 47 * hash + Objects.hashCode(this.CraftTypeNum); hash = 47 * hash + Arrays.deepHashCode(ReverseBitmask); hash = 47 * hash + Arrays.deepHashCode(this.DRValues); hash = 47 * hash + Arrays.hashCode(this.Swash); hash = 47 * hash + Arrays.deepHashCode(this.EndPoints); hash = 47 * hash + Arrays.deepHashCode(this.ThrottleCurves); hash = 47 * hash + Arrays.deepHashCode(this.PitchCurves); hash = 47 * hash + Arrays.hashCode(this.Subtrim); hash = 47 * hash + Arrays.deepHashCode(this.Mixes); hash = 47 * hash + Arrays.deepHashCode(this.SwitchFunctions); hash = 47 * hash + Arrays.deepHashCode(this.VRModes); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ParameterMessage other = (ParameterMessage) obj; if (this.TXModelType != other.TXModelType) { return false; } if (this.CraftTypeNum != other.CraftTypeNum) { return false; } if (!Arrays.deepEquals(this.ReverseBitmask,other.ReverseBitmask)) { return false; } if (!Arrays.deepEquals(this.DRValues, other.DRValues)) { return false; } if (!Arrays.equals(this.Swash, other.Swash)) { return false; } if (!Arrays.deepEquals(this.EndPoints, other.EndPoints)) { return false; } if (!Arrays.deepEquals(this.ThrottleCurves, other.ThrottleCurves)) { return false; } if (!Arrays.deepEquals(this.PitchCurves, other.PitchCurves)) { return false; } if (!Arrays.equals(this.Subtrim, other.Subtrim)) { return false; } if (!Arrays.deepEquals(this.Mixes, other.Mixes)) { return false; } if (!Arrays.deepEquals(this.SwitchFunctions, other.SwitchFunctions)) { return false; } if (!Arrays.deepEquals(this.VRModes, other.VRModes)) { return false; } return true; } public TXModel getTXModelType() { return TXModelType; } public void setTXModelType(TXModel TXModelType) { this.TXModelType = TXModelType; } public CraftType getCraftTypeNum() { return CraftTypeNum; } public void setCraftTypeNum(CraftType CraftTypeNum) { this.CraftTypeNum = CraftTypeNum; } public Boolean[] getReverseBitmask() { return ReverseBitmask; } public ParameterDRValue[] getDRValues() { return DRValues; } public int[] getSwash() { return Swash; } public PotmeterEndPoint[] getEndPoints() { return EndPoints; } public ThrottleCurve[] getThrottleCurves() { return ThrottleCurves; } public PitchCurve[] getPitchCurves() { return PitchCurves; } public int[] getSubtrim() { return Subtrim; } public MixSetting[] getMixes() { return Mixes; } public SwitchFunction[] getSwitchFunction() { return SwitchFunctions; } public VRFunction[] getVRModes() { return VRModes; } private void ValidateDRChannel(int channelNum){ if (channelNum > 2 || channelNum < 0){ throw new IllegalArgumentException("DR is available only for Channel 1,Channel 2 and Channel 4!"); } } private void ValidateSwashValue(int swashValue){ if (swashValue > 127 || swashValue < 0){ throw new IllegalArgumentException("Swash value is available only between 0 and 127!"); } } private void ValidateSubtrimValue(int swashValue){ if (swashValue > 127 || swashValue < -128){ throw new IllegalArgumentException("Subtrim value is available only between -128 and 127!"); } } public void setReverseBitmaskForChannel(ControlChannel channel,boolean Enabled) { int channelNum = (channel.getValue()); this.ReverseBitmask[channelNum] = Enabled; } public void setDRValueForChannel(DRChannel channel,ParameterDRValue value){ int channelNum = (channel.getValue()); this.DRValues[channelNum] = value; } public void setDRValueForChannel(DRChannel channel,int onValue,int offValue){ ParameterDRValue DR = new ParameterDRValue(); DR.setOffValue(offValue); DR.setOnValue(onValue); this.setDRValueForChannel(channel, DR); } public void setSwashValueForChannel(SwashChannel channel,int value){ ValidateSwashValue(value); int channelNum = channel.getValue(); this.Swash[channelNum] = value; } public void setEndPointValueForChannel(ControlChannel channel,PotmeterEndPoint value){ int channelNum = (channel.getValue()); this.EndPoints[channelNum] = value; } public void setEndPointValueForChannel(ControlChannel channel,int left,int right){ PotmeterEndPoint Point = new PotmeterEndPoint(); Point.setLeft(left); Point.setRigth(right); this.setEndPointValueForChannel(channel, Point); } public void setThrottleCurveValueForChannel(HeliEndPoint point,ThrottleCurve value){ int pointNum = (point.getValue()); this.ThrottleCurves[pointNum] = value; } public void setThrottleCurveValueForChannel(HeliEndPoint point,byte normal,byte ID){ ThrottleCurve Point = new ThrottleCurve(); Point.setID(ID); Point.setNormal(normal); this.setThrottleCurveValueForChannel(point, Point); } public void setPitchCurveValueForChannel(HeliEndPoint point,PitchCurve value){ int pointNum = (point.getValue()); this.PitchCurves[pointNum] = value; } public void setPitchCurveValueForChannel(HeliEndPoint point,byte normal,byte ID){ PitchCurve Point = new PitchCurve(); Point.setID(ID); Point.setNormal(normal); this.setPitchCurveValueForChannel(point, Point); } public void setSubtrimValueForChannel(ControlChannel channel,int value){ ValidateSubtrimValue(value); int channelNum = channel.getValue(); this.Subtrim[channelNum] = value; } public void setMixSettingsValue(int Mix,MixSetting value){ if (Mix < 1 || Mix > 3) throw new IllegalArgumentException("There is only Mix1-3 available!"); this.Mixes[Mix-1] = value; } public void setMixSettingsValue( int Mix, MixDestination destination, MixSource source, MixSwitch mixSwitch, int Downrate, int Uprate ){ MixSetting MSetting = new MixSetting(); MSetting.setDestination(destination); MSetting.setDownrate(Downrate); MSetting.setSource(source); MSetting.setSwitch(mixSwitch); MSetting.setUprate(Uprate); this.setMixSettingsValue(Mix, MSetting); } public void setSwitchFunction(SwitchType switchNum,SwitchFunction value){ int pointNum = (switchNum.getValue()); this.SwitchFunctions[pointNum] = value; } public void setVRFunction(VRType vrNum,VRFunction value){ int pointNum = (vrNum.getValue()); this.VRModes[pointNum] = value; } }
f0ae8f6da01c71c5df448db2c65689b09c69c375
6045518db77c6104b4f081381f61c26e0d19d5db
/datasets/file_version_per_commit_backup/apache-jmeter/c08d3221ad959c7d610452928a7e233c77e57ca2.java
ca21e3c0136e2f05de1559471b5782a7abdaf627
[]
no_license
edisutoyo/msr16_td_removal
6e039da7fed166b81ede9b33dcc26ca49ba9259c
41b07293c134496ba1072837e1411e05ed43eb75
refs/heads/master
2023-03-22T21:40:42.993910
2017-09-22T09:19:51
2017-09-22T09:19:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,970
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jmeter.protocol.jms.client; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * * ClientPool holds the client instances in an ArrayList. The main purpose of * this is to make it easier to clean up all the instances at the end of a test. * If we didn't do this, threads might become zombie. * * N.B. This class needs to be fully synchronized as it is called from sample threads * and the thread that runs testEnded() methods. */ public class ClientPool { private static final ArrayList<Object> clients = new ArrayList<Object>(); private static final Map<Object, Object> client_map = new HashMap<Object, Object>(); /** * Add a ReceiveClient to the ClientPool. This is so that we can make sure * to close all clients and make sure all threads are destroyed. * * @param client */ public static synchronized void addClient(ReceiveSubscriber client) { clients.add(client); } /** * Add a OnMessageClient to the ClientPool. This is so that we can make sure * to close all clients and make sure all threads are destroyed. * * @param client */ public static synchronized void addClient(OnMessageSubscriber client) { clients.add(client); } /** * Add a Publisher to the ClientPool. This is so that we can make sure to * close all clients and make sure all threads are destroyed. * * @param client */ public static synchronized void addClient(Publisher client) { clients.add(client); } /** * Clear all the clients created by either Publish or Subscribe sampler. We * need to do this to make sure all the threads creatd during the test are * destroyed and cleaned up. In some cases, the client provided by the * manufacturer of the JMS server may have bugs and some threads may become * zombie. In those cases, it is not the responsibility of JMeter for those * bugs. */ public static synchronized void clearClient() { Iterator<Object> itr = clients.iterator(); while (itr.hasNext()) { Object client = itr.next(); if (client instanceof ReceiveSubscriber) { ReceiveSubscriber sub = (ReceiveSubscriber) client; sub.close(); sub = null; } else if (client instanceof Publisher) { Publisher pub = (Publisher) client; pub.close(); pub = null; } else if (client instanceof OnMessageSubscriber) { OnMessageSubscriber sub = (OnMessageSubscriber) client; sub.close(); sub = null; } } clients.clear(); client_map.clear(); } public static synchronized void put(Object key, OnMessageSubscriber client) { client_map.put(key, client); } public static synchronized void put(Object key, Publisher client) { client_map.put(key, client); } public static synchronized Object get(Object key) { return client_map.get(key); } }
580d7b8e175b275fc77af1c8411da0f01f15fae6
9af4ab4fb5cb46ca80d7760de550719823ee9151
/java/org/apache/catalina/loader/WebappClassLoaderBase.java
e64a2784104b25ed0e93738506c7c8ae7a1be3e6
[]
no_license
HelloArtoo/tomcat-9.0.43-maven
47d4e6e6936b21fbdcd2e56e437177a6c018e562
03c3e0673b012fd2a88338b968a85abb8ea24757
refs/heads/main
2023-07-18T15:39:54.721899
2021-09-06T10:16:29
2021-09-06T10:16:29
403,573,236
0
0
null
null
null
null
UTF-8
Java
false
false
99,349
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.loader; import java.io.File; import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.ref.Reference; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessControlException; import java.security.AccessController; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Policy; import java.security.PrivilegedAction; import java.security.ProtectionDomain; import java.security.cert.Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ThreadPoolExecutor; import java.util.jar.Attributes; import java.util.jar.Attributes.Name; import java.util.jar.Manifest; import org.apache.catalina.Container; import org.apache.catalina.Globals; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleListener; import org.apache.catalina.LifecycleState; import org.apache.catalina.WebResource; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; import org.apache.juli.WebappProperties; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.InstrumentableClassLoader; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.IntrospectionUtils; import org.apache.tomcat.util.compat.JreCompat; import org.apache.tomcat.util.res.StringManager; import org.apache.tomcat.util.security.PermissionCheck; /** * Specialized web application class loader. * <p> * This class loader is a full reimplementation of the * <code>URLClassLoader</code> from the JDK. It is designed to be fully * compatible with a normal <code>URLClassLoader</code>, although its internal * behavior may be completely different. * <p> * <strong>IMPLEMENTATION NOTE</strong> - By default, this class loader follows * the delegation model required by the specification. The system class * loader will be queried first, then the local repositories, and only then * delegation to the parent class loader will occur. This allows the web * application to override any shared class except the classes from J2SE. * Special handling is provided from the JAXP XML parser interfaces, the JNDI * interfaces, and the classes from the servlet API, which are never loaded * from the webapp repositories. The <code>delegate</code> property * allows an application to modify this behavior to move the parent class loader * ahead of the local repositories. * <p> * <strong>IMPLEMENTATION NOTE</strong> - Due to limitations in Jasper * compilation technology, any repository which contains classes from * the servlet API will be ignored by the class loader. * <p> * <strong>IMPLEMENTATION NOTE</strong> - The class loader generates source * URLs which include the full JAR URL when a class is loaded from a JAR file, * which allows setting security permission at the class level, even when a * class is contained inside a JAR. * <p> * <strong>IMPLEMENTATION NOTE</strong> - Local repositories are searched in * the order they are added via the initial constructor. * <p> * <strong>IMPLEMENTATION NOTE</strong> - No check for sealing violations or * security is made unless a security manager is present. * <p> * <strong>IMPLEMENTATION NOTE</strong> - As of 8.0, this class * loader implements {@link InstrumentableClassLoader}, permitting web * application classes to instrument other classes in the same web * application. It does not permit instrumentation of system or container * classes or classes in other web apps. * * @author Remy Maucherat * @author Craig R. McClanahan */ public abstract class WebappClassLoaderBase extends URLClassLoader implements Lifecycle, InstrumentableClassLoader, WebappProperties, PermissionCheck { private static final Log log = LogFactory.getLog(WebappClassLoaderBase.class); /** * List of ThreadGroup names to ignore when scanning for web application * started threads that need to be shut down. */ private static final List<String> JVM_THREAD_GROUP_NAMES = new ArrayList<>(); private static final String JVM_THREAD_GROUP_SYSTEM = "system"; private static final String CLASS_FILE_SUFFIX = ".class"; static { if (!JreCompat.isGraalAvailable()) { ClassLoader.registerAsParallelCapable(); } JVM_THREAD_GROUP_NAMES.add(JVM_THREAD_GROUP_SYSTEM); JVM_THREAD_GROUP_NAMES.add("RMI Runtime"); } protected class PrivilegedFindClassByName implements PrivilegedAction<Class<?>> { private final String name; PrivilegedFindClassByName(String name) { this.name = name; } @Override public Class<?> run() { return findClassInternal(name); } } protected static final class PrivilegedGetClassLoader implements PrivilegedAction<ClassLoader> { private final Class<?> clazz; public PrivilegedGetClassLoader(Class<?> clazz){ this.clazz = clazz; } @Override public ClassLoader run() { return clazz.getClassLoader(); } } protected final class PrivilegedJavaseGetResource implements PrivilegedAction<URL> { private final String name; public PrivilegedJavaseGetResource(String name) { this.name = name; } @Override public URL run() { return javaseClassLoader.getResource(name); } } // ------------------------------------------------------- Static Variables /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(WebappClassLoaderBase.class); // ----------------------------------------------------------- Constructors /** * Construct a new ClassLoader with no defined repositories and no * parent ClassLoader. */ protected WebappClassLoaderBase() { super(new URL[0]); ClassLoader p = getParent(); if (p == null) { p = getSystemClassLoader(); } this.parent = p; ClassLoader j = String.class.getClassLoader(); if (j == null) { j = getSystemClassLoader(); while (j.getParent() != null) { j = j.getParent(); } } this.javaseClassLoader = j; securityManager = System.getSecurityManager(); if (securityManager != null) { refreshPolicy(); } } /** * Construct a new ClassLoader with no defined repositories and the given * parent ClassLoader. * <p> * Method is used via reflection - * see {@link WebappLoader#createClassLoader()} * * @param parent Our parent class loader */ protected WebappClassLoaderBase(ClassLoader parent) { super(new URL[0], parent); ClassLoader p = getParent(); if (p == null) { p = getSystemClassLoader(); } this.parent = p; ClassLoader j = String.class.getClassLoader(); if (j == null) { j = getSystemClassLoader(); while (j.getParent() != null) { j = j.getParent(); } } this.javaseClassLoader = j; securityManager = System.getSecurityManager(); if (securityManager != null) { refreshPolicy(); } } // ----------------------------------------------------- Instance Variables /** * Associated web resources for this webapp. */ protected WebResourceRoot resources = null; /** * The cache of ResourceEntry for classes and resources we have loaded, * keyed by resource path, not binary name. Path is used as the key since * resources may be requested by binary name (classes) or path (other * resources such as property files) and the mapping from binary name to * path is unambiguous but the reverse mapping is ambiguous. */ protected final Map<String, ResourceEntry> resourceEntries = new ConcurrentHashMap<>(); /** * Should this class loader delegate to the parent class loader * <strong>before</strong> searching its own repositories (i.e. the * usual Java2 delegation model)? If set to <code>false</code>, * this class loader will search its own repositories first, and * delegate to the parent only if the class or resource is not * found locally. Note that the default, <code>false</code>, is * the behavior called for by the servlet specification. */ protected boolean delegate = false; private final Map<String,Long> jarModificationTimes = new HashMap<>(); /** * A list of read File Permission's required if this loader is for a web * application context. */ protected final ArrayList<Permission> permissionList = new ArrayList<>(); /** * The PermissionCollection for each CodeSource for a web * application context. */ protected final HashMap<String, PermissionCollection> loaderPC = new HashMap<>(); /** * Instance of the SecurityManager installed. */ protected final SecurityManager securityManager; /** * The parent class loader. */ protected final ClassLoader parent; /** * The bootstrap class loader used to load the JavaSE classes. In some * implementations this class loader is always <code>null</code> and in * those cases {@link ClassLoader#getParent()} will be called recursively on * the system class loader and the last non-null result used. */ private ClassLoader javaseClassLoader; /** * Enables the RMI Target memory leak detection to be controlled. This is * necessary since the detection can only work on Java 9 if some of the * modularity checks are disabled. */ private boolean clearReferencesRmiTargets = true; /** * Should Tomcat attempt to terminate threads that have been started by the * web application? Stopping threads is performed via the deprecated (for * good reason) <code>Thread.stop()</code> method and is likely to result in * instability. As such, enabling this should be viewed as an option of last * resort in a development environment and is not recommended in a * production environment. If not specified, the default value of * <code>false</code> will be used. */ private boolean clearReferencesStopThreads = false; /** * Should Tomcat attempt to terminate any {@link java.util.TimerThread}s * that have been started by the web application? If not specified, the * default value of <code>false</code> will be used. */ private boolean clearReferencesStopTimerThreads = false; /** * Should Tomcat call * {@link org.apache.juli.logging.LogFactory#release(ClassLoader)} when the * class loader is stopped? If not specified, the default value of * <code>true</code> is used. Changing the default setting is likely to lead * to memory leaks and other issues. */ private boolean clearReferencesLogFactoryRelease = true; /** * If an HttpClient keep-alive timer thread has been started by this web * application and is still running, should Tomcat change the context class * loader from the current {@link ClassLoader} to * {@link ClassLoader#getParent()} to prevent a memory leak? Note that the * keep-alive timer thread will stop on its own once the keep-alives all * expire however, on a busy system that might not happen for some time. */ private boolean clearReferencesHttpClientKeepAliveThread = true; /** * Should Tomcat attempt to clear references to classes loaded by this class * loader from the ObjectStreamClass caches? */ private boolean clearReferencesObjectStreamClassCaches = true; /** * Should Tomcat attempt to clear references to classes loaded by this class * loader from ThreadLocals? */ private boolean clearReferencesThreadLocals = true; /** * Should Tomcat skip the memory leak checks when the web application is * stopped as part of the process of shutting down the JVM? */ private boolean skipMemoryLeakChecksOnJvmShutdown = false; /** * Holds the class file transformers decorating this class loader. The * CopyOnWriteArrayList is thread safe. It is expensive on writes, but * those should be rare. It is very fast on reads, since synchronization * is not actually used. Importantly, the ClassLoader will never block * iterating over the transformers while loading a class. */ private final List<ClassFileTransformer> transformers = new CopyOnWriteArrayList<>(); /** * Flag that indicates that {@link #addURL(URL)} has been called which * creates a requirement to check the super class when searching for * resources. */ private boolean hasExternalRepositories = false; /** * Repositories managed by this class rather than the super class. */ private List<URL> localRepositories = new ArrayList<>(); private volatile LifecycleState state = LifecycleState.NEW; // ------------------------------------------------------------- Properties /** * @return associated resources. */ public WebResourceRoot getResources() { return this.resources; } /** * Set associated resources. * @param resources the resources from which the classloader will * load the classes */ public void setResources(WebResourceRoot resources) { this.resources = resources; } /** * @return the context name for this class loader. */ public String getContextName() { if (resources == null) { return "Unknown"; } else { return resources.getContext().getBaseName(); } } /** * Return the "delegate first" flag for this class loader. * @return <code>true</code> if the class lookup will delegate to * the parent first. The default in Tomcat is <code>false</code>. */ public boolean getDelegate() { return this.delegate; } /** * Set the "delegate first" flag for this class loader. * If this flag is true, this class loader delegates * to the parent class loader * <strong>before</strong> searching its own repositories, as * in an ordinary (non-servlet) chain of Java class loaders. * If set to <code>false</code> (the default), * this class loader will search its own repositories first, and * delegate to the parent only if the class or resource is not * found locally, as per the servlet specification. * * @param delegate The new "delegate first" flag */ public void setDelegate(boolean delegate) { this.delegate = delegate; } /** * If there is a Java SecurityManager create a read permission for the * target of the given URL as appropriate. * * @param url URL for a file or directory on local system */ void addPermission(URL url) { if (url == null) { return; } if (securityManager != null) { String protocol = url.getProtocol(); if ("file".equalsIgnoreCase(protocol)) { URI uri; File f; String path; try { uri = url.toURI(); f = new File(uri); path = f.getCanonicalPath(); } catch (IOException | URISyntaxException e) { log.warn(sm.getString( "webappClassLoader.addPermissionNoCanonicalFile", url.toExternalForm())); return; } if (f.isFile()) { // Allow the file to be read addPermission(new FilePermission(path, "read")); } else if (f.isDirectory()) { addPermission(new FilePermission(path, "read")); addPermission(new FilePermission( path + File.separator + "-", "read")); } else { // File does not exist - ignore (shouldn't happen) } } else { // Unsupported URL protocol log.warn(sm.getString( "webappClassLoader.addPermissionNoProtocol", protocol, url.toExternalForm())); } } } /** * If there is a Java SecurityManager create a Permission. * * @param permission The permission */ void addPermission(Permission permission) { if ((securityManager != null) && (permission != null)) { permissionList.add(permission); } } public boolean getClearReferencesRmiTargets() { return this.clearReferencesRmiTargets; } public void setClearReferencesRmiTargets(boolean clearReferencesRmiTargets) { this.clearReferencesRmiTargets = clearReferencesRmiTargets; } /** * @return the clearReferencesStopThreads flag for this Context. */ public boolean getClearReferencesStopThreads() { return this.clearReferencesStopThreads; } /** * Set the clearReferencesStopThreads feature for this Context. * * @param clearReferencesStopThreads The new flag value */ public void setClearReferencesStopThreads( boolean clearReferencesStopThreads) { this.clearReferencesStopThreads = clearReferencesStopThreads; } /** * @return the clearReferencesStopTimerThreads flag for this Context. */ public boolean getClearReferencesStopTimerThreads() { return this.clearReferencesStopTimerThreads; } /** * Set the clearReferencesStopTimerThreads feature for this Context. * * @param clearReferencesStopTimerThreads The new flag value */ public void setClearReferencesStopTimerThreads( boolean clearReferencesStopTimerThreads) { this.clearReferencesStopTimerThreads = clearReferencesStopTimerThreads; } /** * @return the clearReferencesLogFactoryRelease flag for this Context. */ public boolean getClearReferencesLogFactoryRelease() { return this.clearReferencesLogFactoryRelease; } /** * Set the clearReferencesLogFactoryRelease feature for this Context. * * @param clearReferencesLogFactoryRelease The new flag value */ public void setClearReferencesLogFactoryRelease( boolean clearReferencesLogFactoryRelease) { this.clearReferencesLogFactoryRelease = clearReferencesLogFactoryRelease; } /** * @return the clearReferencesHttpClientKeepAliveThread flag for this * Context. */ public boolean getClearReferencesHttpClientKeepAliveThread() { return this.clearReferencesHttpClientKeepAliveThread; } /** * Set the clearReferencesHttpClientKeepAliveThread feature for this * Context. * * @param clearReferencesHttpClientKeepAliveThread The new flag value */ public void setClearReferencesHttpClientKeepAliveThread( boolean clearReferencesHttpClientKeepAliveThread) { this.clearReferencesHttpClientKeepAliveThread = clearReferencesHttpClientKeepAliveThread; } public boolean getClearReferencesObjectStreamClassCaches() { return clearReferencesObjectStreamClassCaches; } public void setClearReferencesObjectStreamClassCaches( boolean clearReferencesObjectStreamClassCaches) { this.clearReferencesObjectStreamClassCaches = clearReferencesObjectStreamClassCaches; } public boolean getClearReferencesThreadLocals() { return clearReferencesThreadLocals; } public void setClearReferencesThreadLocals(boolean clearReferencesThreadLocals) { this.clearReferencesThreadLocals = clearReferencesThreadLocals; } public boolean getSkipMemoryLeakChecksOnJvmShutdown() { return skipMemoryLeakChecksOnJvmShutdown; } public void setSkipMemoryLeakChecksOnJvmShutdown(boolean skipMemoryLeakChecksOnJvmShutdown) { this.skipMemoryLeakChecksOnJvmShutdown = skipMemoryLeakChecksOnJvmShutdown; } // ------------------------------------------------------- Reloader Methods /** * Adds the specified class file transformer to this class loader. The * transformer will then be able to modify the bytecode of any classes * loaded by this class loader after the invocation of this method. * * @param transformer The transformer to add to the class loader */ @Override public void addTransformer(ClassFileTransformer transformer) { if (transformer == null) { throw new IllegalArgumentException(sm.getString( "webappClassLoader.addTransformer.illegalArgument", getContextName())); } if (this.transformers.contains(transformer)) { // if the same instance of this transformer was already added, bail out log.warn(sm.getString("webappClassLoader.addTransformer.duplicate", transformer, getContextName())); return; } this.transformers.add(transformer); log.info(sm.getString("webappClassLoader.addTransformer", transformer, getContextName())); } /** * Removes the specified class file transformer from this class loader. * It will no longer be able to modify the byte code of any classes * loaded by the class loader after the invocation of this method. * However, any classes already modified by this transformer will * remain transformed. * * @param transformer The transformer to remove */ @Override public void removeTransformer(ClassFileTransformer transformer) { if (transformer == null) { return; } if (this.transformers.remove(transformer)) { log.info(sm.getString("webappClassLoader.removeTransformer", transformer, getContextName())); } } protected void copyStateWithoutTransformers(WebappClassLoaderBase base) { base.resources = this.resources; base.delegate = this.delegate; base.state = LifecycleState.NEW; base.clearReferencesStopThreads = this.clearReferencesStopThreads; base.clearReferencesStopTimerThreads = this.clearReferencesStopTimerThreads; base.clearReferencesLogFactoryRelease = this.clearReferencesLogFactoryRelease; base.clearReferencesHttpClientKeepAliveThread = this.clearReferencesHttpClientKeepAliveThread; base.jarModificationTimes.putAll(this.jarModificationTimes); base.permissionList.addAll(this.permissionList); base.loaderPC.putAll(this.loaderPC); } /** * Have one or more classes or resources been modified so that a reload * is appropriate? * @return <code>true</code> if there's been a modification */ public boolean modified() { if (log.isDebugEnabled()) log.debug("modified()"); for (Entry<String,ResourceEntry> entry : resourceEntries.entrySet()) { long cachedLastModified = entry.getValue().lastModified; long lastModified = resources.getClassLoaderResource( entry.getKey()).getLastModified(); if (lastModified != cachedLastModified) { if( log.isDebugEnabled() ) log.debug(sm.getString("webappClassLoader.resourceModified", entry.getKey(), new Date(cachedLastModified), new Date(lastModified))); return true; } } // Check if JARs have been added or removed WebResource[] jars = resources.listResources("/WEB-INF/lib"); // Filter out non-JAR resources int jarCount = 0; for (WebResource jar : jars) { if (jar.getName().endsWith(".jar") && jar.isFile() && jar.canRead()) { jarCount++; Long recordedLastModified = jarModificationTimes.get(jar.getName()); if (recordedLastModified == null) { // Jar has been added log.info(sm.getString("webappClassLoader.jarsAdded", resources.getContext().getName())); return true; } if (recordedLastModified.longValue() != jar.getLastModified()) { // Jar has been changed log.info(sm.getString("webappClassLoader.jarsModified", resources.getContext().getName())); return true; } } } if (jarCount < jarModificationTimes.size()){ log.info(sm.getString("webappClassLoader.jarsRemoved", resources.getContext().getName())); return true; } // No classes have been modified return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(this.getClass().getSimpleName()); sb.append("\r\n context: "); sb.append(getContextName()); sb.append("\r\n delegate: "); sb.append(delegate); sb.append("\r\n"); if (this.parent != null) { sb.append("----------> Parent Classloader:\r\n"); sb.append(this.parent.toString()); sb.append("\r\n"); } if (this.transformers.size() > 0) { sb.append("----------> Class file transformers:\r\n"); for (ClassFileTransformer transformer : this.transformers) { sb.append(transformer).append("\r\n"); } } return sb.toString(); } // ---------------------------------------------------- ClassLoader Methods // Note: exposed for use by tests protected final Class<?> doDefineClass(String name, byte[] b, int off, int len, ProtectionDomain protectionDomain) { return super.defineClass(name, b, off, len, protectionDomain); } /** * Find the specified class in our local repositories, if possible. If * not found, throw <code>ClassNotFoundException</code>. * * @param name The binary name of the class to be loaded * * @exception ClassNotFoundException if the class was not found */ @Override public Class<?> findClass(String name) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug(" findClass(" + name + ")"); checkStateForClassLoading(name); // (1) Permission to define this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { if (log.isTraceEnabled()) log.trace(" securityManager.checkPackageDefinition"); securityManager.checkPackageDefinition(name.substring(0,i)); } catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); } } } // Ask our superclass to locate this class, if possible // (throws ClassNotFoundException if it is not found) Class<?> clazz = null; try { if (log.isTraceEnabled()) log.trace(" findClassInternal(" + name + ")"); try { if (securityManager != null) { PrivilegedAction<Class<?>> dp = new PrivilegedFindClassByName(name); clazz = AccessController.doPrivileged(dp); } else { clazz = findClassInternal(name); } } catch(AccessControlException ace) { log.warn(sm.getString("webappClassLoader.securityException", name, ace.getMessage()), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } if ((clazz == null) && hasExternalRepositories) { try { clazz = super.findClass(name); } catch(AccessControlException ace) { log.warn(sm.getString("webappClassLoader.securityException", name, ace.getMessage()), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } if (clazz == null) { if (log.isDebugEnabled()) log.debug(" --> Returning ClassNotFoundException"); throw new ClassNotFoundException(name); } } catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; } // Return the class we have located if (log.isTraceEnabled()) log.debug(" Returning class " + clazz); if (log.isTraceEnabled()) { ClassLoader cl; if (Globals.IS_SECURITY_ENABLED){ cl = AccessController.doPrivileged( new PrivilegedGetClassLoader(clazz)); } else { cl = clazz.getClassLoader(); } log.debug(" Loaded by " + cl.toString()); } return clazz; } /** * Find the specified resource in our local repository, and return a * <code>URL</code> referring to it, or <code>null</code> if this resource * cannot be found. * * @param name Name of the resource to be found */ @Override public URL findResource(final String name) { if (log.isDebugEnabled()) log.debug(" findResource(" + name + ")"); checkStateForResourceLoading(name); URL url = null; String path = nameToPath(name); WebResource resource = resources.getClassLoaderResource(path); if (resource.exists()) { url = resource.getURL(); trackLastModified(path, resource); } if ((url == null) && hasExternalRepositories) { url = super.findResource(name); } if (log.isDebugEnabled()) { if (url != null) log.debug(" --> Returning '" + url.toString() + "'"); else log.debug(" --> Resource not found, returning null"); } return url; } private void trackLastModified(String path, WebResource resource) { if (resourceEntries.containsKey(path)) { return; } ResourceEntry entry = new ResourceEntry(); entry.lastModified = resource.getLastModified(); synchronized(resourceEntries) { resourceEntries.putIfAbsent(path, entry); } } /** * Return an enumeration of <code>URLs</code> representing all of the * resources with the given name. If no resources with this name are * found, return an empty enumeration. * * @param name Name of the resources to be found * * @exception IOException if an input/output error occurs */ @Override public Enumeration<URL> findResources(String name) throws IOException { if (log.isDebugEnabled()) log.debug(" findResources(" + name + ")"); checkStateForResourceLoading(name); LinkedHashSet<URL> result = new LinkedHashSet<>(); String path = nameToPath(name); WebResource[] webResources = resources.getClassLoaderResources(path); for (WebResource webResource : webResources) { if (webResource.exists()) { result.add(webResource.getURL()); } } // Adding the results of a call to the superclass if (hasExternalRepositories) { Enumeration<URL> otherResourcePaths = super.findResources(name); while (otherResourcePaths.hasMoreElements()) { result.add(otherResourcePaths.nextElement()); } } return Collections.enumeration(result); } /** * Find the resource with the given name. A resource is some data * (images, audio, text, etc.) that can be accessed by class code in a * way that is independent of the location of the code. The name of a * resource is a "/"-separated path name that identifies the resource. * If the resource cannot be found, return <code>null</code>. * <p> * This method searches according to the following algorithm, returning * as soon as it finds the appropriate URL. If the resource cannot be * found, returns <code>null</code>. * <ul> * <li>If the <code>delegate</code> property is set to <code>true</code>, * call the <code>getResource()</code> method of the parent class * loader, if any.</li> * <li>Call <code>findResource()</code> to find this resource in our * locally defined repositories.</li> * <li>Call the <code>getResource()</code> method of the parent class * loader, if any.</li> * </ul> * * @param name Name of the resource to return a URL for */ @Override public URL getResource(String name) { if (log.isDebugEnabled()) log.debug("getResource(" + name + ")"); checkStateForResourceLoading(name); URL url = null; boolean delegateFirst = delegate || filter(name, false); // (1) Delegate to parent if requested if (delegateFirst) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader " + parent); url = parent.getResource(name); if (url != null) { if (log.isDebugEnabled()) log.debug(" --> Returning '" + url.toString() + "'"); return url; } } // (2) Search local repositories url = findResource(name); if (url != null) { if (log.isDebugEnabled()) log.debug(" --> Returning '" + url.toString() + "'"); return url; } // (3) Delegate to parent unconditionally if not already attempted if (!delegateFirst) { url = parent.getResource(name); if (url != null) { if (log.isDebugEnabled()) log.debug(" --> Returning '" + url.toString() + "'"); return url; } } // (4) Resource was not found if (log.isDebugEnabled()) log.debug(" --> Resource not found, returning null"); return null; } @Override public Enumeration<URL> getResources(String name) throws IOException { Enumeration<URL> parentResources = getParent().getResources(name); Enumeration<URL> localResources = findResources(name); // Need to combine these enumerations. The order in which the // Enumerations are combined depends on how delegation is configured boolean delegateFirst = delegate || filter(name, false); if (delegateFirst) { return new CombinedEnumeration(parentResources, localResources); } else { return new CombinedEnumeration(localResources, parentResources); } } /** * Find the resource with the given name, and return an input stream * that can be used for reading it. The search order is as described * for <code>getResource()</code>, after checking to see if the resource * data has been previously cached. If the resource cannot be found, * return <code>null</code>. * * @param name Name of the resource to return an input stream for */ @Override public InputStream getResourceAsStream(String name) { if (log.isDebugEnabled()) log.debug("getResourceAsStream(" + name + ")"); checkStateForResourceLoading(name); InputStream stream = null; boolean delegateFirst = delegate || filter(name, false); // (1) Delegate to parent if requested if (delegateFirst) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader " + parent); stream = parent.getResourceAsStream(name); if (stream != null) { if (log.isDebugEnabled()) log.debug(" --> Returning stream from parent"); return stream; } } // (2) Search local repositories if (log.isDebugEnabled()) log.debug(" Searching local repositories"); String path = nameToPath(name); WebResource resource = resources.getClassLoaderResource(path); if (resource.exists()) { stream = resource.getInputStream(); trackLastModified(path, resource); } try { if (hasExternalRepositories && stream == null) { URL url = super.findResource(name); if (url != null) { stream = url.openStream(); } } } catch (IOException e) { // Ignore } if (stream != null) { if (log.isDebugEnabled()) log.debug(" --> Returning stream from local"); return stream; } // (3) Delegate to parent unconditionally if (!delegateFirst) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader unconditionally " + parent); stream = parent.getResourceAsStream(name); if (stream != null) { if (log.isDebugEnabled()) log.debug(" --> Returning stream from parent"); return stream; } } // (4) Resource was not found if (log.isDebugEnabled()) log.debug(" --> Resource not found, returning null"); return null; } /** * Load the class with the specified name. This method searches for * classes in the same manner as <code>loadClass(String, boolean)</code> * with <code>false</code> as the second argument. * * @param name The binary name of the class to be loaded * * @exception ClassNotFoundException if the class was not found */ @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return loadClass(name, false); } /** * Load the class with the specified name, searching using the following * algorithm until it finds and returns the class. If the class cannot * be found, returns <code>ClassNotFoundException</code>. * <ul> * <li>Call <code>findLoadedClass(String)</code> to check if the * class has already been loaded. If it has, the same * <code>Class</code> object is returned.</li> * <li>If the <code>delegate</code> property is set to <code>true</code>, * call the <code>loadClass()</code> method of the parent class * loader, if any.</li> * <li>Call <code>findClass()</code> to find this class in our locally * defined repositories.</li> * <li>Call the <code>loadClass()</code> method of our parent * class loader, if any.</li> * </ul> * If the class was found using the above steps, and the * <code>resolve</code> flag is <code>true</code>, this method will then * call <code>resolveClass(Class)</code> on the resulting Class object. * * @param name The binary name of the class to be loaded * @param resolve If <code>true</code> then resolve the class * * @exception ClassNotFoundException if the class was not found */ @Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (JreCompat.isGraalAvailable() ? this : getClassLoadingLock(name)) { if (log.isDebugEnabled()) log.debug("loadClass(" + name + ", " + resolve + ")"); Class<?> clazz = null; // Log access to stopped class loader checkStateForClassLoading(name); // (0) Check our previously loaded local class cache clazz = findLoadedClass0(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return clazz; } // (0.1) Check our previously loaded class cache clazz = JreCompat.isGraalAvailable() ? null : findLoadedClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return clazz; } // (0.2) Try loading the class with the system class loader, to prevent // the webapp from overriding Java SE classes. This implements // SRV.10.7.2 String resourceName = binaryNameToPath(name, false); ClassLoader javaseLoader = getJavaseClassLoader(); boolean tryLoadingFromJavaseLoader; try { // Use getResource as it won't trigger an expensive // ClassNotFoundException if the resource is not available from // the Java SE class loader. However (see // https://bz.apache.org/bugzilla/show_bug.cgi?id=58125 for // details) when running under a security manager in rare cases // this call may trigger a ClassCircularityError. // See https://bz.apache.org/bugzilla/show_bug.cgi?id=61424 for // details of how this may trigger a StackOverflowError // Given these reported errors, catch Throwable to ensure any // other edge cases are also caught URL url; if (securityManager != null) { PrivilegedAction<URL> dp = new PrivilegedJavaseGetResource(resourceName); url = AccessController.doPrivileged(dp); } else { url = javaseLoader.getResource(resourceName); } tryLoadingFromJavaseLoader = (url != null); } catch (Throwable t) { // Swallow all exceptions apart from those that must be re-thrown ExceptionUtils.handleThrowable(t); // The getResource() trick won't work for this class. We have to // try loading it directly and accept that we might get a // ClassNotFoundException. tryLoadingFromJavaseLoader = true; } if (tryLoadingFromJavaseLoader) { try { clazz = javaseLoader.loadClass(name); if (clazz != null) { if (resolve) resolveClass(clazz); return clazz; } } catch (ClassNotFoundException e) { // Ignore } } // (0.5) Permission to access this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { securityManager.checkPackageAccess(name.substring(0,i)); } catch (SecurityException se) { String error = sm.getString("webappClassLoader.restrictedPackage", name); log.info(error, se); throw new ClassNotFoundException(error, se); } } } boolean delegateLoad = delegate || filter(name, true); // (1) Delegate to our parent if requested if (delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader1 " + parent); try { clazz = Class.forName(name, false, parent); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return clazz; } } catch (ClassNotFoundException e) { // Ignore } } // (2) Search local repositories if (log.isDebugEnabled()) log.debug(" Searching local repositories"); try { clazz = findClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from local repository"); if (resolve) resolveClass(clazz); return clazz; } } catch (ClassNotFoundException e) { // Ignore } // (3) Delegate to parent unconditionally if (!delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader at end: " + parent); try { clazz = Class.forName(name, false, parent); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return clazz; } } catch (ClassNotFoundException e) { // Ignore } } } throw new ClassNotFoundException(name); } protected void checkStateForClassLoading(String className) throws ClassNotFoundException { // It is not permitted to load new classes once the web application has // been stopped. try { checkStateForResourceLoading(className); } catch (IllegalStateException ise) { throw new ClassNotFoundException(ise.getMessage(), ise); } } protected void checkStateForResourceLoading(String resource) throws IllegalStateException { // It is not permitted to load resources once the web application has // been stopped. if (!state.isAvailable()) { String msg = sm.getString("webappClassLoader.stopped", resource); IllegalStateException ise = new IllegalStateException(msg); log.info(msg, ise); throw ise; } } /** * Get the Permissions for a CodeSource. If this instance * of WebappClassLoaderBase is for a web application context, * add read FilePermission for the appropriate resources. * * @param codeSource where the code was loaded from * @return PermissionCollection for CodeSource */ @Override protected PermissionCollection getPermissions(CodeSource codeSource) { String codeUrl = codeSource.getLocation().toString(); PermissionCollection pc; if ((pc = loaderPC.get(codeUrl)) == null) { pc = super.getPermissions(codeSource); if (pc != null) { for (Permission p : permissionList) { pc.add(p); } loaderPC.put(codeUrl,pc); } } return pc; } @Override public boolean check(Permission permission) { if (!Globals.IS_SECURITY_ENABLED) { return true; } Policy currentPolicy = Policy.getPolicy(); if (currentPolicy != null) { URL contextRootUrl = resources.getResource("/").getCodeBase(); CodeSource cs = new CodeSource(contextRootUrl, (Certificate[]) null); PermissionCollection pc = currentPolicy.getPermissions(cs); if (pc.implies(permission)) { return true; } } return false; } /** * {@inheritDoc} * <p> * Note that list of URLs returned by this method may not be complete. The * web application class loader accesses class loader resources via the * {@link WebResourceRoot} which supports the arbitrary mapping of * additional files, directories and contents of JAR files under * WEB-INF/classes. Any such resources will not be included in the URLs * returned here. */ @Override public URL[] getURLs() { ArrayList<URL> result = new ArrayList<>(); result.addAll(localRepositories); result.addAll(Arrays.asList(super.getURLs())); return result.toArray(new URL[0]); } // ------------------------------------------------------ Lifecycle Methods /** * Add a lifecycle event listener to this component. * * @param listener The listener to add */ @Override public void addLifecycleListener(LifecycleListener listener) { // NOOP } /** * Get the lifecycle listeners associated with this lifecycle. If this * Lifecycle has no listeners registered, a zero-length array is returned. */ @Override public LifecycleListener[] findLifecycleListeners() { return new LifecycleListener[0]; } /** * Remove a lifecycle event listener from this component. * * @param listener The listener to remove */ @Override public void removeLifecycleListener(LifecycleListener listener) { // NOOP } /** * Obtain the current state of the source component. * * @return The current state of the source component. */ @Override public LifecycleState getState() { return state; } /** * {@inheritDoc} */ @Override public String getStateName() { return getState().toString(); } @Override public void init() { state = LifecycleState.INITIALIZED; } /** * Start the class loader. * * @exception LifecycleException if a lifecycle error occurs */ @Override public void start() throws LifecycleException { state = LifecycleState.STARTING_PREP; WebResource[] classesResources = resources.getResources("/WEB-INF/classes"); for (WebResource classes : classesResources) { if (classes.isDirectory() && classes.canRead()) { localRepositories.add(classes.getURL()); } } WebResource[] jars = resources.listResources("/WEB-INF/lib"); for (WebResource jar : jars) { if (jar.getName().endsWith(".jar") && jar.isFile() && jar.canRead()) { localRepositories.add(jar.getURL()); jarModificationTimes.put( jar.getName(), Long.valueOf(jar.getLastModified())); } } state = LifecycleState.STARTED; } /** * Stop the class loader. * * @exception LifecycleException if a lifecycle error occurs */ @Override public void stop() throws LifecycleException { state = LifecycleState.STOPPING_PREP; // Clearing references should be done before setting started to // false, due to possible side effects clearReferences(); state = LifecycleState.STOPPING; resourceEntries.clear(); jarModificationTimes.clear(); resources = null; permissionList.clear(); loaderPC.clear(); state = LifecycleState.STOPPED; } @Override public void destroy() { state = LifecycleState.DESTROYING; try { super.close(); } catch (IOException ioe) { log.warn(sm.getString("webappClassLoader.superCloseFail"), ioe); } state = LifecycleState.DESTROYED; } // ------------------------------------------------------ Protected Methods protected ClassLoader getJavaseClassLoader() { return javaseClassLoader; } protected void setJavaseClassLoader(ClassLoader classLoader) { if (classLoader == null) { throw new IllegalArgumentException( sm.getString("webappClassLoader.javaseClassLoaderNull")); } javaseClassLoader = classLoader; } /** * Clear references. */ protected void clearReferences() { // If the JVM is shutting down, skip the memory leak checks if (skipMemoryLeakChecksOnJvmShutdown && !resources.getContext().getParent().getState().isAvailable()) { // During reloading / redeployment the parent is expected to be // available. Parent is not available so this might be a JVM // shutdown. try { Thread dummyHook = new Thread(); Runtime.getRuntime().addShutdownHook(dummyHook); Runtime.getRuntime().removeShutdownHook(dummyHook); } catch (IllegalStateException ise) { return; } } if (!JreCompat.isGraalAvailable()) { // De-register any remaining JDBC drivers clearReferencesJdbc(); } // Stop any threads the web application started clearReferencesThreads(); // Clear any references retained in the serialization caches if (clearReferencesObjectStreamClassCaches && !JreCompat.isGraalAvailable()) { clearReferencesObjectStreamClassCaches(); } // Check for leaks triggered by ThreadLocals loaded by this class loader if (clearReferencesThreadLocals && !JreCompat.isGraalAvailable()) { checkThreadLocalsForLeaks(); } // Clear RMI Targets loaded by this class loader if (clearReferencesRmiTargets) { clearReferencesRmiTargets(); } // Clear the IntrospectionUtils cache. IntrospectionUtils.clear(); // Clear the classloader reference in common-logging if (clearReferencesLogFactoryRelease) { org.apache.juli.logging.LogFactory.release(this); } // Clear the classloader reference in the VM's bean introspector java.beans.Introspector.flushCaches(); // Clear any custom URLStreamHandlers TomcatURLStreamHandlerFactory.release(this); } /** * Deregister any JDBC drivers registered by the webapp that the webapp * forgot. This is made unnecessary complex because a) DriverManager * checks the class loader of the calling class (it would be much easier * if it checked the context class loader) b) using reflection would * create a dependency on the DriverManager implementation which can, * and has, changed. * * We can't just create an instance of JdbcLeakPrevention as it will be * loaded by the common class loader (since it's .class file is in the * $CATALINA_HOME/lib directory). This would fail DriverManager's check * on the class loader of the calling class. So, we load the bytes via * our parent class loader but define the class with this class loader * so the JdbcLeakPrevention looks like a webapp class to the * DriverManager. * * If only apps cleaned up after themselves... */ private final void clearReferencesJdbc() { // We know roughly how big the class will be (~ 1K) so allow 2k as a // starting point byte[] classBytes = new byte[2048]; int offset = 0; try (InputStream is = getResourceAsStream( "org/apache/catalina/loader/JdbcLeakPrevention.class")) { int read = is.read(classBytes, offset, classBytes.length-offset); while (read > -1) { offset += read; if (offset == classBytes.length) { // Buffer full - double size byte[] tmp = new byte[classBytes.length * 2]; System.arraycopy(classBytes, 0, tmp, 0, classBytes.length); classBytes = tmp; } read = is.read(classBytes, offset, classBytes.length-offset); } Class<?> lpClass = defineClass("org.apache.catalina.loader.JdbcLeakPrevention", classBytes, 0, offset, this.getClass().getProtectionDomain()); Object obj = lpClass.getConstructor().newInstance(); @SuppressWarnings("unchecked") List<String> driverNames = (List<String>) obj.getClass().getMethod( "clearJdbcDriverRegistrations").invoke(obj); for (String name : driverNames) { log.warn(sm.getString("webappClassLoader.clearJdbc", getContextName(), name)); } } catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.jdbcRemoveFailed", getContextName()), t); } } @SuppressWarnings("deprecation") // thread.stop() private void clearReferencesThreads() { Thread[] threads = getThreads(); List<Thread> threadsToStop = new ArrayList<>(); // Iterate over the set of threads for (Thread thread : threads) { if (thread != null) { ClassLoader ccl = thread.getContextClassLoader(); if (ccl == this) { // Don't warn about this thread if (thread == Thread.currentThread()) { continue; } final String threadName = thread.getName(); // JVM controlled threads ThreadGroup tg = thread.getThreadGroup(); if (tg != null && JVM_THREAD_GROUP_NAMES.contains(tg.getName())) { // HttpClient keep-alive threads if (clearReferencesHttpClientKeepAliveThread && threadName.equals("Keep-Alive-Timer")) { thread.setContextClassLoader(parent); log.debug(sm.getString("webappClassLoader.checkThreadsHttpClient")); } // Don't warn about remaining JVM controlled threads continue; } // Skip threads that have already died if (!thread.isAlive()) { continue; } // TimerThread can be stopped safely so treat separately // "java.util.TimerThread" in Sun/Oracle JDK // "java.util.Timer$TimerImpl" in Apache Harmony and in IBM JDK if (thread.getClass().getName().startsWith("java.util.Timer") && clearReferencesStopTimerThreads) { clearReferencesStopTimerThread(thread); continue; } if (isRequestThread(thread)) { log.warn(sm.getString("webappClassLoader.stackTraceRequestThread", getContextName(), threadName, getStackTrace(thread))); } else { log.warn(sm.getString("webappClassLoader.stackTrace", getContextName(), threadName, getStackTrace(thread))); } // Don't try and stop the threads unless explicitly // configured to do so if (!clearReferencesStopThreads) { continue; } // If the thread has been started via an executor, try // shutting down the executor boolean usingExecutor = false; try { // Runnable wrapped by Thread // "target" in Sun/Oracle JDK // "runnable" in IBM JDK // "action" in Apache Harmony Object target = null; for (String fieldName : new String[] { "target", "runnable", "action" }) { try { Field targetField = thread.getClass().getDeclaredField(fieldName); targetField.setAccessible(true); target = targetField.get(thread); break; } catch (NoSuchFieldException nfe) { continue; } } // "java.util.concurrent" code is in public domain, // so all implementations are similar if (target != null && target.getClass().getCanonicalName() != null && target.getClass().getCanonicalName().equals( "java.util.concurrent.ThreadPoolExecutor.Worker")) { Field executorField = target.getClass().getDeclaredField("this$0"); executorField.setAccessible(true); Object executor = executorField.get(target); if (executor instanceof ThreadPoolExecutor) { ((ThreadPoolExecutor) executor).shutdownNow(); usingExecutor = true; } } } catch (NoSuchFieldException | IllegalAccessException | RuntimeException e) { // InaccessibleObjectException is only available in Java 9+, // swapped for RuntimeException log.warn(sm.getString("webappClassLoader.stopThreadFail", thread.getName(), getContextName()), e); } // Stopping an executor automatically interrupts the // associated threads. For non-executor threads, interrupt // them here. if (!usingExecutor && !thread.isInterrupted()) { thread.interrupt(); } // Threads are expected to take a short time to stop after // being interrupted. Make a note of all threads that are // expected to stop to enable them to be checked at the end // of this method. threadsToStop.add(thread); } } } // If thread stopping is enabled, threads should have been stopped above // when the executor was shut down or the thread was interrupted but // that depends on the thread correctly handling the interrupt. Check // each thread and if any are still running give all threads up to a // total of 2 seconds to shutdown. int count = 0; for (Thread t : threadsToStop) { while (t.isAlive() && count < 100) { try { Thread.sleep(20); } catch (InterruptedException e) { // Quit the while loop break; } count++; } if (t.isAlive()) { // This method is deprecated and for good reason. This is // very risky code but is the only option at this point. // A *very* good reason for apps to do this clean-up // themselves. t.stop(); } } } /* * Look at a threads stack trace to see if it is a request thread or not. It * isn't perfect, but it should be good-enough for most cases. */ private boolean isRequestThread(Thread thread) { StackTraceElement[] elements = thread.getStackTrace(); if (elements == null || elements.length == 0) { // Must have stopped already. Too late to ignore it. Assume not a // request processing thread. return false; } // Step through the methods in reverse order looking for calls to any // CoyoteAdapter method. All request threads will have this unless // Tomcat has been heavily modified - in which case there isn't much we // can do. for (int i = 0; i < elements.length; i++) { StackTraceElement element = elements[elements.length - (i+1)]; if ("org.apache.catalina.connector.CoyoteAdapter".equals( element.getClassName())) { return true; } } return false; } private void clearReferencesStopTimerThread(Thread thread) { // Need to get references to: // in Sun/Oracle JDK: // - newTasksMayBeScheduled field (in java.util.TimerThread) // - queue field // - queue.clear() // in IBM JDK, Apache Harmony: // - cancel() method (in java.util.Timer$TimerImpl) try { try { Field newTasksMayBeScheduledField = thread.getClass().getDeclaredField("newTasksMayBeScheduled"); newTasksMayBeScheduledField.setAccessible(true); Field queueField = thread.getClass().getDeclaredField("queue"); queueField.setAccessible(true); Object queue = queueField.get(thread); Method clearMethod = queue.getClass().getDeclaredMethod("clear"); clearMethod.setAccessible(true); synchronized(queue) { newTasksMayBeScheduledField.setBoolean(thread, false); clearMethod.invoke(queue); // In case queue was already empty. Should only be one // thread waiting but use notifyAll() to be safe. queue.notifyAll(); } }catch (NoSuchFieldException nfe){ Method cancelMethod = thread.getClass().getDeclaredMethod("cancel"); synchronized(thread) { cancelMethod.setAccessible(true); cancelMethod.invoke(thread); } } log.warn(sm.getString("webappClassLoader.warnTimerThread", getContextName(), thread.getName())); } catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.stopTimerThreadFail", thread.getName(), getContextName()), t); } } private void checkThreadLocalsForLeaks() { Thread[] threads = getThreads(); try { // Make the fields in the Thread class that store ThreadLocals // accessible Field threadLocalsField = Thread.class.getDeclaredField("threadLocals"); threadLocalsField.setAccessible(true); Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals"); inheritableThreadLocalsField.setAccessible(true); // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects // accessible Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap"); Field tableField = tlmClass.getDeclaredField("table"); tableField.setAccessible(true); Method expungeStaleEntriesMethod = tlmClass.getDeclaredMethod("expungeStaleEntries"); expungeStaleEntriesMethod.setAccessible(true); for (Thread thread : threads) { Object threadLocalMap; if (thread != null) { // Clear the first map threadLocalMap = threadLocalsField.get(thread); if (null != threadLocalMap) { expungeStaleEntriesMethod.invoke(threadLocalMap); checkThreadLocalMapForLeaks(threadLocalMap, tableField); } // Clear the second map threadLocalMap = inheritableThreadLocalsField.get(thread); if (null != threadLocalMap) { expungeStaleEntriesMethod.invoke(threadLocalMap); checkThreadLocalMapForLeaks(threadLocalMap, tableField); } } } } catch (Throwable t) { JreCompat jreCompat = JreCompat.getInstance(); if (jreCompat.isInstanceOfInaccessibleObjectException(t)) { // Must be running on Java 9 without the necessary command line // options. String currentModule = JreCompat.getInstance().getModuleName(this.getClass()); log.warn(sm.getString("webappClassLoader.addExportsThreadLocal", currentModule)); } else { ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.checkThreadLocalsForLeaksFail", getContextName()), t); } } } /** * Analyzes the given thread local map object. Also pass in the field that * points to the internal table to save re-calculating it on every * call to this method. */ private void checkThreadLocalMapForLeaks(Object map, Field internalTableField) throws IllegalAccessException, NoSuchFieldException { if (map != null) { Object[] table = (Object[]) internalTableField.get(map); if (table != null) { for (Object obj : table) { if (obj != null) { boolean keyLoadedByWebapp = false; boolean valueLoadedByWebapp = false; // Check the key Object key = ((Reference<?>) obj).get(); if (this.equals(key) || loadedByThisOrChild(key)) { keyLoadedByWebapp = true; } // Check the value Field valueField = obj.getClass().getDeclaredField("value"); valueField.setAccessible(true); Object value = valueField.get(obj); if (this.equals(value) || loadedByThisOrChild(value)) { valueLoadedByWebapp = true; } if (keyLoadedByWebapp || valueLoadedByWebapp) { Object[] args = new Object[5]; args[0] = getContextName(); if (key != null) { args[1] = getPrettyClassName(key.getClass()); try { args[2] = key.toString(); } catch (Exception e) { log.warn(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badKey", args[1]), e); args[2] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); } } if (value != null) { args[3] = getPrettyClassName(value.getClass()); try { args[4] = value.toString(); } catch (Exception e) { log.warn(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badValue", args[3]), e); args[4] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); } } if (valueLoadedByWebapp) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks", args)); } else if (value == null) { if (log.isDebugEnabled()) { log.debug(sm.getString( "webappClassLoader.checkThreadLocalsForLeaksNull", args)); } } else { if (log.isDebugEnabled()) { log.debug(sm.getString( "webappClassLoader.checkThreadLocalsForLeaksNone", args)); } } } } } } } } private String getPrettyClassName(Class<?> clazz) { String name = clazz.getCanonicalName(); if (name==null){ name = clazz.getName(); } return name; } private String getStackTrace(Thread thread) { StringBuilder builder = new StringBuilder(); for (StackTraceElement ste : thread.getStackTrace()) { builder.append("\n ").append(ste); } return builder.toString(); } /** * @param o object to test, may be null * @return <code>true</code> if o has been loaded by the current classloader * or one of its descendants. */ private boolean loadedByThisOrChild(Object o) { if (o == null) { return false; } Class<?> clazz; if (o instanceof Class) { clazz = (Class<?>) o; } else { clazz = o.getClass(); } ClassLoader cl = clazz.getClassLoader(); while (cl != null) { if (cl == this) { return true; } cl = cl.getParent(); } if (o instanceof Collection<?>) { Iterator<?> iter = ((Collection<?>) o).iterator(); try { while (iter.hasNext()) { Object entry = iter.next(); if (loadedByThisOrChild(entry)) { return true; } } } catch (ConcurrentModificationException e) { log.warn(sm.getString( "webappClassLoader.loadedByThisOrChildFail", clazz.getName(), getContextName()), e); } } return false; } /* * Get the set of current threads as an array. */ private Thread[] getThreads() { // Get the current thread group ThreadGroup tg = Thread.currentThread().getThreadGroup(); // Find the root thread group try { while (tg.getParent() != null) { tg = tg.getParent(); } } catch (SecurityException se) { String msg = sm.getString( "webappClassLoader.getThreadGroupError", tg.getName()); if (log.isDebugEnabled()) { log.debug(msg, se); } else { log.warn(msg); } } int threadCountGuess = tg.activeCount() + 50; Thread[] threads = new Thread[threadCountGuess]; int threadCountActual = tg.enumerate(threads); // Make sure we don't miss any threads while (threadCountActual == threadCountGuess) { threadCountGuess *=2; threads = new Thread[threadCountGuess]; // Note tg.enumerate(Thread[]) silently ignores any threads that // can't fit into the array threadCountActual = tg.enumerate(threads); } return threads; } /** * This depends on the internals of the Sun JVM so it does everything by * reflection. */ private void clearReferencesRmiTargets() { try { // Need access to the ccl field of sun.rmi.transport.Target to find // the leaks Class<?> objectTargetClass = Class.forName("sun.rmi.transport.Target"); Field cclField = objectTargetClass.getDeclaredField("ccl"); cclField.setAccessible(true); // Need access to the stub field to report the leaks Field stubField = objectTargetClass.getDeclaredField("stub"); stubField.setAccessible(true); // Clear the objTable map Class<?> objectTableClass = Class.forName("sun.rmi.transport.ObjectTable"); Field objTableField = objectTableClass.getDeclaredField("objTable"); objTableField.setAccessible(true); Object objTable = objTableField.get(null); if (objTable == null) { return; } Field tableLockField = objectTableClass.getDeclaredField("tableLock"); tableLockField.setAccessible(true); Object tableLock = tableLockField.get(null); synchronized (tableLock) { // Iterate over the values in the table if (objTable instanceof Map<?,?>) { Iterator<?> iter = ((Map<?,?>) objTable).values().iterator(); while (iter.hasNext()) { Object obj = iter.next(); Object cclObject = cclField.get(obj); if (this == cclObject) { iter.remove(); Object stubObject = stubField.get(obj); log.error(sm.getString("webappClassLoader.clearRmi", stubObject.getClass().getName(), stubObject)); } } } // Clear the implTable map Field implTableField = objectTableClass.getDeclaredField("implTable"); implTableField.setAccessible(true); Object implTable = implTableField.get(null); if (implTable == null) { return; } // Iterate over the values in the table if (implTable instanceof Map<?,?>) { Iterator<?> iter = ((Map<?,?>) implTable).values().iterator(); while (iter.hasNext()) { Object obj = iter.next(); Object cclObject = cclField.get(obj); if (this == cclObject) { iter.remove(); } } } } } catch (ClassNotFoundException e) { log.info(sm.getString("webappClassLoader.clearRmiInfo", getContextName()), e); } catch (SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", getContextName()), e); } catch (Exception e) { JreCompat jreCompat = JreCompat.getInstance(); if (jreCompat.isInstanceOfInaccessibleObjectException(e)) { // Must be running on Java 9 without the necessary command line // options. String currentModule = JreCompat.getInstance().getModuleName(this.getClass()); log.warn(sm.getString("webappClassLoader.addExportsRmi", currentModule)); } else { // Re-throw all other exceptions throw e; } } } private void clearReferencesObjectStreamClassCaches() { try { Class<?> clazz = Class.forName("java.io.ObjectStreamClass$Caches"); clearCache(clazz, "localDescs"); clearCache(clazz, "reflectors"); } catch (ReflectiveOperationException | SecurityException | ClassCastException e) { log.warn(sm.getString( "webappClassLoader.clearObjectStreamClassCachesFail", getContextName()), e); } catch (Exception e) { JreCompat jreCompat = JreCompat.getInstance(); if (jreCompat.isInstanceOfInaccessibleObjectException(e)) { // Must be running on Java 9 without the necessary command line // options. String currentModule = JreCompat.getInstance().getModuleName(this.getClass()); log.warn(sm.getString("webappClassLoader.addExportsJavaIo", currentModule)); return; } else { // Re-throw all other exceptions throw e; } } } private void clearCache(Class<?> target, String mapName) throws ReflectiveOperationException, SecurityException, ClassCastException { Field f = target.getDeclaredField(mapName); f.setAccessible(true); Map<?,?> map = (Map<?,?>) f.get(null); Iterator<?> keys = map.keySet().iterator(); while (keys.hasNext()) { Object key = keys.next(); if (key instanceof Reference) { Object clazz = ((Reference<?>) key).get(); if (loadedByThisOrChild(clazz)) { keys.remove(); } } } } /** * Find specified class in local repositories. * * @param name The binary name of the class to be loaded * * @return the loaded class, or null if the class isn't found */ protected Class<?> findClassInternal(String name) { checkStateForResourceLoading(name); if (name == null) { return null; } String path = binaryNameToPath(name, true); ResourceEntry entry = resourceEntries.get(path); WebResource resource = null; if (entry == null) { resource = resources.getClassLoaderResource(path); if (!resource.exists()) { return null; } entry = new ResourceEntry(); entry.lastModified = resource.getLastModified(); // Add the entry in the local resource repository synchronized (resourceEntries) { // Ensures that all the threads which may be in a race to load // a particular class all end up with the same ResourceEntry // instance ResourceEntry entry2 = resourceEntries.get(path); if (entry2 == null) { resourceEntries.put(path, entry); } else { entry = entry2; } } } Class<?> clazz = entry.loadedClass; if (clazz != null) return clazz; synchronized (JreCompat.isGraalAvailable() ? this : getClassLoadingLock(name)) { clazz = entry.loadedClass; if (clazz != null) return clazz; if (resource == null) { resource = resources.getClassLoaderResource(path); } if (!resource.exists()) { return null; } byte[] binaryContent = resource.getContent(); if (binaryContent == null) { // Something went wrong reading the class bytes (and will have // been logged at debug level). return null; } Manifest manifest = resource.getManifest(); URL codeBase = resource.getCodeBase(); Certificate[] certificates = resource.getCertificates(); if (transformers.size() > 0) { // If the resource is a class just being loaded, decorate it // with any attached transformers // Ignore leading '/' and trailing CLASS_FILE_SUFFIX // Should be cheaper than replacing '.' by '/' in class name. String internalName = path.substring(1, path.length() - CLASS_FILE_SUFFIX.length()); for (ClassFileTransformer transformer : this.transformers) { try { byte[] transformed = transformer.transform( this, internalName, null, null, binaryContent); if (transformed != null) { binaryContent = transformed; } } catch (IllegalClassFormatException e) { log.error(sm.getString("webappClassLoader.transformError", name), e); return null; } } } // Looking up the package String packageName = null; int pos = name.lastIndexOf('.'); if (pos != -1) packageName = name.substring(0, pos); Package pkg = null; if (packageName != null) { pkg = getPackage(packageName); // Define the package (if null) if (pkg == null) { try { if (manifest == null) { definePackage(packageName, null, null, null, null, null, null, null); } else { definePackage(packageName, manifest, codeBase); } } catch (IllegalArgumentException e) { // Ignore: normal error due to dual definition of package } pkg = getPackage(packageName); } } if (securityManager != null) { // Checking sealing if (pkg != null) { boolean sealCheck = true; if (pkg.isSealed()) { sealCheck = pkg.isSealed(codeBase); } else { sealCheck = (manifest == null) || !isPackageSealed(packageName, manifest); } if (!sealCheck) throw new SecurityException ("Sealing violation loading " + name + " : Package " + packageName + " is sealed."); } } try { clazz = defineClass(name, binaryContent, 0, binaryContent.length, new CodeSource(codeBase, certificates)); } catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); } entry.loadedClass = clazz; } return clazz; } private String binaryNameToPath(String binaryName, boolean withLeadingSlash) { // 1 for leading '/', 6 for ".class" StringBuilder path = new StringBuilder(7 + binaryName.length()); if (withLeadingSlash) { path.append('/'); } path.append(binaryName.replace('.', '/')); path.append(CLASS_FILE_SUFFIX); return path.toString(); } private String nameToPath(String name) { if (name.startsWith("/")) { return name; } StringBuilder path = new StringBuilder( 1 + name.length()); path.append('/'); path.append(name); return path.toString(); } /** * Returns true if the specified package name is sealed according to the * given manifest. * * @param name Path name to check * @param man Associated manifest * @return <code>true</code> if the manifest associated says it is sealed */ protected boolean isPackageSealed(String name, Manifest man) { String path = name.replace('.', '/') + '/'; Attributes attr = man.getAttributes(path); String sealed = null; if (attr != null) { sealed = attr.getValue(Name.SEALED); } if (sealed == null) { if ((attr = man.getMainAttributes()) != null) { sealed = attr.getValue(Name.SEALED); } } return "true".equalsIgnoreCase(sealed); } /** * Finds the class with the given name if it has previously been * loaded and cached by this class loader, and return the Class object. * If this class has not been cached, return <code>null</code>. * * @param name The binary name of the resource to return * @return a loaded class */ protected Class<?> findLoadedClass0(String name) { String path = binaryNameToPath(name, true); ResourceEntry entry = resourceEntries.get(path); if (entry != null) { return entry.loadedClass; } return null; } /** * Refresh the system policy file, to pick up eventual changes. */ protected void refreshPolicy() { try { // The policy file may have been modified to adjust // permissions, so we're reloading it when loading or // reloading a Context Policy policy = Policy.getPolicy(); policy.refresh(); } catch (AccessControlException e) { // Some policy files may restrict this, even for the core, // so this exception is ignored } } /** * Filter classes. * * @param name class name * @param isClassName <code>true</code> if name is a class name, * <code>false</code> if name is a resource name * @return <code>true</code> if the class should be filtered */ protected boolean filter(String name, boolean isClassName) { if (name == null) return false; char ch; if (name.startsWith("javax")) { /* 5 == length("javax") */ if (name.length() == 5) { return false; } ch = name.charAt(5); if (isClassName && ch == '.') { /* 6 == length("javax.") */ if (name.startsWith("servlet.jsp.jstl.", 6)) { return false; } if (name.startsWith("el.", 6) || name.startsWith("servlet.", 6) || name.startsWith("websocket.", 6) || name.startsWith("security.auth.message.", 6)) { return true; } } else if (!isClassName && ch == '/') { /* 6 == length("javax/") */ if (name.startsWith("servlet/jsp/jstl/", 6)) { return false; } if (name.startsWith("el/", 6) || name.startsWith("servlet/", 6) || name.startsWith("websocket/", 6) || name.startsWith("security/auth/message/", 6)) { return true; } } } else if (name.startsWith("org")) { /* 3 == length("org") */ if (name.length() == 3) { return false; } ch = name.charAt(3); if (isClassName && ch == '.') { /* 4 == length("org.") */ if (name.startsWith("apache.", 4)) { /* 11 == length("org.apache.") */ if (name.startsWith("tomcat.jdbc.", 11)) { return false; } if (name.startsWith("el.", 11) || name.startsWith("catalina.", 11) || name.startsWith("jasper.", 11) || name.startsWith("juli.", 11) || name.startsWith("tomcat.", 11) || name.startsWith("naming.", 11) || name.startsWith("coyote.", 11)) { return true; } } } else if (!isClassName && ch == '/') { /* 4 == length("org/") */ if (name.startsWith("apache/", 4)) { /* 11 == length("org/apache/") */ if (name.startsWith("tomcat/jdbc/", 11)) { return false; } if (name.startsWith("el/", 11) || name.startsWith("catalina/", 11) || name.startsWith("jasper/", 11) || name.startsWith("juli/", 11) || name.startsWith("tomcat/", 11) || name.startsWith("naming/", 11) || name.startsWith("coyote/", 11)) { return true; } } } } return false; } @Override protected void addURL(URL url) { super.addURL(url); hasExternalRepositories = true; } @Override public String getWebappName() { return getContextName(); } @Override public String getHostName() { if (resources != null) { Container host = resources.getContext().getParent(); if (host != null) { return host.getName(); } } return null; } @Override public String getServiceName() { if (resources != null) { Container host = resources.getContext().getParent(); if (host != null) { Container engine = host.getParent(); if (engine != null) { return engine.getName(); } } } return null; } @Override public boolean hasLoggingConfig() { if (Globals.IS_SECURITY_ENABLED) { Boolean result = AccessController.doPrivileged(new PrivilegedHasLoggingConfig()); return result.booleanValue(); } else { return findResource("logging.properties") != null; } } private class PrivilegedHasLoggingConfig implements PrivilegedAction<Boolean> { @Override public Boolean run() { return Boolean.valueOf(findResource("logging.properties") != null); } } private static class CombinedEnumeration implements Enumeration<URL> { private final Enumeration<URL>[] sources; private int index = 0; public CombinedEnumeration(Enumeration<URL> enum1, Enumeration<URL> enum2) { @SuppressWarnings("unchecked") Enumeration<URL>[] sources = new Enumeration[] { enum1, enum2 }; this.sources = sources; } @Override public boolean hasMoreElements() { return inc(); } @Override public URL nextElement() { if (inc()) { return sources[index].nextElement(); } throw new NoSuchElementException(); } private boolean inc() { while (index < sources.length) { if (sources[index].hasMoreElements()) { return true; } index++; } return false; } } }
c69c51e70affdca6b26185769c8e0540b99507a3
cb50cf3b3d76dee396429ac57f0cfef49e39133f
/DaffIEOperation/src/com/daffodil/documentumie/scheduleie/model/apiimpl/EScheduleSort.java
4b44ef44e9aca7894642bfbfd56c603cab7828a5
[]
no_license
Naveen1987/utility
abf52b932dd8ea21b4b20a798df9275bba0f5df2
8ad9c88c2cac4264cc507ee704ef4116be5674cf
refs/heads/master
2021-01-23T05:56:31.953739
2017-03-28T12:41:58
2017-03-28T12:41:58
86,324,203
1
1
null
2017-03-28T12:44:31
2017-03-27T10:51:34
Java
UTF-8
Java
false
false
1,275
java
package com.daffodil.documentumie.scheduleie.model.apiimpl; import java.util.Comparator; import java.util.Date; import com.daffodil.documentumie.scheduleie.bean.EScheduleConfigBean; import com.daffodil.documentumie.scheduleie.bean.IScheduleConfigBean; public class EScheduleSort implements Comparator<EScheduleSort> { private int index; private EScheduleConfigBean configBean; private Date nextScheduleDate; public EScheduleSort(int index, EScheduleConfigBean configBean, Date nextScheduleDate) { super(); this.index = index; this.configBean = configBean; this.nextScheduleDate = nextScheduleDate; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public EScheduleConfigBean getConfigBean() { return configBean; } public void setConfigBean(EScheduleConfigBean configBean) { this.configBean = configBean; } public Date getNextScheduleDate() { return nextScheduleDate; } public void setNextScheduleDate(Date nextScheduleDate) { this.nextScheduleDate = nextScheduleDate; } @Override public int compare(EScheduleSort arg0, EScheduleSort arg1) { if(arg0.getNextScheduleDate().getTime() - arg1.getNextScheduleDate().getTime()>=0) { return 1; } else{ return 0; } } }
[ "Adminstrator" ]
Adminstrator
54d19c91251065a0949b7ad630889cf9b9f17db8
4639f621eef426621b3fdb6bfd921d01b123344d
/src/br/com/MyMoviesDB/model/DAO/BaseInterDAO.java
b093dc3824d67619094c58f5918fcfb5a3b82299
[]
no_license
RianC4rl0s/MyMoviesDB
c8c1035138c86b5583d30a194c42b55480455830
089f32f7d83d06209617e20ecd3d7a30628238ac
refs/heads/main
2023-05-02T14:18:01.241826
2021-05-31T13:06:20
2021-05-31T13:06:20
380,117,917
1
0
null
2021-06-25T03:54:23
2021-06-25T03:54:22
null
UTF-8
Java
false
false
204
java
package br.com.MyMoviesDB.model.DAO; import java.io.IOException; public interface BaseInterDAO<T> { void writer(T list) throws IOException; T reader() throws IOException, ClassNotFoundException; }
e355fbe97f250b9c6bed0595f894f68c31a9ff72
debd61c4c40fac291183e35e91a5af84f711ad6c
/app/src/main/java/com/example/funmusic/utility/CustomStringRequest.java
7471967b8fbf81fde3c7bae899034fcd4e8f24d2
[]
no_license
giriseema/FunMusic
b210723605dab9ccb3ec2350e0fc1e2b1ce3245f
4b49f3e59c7ac3efc2851399e933472c3e9ac82f
refs/heads/master
2020-08-26T12:51:10.362322
2019-10-23T09:13:50
2019-10-23T09:13:50
217,015,582
0
0
null
null
null
null
UTF-8
Java
false
false
2,374
java
package com.example.funmusic.utility; import android.content.Context; import android.util.Log; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import com.android.volley.toolbox.HttpHeaderParser; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; public class CustomStringRequest extends Request<JSONObject> { private Listener<JSONObject> listener; private String methodName; private Context context; private long lastRequestStartTime; public CustomStringRequest(String url, Listener<JSONObject> reponseListener, ErrorListener errorListener) { super(Method.GET, url, errorListener); this.listener = reponseListener; } public CustomStringRequest(Context context, int method, String url, String methodName, Listener<JSONObject> reponseListener, ErrorListener errorListener) { super(method, url, errorListener); this.listener = reponseListener; this.methodName = methodName; this.context = context; } @Override protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { Log.e(CustomStringRequest.class.getSimpleName() + " Response Error:", e.toString()); return Response.error(new ParseError(e)); } catch (JSONException je) { Log.e(CustomStringRequest.class.getSimpleName() + " Response Error:", je.toString()); return Response.error(new ParseError(je)); } } @Override protected void deliverResponse(JSONObject response) { // TODO Auto-generated method stub Log.i(CustomStringRequest.class.getSimpleName() + " Response:", response.toString()); listener.onResponse(response); } }
8ae295ce9f7c2cec821436084eb3614803b67833
376865708b40340fd73e7339575e707fb625182c
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/CraterCrossing.java
40a4cd7e8a32a5acf97116e75d086f07ce32711a
[ "BSD-3-Clause" ]
permissive
FTC4924/2018-2019_RoverRuckus_Early
de336333368765a41e6ee928f900b5ae6210a4ae
32b1d884d6b51eea3606f3159e05789983570abd
refs/heads/master
2023-06-29T14:02:28.355390
2021-07-30T19:23:13
2021-07-30T19:23:13
152,901,536
0
0
null
null
null
null
UTF-8
Java
false
false
18,650
java
/* Copyright (c) 2018 FIRST. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of FIRST nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS * LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.CRServo; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.hardware.TouchSensor; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.robotcore.external.ClassFactory; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer; import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer.CameraDirection; import org.firstinspires.ftc.robotcore.external.tfod.*; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import java.util.List; //import org.firstinspires.ftc.robotcore.external.tfod.TFObjectDetector; /** * This 2018-2019 OpMode illustrates the basics of using the TensorFlowFront Object Detection API to * determine the position of the gold and silver minerals. * * Use Android Studio to Copy this Class, and Paste it into your team's code folder with a new name. * Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list. * * IMPORTANT: In order to use this OpMode, you need to obtain your own Vuforia license key as * is explained below. */ @Autonomous(name = "Crater Starting", group = "4924") public class CraterCrossing extends LinearOpMode { private static final String TFOD_MODEL_ASSET = "RoverRuckus.tflite"; private static final String LABEL_GOLD_MINERAL = "Gold Mineral"; private static final String LABEL_SILVER_MINERAL = "Silver Mineral"; private ElapsedTime runtime = new ElapsedTime(); DcMotor frontLeft; DcMotor frontRight; DcMotor backLeft; DcMotor backRight; DcMotor linearMotor; TouchSensor limitSwitch; Servo linearServo; CRServo collectionServo; static final double COUNTS_PER_MOTOR_REV = 1425.2 ; static final double DRIVE_GEAR_REDUCTION = 2.0 ; // This is < 1.0 if geared UP static final double WHEEL_DIAMETER_INCHES = 4.0 ; // For figuring circumference static final double COUNTS_PER_INCH = (COUNTS_PER_MOTOR_REV * DRIVE_GEAR_REDUCTION) / (WHEEL_DIAMETER_INCHES * 3.1415); static final double DRIVE_SPEED = 0.25; static BNO055IMU imu; static BNO055IMU.Parameters IMU_Parameters = new BNO055IMU.Parameters(); Orientation angles; protected static DcMotor[] DRIVE_BASE_MOTORS = new DcMotor[4]; private static final double GYRO_TURN_TOLERANCE_DEGREES = 3; boolean landed = false; boolean latched = false; boolean kicked = false; /* * IMPORTANT: You need to obtain your own license key to use Vuforia. The string below with which * 'parameters.vuforiaLicenseKey' is initialized is for illustration only, and will not function. * A Vuforia 'Development' license key, can be obtained free of charge from the Vuforia developer * web site at https://developer.vuforia.com/license-manager. * * Vuforia license keys are always 380 characters long, and look as if they contain mostly * random data. As an example, here is a example of a fragment of a valid key: * ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ... * Once you've obtained a license key, copy the string from the Vuforia web site * and paste it in to your code on the next line, between the double quotes. */ private static final String VUFORIA_KEY = "AaeF/Hb/////AAABmXyUA/dvl08Hn6O8IUco1axEjiRtYCVASeXGzCnFiMaizR1b3cvD+SXpU1UHHbSpnyem0dMfGb6wce32IWKttH90xMTnLjY4aXBEYscpQbX/FzUi6uf5M+sXDVNMtaVxLDGOb1phJ8tg9/Udb1cxIUCifI+AHmcwj3eknyY1ZapF81n/R0mVSmuyApS2oGQLnETWaWK+kxkx8cGnQ0Nj7a79gStXqm97obOdzptw7PdDNqOfSLVcyKCegEO0zbGoInhRMDm0MPPTxwnBihZsjDuz+I5kDEZJZfBWZ9O1PZMeFmhe6O8oFwE07nFVoclw7j2P6qHbsKTabg3w9w4ZdeTSZI4sV2t9OhbF13e0MWeV"; /** * {@link #vuforia} is the variable we will use to store our instance of the Vuforia * localization engine. */ private VuforiaLocalizer vuforia; /** * {@link #tfod} is the variable we will use to store our instance of the Tensor Flow Object * Detection engine. */ private TFObjectDetector tfod; @Override public void runOpMode() { // The TFObjectDetector uses the camera frames from the VuforiaLocalizer, so we create that // first. initVuforia(); limitSwitch = hardwareMap.get(TouchSensor.class, "limitSwitch"); linearServo = hardwareMap.get(Servo.class, "linearServo"); collectionServo = hardwareMap.get(CRServo.class, "collectionServo"); frontLeft = hardwareMap.get(DcMotor.class, "frontLeft"); frontRight = hardwareMap.get(DcMotor.class, "frontRight"); backLeft = hardwareMap.get(DcMotor.class, "backLeft"); backRight = hardwareMap.get(DcMotor.class, "backRight"); linearMotor = hardwareMap.get(DcMotor.class, "linearMotor"); linearMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); linearMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION); frontLeft.setDirection(DcMotor.Direction.FORWARD); frontRight.setDirection(DcMotor.Direction.REVERSE); backRight.setDirection(DcMotor.Direction.REVERSE); backLeft.setDirection(DcMotor.Direction.FORWARD); BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES; parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC; parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode parameters.loggingEnabled = true; parameters.loggingTag = "IMU"; parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator(); // Retrieve and initialize the IMU. We expect the IMU to be attached to an I2C port // on a Core Device Interface Module, configured to be a sensor of type "AdaFruit IMU", // and named "imu". imu = hardwareMap.get(BNO055IMU.class, "imu"); imu.initialize(parameters); DRIVE_BASE_MOTORS[0] = frontLeft; DRIVE_BASE_MOTORS[1] = frontRight; DRIVE_BASE_MOTORS[2] = backLeft; DRIVE_BASE_MOTORS[3] = backRight; setMotorsModes(DcMotor.RunMode.STOP_AND_RESET_ENCODER, DRIVE_BASE_MOTORS); setMotorsModes(DcMotor.RunMode.RUN_USING_ENCODER, DRIVE_BASE_MOTORS); /** Wait for the game to begin */ telemetry.addData(">", "Press Play to start tracking"); telemetry.update(); waitForStart(); telemetry.addData("Status:", "Starting"); telemetry.update(); while (opModeIsActive()) { if (!landed && !latched) { runtime.reset(); linearServo.scaleRange(0.0, 1.0); linearMotor.setTargetPosition(-7122); linearMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION); linearMotor.setPower(0.5); if (linearMotor.getCurrentPosition() < -7100){ landed = true; telemetry.addData("Status:", "Landed"); telemetry.update(); } } if (landed && !latched){ linearServo.setPosition(1); collectionServo.setPower(1); sleep(1250); collectionServo.setPower(0); latched = true; telemetry.addData("Status:", "Latched"); telemetry.update(); } if (landed && latched) { if (ClassFactory.getInstance().canCreateTFObjectDetector()) { initTfod(); } else { telemetry.addData("Sorry!", "This device is not compatible with TFOD"); } /** Activate Tensor Flow Object Detection. */ if (tfod != null) { tfod.activate(); } while (opModeIsActive()) { if (tfod != null) { // getUpdatedRecognitions() will return null if no new information is available since // the last time that call was made. List<Recognition> updatedRecognitions = tfod.getUpdatedRecognitions(); if (updatedRecognitions != null) { telemetry.addData("# Object Detected", updatedRecognitions.size()); telemetry.update(); if (updatedRecognitions.size() == 3) { int goldMineralX = -1; int silverMineral1X = -1; int silverMineral2X = -1; for (Recognition recognition : updatedRecognitions) { if (recognition.getLabel().equals(LABEL_GOLD_MINERAL)) { goldMineralX = (int) recognition.getLeft(); } else if (silverMineral1X == -1) { silverMineral1X = (int) recognition.getLeft(); } else { silverMineral2X = (int) recognition.getLeft(); } } if (goldMineralX != -1 && silverMineral1X != -1 && silverMineral2X != -1 && !kicked) { if (goldMineralX < silverMineral1X && goldMineralX < silverMineral2X) { kicked = true; telemetry.addData("Gold Mineral Position", "Left"); telemetry.update(); encoderDrive(DRIVE_SPEED, 2, 2, 5); turnToPosition(.5, 25); encoderDrive(DRIVE_SPEED, 13, 13, 7); } else if (goldMineralX > silverMineral1X && goldMineralX > silverMineral2X) { kicked = true; telemetry.addData("Gold Mineral Position", "Right"); telemetry.update(); encoderDrive(DRIVE_SPEED, 2, 2, 7); turnToPosition(.5, -25); encoderDrive(DRIVE_SPEED, 13, 13, 7); } else { kicked = true; encoderDrive(DRIVE_SPEED, 2, 2, 5); telemetry.addData("Gold Mineral Position", "Center"); telemetry.update(); encoderDrive(DRIVE_SPEED, 10, 10, 7); } } } else if (runtime.seconds() >= 15 && !kicked){ //It has been 20 seconds and we cannot identify the gold //Assume middle kicked = true; encoderDrive(DRIVE_SPEED, 2, 2, 5); telemetry.addData("Gold Mineral Position", "Unknown"); telemetry.update(); encoderDrive(DRIVE_SPEED, 10, 10, 5); encoderDrive(.5,5,5,5); } } } } if (tfod != null) { tfod.shutdown(); } } } } /** * Initialize the Vuforia localization engine. */ private void initVuforia() { /* * Configure Vuforia by creating a Parameter object, and passing it to the Vuforia engine. */ VuforiaLocalizer.Parameters parameters = new VuforiaLocalizer.Parameters(); parameters.vuforiaLicenseKey = VUFORIA_KEY; parameters.cameraDirection = CameraDirection.BACK; // Instantiate the Vuforia engine vuforia = ClassFactory.getInstance().createVuforia(parameters); // Loading trackables is not necessary for the Tensor Flow Object Detection engine. } /** * Initialize the Tensor Flow Object Detection engine. */ private void initTfod() { int tfodMonitorViewId = hardwareMap.appContext.getResources().getIdentifier( "tfodMonitorViewId", "id", hardwareMap.appContext.getPackageName()); TFObjectDetector.Parameters tfodParameters = new TFObjectDetector.Parameters(tfodMonitorViewId); tfod = ClassFactory.getInstance().createTFObjectDetector(tfodParameters, vuforia); tfod.loadModelFromAsset(TFOD_MODEL_ASSET, LABEL_GOLD_MINERAL, LABEL_SILVER_MINERAL); } public void encoderDrive(double speed, double leftInches, double rightInches, double timeoutS) { int newLeftTarget; int newRightTarget; // Ensure that the opmode is still active if (opModeIsActive()) { // Determine new target position, and pass to motor controller newLeftTarget = frontLeft.getCurrentPosition() + (int)(leftInches * COUNTS_PER_INCH); newRightTarget = frontRight.getCurrentPosition() + (int)(rightInches * COUNTS_PER_INCH); frontLeft.setTargetPosition(newLeftTarget); backLeft.setTargetPosition(newLeftTarget); frontRight.setTargetPosition(newRightTarget); backRight.setTargetPosition(newRightTarget); // Turn On RUN_TO_POSITION frontRight.setMode(DcMotor.RunMode.RUN_TO_POSITION); backRight.setMode(DcMotor.RunMode.RUN_TO_POSITION); frontLeft.setMode(DcMotor.RunMode.RUN_TO_POSITION); backLeft.setMode(DcMotor.RunMode.RUN_TO_POSITION); // reset the timeout time and start motion. runtime.reset(); frontRight.setPower(Math.abs(speed)); frontLeft.setPower(Math.abs(speed)); backRight.setPower(Math.abs(speed)); backLeft.setPower(Math.abs(speed)); while (opModeIsActive() && (runtime.seconds() < timeoutS) && (frontLeft.isBusy() && frontRight.isBusy())) { } // Stop all motion; frontLeft.setPower(0); frontRight.setPower(0); backLeft.setPower(0); backRight.setPower(0); // Turn off RUN_TO_POSITION frontLeft.setMode(DcMotor.RunMode.RUN_USING_ENCODER); frontRight.setMode(DcMotor.RunMode.RUN_USING_ENCODER); backLeft.setMode(DcMotor.RunMode.RUN_USING_ENCODER); backRight.setMode(DcMotor.RunMode.RUN_USING_ENCODER); } } public void turn(double power) { frontLeft.setPower(power); frontRight.setPower(-power); backLeft.setPower(power); backRight.setPower(-power); } public void turnToPosition(double turnPower, double desiredHeading) { setMotorsModes(DcMotor.RunMode.RUN_WITHOUT_ENCODER, DRIVE_BASE_MOTORS); while (getHeading() - desiredHeading > GYRO_TURN_TOLERANCE_DEGREES && opModeIsActive()) { turn(turnPower); } while (getHeading() - desiredHeading < -GYRO_TURN_TOLERANCE_DEGREES && opModeIsActive()) { turn(-turnPower); } setMotorsPowers(0, DRIVE_BASE_MOTORS); //defaults to CW turning } public double getHeading() { updateGyro(); return angles.firstAngle; } void updateGyro() { angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); } public static void setMotorsModes(DcMotor.RunMode runMode, DcMotor[] motors) { for (DcMotor d : motors) d.setMode(runMode); } protected static void setMotorsPowers(double power, DcMotor[] motors) { for (DcMotor d : motors) d.setPower(power); } }
6062c178d2d78be561b1d76217a44a9c8dd6e175
9cc7d18d674ef6e7dcbe1e498fdb11fe4976ac2f
/src/main/java/com/frontend/domain/SavingsAccount.java
b178549fc17f354ec2cfb40366b389c089367b8b
[]
no_license
roshankkumar/springbootproject
43994087eef541a2b1b898869fb892ca2cc2db6d
2c3239c429e42f7e77e522a1b1835bebd54223ea
refs/heads/master
2020-03-24T13:00:24.265878
2018-07-29T09:08:23
2018-07-29T09:08:23
142,732,055
0
0
null
null
null
null
UTF-8
Java
false
false
1,648
java
package com.frontend.domain; import java.math.BigDecimal; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import com.fasterxml.jackson.annotation.JsonIgnore; /* * Savings Acc model class * */ @Entity public class SavingsAccount { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private int accountNumber; private BigDecimal accountBalance; @OneToMany(mappedBy = "savingsaccount", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JsonIgnore private List<SavingsTransaction> savingsTransactions; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getAccountNumber() { return accountNumber; } public void setAccountNumber(int accountNumber) { this.accountNumber = accountNumber; } public BigDecimal getAccountBalance() { return accountBalance; } public void setAccountBalance(BigDecimal accountBalance) { this.accountBalance = accountBalance; } public List<SavingsTransaction> getSavingsTransactions() { return savingsTransactions; } public void setSavingsTransactions(List<SavingsTransaction> savingsTransactions) { this.savingsTransactions = savingsTransactions; } @Override public String toString() { return "SavingsAccount [id=" + id + ", accountNumber=" + accountNumber + ", accountBalance=" + accountBalance + ", savingsTransactions=" + savingsTransactions + "]"; } }
d6900a720410f7245b76bc2b4d97cb64718df5ec
ebf8e1c8dff50a2142de25ae6ca1a0c7b0b825a9
/api/src/main/java/com/teckup/api/exception/ExcpetionControllerAdvice.java
b09141b6983057e093ab484f9c78b97b2803846f
[]
no_license
saberdaagi/gae
0793cb71d27d5b0f65769d7ce7c3d6ca67f1b214
3c1177ed4e03c18e09446552f1e48b0f34ed07cb
refs/heads/master
2020-11-24T16:44:04.100148
2020-02-04T21:30:33
2020-02-04T21:30:33
226,727,669
0
0
null
null
null
null
UTF-8
Java
false
false
945
java
package com.teckup.api.exception; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import java.text.ParseException; @ControllerAdvice @Slf4j public class ExcpetionControllerAdvice { @ExceptionHandler(Exception.class) public ResponseEntity<String> defaultErrorHandler(@NonNull Exception exception) { log.error("Unhandled exception occured", exception); return ResponseEntity.badRequest().body(exception.getMessage()); } @ExceptionHandler(ParseException.class) public ResponseEntity<String> parseErrorHandler(@NonNull ParseException exception) { log.error("Unhandled exception occured", exception); return ResponseEntity.badRequest().body(exception.getMessage()); } }
451b7c2a82e624636ac1be9a3633fa56ce4436fa
93a0000df9327efa1cc50304f6851cd4ca3fa131
/src/main/java/com/example/springBootOauth2/service/CustomUserDetailsService.java
d8c342602c4e79193019a22d19e098dd6e4ba1fb
[]
no_license
jharaghav/oauth-system
6ad15b38c829a72018481363fd8196df12cfb95e
97f0fe42c152978b2152a88b14ffa88776f1e691
refs/heads/master
2020-05-19T11:37:28.213174
2019-05-07T05:27:20
2019-05-07T05:27:20
184,996,630
0
0
null
null
null
null
UTF-8
Java
false
false
1,776
java
package com.example.springBootOauth2.service; import com.example.springBootOauth2.repository.AccountRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import com.example.springBootOauth2.config.AuthServerConfig; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import sun.security.util.Password; @Service public class CustomUserDetailsService implements UserDetailsService { @Autowired PasswordEncoder encoder; // @Autowired // AuthenticationManager authenticationManager; @Autowired AccountRepository accountRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return accountRepository.findByUsername(username) .map(account -> new User(account.getUsername(), encoder.encode(account.getPassword()), true, true, true, true, AuthorityUtils.createAuthorityList("write","read"))) .orElseThrow(() -> new UsernameNotFoundException("username does not exist")); } }
c774d5f6c530adb34578053ae415eadba9507180
7cee584d730d6acc88ef57eb75de9461830dbaf1
/techtribes-updater/src/je/techtribes/updater/Main.java
e0a50bada744bbc452bfbfb620927a88eeba37fa
[ "Apache-2.0" ]
permissive
ajambor/techtribesje
9298c56746bb8f7113d58caa72e3c04e8ebba59d
82ff86834a06f728be35759e6aa7612ed59699c2
refs/heads/master
2020-09-15T09:21:47.415708
2013-07-04T20:56:40
2013-07-04T20:56:40
11,199,943
1
1
null
null
null
null
UTF-8
Java
false
false
5,975
java
package je.techtribes.updater; import je.techtribes.component.contentsource.ContentSourceComponent; import je.techtribes.component.log.LoggingComponent; import je.techtribes.component.newsfeedentry.NewsFeedEntryComponent; import je.techtribes.component.scheduledcontentupdater.ScheduledContentUpdater; import je.techtribes.component.search.SearchComponent; import je.techtribes.component.tweet.TweetComponent; import je.techtribes.domain.NewsFeedEntry; import je.techtribes.domain.Tweet; import je.techtribes.util.DateUtils; import je.techtribes.util.PageSize; import je.techtribes.util.Version; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; import java.util.TimeZone; /** * Standalone application that updates tweets, news, badges, etc. */ public class Main { public static void main(String[] args) { TimeZone.setDefault(TimeZone.getTimeZone(DateUtils.UTC_TIME_ZONE)); ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); LoggingComponent loggingComponent = (LoggingComponent)applicationContext.getBean("loggingComponent"); loggingComponent.info(Main.class, "techtribes.je updater, version " + Version.getBuildNumber() + " built on " + Version.getBuildTimestamp()); if (args.length > 0 && "rebuildsearch".equals(args[0])) { ContentSourceComponent contentSourceComponent = (ContentSourceComponent)applicationContext.getBean("contentSourceComponent"); contentSourceComponent.refreshContentSources(); rebuildSearchIndexes(applicationContext); System.exit(0); } else if (args.length > 0 && "migrate".equals(args[0])) { NewsFeedEntryComponent newsFeedEntryComponent = (NewsFeedEntryComponent)applicationContext.getBean("newsFeedEntryComponent"); TweetComponent tweetComponent = (TweetComponent)applicationContext.getBean("tweetComponent"); ContentSourceComponent contentSourceComponent = (ContentSourceComponent)applicationContext.getBean("contentSourceComponent"); contentSourceComponent.refreshContentSources(); long numberOfNewsFeedEntries = newsFeedEntryComponent.getNumberOfNewsFeedEntries(); loggingComponent.info(Main.class, "Number of NFEs: " + numberOfNewsFeedEntries); int numberOfPages = PageSize.calculateNumberOfPages(numberOfNewsFeedEntries, PageSize.RECENT_NEWS_FEED_ENTRIES); for (int page = 1; page <= numberOfPages; page++) { loggingComponent.info(Main.class, "Migrating NFEs; page " + page + " of " + numberOfPages); List<NewsFeedEntry> nfes = newsFeedEntryComponent.getRecentNewsFeedEntries(page, PageSize.RECENT_NEWS_FEED_ENTRIES); newsFeedEntryComponent.storeNewsFeedEntries(nfes); } long numberOfTweets = tweetComponent.getNumberOfTweets(); loggingComponent.info(Main.class, "Number of tweets: " + numberOfTweets); numberOfPages = PageSize.calculateNumberOfPages(numberOfTweets, PageSize.RECENT_TWEETS); for (int page = 1; page <= numberOfPages; page++) { loggingComponent.info(Main.class, "Migrating tweets; page " + page + " of " + numberOfPages); List<Tweet> tweets = tweetComponent.getRecentTweets(page, PageSize.RECENT_TWEETS); tweetComponent.storeTweets(tweets); } System.exit(0); } ScheduledContentUpdater scu = (ScheduledContentUpdater)applicationContext.getBean("contentUpdater"); scu.start(); } private static void rebuildSearchIndexes(ApplicationContext applicationContext) { LoggingComponent loggingComponent = (LoggingComponent)applicationContext.getBean("loggingComponent"); loggingComponent.info(Main.class, "Starting to rebuild search indexes"); SearchComponent searchComponent = (SearchComponent)applicationContext.getBean("searchComponent"); NewsFeedEntryComponent newsFeedEntryComponent = (NewsFeedEntryComponent)applicationContext.getBean("newsFeedEntryComponent"); TweetComponent tweetComponent = (TweetComponent)applicationContext.getBean("tweetComponent"); searchComponent.clearSearchIndex(); // add add everything that the news feed service knows about long numberOfNewsFeedEntries = newsFeedEntryComponent.getNumberOfNewsFeedEntries(); loggingComponent.info(Main.class, "Number of news feed entries: " + numberOfNewsFeedEntries); int numberOfPages = PageSize.calculateNumberOfPages(numberOfNewsFeedEntries, PageSize.RECENT_NEWS_FEED_ENTRIES); for (int page = 1; page <= numberOfPages; page++) { loggingComponent.info(Main.class, "Indexing news feed entries; page " + page + " of " + numberOfPages); List<NewsFeedEntry> newsFeedEntries = newsFeedEntryComponent.getRecentNewsFeedEntries(page, PageSize.RECENT_NEWS_FEED_ENTRIES); for (NewsFeedEntry newsFeedEntry : newsFeedEntries) { searchComponent.add(newsFeedEntry); } } // add add everything that the tweet service knows about long numberOfTweets = tweetComponent.getNumberOfTweets(); loggingComponent.info(Main.class, "Number of tweets: " + numberOfTweets); numberOfPages = PageSize.calculateNumberOfPages(numberOfTweets, PageSize.RECENT_TWEETS); for (int page = 1; page <= numberOfPages; page++) { loggingComponent.info(Main.class, "Indexing tweets; page " + page + " of " + numberOfPages); List<Tweet> tweets = tweetComponent.getRecentTweets(page, PageSize.RECENT_TWEETS); for (Tweet tweet : tweets) { searchComponent.add(tweet); } } loggingComponent.info(Main.class, "Finished rebuilding search indexes"); } }
4ff899fdb493c0efbcf5815e22fffdb35e0a3e6b
cdef14a336cc2a256d36467990d5479d580833b1
/app/src/main/java/com/ruhul/admin_app/model/StoryName.java
94e9043a8d3348b1bf0c6c1487207c5262fd9596
[]
no_license
RUHULRUHUL/Admin_App_Read
58fac923e50806eef454a5ea997381757bcaf4d5
4626d5717784f5e1f93d212d044aeb3271b41914
refs/heads/master
2023-03-31T21:10:02.573357
2021-04-02T09:54:34
2021-04-02T09:54:34
353,977,634
0
0
null
null
null
null
UTF-8
Java
false
false
319
java
package com.ruhul.admin_app.model; public class StoryName { public StoryName() { } public String getName() { return name; } public void setName(String name) { this.name = name; } private String name; public StoryName(String name) { this.name = name; } }