hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
92359b13b763bb2c0ccdb3382b871268f55a3ecb
572
java
Java
Chapter03/Test_p69.java
miaocheng/Java_Textbook_2021
5908bf6a3a56ee2185fed81e30d13a9eca9b846a
[ "Unlicense" ]
null
null
null
Chapter03/Test_p69.java
miaocheng/Java_Textbook_2021
5908bf6a3a56ee2185fed81e30d13a9eca9b846a
[ "Unlicense" ]
null
null
null
Chapter03/Test_p69.java
miaocheng/Java_Textbook_2021
5908bf6a3a56ee2185fed81e30d13a9eca9b846a
[ "Unlicense" ]
null
null
null
15.888889
48
0.517483
997,355
import java.util.*; public class Test_p69 { public static void main(String args []) { char grade = args[0].charAt(0); switch(grade) { case 'A': System.out.print("Excellent !"); break; case 'B': case 'C': System.out.print("Well done."); break; case 'D': System.out.print("You passed."); case 'F': System.out.print("Better try again."); break; default: System.out.print("Invalid grade."); } System.out.println("Your grade is " + grade); } }
92359b1f0b69c468ebd9d709c5b4dc4c876b437e
1,552
java
Java
backend/authprovider/src/main/java/de/egladil/web/authprovider/dao/impl/ActivationCodeDaoImpl.java
heike2718/authenticationprovider
c321ff3d76a5ca511504dca7e612c1b286eaf583
[ "MIT" ]
null
null
null
backend/authprovider/src/main/java/de/egladil/web/authprovider/dao/impl/ActivationCodeDaoImpl.java
heike2718/authenticationprovider
c321ff3d76a5ca511504dca7e612c1b286eaf583
[ "MIT" ]
24
2020-07-13T05:04:29.000Z
2022-01-19T19:27:26.000Z
backend/authprovider/src/main/java/de/egladil/web/authprovider/dao/impl/ActivationCodeDaoImpl.java
heike2718/authenticationprovider
c321ff3d76a5ca511504dca7e612c1b286eaf583
[ "MIT" ]
null
null
null
26.758621
124
0.722294
997,356
// ===================================================== // Projekt: authprovider // (c) Heike Winkelvoß // ===================================================== package de.egladil.web.authprovider.dao.impl; import java.util.List; import java.util.Optional; import javax.enterprise.context.RequestScoped; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import de.egladil.web.authprovider.dao.ActivationCodeDao; import de.egladil.web.authprovider.domain.ActivationCode; import de.egladil.web.authprovider.error.AuthRuntimeException; /** * ActivationCodeDaoImpl */ @RequestScoped public class ActivationCodeDaoImpl extends BaseDaoImpl implements ActivationCodeDao { /** * Erzeugt eine Instanz von ActivationCodeDaoImpl */ public ActivationCodeDaoImpl() { } /** * Erzeugt eine Instanz von ActivationCodeDaoImpl */ public ActivationCodeDaoImpl(final EntityManager em) { super(em); } @Override public Optional<ActivationCode> findByConfirmationCode(final String confirmationCode) { TypedQuery<ActivationCode> query = getEm().createNamedQuery("findActivationCodeByConfirmationCode", ActivationCode.class); query.setParameter("confirmationCode", confirmationCode); List<ActivationCode> trefferliste = query.getResultList(); if (trefferliste.size() > 1) { throw new AuthRuntimeException( "mehr als ein Eintrag mit CONFIRM_CODE='" + confirmationCode + "' in Tabelle activationcodes"); } return trefferliste.isEmpty() ? Optional.empty() : Optional.of(trefferliste.get(0)); } }
92359b7afdffb6ff02c51aca509f0dc597c0a903
2,865
java
Java
common/src/main/java/com/codefinity/microcontinuum/common/notification/Notification.java
codefinity/micro-continuum
59f0b426faaf6faa551f2bda1c305040e2a8d31d
[ "MIT" ]
4
2018-03-28T04:29:26.000Z
2018-06-24T20:47:47.000Z
common/src/main/java/com/codefinity/microcontinuum/common/notification/Notification.java
codefinity/micro-continuum
59f0b426faaf6faa551f2bda1c305040e2a8d31d
[ "MIT" ]
2
2018-04-14T02:15:50.000Z
2018-07-25T03:37:49.000Z
common/src/main/java/com/codefinity/microcontinuum/common/notification/Notification.java
codefinity/micro-continuum
59f0b426faaf6faa551f2bda1c305040e2a8d31d
[ "MIT" ]
1
2018-03-14T03:17:12.000Z
2018-03-14T03:17:12.000Z
26.045455
99
0.640489
997,357
package com.codefinity.microcontinuum.common.notification; import java.io.Serializable; import java.util.Date; import com.codefinity.microcontinuum.common.AssertionConcern; import com.codefinity.microcontinuum.common.domain.model.DomainEvent; public class Notification extends AssertionConcern implements Serializable { private static final long serialVersionUID = 1L; private DomainEvent event; private long notificationId; private Date occurredOn; private String typeName; private int version; public Notification( long aNotificationId, DomainEvent anEvent) { this(); this.setEvent(anEvent); this.setNotificationId(aNotificationId); this.setOccurredOn(anEvent.occurredOn()); this.setTypeName(anEvent.getClass().getName()); this.setVersion(anEvent.eventVersion()); } @SuppressWarnings("unchecked") public <T extends DomainEvent> T event() { return (T) this.event; } public long notificationId() { return this.notificationId; } public Date occurredOn() { return this.occurredOn; } public String typeName() { return this.typeName; } public int version() { return version; } @Override public boolean equals(Object anObject) { boolean equalObjects = false; if (anObject != null && this.getClass() == anObject.getClass()) { Notification typedObject = (Notification) anObject; equalObjects = this.notificationId() == typedObject.notificationId(); } return equalObjects; } @Override public int hashCode() { int hashCodeValue = + (3017 * 197) + (int) this.notificationId(); return hashCodeValue; } @Override public String toString() { return "Notification [event=" + event + ", notificationId=" + notificationId + ", occurredOn=" + occurredOn + ", typeName=" + typeName + ", version=" + version + "]"; } protected Notification() { super(); } protected void setEvent(DomainEvent anEvent) { this.assertArgumentNotNull(anEvent, "The event is required."); this.event = anEvent; } protected void setNotificationId(long aNotificationId) { this.notificationId = aNotificationId; } protected void setOccurredOn(Date anOccurredOn) { this.occurredOn = anOccurredOn; } protected void setTypeName(String aTypeName) { this.assertArgumentNotEmpty(aTypeName, "The type name is required."); this.assertArgumentLength(aTypeName, 100, "The type name must be 100 characters or less."); this.typeName = aTypeName; } private void setVersion(int aVersion) { this.version = aVersion; } }
92359bc7613595ddcfbc3590e6768b130115aff8
1,435
java
Java
src/main/java/ru/betterend/blocks/FlammalixBlock.java
rjuven2401/BetterEnd
634927b2eba82751d7c004a457576fefc1b3487b
[ "MIT" ]
83
2020-09-22T20:31:23.000Z
2022-03-31T10:31:24.000Z
src/main/java/ru/betterend/blocks/FlammalixBlock.java
rjuven2401/BetterEnd
634927b2eba82751d7c004a457576fefc1b3487b
[ "MIT" ]
427
2020-10-18T13:12:33.000Z
2022-03-30T02:48:42.000Z
src/main/java/ru/betterend/blocks/FlammalixBlock.java
rjuven2401/BetterEnd
634927b2eba82751d7c004a457576fefc1b3487b
[ "MIT" ]
59
2020-09-21T06:08:15.000Z
2022-03-30T19:30:24.000Z
29.895833
102
0.794425
997,358
package ru.betterend.blocks; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.core.BlockPos; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.models.ModelsHelper; import ru.betterend.blocks.basis.EndPlantBlock; import ru.betterend.registry.EndBlocks; public class FlammalixBlock extends EndPlantBlock { private static final VoxelShape SHAPE = Block.box(2, 0, 2, 14, 14, 14); public FlammalixBlock() { super(false, 12); } @Override protected boolean isTerrain(BlockState state) { return state.is(EndBlocks.PALLIDIUM_FULL) || state.is(EndBlocks.PALLIDIUM_HEAVY) || state.is(EndBlocks.PALLIDIUM_THIN) || state.is(EndBlocks.PALLIDIUM_TINY); } @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { return SHAPE; } @Override public OffsetType getOffsetType() { return OffsetType.NONE; } @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { return ModelsHelper.createItemModel(resourceLocation); } }
92359c43797015d148e54f433476fbe5a40523c4
1,503
java
Java
src/com/ikonoklastik/roller/business/plugins/entry/markdown/MarkdownCommentPlugin.java
myabc/roller-markdown
1bc0ac0a599efba4f80319e76f2e786012e11be7
[ "MIT" ]
5
2015-09-02T10:56:41.000Z
2022-02-22T02:43:58.000Z
src/com/ikonoklastik/roller/business/plugins/entry/markdown/MarkdownCommentPlugin.java
myabc/roller-markdown
1bc0ac0a599efba4f80319e76f2e786012e11be7
[ "MIT" ]
null
null
null
src/com/ikonoklastik/roller/business/plugins/entry/markdown/MarkdownCommentPlugin.java
myabc/roller-markdown
1bc0ac0a599efba4f80319e76f2e786012e11be7
[ "MIT" ]
1
2021-05-10T04:23:17.000Z
2021-05-10T04:23:17.000Z
27.833333
85
0.709914
997,359
package com.ikonoklastik.roller.business.plugins.entry.markdown; import com.petebevin.markdown.MarkdownProcessor; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.roller.weblogger.business.plugins.comment.WeblogEntryCommentPlugin; import org.apache.roller.weblogger.pojos.WeblogEntryComment; /** * Markdown Comments Plugin for Roller * * @author alexbcoles */ public class MarkdownCommentPlugin implements WeblogEntryCommentPlugin { private static final Log log = LogFactory.getLog(MarkdownCommentPlugin.class); public static final String PLUGIN_ID = "Markdown"; public static final String NAME = "Markdown"; public static final String DESCRIPTION = "Allows the use of the Markdown" + " lightweight markup language in weblog comments."; private MarkdownProcessor processor = new MarkdownProcessor(); public String getId() { return PLUGIN_ID; } public String getName() { return NAME; } public String getDescription() { return StringEscapeUtils.escapeJavaScript(DESCRIPTION); } /** * * @param comment * @param str * @return */ public String render(final WeblogEntryComment comment, String text) { log.debug("starting value:\n" + text); String result = processor.markdown(text); log.debug("ending value:\n" + result); return result; } }
92359c7336643485ed098456e46903bcbebde784
5,006
java
Java
engine-tests/src/test/java/org/terasology/utilities/collection/CircularBufferTest.java
rooterWhy/Terasology
a38d0c814009f83b27a13564d9b2429452c9dd50
[ "Apache-2.0", "CC-BY-4.0" ]
3
2016-05-14T22:55:53.000Z
2017-06-13T17:20:13.000Z
engine-tests/src/test/java/org/terasology/utilities/collection/CircularBufferTest.java
rooterWhy/Terasology
a38d0c814009f83b27a13564d9b2429452c9dd50
[ "Apache-2.0", "CC-BY-4.0" ]
16
2016-05-01T03:22:35.000Z
2016-05-02T00:16:43.000Z
engine-tests/src/test/java/org/terasology/utilities/collection/CircularBufferTest.java
rooterWhy/Terasology
a38d0c814009f83b27a13564d9b2429452c9dd50
[ "Apache-2.0", "CC-BY-4.0" ]
1
2015-10-30T02:42:44.000Z
2015-10-30T02:42:44.000Z
30.52439
75
0.631842
997,360
/* * Copyright 2013 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.utilities.collection; import com.google.common.collect.ImmutableList; import org.junit.Test; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** */ public class CircularBufferTest { @Test public void testAddItems() { CircularBuffer<Integer> buffer = CircularBuffer.create(4); for (int i = 0; i < 100; ++i) { buffer.add(i); assertEquals((Integer) i, buffer.getLast()); } } @Test public void testRemoveItems() { CircularBuffer<Integer> buffer = CircularBuffer.create(4); buffer.add(1); buffer.add(2); buffer.add(3); buffer.add(4); buffer.add(5); assertEquals(4, buffer.size()); assertEquals((Integer) 2, buffer.getFirst()); assertEquals((Integer) 2, buffer.popFirst()); assertEquals((Integer) 3, buffer.getFirst()); assertEquals(3, buffer.size()); assertEquals((Integer) 5, buffer.popLast()); assertEquals((Integer) 4, buffer.popLast()); assertEquals((Integer) 3, buffer.getLast()); assertEquals((Integer) 3, buffer.popLast()); assertTrue(buffer.isEmpty()); } @Test public void testCollectionMethods() { Collection<Integer> buffer = CircularBuffer.create(4); buffer.addAll(ImmutableList.of(1, 2, 3, 4, 5, 6)); buffer.add(4); assertTrue(buffer.contains(5)); assertTrue(buffer.containsAll(ImmutableList.of(5, 4))); } @Test public void testGetSet() { CircularBuffer<Integer> buffer = CircularBuffer.create(4); buffer.addAll(ImmutableList.of(11, 12, 0, 1, 2, 3)); assertEquals((Integer) 0, buffer.get(0)); assertEquals((Integer) 3, buffer.get(3)); assertEquals((Integer) 2, buffer.set(2, 8)); assertEquals((Integer) 8, buffer.get(2)); assertEquals((Integer) 0, buffer.set(0, 5)); assertEquals((Integer) 5, buffer.get(0)); assertEquals((Integer) 3, buffer.set(3, 6)); assertEquals((Integer) 6, buffer.get(3)); } @Test public void testInsert() { CircularBuffer<Integer> buffer = CircularBuffer.create(4); buffer.addAll(ImmutableList.of(1, 2, 5, 7)); // remove from the middle assertEquals((Integer) 2, buffer.remove(1)); assertEquals((Integer) 5, buffer.get(1)); // remove from the left side assertEquals((Integer) 1, buffer.remove(0)); // remove from the right side assertEquals((Integer) 7, buffer.remove(1)); // remove the only element assertEquals((Integer) 5, buffer.remove(0)); assertTrue(buffer.isEmpty()); } @Test public void testIterator1() { CircularBuffer<Integer> buffer = CircularBuffer.create(2); buffer.addAll(ImmutableList.of(1, 2)); Iterator<Integer> iterator = buffer.iterator(); iterator.next(); iterator.remove(); } @Test public void testIterator2() { CircularBuffer<Integer> buffer = CircularBuffer.create(2); buffer.addAll(ImmutableList.of(1, 2)); Iterator<Integer> iterator = buffer.iterator(); iterator.next(); iterator.remove(); iterator.next(); iterator.remove(); assertTrue(buffer.isEmpty()); } @Test(expected = IllegalStateException.class) public void testIteratorRemoveTwice() { CircularBuffer<Integer> buffer = CircularBuffer.create(2); buffer.addAll(ImmutableList.of(1, 2)); Iterator<Integer> iterator = buffer.iterator(); iterator.next(); iterator.remove(); iterator.remove(); } @Test(expected = IllegalStateException.class) public void testIteratorRemoveWithoutNext() { CircularBuffer<Integer> buffer = CircularBuffer.create(2); buffer.addAll(ImmutableList.of(1, 2)); buffer.iterator().remove(); } @Test(expected = NoSuchElementException.class) public void testIteratorAfterEnd() { CircularBuffer<Integer> buffer = CircularBuffer.create(1); buffer.add(1); Iterator<Integer> it = buffer.iterator(); it.next(); it.remove(); it.next(); it.remove(); } }
92359c7805d78a9b99f201644b1de0b47b480121
6,503
java
Java
src-app/hu/scelight/sc2/rep/s2prot/VersionedDecoder.java
Kpunto/scelight
99672f74ac55b96dc7875bbe39bafba38f1bb099
[ "Apache-2.0" ]
114
2016-02-04T13:47:21.000Z
2021-12-17T19:39:16.000Z
src-app/hu/scelight/sc2/rep/s2prot/VersionedDecoder.java
Kpunto/scelight
99672f74ac55b96dc7875bbe39bafba38f1bb099
[ "Apache-2.0" ]
25
2016-02-04T22:19:57.000Z
2022-02-25T09:54:46.000Z
src-app/hu/scelight/sc2/rep/s2prot/VersionedDecoder.java
Kpunto/scelight
99672f74ac55b96dc7875bbe39bafba38f1bb099
[ "Apache-2.0" ]
20
2016-02-04T18:11:54.000Z
2022-02-23T21:56:24.000Z
24.171004
101
0.588281
997,361
/* * Project Scelight * * Copyright (c) 2013 Andras Belicza <upchh@example.com> * * This software is the property of Andras Belicza. * Copying, modifying, distributing, refactoring without the author's permission * is prohibited and protected by Law. */ package hu.scelight.sc2.rep.s2prot; import hu.belicza.andras.util.ArrayMap; import hu.belicza.andras.util.type.BitArray; import hu.belicza.andras.util.type.XString; import hu.scelight.sc2.rep.s2prot.type.Field; import hu.scelight.sc2.rep.s2prot.type.IntBounds; import hu.scelight.sc2.rep.s2prot.type.LongBounds; import hu.scelight.sc2.rep.s2prot.type.TypeInfo; import hu.sllauncher.util.Pair; import java.util.Map; /** * Versioned decoder. * * <p> * Implementation is not thread-safe! * </p> * * @author Andras Belicza */ public class VersionedDecoder extends BitPackedBuffer { /** * Creates a new {@link VersionedDecoder}. * * @param data raw byte data * @param typeInfos type info array */ public VersionedDecoder( final byte[] data, final TypeInfo[] typeInfos ) { super( data, typeInfos ); } /** * Creates a new {@link VersionedDecoder}. * * @param data raw byte data * @param typeInfos type info array * @param bigEndian tells if byte order is big endian */ public VersionedDecoder( final byte[] data, final TypeInfo[] typeInfos, final boolean bigEndian ) { super( data, typeInfos, bigEndian ); } /** * Reads a variable length <code>int</code>. * * @return the read <code>int</code> */ public int _vint() { int data, value = 0; for ( int shift = 0;; shift += 7 ) { data = read_bits_int( 8 ); value |= ( data & 0x7f ) << shift; if ( ( data & 0x80 ) == 0 ) return ( value & 0x01 ) > 0 ? -( value >> 1 ) : value >> 1; } } /** * Reads a variable length <code>long</code>. * * @return the read <code>long</code> */ public long _vlong() { long data, value = 0; for ( int shift = 0;; shift += 7 ) { data = read_bits_int( 8 ); value |= ( data & 0x7f ) << shift; if ( ( data & 0x80 ) == 0 ) return ( value & 0x01 ) > 0 ? -( value >> 1 ) : value >> 1; } } @Override public Object[] _array( final IntBounds bounds, final int typeid ) { read_bits_int( 8 ); // field type (0) final int length = _vint(); return instances( typeid, length ); } @Override public BitArray _bitarray( final IntBounds bounds ) { read_bits_int( 8 ); // field type (1) final int length = _vint(); return new BitArray( length, read_aligned_bytes_arr( ( length + 7 ) >> 3 ) ); } @Override public XString _blob( final IntBounds bounds ) { read_bits_int( 8 ); // field type (2) final int length = _vint(); return read_aligned_bytes( length ); } @Override public boolean _bool() { read_bits_int( 8 ); // field type (6) return read_bits_int( 8 ) != 0; } @Override public Pair< String, Object > _choice( final IntBounds bounds, final Field[] fields ) { read_bits_int( 8 ); // field type (3) final int tag = _vint(); if ( tag >= fields.length ) return null; final Field field = fields[ tag ]; return new Pair<>( field.name, instance( field.typeid ) ); } @Override public XString _fourcc() { read_bits_int( 8 ); // field type (7) return read_aligned_bytes( 4 ); } @Override public int _int( final IntBounds bounds ) { read_bits_int( 8 ); // field type (9) return _vint(); } @Override public long _long( final LongBounds bounds ) { read_bits_int( 8 ); // field type (9) return _vlong(); } @Override public Object _optional( final int typeid ) { read_bits_int( 8 ); // field type (4) return read_bits_int( 8 ) != 0 ? instance( typeid ) : null; } @Override public float _float() { read_bits_int( 8 ); // field type (7) System.out.println( "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW" ); // TODO Auto-generated method stub read_aligned_bytes_arr( 4 ); return 0; } @Override public double _double() { read_bits_int( 8 ); // field type (8) System.out.println( "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW" ); // TODO Auto-generated method stub read_aligned_bytes_arr( 8 ); return 0; } @Override @SuppressWarnings( "unchecked" ) public Map< String, Object > _struct( final Field[] fields, final int extraEntriesCount ) { read_bits_int( 8 ); // field type (5) // Our ArrayMap also guarantees the same iteration order as elements are added final Map< String, Object > result = new ArrayMap<>( fields.length + extraEntriesCount ); final int length = _vint(); for ( int i = 0; i < length; i++ ) { final int tag = _vint(); Field field = null; for ( int j = fields.length - 1; j >= 0; j-- ) if ( fields[ j ].tag == tag ) { field = fields[ j ]; break; } if ( field == null ) _skip_instance(); else { if ( field.isNameParent ) { final Object parent = instance( field.typeid ); if ( parent instanceof Map ) result.putAll( (Map< String, Object >) parent ); else if ( fields.length == 1 ) result.put( field.name, parent ); // it should be: result = parent; but parent is not a map! else result.put( field.name, parent ); } else result.put( field.name, instance( field.typeid ) ); } } return result; } /** * Skips an instance. */ public void _skip_instance() { switch ( read_bits_int( 8 ) ) { // Switch by field type case 0 : { // array final int length = _vint(); for ( int i = 0; i < length; i++ ) _skip_instance(); break; } case 1 : // bitblob skipBytes( ( _vint() + 7 ) >> 3 ); break; case 2 : // blob skipBytes( _vint() ); break; case 3 : // choice _vint(); // tag _skip_instance(); break; case 4 : // optional if ( read_bits_int( 8 ) != 0 ) _skip_instance(); break; case 5 : {// struct final int length = _vint(); for ( int i = 0; i < length; i++ ) { _vint(); // tag _skip_instance(); } break; } case 6 : // u8 skipBytes( 1 ); break; case 7 : // u32 skipBytes( 4 ); break; case 8 : // u64 skipBytes( 8 ); break; case 9 : // vint _vint(); break; } } }
92359da3e9ba6933a5324d635b2fd60b3d1e376b
611
java
Java
Lab3/Motor.java
juozasd/MobileRobotics
aef9b0cef790c1813a5379b5b9dcbffe68abe72c
[ "MIT" ]
null
null
null
Lab3/Motor.java
juozasd/MobileRobotics
aef9b0cef790c1813a5379b5b9dcbffe68abe72c
[ "MIT" ]
null
null
null
Lab3/Motor.java
juozasd/MobileRobotics
aef9b0cef790c1813a5379b5b9dcbffe68abe72c
[ "MIT" ]
null
null
null
19.709677
44
0.646481
997,362
import lejos.nxt.Button; import lejos.nxt.LCD; import lejos.nxt.Motor; import lejos.util.Delay; public class MotorLab{ public static void main(String[] args) { LCD.drawString("Motor Test",0,0); //1 Button.waitForAnyPress(); //2 LCD.clear(); Motor.A.setSpeed(720);//3 Motor.B.setSpeed(720); do{ LCD.clear(); Motor.A.forward(); Motor.B.forward(); Delay.msDelay(1000); LCD.drawInt(Motor.A.getTachoCount(),0,0); LCD.drawInt(Motor.B.getTachoCount(),1,0); Motor.A.stop(); Motor.B.stop(); Delay.msDelay(500); }while(Button.ESCAPE.isPressed == false); } }
92359ea37d58157df7c2988a9c64bf19e12108eb
4,454
java
Java
myleesite-database/src/main/java/com/zyw/myleesite/database/pojo/SysMdict.java
meixiaoyao/myleesite
82c34861bc87c76488254306610a486886ad7b25
[ "Apache-2.0" ]
null
null
null
myleesite-database/src/main/java/com/zyw/myleesite/database/pojo/SysMdict.java
meixiaoyao/myleesite
82c34861bc87c76488254306610a486886ad7b25
[ "Apache-2.0" ]
null
null
null
myleesite-database/src/main/java/com/zyw/myleesite/database/pojo/SysMdict.java
meixiaoyao/myleesite
82c34861bc87c76488254306610a486886ad7b25
[ "Apache-2.0" ]
null
null
null
15.253425
55
0.480242
997,363
package com.zyw.myleesite.database.pojo; import java.util.Date; import javax.persistence.*; @Table(name = "sys_mdict") public class SysMdict { /** * 编号 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private String id; /** * 父级编号 */ @Column(name = "parent_id") private String parentId; /** * 所有父级编号 */ @Column(name = "parent_ids") private String parentIds; /** * 名称 */ private String name; /** * 排序 */ private Long sort; /** * 描述 */ private String description; /** * 创建者 */ @Column(name = "create_by") private String createBy; /** * 创建时间 */ @Column(name = "create_date") private Date createDate; /** * 更新者 */ @Column(name = "update_by") private String updateBy; /** * 更新时间 */ @Column(name = "update_date") private Date updateDate; /** * 备注信息 */ private String remarks; /** * 删除标记 */ @Column(name = "del_flag") private String delFlag; /** * 获取编号 * * @return id - 编号 */ public String getId() { return id; } /** * 设置编号 * * @param id 编号 */ public void setId(String id) { this.id = id; } /** * 获取父级编号 * * @return parent_id - 父级编号 */ public String getParentId() { return parentId; } /** * 设置父级编号 * * @param parentId 父级编号 */ public void setParentId(String parentId) { this.parentId = parentId; } /** * 获取所有父级编号 * * @return parent_ids - 所有父级编号 */ public String getParentIds() { return parentIds; } /** * 设置所有父级编号 * * @param parentIds 所有父级编号 */ public void setParentIds(String parentIds) { this.parentIds = parentIds; } /** * 获取名称 * * @return name - 名称 */ public String getName() { return name; } /** * 设置名称 * * @param name 名称 */ public void setName(String name) { this.name = name; } /** * 获取排序 * * @return sort - 排序 */ public Long getSort() { return sort; } /** * 设置排序 * * @param sort 排序 */ public void setSort(Long sort) { this.sort = sort; } /** * 获取描述 * * @return description - 描述 */ public String getDescription() { return description; } /** * 设置描述 * * @param description 描述 */ public void setDescription(String description) { this.description = description; } /** * 获取创建者 * * @return create_by - 创建者 */ public String getCreateBy() { return createBy; } /** * 设置创建者 * * @param createBy 创建者 */ public void setCreateBy(String createBy) { this.createBy = createBy; } /** * 获取创建时间 * * @return create_date - 创建时间 */ public Date getCreateDate() { return createDate; } /** * 设置创建时间 * * @param createDate 创建时间 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * 获取更新者 * * @return update_by - 更新者 */ public String getUpdateBy() { return updateBy; } /** * 设置更新者 * * @param updateBy 更新者 */ public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } /** * 获取更新时间 * * @return update_date - 更新时间 */ public Date getUpdateDate() { return updateDate; } /** * 设置更新时间 * * @param updateDate 更新时间 */ public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } /** * 获取备注信息 * * @return remarks - 备注信息 */ public String getRemarks() { return remarks; } /** * 设置备注信息 * * @param remarks 备注信息 */ public void setRemarks(String remarks) { this.remarks = remarks; } /** * 获取删除标记 * * @return del_flag - 删除标记 */ public String getDelFlag() { return delFlag; } /** * 设置删除标记 * * @param delFlag 删除标记 */ public void setDelFlag(String delFlag) { this.delFlag = delFlag; } }
92359fd356abeb1c85fe3aff9ab310f509bfcc56
812
java
Java
src/main/java/com/diegotobalina/framework/customizable/entities/example/application/usecase/IFindExampleUseCase.java
xBidi/SpringBoot
01b386aba4f99829a0a2ff27d8c32c067f4ae435
[ "MIT" ]
null
null
null
src/main/java/com/diegotobalina/framework/customizable/entities/example/application/usecase/IFindExampleUseCase.java
xBidi/SpringBoot
01b386aba4f99829a0a2ff27d8c32c067f4ae435
[ "MIT" ]
null
null
null
src/main/java/com/diegotobalina/framework/customizable/entities/example/application/usecase/IFindExampleUseCase.java
xBidi/SpringBoot
01b386aba4f99829a0a2ff27d8c32c067f4ae435
[ "MIT" ]
null
null
null
35.304348
96
0.795567
997,364
package com.diegotobalina.framework.customizable.entities.example.application.usecase; import com.diegotobalina.framework.core.anotation.UseCase; import com.diegotobalina.framework.core.crud.services.IBaseService; import com.diegotobalina.framework.core.crud.usecases.IFindUseCase; import com.diegotobalina.framework.customizable.entities.example.domain.Example; import org.springframework.data.jpa.repository.JpaRepository; @UseCase public class IFindExampleUseCase implements IFindUseCase<Example> { @Override public void preLoad( long id, IBaseService<Example> service, JpaRepository<Example, Long> repository) { /* implement */ } @Override public void postLoad( Example example, IBaseService<Example> service, JpaRepository<Example, Long> repository) { /* implement */ } }
92359fdcee57271aaf02a0bbf1c4ef08ce31cdf4
1,931
java
Java
Java/src/main/java/com/gildedrose/GildedRose.java
SDiamante13/GildedRose-Refactoring-Kata
0736f576a16fdeb7764180c4d6c75d20699d548d
[ "MIT" ]
null
null
null
Java/src/main/java/com/gildedrose/GildedRose.java
SDiamante13/GildedRose-Refactoring-Kata
0736f576a16fdeb7764180c4d6c75d20699d548d
[ "MIT" ]
null
null
null
Java/src/main/java/com/gildedrose/GildedRose.java
SDiamante13/GildedRose-Refactoring-Kata
0736f576a16fdeb7764180c4d6c75d20699d548d
[ "MIT" ]
null
null
null
29.257576
85
0.547903
997,365
package com.gildedrose; import static com.gildedrose.Constants.*; class GildedRose { Item[] items; public GildedRose(Item[] items) { this.items = items; } public void updateQuality() { // iterate through list of items, update sellin and quality according to name for (int i = 0; i < items.length; i++) { if (SULFURAS.equals(items[i].name)) { continue; } else if (AGED_BRIE.equals(items[i].name)) { setItemQuality(items[i], 1); } else if (BACKSTAGE_PASS.equals(items[i].name)) { updateQualityForBackstagePass(items[i]); } else if (items[i].name.contains(CONJURED_ITEM)) { setItemQuality(items[i], -2); } else { setItemQuality(items[i], -1); } items[i].sellIn = items[i].sellIn - 1; handleExpiredItem(items[i]); } } private void setItemQuality(Item item, int qualityDifference) { if (item.quality < MIN_QUALITY || item.quality >= MAX_QUALITY) return; if (item.quality == MIN_QUALITY && !item.name.equals(AGED_BRIE)) return; item.quality = item.quality + qualityDifference; if (item.quality > 50) { item.quality = 50; } } private void updateQualityForBackstagePass(Item item) { if (item.sellIn > 10) { setItemQuality(item, 1); } else if (item.sellIn > 5) { setItemQuality(item, 2); } else { setItemQuality(item, 3); } } private void handleExpiredItem(Item item) { if (item.sellIn >= EXPIRATION_DATE) return; if (item.name.equals(AGED_BRIE)) { setItemQuality(item, 1); } else if (item.name.equals(BACKSTAGE_PASS)) { item.quality = 0; } else { setItemQuality(item, -1); } } }
9235a291237d7d90938d898d628752b37149bddc
952
java
Java
rdfit-core/src/test/java/com/github/lapesd/rdfit/components/normalizers/DefaultSourceNormalizerRegistryTest.java
lapesd/rdfit
9d66746cb4a80454da13931c77e9745be46ff521
[ "Apache-2.0" ]
2
2021-06-15T19:02:57.000Z
2021-08-20T14:31:42.000Z
rdfit-core/src/test/java/com/github/lapesd/rdfit/components/normalizers/DefaultSourceNormalizerRegistryTest.java
lapesd/rdfit
9d66746cb4a80454da13931c77e9745be46ff521
[ "Apache-2.0" ]
null
null
null
rdfit-core/src/test/java/com/github/lapesd/rdfit/components/normalizers/DefaultSourceNormalizerRegistryTest.java
lapesd/rdfit
9d66746cb4a80454da13931c77e9745be46ff521
[ "Apache-2.0" ]
null
null
null
38.08
91
0.741597
997,366
/* * Copyright 2021 Alexis Armin Huf * * 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.github.lapesd.rdfit.components.normalizers; import javax.annotation.Nonnull; public class DefaultSourceNormalizerRegistryTest extends SourceNormalizerRegistryTestBase { @Override protected @Nonnull SourceNormalizerRegistry createRegistry() { return new DefaultSourceNormalizerRegistry(); } }
9235a2d784976a76917d0900135f8776e89e112c
1,763
java
Java
ExtractedJars/PACT_com.pactforcure.app/javafiles/com/google/android/gms/internal/zzaxs.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
3
2019-05-01T09:22:08.000Z
2019-07-06T22:21:59.000Z
ExtractedJars/PACT_com.pactforcure.app/javafiles/com/google/android/gms/internal/zzaxs.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
null
null
null
ExtractedJars/PACT_com.pactforcure.app/javafiles/com/google/android/gms/internal/zzaxs.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
1
2020-11-26T12:22:02.000Z
2020-11-26T12:22:02.000Z
29.383333
110
0.572887
997,367
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.google.android.gms.internal; import android.os.Parcel; import com.google.android.gms.common.internal.safeparcel.zza; import java.util.List; // Referenced classes of package com.google.android.gms.internal: // zzaxt public class zzaxs extends zza { zzaxs(int i, boolean flag, List list) { // 0 0:aload_0 // 1 1:invokespecial #26 <Method void zza()> mVersionCode = i; // 2 4:aload_0 // 3 5:iload_1 // 4 6:putfield #28 <Field int mVersionCode> zzbCn = flag; // 5 9:aload_0 // 6 10:iload_2 // 7 11:putfield #30 <Field boolean zzbCn> zzbCo = list; // 8 14:aload_0 // 9 15:aload_3 // 10 16:putfield #32 <Field List zzbCo> // 11 19:return } public void writeToParcel(Parcel parcel, int i) { com.google.android.gms.internal.zzaxt.zza(this, parcel, i); // 0 0:aload_0 // 1 1:aload_1 // 2 2:iload_2 // 3 3:invokestatic #40 <Method void com.google.android.gms.internal.zzaxt.zza(zzaxs, Parcel, int)> // 4 6:return } public static final android.os.Parcelable.Creator CREATOR = new zzaxt(); final int mVersionCode; final boolean zzbCn; final List zzbCo; static { // 0 0:new #18 <Class zzaxt> // 1 3:dup // 2 4:invokespecial #21 <Method void zzaxt()> // 3 7:putstatic #23 <Field android.os.Parcelable$Creator CREATOR> //* 4 10:return } }
9235a30a5ca294b4ab207646c6c8dafbfa15c63b
1,407
java
Java
ole-app/olefs/src/main/java/org/kuali/ole/pdp/util/HttpsTrustManager.java
VU-libtech/OLE-INST
9f5efae4dfaf810fa671c6ac6670a6051303b43d
[ "ECL-2.0" ]
1
2017-01-26T03:50:56.000Z
2017-01-26T03:50:56.000Z
ole-app/olefs/src/main/java/org/kuali/ole/pdp/util/HttpsTrustManager.java
VU-libtech/OLE-INST
9f5efae4dfaf810fa671c6ac6670a6051303b43d
[ "ECL-2.0" ]
3
2020-11-16T20:28:08.000Z
2021-03-22T23:41:19.000Z
ole-app/olefs/src/main/java/org/kuali/ole/pdp/util/HttpsTrustManager.java
VU-libtech/OLE-INST
9f5efae4dfaf810fa671c6ac6670a6051303b43d
[ "ECL-2.0" ]
null
null
null
32.72093
106
0.758351
997,368
/* * Copyright 2011 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.ole.pdp.util; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; /** * A simple implementation of X509TrustManager which bypass any server certificate. * This implementation can be used for known trusted HTTPS URLs that don't require authentication. */ public class HttpsTrustManager implements X509TrustManager { public HttpsTrustManager() { } public void checkClientTrusted(X509Certificate chain[], String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate chain[], String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }
9235a36200786c144c0b014e3e2a7583f88210fa
4,849
java
Java
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/CompressionOutputStream.java
dmgerman/hadoop
70c015914a8756c5440cd969d70dac04b8b6142b
[ "Apache-2.0" ]
null
null
null
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/CompressionOutputStream.java
dmgerman/hadoop
70c015914a8756c5440cd969d70dac04b8b6142b
[ "Apache-2.0" ]
null
null
null
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/CompressionOutputStream.java
dmgerman/hadoop
70c015914a8756c5440cd969d70dac04b8b6142b
[ "Apache-2.0" ]
null
null
null
19.791837
813
0.785935
997,369
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package DECL|package|org.apache.hadoop.io.compress package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|io operator|. name|compress package|; end_package begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|io operator|. name|OutputStream import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|classification operator|. name|InterfaceAudience import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|classification operator|. name|InterfaceStability import|; end_import begin_comment comment|/** * A compression output stream. */ end_comment begin_class annotation|@ name|InterfaceAudience operator|. name|Public annotation|@ name|InterfaceStability operator|. name|Evolving DECL|class|CompressionOutputStream specifier|public specifier|abstract class|class name|CompressionOutputStream extends|extends name|OutputStream block|{ comment|/** * The output stream to be compressed. */ DECL|field|out specifier|protected specifier|final name|OutputStream name|out decl_stmt|; comment|/** * If non-null, this is the Compressor object that we should call * CodecPool#returnCompressor on when this stream is closed. */ DECL|field|trackedCompressor specifier|private name|Compressor name|trackedCompressor decl_stmt|; comment|/** * Create a compression output stream that writes * the compressed bytes to the given stream. * @param out */ DECL|method|CompressionOutputStream (OutputStream out) specifier|protected name|CompressionOutputStream parameter_list|( name|OutputStream name|out parameter_list|) block|{ name|this operator|. name|out operator|= name|out expr_stmt|; block|} DECL|method|setTrackedCompressor (Compressor compressor) name|void name|setTrackedCompressor parameter_list|( name|Compressor name|compressor parameter_list|) block|{ name|trackedCompressor operator|= name|compressor expr_stmt|; block|} annotation|@ name|Override DECL|method|close () specifier|public name|void name|close parameter_list|() throws|throws name|IOException block|{ try|try block|{ name|finish argument_list|() expr_stmt|; block|} finally|finally block|{ try|try block|{ name|out operator|. name|close argument_list|() expr_stmt|; block|} finally|finally block|{ if|if condition|( name|trackedCompressor operator|!= literal|null condition|) block|{ name|CodecPool operator|. name|returnCompressor argument_list|( name|trackedCompressor argument_list|) expr_stmt|; name|trackedCompressor operator|= literal|null expr_stmt|; block|} block|} block|} block|} annotation|@ name|Override DECL|method|flush () specifier|public name|void name|flush parameter_list|() throws|throws name|IOException block|{ name|out operator|. name|flush argument_list|() expr_stmt|; block|} comment|/** * Write compressed bytes to the stream. * Made abstract to prevent leakage to underlying stream. */ annotation|@ name|Override DECL|method|write (byte[] b, int off, int len) specifier|public specifier|abstract name|void name|write parameter_list|( name|byte index|[] name|b parameter_list|, name|int name|off parameter_list|, name|int name|len parameter_list|) throws|throws name|IOException function_decl|; comment|/** * Finishes writing compressed data to the output stream * without closing the underlying stream. */ DECL|method|finish () specifier|public specifier|abstract name|void name|finish parameter_list|() throws|throws name|IOException function_decl|; comment|/** * Reset the compression to the initial state. * Does not reset the underlying stream. */ DECL|method|resetState () specifier|public specifier|abstract name|void name|resetState parameter_list|() throws|throws name|IOException function_decl|; block|} end_class end_unit
9235a425298ac225bfff7a2f19fbf0f452e8047f
520
java
Java
src/main/java/com/werken/xpath/function/FalseFunction.java
Obsidian-StudiosInc/werken-xpath
21ce6ed9e1d93f4a4f382d10a475f4bc69e1a0bf
[ "Apache-2.0" ]
null
null
null
src/main/java/com/werken/xpath/function/FalseFunction.java
Obsidian-StudiosInc/werken-xpath
21ce6ed9e1d93f4a4f382d10a475f4bc69e1a0bf
[ "Apache-2.0" ]
null
null
null
src/main/java/com/werken/xpath/function/FalseFunction.java
Obsidian-StudiosInc/werken-xpath
21ce6ed9e1d93f4a4f382d10a475f4bc69e1a0bf
[ "Apache-2.0" ]
null
null
null
15.294118
53
0.601923
997,370
package com.werken.xpath.function; import com.werken.xpath.impl.Context; import java.util.List; /** <p><b>4.3</b> <code><i>boolean</i> false()</code> @author bob mcwhirter (bob @ werken.com) */ public class FalseFunction implements Function { public Object call(Context context, List args) { if (args.size() == 0) { return evaluate(); } // FIXME: Toss exception return null; } public static Boolean evaluate() { return Boolean.FALSE; } }
9235a470fb0b86b70ee0bd4bee3e3e3fb7f9a0a7
3,929
java
Java
src/com/student/view/TestPlatform.java
haifengchengguang/java-Online-Exam-Platform
6b065c197236ee74388b923fc8a5122bd5b7841c
[ "BSD-3-Clause" ]
null
null
null
src/com/student/view/TestPlatform.java
haifengchengguang/java-Online-Exam-Platform
6b065c197236ee74388b923fc8a5122bd5b7841c
[ "BSD-3-Clause" ]
null
null
null
src/com/student/view/TestPlatform.java
haifengchengguang/java-Online-Exam-Platform
6b065c197236ee74388b923fc8a5122bd5b7841c
[ "BSD-3-Clause" ]
null
null
null
30.223077
143
0.594044
997,371
package com.student.view; import com.common.Message; import com.common.MsgType; import com.server.ManageThread; import com.student.tool.ClientToServerThread; import javax.swing.*; import java.awt.*; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.IOException; import java.io.ObjectOutputStream; public class TestPlatform extends JFrame implements WindowListener { private String ownerId; public TestPlatform(String ownerId) { this.ownerId=ownerId; this.setTitle("\u7ebf\u4e0a\u8003\u8bd5\u5e73\u53f0\u2014\u5b66\u751f\u7aef");//线上考试平台—学生端 this.setBounds(100,100,350,200); //this.setLocationRelativeTo(null); // Center the frame this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);; this.setSize(1000, 600); /* * 调用用户定义的方法并添加组件到面板 */ Container container=this.getContentPane(); container.setLayout(new BorderLayout()); JPanel panelW=new JPanel(); container.add(panelW, BorderLayout.WEST); JPanel panelN=new JPanel(); container.add(panelN,BorderLayout.NORTH); JLabel jLabel1=new JLabel(ownerId);//用户1 panelW.add(jLabel1); JTextPane jTextPane1=new JTextPane(); jTextPane1.setEnabled(false); panelW.add(jTextPane1); /*JTextField jTextField1=new JPasswordField(); jTextField1.setEnabled(false); panelW.add(jTextField1);*/ JLabel jLabel2=new JLabel("<html><body><p align=\"center\">\u5b66\u751f\u8003\u8bd5\u5e73\u53f0<br/>v1.0.0</p></body></html>");//学生考试平台 panelN.add(jLabel2); JPanel panelC=new JPanel(); container.add(panelC,BorderLayout.CENTER); JPanel panelE=new JPanel(); JLabel jLabelE=new JLabel("\u9898\u76ee");//"题目" panelE.add(jLabelE); container.add(panelE,BorderLayout.EAST); this.addWindowListener(this); //按关闭按钮,啥事也不做 this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); // 设置界面可见 this.setVisible(true); } @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosing(WindowEvent e) { int option = JOptionPane.showConfirmDialog(this, "\u786e\u5b9a\u9000\u51fa\u7cfb\u7edf?", "\u63d0\u793a", JOptionPane.YES_NO_OPTION);//确定退出系统? 提示 if (option == JOptionPane.YES_OPTION) { if (e.getWindow() == this) { Message msg = new Message(); msg.setSenderId(ownerId); msg.setType(MsgType.UNLOAD_LOGIN); try { ClientToServerThread th = ManageThread.getThread(ownerId); ObjectOutputStream out = new ObjectOutputStream(th.getClient().getOutputStream()); out.writeObject(msg); //结束线程 th.myStop(); ManageThread.removeThread(ownerId); this.dispose(); } catch (IOException ex) { ex.printStackTrace(); } System.exit(0); this.dispose(); System.exit(0); } else { return; } } else if(option == JOptionPane.NO_OPTION){ if (e.getWindow() == this) { return; } } } @Override public void windowClosed(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } /*public void paint(Graphics g){ Font f1 = new Font("宋体", Font.BOLD, 28); g.setFont(f1); g.drawString("线上考试平台", 100, 100); }*/ }
9235a4dba4c38ad1b30bf93fd9b43b0523a2a9da
4,577
java
Java
project/src/main/java/com/edu/neu/csye6225/application/user/User.java
csye6225org/webapp
f87e0cd98fb35534f9ed9012b808373f0579a1ac
[ "MIT" ]
null
null
null
project/src/main/java/com/edu/neu/csye6225/application/user/User.java
csye6225org/webapp
f87e0cd98fb35534f9ed9012b808373f0579a1ac
[ "MIT" ]
null
null
null
project/src/main/java/com/edu/neu/csye6225/application/user/User.java
csye6225org/webapp
f87e0cd98fb35534f9ed9012b808373f0579a1ac
[ "MIT" ]
null
null
null
25.287293
88
0.577671
997,372
package com.edu.neu.csye6225.application.user; import javax.persistence.*; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.UUID; @Entity(name = "User") @Table( name = "\"user\"", uniqueConstraints = { @UniqueConstraint( name = "user_email_unique", columnNames = "username" ) } ) public class User { @Id private UUID id; @Column( name = "first_name", columnDefinition = "TEXT" ) private String first_name; @Column( name = "last_name", columnDefinition = "TEXT" ) private String last_name; @Column( name = "username", nullable = false, columnDefinition = "TEXT" ) private String username; @Column( name = "password", nullable = false, columnDefinition = "TEXT" ) private String password; @Column( name = "account_created", nullable = false, columnDefinition = "TIMESTAMP", updatable = false ) private ZonedDateTime account_created; @Column( name = "account_updated", columnDefinition = "TIMESTAMP" ) private ZonedDateTime account_updated; @Column( name = "verified" ) private boolean verified; @Column( name = "verified_on", columnDefinition = "TIMESTAMP" ) private ZonedDateTime verified_on; public UUID getId() { UUID uid = new UUID(0,0); if (id == null) return uid; else return id; } public void setId(UUID id) { this.id = id; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public ZonedDateTime getAccount_created() { ZonedDateTime zdt = ZonedDateTime.of(01,01,01,01,01,01,01,ZoneId.of("Z")); if(account_created == null) return zdt; else return account_created.withZoneSameInstant(ZoneId.of("Z")); } public void setAccount_created(ZonedDateTime account_created) { this.account_created = account_created; } public ZonedDateTime getAccount_updated() { ZonedDateTime zdt = ZonedDateTime.of(01,01,01,01,01,01,01,ZoneId.of("Z")); if(account_updated == null) return zdt; else return account_updated.withZoneSameInstant(ZoneId.of("Z")); } public void setAccount_updated(ZonedDateTime account_updated) { this.account_updated = account_updated; } public Boolean getVerified() { return verified; } public void setVerified(Boolean verified) { this.verified = verified; } public ZonedDateTime getVerified_on() { ZonedDateTime zdt = ZonedDateTime.of(01,01,01,01,01,01,01,ZoneId.of("Z")); if(verified_on == null) return zdt; else return verified_on.withZoneSameInstant(ZoneId.of("Z")); } public void setVerified_on(ZonedDateTime verified_on) { this.verified_on = verified_on; } public User() { } public User(String first_name, String last_name, String username, String password) { this.first_name = first_name; this.last_name = last_name; this.username = username; this.password = password; } public User(String first_name) { this.first_name = first_name; } @Override public String toString() { return "User{" + "id=" + this.getId().toString() + ", first_name='" + this.getFirst_name() + '\'' + ", last_name='" + this.getLast_name() + '\'' + ", username='" + this.getUsername() + '\'' + ", account_created=" + this.getAccount_created() + ", account_updated=" + this.getAccount_updated() + ", verified=" + this.getVerified() + ", verified_on=" + this.getVerified_on() + '}'; } }
9235a560d489194df4f43af8a89dfd9e6fd74a79
2,440
java
Java
src/org/seqcode/data/io/parsing/ParseGFF.java
seqcode/seqcode-core
db04b02e257dd460926d1dc5d499128c27ee4594
[ "MIT" ]
4
2017-05-22T18:06:22.000Z
2022-03-28T20:27:40.000Z
src/org/seqcode/data/io/parsing/ParseGFF.java
yztxwd/seqcode-core
51595220bc2fec4e7a2f10ced894b4b3bd8a4cda
[ "MIT" ]
null
null
null
src/org/seqcode/data/io/parsing/ParseGFF.java
yztxwd/seqcode-core
51595220bc2fec4e7a2f10ced894b4b3bd8a4cda
[ "MIT" ]
4
2017-05-24T18:49:49.000Z
2019-05-23T13:58:02.000Z
28.372093
104
0.509426
997,373
package org.seqcode.data.io.parsing; import java.io.BufferedReader; import java.io.*; import java.util.*; import java.net.URLEncoder; public class ParseGFF implements Iterator { public static void main(String[] args) { try { ParseGFF parser = new ParseGFF(new File(args[0])); parser.printLines(System.out); } catch(IOException ie) { ie.printStackTrace(); } } private BufferedReader br; private int lineNum; private String line, filename; private boolean dirty; public ParseGFF(File f) throws IOException { br = new BufferedReader(new FileReader(f)); lineNum = 0; dirty = true; filename = f.getName(); } public boolean hasNext() { if (dirty) { try { lineNum++; line = br.readLine(); } catch (IOException ex) { throw new RuntimeException("Parsing Error, File \"" + filename + "\", line " + lineNum); } dirty = false; } if (line == null) { try { br.close(); } catch (IOException ex) { throw new RuntimeException("Can't close " + filename); } return false; } else { if (line.startsWith("#")) { dirty = true; return hasNext(); } else { return true; } } } public GFFEntry next() throws NoSuchElementException { if (line == null) { throw new NoSuchElementException("No more lines to parse"); } dirty = true; line = line.trim(); if(!line.startsWith("#")) { try { GFFEntry gffLine = new GFFEntry(line); return gffLine; } catch(NoSuchElementException e) { throw new RuntimeException("Parsing Error, File \"" + filename + "\", line " + lineNum); } } else { return next(); } } public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException("Can't remove lines from GFF file"); } public void printLines() { printLines(System.out); } public void printLines(PrintStream ps) { while(hasNext()) { next().printLine(ps); } } }
9235a5e7ecd8d82546af1af1cc5db3427d4239c5
964
java
Java
gateway-core/src/main/java/com/kalman03/gateway/interceptor/AbstractRouteHandlerInterceptor.java
jingxiang/dubbo-gateway
ed86e8caa34cc0546afe8ce6e62ce6bc342e5ff3
[ "Apache-2.0" ]
20
2022-03-16T02:48:57.000Z
2022-03-27T09:43:45.000Z
gateway-core/src/main/java/com/kalman03/gateway/interceptor/AbstractRouteHandlerInterceptor.java
jingxiang/dubbo-gateway
ed86e8caa34cc0546afe8ce6e62ce6bc342e5ff3
[ "Apache-2.0" ]
null
null
null
gateway-core/src/main/java/com/kalman03/gateway/interceptor/AbstractRouteHandlerInterceptor.java
jingxiang/dubbo-gateway
ed86e8caa34cc0546afe8ce6e62ce6bc342e5ff3
[ "Apache-2.0" ]
4
2022-03-16T02:49:11.000Z
2022-03-25T05:27:51.000Z
31.096774
118
0.799793
997,374
package com.kalman03.gateway.interceptor; import com.kalman03.gateway.constants.AttributeConstans; import com.kalman03.gateway.dubbo.DubboRoute; import com.kalman03.gateway.http.GatewayHttpRequest; import com.kalman03.gateway.http.GatewayHttpResponse; import lombok.extern.slf4j.Slf4j; /** * @author kalman03 * @since 2022-03-15 */ @Slf4j public abstract class AbstractRouteHandlerInterceptor implements HandlerInterceptor { public abstract DubboRoute resolvingDubboRoute(GatewayHttpRequest request); @Override public boolean preHandle(GatewayHttpRequest request, GatewayHttpResponse response) throws Exception { DubboRoute dubboRoute = resolvingDubboRoute(request); if (dubboRoute == null) { log.warn("Route parameters error.Request should matches Path or Mix route rule.Request path is {}",request.path()); response.setRouteError(); return false; } request.setAttribute(AttributeConstans.DUBBO_ROUTE, dubboRoute); return true; } }
9235a69c4703573c8ae6b4f0c1dd4d3294abec3d
1,785
java
Java
java/contemporary_programming_methods/OctagonTester.java
innovaTe-dev/wuproj
8cda86e36bd678d23d662187d41ed6edd3c79871
[ "MIT" ]
null
null
null
java/contemporary_programming_methods/OctagonTester.java
innovaTe-dev/wuproj
8cda86e36bd678d23d662187d41ed6edd3c79871
[ "MIT" ]
null
null
null
java/contemporary_programming_methods/OctagonTester.java
innovaTe-dev/wuproj
8cda86e36bd678d23d662187d41ed6edd3c79871
[ "MIT" ]
null
null
null
32.454545
103
0.513165
997,375
/* * 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 Lab05; import java.util.*; import java.io.*; import java.util.ArrayList; /** * * @author Tbeur */ public class OctagonTester { public static void main(String[] args) throws FileNotFoundException { ArrayList<Octagon> list = new ArrayList<>(); Scanner sideReader = new Scanner(new File("data.txt")); PrintWriter dataOut = new PrintWriter(new File("report.txt")); dataOut.println("Trevor Beurman, Lab05, 3/22/2018"); while (sideReader.hasNextLine()) { String rec = sideReader.nextLine(); String[] fields = rec.split(","); for (int k = 0; k < fields.length; k++) { try { double a = Double.parseDouble(fields[k]); Octagon o = new Octagon(a); list.add(o); dataOut.println(fields[k]); } catch (NumberFormatException ex) { dataOut.println("Invalid input detected. This input was skipped: " + fields[k]); } catch (IllegalArgumentException ex) { dataOut.println("Input was less than zero. This input was skipped: " + fields[k]); } } } dataOut.print(list); java.util.Collections.sort(list); for (int j = 0; j < list.size(); j++) { dataOut.println(list.get(j)); } dataOut.close(); sideReader.close(); } }
9235a8657dda92442e8a33f60c9fdfba8592b507
456
java
Java
src/test/java/com/mingshashan/learn/lt/Solution_202_Test.java
mingshashan/learn-algo
5022168a50bb003b839f4e03a1bc760e11d45617
[ "MIT" ]
null
null
null
src/test/java/com/mingshashan/learn/lt/Solution_202_Test.java
mingshashan/learn-algo
5022168a50bb003b839f4e03a1bc760e11d45617
[ "MIT" ]
null
null
null
src/test/java/com/mingshashan/learn/lt/Solution_202_Test.java
mingshashan/learn-algo
5022168a50bb003b839f4e03a1bc760e11d45617
[ "MIT" ]
null
null
null
21.714286
56
0.657895
997,376
package com.mingshashan.learn.lt; import com.mingshashan.learn.lt.l202.Solution_202; import org.junit.Assert; import org.junit.Test; public class Solution_202_Test { @Test public void test_01() { boolean result = new Solution_202().isHappy(19); Assert.assertTrue("ok", result); } @Test public void test_02() { boolean result = new Solution_202().isHappy(2); Assert.assertTrue("ok", !result); } }
9235ac117ad649b11ac081c9879e8f1ee9e80699
560
java
Java
javaSources/Miscellaneous/Pen_NoteBook.java
CodingExpertNeeraj/full-stack-development
62ac2a65a720f46590996dafa357d376a0b68279
[ "MIT" ]
1
2021-08-22T16:15:08.000Z
2021-08-22T16:15:08.000Z
javaSources/Miscellaneous/Pen_NoteBook.java
CodingExpertNeeraj/full-stack-development
62ac2a65a720f46590996dafa357d376a0b68279
[ "MIT" ]
null
null
null
javaSources/Miscellaneous/Pen_NoteBook.java
CodingExpertNeeraj/full-stack-development
62ac2a65a720f46590996dafa357d376a0b68279
[ "MIT" ]
null
null
null
24.347826
50
0.526786
997,377
import java.util.Scanner; public class Pen_NoteBook { public static void main(String[] args) { // conditional statments Scanner sc = new Scanner(System.in); // pen = 10 Notebook = 40 int cash = sc.nextInt(); if(cash < 10){ System.out.println("cannot by anything"); System.out.println("get more cash"); } else if(cash > 10 && cash < 50){ System.out.println("can get 1 thing"); } else{ System.out.println("can get both"); } } }
9235ac1afa7e64103ffd9d17dd6f98b519117d4e
25
java
Java
branchs/code/core/mservice-form/src/main/java/org/woo/mservice/package-info.java
valiantwu/estore
438b7eaeb8bf8f7639b3c5a00349738ddd1aa780
[ "Apache-2.0" ]
null
null
null
branchs/code/core/mservice-form/src/main/java/org/woo/mservice/package-info.java
valiantwu/estore
438b7eaeb8bf8f7639b3c5a00349738ddd1aa780
[ "Apache-2.0" ]
null
null
null
branchs/code/core/mservice-form/src/main/java/org/woo/mservice/package-info.java
valiantwu/estore
438b7eaeb8bf8f7639b3c5a00349738ddd1aa780
[ "Apache-2.0" ]
null
null
null
25
25
0.84
997,378
package org.woo.mservice;
9235ace1e78c74eb6a3bfc553f33d88ee2d65513
788
java
Java
android/app/src/main/java/com/upcwangying/apps/rn/demo/CustomTextViewManager.java
upcwangying/react-native-gallery-demo
4f4adbec296932c9847ed99b5725f31ef6503725
[ "MIT" ]
3
2021-07-27T15:55:49.000Z
2021-12-09T07:20:45.000Z
android/app/src/main/java/com/upcwangying/apps/rn/demo/CustomTextViewManager.java
upcwangying/react-native-gallery-demo
4f4adbec296932c9847ed99b5725f31ef6503725
[ "MIT" ]
1
2020-06-18T01:22:58.000Z
2020-06-22T07:17:04.000Z
android/app/src/main/java/com/upcwangying/apps/rn/demo/CustomTextViewManager.java
upcwangying/react-native-gallery-demo
4f4adbec296932c9847ed99b5725f31ef6503725
[ "MIT" ]
1
2021-09-06T17:20:16.000Z
2021-09-06T17:20:16.000Z
25.419355
85
0.741117
997,379
package com.upcwangying.apps.rn.demo; import android.widget.TextView; import androidx.annotation.NonNull; import com.facebook.react.uimanager.SimpleViewManager; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.annotations.ReactProp; class CustomTextViewManager extends SimpleViewManager<TextView> { public static final String REACT_CLASS = "RNDCustomTextView"; @NonNull @Override public String getName() { return REACT_CLASS; } @NonNull @Override protected TextView createViewInstance(@NonNull ThemedReactContext reactContext) { return new TextView(reactContext); } @ReactProp(name = "text") public void setText(TextView view, String text) { view.setText(text); } }
9235ace525070bf9cfd94adc7a3abff5eda5e872
1,790
java
Java
application/application-api/src/main/java/org/apache/aries/application/management/spi/convert/BundleConverter.java
lburgazzoli/apache-aries
d85be2b8f8a026cb1959c83ceb4ed812cd9d1279
[ "Apache-2.0" ]
75
2015-01-09T20:20:37.000Z
2022-03-22T13:22:30.000Z
application/application-api/src/main/java/org/apache/aries/application/management/spi/convert/BundleConverter.java
lburgazzoli/apache-aries
d85be2b8f8a026cb1959c83ceb4ed812cd9d1279
[ "Apache-2.0" ]
77
2015-02-06T11:24:25.000Z
2022-03-18T17:41:52.000Z
application/application-api/src/main/java/org/apache/aries/application/management/spi/convert/BundleConverter.java
coheigea/aries
457551c4dda9ceca2e57572c121c605afb52db36
[ "Apache-2.0" ]
157
2015-01-12T20:43:13.000Z
2022-01-31T12:11:40.000Z
42.619048
101
0.744693
997,380
/* * 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 WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.application.management.spi.convert; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.filesystem.IFile; /** * A BundleConverter turns a .jar that is not an OSGi bundle into a well formed OSGi bundle, * or a .war that is not a WAB into a WAB. The first converter to return a non-null result is * taken as having fully converted the bundle. */ public interface BundleConverter { /** * @param parentEba The root of the eba containing the artifact being converted - * a zip format file with .eba suffix, or an exploded directory. * @param fileInEba The object within the eba to convert * @throws ConversionException if conversion was attempted but failed * @return valid input stream or null if this converter does not support conversion of * this artifact type. */ public BundleConversion convert (IDirectory parentEba, IFile fileInEba) throws ConversionException; }
9235aeae7f285a957aaaefb9b098c8bb3383047c
2,231
java
Java
src/test/java/dukecooks/storage/mealplan/JsonSerializableMealPlanBookTest.java
bigjunnn/addressbook-level3
dd56021258de9ccbd7300829d088a7aaf7054a5e
[ "MIT" ]
null
null
null
src/test/java/dukecooks/storage/mealplan/JsonSerializableMealPlanBookTest.java
bigjunnn/addressbook-level3
dd56021258de9ccbd7300829d088a7aaf7054a5e
[ "MIT" ]
81
2019-10-02T17:21:33.000Z
2019-11-14T05:47:07.000Z
src/test/java/dukecooks/storage/mealplan/JsonSerializableMealPlanBookTest.java
bigjunnn/addressbook-level3
dd56021258de9ccbd7300829d088a7aaf7054a5e
[ "MIT" ]
4
2019-09-15T07:16:48.000Z
2019-09-20T08:08:11.000Z
47.468085
119
0.793814
997,381
package dukecooks.storage.mealplan; import static dukecooks.testutil.Assert.assertThrows; import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.jupiter.api.Test; import dukecooks.commons.exceptions.IllegalValueException; import dukecooks.commons.util.JsonUtil; import dukecooks.model.mealplan.MealPlanBook; import dukecooks.testutil.mealplan.TypicalMealPlans; public class JsonSerializableMealPlanBookTest { private static final Path TEST_DATA_FOLDER = Paths.get("src", "test", "data", "JsonSerializableMealPlanBookTest"); private static final Path TYPICAL_MEALPLANS_FILE = TEST_DATA_FOLDER.resolve("typicalMealPlansMealPlanBook.json"); private static final Path INVALID_MEALPLAN_FILE = TEST_DATA_FOLDER.resolve("invalidMealPlanMealPlanBook.json"); private static final Path DUPLICATE_MEALPLAN_FILE = TEST_DATA_FOLDER.resolve("duplicateMealPlanMealPlanBook.json"); @Test public void toModelType_typicalMealPlansFile_success() throws Exception { JsonSerializableMealPlanBook dataFromFile = JsonUtil.readJsonFile(TYPICAL_MEALPLANS_FILE, JsonSerializableMealPlanBook.class).get(); MealPlanBook mealPlanBookFromFile = dataFromFile.toModelType(); MealPlanBook typicalMealPlansMealPlanBook = TypicalMealPlans.getTypicalMealPlanBook(); assertEquals(mealPlanBookFromFile, typicalMealPlansMealPlanBook); } @Test public void toModelType_invalidMealPlanFile_throwsIllegalValueException() throws Exception { JsonSerializableMealPlanBook dataFromFile = JsonUtil.readJsonFile(INVALID_MEALPLAN_FILE, JsonSerializableMealPlanBook.class).get(); assertThrows(IllegalValueException.class, dataFromFile::toModelType); } @Test public void toModelType_duplicateMealPlans_throwsIllegalValueException() throws Exception { JsonSerializableMealPlanBook dataFromFile = JsonUtil.readJsonFile(DUPLICATE_MEALPLAN_FILE, JsonSerializableMealPlanBook.class).get(); assertThrows(IllegalValueException.class, JsonSerializableMealPlanBook.MESSAGE_DUPLICATE_MEALPLAN, dataFromFile::toModelType); } }
9235af1d052eb15593f543911e5bfae747c4e14c
1,543
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/HardwarePack/HardwareMapping.java
StamatieMihnea/UltimateGoal2020
d432cf6c8a1b38b1228f823e7859e3d49f7600eb
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/HardwarePack/HardwareMapping.java
StamatieMihnea/UltimateGoal2020
d432cf6c8a1b38b1228f823e7859e3d49f7600eb
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/HardwarePack/HardwareMapping.java
StamatieMihnea/UltimateGoal2020
d432cf6c8a1b38b1228f823e7859e3d49f7600eb
[ "MIT" ]
null
null
null
37.634146
75
0.748542
997,382
package org.firstinspires.ftc.teamcode.HardwarePack; import com.qualcomm.robotcore.hardware.HardwareMap; import org.firstinspires.ftc.teamcode.Utils.HardwareUtil; import static org.firstinspires.ftc.teamcode.Utils.HardwareUtil.getCRServo; import static org.firstinspires.ftc.teamcode.Utils.HardwareUtil.getDC; import static org.firstinspires.ftc.teamcode.Utils.HardwareUtil.getIMU; import static org.firstinspires.ftc.teamcode.Utils.HardwareUtil.getServo; import static org.firstinspires.ftc.teamcode.Utils.HardwareUtil.getWebcam; public class HardwareMapping extends HardwareDeclarations{ protected static void hardwareMapping(HardwareMap hardwareMap) { front_right = getDC("front_right", hardwareMap); front_left = getDC("front_left", hardwareMap); back_left = getDC("back_left", hardwareMap); back_right = getDC("back_right", hardwareMap); webcam = getWebcam("webcam", hardwareMap); imu = getIMU("imu", hardwareMap); angleControlSecvL = getServo("angle_control_left_s",hardwareMap); angleControlSecvR = getServo("angle_control_right_s",hardwareMap); shooter_left = getDC("shooter_left", hardwareMap); shooter_right = getDC("shooter_right",hardwareMap); shooter_idler = getServo("shooter_idler", hardwareMap); shooter_booster = getCRServo("shooter_booster", hardwareMap); HardwareUtil.InitializeIMU(imu); right_encoder = back_right; left_encoder = back_left; center_encoder = front_right; } }
9235b03ba6d6367422d9223578597e6230c4af61
1,893
java
Java
src/main/java/com/github/piotrkot/mustache/Tags.java
piotrkot/simple-mustache
5ecee38ede7e19ae126102a711919e330224d98c
[ "MIT" ]
null
null
null
src/main/java/com/github/piotrkot/mustache/Tags.java
piotrkot/simple-mustache
5ecee38ede7e19ae126102a711919e330224d98c
[ "MIT" ]
3
2019-10-14T08:30:56.000Z
2019-10-23T12:59:24.000Z
src/main/java/com/github/piotrkot/mustache/Tags.java
piotrkot/simple-mustache
5ecee38ede7e19ae126102a711919e330224d98c
[ "MIT" ]
null
null
null
32.758621
80
0.692105
997,383
/** * The MIT License (MIT) * * Copyright (c) 2016 piotrkot * * 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.github.piotrkot.mustache; import java.util.Map; /** * Group of tags that can together render a content. * @author Piotr Kotlicki (dycjh@example.com) * @version $Id$ * @since 1.0 */ public final class Tags implements Tag { /** * Group of tags. */ private final Tag[] grp; /** * Constructor. * @param group Group of tags. */ public Tags(final Tag... group) { this.grp = group; } @Override public String render(final CharSequence template, final Map<CharSequence, Object> pairs) { String rendered = template.toString(); for (final Tag tag : this.grp) { rendered = tag.render(rendered, pairs); } return rendered; } }
9235b1b6ba942803422049a34b6dd1c54a83d4c2
1,024
java
Java
app/src/main/java/com/appjishu/starzone/app/mvp/presenter/IMomentPresenter.java
liushaoming/star-zone-android
396609711251fd501305dcdfac501b3318b63a6f
[ "Apache-2.0" ]
27
2019-01-16T05:22:43.000Z
2019-07-08T07:27:38.000Z
app/src/main/java/com/appjishu/starzone/app/mvp/presenter/IMomentPresenter.java
bootsrc/star-zone-android
396609711251fd501305dcdfac501b3318b63a6f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/appjishu/starzone/app/mvp/presenter/IMomentPresenter.java
bootsrc/star-zone-android
396609711251fd501305dcdfac501b3318b63a6f
[ "Apache-2.0" ]
17
2019-08-16T07:21:28.000Z
2021-10-13T03:23:29.000Z
30.117647
133
0.800781
997,384
package com.appjishu.starzone.app.mvp.presenter; import android.content.Context; import android.support.annotation.NonNull; import com.razerdp.github.com.common.entity.CommentInfo; import com.razerdp.github.com.common.entity.LikeInfo; import com.razerdp.github.com.common.entity.MomentInfo; import java.util.List; import com.appjishu.starzone.app.mvp.view.IMomentView; import razerdp.github.com.lib.mvp.IBasePresenter; /** * Created by liushaoming on 2016/12/7. */ public interface IMomentPresenter extends IBasePresenter<IMomentView> { void addLike(int viewHolderPos, long momentid, List<LikeInfo> currentLikeList); void unLike(int viewHolderPos, long likesid, List<LikeInfo> currentLikeList); void addComment(int viewHolderPos, long momentid, long replyUserid, String commentContent, List<CommentInfo> currentCommentList); void deleteComment(int viewHolderPos, long commentid, List<CommentInfo> currentCommentList); void deleteMoments(Context context,@NonNull MomentInfo momentInfo); }
9235b278c0ef03b4fe5b9f2488358ee7ff91f271
1,909
java
Java
core/src/main/java/module-info.java
mjKosmic/SpinyGUI
f8bed6ff604f208d3f6e5cdbe816d2d754308d36
[ "MIT" ]
null
null
null
core/src/main/java/module-info.java
mjKosmic/SpinyGUI
f8bed6ff604f208d3f6e5cdbe816d2d754308d36
[ "MIT" ]
null
null
null
core/src/main/java/module-info.java
mjKosmic/SpinyGUI
f8bed6ff604f208d3f6e5cdbe816d2d754308d36
[ "MIT" ]
null
null
null
34.089286
72
0.760608
997,385
open module com.spinyowl.spinygui.core { requires transitive jdom2; requires transitive java.xml; requires transitive org.joml; requires org.lwjgl; requires org.lwjgl.natives; requires org.lwjgl.yoga; requires org.lwjgl.yoga.natives; requires guava.base.r03; requires guava.collections.r03; requires io.github.classgraph; requires org.antlr.antlr4.runtime; requires transitive commons.logging; exports com.spinyowl.spinygui.core.animation; exports com.spinyowl.spinygui.core.api; exports com.spinyowl.spinygui.core.node; exports com.spinyowl.spinygui.core.node.base; exports com.spinyowl.spinygui.core.node.element; exports com.spinyowl.spinygui.core.node.intersection; exports com.spinyowl.spinygui.core.converter; exports com.spinyowl.spinygui.core.converter.css.parser; exports com.spinyowl.spinygui.core.converter.css.parser.annotations; exports com.spinyowl.spinygui.core.converter.css.parser.visitor; exports com.spinyowl.spinygui.core.converter.dom; exports com.spinyowl.spinygui.core.event; exports com.spinyowl.spinygui.core.event.listener; exports com.spinyowl.spinygui.core.event.processor; exports com.spinyowl.spinygui.core.layout; exports com.spinyowl.spinygui.core.style; exports com.spinyowl.spinygui.core.style.css; exports com.spinyowl.spinygui.core.style.css.extractor; exports com.spinyowl.spinygui.core.style.css.property; exports com.spinyowl.spinygui.core.style.css.selector; exports com.spinyowl.spinygui.core.style.manager; exports com.spinyowl.spinygui.core.style.types; exports com.spinyowl.spinygui.core.style.types.border; exports com.spinyowl.spinygui.core.style.types.flex; exports com.spinyowl.spinygui.core.style.types.length; exports com.spinyowl.spinygui.core.util; exports com.spinyowl.spinygui.core; }
9235b41c85552cd30dfa76b76405d2e934ce92f2
486
java
Java
src/main/java/dev/sim0n/caesium/mutator/impl/ClassFolderMutator.java
xiaonian233/Caesium
b607591efdce6cbbfc672a09af0ceab7c019c514
[ "MIT" ]
193
2020-11-18T09:01:41.000Z
2022-03-28T21:28:24.000Z
src/main/java/dev/sim0n/caesium/mutator/impl/ClassFolderMutator.java
xiaonian233/Caesium
b607591efdce6cbbfc672a09af0ceab7c019c514
[ "MIT" ]
23
2020-12-02T18:25:56.000Z
2022-03-25T21:00:03.000Z
src/main/java/dev/sim0n/caesium/mutator/impl/ClassFolderMutator.java
xiaonian233/Caesium
b607591efdce6cbbfc672a09af0ceab7c019c514
[ "MIT" ]
39
2020-11-29T19:09:56.000Z
2022-02-16T10:10:05.000Z
24.3
70
0.705761
997,386
package dev.sim0n.caesium.mutator.impl; import dev.sim0n.caesium.mutator.ClassMutator; import dev.sim0n.caesium.util.wrapper.impl.ClassWrapper; /** * This will turn all classes into directories by append a / to .class */ public class ClassFolderMutator extends ClassMutator { @Override public void handle(ClassWrapper wrapper) { ++counter; } @Override public void handleFinish() { logger.info("Turned {} classes into folders", counter); } }
9235b45e02465c796e42d589ecc7b31f4d065c9b
8,860
java
Java
Client/Login.java
mxue2/COMP90015-Distributed-System-Project2-2018S2
c44c8f8a35220a856e17c05eba88c1a0538ac6a2
[ "MIT" ]
null
null
null
Client/Login.java
mxue2/COMP90015-Distributed-System-Project2-2018S2
c44c8f8a35220a856e17c05eba88c1a0538ac6a2
[ "MIT" ]
null
null
null
Client/Login.java
mxue2/COMP90015-Distributed-System-Project2-2018S2
c44c8f8a35220a856e17c05eba88c1a0538ac6a2
[ "MIT" ]
null
null
null
37.07113
133
0.527991
997,387
package Client; import javafx.application.Application; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; import javafx.stage.Stage; import java.io.*; import java.net.Socket; import java.net.SocketException; import java.util.Optional; /** * * 948602 Xinwei Luo * 927096 Lixuan Ding * 950214 Lei REN * 897082 Min XUE */ public class Login extends Application { private static String ipAddress; private static int port; private GridPane gridPane = new GridPane(); public BufferedReader bufferedReader; public BufferedWriter bufferedWriter; public static void main(String[] args){ launch(args); } /** * * send message to the server */ public synchronized void write(String msg){ try { bufferedWriter.write(msg + "\n"); bufferedWriter.flush(); } catch(SocketException e){ // Alert window Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error Message"); alert.setHeaderText("Connection Error!"); alert.setContentText("Port Number is not correct or Invalid input!"); alert.showAndWait(); }catch(IOException e){ e.printStackTrace(); } } /** * * Initialize Login Stage */ @Override public void start(Stage primaryStage) { primaryStage.setTitle("Login"); gridPane.setAlignment(Pos.CENTER); Text title = new Text("Welcome to Scrabble Game"); title.setTextAlignment(TextAlignment.LEFT); title.setFill(Color.DARKBLUE); title.setFont(Font.font("Times", FontWeight.BOLD,25)); gridPane.add(title,0,0,3,1); gridPane.setHgap(10); gridPane.setVgap(10); gridPane.setPadding(new Insets(25, 25, 25, 25)); Label label2 = new Label(); label2.setText("IP Address"); label2.setFont(Font.font("Times",FontWeight.NORMAL,18)); gridPane.add(label2,1,3,1,1); TextField textField2 = new TextField(); textField2.setFont(Font.font("Times",FontWeight.NORMAL,18)); textField2.setStyle("-fx-background-color: null;" + "-fx-border-width: 0.5;" + "-fx-border-insets: 2;" + "-fx-border-radius: 5;" + "-fx-border-color: black;"); gridPane.add(textField2,2,3,1,1); Label label3 = new Label(); label3.setText("Port"); label3.setFont(Font.font("Times",FontWeight.NORMAL,18)); gridPane.add(label3,1,4,1,1); TextField textField3 = new TextField(); textField3.setFont(Font.font("Times",FontWeight.NORMAL,18)); textField3.setStyle("-fx-background-color: null;" + "-fx-border-width: 0.5;" + "-fx-border-insets: 2;" + "-fx-border-radius: 5;" + "-fx-border-color: black;"); gridPane.add(textField3,2,4,1,1); Button button1 = new Button(); button1.setText("Login"); button1.setFont(Font.font("Times",FontWeight.NORMAL,16)); Button button2 = new Button(); button2.setText("Cancel"); button2.setFont(Font.font("Times",FontWeight.NORMAL,16)); HBox hBox = new HBox(); hBox.setSpacing(35); hBox.setAlignment(Pos.CENTER_LEFT); hBox.getChildren().add(button1); hBox.getChildren().add(button2); gridPane.add(hBox,2,6,2,1); /** * * The action after clicking button Login */ button1.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { try { port = Integer.valueOf(textField3.getText()); ipAddress = textField2.getText(); } catch (Exception e){ System.out.println("exception successful"); } try { Socket socket = new Socket(ipAddress, port); bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); MessageListener.getInstance().init(socket,bufferedWriter,bufferedReader); MessageListener.getInstance().messageListener.start(); // listen to the feedback from the server System.out.println("Establish socket successfully"); IdentifyUsername.getInstance().Identify(); // Open IdentifyUsername stage /** * * The action after clicking button Validate */ IdentifyUsername.getInstance().validate.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { try { if (!IdentifyUsername.getInstance().textField1.getText().equals("")) { write("\n"); // write message to the server write("validate" + "|" + IdentifyUsername.getInstance().textField1.getText() + "\n"); } else { // Alert window Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Warning!"); alert.setHeaderText("Please input your username!"); alert.setHeight(50); alert.setWidth(40); ButtonType confirm = new ButtonType("OK"); alert.getButtonTypes().setAll(confirm); Optional<ButtonType> result = alert.showAndWait(); } }catch(Exception e){ // Alert window Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error Message"); alert.setHeaderText("Connection Error or Input Error!"); alert.setContentText("Port Number is not correct or Invalid input!"); alert.showAndWait(); textField2.setText(""); textField3.setText(""); } } }); primaryStage.close(); }catch(SocketException e){ // Alert window Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error Message"); alert.setHeaderText("Connection Error or Input Error!"); alert.setContentText("Port Number is not correct or Invalid input!"); alert.showAndWait(); textField2.setText(""); textField3.setText(""); } catch (IOException e) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error Message"); alert.setHeaderText("Connection Error or Input Error!"); alert.setContentText("Port Number is not correct or Invalid input!"); alert.showAndWait(); textField2.setText(""); textField3.setText(""); } } }); /** * * The action after clicking button Cancel */ button2.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { System.exit(0); // Exit the system } }); Scene scene = new Scene(gridPane,400,250); primaryStage.setScene(scene); scene.getStylesheets().add(getClass().getResource("background.css").toExternalForm()); primaryStage.show(); } }
9235b54b0c99a3eed9953ba8df18c7ce7c64b84f
109,369
java
Java
tmp/CodeResult/WordExtractor/99552391.java
takata-daiki/catalogen
1535798ab54f13213c2aea6501cb76f7ca6d5e19
[ "MIT" ]
null
null
null
tmp/CodeResult/WordExtractor/99552391.java
takata-daiki/catalogen
1535798ab54f13213c2aea6501cb76f7ca6d5e19
[ "MIT" ]
null
null
null
tmp/CodeResult/WordExtractor/99552391.java
takata-daiki/catalogen
1535798ab54f13213c2aea6501cb76f7ca6d5e19
[ "MIT" ]
null
null
null
44.01167
374
0.721539
997,388
/* =============================================================================== * * Part of the InfoGlue Content Management Platform (www.infoglue.org) * * =============================================================================== * * Copyright (C) * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2, as published by the * Free Software Foundation. See the file LICENSE.html for more information. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple * Place, Suite 330 / Boston, MA 02111-1307 / USA. * * =============================================================================== */ package org.infoglue.cms.controllers.kernel.impl.simple; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.StringReader; import java.io.Writer; import java.nio.channels.OverlappingFileLockException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.DateTools; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.NumericField; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.MultiFieldQueryParser; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.NIOFSDirectory; import org.apache.lucene.store.SingleInstanceLockFactory; import org.apache.lucene.util.Version; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.extractor.WordExtractor; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.exolab.castor.jdo.Database; import org.exolab.castor.jdo.OQLQuery; import org.exolab.castor.jdo.QueryResults; import org.infoglue.cms.entities.content.Content; import org.infoglue.cms.entities.content.ContentCategory; import org.infoglue.cms.entities.content.ContentVO; import org.infoglue.cms.entities.content.ContentVersion; import org.infoglue.cms.entities.content.ContentVersionVO; import org.infoglue.cms.entities.content.DigitalAsset; import org.infoglue.cms.entities.content.DigitalAssetVO; import org.infoglue.cms.entities.content.SmallestContentVersionVO; import org.infoglue.cms.entities.content.impl.simple.ContentImpl; import org.infoglue.cms.entities.content.impl.simple.ContentVersionImpl; import org.infoglue.cms.entities.content.impl.simple.DigitalAssetImpl; import org.infoglue.cms.entities.content.impl.simple.MediumDigitalAssetImpl; import org.infoglue.cms.entities.content.impl.simple.SmallestContentVersionImpl; import org.infoglue.cms.entities.kernel.BaseEntityVO; import org.infoglue.cms.entities.management.CategoryAttribute; import org.infoglue.cms.entities.management.ContentTypeDefinitionVO; import org.infoglue.cms.entities.management.LanguageVO; import org.infoglue.cms.entities.structure.SiteNode; import org.infoglue.cms.entities.structure.SiteNodeVO; import org.infoglue.cms.entities.structure.SiteNodeVersion; import org.infoglue.cms.entities.structure.SiteNodeVersionVO; import org.infoglue.cms.entities.structure.impl.simple.SiteNodeImpl; import org.infoglue.cms.entities.structure.impl.simple.SiteNodeVersionImpl; import org.infoglue.cms.exception.Bug; import org.infoglue.cms.exception.SystemException; import org.infoglue.cms.util.CmsPropertyHandler; import org.infoglue.cms.util.NotificationListener; import org.infoglue.cms.util.NotificationMessage; import org.infoglue.deliver.util.CacheController; import org.infoglue.deliver.util.RequestAnalyser; import org.infoglue.deliver.util.Timer; import org.pdfbox.pdmodel.PDDocument; import org.pdfbox.util.PDFTextStripper; public class LuceneController extends BaseController implements NotificationListener { private static Directory directory = null; private static IndexWriter writer = null; private static IndexReader indexReader = null; private static int reopened = 0; private final static Logger logger = Logger.getLogger(LuceneController.class.getName()); private static int indexedDocumentsSinceLastOptimize = 0; private Integer lastCommitedContentVersionId = -1; private static Integer numberOfVersionToIndexInBatch = 1000; private static AtomicBoolean indexingInitialized = new AtomicBoolean(false); private static AtomicBoolean stopIndexing = new AtomicBoolean(false); private static AtomicBoolean deleteIndexOnStop = new AtomicBoolean(false); public static void setNumberOfVersionToIndexInBatch(Integer numberOfVersionToIndexInBatch) { numberOfVersionToIndexInBatch = numberOfVersionToIndexInBatch; } public static void stopIndexing() { stopIndexing.set(true); } /** * Default Constructor */ public static LuceneController getController() { return new LuceneController(); } private static List<NotificationMessage> qeuedMessages = new ArrayList<NotificationMessage>(); private StandardAnalyzer getStandardAnalyzer() throws Exception { return new StandardAnalyzer(Version.LUCENE_34); } private Directory getDirectory() throws Exception { if(LuceneController.directory != null) return directory; String index = CmsPropertyHandler.getContextDiskPath() + File.separator + "lucene" + File.separator + "index"; index = index.replaceAll("//", "/"); //System.out.println("index:" + index); File INDEX_DIR = new File(index); directory = new NIOFSDirectory(INDEX_DIR); directory.setLockFactory(new SingleInstanceLockFactory()); boolean indexExists = IndexReader.indexExists(directory); if(!indexExists) { createIndex(directory); } return directory; } private void createIndex(Directory directory) throws Exception { IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_34, getStandardAnalyzer()); IndexWriter indexWriter = new IndexWriter(directory, config); indexWriter.deleteDocuments(new Term("initializer", "true")); indexWriter.close(true); } private IndexWriter getIndexWriter() throws Exception { //Singleton returns if(writer != null) return writer; Timer t = new Timer(); Directory directory = getDirectory(); StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_34); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_34, analyzer); if(getIsIndexedLocked(true)) { logger.warn("Directory is locked - leaving the messages in the qeuedMessages list..."); throw new Exception("Lock not granted"); } else { writer = new IndexWriter(directory, config); return writer; } } private IndexReader getIndexReader() throws Exception { if(indexReader == null) { indexReader = IndexReader.open(getDirectory(), true); } synchronized (indexReader) { if(!indexReader.isCurrent()) { reopened++; indexReader.close(); indexReader = IndexReader.open(getDirectory(), true); //indexReader = IndexReader.openIfChanged(indexReader, true); logger.info("reopened:" + reopened); } } return indexReader; } private IndexSearcher getIndexSearcher() throws Exception { return new IndexSearcher(getIndexReader()); } private Boolean getIsIndexedLocked() throws Exception { return getIsIndexedLocked(false); } private Boolean getIsIndexedLocked(boolean returnIfFileLockException) throws Exception { Directory directory = getDirectory(); try { return IndexWriter.isLocked(directory); } catch (OverlappingFileLockException e) { return returnIfFileLockException; } } private void unlockIndex() throws Exception { Directory directory = getDirectory(); IndexWriter.unlock(directory); } public Map<String,Object> getIndexInformation() throws Exception { Map<String,Object> info = new HashMap<String,Object>(); try { Directory directory = getDirectory(); IndexReader reader = getIndexReader(); int maxDoc = reader.maxDoc(); int numDoc = reader.numDocs(); long lastModified = getIndexReader().lastModified(directory); info.put("maxDoc", new Integer(maxDoc)); info.put("numDoc", new Integer(numDoc)); info.put("lastModified", new Date(lastModified)); info.put("lastCommitedContentVersionId", getLastCommitedContentVersionId()); List<LanguageVO> languageVOList = LanguageController.getController().getLanguageVOList(); Iterator<LanguageVO> languageVOListIterator = languageVOList.iterator(); outer:while(languageVOListIterator.hasNext()) { LanguageVO languageVO = (LanguageVO)languageVOListIterator.next(); info.put("indexAllLastCommittedContentVersionId_" + languageVO.getId(), getIndexAllLastCommittedContentVersionId(languageVO.getId())); info.put("indexAllLastCommittedMetaContentVersionId_" + languageVO.getId(), getIndexAllLastCommittedMetaContentVersionId(languageVO.getId())); } //reader.close(); //directory.close(); } catch (Exception e) { logger.error("Error creating index:" + e.getMessage(), e); throw e; } return info; } public Integer getIndexAllLastCommittedContentVersionId(Integer languageId) throws Exception { Integer indexAllLastCommittedContentVersionId = null; try { Document indexAllDocumentMetaData = getIndexAllStatusDocument(); if(indexAllDocumentMetaData != null && indexAllDocumentMetaData.get("lastCommitedContentVersionId_" + languageId) != null && !indexAllDocumentMetaData.get("lastCommitedContentVersionId_" + languageId).equals("null")) indexAllLastCommittedContentVersionId = new Integer(indexAllDocumentMetaData.get("lastCommitedContentVersionId_" + languageId)); } catch (Exception e) { logger.error("Error creating index:" + e.getMessage(), e); throw e; } return indexAllLastCommittedContentVersionId; } public Integer getIndexAllLastCommittedMetaContentVersionId(Integer languageId) throws Exception { Integer indexAllLastCommittedSiteNodeVersionId = null; try { Document indexAllDocumentMetaData = getIndexAllStatusDocument(); if(indexAllDocumentMetaData != null && indexAllDocumentMetaData.get("lastCommitedMetaContentVersionId_" + languageId) != null && !indexAllDocumentMetaData.get("lastCommitedMetaContentVersionId_" + languageId).equals("null")) indexAllLastCommittedSiteNodeVersionId = new Integer(indexAllDocumentMetaData.get("lastCommitedMetaContentVersionId_" + languageId)); } catch (Exception e) { logger.error("Error creating index:" + e.getMessage(), e); throw e; } return indexAllLastCommittedSiteNodeVersionId; } public Document createStatusDocument(Integer lastCommitedContentVersionId) throws Exception { Document doc = new Document(); doc.add(new Field("lastCommitedContentVersionId", "" + lastCommitedContentVersionId, Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("lastCommitedModifiedDate", "" + new Date().getTime(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("meta", new StringReader("lastCommitedContentVersionId"))); return doc; } public Document getStatusDocument() throws Exception { List<Document> docs = queryDocuments("meta", "lastCommitedContentVersionId", 5); logger.info(docs.size() + " total matching documents for 'lastCommitedContentVersionId'"); return (docs != null && docs.size() > 0 ? docs.get(0) : null); } public Document getIndexAllStatusDocument() throws Exception { List<Document> docs = queryDocuments(new Term("meta", "indexAllRunning"), 5); logger.info(docs.size() + " total matching documents for 'indexAllRunning'"); return (docs != null && docs.size() > 0 ? docs.get(0) : null); } public Integer getLastCommitedContentVersionId() throws Exception { Integer lastCommitedContentVersionId = -1; Document doc = getStatusDocument(); logger.info("STATUS doc:" + doc); if(doc != null) { String lastCommitedContentVersionIdString = doc.get("lastCommitedContentVersionId"); logger.info("doc:" + doc); logger.info("lastCommitedContentVersionId:" + lastCommitedContentVersionIdString); lastCommitedContentVersionId = Integer.parseInt(lastCommitedContentVersionIdString); } return lastCommitedContentVersionId; } private void setLastCommitedContentVersionId(IndexWriter writer, Integer lastCommitedContentVersionId) throws Exception { Integer prevLastCommitedContentVersionId = getLastCommitedContentVersionId(); logger.info("prevLastCommitedContentVersionId:" + prevLastCommitedContentVersionId); logger.info("lastCommitedContentVersionId:" + lastCommitedContentVersionId); if(lastCommitedContentVersionId == -1 || prevLastCommitedContentVersionId > lastCommitedContentVersionId) return; logger.info("setLastCommitedContentVersionId:" + lastCommitedContentVersionId); Query query = new QueryParser(Version.LUCENE_34, "meta", getStandardAnalyzer()).parse("lastCommitedContentVersionId"); writer.deleteDocuments(query); writer.addDocument(createStatusDocument(lastCommitedContentVersionId)); } public Date getLastCommitedModifiedDate() throws Exception { Date lastCommitedModifiedDate = new Date(10000); Document doc = getStatusDocument(); if(doc != null) { String lastCommitedModifiedDateString = doc.get("lastCommitedModifiedDate"); logger.info("doc:" + doc); logger.info("lastCommitedModifiedDate:" + lastCommitedModifiedDateString); Date d = new Date(); d.setTime(Long.parseLong(lastCommitedModifiedDateString)); lastCommitedModifiedDate = d; } return lastCommitedModifiedDate; } private void registerIndexAllProcessOngoing(Integer lastCommitedContentVersionId, Integer lastCommitedSiteNodeVersionId, Integer languageId) throws Exception { //M�ste skrivas om f�r att uppdatera b�ttre.... //Document doc = new Document(); IndexWriter writer = getIndexWriter(); IndexSearcher searcher = getIndexSearcher(); Term term = new Term("meta", "indexAllRunning"); TermQuery query = new TermQuery(term); //Query query = new QueryParser(Version.LUCENE_34, "meta", getStandardAnalyzer()).parse("indexAllRunning"); TopDocs hits = searcher.search(query, 50); //System.out.println("hits:" + hits); //System.out.println("hits.scoreDocs.length:" + hits.scoreDocs.length); if(hits.scoreDocs.length > 1) System.out.println("Must be wrong - should only be one of these docs:" + hits.scoreDocs.length); if(hits.scoreDocs.length > 0) { for(ScoreDoc scoreDoc : hits.scoreDocs) { org.apache.lucene.document.Document docExisting = searcher.doc(scoreDoc.doc); //System.out.println("Updating doc...:" + docExisting); //System.out.println("lastCommitedContentVersionId:" + lastCommitedContentVersionId); //System.out.println("lastCommitedSiteNodeVersionId:" + lastCommitedSiteNodeVersionId); //System.out.println("languageId:" + languageId); if(lastCommitedContentVersionId != null && lastCommitedContentVersionId != -1) { docExisting.removeFields("lastCommitedContentVersionId_" + languageId); docExisting.add(new Field("lastCommitedContentVersionId_" + languageId, "" + lastCommitedContentVersionId, Field.Store.YES, Field.Index.NOT_ANALYZED)); } if(lastCommitedSiteNodeVersionId != null && lastCommitedSiteNodeVersionId != -1) { docExisting.removeFields("lastCommitedMetaContentVersionId_" + languageId); docExisting.add(new Field("lastCommitedMetaContentVersionId_" + languageId, "" + lastCommitedSiteNodeVersionId, Field.Store.YES, Field.Index.NOT_ANALYZED)); } docExisting.removeFields("lastCommitedModifiedDate"); docExisting.add(new Field("lastCommitedModifiedDate", "" + new Date().getTime(), Field.Store.YES, Field.Index.NOT_ANALYZED)); //docExisting.add(new Field("meta", new StringReader("indexAllRunning"))); //docExisting.add(new Field("meta", "indexAllRunning", Field.Store.YES, Field.Index.NOT_ANALYZED)); writer.updateDocument(term, docExisting); //System.out.println("Updating doc...:" + docExisting); //Term t = new Term("meta", "indexAllRunning"); break; } } else { Document docExisting = new Document(); //System.out.println("lastCommitedContentVersionId:" + lastCommitedContentVersionId); //System.out.println("lastCommitedSiteNodeVersionId:" + lastCommitedSiteNodeVersionId); //System.out.println("languageId:" + languageId); if(lastCommitedContentVersionId != null) docExisting.add(new Field("lastCommitedContentVersionId_" + languageId, "" + lastCommitedContentVersionId, Field.Store.YES, Field.Index.NOT_ANALYZED)); if(lastCommitedSiteNodeVersionId != null) docExisting.add(new Field("lastCommitedMetaContentVersionId_" + languageId, "" + lastCommitedSiteNodeVersionId, Field.Store.YES, Field.Index.NOT_ANALYZED)); docExisting.add(new Field("lastCommitedModifiedDate", "" + new Date().getTime(), Field.Store.YES, Field.Index.NOT_ANALYZED)); //docExisting.add(new Field("meta", new StringReader("indexAllRunning"))); docExisting.add(new Field("meta", "indexAllRunning", Field.Store.YES, Field.Index.NOT_ANALYZED)); writer.addDocument(docExisting); } searcher.close(); //Query query = new QueryParser(Version.LUCENE_34, "meta", getStandardAnalyzer()).parse("indexAllRunning"); //writer.deleteDocuments(query); //writer.updateDocument(term, doc); //writer.addDocument(doc); //writer.close(true); writer.commit(); } private void registerIndexAllProcessDone() throws Exception { IndexWriter writer = getIndexWriter(); //Query query = new QueryParser(Version.LUCENE_34, "meta", getStandardAnalyzer()).parse("indexAllRunning"); Term term = new Term("meta", "indexAllRunning"); TermQuery query = new TermQuery(term); writer.deleteDocuments(query); writer.commit(); } public void clearIndex() throws Exception { if (indexingInitialized.compareAndSet(false, true)) { logger.warn("Clearing index.."); try { logger.info("NumDocs:" + getIndexReader().numDocs()); IndexWriter writer = getIndexWriter(); writer.deleteAll(); //writer.close(true); writer.commit(); logger.info("NumDocs after delete:" + getIndexReader().numDocs()); } catch (Exception e) { stopIndexing.set(true); deleteIndexOnStop.set(true); logger.error("Error clearing index:" + e.getMessage(), e); } finally { logger.info("Releasing indexing flag"); this.indexingInitialized.set(false); stopIndexing.set(false); } } else { stopIndexing.set(true); deleteIndexOnStop.set(true); logger.error("Could not delete index while indexing. Queueing it...."); } } public TopDocs query(String text, Integer numberOfHits) throws Exception { return query("contents", text, numberOfHits); } public TopDocs query(String field, String text, Integer numberOfHits) throws Exception { IndexSearcher searcher = getIndexSearcher(); Query query = new QueryParser(Version.LUCENE_34, "contents", getStandardAnalyzer()).parse(text); TopDocs hits = searcher.search(query, numberOfHits); logger.info(hits.totalHits + " total matching documents for '" + text + "'"); return hits; } public List<Document> queryDocuments(Term term, Integer numberOfHits) throws Exception { IndexSearcher searcher = getIndexSearcher(); Query query = new TermQuery(term); TopDocs hits = searcher.search(query, numberOfHits); logger.info(hits.totalHits + " total matching documents for '" + term.field() + ":" + term.text() + "'"); List<Document> docs = new ArrayList<Document>(); for(ScoreDoc scoreDoc : hits.scoreDocs) { org.apache.lucene.document.Document doc = searcher.doc(scoreDoc.doc); docs.add(doc); } searcher.close(); return docs; } public List<Document> queryDocuments(String field, String text, Integer numberOfHits) throws Exception { IndexSearcher searcher = getIndexSearcher(); Query query = new QueryParser(Version.LUCENE_34, field, getStandardAnalyzer()).parse(text); logger.info("query:" + query); TopDocs hits = searcher.search(query, numberOfHits); logger.info(hits.totalHits + " total matching documents for '" + field + ":" + text + "'"); List<Document> docs = new ArrayList<Document>(); for(ScoreDoc scoreDoc : hits.scoreDocs) { org.apache.lucene.document.Document doc = searcher.doc(scoreDoc.doc); docs.add(doc); } searcher.close(); return docs; } public TopDocs query(String[] fields, BooleanClause.Occur[] flags, String[] queries, Sort sort, Integer numberOfHits) throws Exception { IndexSearcher searcher = getIndexSearcher(); Query query = MultiFieldQueryParser.parse(Version.LUCENE_34, queries, fields, flags, getStandardAnalyzer()); //Query query = new QueryParser(Version.LUCENE_34, "contents", getStandardAnalyzer()).parse(text); TopDocs hits = searcher.search(query, numberOfHits); logger.info(hits.totalHits + " total matching documents for '" + queries + "'"); return hits; } public List<Document> queryDocuments(String[] fields, BooleanClause.Occur[] flags, String[] queries, Sort sort, Integer numberOfHits, Map searchMetaData) throws Exception { IndexSearcher searcher = getIndexSearcher(); Query query = MultiFieldQueryParser.parse(Version.LUCENE_34, queries, fields, flags, getStandardAnalyzer()); logger.info("query:" + query); //Query query = new QueryParser(Version.LUCENE_34, "contents", getStandardAnalyzer()).parse(text); TopDocs hits = searcher.search(query, numberOfHits); searchMetaData.put("totalHits", hits.totalHits); logger.info(hits.totalHits + " total matching documents for '" + query + "'"); //System.out.println(hits.totalHits + " total matching documents for '" + queries + "'"); List<Document> docs = new ArrayList<Document>(); for(ScoreDoc scoreDoc : hits.scoreDocs) { org.apache.lucene.document.Document doc = searcher.doc(scoreDoc.doc); docs.add(doc); } searcher.close(); return docs; } private void query(IndexSearcher searcher, Analyzer analyzer, String text) throws Exception { Query query = new QueryParser(Version.LUCENE_34, "contents", analyzer).parse(text); TopDocs hits = searcher.search(query, 50); logger.info(hits.totalHits + " total matching documents for '" + text + "'"); for(ScoreDoc scoreDoc : hits.scoreDocs) { org.apache.lucene.document.Document doc = searcher.doc(scoreDoc.doc); String cvId = doc.get("contentVersionId"); logger.info("cvId: " + cvId); } } public boolean indexAll() throws Exception { if(!CmsPropertyHandler.getInternalSearchEngine().equalsIgnoreCase("lucene")) return false; logger.warn("INDEXING ALL - correct: " + indexingInitialized + "/" + deleteIndexOnStop + "/" + stopIndexing + "?"); Thread.currentThread().setPriority(Thread.MIN_PRIORITY); if(deleteIndexOnStop.get()) { clearIndex(); deleteIndexOnStop.set(false); stopIndexing.set(false); } else { stopIndexing.set(false); } logger.warn("Resetting stopIndexing to false...."); logger.warn("------------------------------Got indexAll directive...."); if (indexingInitialized.compareAndSet(false, true)) { //createTestIndex(); //indexingInitialized.set(false); //if(true) // return true; try { Timer t = new Timer(); Timer t2 = new Timer(); //Indexing all normal contents now logger.info("Indexing all normal contents: " + CmsPropertyHandler.getContextDiskPath()); List<LanguageVO> languageVOList = LanguageController.getController().getLanguageVOList(); Iterator<LanguageVO> languageVOListIterator = languageVOList.iterator(); outer:while(languageVOListIterator.hasNext()) { LanguageVO languageVO = (LanguageVO)languageVOListIterator.next(); logger.info("Getting notification messages for " + languageVO.getName()); Integer previousIndexAllLastContentVersionId = getIndexAllLastCommittedContentVersionId(languageVO.getId()); int startID = 0; if(previousIndexAllLastContentVersionId != null) startID = previousIndexAllLastContentVersionId; logger.info("Starting from " + startID); int newLastContentVersionId = getContentNotificationMessages(languageVO, startID); logger.info("newLastContentVersionId: " + newLastContentVersionId + " on " + languageVO.getName()); registerIndexAllProcessOngoing(newLastContentVersionId, null, languageVO.getId()); //previousIndexAllLastContentVersionId = newLastContentVersionId; RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getNotificationMessages", t.getElapsedTime()); logger.info("newLastContentVersionId " + newLastContentVersionId); while(newLastContentVersionId != -1) { logger.info("stopIndexing.get():" + stopIndexing.get()); if(stopIndexing.get()) break outer; Thread.sleep(5000); newLastContentVersionId = getContentNotificationMessages(languageVO, newLastContentVersionId); logger.info("newLastContentVersionId: " + newLastContentVersionId + " on " + languageVO.getName()); registerIndexAllProcessOngoing(newLastContentVersionId, null, languageVO.getId()); //previousIndexAllLastContentVersionId = newLastContentVersionId; RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getNotificationMessages 2", t.getElapsedTime()); logger.info("newLastContentVersionId " + newLastContentVersionId); } } languageVOList = LanguageController.getController().getLanguageVOList(); languageVOListIterator = languageVOList.iterator(); outer:while(languageVOListIterator.hasNext()) { LanguageVO languageVO = (LanguageVO)languageVOListIterator.next(); logger.info("languageVO from " + languageVO); List<NotificationMessage> notificationMessages = new ArrayList<NotificationMessage>(); Integer previousIndexAllLastMetaContentVersionId = getIndexAllLastCommittedMetaContentVersionId(languageVO.getId()); logger.info("previousIndexAllLastMetaContentVersionId: " + previousIndexAllLastMetaContentVersionId); int startID = 0; if(previousIndexAllLastMetaContentVersionId != null) startID = previousIndexAllLastMetaContentVersionId; logger.info("Starting from " + startID); int newLastMetaContentVersionId = getPageNotificationMessages(notificationMessages, languageVO, startID); logger.info("newLastSiteNodeVersionId " + newLastMetaContentVersionId + " on " + languageVO.getName()); logger.info("notificationMessages: " + notificationMessages.size()); registerIndexAllProcessOngoing(null, newLastMetaContentVersionId, languageVO.getId()); //previousIndexAllLastMetaContentVersionId = newLastMetaContentVersionId; RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getNotificationMessagesForStructure", t.getElapsedTime()); logger.info("newLastMetaContentVersionId " + newLastMetaContentVersionId); while(newLastMetaContentVersionId != -1) { logger.info("stopIndexing.get():" + stopIndexing.get()); if(stopIndexing.get()) break outer; Thread.sleep(5000); newLastMetaContentVersionId = getPageNotificationMessages(notificationMessages, languageVO, newLastMetaContentVersionId); logger.info("newLastMetaContentVersionId " + newLastMetaContentVersionId + " on " + languageVO.getName()); logger.info("notificationMessages: " + notificationMessages.size()); registerIndexAllProcessOngoing(null, newLastMetaContentVersionId, languageVO.getId()); //previousIndexAllLastMetaContentVersionId = newLastMetaContentVersionId; RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getNotificationMessages 2", t.getElapsedTime()); logger.info("newLastMetaContentVersionId " + newLastMetaContentVersionId); } } registerIndexAllProcessDone(); t2.printElapsedTime("All indexing took"); } catch (Exception e) { logger.error("Error indexing notifications:" + e.getMessage(), e); } finally { logger.error("Releasing indexing flag"); this.indexingInitialized.set(false); } } else { logger.warn("-------------------: Allready running index all..."); return false; } return true; } private void createTestIndex() { System.out.println("STARTING TEST"); try { clearIndex(); IndexWriter writer = getIndexWriter(); for(int i=0; i<10000; i++) { // make a new, empty document Document doc = new Document(); doc.add(new NumericField("publishDateTime", Field.Store.YES, true).setLongValue(23423423423L)); doc.add(new NumericField("modificationDateTime", Field.Store.YES, true).setLongValue(23423423423L)); doc.add(new Field("modified", DateTools.timeToString(23423423423L, DateTools.Resolution.MINUTE), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("contentVersionId", "324234234", Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("contentId", "324234234", Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("contentTypeDefinitionId", "344", Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("languageId", "33", Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("repositoryId", "22", Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("lastModifier", "Mattias Bogeblad", Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("stateId", "3", Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("isAsset", "false", Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("contents", new StringReader(i + " fwe foweif oiwejfoijweoifiweuhfi uehwiufh weiuhfiuwehfiew iufiuwehfi ewiufh iuwehfiuehwiufiweuhfiu ehwifhw eifew efiwehfiuwe" + "ff wehfiuehwiufiuwehfiuehw iufhwei uhfiehwiufweiuhf iwefihw eifiuwe ifhwe ifihew iufi weuhfiuwe" + "dfbsdjfsjdjfjksdf s f jdsjkfs dkjfh ksdfk sdkfhkds fksd " + "fjsd fsdhf uiweo p fiieowhf iehwiufiewhfiewfhw efn ewfowe ifioewf owehfowe"))); doc.add(new Field("uid", "" + i, Field.Store.NO, Field.Index.NOT_ANALYZED)); writer.addDocument(doc); if(i == 1000 || i == 2000 ||i == 3000 ||i == 4000 ||i == 5000 ||i == 6000 ||i == 7000 ||i == 8000 ||i == 9000) { //writer.optimize(); //writer.optimize(true); logger.info("Sleeping...:" + getIndexInformation().get("numDoc")); Thread.sleep(5000); } } //writer.close(true); writer.commit(); } catch (Exception e) { e.printStackTrace(); } } /** * This method gets called when a new notification has come. * It then iterates through the listeners and notifies them. */ public void addNotificationMessage(NotificationMessage notificationMessage) { if(notificationMessage.getClassName().equals(ContentImpl.class.getName()) || notificationMessage.getClassName().equals(ContentVersionImpl.class.getName()) || notificationMessage.getClassName().equals(SiteNodeImpl.class.getName()) || notificationMessage.getClassName().equals(SiteNodeVersionImpl.class.getName()) || notificationMessage.getClassName().equals(DigitalAssetImpl.class.getName()) || notificationMessage.getClassName().equals(MediumDigitalAssetImpl.class.getName())) { if(qeuedMessages.size() == 1000) { logger.warn("qeuedMessages went over 1000 - seems wrong"); Thread.dumpStack(); } synchronized (qeuedMessages) { qeuedMessages.add(notificationMessage); } } else { logger.info("Skipping indexing:" + notificationMessage.getClassName()); } } /** * This method gets called when a new NotificationMessage is available. * The writer just calls the transactionHistoryController which stores it. */ public void notify(NotificationMessage notificationMessage) { try { if(logger.isInfoEnabled()) logger.info("Indexing:" + notificationMessage.getName() + ":" + notificationMessage.getType() + ":" + notificationMessage.getObjectId() + ":" + notificationMessage.getObjectName()); addNotificationMessage(notificationMessage); } catch(Exception e) { logger.error("Error notifying: " + e.getMessage()); } } public void process() throws Exception { logger.info("Process inside LuceneController"); notifyListeners(false, true); } public void notifyListeners(boolean forceVersionIndexing, boolean checkForIndexingJobs) throws IOException, Exception { if(!CmsPropertyHandler.getInternalSearchEngine().equalsIgnoreCase("lucene") || CmsPropertyHandler.getContextDiskPath().contains("@deploy.dir")) return; boolean initDoneLocally = false; boolean finishDoneLocally = false; logger.info("------------------------------->notifyListeners before check in " + CmsPropertyHandler.getContextRootPath() + "/" + deleteIndexOnStop.get() + "/" + stopIndexing.get()); if(deleteIndexOnStop.get()) { clearIndex(); deleteIndexOnStop.set(false); stopIndexing.set(false); } else { stopIndexing.set(false); } if (!checkForIndexingJobs || indexingInitialized.compareAndSet(false, true)) { if(checkForIndexingJobs) initDoneLocally = true; List<NotificationMessage> internalMessageList = new ArrayList<NotificationMessage>(); synchronized (qeuedMessages) { //logger.error("internalMessageList: " + internalMessageList.size() + "/" + qeuedMessages.size()); internalMessageList.addAll(qeuedMessages); //logger.error("internalMessageList: " + internalMessageList.size() + "/" + qeuedMessages.size()); qeuedMessages.clear(); //logger.error("internalMessageList: " + internalMessageList.size() + "/" + qeuedMessages.size()); } //Should implement equals on NotificationMessage later List<NotificationMessage> baseEntitiesToIndexMessageList = new ArrayList<NotificationMessage>(); List<String> existingSignatures = new ArrayList<String>(); logger.info("Before AAAAA:" + internalMessageList.size() + ":" + existingSignatures.size()); Iterator<NotificationMessage> cleanupInternalMessageListIterator = internalMessageList.iterator(); while(cleanupInternalMessageListIterator.hasNext()) { NotificationMessage notificationMessage = cleanupInternalMessageListIterator.next(); logger.info("Indexing........:" + notificationMessage.getClassName()); if(notificationMessage.getClassName().equals(ContentImpl.class.getName()) || notificationMessage.getClassName().equals(Content.class.getName())) { ContentVO contentVO = ContentController.getContentController().getContentVOWithId((Integer)notificationMessage.getObjectId()); ContentTypeDefinitionVO ctdVO = null; try { ctdVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithId(contentVO.getContentTypeDefinitionId()); } catch (SystemException sex) { logger.warn("Failed to get the content type definition for content with Id: " + contentVO.getContentId() + ". The content will not be indexed. Message: " + sex.getMessage()); logger.info("Failed to get the content type definition for content with Id: " + contentVO.getContentId(), sex); } if(ctdVO != null && ctdVO.getName().equals("Meta info")) { SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithMetaInfoContentId(contentVO.getContentId()); NotificationMessage newNotificationMessage = new NotificationMessage("" + siteNodeVO.getName(), SiteNodeImpl.class.getName(), "SYSTEM", notificationMessage.getType(), siteNodeVO.getId(), "" + siteNodeVO.getName()); String key = "" + newNotificationMessage.getClassName() + "_" + newNotificationMessage.getObjectId() + "_" + "_" + newNotificationMessage.getType(); if(!existingSignatures.contains(key)) { logger.info("++++++++++++++Got an META PAGE notification - just adding it AS A PAGE instead: " + newNotificationMessage.getObjectId()); baseEntitiesToIndexMessageList.add(newNotificationMessage); existingSignatures.add(key); } else { logger.info("++++++++++++++Skipping Content notification - duplicate existed: " + notificationMessage.getObjectId()); } } else { String key = "" + notificationMessage.getClassName() + "_" + notificationMessage.getObjectId() + "_" + "_" + notificationMessage.getType(); if(!existingSignatures.contains(key)) { logger.info("++++++++++++++Got an Content notification - just adding it: " + notificationMessage.getObjectId()); baseEntitiesToIndexMessageList.add(notificationMessage); existingSignatures.add(key); } else { logger.info("++++++++++++++Skipping Content notification - duplicate existed: " + notificationMessage.getObjectId()); } } } else if(notificationMessage.getClassName().equals(ContentVersionImpl.class.getName()) || notificationMessage.getClassName().equals(ContentVersion.class.getName())) { logger.info("++++++++++++++Got an ContentVersion notification - focus on content: " + notificationMessage.getObjectId()); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getContentVersionVOWithId((Integer)notificationMessage.getObjectId()); ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentVersionVO.getContentId()); if(contentVO.getContentTypeDefinitionId() != null) { ContentTypeDefinitionVO ctdVO = null; try { ctdVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithId(contentVO.getContentTypeDefinitionId()); } catch (SystemException sex) { logger.warn("Failed to get the content type definition for content with Id: " + contentVO.getContentId() + ". The content version will not be indexed. Message: " + sex.getMessage()); logger.info("Failed to get the content type definition for content with Id: " + contentVO.getContentId(), sex); } if(ctdVO != null && ctdVO.getName().equals("Meta info")) { SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithMetaInfoContentId(contentVO.getContentId()); if (siteNodeVO == null) { logger.warn("Got meta info notification but could not find a page for the Content-id. Content.id: " + contentVO.getContentId()); } else { NotificationMessage newNotificationMessage = new NotificationMessage("" + siteNodeVO.getName(), SiteNodeImpl.class.getName(), "SYSTEM", notificationMessage.getType(), siteNodeVO.getId(), "" + siteNodeVO.getName()); String key = "" + newNotificationMessage.getClassName() + "_" + newNotificationMessage.getObjectId() + "_" + newNotificationMessage.getType(); if(!existingSignatures.contains(key)) { logger.info("++++++++++++++Got an META PAGE notification - just adding it AS A PAGE instead: " + newNotificationMessage.getObjectId()); baseEntitiesToIndexMessageList.add(newNotificationMessage); existingSignatures.add(key); } else { logger.info("++++++++++++++Skipping Content notification - duplicate existed: " + notificationMessage.getObjectId()); } } } else { NotificationMessage newNotificationMessage = new NotificationMessage("" + contentVersionVO.getContentName(), ContentImpl.class.getName(), "SYSTEM", notificationMessage.getType(), contentVersionVO.getContentId(), "" + contentVersionVO.getContentName()); String key = "" + newNotificationMessage.getClassName() + "_" + newNotificationMessage.getObjectId() + "_" + newNotificationMessage.getType(); if(!existingSignatures.contains(key)) { logger.info("++++++++++++++Got an Content notification - just adding it: " + newNotificationMessage.getObjectId()); baseEntitiesToIndexMessageList.add(newNotificationMessage); existingSignatures.add(key); } else { logger.info("++++++++++++++Skipping Content notification - duplicate existed: " + notificationMessage.getObjectId()); } } } } else if(notificationMessage.getClassName().equals(DigitalAssetImpl.class.getName()) || notificationMessage.getClassName().equals(MediumDigitalAssetImpl.class.getName()) || notificationMessage.getClassName().equals(DigitalAsset.class.getName()) || notificationMessage.getClassName().equals(SiteNodeImpl.class.getName()) || notificationMessage.getClassName().equals(SiteNode.class.getName()) || notificationMessage.getClassName().equals(SiteNodeVersionImpl.class.getName()) || notificationMessage.getClassName().equals(SiteNodeVersion.class.getName())) { logger.info("notificationMessage.getClassName():" + notificationMessage.getClassName()); String key = "" + notificationMessage.getClassName() + "_" + notificationMessage.getObjectId() + "_" + "_" + notificationMessage.getType(); if(notificationMessage.getClassName().equals(SiteNodeVersionImpl.class.getName()) || notificationMessage.getClassName().equals(SiteNodeVersion.class.getName())) { logger.info("PPPPPPPPPPPPPPPPPPPPPPPPPP:" + notificationMessage.getObjectId()); SiteNodeVersionVO siteNodeVersionVO = SiteNodeVersionController.getController().getSiteNodeVersionVOWithId((Integer)notificationMessage.getObjectId()); SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId(siteNodeVersionVO.getSiteNodeId()); NotificationMessage newNotificationMessage = new NotificationMessage("" + siteNodeVO.getName(), SiteNodeImpl.class.getName(), "SYSTEM", notificationMessage.getType(), siteNodeVO.getId(), "" + siteNodeVO.getName()); key = "" + newNotificationMessage.getClassName() + "_" + newNotificationMessage.getObjectId() + "_" + newNotificationMessage.getType(); if(!existingSignatures.contains(key)) { logger.info("++++++++++++++Got an SiteNodeVersionImpl notification - just adding it as SiteNodeImpl: " + newNotificationMessage.getClassName() + ":" + newNotificationMessage.getObjectId()); baseEntitiesToIndexMessageList.add(newNotificationMessage); existingSignatures.add(key); } else { logger.info("++++++++++++++Skipping notification - duplicate existed: " + notificationMessage.getClassName() + ":" + notificationMessage.getObjectId()); } } else if(notificationMessage.getClassName().equals(SiteNodeImpl.class.getName()) || notificationMessage.getClassName().equals(SiteNode.class.getName())) { if(!existingSignatures.contains(key)) { logger.info("++++++++++++++Got an Page notification - just adding it: " + notificationMessage.getClassName() + ":" + notificationMessage.getObjectId()); baseEntitiesToIndexMessageList.add(notificationMessage); existingSignatures.add(key); } else { logger.info("++++++++++++++Skipping notification - duplicate existed: " + notificationMessage.getClassName() + ":" + notificationMessage.getObjectId()); } } else { NotificationMessage newNotificationMessage = new NotificationMessage("" + notificationMessage.getName(), DigitalAssetImpl.class.getName(), "SYSTEM", notificationMessage.getType(), notificationMessage.getObjectId(), "" + notificationMessage.getName()); key = "" + newNotificationMessage.getClassName() + "_" + newNotificationMessage.getObjectId() + "_" + "_" + newNotificationMessage.getType(); if(!existingSignatures.contains(key)) { logger.info("++++++++++++++Got an Content notification - just adding it: " + notificationMessage.getClassName() + ":" + notificationMessage.getObjectId()); baseEntitiesToIndexMessageList.add(newNotificationMessage); existingSignatures.add(key); } else { logger.info("++++++++++++++Skipping notification - duplicate existed: " + notificationMessage.getClassName() + ":" + notificationMessage.getObjectId()); } } } } internalMessageList = baseEntitiesToIndexMessageList; logger.info("After in [" + CmsPropertyHandler.getContextRootPath() + "]:" + internalMessageList.size() + ":" + existingSignatures.size()); try { logger.info("notifyListeners actually running"); if(getIsIndexedLocked()) { logger.warn("The index should not be locked as no indexing is registered to be carried out. Lets unlock it as it may be the result of a crash."); unlockIndex(); } //logger.error("Starting indexin of " + qeuedMessages.size()); Timer t = new Timer(); IndexWriter writer = getIndexWriter(); //t.printElapsedTime("Creating writer took"); Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { int numberOfMessages = internalMessageList.size(); Iterator internalMessageListIterator = internalMessageList.iterator(); while(internalMessageListIterator.hasNext()) { NotificationMessage notificationMessage = (NotificationMessage)internalMessageListIterator.next(); try { if(logger.isInfoEnabled()) logger.info("Starting indexin of " + notificationMessage); indexInformation(notificationMessage, writer, internalMessageList, forceVersionIndexing, db); internalMessageListIterator.remove(); } catch (Exception e) { e.printStackTrace(); } } //t.printElapsedTime("Indexing " + numberOfMessages + " documents took"); //Map<String,String> commitUserData = new HashMap<String,String>(); //internalMessageList.clear(); //writer.commit(commitUserData); logger.info("##############lastCommitedContentVersionId before close:" + lastCommitedContentVersionId); if(lastCommitedContentVersionId > -1) { Integer previousLastCommittedContentVersionId = getLastCommitedContentVersionId(); logger.info("##############previousLastCommittedContentVersionId before close:" + previousLastCommittedContentVersionId); if(previousLastCommittedContentVersionId < lastCommitedContentVersionId) { try { logger.info("*************ADDING status doc " + lastCommitedContentVersionId + "**************"); setLastCommitedContentVersionId(writer, lastCommitedContentVersionId); } catch (Exception e) { logger.error("*************ERROR: ADDING status doc**************", e); } } else { logger.warn("The content version was not a higher number than what was allready indexed - lets not add status...."); } } commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e.getMessage(), e); rollbackTransaction(db); } finally { writer.commit(); //writer.close(true); } logger.info("OOOOOOOOOOOOOO:" + getLastCommitedContentVersionId()); } catch (Exception e) { logger.error("Error indexing notifications:" + e.getMessage()); logger.warn("Error indexing notifications:" + e.getMessage(), e); } finally { logger.info("Releasing indexing flag"); try { if(internalMessageList.size() > 0) { synchronized (qeuedMessages) { logger.info("Returning internalMessageList:" + internalMessageList.size() + " to qeuedMessages as some failed."); qeuedMessages.addAll(internalMessageList); internalMessageList.clear(); } } } catch (Exception e) { e.printStackTrace(); } if(checkForIndexingJobs) { this.indexingInitialized.set(false); finishDoneLocally = true; } } if(initDoneLocally && !finishDoneLocally) logger.error("EEEEEEEEEEEEEEERRRRRRRRRRRRRRROOOOOOOOOOOORRRRRRRR aaaaaaa"); logger.info("internalMessageList 1:" + internalMessageList.size() + " / " + qeuedMessages.size()); } else { logger.info("------------------------------->Indexing job allready running... skipping in " + CmsPropertyHandler.getContextRootPath()); } logger.info("queued messages 1:" + qeuedMessages.size()); } public void index() throws Exception { if(!CmsPropertyHandler.getInternalSearchEngine().equalsIgnoreCase("lucene")) return; logger.info("Start index: " + CmsPropertyHandler.getContextRootPath() + "/" + deleteIndexOnStop.get() + "/" + stopIndexing.get()); if(deleteIndexOnStop.get()) { clearIndex(); deleteIndexOnStop.set(false); stopIndexing.set(false); } else { stopIndexing.set(false); } logger.info("################# starting index"); //if (indexStarted.compareAndSet(false, true)) //{ IndexReader indexReader = null; try { Integer lastCommitedContentVersionId = getLastCommitedContentVersionId(); Document indexAllDocumentMetaData = getIndexAllStatusDocument(); //Integer previousIndexAllLastContentVersionId = getIndexAllLastCommittedContentVersionId(); logger.info("lastCommitedContentVersionId:" + lastCommitedContentVersionId); Date lastCommitedModifiedDate = getLastCommitedModifiedDate(); Calendar yesterday = Calendar.getInstance(); yesterday.add(Calendar.HOUR_OF_DAY, -1); logger.info("lastCommitedContentVersionId: " + lastCommitedContentVersionId); logger.info("lastCommitedModifiedDate: " + lastCommitedModifiedDate); indexReader = getIndexReader(); boolean didIndex = false; if(lastCommitedContentVersionId == -1 || indexAllDocumentMetaData != null || indexReader.numDocs() < 100) { logger.info("indexAll as it seemed to be not ready....."); logger.info("###########################IndexAll"); didIndex = indexAll(); } else //Skipping indexing for now.. { logger.info("###########################indexIncremental"); didIndex = indexIncremental(lastCommitedContentVersionId, yesterday.getTime()); } if(didIndex) { CacheController.clearCache("pageCache"); CacheController.clearCache("pageCacheExtra"); } } catch (Exception e) { logger.error("Error indexing notifications:" + e.getMessage()); logger.warn("Error indexing notifications:" + e.getMessage(), e); } /* } else { logger.error("################# skipping index, was allready started"); } */ } public boolean indexIncremental(Integer lastCommitedContentVersionId, Date lastCommitedDateTime) throws Exception { if(!CmsPropertyHandler.getInternalSearchEngine().equalsIgnoreCase("lucene")) return false; Timer t = new Timer(); Timer t2 = new Timer(); logger.info("Indexing incremental:" + lastCommitedContentVersionId + "/" + lastCommitedDateTime); //Map<String,String> lastCommitData = reader.getCommitUserData(); List<LanguageVO> languageVOList = LanguageController.getController().getLanguageVOList(); Iterator<LanguageVO> languageVOListIterator = languageVOList.iterator(); outer:while(languageVOListIterator.hasNext()) { LanguageVO languageVO = (LanguageVO)languageVOListIterator.next(); List<NotificationMessage> notificationMessages = new ArrayList<NotificationMessage>(); //logger.error("Getting notification messages for " + languageVO.getName()); int newLastContentVersionId = getNotificationMessages(notificationMessages, languageVO, lastCommitedContentVersionId, lastCommitedDateTime, 1000); while(newLastContentVersionId != -1) { Thread.sleep(5000); if(stopIndexing.get()) break outer; logger.info("Queueing " + notificationMessages.size() + " notificationMessages for indexing"); for(NotificationMessage notificationMessage : notificationMessages) { notify(notificationMessage); } notifyListeners(true, false); notificationMessages.clear(); //t.printElapsedTime("Indexing size():" + notificationMessages.size() + " took"); Integer newLastContentVersionIdCandidate = getNotificationMessages(notificationMessages, languageVO, newLastContentVersionId, lastCommitedDateTime, 1000); logger.info("newLastContentVersionIdCandidate:" + newLastContentVersionIdCandidate + "=" + newLastContentVersionId); if(newLastContentVersionIdCandidate > newLastContentVersionId) newLastContentVersionId = newLastContentVersionIdCandidate; else break; //t.printElapsedTime("newLastContentVersionId:" + newLastContentVersionId + " took"); } } if(logger.isInfoEnabled()) t2.printElapsedTime("All indexing took"); return true; } private int getNotificationMessagesForStructure(List<NotificationMessage> notificationMessages, LanguageVO languageVO, int lastSiteNodeVersionId) throws Exception { Timer t = new Timer(); logger.info("getNotificationMessages:" + lastSiteNodeVersionId); int newLastSiteNodeVersionId = -1; Database db = CastorDatabaseService.getDatabase(); try { beginTransaction(db); ContentTypeDefinitionVO contentTypeDefinitionVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName("Meta info", db); ContentVersionVO lastContentVersionVO = ContentVersionController.getContentVersionController().getLatestContentVersionVO(languageVO.getId(), db); Integer maxContentVersionId = (lastContentVersionVO == null ? 1000 : lastContentVersionVO.getId()); logger.info("maxContentVersionId:" + maxContentVersionId + " for " + languageVO.getName()); List<ContentVersionVO> versions = new ArrayList<ContentVersionVO>(); if(CmsPropertyHandler.getApplicationName().equalsIgnoreCase("cms")) { versions = ContentVersionController.getContentVersionController().getContentVersionVOList(contentTypeDefinitionVO.getId(), null, languageVO.getId(), false, 0, newLastSiteNodeVersionId, numberOfVersionToIndexInBatch, numberOfVersionToIndexInBatch*10, true, db, true, maxContentVersionId); } else { versions = ContentVersionController.getContentVersionController().getContentVersionVOList(contentTypeDefinitionVO.getId(), null, languageVO.getId(), false, Integer.parseInt(CmsPropertyHandler.getOperatingMode()), newLastSiteNodeVersionId, numberOfVersionToIndexInBatch, numberOfVersionToIndexInBatch*10, true, db, true, maxContentVersionId); } RequestAnalyser.getRequestAnalyser().registerComponentStatistics("Index all : getContentVersionVOList", t.getElapsedTime()); logger.info("versions in getNotificationMessagesForStructure:" + versions.size()); logger.info("Looping versions:" + versions.size()); for(ContentVersionVO version : versions) { NotificationMessage notificationMessage = new NotificationMessage("LuceneController", ContentVersionImpl.class.getName(), "SYSTEM", NotificationMessage.TRANS_UPDATE, version.getId(), "dummy"); notificationMessages.add(notificationMessage); newLastSiteNodeVersionId = version.getId().intValue(); } logger.info("Finished round 1:" + notificationMessages.size() + ":" + newLastSiteNodeVersionId); } catch ( Exception e ) { rollbackTransaction(db); throw new SystemException("An error occurred when we tried to fetch a list of users in this role. Reason:" + e.getMessage(), e); } commitTransaction(db); return newLastSiteNodeVersionId; } private int getContentNotificationMessages(LanguageVO languageVO, int lastContentVersionId) throws Exception { Timer t = new Timer(); logger.info("getNotificationMessages:" + languageVO.getName() + " : " + lastContentVersionId); logger.info("notifyListeners actually running"); if(getIsIndexedLocked()) { logger.info("The index should not be locked as no indexing is registered to be carried out. Lets unlock it as it may be the result of a crash."); unlockIndex(); } IndexWriter writer = getIndexWriter(); //t.printElapsedTime("Creating writer took"); int newLastContentVersionId = -1; Database db = CastorDatabaseService.getDatabase(); try { beginTransaction(db); logger.info("lastContentVersionId:" + lastContentVersionId); if(lastContentVersionId < 1) { SmallestContentVersionVO firstContentVersionVO = ContentVersionController.getContentVersionController().getFirstContentVersionId(languageVO.getId(), db); if(firstContentVersionVO != null) lastContentVersionId = firstContentVersionVO.getId(); } logger.info("lastContentVersionId 2:" + lastContentVersionId); ContentTypeDefinitionVO contentTypeDefinitionVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName("Meta info", db); ContentVersionVO lastContentVersionVO = ContentVersionController.getContentVersionController().getLatestContentVersionVO(languageVO.getId(), db); Integer maxContentVersionId = (lastContentVersionVO == null ? 1000 : lastContentVersionVO.getId()); logger.info("maxContentVersionId 1:" + maxContentVersionId + " for " + languageVO.getName()); List<ContentVersionVO> versions = new ArrayList<ContentVersionVO>(); if(CmsPropertyHandler.getApplicationName().equalsIgnoreCase("cms")) { versions = ContentVersionController.getContentVersionController().getContentVersionVOList(null, contentTypeDefinitionVO.getId(), languageVO.getId(), false, 0, lastContentVersionId, numberOfVersionToIndexInBatch, numberOfVersionToIndexInBatch*10, true, db, false, maxContentVersionId); } else { versions = ContentVersionController.getContentVersionController().getContentVersionVOList(null, contentTypeDefinitionVO.getId(), languageVO.getId(), false, Integer.parseInt(CmsPropertyHandler.getOperatingMode()), lastContentVersionId, numberOfVersionToIndexInBatch, numberOfVersionToIndexInBatch*10, true, db, false, maxContentVersionId); } RequestAnalyser.getRequestAnalyser().registerComponentStatistics("Index all : getContentVersionVOList", t.getElapsedTime()); logger.info("versions in getContentNotificationMessages:" + versions.size()); logger.info("Looping versions:" + versions.size()); for(ContentVersionVO version : versions) { if(stopIndexing.get()) return newLastContentVersionId; Document document = getDocumentFromContentVersion(version, db); String uid = document.get("uid"); logger.info("document: " + document); writer.deleteDocuments(new Term("uid", "" + uid)); if(logger.isDebugEnabled()) logger.debug("Adding document with uid:" + uid + " - " + document); if(document != null) writer.addDocument(document); logger.info("version assetCount:" + version.getAssetCount()); if(version.getAssetCount() == null || version.getAssetCount() > 0) { List digitalAssetVOList = DigitalAssetController.getDigitalAssetVOList(version.getId(), db); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getDigitalAssetVOList", (t.getElapsedTimeNanos() / 1000)); if(digitalAssetVOList.size() > 0) { logger.info("digitalAssetVOList:" + digitalAssetVOList.size()); Iterator digitalAssetVOListIterator = digitalAssetVOList.iterator(); while(digitalAssetVOListIterator.hasNext()) { DigitalAssetVO assetVO = (DigitalAssetVO)digitalAssetVOListIterator.next(); Document assetDocument = getDocumentFromDigitalAsset(assetVO, version, db); String assetUid = assetDocument.get("uid"); writer.deleteDocuments(new Term("uid", "" + assetUid)); if(logger.isDebugEnabled()) logger.debug("Adding document with assetUid:" + assetUid + " - " + assetDocument); if(assetDocument != null) writer.addDocument(assetDocument); } } } newLastContentVersionId = version.getId().intValue(); } //logger.info("Finished round 2:" + notificationMessages.size() + ":" + newLastContentVersionId); } catch ( Exception e ) { logger.error("Error in lucene indexing: " + e.getMessage(), e); rollbackTransaction(db); throw new SystemException("An error occurred when we tried to getContentNotificationMessages. Reason:" + e.getMessage(), e); } finally { try{setLastCommitedContentVersionId(writer, newLastContentVersionId); writer.commit(); /*writer.close(true);*/}catch (Exception e) {e.printStackTrace();} } commitTransaction(db); return newLastContentVersionId; } private int getPageNotificationMessages(List notificationMessages, LanguageVO languageVO, int lastContentVersionId) throws Exception { Timer t = new Timer(); logger.info("getNotificationMessages:" + languageVO.getName() + " : " + lastContentVersionId); logger.info("notifyListeners actually running"); if(getIsIndexedLocked()) { logger.info("The index should not be locked as no indexing is registered to be carried out. Lets unlock it as it may be the result of a crash."); unlockIndex(); } IndexWriter writer = getIndexWriter(); //t.printElapsedTime("Creating writer took"); int newLastContentVersionId = -1; Database db = CastorDatabaseService.getDatabase(); try { beginTransaction(db); ContentTypeDefinitionVO contentTypeDefinitionVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName("Meta info", db); ContentVersionVO lastContentVersionVO = ContentVersionController.getContentVersionController().getLatestContentVersionVO(languageVO.getId(), db); Integer maxContentVersionId = (lastContentVersionVO == null ? 1000 : lastContentVersionVO.getId()); logger.info("maxContentVersionId:" + maxContentVersionId + " for " + languageVO.getName()); List<ContentVersionVO> versions = new ArrayList<ContentVersionVO>(); if(CmsPropertyHandler.getApplicationName().equalsIgnoreCase("cms")) { versions = ContentVersionController.getContentVersionController().getContentVersionVOList(contentTypeDefinitionVO.getId(), null, languageVO.getId(), false, 0, lastContentVersionId, numberOfVersionToIndexInBatch, numberOfVersionToIndexInBatch*10, true, db, true, maxContentVersionId); } else { versions = ContentVersionController.getContentVersionController().getContentVersionVOList(contentTypeDefinitionVO.getId(), null, languageVO.getId(), false, Integer.parseInt(CmsPropertyHandler.getOperatingMode()), lastContentVersionId, numberOfVersionToIndexInBatch, numberOfVersionToIndexInBatch*10, true, db, true, maxContentVersionId); } logger.info("versions:" + versions.size()); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("Index all : getContentVersionVOList", t.getElapsedTime()); logger.info("versions in getContentNotificationMessages:" + versions.size()); logger.info("Looping versions:" + versions.size()); for(ContentVersionVO version : versions) { if(stopIndexing.get()) return newLastContentVersionId; Document documents = getSiteNodeDocument(version, writer, db); if (documents != null) { String uid = documents.get("uid"); logger.debug("Regging doc: " + documents); writer.deleteDocuments(new Term("uid", "" + uid)); if(logger.isDebugEnabled()) logger.debug("Adding document with uid:" + uid + " - " + documents); writer.addDocument(documents); } else if(logger.isInfoEnabled()) { logger.info("Failed to get document for SiteNode. Meta info content.id: " + version.getContentVersionId()); } /* logger.info("version assetCount:" + version.getAssetCount()); if(version.getAssetCount() == null || version.getAssetCount() > 0) { List digitalAssetVOList = DigitalAssetController.getDigitalAssetVOList(version.getId(), db); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getDigitalAssetVOList", (t.getElapsedTimeNanos() / 1000)); if(digitalAssetVOList.size() > 0) { logger.info("digitalAssetVOList:" + digitalAssetVOList.size()); Iterator digitalAssetVOListIterator = digitalAssetVOList.iterator(); while(digitalAssetVOListIterator.hasNext()) { DigitalAssetVO assetVO = (DigitalAssetVO)digitalAssetVOListIterator.next(); NotificationMessage assetNotificationMessage = new NotificationMessage("LuceneController", DigitalAssetImpl.class.getName(), "SYSTEM", NotificationMessage.TRANS_UPDATE, assetVO.getId(), "dummy"); notificationMessages.add(assetNotificationMessage); } } } NotificationMessage notificationMessage = new NotificationMessage("LuceneController", ContentVersionImpl.class.getName(), "SYSTEM", NotificationMessage.TRANS_UPDATE, version.getId(), "dummy"); notificationMessages.add(notificationMessage); */ newLastContentVersionId = version.getId().intValue(); } logger.info("Finished round 3:" + notificationMessages.size() + ":" + newLastContentVersionId); } catch ( Exception e ) { rollbackTransaction(db); throw new SystemException("An error occurred when we tried to fetch a list of users in this role. Reason:" + e.getMessage(), e); } finally { try{setLastCommitedContentVersionId(writer, newLastContentVersionId); writer.commit(); /*writer.close(true);*/}catch (Exception e) {e.printStackTrace();} } commitTransaction(db); return newLastContentVersionId; } public void testSQL() { try { getNotificationMessages(new ArrayList(), LanguageController.getController().getLanguageVOWithCode("sv"), 100000, new Date(), 1000); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); logger.error("Errro:" + e.getMessage(), e); } } private int getNotificationMessages(List notificationMessages, LanguageVO languageVO, int lastContentVersionId, Date lastCheckDateTime, int batchSize) throws Exception { Timer t = new Timer(); logger.info("getNotificationMessages:" + languageVO.getName() + " : " + lastContentVersionId + ":" + lastCheckDateTime); int newLastContentVersionId = -1; Database db = CastorDatabaseService.getDatabase(); try { beginTransaction(db); logger.info("**************Getting contents start:" + t.getElapsedTime() + ":" + lastCheckDateTime); Calendar date = Calendar.getInstance(); date.setTime(lastCheckDateTime); date.add(Calendar.DAY_OF_YEAR, -1); //String SQL = "select cv.contentVersionId, cv.stateId, cv.modifiedDateTime, cv.versionComment, cv.isCheckedOut, cv.isActive, cv.contentId, cv.languageId, cv.versionModifier FROM cmContentVersion cv where cv.languageId = $1 AND cv.isActive = $2 AND ((cv.contentVersionId > $3 AND cv.contentVersionId < $4) OR cv.modifiedDateTime > $5) ORDER BY cv.contentVersionId"; //if(CmsPropertyHandler.getUseShortTableNames() != null && CmsPropertyHandler.getUseShortTableNames().equalsIgnoreCase("true")) // SQL = "select cv.contVerId, cv.stateId, cv.modifiedDateTime, cv.verComment, cv.isCheckedOut, cv.isActive, cv.contId, cv.languageId, cv.versionModifier FROM cmContVer cv where cv.languageId = $1 AND cv.isActive = $2 AND ((cv.contVerId > $3 AND cv.contVerId < $4) OR cv.modifiedDateTime > TO_DATE('2013-03-20','YYYY-MM-DD')) ORDER BY cv.contVerId"; //System.out.println("SQL:" + SQL); //OQLQuery oql = db.getOQLQuery("CALL SQL " + SQL + " AS org.infoglue.cms.entities.content.impl.simple.SmallestContentVersionImpl"); //if(CmsPropertyHandler.getUseShortTableNames() != null && CmsPropertyHandler.getUseShortTableNames().equalsIgnoreCase("true")) // oql = db.getOQLQuery("CALL SQL " + SQL + " AS org.infoglue.cms.entities.content.impl.simple.SmallestContentVersionImpl"); //oracle.sql.DATE oracleDate = new oracle.sql.DATE(new java.sql.Date(date.getTime().getTime())); OQLQuery oql = db.getOQLQuery( "SELECT cv FROM " + SmallestContentVersionImpl.class.getName() + " cv WHERE cv.languageId = $1 AND cv.isActive = $2 AND ((cv.contentVersionId > $3 AND cv.contentVersionId < $4) OR cv.modifiedDateTime > $5) ORDER BY cv.contentVersionId limit $6"); //OQLQuery oql = db.getOQLQuery( "SELECT cv FROM " + SmallestContentVersionImpl.class.getName() + " cv WHERE cv.languageId = $1 AND cv.isActive = $2 AND ((cv.contentVersionId > $3 AND cv.contentVersionId < $4)) ORDER BY cv.contentVersionId limit $5"); oql.bind(languageVO.getId()); oql.bind(true); oql.bind(lastContentVersionId); oql.bind(lastContentVersionId+(batchSize*10)); //oql.bind(date.getTime()); oql.bind(date.getTime()); oql.bind(batchSize); QueryResults results = oql.execute(Database.ReadOnly); if(logger.isInfoEnabled()) logger.info("Getting contents took: " + t.getElapsedTime()); int processedItems = 0; Integer previousContentId = null; while (results.hasMore()) { SmallestContentVersionImpl smallestContentVersionImpl = (SmallestContentVersionImpl)results.next(); if(previousContentId == null || !previousContentId.equals(smallestContentVersionImpl.getContentId())) { List digitalAssetVOList = DigitalAssetController.getDigitalAssetVOList(smallestContentVersionImpl.getId(), db); if(digitalAssetVOList.size() > 0) { logger.info("digitalAssetVOList:" + digitalAssetVOList.size()); Iterator digitalAssetVOListIterator = digitalAssetVOList.iterator(); while(digitalAssetVOListIterator.hasNext()) { DigitalAssetVO assetVO = (DigitalAssetVO)digitalAssetVOListIterator.next(); if(assetVO.getAssetFileSize() < 10000000) //Do not index large files { NotificationMessage assetNotificationMessage = new NotificationMessage("LuceneController", DigitalAssetImpl.class.getName(), "SYSTEM", NotificationMessage.TRANS_UPDATE, assetVO.getId(), "dummy"); notificationMessages.add(assetNotificationMessage); } } } NotificationMessage notificationMessage = new NotificationMessage("LuceneController", ContentVersionImpl.class.getName(), "SYSTEM", NotificationMessage.TRANS_UPDATE, smallestContentVersionImpl.getId(), "dummy"); notificationMessages.add(notificationMessage); previousContentId = smallestContentVersionImpl.getContentId(); } newLastContentVersionId = smallestContentVersionImpl.getId().intValue(); lastCommitedContentVersionId = newLastContentVersionId; processedItems++; logger.info("previousContentId:" + previousContentId + "/" + processedItems); if(processedItems > batchSize) { System.out.println("Batch full..."); break; } } results.close(); logger.info("Finished round 4:" + processedItems + ":" + newLastContentVersionId); } catch ( Exception e ) { rollbackTransaction(db); throw new SystemException("An error occurred when we tried to fetch a list of users in this role. Reason:" + e.getMessage(), e); } commitTransaction(db); return newLastContentVersionId; } private void indexInformation(NotificationMessage notificationMessage, IndexWriter writer, List<NotificationMessage> internalMessageList, Boolean forceVersionIndexing, Database db) { Timer t = new Timer(); try { try { //writer.setMaxMergeDocs(500000); if(logger.isInfoEnabled()) logger.info("Indexing to directory '" + writer.getDirectory().toString() + "'..."); List<Document> documents = getDocumentsForIncremental(notificationMessage, writer, forceVersionIndexing, db); Iterator<Document> documentsIterator = documents.iterator(); while(documentsIterator.hasNext()) { Document indexingDocument = documentsIterator.next(); String uid = indexingDocument.get("uid"); if(logger.isDebugEnabled()) logger.debug("Adding document with uid:" + uid + " - " + indexingDocument); //logger.error("Adding document with uid:" + uid + " - " + indexingDocument); if(indexingDocument != null) writer.addDocument(indexingDocument); } } catch (Exception e) { logger.error("Error indexing:" + e.getMessage(), e); } finally { indexedDocumentsSinceLastOptimize++; if(indexedDocumentsSinceLastOptimize > 1000) { indexedDocumentsSinceLastOptimize = 0; } } } catch (Exception e) { logger.error("Error indexing:" + e.getMessage(), e); } } private List<Document> getDocumentsForIncremental(NotificationMessage notificationMessage, IndexWriter writer, Boolean forceVersionIndexing, Database db) throws Exception { Timer t = new Timer(); List<Document> returnDocuments = new ArrayList<Document>(); logger.info("2222222222 notificationMessage.getClassName():" + notificationMessage.getClassName() + " in " + CmsPropertyHandler.getApplicationName()); Set<Integer> contentIdsToIndex = new HashSet<Integer>(); Set<Integer> siteNodeIdsToIndex = new HashSet<Integer>(); if(notificationMessage.getClassName().equals(ContentImpl.class.getName()) || notificationMessage.getClassName().equals(Content.class.getName())) { logger.info("++++++++++++++Got an Content notification: " + notificationMessage.getObjectId()); ContentVO contentVO = ContentController.getContentController().getContentVOWithId((Integer)notificationMessage.getObjectId(), db); //ContentVO contentVO = ContentController.getContentController().getContentVOWithId((Integer)notificationMessage.getObjectId()); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getContentVOWithId", (t.getElapsedTimeNanos() / 1000)); contentIdsToIndex.add(contentVO.getId()); } else if(notificationMessage.getClassName().equals(ContentVersionImpl.class.getName()) || notificationMessage.getClassName().equals(ContentVersion.class.getName())) { logger.info("++++++++++++++Got an ContentVersion notification: " + notificationMessage.getObjectId()); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getContentVersionVOWithId((Integer)notificationMessage.getObjectId(), db); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getContentVersionVOWithId", t.getElapsedTime()); contentIdsToIndex.add(contentVersionVO.getContentId()); } else if(notificationMessage.getClassName().equals(DigitalAssetImpl.class.getName()) || notificationMessage.getClassName().equals(DigitalAsset.class.getName())) { logger.info("++++++++++++++Got an DigitalAssetImpl notification: " + notificationMessage.getObjectId()); Database db2 = CastorDatabaseService.getDatabase(); beginTransaction(db2); try { DigitalAssetVO asset = DigitalAssetController.getSmallDigitalAssetVOWithId((Integer)notificationMessage.getObjectId(), db2); //MediumDigitalAssetImpl asset = (MediumDigitalAssetImpl)DigitalAssetController.getMediumDigitalAssetWithIdReadOnly((Integer)notificationMessage.getObjectId(), db2); //RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getMediumDigitalAssetWithIdReadOnly", t.getElapsedTime()); //Collection contentVersions = asset.getContentVersions(); List<SmallestContentVersionVO> contentVersionVOList = DigitalAssetController.getContentVersionVOListConnectedToAssetWithId((Integer)notificationMessage.getObjectId()); if(logger.isInfoEnabled()) logger.info("contentVersionVOList:" + contentVersionVOList.size()); Iterator<SmallestContentVersionVO> contentVersionsIterator = contentVersionVOList.iterator(); while(contentVersionsIterator.hasNext()) { SmallestContentVersionVO version = contentVersionsIterator.next(); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("contentVersionsIterator", t.getElapsedTime()); ContentVersionVO cvVO = ContentVersionController.getContentVersionController().getContentVersionVOWithId(version.getId(), db2); Document document = getDocumentFromDigitalAsset(asset, cvVO, db); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getDocumentFromDigitalAsset", t.getElapsedTime()); logger.info("00000000000000000: Adding asset document:" + document); if(document != null) returnDocuments.add(document); } commitTransaction(db2); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db2); throw new SystemException(e.getMessage()); } } else if(notificationMessage.getClassName().equals(SiteNodeImpl.class.getName()) || notificationMessage.getClassName().equals(SiteNode.class.getName())) { SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId((Integer)notificationMessage.getObjectId(), db); if (siteNodeVO == null) { logger.warn("Could not find SiteNode with id: " + notificationMessage.getObjectId()); } else { siteNodeIdsToIndex.add(siteNodeVO.getId()); } } logger.info("Indexing:" + siteNodeIdsToIndex.size()); for(Integer siteNodeId : siteNodeIdsToIndex) { //Deleting all info based on content Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_34); logger.info("Deleting all info on:" + siteNodeId); //TODO - Fixa sŒ inte assets tas med hŠr.... Query query = new QueryParser(Version.LUCENE_34, "siteNodeId", analyzer).parse("" + siteNodeId); writer.deleteDocuments(query); //End logger.info("QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ:" + notificationMessage.getObjectId()); SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId((Integer)notificationMessage.getObjectId(), db); logger.info("$$$$$$$$$$Getting doc for " + siteNodeVO.getName()); Document document = getDocumentFromSiteNode(siteNodeVO, writer, db); logger.info("document " + document); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getDocumentFromSiteNode", t.getElapsedTime()); if(document != null) returnDocuments.add(document); } logger.info("Indexing contentIdsToIndex:" + contentIdsToIndex.size()); for(Integer contentId : contentIdsToIndex) { //Deleting all info based on content Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_34); logger.info("Deleting all info on:" + contentId); //TODO - Fixa sŒ inte assets tas med hŠr.... String[] fields = new String[]{"isAsset","contentId"}; String[] queries = new String[]{"true","" + contentId}; BooleanClause.Occur[] flags = new BooleanClause.Occur[]{BooleanClause.Occur.MUST_NOT,BooleanClause.Occur.MUST}; Query query = MultiFieldQueryParser.parse(Version.LUCENE_34, queries, fields, flags, analyzer); //Query query = new QueryParser(Version.LUCENE_34, "contentId", analyzer).parse("" + contentId); writer.deleteDocuments(query); //End ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); Document document = getDocumentFromContent(contentVO, notificationMessage, writer, forceVersionIndexing, db); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getDocumentFromContent", (t.getElapsedTimeNanos() / 1000)); if(document != null) { returnDocuments.add(document); logger.info("++++++++++++++Forcing cv indexing"); List<ContentVersionVO> versions = new ArrayList<ContentVersionVO>(); if(CmsPropertyHandler.getApplicationName().equalsIgnoreCase("cms")) { //List<LanguageVO> languages = LanguageController.getController().getLanguageVOList(contentVO.getRepositoryId()); List<LanguageVO> languages = LanguageController.getController().getLanguageVOList(contentVO.getRepositoryId(), db); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getLanguageVOList", (t.getElapsedTimeNanos() / 1000)); for(LanguageVO language : languages) { ContentVersionVO latestVersion = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), language.getId(), Integer.parseInt(CmsPropertyHandler.getOperatingMode()), db); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getLatestActiveContentVersionVO", (t.getElapsedTimeNanos() / 1000)); if(latestVersion != null) versions.add(latestVersion); ContentVersionVO latestVersionPublishedVersion = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), language.getId(), ContentVersionVO.PUBLISHED_STATE, db); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getLatestActiveContentVersionVO", (t.getElapsedTimeNanos() / 1000)); if(latestVersionPublishedVersion != null && latestVersionPublishedVersion.getId().intValue() != latestVersion.getId().intValue()) versions.add(latestVersionPublishedVersion); } } else { List<LanguageVO> languages = LanguageController.getController().getLanguageVOList(contentVO.getRepositoryId(), db); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getLanguageVOList", (t.getElapsedTimeNanos() / 1000)); for(LanguageVO language : languages) { ContentVersionVO version = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), language.getId(), Integer.parseInt(CmsPropertyHandler.getOperatingMode()), db); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getLatestActiveContentVersionVO", (t.getElapsedTimeNanos() / 1000)); if(version != null) versions.add(version); } } logger.info("versions:" + versions.size()); for(ContentVersionVO version : versions) { logger.info("version:" + version.getId()); Document versionDocument = getDocumentFromContentVersion(version, db); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getDocumentFromContentVersion", t.getElapsedTime()); if(versionDocument != null) returnDocuments.add(versionDocument); if(version.getId() > this.lastCommitedContentVersionId) lastCommitedContentVersionId = version.getId(); } } } return returnDocuments; } private List<Document> getDocumentsForContentVersion(ContentVersionVO contentVersionVO, Database db) throws Exception { Timer t = new Timer(); List<Document> returnDocuments = new ArrayList<Document>(); //ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentVersionVO.getContentId(), db); //RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getContentVOWithId", (t.getElapsedTimeNanos() / 1000)); Document document = getDocumentFromContentVersion(contentVersionVO, db); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getDocumentFromContentVersion", t.getElapsedTime()); if(document != null) returnDocuments.add(document); return returnDocuments; } public Document getDocumentFromSiteNode(SiteNodeVO siteNodeVO, IndexWriter writer, Database db) throws Exception, InterruptedException { logger.info("getDocumentFromSiteNode:" + siteNodeVO.getName() + ":" + siteNodeVO.getIsDeleted()); if(siteNodeVO == null || siteNodeVO.getIsDeleted()) { logger.info("Adding a delete directive to the indexer"); String uid = "siteNodeId_" + siteNodeVO.getId(); logger.info("Deleting documents:" + "uid=" + uid); logger.info("Before delete:" + writer.numDocs()); //writer.deleteDocuments(new Term("uid", "" + uid)); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_34); Query query = new QueryParser(Version.LUCENE_34, "siteNodeId", analyzer).parse("" + siteNodeVO.getId()); writer.deleteDocuments(query); logger.info("Before delete:" + writer.numDocs()); return null; } // make a new, empty document Document doc = new Document(); // Add the last modified date of the file a field named "modified". // Use a field that is indexed (i.e. searchable), but don't tokenize // the field into words. doc.add(new NumericField("publishDateTime", Field.Store.YES, true).setLongValue(siteNodeVO.getPublishDateTime().getTime())); doc.add(new Field("modified", DateTools.timeToString(new Date().getTime(), DateTools.Resolution.MINUTE), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("siteNodeId", "" + siteNodeVO.getId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("repositoryId", "" + siteNodeVO.getRepositoryId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("lastModifier", "" + siteNodeVO.getCreatorName(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("isAsset", "false", Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("isSiteNode", "true", Field.Store.YES, Field.Index.NOT_ANALYZED)); SiteNodeVersionVO siteNodeVersionVO = SiteNodeVersionController.getController().getLatestActiveSiteNodeVersionVO(db, siteNodeVO.getId()); if(siteNodeVersionVO != null) { doc.add(new NumericField("modificationDateTime", Field.Store.YES, true).setLongValue(siteNodeVersionVO.getModifiedDateTime().getTime())); doc.add(new Field("siteNodeVersionId", "" + siteNodeVersionVO.getId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("stateId", "" + siteNodeVersionVO.getStateId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("path", "" + getSiteNodePath(siteNodeVO.getId(), db), Field.Store.YES, Field.Index.NOT_ANALYZED)); } // Add the uid as a field, so that index can be incrementally // maintained. // This field is not stored with document, it is indexed, but it is not // tokenized prior to indexing. doc.add(new Field("uid", "siteNodeId_" + siteNodeVO.getId(), Field.Store.NO, Field.Index.NOT_ANALYZED)); // Add the tag-stripped contents as a Reader-valued Text field so it // will // get tokenized and indexed. doc.add(new Field("contents", new StringReader(siteNodeVO.getName()))); if(siteNodeVO.getMetaInfoContentId() != null && siteNodeVO.getMetaInfoContentId() > -1) { List<LanguageVO> languages = LanguageController.getController().getLanguageVOList(siteNodeVO.getRepositoryId(), db); for(LanguageVO language : languages) { ContentVersionVO cvVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(siteNodeVO.getMetaInfoContentId(), language.getId(), Integer.parseInt(CmsPropertyHandler.getOperatingMode()), db); if(cvVO != null) doc.add(new Field("contents", new StringReader(cvVO.getVersionValue()))); } } // return the document return doc; } public Document getSiteNodeDocument(ContentVersionVO contentVersionVO, IndexWriter writer, Database db) throws Exception, InterruptedException { Timer t = new Timer(); ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentVersionVO.getContentId(), db); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getContentVOWithId", (t.getElapsedTimeNanos() / 1000)); if(contentVO.getIsDeleted()) return null; if (contentVersionVO.getSiteNodeId() == null || contentVersionVO.getSiteNodeName() == null) { logger.warn("Content version does not have a SiteNode connected. Will not index content version. ContentVersion.id: " + contentVersionVO.getContentVersionId()); return null; } // make a new, empty document Document doc = new Document(); // Add the last modified date of the file a field named "modified". // Use a field that is indexed (i.e. searchable), but don't tokenize // the field into words. doc.add(new NumericField("publishDateTime", Field.Store.YES, true).setLongValue(contentVersionVO.getModifiedDateTime().getTime())); doc.add(new Field("modified", DateTools.timeToString(new Date().getTime(), DateTools.Resolution.MINUTE), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("siteNodeId", "" + contentVersionVO.getSiteNodeId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("repositoryId", "" + contentVO.getRepositoryId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("lastModifier", "" + contentVersionVO.getVersionModifier(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("isAsset", "false", Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("isSiteNode", "true", Field.Store.YES, Field.Index.NOT_ANALYZED)); //doc.add(new Field("contentTypeDefinitionId", "" + ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName("Meta info", db).getId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); try { SiteNodeVersionVO siteNodeVersionVO = SiteNodeVersionController.getController().getLatestActiveSiteNodeVersionVO(db, contentVersionVO.getSiteNodeId()); if(siteNodeVersionVO != null) doc.add(new Field("siteNodeVersionId", "" + siteNodeVersionVO.getId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); else logger.warn("No site node version found on siteNode: " + contentVersionVO.getSiteNodeId()); } catch (Exception e) { e.printStackTrace(); } doc.add(new NumericField("modificationDateTime", Field.Store.YES, true).setLongValue(contentVersionVO.getModifiedDateTime().getTime())); doc.add(new Field("stateId", "" + contentVersionVO.getStateId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("path", "" + getSiteNodePath(contentVersionVO.getSiteNodeId(), db), Field.Store.YES, Field.Index.NOT_ANALYZED)); // Add the uid as a field, so that index can be incrementally // maintained. // This field is not stored with document, it is indexed, but it is not // tokenized prior to indexing. doc.add(new Field("uid", "siteNodeId_" + contentVersionVO.getSiteNodeId(), Field.Store.NO, Field.Index.NOT_ANALYZED)); // Add the tag-stripped contents as a Reader-valued Text field so it // will // get tokenized and indexed. String pageName = contentVersionVO.getSiteNodeName(); if(pageName == null) { logger.info("Have to read again..."); SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId(contentVersionVO.getSiteNodeId(), db); pageName = siteNodeVO.getName(); } String versionValue = contentVersionVO.getVersionValue(); if(versionValue == null) { logger.info("Have to read version again..."); ContentVersionVO cvVO = ContentVersionController.getContentVersionController().getContentVersionVOWithId(contentVersionVO.getContentVersionId(), db); versionValue = cvVO.getVersionValue(); } doc.add(new Field("contents", new StringReader(versionValue))); doc.add(new Field("contents", new StringReader(pageName))); // return the document return doc; } public Document getDocumentFromContent(ContentVO contentVO, NotificationMessage message, IndexWriter writer, boolean indexVersions, Database db) throws Exception, InterruptedException { logger.info("getDocumentFromContent:" + contentVO.getName() + ":" + contentVO.getIsDeleted()); if(contentVO == null || contentVO.getIsDeleted()) { //NotificationMessage notificationMessage = new NotificationMessage(message.getName(), message.getClassName(), message.getSystemUserName(), NotificationMessage.TRANS_DELETE, message.getObjectId(), message.getObjectName()); logger.info("Adding a delete directive to the indexer"); //internalMessageList.add(notificationMessage); String uid = "contentId_" + contentVO.getId(); logger.info("Deleting documents:" + "uid=" + uid); logger.info("Before delete:" + writer.numDocs()); //writer.deleteDocuments(new Term("uid", "" + uid)); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_34); Query query = new QueryParser(Version.LUCENE_34, "contentId", analyzer).parse("" + contentVO.getId()); writer.deleteDocuments(query); logger.info("Before delete:" + writer.numDocs()); return null; } // make a new, empty document Document doc = new Document(); // Add the last modified date of the file a field named "modified". // Use a field that is indexed (i.e. searchable), but don't tokenize // the field into words. doc.add(new NumericField("publishDateTime", Field.Store.YES, true).setLongValue(contentVO.getPublishDateTime().getTime())); doc.add(new Field("modified", DateTools.timeToString(new Date().getTime(), DateTools.Resolution.MINUTE), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("contentId", "" + contentVO.getContentId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("contentTypeDefinitionId", "" + contentVO.getContentTypeDefinitionId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("repositoryId", "" + contentVO.getRepositoryId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("lastModifier", "" + contentVO.getCreatorName(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("isAsset", "false", Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("path", "" + getContentPath(contentVO.getId(), db), Field.Store.YES, Field.Index.NOT_ANALYZED)); // Add the uid as a field, so that index can be incrementally // maintained. // This field is not stored with document, it is indexed, but it is not // tokenized prior to indexing. doc.add(new Field("uid", "contentId_" + contentVO.getId(), Field.Store.NO, Field.Index.NOT_ANALYZED)); // Add the tag-stripped contents as a Reader-valued Text field so it // will // get tokenized and indexed. doc.add(new Field("contents", new StringReader(contentVO.getName()))); // return the document return doc; } public Document getDocumentFromContentVersion(ContentVersionVO contentVersionVO, Database db) throws Exception, InterruptedException { logger.info("getting document from content version:" + contentVersionVO.getContentName()); Timer t = new Timer(); //ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentVersionVO.getContentId()); ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentVersionVO.getContentId(), db); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getContentVOWithId", (t.getElapsedTimeNanos() / 1000)); if(contentVO.getIsDeleted()) return null; // make a new, empty document Document doc = new Document(); // Add the last modified date of the file a field named "modified". // Use a field that is indexed (i.e. searchable), but don't tokenize // the field into words. logger.info("contentVersionVO:" + contentVersionVO.getContentName()); doc.add(new NumericField("publishDateTime", Field.Store.YES, true).setLongValue(contentVO.getPublishDateTime().getTime())); doc.add(new NumericField("modificationDateTime", Field.Store.YES, true).setLongValue(contentVersionVO.getModifiedDateTime().getTime())); doc.add(new Field("modified", DateTools.timeToString(contentVersionVO.getModifiedDateTime().getTime(), DateTools.Resolution.MINUTE), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("contentVersionId", "" + contentVersionVO.getId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("contentId", "" + contentVersionVO.getContentId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("contentTypeDefinitionId", "" + contentVO.getContentTypeDefinitionId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("languageId", "" + contentVersionVO.getLanguageId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("repositoryId", "" + contentVO.getRepositoryId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("lastModifier", "" + contentVersionVO.getVersionModifier(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("stateId", "" + contentVersionVO.getStateId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("isAsset", "false", Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("path", "" + getContentPath(contentVO.getId(), db), Field.Store.YES, Field.Index.NOT_ANALYZED)); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("Indexing normalFields", (t.getElapsedTimeNanos() / 1000)); //Testing adding the categories for this version try { if(contentVO.getContentTypeDefinitionId() != null) { ContentTypeDefinitionVO ctdVO = null; try { ctdVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithId(contentVO.getContentTypeDefinitionId(), db); } catch (SystemException sex) { logger.warn("Failed to get the content type definition for content with Id: " + contentVO.getContentId() + ". The categories for the content will not be indexed. Message: " + sex.getMessage()); logger.info("Failed to get the content type definition for content with Id: " + contentVO.getContentId(), sex); } if (ctdVO != null) { RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getContentTypeDefinitionVOWithId", (t.getElapsedTimeNanos() / 1000)); List<CategoryAttribute> categoryKeys = ContentTypeDefinitionController.getController().getDefinedCategoryKeys(ctdVO, true); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("getDefinedCategoryKeys", (t.getElapsedTimeNanos() / 1000)); for(CategoryAttribute categoryKey : categoryKeys) { logger.info("categoryKey:" + categoryKey.getValue() + " for content:" + contentVO.getName()); //List<ContentCategoryVO> contentCategoryVOList = ContentCategoryController.getController().findByContentVersionAttribute(categoryKey.getValue(), contentVersionVO.getId()); List<ContentCategory> contentCategoryVOList = ContentCategoryController.getController().findByContentVersionAttribute(categoryKey.getValue(), contentVersionVO.getId(), db, true); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("Indexing categories", (t.getElapsedTimeNanos() / 1000)); logger.info("contentCategoryVOList:" + contentCategoryVOList.size()); for(ContentCategory contentCategory : contentCategoryVOList) { doc.add(new Field("categories", "" + contentCategory.getAttributeName().replaceAll(" ", "_").toLowerCase() + "eq" + contentCategory.getCategory().getId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("categories", "" + contentCategory.getAttributeName() + "=" + contentCategory.getCategory().getId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("" + contentCategory.getAttributeName() + "_categoryId", "" + contentCategory.getCategory().getId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); } } } } } catch (Exception e) { logger.error("Problem indexing categories for contentVO: " + contentVO.getName() + "(" + contentVO.getId() + "): " + e.getMessage(), e); } RequestAnalyser.getRequestAnalyser().registerComponentStatistics("Indexing categories", (t.getElapsedTimeNanos() / 1000)); //End test // Add the uid as a field, so that index can be incrementally // maintained. // This field is not stored with document, it is indexed, but it is not // tokenized prior to indexing. doc.add(new Field("uid", "contentVersionId_" + contentVersionVO.getId(), Field.Store.NO, Field.Index.NOT_ANALYZED)); // Add the tag-stripped contents as a Reader-valued Text field so it // will // get tokenized and indexed. doc.add(new Field("contents", new StringReader(contentVersionVO.getVersionValue()))); doc.add(new Field("contents", new StringReader(contentVersionVO.getContentName()))); RequestAnalyser.getRequestAnalyser().registerComponentStatistics("Indexing end fields", (t.getElapsedTimeNanos() / 1000)); // return the document return doc; } public Document getDocumentFromDigitalAsset(DigitalAssetVO digitalAssetVO, ContentVersionVO contentVersionVO, Database db) throws Exception, InterruptedException { ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentVersionVO.getContentId(), db); if(contentVO == null || contentVO.getIsDeleted()) return null; // make a new, empty document Document doc = new Document(); // Add the last modified date of the file a field named "modified". // Use a field that is indexed (i.e. searchable), but don't tokenize // the field into words. //doc.add(new Field("modified", DateTools.timeToString(contentVersionVO.getModifiedDateTime().getTime(), DateTools.Resolution.MINUTE), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new NumericField("modificationDateTime", Field.Store.YES, true).setLongValue(contentVersionVO.getModifiedDateTime().getTime())); doc.add(new Field("digitalAssetId", "" + digitalAssetVO.getId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("contentVersionId", "" + contentVersionVO.getId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("contentId", "" + contentVersionVO.getContentId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("contentTypeDefinitionId", "" + contentVO.getContentTypeDefinitionId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("languageId", "" + contentVersionVO.getLanguageId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("repositoryId", "" + contentVO.getRepositoryId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("lastModifier", "" + contentVersionVO.getVersionModifier(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("stateId", "" + contentVersionVO.getStateId(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("isAsset", "true", Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("path", "" + getContentPath(contentVO.getId(), db), Field.Store.YES, Field.Index.NOT_ANALYZED)); // Add the uid as a field, so that index can be incrementally // maintained. // This field is not stored with document, it is indexed, but it is not // tokenized prior to indexing. doc.add(new Field("uid", "digitalAssetId_" + digitalAssetVO.getId(), Field.Store.NO, Field.Index.NOT_ANALYZED)); //doc.add(new Field("uid", "" + contentVersionVO.getId(), Field.Store.NO, Field.Index.NOT_ANALYZED)); // Add the tag-stripped contents as a Reader-valued Text field so it // will // get tokenized and indexed. doc.add(new Field("contents", new StringReader(digitalAssetVO.getAssetKey() + " " + digitalAssetVO.getAssetFileName() + " " + digitalAssetVO.getAssetContentType()))); if (CmsPropertyHandler.getIndexDigitalAssetContent()) { //String url = DigitalAssetController.getController().getDigitalAssetUrl(digitalAssetVO, db); //if(logger.isInfoEnabled()) // logger.info("url if we should index file:" + url); try { String filePath = DigitalAssetController.getController().getDigitalAssetFilePath(digitalAssetVO, db); if(logger.isInfoEnabled()) logger.info("filePath if we should index file:" + filePath); File file = new File(filePath); String text = extractTextToIndex(digitalAssetVO, file); doc.add(new Field("contents", new StringReader(text))); } catch(Exception e) { logger.warn("Problem getting asset:" + digitalAssetVO.getId() + ": " + e.getMessage()); } } return doc; } private String extractTextToIndex(DigitalAssetVO digitalAssetVO, File file) { String text = ""; if(logger.isInfoEnabled()) logger.info("Asset content type:" + digitalAssetVO.getAssetContentType()); if(digitalAssetVO.getAssetContentType().equalsIgnoreCase("application/pdf")) { try { Writer output = null; PDDocument document = null; try { document = PDDocument.load(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if(!document.isEncrypted()) { output = new OutputStreamWriter(baos, "UTF-8"); PDFTextStripper stripper = new PDFTextStripper(); //stripper.setSortByPosition( sort ); //stripper.setStartPage( startPage ); //stripper.setEndPage( endPage ); stripper.writeText( document, output ); text = baos.toString("UTF-8"); if(logger.isInfoEnabled()) logger.info("PDF Document has " + text.length() + " chars\n\n" + text); } } catch (Exception e) { logger.warn("Error indexing file: " + file + "\nMessage: " + e.getMessage()); } finally { if( output != null ) { output.close(); } if( document != null ) { document.close(); } } } catch (Exception e) { logger.warn("Error indexing:" + e.getMessage()); } } else if(digitalAssetVO.getAssetContentType().equalsIgnoreCase("application/msword")) { try { InputStream is = new FileInputStream(file); POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file)); is.close(); // Create a document for this file HWPFDocument doc = new HWPFDocument(fs); // Create a WordExtractor to read the text of the word document WordExtractor we = new WordExtractor(doc); // Extract all paragraphs in the document as strings text = we.getText(); // Output the document if(logger.isInfoEnabled()) logger.info("Word Document has " + text.length() + " chars\n\n" + text); } catch (Exception e) { logger.warn("Error indexing file: " + file + "\nMessage: " + e.getMessage()); } } return text; } public void deleteVersionFromIndex(String contentVersionId) { try { IndexWriter writer = getIndexWriter(); logger.info("Deleting contentVersionId:" + contentVersionId); writer.deleteDocuments(new Term("contentVersionId", "" + contentVersionId)); writer.commit(); } catch (Exception e) { logger.error("Error deleteVersionFromIndex:" + e.getMessage(), e); } } public String getContentPath(Integer contentId, Database db) throws Exception { StringBuffer sb = new StringBuffer(); ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); sb.insert(0, contentVO.getName()); while(contentVO.getParentContentId() != null) { contentVO = ContentController.getContentController().getContentVOWithId(contentVO.getParentContentId(), db); sb.insert(0, contentVO.getName() + "/"); } sb.insert(0, "/"); return sb.toString(); } public String getSiteNodePath(Integer siteNodeId, Database db) throws Exception { StringBuffer sb = new StringBuffer(); SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId(siteNodeId, db); while(siteNodeVO != null) { sb.insert(0, "/" + siteNodeVO.getName()); if(siteNodeVO.getParentSiteNodeId() != null) siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId(siteNodeVO.getParentSiteNodeId(), db); else siteNodeVO = null; } return sb.toString(); } /** * This is a method that never should be called. */ public BaseEntityVO getNewVO() { return null; } public void setContextParameters(Map map) { // TODO Auto-generated method stub } }
9235b5cb48fb35285aa551efd42142504c178051
1,618
java
Java
spring-boot-security-demo/src/main/java/com/example/demo/model/AdminUserDetails.java
KevinEthan/spring-boot-demo
4a521faf080409788b2e32405de58a588a7c9a75
[ "MIT" ]
1
2021-05-28T05:35:11.000Z
2021-05-28T05:35:11.000Z
spring-boot-security-demo/src/main/java/com/example/demo/model/AdminUserDetails.java
KevinEthan/spring-boot-demo
4a521faf080409788b2e32405de58a588a7c9a75
[ "MIT" ]
null
null
null
spring-boot-security-demo/src/main/java/com/example/demo/model/AdminUserDetails.java
KevinEthan/spring-boot-demo
4a521faf080409788b2e32405de58a588a7c9a75
[ "MIT" ]
null
null
null
24.149254
95
0.667491
997,389
package com.example.demo.model; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Title: {@link AdminUserDetails} * Description: * * @author 谭 tmn * @email efpyi@example.com * @date 2019/11/20 16:10 */ public class AdminUserDetails implements UserDetails { private MyUser user; private List<Map> permissionList; public AdminUserDetails(MyUser user,List<Map> permissionList) { this.user = user; this.permissionList = permissionList; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { //返回当前用户的权限 return permissionList.stream() .filter(permission -> permission.get("value")!=null) .map(permission ->new SimpleGrantedAuthority((String) permission.get("value"))) .collect(Collectors.toList()); } @Override public String getPassword() { return user.getPassword(); } @Override public String getUsername() { return user.getUserName(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
9235b6678d569e615a9c8216fc4fed75b73480c1
1,789
java
Java
core/graph/src/test/java/uk/gov/gchq/gaffer/graph/hook/Log4jLoggerTest.java
r001zse/Gaffer
6abb5e8e3e96fb04add505beb2ad3ae5ae469f1c
[ "Apache-2.0" ]
null
null
null
core/graph/src/test/java/uk/gov/gchq/gaffer/graph/hook/Log4jLoggerTest.java
r001zse/Gaffer
6abb5e8e3e96fb04add505beb2ad3ae5ae469f1c
[ "Apache-2.0" ]
null
null
null
core/graph/src/test/java/uk/gov/gchq/gaffer/graph/hook/Log4jLoggerTest.java
r001zse/Gaffer
6abb5e8e3e96fb04add505beb2ad3ae5ae469f1c
[ "Apache-2.0" ]
null
null
null
31.946429
97
0.696478
997,390
/* * Copyright 2016-2019 Crown Copyright * * 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 uk.gov.gchq.gaffer.graph.hook; import org.junit.Test; import uk.gov.gchq.gaffer.JSONSerialisationTest; import uk.gov.gchq.gaffer.operation.OperationChain; import uk.gov.gchq.gaffer.operation.impl.generate.GenerateObjects; import uk.gov.gchq.gaffer.store.Context; import uk.gov.gchq.gaffer.user.User; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; public class Log4jLoggerTest extends JSONSerialisationTest<Log4jLogger> { @Test public void shouldReturnResultWithoutModification() { // Given final Log4jLogger hook = getTestObject(); final Object result = mock(Object.class); final OperationChain opChain = new OperationChain.Builder() .first(new GenerateObjects<>()) .build(); final User user = new User.Builder() .opAuths("NoScore") .build(); // When final Object returnedResult = hook.postExecute(result, opChain, new Context(new User())); // Then assertSame(result, returnedResult); } @Override public Log4jLogger getTestObject() { return new Log4jLogger(); } }
9235b6b1bc757862ca22f0c64f802bef27c13f24
830
java
Java
P_Examples_Java/Ejemplo1/src/ejemplo1/Ejemplo1.java
KaizerHind/FreeExcersice_Javascript
2ca941c134a19841611d02f9309f17de83a1397b
[ "MIT" ]
1
2019-11-24T18:25:54.000Z
2019-11-24T18:25:54.000Z
P_Examples_Java/Ejemplo1/src/ejemplo1/Ejemplo1.java
KaizerHind/FreeExcersice_Javascript
2ca941c134a19841611d02f9309f17de83a1397b
[ "MIT" ]
null
null
null
P_Examples_Java/Ejemplo1/src/ejemplo1/Ejemplo1.java
KaizerHind/FreeExcersice_Javascript
2ca941c134a19841611d02f9309f17de83a1397b
[ "MIT" ]
null
null
null
25.151515
95
0.598795
997,391
/* * 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 ejemplo1; import java.util.Scanner; /** * * @author mjimenez47 */ public class Ejemplo1 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int num1, num2, res; Scanner in = new Scanner(System.in); System.out.print("Ingrese el primer número: "); num1 = in.nextInt(); System.out.print("Ingrese el segundo número: "); num2 = in.nextInt(); res = num1 + num2; System.out.println("El resultado de la suma de " + num1 + " + " + num2 + " es " + res); } }
9235b74dc2d34526026a7422faf7842e8005aa3b
129
java
Java
ProjectSourceCode/Apache Commons Math v3.5/src/main/java/org/apache/commons/math3/linear/NonSquareOperatorException.java
yashgolwala/Software_Measurement_Team_M
3d2aef4c0711b7a02155a42ca6b08bb6c2693d4c
[ "Unlicense" ]
null
null
null
ProjectSourceCode/Apache Commons Math v3.5/src/main/java/org/apache/commons/math3/linear/NonSquareOperatorException.java
yashgolwala/Software_Measurement_Team_M
3d2aef4c0711b7a02155a42ca6b08bb6c2693d4c
[ "Unlicense" ]
null
null
null
ProjectSourceCode/Apache Commons Math v3.5/src/main/java/org/apache/commons/math3/linear/NonSquareOperatorException.java
yashgolwala/Software_Measurement_Team_M
3d2aef4c0711b7a02155a42ca6b08bb6c2693d4c
[ "Unlicense" ]
2
2019-06-24T22:57:32.000Z
2019-06-26T16:58:52.000Z
32.25
75
0.883721
997,392
version https://git-lfs.github.com/spec/v1 oid sha256:14c21e3886080befe459f845508af88981f754175c7a9349e837cd76664cdd3b size 1565
9235b7ca3ce6d686d339966c6cee1cbcc4d0c130
388
java
Java
Hemant/Hashset.java
Hemantgarg06/30-days-of-Java
d697b897d40025fea53ad09105c20d4b468c4c21
[ "MIT" ]
null
null
null
Hemant/Hashset.java
Hemantgarg06/30-days-of-Java
d697b897d40025fea53ad09105c20d4b468c4c21
[ "MIT" ]
1
2022-03-07T15:34:14.000Z
2022-03-07T15:34:14.000Z
Hemant/Hashset.java
Hemantgarg06/30-days-of-Java
d697b897d40025fea53ad09105c20d4b468c4c21
[ "MIT" ]
4
2022-03-01T14:48:16.000Z
2022-03-01T15:15:12.000Z
27.714286
65
0.510309
997,393
import java.util.HashSet; public class Hashset { public static void main(String[] args) { HashSet<Integer> myHashSet = new HashSet<>(6, 0.5f); myHashSet.add(6); myHashSet.add(8); myHashSet.add(3); myHashSet.add(11); myHashSet.add(11); System.out.println(myHashSet); } }
9235b91fb28361b875f88f853bd617e2e86f473b
16,464
java
Java
src/main/java/frc/swerverobot/subsystems/DrivetrainSubsystem.java
Team-4153/2022
8f47be462d34986f96ea56661e79dd0bc23b19f8
[ "BSD-3-Clause" ]
3
2022-01-27T00:47:23.000Z
2022-03-01T05:00:14.000Z
src/main/java/frc/swerverobot/subsystems/DrivetrainSubsystem.java
Team-4153/2022
8f47be462d34986f96ea56661e79dd0bc23b19f8
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/swerverobot/subsystems/DrivetrainSubsystem.java
Team-4153/2022
8f47be462d34986f96ea56661e79dd0bc23b19f8
[ "BSD-3-Clause" ]
1
2022-01-27T00:44:54.000Z
2022-01-27T00:44:54.000Z
41.786802
147
0.635386
997,394
package frc.swerverobot.subsystems; import com.google.errorprone.annotations.concurrent.GuardedBy; import com.revrobotics.CANSparkMax; import com.revrobotics.CANSparkMaxLowLevel; import edu.wpi.first.networktables.NetworkTableEntry; import edu.wpi.first.wpilibj.ADIS16470_IMU; import edu.wpi.first.wpilibj.shuffleboard.BuiltInLayouts; import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardLayout; import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab; import edu.wpi.first.wpilibj2.command.SubsystemBase; import edu.wpi.first.wpilibj.RobotController; import frc.swerverobot.RobotMap; import frc.swerverobot.commands.climb.States; import frc.swerverobot.drivers.T265; import org.frcteam2910.common.drivers.SwerveModule; import org.frcteam2910.common.kinematics.ChassisVelocity; import org.frcteam2910.common.kinematics.SwerveKinematics; import org.frcteam2910.common.kinematics.SwerveOdometry; import org.frcteam2910.common.math.RigidTransform2; import org.frcteam2910.common.math.Rotation2; import org.frcteam2910.common.math.Vector2; import org.frcteam2910.common.robot.UpdateManager; import org.frcteam2910.common.robot.drivers.Mk2SwerveModuleBuilder; import org.frcteam2910.common.util.HolonomicDriveSignal; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.frcteam2910.common.control.*; import org.frcteam2910.common.util.*; import java.util.Optional; import static frc.swerverobot.RobotMap.*; @Deprecated @SuppressWarnings("unused") public class DrivetrainSubsystem extends SubsystemBase implements UpdateManager.Updatable { // define the trackwidth (short side in our case) and wheelbase (long side in our case) ratio of the robot public static final double TRACKWIDTH = 0.7248; // 19.685; // 22.5; // 1.0; public static final double WHEELBASE = 1; // 27.159; // 22.5; // 1.0; // private double angle = 0; private static boolean locked; public static final DrivetrainFeedforwardConstants FEEDFORWARD_CONSTANTS = new DrivetrainFeedforwardConstants( 0.042746, 0.0032181, 0.30764 ); public static final TrajectoryConstraint[] TRAJECTORY_CONSTRAINTS = { new FeedforwardConstraint(11.0, FEEDFORWARD_CONSTANTS.getVelocityConstant(), FEEDFORWARD_CONSTANTS.getAccelerationConstant(), false), new MaxAccelerationConstraint(12.5 * 12.0), new CentripetalAccelerationConstraint(15 * 12.0) }; private static final int MAX_LATENCY_COMPENSATION_MAP_ENTRIES = 25; private final HolonomicMotionProfiledTrajectoryFollower follower = new HolonomicMotionProfiledTrajectoryFollower( new PidConstants(1.0, 0.0, 0.01), new PidConstants(1.0, 0.0, 0.01), new HolonomicFeedforward(FEEDFORWARD_CONSTANTS) ); // define the pid constants for each rotation motor private static final PidConstants rotation2 = new PidConstants(1.0, 0.0, 0.001); private static final PidConstants rotation4 = new PidConstants(1.0, 0.0, 0.001); private static final PidConstants rotation6 = new PidConstants(1.0, 0.0, 0.5); private static final PidConstants rotation8 = new PidConstants(1.0, 0.0, 0.5); // // initialize each module using Mk2SwerveModuleBuilder // // check org/frcteam2910/common/robot/drivers/Mk2SwerveModuleBuilder // to see the initialization arguments private final SwerveModule frontLeftModule = new Mk2SwerveModuleBuilder(new Vector2(TRACKWIDTH / 2.0, WHEELBASE / 2.0)) .angleMotor( new CANSparkMax(DRIVETRAIN_FRONT_LEFT_MODULE_ANGLE_MOTOR, CANSparkMaxLowLevel.MotorType.kBrushless), rotation6, 18.0 / 1.0, DRIVETRAIN_FRONT_LEFT_MODULE_ANGLE_OFFSET, DRIVETRAIN_FRONT_LEFT_MODULE_ENCODER_VOLTAGE_MAX) .driveMotor( new CANSparkMax(DRIVETRAIN_FRONT_LEFT_MODULE_DRIVE_MOTOR, CANSparkMaxLowLevel.MotorType.kBrushless), Mk2SwerveModuleBuilder.MotorType.NEO) .build(); private final SwerveModule frontRightModule = new Mk2SwerveModuleBuilder(new Vector2(TRACKWIDTH / 2.0, -WHEELBASE / 2.0)) .angleMotor( new CANSparkMax(DRIVETRAIN_FRONT_RIGHT_MODULE_ANGLE_MOTOR, CANSparkMaxLowLevel.MotorType.kBrushless), rotation2, 18.0/1.0, DRIVETRAIN_FRONT_RIGHT_MODULE_ANGLE_OFFSET, DRIVETRAIN_FRONT_RIGHT_MODULE_ENCODER_VOLTAGE_MAX) .driveMotor( new CANSparkMax(DRIVETRAIN_FRONT_RIGHT_MODULE_DRIVE_MOTOR, CANSparkMaxLowLevel.MotorType.kBrushless), Mk2SwerveModuleBuilder.MotorType.NEO) .build(); private final SwerveModule backLeftModule = new Mk2SwerveModuleBuilder(new Vector2(-TRACKWIDTH / 2.0, WHEELBASE / 2.0)) .angleMotor( new CANSparkMax(DRIVETRAIN_BACK_LEFT_MODULE_ANGLE_MOTOR, CANSparkMaxLowLevel.MotorType.kBrushless), rotation8, 18.0/1.0, DRIVETRAIN_BACK_LEFT_MODULE_ANGLE_OFFSET, DRIVETRAIN_BACK_LEFT_MODULE_ENCODER_VOLTAGE_MAX) .driveMotor( new CANSparkMax(DRIVETRAIN_BACK_LEFT_MODULE_DRIVE_MOTOR, CANSparkMaxLowLevel.MotorType.kBrushless), Mk2SwerveModuleBuilder.MotorType.NEO) .build(); private final SwerveModule backRightModule = new Mk2SwerveModuleBuilder(new Vector2(-TRACKWIDTH / 2.0, -WHEELBASE / 2.0)) .angleMotor( new CANSparkMax(DRIVETRAIN_BACK_RIGHT_MODULE_ANGLE_MOTOR, CANSparkMaxLowLevel.MotorType.kBrushless), rotation4, 18.0/1.0, DRIVETRAIN_BACK_RIGHT_MODULE_ANGLE_OFFSET, DRIVETRAIN_BACK_RIGHT_MODULE_ENCODER_VOLTAGE_MAX) .driveMotor( new CANSparkMax(DRIVETRAIN_BACK_RIGHT_MODULE_DRIVE_MOTOR, CANSparkMaxLowLevel.MotorType.kBrushless), Mk2SwerveModuleBuilder.MotorType.NEO) .build(); private final SwerveModule[] modules = {frontLeftModule, frontRightModule, backLeftModule, backRightModule}; // set wheel positions private final SwerveKinematics kinematics = new SwerveKinematics( new Vector2(TRACKWIDTH / 2.0, WHEELBASE / 2.0), // Front Left new Vector2(TRACKWIDTH / 2.0, -WHEELBASE / 2.0), // Front Right new Vector2(-TRACKWIDTH / 2.0, WHEELBASE / 2.0), // Back Left new Vector2(-TRACKWIDTH / 2.0, -WHEELBASE / 2.0) // Back Right ); private final SwerveOdometry odometry = new SwerveOdometry(kinematics, RigidTransform2.ZERO); @GuardedBy("kinematicsLock") private Vector2 velocity = Vector2.ZERO; @GuardedBy("kinematicsLock") private double angularVelocity = 0.0; @GuardedBy("kinematicsLock") private final InterpolatingTreeMap<InterpolatingDouble, RigidTransform2> latencyCompensationMap = new InterpolatingTreeMap<>(); private final Object sensorLock = new Object(); @GuardedBy("sensorLock") public final ADIS16470_IMU adisGyro = RobotMap.imu; public final T265 t265 = new T265(); private final boolean useT265 = false; private final Object kinematicsLock = new Object(); @GuardedBy("kinematicsLock") private RigidTransform2 pose = RigidTransform2.ZERO; private final Object stateLock = new Object(); @GuardedBy("stateLock") private HolonomicDriveSignal driveSignal = null; // Logging stuff private NetworkTableEntry poseXEntry; private NetworkTableEntry poseYEntry; private NetworkTableEntry poseAngleEntry; private NetworkTableEntry[] moduleAngleEntries = new NetworkTableEntry[modules.length]; public DrivetrainSubsystem() { synchronized (sensorLock) { // navX.setInverted(true); } ShuffleboardTab tab = Shuffleboard.getTab("Drivetrain"); poseXEntry = tab.add("Pose X", 0.0) .withPosition(0, 0) .withSize(1, 1) .getEntry(); poseYEntry = tab.add("Pose Y", 0.0) .withPosition(0, 1) .withSize(1, 1) .getEntry(); poseAngleEntry = tab.add("Pose Angle", 0.0) .withPosition(0, 2) .withSize(1, 1) .getEntry(); // this section adds each swerve module to the driver station's shuffleboard ShuffleboardLayout frontLeftModuleContainer = tab.getLayout("Front Left Module", BuiltInLayouts.kList) .withPosition(1, 0) .withSize(2, 3); moduleAngleEntries[0] = frontLeftModuleContainer.add("Angle", 0.0).getEntry(); ShuffleboardLayout frontRightModuleContainer = tab.getLayout("Front Right Module", BuiltInLayouts.kList) .withPosition(3, 0) .withSize(2, 3); moduleAngleEntries[1] = frontRightModuleContainer.add("Angle", 0.0).getEntry(); ShuffleboardLayout backLeftModuleContainer = tab.getLayout("Back Left Module", BuiltInLayouts.kList) .withPosition(5, 0) .withSize(2, 3); moduleAngleEntries[2] = backLeftModuleContainer.add("Angle", 0.0).getEntry(); ShuffleboardLayout backRightModuleContainer = tab.getLayout("Back Right Module", BuiltInLayouts.kList) .withPosition(7, 0) .withSize(2, 3); moduleAngleEntries[3] = backRightModuleContainer.add("Angle", 0.0).getEntry(); } public RigidTransform2 getPose() { synchronized (kinematicsLock) { return pose; } } public void resetPose() { synchronized (kinematicsLock) { pose = RigidTransform2.ZERO; odometry.resetPose(pose); t265.reset(); resetGyroAngle(); } } /* public void resetPose(RigidTransform2 pose) { synchronized (kinematicsLock) { this.pose = pose; odometry.resetPose(pose); } } */ public Vector2 getVelocity() { synchronized (kinematicsLock) { return velocity; } } public double getAngularVelocity() { synchronized (kinematicsLock) { return angularVelocity; } } public void drive(Vector2 translationalVelocity, double rotationalVelocity, boolean fieldOriented) { synchronized (stateLock) { driveSignal = new HolonomicDriveSignal(translationalVelocity, rotationalVelocity, fieldOriented); } } public void resetGyroAngle() { synchronized (sensorLock) { adisGyro.reset(); } } public void setAngle(double angle) { // this.angle = angle; t265.setRotation(angle); } public double getGyroAngle() { synchronized (sensorLock) { if(useT265) { return t265.getRotation(); } else { return adisGyro.getAngle(); // + angle; } } } @Override public void update(double timestamp, double dt) { // updates the odometry and drive signal for the robot at time intervals of length dt updateOdometry(timestamp, dt); HolonomicDriveSignal driveSignal; Optional<HolonomicDriveSignal> trajectorySignal = follower.update( getPose(), getVelocity(), getAngularVelocity(), timestamp, dt ); if (trajectorySignal.isPresent()) { driveSignal = trajectorySignal.get(); driveSignal = new HolonomicDriveSignal( driveSignal.getTranslation().scale(1.0 / RobotController.getBatteryVoltage()), driveSignal.getRotation() / RobotController.getBatteryVoltage(), driveSignal.isFieldOriented() ); // SmartDashboard.putNumber("drive signal x", driveSignal.getTranslation().x); // SmartDashboard.putNumber("drive signal y", driveSignal.getTranslation().y); // SmartDashboard.putNumber("drive signal rot", driveSignal.getRotation()); } else { synchronized (stateLock) { driveSignal = this.driveSignal; } } updateModules(driveSignal, dt); } private void updateOdometry(double timestamp, double dt) { // updates the module velocities at time intervals of length dt Vector2[] moduleVelocities = new Vector2[modules.length]; for (int i = 0; i < modules.length; i++) { var module = modules[i]; module.updateSensors(); moduleVelocities[i] = Vector2.fromAngle(Rotation2.fromRadians(module.getCurrentAngle())).scale(module.getCurrentVelocity()); } // updates robot angle based on gyro at intervals of length dt Rotation2 angle; double angularVelocity; synchronized (sensorLock) { if (useT265) { angle = Rotation2.fromRadians(getGyroAngle()); angularVelocity = t265.getAngularVelocity(); } else { angle = Rotation2.fromDegrees(getGyroAngle()); angularVelocity = adisGyro.getRate(); } } SmartDashboard.putNumber(String.format("gyro reading"), angle.toDegrees()); // put the gyro reading into the smartdashboard synchronized (kinematicsLock) { if (useT265) { this.pose = t265.getPose(); this.velocity = t265.getVelocity(); //velocity.getTranslationalVelocity(); this.angularVelocity = angularVelocity; // t265.getAngularVelocity(); // angularVelocity; } else { ChassisVelocity velocity = kinematics.toChassisVelocity(moduleVelocities); this.pose = odometry.update(angle, dt, moduleVelocities); this.velocity = velocity.getTranslationalVelocity(); this.angularVelocity = angularVelocity; } } } private void updateModules(HolonomicDriveSignal signal, double dt) { ChassisVelocity velocity; if (signal == null) { velocity = new ChassisVelocity(Vector2.ZERO, 0.0); } else if (signal.isFieldOriented()) { // if the robot is field oriented, shift translation to account for the rotation // double rot = signal.getRotation() - getPose().rotation.toRadians(); velocity = new ChassisVelocity( signal.getTranslation().rotateBy(getPose().rotation.inverse()), signal.getRotation() ); } else { // if the robot is robot oriented, just get translation and rotation velocity = new ChassisVelocity(signal.getTranslation(), signal.getRotation()); } Vector2[] moduleOutputs = kinematics.toModuleVelocities(velocity); SwerveKinematics.normalizeModuleVelocities(moduleOutputs, 1.0); for (int i = 0; i < modules.length; i++) { var module = modules[i]; module.setTargetVelocity(moduleOutputs[i]); module.updateState(dt); } } @Override public void periodic() { // this function is called once per scheduler run var pose = getPose(); poseXEntry.setDouble(pose.translation.x); poseYEntry.setDouble(pose.translation.y); poseAngleEntry.setDouble(pose.rotation.toDegrees()); for (int i = 0; i < modules.length; i++) { var module = modules[i]; // if(locked){ moduleAngleEntries[i].setDouble(((i+1)*90)-45); // } // else{ moduleAngleEntries[i].setDouble(Math.toDegrees(module.getCurrentAngle())); // } } } // public void lock(States in){ // switch(in){ // case LOCKED: // locked = true; // break; // case UNLOCKED: // locked = false; // break; // case TOGGLE: // locked = !locked; // break; // } // } }
9235ba98a47ed804171cd80ed91945556fca454d
11,329
java
Java
src/me/fluglow/DoorOpenListener.java
Fluglow/DoorPasscodes
446d0abbd74eecfa36b0d5d465e3b668773bdd61
[ "MIT" ]
null
null
null
src/me/fluglow/DoorOpenListener.java
Fluglow/DoorPasscodes
446d0abbd74eecfa36b0d5d465e3b668773bdd61
[ "MIT" ]
null
null
null
src/me/fluglow/DoorOpenListener.java
Fluglow/DoorPasscodes
446d0abbd74eecfa36b0d5d465e3b668773bdd61
[ "MIT" ]
null
null
null
27.233173
164
0.702004
997,395
package me.fluglow; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.BlockState; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockRedstoneEvent; import org.bukkit.event.inventory.*; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.material.Door; import org.bukkit.scheduler.BukkitRunnable; import java.util.*; import static me.fluglow.DoorPasscodes.*; public class DoorOpenListener implements Listener { private final String failedAttemptsMessage = ChatColor.RED + "You can't open this door because of too many failed attempts! Please try again later."; private final PasscodeDoorManager manager; private final DoorPasscodes mainPlugin; private Map<UUID, PlayerDoorOpenTries> openTries = new HashMap<>(); private Map<Inventory, Location> guiSessions = new HashMap<>(); private Map<PasscodeDoor, List<UUID>> allowedPassers = new HashMap<>(); DoorOpenListener(DoorPasscodes mainPlugin, PasscodeDoorManager manager) { this.mainPlugin = mainPlugin; this.manager = manager; doorOpenTryClearTask(); } @EventHandler public void blockRedstoneEvent(BlockRedstoneEvent event) { Location location = event.getBlock().getLocation(); if(location.getBlock().getType() == Material.WOODEN_DOOR) { PasscodeDoor door = manager.getDoorByLocation(location); if(door == null) return; if(!door.isOpen()) { event.setNewCurrent(0); } } } @EventHandler public void doorPassEvent(PlayerMoveEvent event) { Location to = event.getTo().getBlock().getLocation(); if(event.getFrom().getBlock().getLocation().equals(to)) return; if(to.getBlock().getType() == Material.WOODEN_DOOR) { PasscodeDoor toDoor = manager.getDoorByLocation(to); if(toDoor == null) return; if(allowedPassers.get(toDoor) == null || !allowedPassers.get(toDoor).contains(event.getPlayer().getUniqueId())) { //Player's who fall on a door will get stuck :^) //Warn downloaders, no need to work around if no one requests a fix. event.setCancelled(true); } } } @EventHandler public void interactEvent(PlayerInteractEvent event) { if(event.getAction() == Action.RIGHT_CLICK_BLOCK) { BlockState state = event.getClickedBlock().getState(); if(!(state.getData() instanceof Door)) { return; } Location doorLocation = state.getLocation(); PasscodeDoor passcodeDoor = manager.getDoorByLocation(doorLocation); if(passcodeDoor == null) { return; //Door isn't passcodeDoor, return. } event.setCancelled(true); if(passcodeDoor.isOpen()) return; //If door is already open, don't open GUI. DoorOpenResult openResult = isAllowedToOpen(event.getPlayer(), passcodeDoor); if(openResult == DoorOpenResult.FAILURE_ATTEMPTS) { event.getPlayer().sendMessage(failedAttemptsMessage); return; } else if(openResult == DoorOpenResult.FAILURE_PERMISSION) { event.getPlayer().sendMessage(ChatColor.RED + "You're not allowed to open that."); return; } openCodeGUI(event.getPlayer(), doorLocation); } } @EventHandler public void inventoryClose(InventoryCloseEvent event) { guiSessions.remove(event.getInventory()); } @EventHandler public void inventoryDrag(InventoryDragEvent event) { Inventory inv = event.getInventory(); if(inv == null) return; if(inv.getType() == InventoryType.CHEST && guiSessions.containsKey(inv)) { event.setCancelled(true); } } @EventHandler public void inventoryClick(InventoryClickEvent event) { Inventory inv = event.getClickedInventory(); if(inv == null) return; if(guiSessions.containsKey(event.getInventory())) //If this inventory is registered for a session { if(event.getClick() == ClickType.DOUBLE_CLICK || event.getClick() == ClickType.SHIFT_LEFT || event.getClick() == ClickType.SHIFT_RIGHT) { event.setCancelled(true); //Cancel double click to stop stealing from display inv } if(inv.getType() != InventoryType.CHEST || !guiSessions.containsKey(event.getClickedInventory())) //If the player didn't itneract with the top inventory, return. { return; } event.setCancelled(true); if(event.getClick() != ClickType.LEFT) return; ItemStack clicked = event.getCurrentItem(); Player clicker = (Player)event.getWhoClicked(); if(clicked == null || clicked.getItemMeta() == null) return; String name = clicked.getItemMeta().getDisplayName(); int slot; ItemStack item = null; switch(name) { case "+": slot = event.getSlot() + 9; item = inv.getItem(slot); if(item.getAmount() == MAX_CODE_NUM) { item.setAmount(MIN_CODE_NUM); } else { item.setAmount(item.getAmount() + 1); } break; case "-": slot = event.getSlot() - 9; item = inv.getItem(slot); if(item.getAmount() == DoorPasscodes.MIN_CODE_NUM) { item.setAmount(MAX_CODE_NUM); } else { item.setAmount(item.getAmount() - 1); } break; case "Open": tryOpenDoor(getCode(inv), clicker, manager.getDoorByLocation(guiSessions.get(inv))); clicker.closeInventory(); break; case "Cancel": clicker.closeInventory(); } if(item != null) { ItemMeta meta = item.getItemMeta(); meta.setDisplayName(Integer.toString(item.getAmount())); item.setItemMeta(meta); } } } private DoorOpenResult isAllowedToOpen(Player player, PasscodeDoor door) { if(!player.hasPermission("doorpasscodes.open")) return DoorOpenResult.FAILURE_PERMISSION; if(!openTries.containsKey(player.getUniqueId())) { return DoorOpenResult.SUCCESS; } PlayerDoorOpenTries tries = openTries.get(player.getUniqueId()); if(tries.contains(door) && System.currentTimeMillis() - tries.getCreationTimestamp(door) > INCORRECT_PASSCODE_WAIT_MILLISECONDS) { tries.expire(door); if(tries.isEmpty()) openTries.remove(player.getUniqueId()); return DoorOpenResult.SUCCESS; } return tries.getTries(door) <= ALLOWED_WRONG_TRIES ? DoorOpenResult.SUCCESS : DoorOpenResult.FAILURE_ATTEMPTS; } private enum DoorOpenResult { FAILURE_ATTEMPTS, FAILURE_PERMISSION, SUCCESS } private void tryOpenDoor(int[] code, Player player, PasscodeDoor door) { if(code == null) return; if(door.isCorrectCode(code)) { openDoor(player, door); player.sendMessage(ChatColor.GREEN + "Correct passcode!"); if(openTries.containsKey(player.getUniqueId())) { openTries.get(player.getUniqueId()).expire(door); //Expire tries since player successfully opened door. } } else { if(!openTries.containsKey(player.getUniqueId())) { openTries.put(player.getUniqueId(), new PlayerDoorOpenTries()); } int currentTries = openTries.get(player.getUniqueId()).addTry(door); if(currentTries == ALLOWED_WRONG_TRIES + 1) { player.sendMessage(failedAttemptsMessage); } else { player.sendMessage(ChatColor.RED + "Incorrect passcode! (" + + currentTries + "/" + ALLOWED_WRONG_TRIES + ")"); } } } private void openDoor(Player player, PasscodeDoor door) { door.setOpenState(true); List<UUID> allowed = allowedPassers.getOrDefault(door, new ArrayList<>()); allowed.add(player.getUniqueId()); allowedPassers.put(door, allowed); new BukkitRunnable() { @Override public void run() { door.setOpenState(false); List<UUID> allowed = allowedPassers.get(door); allowed.remove(player.getUniqueId()); allowedPassers.put(door, allowed); if(allowedPassers.get(door).isEmpty()) { allowedPassers.remove(door); } } }.runTaskLater(mainPlugin, DOOR_OPEN_DURATION_SECONDS*20); } private int[] getCode(Inventory inv) { int[] slots = {10, 12, 14, 16}; int[] code = new int[4]; for(int i = 0; i < slots.length; i++) { ItemStack item = inv.getItem(slots[i]); if(item == null || item.getType() == Material.AIR) return null; code[i] = item.getAmount(); } return code; } private void openCodeGUI(Player player, Location doorLocation) { Inventory inv = Bukkit.createInventory(player, InventoryType.CHEST, "Door passcode"); int[] upperSlots = {1, 3, 5, 7}; int[] slots = {10, 12, 14, 16}; int[] bottomSlots = {19, 21, 23, 25}; ItemStack code0 = new ItemStack(Material.PAPER, DoorPasscodes.MIN_CODE_NUM); ItemMeta code0Meta = code0.getItemMeta(); code0Meta.setDisplayName("1"); code0.setItemMeta(code0Meta); ItemStack add = new ItemStack(Material.STICK, 1); ItemMeta addItemMeta = add.getItemMeta(); addItemMeta.setDisplayName("+"); add.setItemMeta(addItemMeta); ItemStack decrement = new ItemStack(Material.STICK, 1); ItemMeta decItemMeta = add.getItemMeta(); decItemMeta.setDisplayName("-"); decrement.setItemMeta(decItemMeta); for(int slot : slots) { inv.setItem(slot, code0); } for(int slot : upperSlots) { inv.setItem(slot, add); } for(int slot : bottomSlots) { inv.setItem(slot, decrement); } ItemStack openItem = new ItemStack(Material.STAINED_CLAY, 1, (short)5); ItemMeta saveItemMeta = openItem.getItemMeta(); saveItemMeta.setDisplayName("Open"); openItem.setItemMeta(saveItemMeta); ItemStack backItem = new ItemStack(Material.STAINED_CLAY, 1, (short)14); ItemMeta backItemMeta = backItem.getItemMeta(); backItemMeta.setDisplayName("Cancel"); backItem.setItemMeta(backItemMeta); inv.setItem(18, backItem); inv.setItem(26, openItem); guiSessions.put(inv, doorLocation); player.openInventory(inv); } private void doorOpenTryClearTask() { new BukkitRunnable() { @Override public void run() { for(Map.Entry<UUID, PlayerDoorOpenTries> tries : openTries.entrySet()) { tries.getValue().expireAllIfDone(); if(tries.getValue().isEmpty()) { openTries.remove(tries.getKey()); } } } }.runTaskTimer(mainPlugin, 10*60*20, 10*60*20); //10*60*20 = 10 minutes } class PlayerDoorOpenTries { private Map<PasscodeDoor, Integer> tries; private Map<PasscodeDoor, Long> timeStamps; PlayerDoorOpenTries() { tries = new HashMap<>(); this.timeStamps = new HashMap<>(); } int getTries(PasscodeDoor door) { return tries.getOrDefault(door, 0); } boolean contains(PasscodeDoor door) { return tries.containsKey(door); } long getCreationTimestamp(PasscodeDoor door) { return timeStamps.get(door); } void expire(PasscodeDoor door) { tries.remove(door); timeStamps.remove(door); } void expireIfDone(PasscodeDoor door) { if(!timeStamps.containsKey(door)) return; if(System.currentTimeMillis() - timeStamps.get(door) > INCORRECT_PASSCODE_WAIT_MILLISECONDS) { expire(door); } } void expireAllIfDone() { for(PasscodeDoor door : tries.keySet()) { expireIfDone(door); } } boolean isEmpty() { return tries.isEmpty(); } int addTry(PasscodeDoor door) { tries.put(door, tries.getOrDefault(door, 0) + 1); timeStamps.put(door, System.currentTimeMillis()); return tries.get(door); } } }
9235bc04e914e63d6d87381b99aee78d5df89cd4
390
java
Java
nreod/nre-darwin-model/src/main/java/uk/trainwatch/nre/darwin/model/util/PublicArrival.java
peter-mount/opendata
03fca4c2e63488ec01a1ad82f858ff954e4d90fe
[ "Apache-2.0" ]
15
2015-02-10T13:23:36.000Z
2021-12-21T13:34:54.000Z
nreod/nre-darwin-model/src/main/java/uk/trainwatch/nre/darwin/model/util/PublicArrival.java
peter-mount/opendata
03fca4c2e63488ec01a1ad82f858ff954e4d90fe
[ "Apache-2.0" ]
55
2015-04-04T12:35:08.000Z
2017-09-04T17:56:56.000Z
nreod/nre-darwin-model/src/main/java/uk/trainwatch/nre/darwin/model/util/PublicArrival.java
peter-mount/opendata
03fca4c2e63488ec01a1ad82f858ff954e4d90fe
[ "Apache-2.0" ]
4
2015-11-16T03:20:54.000Z
2022-03-06T00:36:20.000Z
20.526316
79
0.707692
997,396
/* * 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 uk.trainwatch.nre.darwin.model.util; /** * Object contains a public arrival time. * <p> * @author peter */ public interface PublicArrival extends WorkArrival { String getPta(); }
9235bd696c31e5403d88e4296fc41e4acdc9626b
11,159
java
Java
src/test/java/sk/mlobb/be/rcon/BERconClientTest.java
Matej-Lobb/java-be-rcon
1c348c8b7c64e7a7746013d4787fc1e56aef4025
[ "Apache-2.0" ]
1
2019-09-04T13:11:26.000Z
2019-09-04T13:11:26.000Z
src/test/java/sk/mlobb/be/rcon/BERconClientTest.java
Matej-Lobb/java-be-rcon
1c348c8b7c64e7a7746013d4787fc1e56aef4025
[ "Apache-2.0" ]
14
2019-10-07T09:07:45.000Z
2020-06-29T20:16:08.000Z
src/test/java/sk/mlobb/be/rcon/BERconClientTest.java
Matej-Lobb/java-be-rcon
1c348c8b7c64e7a7746013d4787fc1e56aef4025
[ "Apache-2.0" ]
1
2019-09-03T21:54:20.000Z
2019-09-03T21:54:20.000Z
36.828383
98
0.714222
997,397
package sk.mlobb.be.rcon; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import sk.mlobb.be.rcon.handler.ConnectionHandler; import sk.mlobb.be.rcon.handler.ResponseHandler; import sk.mlobb.be.rcon.model.BECommand; import sk.mlobb.be.rcon.model.BELoginCredential; import sk.mlobb.be.rcon.model.command.DayzBECommandType; import sk.mlobb.be.rcon.model.configuration.BERconConfiguration; import sk.mlobb.be.rcon.model.enums.BEConnectType; import sk.mlobb.be.rcon.model.enums.BEDisconnectType; import sk.mlobb.be.rcon.model.enums.BEMessageType; import sk.mlobb.be.rcon.model.exception.BERconException; import sk.mlobb.be.rcon.wrapper.DatagramChannelWrapper; import sk.mlobb.be.rcon.wrapper.LogWrapper; import java.io.IOException; import java.net.StandardSocketOptions; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import static org.apache.commons.lang3.reflect.FieldUtils.writeField; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) public class BERconClientTest { private BERconClient beRconClient; @Mock private BERconConfiguration configuration; @Mock private DatagramChannel datagramChannel; @Mock private Queue<BECommand> commandQueue; @Mock private BECommand beCommand; @Mock private DatagramChannelWrapper datagramChannelWrapper; @Mock private BELoginCredential beLoginCredential; @BeforeEach void setUp() throws IllegalAccessException { AtomicInteger sequenceNumber = new AtomicInteger(0); ByteBuffer receiveBuffer = ByteBuffer.wrap("test".getBytes()); AtomicLong lastSentTime = new AtomicLong(100L); AtomicLong lastReceivedTime = new AtomicLong(0); ByteBuffer sendBuffer = ByteBuffer.allocate(9999); configuration.setConnectionDelay(1L); beRconClient = new BERconClient(configuration, new TestLogImpl()); writeField(beRconClient, "datagramChannelWrapper", datagramChannelWrapper, true); writeField(beRconClient, "sequenceNumber", sequenceNumber , true); writeField(beRconClient, "commandQueue", commandQueue, true); writeField(beRconClient, "receiveBuffer", receiveBuffer, true); writeField(beRconClient, "sendBuffer", sendBuffer, true); writeField(beRconClient, "datagramChannel", datagramChannel, true); writeField(beRconClient, "lastSentTime", lastSentTime, true); writeField(beRconClient, "lastReceivedTime", lastReceivedTime ,true); writeField(beRconClient, "beRconConfiguration", configuration, true); writeField(beRconClient, "log", new TestLogImpl(), true); writeField(beRconClient, "loggingEnabled", true, true); beRconClient.addConnectionHandler(new CustomConnectionHandler()); beRconClient.addResponseHandler(new CustomResponseHandler()); } @Test public void shouldReceiveLoginPacketException() { assertThrows(BERconException.class, () -> beRconClient.receiveLoginPacket()); } @Test public void shouldReceiveLoginPacketSuccess() throws IllegalAccessException { ByteBuffer receiveBuffer = ByteBuffer.wrap(new byte[]{0,1,2,3,4,5,6,7,0x01}); writeField(beRconClient, "receiveBuffer", receiveBuffer, true); beRconClient.receiveLoginPacket(); assertTrue(beRconClient.getConnected().get()); } @Test public void shouldReceiveLoginPacketFailure() throws IOException, IllegalAccessException { ByteBuffer receiveBuffer = ByteBuffer.wrap(new byte[]{0,1,2,3,4,5,6,7,0x00}); writeField(beRconClient, "receiveBuffer", receiveBuffer, true); beRconClient.receiveLoginPacket(); verify(datagramChannel).disconnect(); verify(datagramChannelWrapper).close(any()); verify(datagramChannelWrapper).close(any()); } @Test public void shouldReceiveLoginPacketUnknown() throws IOException, IllegalAccessException { ByteBuffer receiveBuffer = ByteBuffer.wrap(new byte[]{0,1,2,3,4,5,6,7,8,0x05}); writeField(beRconClient, "receiveBuffer", receiveBuffer, true); beRconClient.receiveLoginPacket(); verify(datagramChannel).disconnect(); verify(datagramChannelWrapper).close(any()); } @Test public void shouldReceiveCommandPacketMessage() throws IOException { when(beCommand.getMessageType()).thenReturn(BEMessageType.COMMAND); when(datagramChannel.isConnected()).thenReturn(true); when(beCommand.getCommand()).thenReturn("command"); when(commandQueue.poll()).thenReturn(beCommand); beRconClient.receiveCommandPacket(); verify(datagramChannel).write((ByteBuffer) any()); } @Test public void shouldReceiveCommandPacket() throws IOException, IllegalAccessException { when(beCommand.getMessageType()).thenReturn(BEMessageType.COMMAND); when(datagramChannel.isConnected()).thenReturn(true); when(beCommand.getCommand()).thenReturn("command"); when(commandQueue.poll()).thenReturn(beCommand); ByteBuffer receiveBuffer = ByteBuffer.wrap(new byte[]{0x00,0x00,9,4,5,6,7,8,9,9,9,9,9,9}); writeField(beRconClient, "receiveBuffer", receiveBuffer, true); beRconClient.receiveCommandPacket(); verify(datagramChannel).write((ByteBuffer) any()); } @Test public void shouldReceiveServerPacket() throws IOException { when(datagramChannel.isConnected()).thenReturn(true); when(commandQueue.poll()).thenReturn(beCommand); when(beCommand.getMessageType()).thenReturn(BEMessageType.COMMAND); when(beCommand.getCommand()).thenReturn("command"); beRconClient.receiveServerPacket(); verify(datagramChannel, times(2)).write((ByteBuffer) any()); } @Test public void shouldNotSendNextCommand() throws IOException { when(beCommand.getMessageType()).thenReturn(BEMessageType.COMMAND); when(datagramChannel.isConnected()).thenReturn(true); when(commandQueue.poll()).thenReturn(beCommand); doThrow(IOException.class).when(datagramChannel).write((ByteBuffer) any()); assertThrows(BERconException.class, () -> beRconClient.sendNextCommand()); } @Test public void shouldSendNextCommand() throws IOException { when(beCommand.getMessageType()).thenReturn(BEMessageType.COMMAND); when(datagramChannel.isConnected()).thenReturn(true); when(commandQueue.poll()).thenReturn(beCommand); beRconClient.sendNextCommand(); verify(datagramChannel).write((ByteBuffer) any()); } @Test public void shouldSentKeepAlive() throws IOException { when(datagramChannel.isConnected()).thenReturn(true); beRconClient.sentKeepAlive(); verify(datagramChannel).write((ByteBuffer) any()); } @Test public void shouldNotDisconnect() throws IOException { doThrow(IOException.class).when(datagramChannelWrapper).close(any()); beRconClient.disconnect(); verify(datagramChannel).disconnect(); } @Test public void shouldDisconnect() throws IOException { beRconClient.disconnect(); verify(datagramChannel).disconnect(); verify(datagramChannelWrapper).close(any()); } @Test public void shouldCheckTimeout() throws IOException { doNothing().when(datagramChannelWrapper).close(datagramChannel); beRconClient.checkTimeout(); verify(datagramChannelWrapper).close(any()); } @Test public void shouldConnect() throws IOException { when(datagramChannelWrapper.open()).thenReturn(datagramChannel); when(datagramChannel.connect(any())).thenReturn(datagramChannel); when(datagramChannel.getOption(StandardSocketOptions.SO_SNDBUF)).thenReturn(99999); when(datagramChannel.getOption(StandardSocketOptions.SO_RCVBUF)).thenReturn(99999); when(datagramChannel.isConnected()).thenReturn(true); when(datagramChannel.write((ByteBuffer) any())).thenReturn(1); when(configuration.getConnectionDelay()).thenReturn(1L); beRconClient.connect(beLoginCredential); verify(datagramChannel).write((ByteBuffer) any()); assertNotNull(beRconClient.getMonitorThread()); assertNotNull(beRconClient.getReceiveThread()); } @Test public void shouldNotConnect() throws IOException, IllegalAccessException { Thread receiveThread = mock(Thread.class); writeField(beRconClient, "receiveThread", receiveThread, true); when(datagramChannelWrapper.open()).thenReturn(datagramChannel); when(datagramChannel.getOption(StandardSocketOptions.SO_SNDBUF)).thenReturn(99999); when(datagramChannel.getOption(StandardSocketOptions.SO_RCVBUF)).thenReturn(99999); doThrow(RuntimeException.class).when(receiveThread).start(); assertThrows(BERconException.class, () -> beRconClient.connect(beLoginCredential)); } @Test public void shouldSendCommandString() { beRconClient.sendCommand("test command"); verify(commandQueue).add(any()); } @Test public void shouldSendCommandNoArgs() { beRconClient.sendCommand(DayzBECommandType.EMPTY); verify(commandQueue).add(any()); } @Test public void shouldSendCommandArgs() { beRconClient.sendCommand(DayzBECommandType.EMPTY, "arg1", "arg2"); verify(commandQueue).add(any()); } private static class CustomConnectionHandler implements ConnectionHandler { public void onConnected(BEConnectType connectType) { System.out.println("Connected!"); } public void onDisconnected(BEDisconnectType disconnectType) { System.out.println("Disconnected!"); } } private static class CustomResponseHandler implements ResponseHandler { @Override public void onResponse(String response) { System.out.println(response); } } private static class TestLogImpl implements LogWrapper { public void debug(String msg) { System.out.println(msg); } public void info(String msg) { System.out.println(msg); } public void warn(String msg) { System.out.println(msg); } public void warn(String msg, Throwable t) { System.out.println(msg); } } }
9235beb7d340b5109206ac079a748f17b6ef13c9
3,933
java
Java
squin-core/src/main/java/org/squin/lookup/urisearch/impl/URISearchTask.java
castagna/squin
8f2f3c3bbc6a9f37a5b17592997ba06dc61554eb
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
squin-core/src/main/java/org/squin/lookup/urisearch/impl/URISearchTask.java
castagna/squin
8f2f3c3bbc6a9f37a5b17592997ba06dc61554eb
[ "ECL-2.0", "Apache-2.0" ]
1
2018-07-04T11:12:44.000Z
2018-07-04T11:12:44.000Z
squin-core/src/main/java/org/squin/lookup/urisearch/impl/URISearchTask.java
castagna/squin
8f2f3c3bbc6a9f37a5b17592997ba06dc61554eb
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
29.893939
237
0.741257
997,398
/* This file is part of SQUIN and it falls under the copyright as specified for the whole SQUIN package. */ package org.squin.lookup.urisearch.impl; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.squin.common.Priority; import org.squin.common.Task; import org.squin.common.impl.TaskBase; import org.squin.lookup.urisearch.URISearchResult; /** * Represents a task to search for RDF documents that mention a given URI. * * @author Olaf Hartig (kenaa@example.com) */ public class URISearchTask extends TaskBase<URISearchResult> implements Task<URISearchResult> { // members final private Logger log = LoggerFactory.getLogger( URISearchTask.class ); /** * Identifier of the URI that has to be searched. */ final public int uriID; final protected QueryProcessor processor; // initialization /** * Constructs a URI search task. * * @param uriID identifier of the URI that has to be searched * @param priority priority of this task * (mandatory, i.e. must not be null) */ public URISearchTask ( int uriID, Priority priority, QueryProcessor processor ) { super( priority ); assert processor != null; this.uriID = uriID; this.processor = processor; } // implementation of the TaskBase<URISearchResult> abstract methods public URISearchResult createFailureResult ( Exception e ) { return new Failure( uriID, getTimestamp(), getExecutionStartTimestamp(), e ); } // implementation of the Callable interface public URISearchResult call () { log.debug( "Started to search for the URI with ID {}.", uriID ); List<Integer> discoveredDocumentURIs; try { discoveredDocumentURIs = processor.process( uriID ); } catch ( QueryProcessingException e ) { log.debug( "Searching for the URI with ID {} failed: {}", uriID, e.getMessage() ); return new Failure( uriID, getTimestamp(), getExecutionStartTimestamp(), e ); } log.debug( "Finished to search for the URI with ID {} - {} document URIs found.", uriID, discoveredDocumentURIs.size() ); return new URIsDiscovered( uriID, getTimestamp(), getExecutionStartTimestamp(), discoveredDocumentURIs ); } // implementations of the URISearchResult interface static abstract class URISearchResultBase implements URISearchResult { final public int uriID; final public long queueTime; final public long execTime; public URISearchResultBase ( int uriID, long taskInitTimestamp, long taskStartTimestamp ) { this.uriID = uriID; queueTime = taskStartTimestamp - taskInitTimestamp; execTime = System.currentTimeMillis() - taskStartTimestamp; } public int getURIID () { return uriID; } public List<Integer> getDiscoveredDocumentURIs () { throw new UnsupportedOperationException(); } public Exception getException () { throw new UnsupportedOperationException(); } public long getQueueTime () { return queueTime; } public long getExecutionTime () { return execTime; } } static protected class URIsDiscovered extends URISearchResultBase { final public List<Integer> discoveredDocumentURIs; public URIsDiscovered ( int uriID, long taskInitTimestamp, long taskStartTimestamp, List<Integer> discoveredDocumentURIs ) { super( uriID, taskInitTimestamp, taskStartTimestamp ); this.discoveredDocumentURIs = discoveredDocumentURIs; } public boolean isFailure () { return false; } @Override public List<Integer> getDiscoveredDocumentURIs () { return discoveredDocumentURIs; } } static protected class Failure extends URISearchResultBase { final public Exception exception; public Failure ( int uriID, long taskInitTimestamp, long taskStartTimestamp, Exception exception ) { super( uriID, taskInitTimestamp, taskStartTimestamp ); this.exception = exception; } public boolean isFailure () { return true; } @Override public Exception getException () { return exception; } } }
9235bf13a9ef2d2020d50587cde72f7f799e9198
1,787
java
Java
src/main/java/io/github/lukegrahamlandry/mountables/client/render/layer/CollarLayer.java
LukeGrahamLandry/mountables-mod
396476ed2e83b1b7cdf45c103cecfcf407c15f5d
[ "MIT" ]
null
null
null
src/main/java/io/github/lukegrahamlandry/mountables/client/render/layer/CollarLayer.java
LukeGrahamLandry/mountables-mod
396476ed2e83b1b7cdf45c103cecfcf407c15f5d
[ "MIT" ]
1
2021-06-06T11:43:20.000Z
2021-06-06T23:28:27.000Z
src/main/java/io/github/lukegrahamlandry/mountables/client/render/layer/CollarLayer.java
LukeGrahamLandry/mountables-mod
396476ed2e83b1b7cdf45c103cecfcf407c15f5d
[ "MIT" ]
null
null
null
48.297297
231
0.73643
997,399
package io.github.lukegrahamlandry.mountables.client.render.layer; import com.mojang.blaze3d.matrix.MatrixStack; import io.github.lukegrahamlandry.mountables.client.models.WolfMountModel; import io.github.lukegrahamlandry.mountables.mounts.MountEntity; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.entity.IEntityRenderer; import net.minecraft.client.renderer.entity.layers.LayerRenderer; import net.minecraft.client.renderer.entity.model.WolfModel; import net.minecraft.entity.passive.WolfEntity; import net.minecraft.item.DyeColor; import net.minecraft.util.ResourceLocation; public class CollarLayer extends LayerRenderer<MountEntity, WolfMountModel> { private static final ResourceLocation WOLF_COLLAR_LOCATION = new ResourceLocation("textures/entity/wolf/wolf_collar.png"); public CollarLayer(IEntityRenderer<MountEntity, WolfMountModel> p_i50914_1_) { super(p_i50914_1_); } public void render(MatrixStack p_225628_1_, IRenderTypeBuffer p_225628_2_, int p_225628_3_, MountEntity mount, float p_225628_5_, float p_225628_6_, float p_225628_7_, float p_225628_8_, float p_225628_9_, float p_225628_10_) { if (!mount.isInvisible() && mount.getColorType() != 0) { DyeColor color; if (mount.getColorType() <= 16) { color = DyeColor.byId(mount.getColorType() - 1); } else { int index = ((mount.tickCount + mount.getId()) / 25) % 16; color = DyeColor.byId(index); } float[] afloat = color.getTextureDiffuseColors(); renderColoredCutoutModel(this.getParentModel(), WOLF_COLLAR_LOCATION, p_225628_1_, p_225628_2_, p_225628_3_, mount, afloat[0], afloat[1], afloat[2]); } } }
9235bf1ad0bb40317751089c91e5a1e3330152d0
8,372
java
Java
src/main/java/cn/cash/register/service/impl/GoodsTrafficServiceImpl.java
huhuics/cash-register
f6cab4ed42b0d46a3a43e739d3c17ca45c1855ad
[ "Apache-2.0" ]
7
2018-10-31T06:17:54.000Z
2022-02-22T03:44:50.000Z
src/main/java/cn/cash/register/service/impl/GoodsTrafficServiceImpl.java
huhuics/cash-register
f6cab4ed42b0d46a3a43e739d3c17ca45c1855ad
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/cash/register/service/impl/GoodsTrafficServiceImpl.java
huhuics/cash-register
f6cab4ed42b0d46a3a43e739d3c17ca45c1855ad
[ "Apache-2.0" ]
4
2018-04-17T01:47:10.000Z
2020-08-05T08:10:21.000Z
39.677725
190
0.67236
997,400
/** * Cash-Register * Copyright (c) 1995-2018 All Rights Reserved. */ package cn.cash.register.service.impl; import java.util.Date; import java.util.List; import javax.annotation.Resource; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.cash.register.common.request.GoodsTrafficQueryRequest; import cn.cash.register.common.request.InTrafficRequest; import cn.cash.register.common.request.OutTrafficRequest; import cn.cash.register.dao.GoodsTrafficMapper; import cn.cash.register.dao.domain.GoodsInfo; import cn.cash.register.dao.domain.GoodsTraffic; import cn.cash.register.enums.StockFlowTypeEnum; import cn.cash.register.enums.TrafficTypeEnum; import cn.cash.register.service.GoodsInfoService; import cn.cash.register.service.GoodsStockService; import cn.cash.register.service.GoodsTrafficService; import cn.cash.register.util.Money; import cn.cash.register.util.NumUtil; /** * 商品货流服务接口实现类 * @author HuHui * @version $Id: GoodsTrafficServiceImpl.java, v 0.1 2018年4月25日 上午11:38:12 HuHui Exp $ */ @Service public class GoodsTrafficServiceImpl implements GoodsTrafficService { @Resource private GoodsTrafficMapper trafficMapper; @Resource private GoodsInfoService goodsInfoService; @Resource private TransactionTemplate txTemplate; @Resource private GoodsStockService stockService; @Override public Long addInTraffic(InTrafficRequest request) { GoodsTraffic traffic = convert(request); return txTemplate.execute(new TransactionCallback<Long>() { @Override public Long doInTransaction(TransactionStatus status) { //查询并修改商品信息 GoodsInfo goodsInfo = goodsInfoService.queryById(request.getGoodsId()); inUpdateGoodsInfo(goodsInfo, traffic); //记录库存变化 int flowCount = traffic.getInCount() + traffic.getFreeCount(); stockService.record(goodsInfo.getGoodsName(), goodsInfo.getBarCode(), StockFlowTypeEnum.TRAFFIC_IN, flowCount, traffic.getTrafficNo()); return trafficMapper.insertSelective(traffic); } }); } @Override public Long addOutTraffic(OutTrafficRequest request) { GoodsTraffic traffic = convert(request); return txTemplate.execute(new TransactionCallback<Long>() { @Override public Long doInTransaction(TransactionStatus status) { //查询并修改商品信息 GoodsInfo goodsInfo = goodsInfoService.queryById(request.getGoodsId()); outUpdateGoodsInfo(goodsInfo, traffic); //记录库存变化 int flowCount = -traffic.getOutCount();//负号 StockFlowTypeEnum typeEnum = null; if (StringUtils.equals(traffic.getTrafficType(), TrafficTypeEnum.ORDINARY_OUT.getCode())) { typeEnum = StockFlowTypeEnum.TRAFFIC_OUT; } else if (StringUtils.equals(traffic.getTrafficType(), TrafficTypeEnum.SUPPLIER_OUT.getCode())) { typeEnum = StockFlowTypeEnum.TRAFFIC_OUT_SUPPLIER; } stockService.record(goodsInfo.getGoodsName(), goodsInfo.getBarCode(), typeEnum, flowCount, traffic.getTrafficNo()); return trafficMapper.insertSelective(traffic); } }); } @Override public GoodsTraffic queryById(Long id) { return trafficMapper.selectByPrimaryKey(id); } @Override public PageInfo<GoodsTraffic> queryList(GoodsTrafficQueryRequest request) { PageHelper.startPage(request.getPageNum(), request.getPageSize()); PageHelper.orderBy(request.getSidx() + " " + request.getOrder()); List<GoodsTraffic> list = trafficMapper.list(request); return new PageInfo<GoodsTraffic>(list); } /** * 进货--修改商品信息属性值 */ private void inUpdateGoodsInfo(GoodsInfo goodsInfo, GoodsTraffic traffic) { //库存 int inStock = goodsInfo.getGoodsStock() + traffic.getInCount();//实际进货库存 int newTotalStock = inStock + traffic.getFreeCount();//实际总库存 //新加权进货价 = ((原库存*原加权进货价)+(入库数*进货价))/实际进货库存 Money newAvgPrice = ((goodsInfo.getAverageImportPrice().multiply(goodsInfo.getGoodsStock()))// .add((traffic.getInAmount().multiply(traffic.getInCount()))))// .divide(inStock); goodsInfo.setGoodsStock(newTotalStock); goodsInfo.setAverageImportPrice(newAvgPrice); goodsInfo.setLastImportPrice(traffic.getInAmount()); goodsInfoService.update(goodsInfo); } /** * 出库--修改商品信息属性值 */ private void outUpdateGoodsInfo(GoodsInfo goodsInfo, GoodsTraffic traffic) { //库存 int newTotalStock = goodsInfo.getGoodsStock() - traffic.getOutCount(); //新加权进货价 = 旧加权进货价 - (变动库存*(出货价 - 旧加权进货价)) / (原库存 - 变动库存) Money newAvgPrice = goodsInfo.getAverageImportPrice().subtract((traffic.getOutAmount().subtract(goodsInfo.getAverageImportPrice())).multiply(traffic.getOutCount() / newTotalStock)); goodsInfo.setGoodsStock(newTotalStock); goodsInfo.setAverageImportPrice(newAvgPrice); goodsInfoService.update(goodsInfo); } private GoodsTraffic convert(InTrafficRequest request) { GoodsTraffic traffic = new GoodsTraffic(); traffic.setTrafficNo(NumUtil.getTrafficNo()); traffic.setTrafficType(TrafficTypeEnum.IN.getCode()); traffic.setStatus(request.getStatus()); traffic.setGoodsName(request.getGoodsName()); traffic.setBarCode(request.getBarCode()); traffic.setGoodsColor(request.getGoodsColor()); traffic.setGoodsSize(request.getGoodsSize()); traffic.setSupplierName(request.getSupplierName()); traffic.setGoodsStock(request.getGoodsStock()); traffic.setInCount(request.getInCount()); if (StringUtils.isNotBlank(request.getInAmount())) { traffic.setInAmount(new Money(request.getInAmount())); } traffic.setFreeCount(request.getFreeCount()); if (StringUtils.isNotBlank(request.getAdvancePaymentAmount())) { traffic.setAdvancePaymentAmount(new Money(request.getAdvancePaymentAmount())); } traffic.setQuantityUnit(request.getQuantityUnit()); if (StringUtils.isNotBlank(request.getTotalAmount())) { traffic.setTotalAmount(new Money(request.getTotalAmount())); } traffic.setOperatorNo(request.getOperatorNo()); traffic.setRemark(request.getRemark()); traffic.setGmtCreate(new Date()); return traffic; } private GoodsTraffic convert(OutTrafficRequest request) { GoodsTraffic traffic = new GoodsTraffic(); traffic.setTrafficNo(NumUtil.getTrafficNo()); traffic.setTrafficType(request.getTrafficType()); traffic.setStatus(true); traffic.setGoodsName(request.getGoodsName()); traffic.setBarCode(request.getBarCode()); traffic.setGoodsColor(request.getGoodsColor()); traffic.setGoodsSize(request.getGoodsSize()); traffic.setSupplierName(request.getSupplierName()); traffic.setGoodsStock(request.getGoodsStock()); traffic.setQuantityUnit(request.getQuantityUnit()); traffic.setOutPriceType(request.getOutPriceType()); if (StringUtils.isNotBlank(request.getOutAmount())) { traffic.setOutAmount(new Money(request.getOutAmount())); } traffic.setOutCount(request.getOutCount()); if (StringUtils.isNotBlank(request.getTotalAmount())) { traffic.setTotalAmount(new Money(request.getTotalAmount())); } traffic.setOperatorNo(request.getOperatorNo()); traffic.setRemark(request.getRemark()); traffic.setGmtCreate(new Date()); return traffic; } }
9235bf2d06bb0f71609245842c60d8bd655dfb93
2,601
java
Java
build/tmp/expandedArchives/forge-1.16.5-36.1.0_mapped_official_1.16.5-sources.jar_01fb3b8234f72f7172716347a075bc60/net/minecraft/world/storage/IServerConfiguration.java
Mortimyrrh/Mycelia-Forge
a71403c23cb7d267d73ec3de6a5a3228a65f2238
[ "MIT" ]
1
2021-01-04T11:34:52.000Z
2021-01-04T11:34:52.000Z
build/tmp/expandedArchives/forge-1.16.5-36.1.0_mapped_official_1.16.5-sources.jar_01fb3b8234f72f7172716347a075bc60/net/minecraft/world/storage/IServerConfiguration.java
Mortimyrrh/Mycelia-Forge
a71403c23cb7d267d73ec3de6a5a3228a65f2238
[ "MIT" ]
null
null
null
build/tmp/expandedArchives/forge-1.16.5-36.1.0_mapped_official_1.16.5-sources.jar_01fb3b8234f72f7172716347a075bc60/net/minecraft/world/storage/IServerConfiguration.java
Mortimyrrh/Mycelia-Forge
a71403c23cb7d267d73ec3de6a5a3228a65f2238
[ "MIT" ]
null
null
null
26.540816
91
0.73664
997,401
package net.minecraft.world.storage; import com.mojang.serialization.Lifecycle; import java.util.Set; import javax.annotation.Nullable; import net.minecraft.crash.CrashReportCategory; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.datafix.codec.DatapackCodec; import net.minecraft.util.registry.DynamicRegistries; import net.minecraft.world.Difficulty; import net.minecraft.world.GameRules; import net.minecraft.world.GameType; import net.minecraft.world.WorldSettings; import net.minecraft.world.gen.settings.DimensionGeneratorSettings; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; public interface IServerConfiguration { DatapackCodec getDataPackConfig(); void setDataPackConfig(DatapackCodec p_230410_1_); boolean wasModded(); Set<String> getKnownServerBrands(); void setModdedInfo(String p_230412_1_, boolean p_230412_2_); default void fillCrashReportCategory(CrashReportCategory p_85118_1_) { p_85118_1_.setDetail("Known server brands", () -> { return String.join(", ", this.getKnownServerBrands()); }); p_85118_1_.setDetail("Level was modded", () -> { return Boolean.toString(this.wasModded()); }); p_85118_1_.setDetail("Level storage version", () -> { int i = this.getVersion(); return String.format("0x%05X - %s", i, this.getStorageVersionName(i)); }); } default String getStorageVersionName(int p_237379_1_) { switch(p_237379_1_) { case 19132: return "McRegion"; case 19133: return "Anvil"; default: return "Unknown?"; } } @Nullable CompoundNBT getCustomBossEvents(); void setCustomBossEvents(@Nullable CompoundNBT p_230414_1_); IServerWorldInfo overworldData(); @OnlyIn(Dist.CLIENT) WorldSettings getLevelSettings(); CompoundNBT createTag(DynamicRegistries p_230411_1_, @Nullable CompoundNBT p_230411_2_); boolean isHardcore(); int getVersion(); String getLevelName(); GameType getGameType(); void setGameType(GameType p_230392_1_); boolean getAllowCommands(); Difficulty getDifficulty(); void setDifficulty(Difficulty p_230409_1_); boolean isDifficultyLocked(); void setDifficultyLocked(boolean p_230415_1_); GameRules getGameRules(); CompoundNBT getLoadedPlayerTag(); CompoundNBT endDragonFightData(); void setEndDragonFightData(CompoundNBT p_230413_1_); DimensionGeneratorSettings worldGenSettings(); @OnlyIn(Dist.CLIENT) Lifecycle worldGenSettingsLifecycle(); }
9235c06b53e753bf1488c950ccbb7a0a83b700f7
488
java
Java
src/examples/adaptive/Password.java
isstac/spf-sca
11e4c6eb4c1a19d68f2e66ec81c683eba7f93b12
[ "MIT" ]
4
2018-02-02T03:01:02.000Z
2020-10-02T13:14:23.000Z
src/examples/adaptive/Password.java
isstac/spf-sca
11e4c6eb4c1a19d68f2e66ec81c683eba7f93b12
[ "MIT" ]
null
null
null
src/examples/adaptive/Password.java
isstac/spf-sca
11e4c6eb4c1a19d68f2e66ec81c683eba7f93b12
[ "MIT" ]
null
null
null
16.266667
56
0.668033
997,402
package adaptive; import multirun.adaptive.SymbolicAdaptiveExample; public class Password extends SymbolicAdaptiveExample { static{ init("src/examples/adaptive/Password.jpf"); } // binary search public static int check(int h, int l) { if(h != l){ return 0; } return 1; } public static void main(String[] args) { Password test = new Password(); test.adaptiveAttack(args); } @Override public int cost(int[] h, int[] l) { return check(h[0], l[0]); } }
9235c237bf336e2b7386cd2ee7c34411e41690f4
16,786
java
Java
core/metamodel/src/main/java/org/apache/isis/core/commons/config/IsisConfigurationDefault.java
kshithijiyer/isis
b99a6a9057fdcd4af25b0a2f36f7b32efa6f137c
[ "ECL-2.0", "Apache-2.0" ]
1
2019-03-17T03:19:33.000Z
2019-03-17T03:19:33.000Z
core/metamodel/src/main/java/org/apache/isis/core/commons/config/IsisConfigurationDefault.java
DalavanCloud/isis
2af2ef3e2edcb807d742f089839e0571d8132bd9
[ "Apache-2.0" ]
null
null
null
core/metamodel/src/main/java/org/apache/isis/core/commons/config/IsisConfigurationDefault.java
DalavanCloud/isis
2af2ef3e2edcb807d742f089839e0571d8132bd9
[ "Apache-2.0" ]
null
null
null
32.978389
126
0.608602
997,403
/* * 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.isis.core.commons.config; import java.awt.Color; import java.awt.Font; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.isis.applib.annotation.Programmatic; import org.apache.isis.applib.services.config.ConfigurationProperty; import org.apache.isis.core.commons.exceptions.IsisException; import org.apache.isis.core.commons.resource.ResourceStreamSource; import org.apache.isis.core.metamodel.services.ServicesInjector; import org.apache.isis.core.metamodel.services.configinternal.ConfigurationServiceInternal; /** * This object will typically be registered as the implementation of the {@link ConfigurationServiceInternal} * (internal) domain service, using * {@link ServicesInjector#addFallbackIfRequired(Class, Object)}. * * <p> * If an integration test is running, then the <code>IsisConfigurationForJdoIntegTests</code> will be used instead. * </p> */ public class IsisConfigurationDefault implements ConfigurationServiceInternal { private static final Logger LOG = LoggerFactory.getLogger(IsisConfigurationDefault.class); private final ResourceStreamSource resourceStreamSource; private final Properties properties = new Properties(); /** * derived lazily from {@link #properties}. */ private Properties applicationProperties; // //////////////////////////////////////////////// // Constructor // //////////////////////////////////////////////// public IsisConfigurationDefault() { this(null); } public IsisConfigurationDefault(final ResourceStreamSource resourceStreamSource) { this.resourceStreamSource = resourceStreamSource; LOG.debug("configuration initialised with stream: {}", nameOf(resourceStreamSource)); } private String nameOf(final ResourceStreamSource resourceStreamSource) { return resourceStreamSource != null ? resourceStreamSource.getName() : null; } // //////////////////////////////////////////////// // ResourceStreamSource // //////////////////////////////////////////////// @Override public ResourceStreamSource getResourceStreamSource() { return resourceStreamSource; } // //////////////////////////////////////////////// // add // //////////////////////////////////////////////// /** * How to handle the case when the configuration already contains the key being added. */ public enum ContainsPolicy { /** * If the configuration already contains the key, then ignore the new value. */ IGNORE, /** * If the configuration already contains the key, then overwrite with the new. */ OVERWRITE, /** * If the configuration already contains the key, then throw an exception. */ EXCEPTION } /** * Add the properties from an existing Properties object. */ @Programmatic public void add(final Properties properties, final ContainsPolicy containsPolicy) { for(Object key: properties.keySet()) { Object value = properties.get(key); addPerPolicy((String) key, (String) value, containsPolicy); } } /** * Adds a key-value pair to this set of properties; if the key exists in the configuration then will be ignored. * * <p> * @see #addPerPolicy(String, String, ContainsPolicy) * @see #put(String, String) */ @Programmatic public void add(final String key, final String value) { addPerPolicy(key, value, ContainsPolicy.IGNORE); } /** * Adds a key-value pair to this set of properties; if the key exists in the configuration then will be replaced. * * <p> * @see #add(String, String) * @see #addPerPolicy(String, String, ContainsPolicy) */ @Programmatic public void put(final String key, final String value) { addPerPolicy(key, value, ContainsPolicy.OVERWRITE); } /** * Adds a key-value pair to this set of properties; if the key exists in the configuration then the * {@link ContainsPolicy} will be applied. * * @see #add(String, String) * @see #put(String, String) */ private void addPerPolicy(final String key, final String value, final ContainsPolicy policy) { if (value == null) { LOG.debug("ignoring {} as value is null", key); return; } if (key == null) { return; } if (properties.containsKey(key)) { switch (policy) { case IGNORE: LOG.debug("ignoring {}={} as value already set (with {})", key, value, properties.get(key)); break; case OVERWRITE: LOG.debug("overwriting {}={} (previous value was {})", key, value, properties.get(key)); properties.put(key, value); break; case EXCEPTION: throw new IllegalStateException(String.format( "Configuration already has a key {}, value of {}%s, value of %s", key, properties.get(key))); } } else { LOG.debug("adding {} = {}", key , safe(key, value)); properties.put(key, value); } } static String safe(final String key, final String value) { return ConfigurationProperty.Util.maskIfProtected(key, value); } @Override public IsisConfiguration createSubset(final String prefix) { final IsisConfigurationDefault subset = new IsisConfigurationDefault(resourceStreamSource); String startsWith = prefix; if (!startsWith.endsWith(".")) { startsWith = startsWith + '.'; } final int prefixLength = startsWith.length(); for(Object keyObj: properties.keySet()) { final String key = (String)keyObj; if (key.startsWith(startsWith)) { final String modifiedKey = key.substring(prefixLength); subset.properties.put(modifiedKey, properties.get(key)); } } return subset; } // //////////////////////////////////////////////// // getXxx // //////////////////////////////////////////////// /** * Gets the boolean value for the specified name where no value or 'on' will * result in true being returned; anything gives false. If no boolean * property is specified with this name then false is returned. * * @param name * the property name */ @Override public boolean getBoolean(final String name) { return getBoolean(name, false); } /** * Gets the boolean value for the specified name. If no property is * specified with this name then the specified default boolean value is * returned. * * @param name * the property name * @param defaultValue * the value to use as a default */ @Override public boolean getBoolean(final String name, final boolean defaultValue) { String value = getPropertyElseNull(name); if (value == null) { return defaultValue; } value = value.toLowerCase(); if (value.equals("on") || value.equals("yes") || value.equals("true") || value.equals("")) { return true; } if (value.equals("off") || value.equals("no") || value.equals("false")) { return false; } throw new IsisConfigurationException("Illegal flag for " + name + "; must be one of on, off, yes, no, true or false"); } /** * Gets the color for the specified name. If no color property is specified * with this name then null is returned. * * @param name * the property name */ @Override public Color getColor(final String name) { return getColor(name, null); } /** * Gets the color for the specified name. If no color property is specified * with this name then the specified default color is returned. * * @param name * the property name * @param defaultValue * the value to use as a default */ @Override public Color getColor(final String name, final Color defaultValue) { final String color = getPropertyElseNull(name); if (color == null) { return defaultValue; } return Color.decode(color); } /** * Gets the font for the specified name. If no font property is specified * with this name then null is returned. * * @param name * the property name */ @Override public Font getFont(final String name) { return getFont(name, null); } /** * Gets the font for the specified name. If no font property is specified * with this name then the specified default font is returned. * * @param name * the property name * @param defaultValue * the color to use as a default */ @Override public Font getFont(final String name, final Font defaultValue) { final String font = getPropertyElseNull(name); if (font == null) { return defaultValue; } return Font.decode(font); } /** * Gets the number value for the specified name. If no property is specified * with this name then 0 is returned. * * @param name * the property name */ @Override public int getInteger(final String name) { return getInteger(name, 0); } /** * Gets the number value for the specified name. If no property is specified * with this name then the specified default number value is returned. * * @param name * the property name * @param defaultValue * the value to use as a default */ @Override public int getInteger(final String name, final int defaultValue) { final String value = getPropertyElseNull(name); if (value == null) { return defaultValue; } return Integer.valueOf(value).intValue(); } @Override public String[] getList(final String name) { final String listAsCommaSeparatedArray = getString(name); return stringAsList(listAsCommaSeparatedArray); } @Override public String[] getList(String name, String defaultListAsCommaSeparatedArray) { final String listAsCommaSeparatedArray = getString(name, defaultListAsCommaSeparatedArray); return stringAsList(listAsCommaSeparatedArray); } private String[] stringAsList(String list) { if (list == null) { return new String[0]; } else { final StringTokenizer tokens = new StringTokenizer(list, ConfigurationConstants.LIST_SEPARATOR); final String array[] = new String[tokens.countTokens()]; int i = 0; while (tokens.hasMoreTokens()) { array[i++] = tokens.nextToken().trim(); } return array; } } @Override public IsisConfiguration getProperties(final String withPrefix) { final int prefixLength = "".length(); final Properties properties = new Properties(); final Enumeration<?> e = this.properties.keys(); while (e.hasMoreElements()) { final String key = (String) e.nextElement(); if (key.startsWith(withPrefix)) { final String modifiedKey = key.substring(prefixLength); properties.put(modifiedKey, this.properties.get(key)); } } final IsisConfigurationDefault isisConfigurationDefault = new IsisConfigurationDefault(resourceStreamSource); isisConfigurationDefault.add(properties, ContainsPolicy.IGNORE); return isisConfigurationDefault; } private String getPropertyElseNull(final String name) { return getProperty(name, null); } private String getProperty(final String name, final String defaultValue) { final String key = referedToAs(name); if (key.indexOf("..") >= 0) { throw new IsisException("property names should not have '..' within them: " + name); } String property = properties.getProperty(key, defaultValue); property = property != null ? property.trim() : null; LOG.debug("get property: '{} = '{}'", key, property); return property; } /** * Returns the configuration property with the specified name. If there is * no matching property then null is returned. */ @Override public String getString(final String name) { return getPropertyElseNull(name); } @Override public String getString(final String name, final String defaultValue) { return getProperty(name, defaultValue); } @Override public boolean hasProperty(final String name) { final String key = referedToAs(name); return properties.containsKey(key); } @Override public boolean isEmpty() { return properties.isEmpty(); } @Override public Iterator<String> iterator() { return asIterable().iterator(); } @Override public Iterable<String> asIterable() { return properties.stringPropertyNames(); } /** * Returns as a String that the named property is refered to as. For example * in a simple properties file the property z might be specified in the file * as x.y.z. */ private String referedToAs(final String name) { return name; } @Override public int size() { return properties.size(); } @Override public String toString() { return "ConfigurationParameters [properties=" + properties + "]"; } // //////////////////////////////////////////////////////////////////// // injectInto // //////////////////////////////////////////////////////////////////// @Override public Map<String,String> asMap() { final Map<String, String> map = Maps.newHashMap(); for(String propertyName: this.asIterable()) { final String propertyValue = this.getPropertyElseNull(propertyName); map.put(propertyName, propertyValue); } return map; } //region > ConfigurationService impl @Override public String getProperty(final String name) { initAppPropertiesIfRequired(); return applicationProperties.getProperty(name); } private void initAppPropertiesIfRequired() { if(applicationProperties == null) { applicationProperties = deriveApplicationProperties(); } } private Properties deriveApplicationProperties() { final Properties applicationProperties = new Properties(); final IsisConfiguration applicationConfiguration = getProperties("application"); for (final String key : applicationConfiguration.asIterable()) { final String value = applicationConfiguration.getString(key); final String newKey = key.substring("application.".length()); applicationProperties.setProperty(newKey, value); } return applicationProperties; } @Override public List<String> getPropertyNames() { initAppPropertiesIfRequired(); final List<String> list = Lists.newArrayList(); for (final Object key : applicationProperties.keySet()) { list.add((String) key); } return list; } //endregion }
9235c3c5082efa63a2246c4a43f966b7777796fa
1,157
java
Java
src/com/algorithm/medium/_94.java
sch-git/LeetCode
c6bc4665a6861bef73ea04db5c169de21b83e8fe
[ "Apache-2.0" ]
null
null
null
src/com/algorithm/medium/_94.java
sch-git/LeetCode
c6bc4665a6861bef73ea04db5c169de21b83e8fe
[ "Apache-2.0" ]
null
null
null
src/com/algorithm/medium/_94.java
sch-git/LeetCode
c6bc4665a6861bef73ea04db5c169de21b83e8fe
[ "Apache-2.0" ]
null
null
null
21.425926
58
0.538462
997,404
package com.algorithm.medium; import java.util.ArrayList; import java.util.List; import java.util.Stack; /** * @Solution: 二叉树遍历框架 * @Title: 二叉树的中序遍历 * @Description: 给定一个二叉树,返回它的中序 遍历。 * @Author: chenghao.su * @Date: 2020/2/24 22:18 */ public class _94 { public static void main(String[] args) { } /** * 栈不为空或当前节点存在,进入循环(弹出root节点时,栈为空而右子树还没有遍历) * 往栈中添加当前节点,当前节点变为左孩子 * 当前节点为空时退出循环,说明已经没有左节点了 * 将栈顶元素弹出,加入结果集,查找它的右子树 * * @param root * @return */ public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); TreeNode node = root; while (!stack.isEmpty() || node != null) { while (node != null) { stack.push(node); node = node.left; } node = stack.pop(); result.add(node.val); node = node.right; } return result; } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } } }
9235c3e0fbd89f1cf8853ff77f2624406be51d84
2,973
java
Java
mod_xerces/src/main/java/org/apache/xerces/impl/dv/dtd/XML11IDDatatypeValidator.java
zhanyanjie6796/JFugue-for-Android
61b1cc52fe97e70af3e868b8a8d5398deff094c0
[ "Apache-2.0" ]
67
2015-01-03T22:34:54.000Z
2021-07-07T12:11:40.000Z
mod_xerces/src/main/java/org/apache/xerces/impl/dv/dtd/XML11IDDatatypeValidator.java
zhanyanjie6796/JFugue-for-Android
61b1cc52fe97e70af3e868b8a8d5398deff094c0
[ "Apache-2.0" ]
10
2015-01-01T20:38:17.000Z
2021-06-27T18:02:14.000Z
mod_xerces/src/main/java/org/apache/xerces/impl/dv/dtd/XML11IDDatatypeValidator.java
zhanyanjie6796/JFugue-for-Android
61b1cc52fe97e70af3e868b8a8d5398deff094c0
[ "Apache-2.0" ]
24
2015-04-01T16:21:11.000Z
2022-02-15T07:26:36.000Z
34.976471
106
0.676757
997,405
/* * Copyright 1999-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.impl.dv.dtd; import org.apache.xerces.impl.dv.*; import org.apache.xerces.util.XML11Char; /** * <P>IDDatatypeValidator - ID represents the ID attribute * type from XML 1.1 Recommendation. The value space * of ID is the set of all strings that match the * NCName production and have been used in an XML * document. The lexical space of ID is the set of all * strings that match the NCName production.</P> * <P>The value space of ID is scoped to a specific * instance document.</P> * <P>The following constraint applies: * An ID must not appear more than once in an XML * document as a value of this type; i.e., ID values * must uniquely identify the elements which bear * them.</P> * * @xerces.internal * * @author Jeffrey Rodriguez, IBM * @author Sandy Gao, IBM * @author Neil Graham, IBM * * @version $Id: XML11IDDatatypeValidator.java 320097 2004-10-06 14:56:52Z mrglavas $ */ public class XML11IDDatatypeValidator extends IDDatatypeValidator { // construct an ID datatype validator public XML11IDDatatypeValidator() { super(); } /** * Checks that "content" string is valid ID value. * If invalid a Datatype validation exception is thrown. * * @param content the string value that needs to be validated * @param context the validation context * @throws InvalidDatatypeException if the content is * invalid according to the rules for the validators * @see InvalidDatatypeValueException */ public void validate(String content, ValidationContext context) throws InvalidDatatypeValueException { //Check if is valid key-[81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')* if(context.useNamespaces()) { if (!XML11Char.isXML11ValidNCName(content)) { throw new InvalidDatatypeValueException("IDInvalidWithNamespaces", new Object[]{content}); } } else { if (!XML11Char.isXML11ValidName(content)) { throw new InvalidDatatypeValueException("IDInvalid", new Object[]{content}); } } if (context.isIdDeclared(content)) { throw new InvalidDatatypeValueException("IDNotUnique", new Object[]{content}); } context.addId(content); } }
9235c412543a672a2d3044a910d88906f618eb0b
11,271
java
Java
ocridcardlibrary/src/main/java/com/kernal/passportreader/sdk/utils/CameraConfigurationManager.java
YassKnight/PassportReader
1e1d3b4ec36c4e4e478ec6506664ab6eb3e7e001
[ "Apache-2.0" ]
null
null
null
ocridcardlibrary/src/main/java/com/kernal/passportreader/sdk/utils/CameraConfigurationManager.java
YassKnight/PassportReader
1e1d3b4ec36c4e4e478ec6506664ab6eb3e7e001
[ "Apache-2.0" ]
null
null
null
ocridcardlibrary/src/main/java/com/kernal/passportreader/sdk/utils/CameraConfigurationManager.java
YassKnight/PassportReader
1e1d3b4ec36c4e4e478ec6506664ab6eb3e7e001
[ "Apache-2.0" ]
null
null
null
34.362805
148
0.597906
997,406
package com.kernal.passportreader.sdk.utils; import android.content.Context; import android.graphics.Point; import android.hardware.Camera; import android.view.Display; import android.view.Surface; import android.view.WindowManager; import java.util.Collection; import java.util.List; import java.util.regex.Pattern; import kernal.idcard.camera.CardOcrRecogConfigure; public final class CameraConfigurationManager { private static final int TEN_DESIRED_ZOOM = 27; private static final Pattern COMMA_PATTERN = Pattern.compile(","); private final Context mContext; private Point mScreenResolution; private Point mCameraResolution; private Point mPreviewResolution; public CameraConfigurationManager(Context context) { mContext = context; } public void initFromCameraParameters(Camera camera) { Camera.Parameters parameters = camera.getParameters(); if (CameraConfigurationManager.autoFocusAble(camera)) { parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); } mScreenResolution = CardScreenUtil.getScreenResolution(mContext); Point screenResolutionForCamera = new Point(); screenResolutionForCamera.x = mScreenResolution.x; screenResolutionForCamera.y = mScreenResolution.y; // preview size is always something like 480*320, other 320*480 int orientation = CardScreenUtil.getScreenOrientation(mContext); if (orientation == CardScreenUtil.ORIENTATION_PORTRAIT) { screenResolutionForCamera.x = mScreenResolution.y; screenResolutionForCamera.y = mScreenResolution.x; } if ((float) screenResolutionForCamera.x / screenResolutionForCamera.y == 0.75) { screenResolutionForCamera.x=1280; screenResolutionForCamera.y=960; // WriteUtil.writeLog("设置的目标分辨率1280X960"); mPreviewResolution = getPreviewResolution(parameters, screenResolutionForCamera); }/* else if((float) screenResolutionForCamera.x/screenResolutionForCamera.y<0.5625){ screenResolutionForCamera.x=1440; screenResolutionForCamera.y=720; WriteUtil.writeLog("设置的目标分辨率1440X720"); mPreviewResolution = getPreviewResolution(parameters, screenResolutionForCamera); }*/else{ // WriteUtil.writeLog("设置的目标分辨率1280X720"); if( CardOcrRecogConfigure.getInstance().nMainId==2010){ /** * 算法强烈要求 * 由于印度尼西亚身份证识别 * 需要高清图片所以设置成1080P */ screenResolutionForCamera.x=1920; screenResolutionForCamera.y=1080; }else{ screenResolutionForCamera.x=1280; screenResolutionForCamera.y=720; } mPreviewResolution = getPreviewResolution(parameters, screenResolutionForCamera); } // WriteUtil.writeLog("获取的预览分辨率为"+mPreviewResolution.x+"X"+mPreviewResolution.y); if (orientation == CardScreenUtil.ORIENTATION_PORTRAIT) { mCameraResolution = new Point(mPreviewResolution.y, mPreviewResolution.x); } else { mCameraResolution = mPreviewResolution; } } /** * 获取对焦方式 * @param camera * @return */ public static boolean autoFocusAble(Camera camera) { List<String> supportedFocusModes = camera.getParameters().getSupportedFocusModes(); String focusMode = findSettableValue(supportedFocusModes, Camera.Parameters.FOCUS_MODE_AUTO); return focusMode != null; } public Point getCameraResolution() { return mCameraResolution; } public Point getmPreviewResolution(){ return mPreviewResolution; } /** * 设置相机的参数 * @param camera */ public void setDesiredCameraParameters(Camera camera) { Camera.Parameters parameters = camera.getParameters(); parameters.setPreviewSize(mPreviewResolution.x, mPreviewResolution.y); setZoom(parameters); camera.setDisplayOrientation(getDisplayOrientation()); camera.setParameters(parameters); } /** * 开启闪光灯 * @param camera */ public void openFlashlight(Camera camera) { doSetTorch(camera, true); } /** * 关闭闪光灯 * @param camera */ public void closeFlashlight(Camera camera) { doSetTorch(camera, false); } private void doSetTorch(Camera camera, boolean newSetting) { Camera.Parameters parameters = camera.getParameters(); String flashMode; /** 是否支持闪光灯 */ if (newSetting) { flashMode = findSettableValue(parameters.getSupportedFlashModes(), Camera.Parameters.FLASH_MODE_TORCH, Camera.Parameters.FLASH_MODE_ON); } else { flashMode = findSettableValue(parameters.getSupportedFlashModes(), Camera.Parameters.FLASH_MODE_OFF); } if (flashMode != null) { parameters.setFlashMode(flashMode); } camera.setParameters(parameters); } /** * * @param supportedValues * @param desiredValues * @return */ private static String findSettableValue(Collection<String> supportedValues, String... desiredValues) { String result = null; if (supportedValues != null) { for (String desiredValue : desiredValues) { if (supportedValues.contains(desiredValue)) { result = desiredValue; break; } } } return result; } /** * 获取旋转角度 * @return */ public int getDisplayOrientation() { Camera.CameraInfo info = new Camera.CameraInfo(); Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, info); WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); int rotation = display.getRotation(); int degrees = 0; switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; } int result; if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { result = (info.orientation + degrees) % 360; result = (360 - result) % 360; } else { result = (info.orientation - degrees + 360) % 360; } return result; } /** * 获取预览分辨率 * @param parameters * @param screenResolution * @return */ private static Point getPreviewResolution(Camera.Parameters parameters, Point screenResolution) { Point previewResolution = findBestPreviewSizeValue(parameters.getSupportedPreviewSizes(), screenResolution); if (previewResolution == null) { previewResolution = new Point((screenResolution.x >> 3) << 3, (screenResolution.y >> 3) << 3); } return previewResolution; } /** * 获取合适的预览分辨率 * @param supportSizeList * @param screenResolution * @return */ private static Point findBestPreviewSizeValue(List<Camera.Size> supportSizeList, Point screenResolution) { int bestX = 0; int bestY = 0; int diff = Integer.MAX_VALUE; for (Camera.Size previewSize : supportSizeList) { int newX = previewSize.width; int newY = previewSize.height; // WriteUtil.writeLog("设备中预览分辨率"+newX+"X"+newY); int newDiff = Math.abs(newX - screenResolution.x) + Math.abs(newY - screenResolution.y); if (newDiff == 0) { bestX = newX; bestY = newY; break; } else if (newDiff < diff) { bestX = newX; bestY = newY; diff = newDiff; } } if (bestX > 0 && bestY > 0) { return new Point(bestX, bestY); } return null; } /** * 获取合适的缩放值 * @param stringValues * @param tenDesiredZoom * @return */ private static int findBestMotZoomValue(CharSequence stringValues, int tenDesiredZoom) { int tenBestValue = 0; for (String stringValue : COMMA_PATTERN.split(stringValues)) { stringValue = stringValue.trim(); double value; try { value = Double.parseDouble(stringValue); } catch (NumberFormatException nfe) { return tenDesiredZoom; } int tenValue = (int) (10.0 * value); if (Math.abs(tenDesiredZoom - value) < Math.abs(tenDesiredZoom - tenBestValue)) { tenBestValue = tenValue; } } return tenBestValue; } /** * 设置缩放 * @param parameters */ private void setZoom(Camera.Parameters parameters) { String zoomSupportedString = parameters.get("zoom-supported"); if (zoomSupportedString != null && !Boolean.parseBoolean(zoomSupportedString)) { return; } int tenDesiredZoom = TEN_DESIRED_ZOOM; String maxZoomString = parameters.get("max-zoom"); if (maxZoomString != null) { try { int tenMaxZoom = (int) (10.0 * Double.parseDouble(maxZoomString)); if (tenDesiredZoom > tenMaxZoom) { tenDesiredZoom = tenMaxZoom; } } catch (NumberFormatException nfe) { } } String takingPictureZoomMaxString = parameters.get("taking-picture-zoom-max"); if (takingPictureZoomMaxString != null) { try { int tenMaxZoom = Integer.parseInt(takingPictureZoomMaxString); if (tenDesiredZoom > tenMaxZoom) { tenDesiredZoom = tenMaxZoom; } } catch (NumberFormatException nfe) { } } String motZoomValuesString = parameters.get("mot-zoom-values"); if (motZoomValuesString != null) { tenDesiredZoom = findBestMotZoomValue(motZoomValuesString, tenDesiredZoom); } String motZoomStepString = parameters.get("mot-zoom-step"); if (motZoomStepString != null) { try { double motZoomStep = Double.parseDouble(motZoomStepString.trim()); int tenZoomStep = (int) (10.0 * motZoomStep); if (tenZoomStep > 1) { tenDesiredZoom -= tenDesiredZoom % tenZoomStep; } } catch (NumberFormatException nfe) { // continue } } if (maxZoomString != null || motZoomValuesString != null) { parameters.set("zoom", String.valueOf(tenDesiredZoom / 10.0)); } if (takingPictureZoomMaxString != null) { parameters.set("taking-picture-zoom", tenDesiredZoom); } } }
9235c48a3d531f16239e65bc379848739440505c
4,035
java
Java
sdk/src/test/java/io/opentelemetry/sdk/common/export/ConfigBuilderTest.java
RashmiRam/opentelemetry-java
9ddcb32a59db8f03742fbd957e1df84b720547b2
[ "Apache-2.0" ]
null
null
null
sdk/src/test/java/io/opentelemetry/sdk/common/export/ConfigBuilderTest.java
RashmiRam/opentelemetry-java
9ddcb32a59db8f03742fbd957e1df84b720547b2
[ "Apache-2.0" ]
null
null
null
sdk/src/test/java/io/opentelemetry/sdk/common/export/ConfigBuilderTest.java
RashmiRam/opentelemetry-java
9ddcb32a59db8f03742fbd957e1df84b720547b2
[ "Apache-2.0" ]
null
null
null
31.771654
99
0.72119
997,407
/* * Copyright 2020, OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.opentelemetry.sdk.common.export; import static com.google.common.truth.Truth.assertThat; import io.opentelemetry.sdk.common.export.ConfigBuilder.NamingConvention; import java.util.Collections; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link io.opentelemetry.sdk.common.export.ConfigBuilder}. */ @RunWith(JUnit4.class) public class ConfigBuilderTest { @Test public void normalize() { Map<String, String> dotValues = NamingConvention.DOT.normalize(Collections.singletonMap("Test.Config.Key", "value")); assertThat(dotValues).containsEntry("test.config.key", "value"); Map<String, String> envValue = NamingConvention.ENV_VAR.normalize(Collections.singletonMap("TEST_CONFIG_KEY", "value")); assertThat(envValue).containsEntry("test.config.key", "value"); } @Test public void booleanProperty() { Boolean booleanProperty = ConfigBuilder.getBooleanProperty("boolean", Collections.singletonMap("boolean", "true")); assertThat(booleanProperty).isTrue(); } @Test public void longProperty() { Long longProperty = ConfigBuilder.getLongProperty("long", Collections.singletonMap("long", "42343")); assertThat(longProperty).isEqualTo(42343); } @Test public void intProperty() { Integer intProperty = ConfigBuilder.getIntProperty("int", Collections.singletonMap("int", "43543")); assertThat(intProperty).isEqualTo(43543); } @Test public void doubleProperty() { Double doubleProperty = ConfigBuilder.getDoubleProperty("double", Collections.singletonMap("double", "5.6")); assertThat(doubleProperty).isEqualTo(5.6); } @Test public void invalidBooleanProperty() { Boolean booleanProperty = ConfigBuilder.getBooleanProperty("boolean", Collections.singletonMap("boolean", "23435")); assertThat(booleanProperty).isFalse(); } @Test public void invalidLongProperty() { Long longProperty = ConfigBuilder.getLongProperty("long", Collections.singletonMap("long", "45.6")); assertThat(longProperty).isNull(); } @Test public void invalidIntProperty() { Integer intProperty = ConfigBuilder.getIntProperty("int", Collections.singletonMap("int", "false")); assertThat(intProperty).isNull(); } @Test public void invalidDoubleProperty() { Double doubleProperty = ConfigBuilder.getDoubleProperty("double", Collections.singletonMap("double", "something")); assertThat(doubleProperty).isNull(); } @Test public void nullValue_BooleanProperty() { Boolean booleanProperty = ConfigBuilder.getBooleanProperty("boolean", Collections.<String, String>emptyMap()); assertThat(booleanProperty).isNull(); } @Test public void nullValue_LongProperty() { Long longProperty = ConfigBuilder.getLongProperty("long", Collections.<String, String>emptyMap()); assertThat(longProperty).isNull(); } @Test public void nullValue_IntProperty() { Integer intProperty = ConfigBuilder.getIntProperty("int", Collections.<String, String>emptyMap()); assertThat(intProperty).isNull(); } @Test public void nullValue_DoubleProperty() { Double doubleProperty = ConfigBuilder.getDoubleProperty("double", Collections.<String, String>emptyMap()); assertThat(doubleProperty).isNull(); } }
9235c48c98ecacb1a9c49ed9b6ea3c87362d417d
3,925
java
Java
projects/asw-830-grpc/b-restaurant/restaurant-server/src/main/java/asw/efood/restaurantservice/grpc/RestaurantServiceGrpcServer.java
HalfWeight/asw
c34cf9f8becde687aef2b4538201effd416ad74f
[ "MIT" ]
30
2016-03-10T22:59:38.000Z
2022-03-08T10:33:03.000Z
projects/asw-830-grpc/b-restaurant/restaurant-server/src/main/java/asw/efood/restaurantservice/grpc/RestaurantServiceGrpcServer.java
HalfWeight/asw
c34cf9f8becde687aef2b4538201effd416ad74f
[ "MIT" ]
null
null
null
projects/asw-830-grpc/b-restaurant/restaurant-server/src/main/java/asw/efood/restaurantservice/grpc/RestaurantServiceGrpcServer.java
HalfWeight/asw
c34cf9f8becde687aef2b4538201effd416ad74f
[ "MIT" ]
44
2016-03-03T09:05:10.000Z
2021-11-09T09:10:44.000Z
37.380952
127
0.638471
997,408
package asw.efood.restaurantservice.grpc; import asw.efood.restaurantservice.domain.*; import asw.efood.restaurantservice.api.grpc.*; import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.stub.StreamObserver; import java.util.logging.Logger; import java.util.*; import java.util.stream.*; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.IOException; import org.springframework.stereotype.Component; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @Component public class RestaurantServiceGrpcServer { private static final Logger logger = Logger.getLogger(RestaurantServiceGrpcServer.class.toString()); @Autowired private RestaurantService restaurantService; @Value("${asw.efood.restaurantservice.grpc.port}") private int port; private Server server; @PostConstruct public void start() throws IOException { server = ServerBuilder.forPort(port) .addService(new RestaurantServiceImpl()) .build() .start(); logger.info("Server started, listening on " + port); } @PreDestroy public void stop() { if (server != null) { logger.info("*** shutting down gRPC server since JVM is shutting down"); server.shutdown(); logger.info("*** server shut down"); } } private class RestaurantServiceImpl extends RestaurantServiceGrpc.RestaurantServiceImplBase { @Override public void createRestaurant(CreateRestaurantRequest req, StreamObserver<CreateRestaurantReply> responseObserver) { String name = req.getName(); String location = req.getLocation(); logger.info("gRPC CALL: createRestaurant " + name + ", " + location); Restaurant restaurant = restaurantService.createRestaurant(name, location); CreateRestaurantReply reply = CreateRestaurantReply.newBuilder() .setRestaurantId(restaurant.getId()) .build(); responseObserver.onNext(reply); responseObserver.onCompleted(); } @Override public void getRestaurant(GetRestaurantRequest req, StreamObserver<GetRestaurantReply> responseObserver) { Long restaurantId = req.getRestaurantId(); logger.info("gRPC CALL: getRestaurant " + restaurantId); Restaurant restaurant = restaurantService.getRestaurant(restaurantId); GetRestaurantReply reply = GetRestaurantReply.newBuilder() .setRestaurantId(restaurant.getId()) .setName(restaurant.getName()) .setLocation(restaurant.getLocation()) .build(); responseObserver.onNext(reply); responseObserver.onCompleted(); } @Override public void getAllRestaurants(GetAllRestaurantsRequest req, StreamObserver<GetAllRestaurantsReply> responseObserver) { logger.info("gRPC CALL: getAllRestaurants"); Collection<Restaurant> restaurants = restaurantService.getAllRestaurants(); List<GetRestaurantReply> rr = restaurants.stream() .map(restaurant -> GetRestaurantReply.newBuilder() .setRestaurantId(restaurant.getId()) .setName(restaurant.getName()) .setLocation(restaurant.getLocation()) .build()) .collect(Collectors.toList()); GetAllRestaurantsReply reply = GetAllRestaurantsReply.newBuilder() .addAllRestaurants(rr) .build(); responseObserver.onNext(reply); responseObserver.onCompleted(); } } }
9235c60ac0884d54a030d0da45dffeae5bc8b5c3
942
java
Java
No910To920/ReverseOnlyLetters_917.java
Yankfu/LeetCode
bce241e0cb4733c3eda75990398fde2f4e47cba5
[ "Apache-2.0" ]
null
null
null
No910To920/ReverseOnlyLetters_917.java
Yankfu/LeetCode
bce241e0cb4733c3eda75990398fde2f4e47cba5
[ "Apache-2.0" ]
null
null
null
No910To920/ReverseOnlyLetters_917.java
Yankfu/LeetCode
bce241e0cb4733c3eda75990398fde2f4e47cba5
[ "Apache-2.0" ]
null
null
null
26.166667
74
0.4862
997,409
package no910To920; public class ReverseOnlyLetters_917 { public static void main(String[] args) { System.out.println(reverseOnlyLetters("a-bC-dEf-ghIj")); } public static String reverseOnlyLetters(String s) { int n = s.length(); char[] arr = s.toCharArray(); int left = 0, right = n - 1; while (true) { while (left < right && !Character.isLetter(s.charAt(left))) { left++; } while (right > left && !Character.isLetter(s.charAt(right))) { right--; } if (left >= right) { break; } swap(arr, left, right); left++; right--; } return new String(arr); } public static void swap(char[] arr, int left, int right) { char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } }
9235c6d85bf65f1242300155f94842011e521523
1,764
java
Java
src/main/java/me/paulf/minecraftmania/WordBlacklist.java
pau101/Minecraft-Mania
4e994c12234dd34a4f5d3bb3b67dab4f45c56ef4
[ "MIT" ]
1
2020-03-22T09:20:17.000Z
2020-03-22T09:20:17.000Z
src/main/java/me/paulf/minecraftmania/WordBlacklist.java
pau101/Minecraft-Mania
4e994c12234dd34a4f5d3bb3b67dab4f45c56ef4
[ "MIT" ]
null
null
null
src/main/java/me/paulf/minecraftmania/WordBlacklist.java
pau101/Minecraft-Mania
4e994c12234dd34a4f5d3bb3b67dab4f45c56ef4
[ "MIT" ]
null
null
null
37.531915
129
0.744898
997,410
package me.paulf.minecraftmania; import com.google.common.collect.ImmutableList; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.ReloadListener; import net.minecraft.profiler.IProfiler; import net.minecraft.resources.IResource; import net.minecraft.resources.IResourceManager; import net.minecraft.util.ResourceLocation; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; public class WordBlacklist extends ReloadListener<ImmutableList<String>> { private static final Logger LOGGER = LogManager.getLogger(); private static final ResourceLocation PATH = new ResourceLocation(MinecraftMania.ID, "texts/word_blacklist.txt"); private ImmutableList<String> words = ImmutableList.of(); public ImmutableList<String> getWords() { return this.words; } @Override protected ImmutableList<String> prepare(final IResourceManager manager, final IProfiler profiler) { try ( final IResource res = Minecraft.getInstance().getResourceManager().getResource(PATH); final BufferedReader reader = new BufferedReader(new InputStreamReader(res.getInputStream(), StandardCharsets.UTF_8)) ) { return reader.lines().map(String::trim).collect(ImmutableList.toImmutableList()); } catch (final IOException e) { LOGGER.warn("Problem loading blacklist", e); return ImmutableList.of(); } } @Override protected void apply(final ImmutableList<String> words, final IResourceManager manager, final IProfiler profiler) { this.words = words; } }
9235c82f541abe799f72f31dedab95f0d873c0fa
92
java
Java
springockito/src/test/java/org/kubek2k/mockito/spring/MockitoMockAutowiringIntegrationTest.java
zxybird/springockito
3596673fdc44b1738325fded4f5f832446eeff83
[ "Unlicense", "MIT" ]
46
2015-10-02T12:19:15.000Z
2021-09-24T15:02:54.000Z
springockito/src/test/java/org/kubek2k/mockito/spring/MockitoMockAutowiringIntegrationTest.java
zxybird/springockito
3596673fdc44b1738325fded4f5f832446eeff83
[ "Unlicense", "MIT" ]
5
2016-10-26T16:49:16.000Z
2018-08-21T14:00:47.000Z
springockito/src/test/java/org/kubek2k/mockito/spring/MockitoMockAutowiringIntegrationTest.java
zxybird/springockito
3596673fdc44b1738325fded4f5f832446eeff83
[ "Unlicense", "MIT" ]
24
2015-10-25T18:48:39.000Z
2021-02-22T09:29:27.000Z
15.333333
51
0.836957
997,411
package org.kubek2k.mockito.spring; public class MockitoMockAutowiringIntegrationTest { }
9235c836db5bf869d444cc02dafb81d685e837bb
751
java
Java
Updater/src/main/java/updater/ModernProgressBar.java
ParkerTenBroeck/MIPS
87a28059e61064ba6adafc392743d2f8f48f75c7
[ "Apache-2.0" ]
3
2020-11-04T00:03:41.000Z
2020-11-30T00:35:39.000Z
Updater/src/main/java/updater/ModernProgressBar.java
ParkerTenBroeck/MIPS
87a28059e61064ba6adafc392743d2f8f48f75c7
[ "Apache-2.0" ]
27
2020-09-01T00:44:10.000Z
2021-05-10T15:59:46.000Z
Updater/src/main/java/updater/ModernProgressBar.java
ParkerTenBroeck/MIPS
87a28059e61064ba6adafc392743d2f8f48f75c7
[ "Apache-2.0" ]
1
2020-12-05T00:14:11.000Z
2020-12-05T00:14:11.000Z
25.896552
96
0.676431
997,412
/* * 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 updater; import java.awt.Color; import java.awt.Graphics; import javax.swing.JProgressBar; /** * * @author parke */ public class ModernProgressBar extends JProgressBar { private Color onColor = new Color(70, 70, 70); private Color offColor = new Color(110, 110, 110); @Override public void paint(Graphics g) { g.setColor(offColor); g.fillRect(0, 0, this.getWidth(), this.getHeight()); g.setColor(onColor); g.fillRect(0, 0, (int) (this.getWidth() * this.getPercentComplete()), this.getHeight()); } }
9235c857456487da2883933cfefdad89d04586ca
2,877
java
Java
src/main/java/be/yildizgames/module/graphic/ogre/misc/OgreLine.java
yildiz-online/module-graphic-ogre
8f45fbfd3984d3f9f3143767de5b211e9a9c525f
[ "MIT" ]
null
null
null
src/main/java/be/yildizgames/module/graphic/ogre/misc/OgreLine.java
yildiz-online/module-graphic-ogre
8f45fbfd3984d3f9f3143767de5b211e9a9c525f
[ "MIT" ]
8
2018-11-19T20:41:21.000Z
2021-12-03T03:03:51.000Z
src/main/java/be/yildizgames/module/graphic/ogre/misc/OgreLine.java
yildiz-online/module-graphic-ogre
8f45fbfd3984d3f9f3143767de5b211e9a9c525f
[ "MIT" ]
null
null
null
36.417722
141
0.724366
997,413
/* * This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT) * * Copyright (c) 2019 Grégory Van den Borre * * More infos available: https://engine.yildiz-games.be * * 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 be.yildizgames.module.graphic.ogre.misc; import be.yildizgames.common.jni.NativePointer; import be.yildizgames.module.graphic.material.Material; import be.yildizgames.module.graphic.misc.Line; import be.yildizgames.module.graphic.ogre.OgreMaterial; import be.yildizgames.module.graphic.ogre.OgreNode; import jni.JniDynamicLine; /** * Ogre Line implementation. * * @author Grégory Van den Borre */ public final class OgreLine extends Line { /** * Address to the associated native object. */ private final NativePointer pointer; private final JniDynamicLine jni = new JniDynamicLine(); /** * Full constructor. * * @param node Node to attach the created line. */ public OgreLine(final OgreNode node) { super(); this.pointer = NativePointer.create(this.jni.constructor(node.getPointer().getPointerAddress())); } @Override protected void update(final float beginX, final float beginY, final float beginZ, final float endX, final float endY, final float endZ) { this.jni.update(this.pointer.getPointerAddress(), beginX, beginY, beginZ, endX, endY, endZ); } @Override protected void hideImpl() { this.jni.hide(this.pointer.getPointerAddress()); } @Override protected void showImpl() { this.jni.show(this.pointer.getPointerAddress()); } @Override protected void setMaterialImpl(final Material material) { this.jni.setMaterial(this.pointer.getPointerAddress(), ((OgreMaterial) material).getPointer().getPointerAddress()); } }
9235c9b908aebcec28e514de0c71aa3e9df6923c
18,700
java
Java
document/src/test/java/com/yahoo/document/json/DocumentUpdateJsonSerializerTest.java
t1707/vespa
9f4859e9996ac9913ce80ed9b209f683507fe157
[ "Apache-2.0" ]
1
2018-12-30T05:42:18.000Z
2018-12-30T05:42:18.000Z
document/src/test/java/com/yahoo/document/json/DocumentUpdateJsonSerializerTest.java
t1707/vespa
9f4859e9996ac9913ce80ed9b209f683507fe157
[ "Apache-2.0" ]
1
2021-01-21T01:37:37.000Z
2021-01-21T01:37:37.000Z
document/src/test/java/com/yahoo/document/json/DocumentUpdateJsonSerializerTest.java
t1707/vespa
9f4859e9996ac9913ce80ed9b209f683507fe157
[ "Apache-2.0" ]
1
2020-02-01T07:21:28.000Z
2020-02-01T07:21:28.000Z
35.630476
133
0.398161
997,414
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document.json; import com.fasterxml.jackson.core.JsonFactory; import com.yahoo.document.ArrayDataType; import com.yahoo.document.DataType; import com.yahoo.document.DocumentType; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.DocumentUpdate; import com.yahoo.document.Field; import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.ReferenceDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.TensorDataType; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.json.document.DocumentParser; import com.yahoo.tensor.TensorType; import com.yahoo.text.Utf8; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import static com.yahoo.test.json.JsonTestHelper.assertJsonEquals; import static com.yahoo.test.json.JsonTestHelper.inputJson; /** * @author Vegard Sjonfjell */ public class DocumentUpdateJsonSerializerTest { final static TensorType tensorType = new TensorType.Builder().mapped("x").mapped("y").build(); final static DocumentTypeManager types = new DocumentTypeManager(); final static JsonFactory parserFactory = new JsonFactory(); final static DocumentType docType = new DocumentType("doctype"); final static DocumentType refTargetDocType = new DocumentType("target_doctype"); final static String DEFAULT_DOCUMENT_ID = "id:test:doctype::1"; static { StructDataType myStruct = new StructDataType("my_struct"); myStruct.addField(new Field("my_string_field", DataType.STRING)); myStruct.addField(new Field("my_int_field", DataType.INT)); types.registerDocumentType(refTargetDocType); docType.addField(new Field("string_field", DataType.STRING)); docType.addField(new Field("int_field", DataType.INT)); docType.addField(new Field("float_field", DataType.FLOAT)); docType.addField(new Field("double_field", DataType.DOUBLE)); docType.addField(new Field("byte_field", DataType.BYTE)); docType.addField(new Field("tensor_field", new TensorDataType(tensorType))); docType.addField(new Field("reference_field", new ReferenceDataType(refTargetDocType, 777))); docType.addField(new Field("predicate_field", DataType.PREDICATE)); docType.addField(new Field("raw_field", DataType.RAW)); docType.addField(new Field("int_array", new ArrayDataType(DataType.INT))); docType.addField(new Field("string_array", new ArrayDataType(DataType.STRING))); docType.addField(new Field("int_set", new WeightedSetDataType(DataType.INT, true, true))); docType.addField(new Field("string_set", new WeightedSetDataType(DataType.STRING, true, true))); docType.addField(new Field("string_map", new MapDataType(DataType.STRING, DataType.STRING))); docType.addField(new Field("deep_map", new MapDataType(DataType.STRING, new MapDataType(DataType.STRING, DataType.STRING)))); docType.addField(new Field("map_array", new MapDataType(DataType.STRING, new ArrayDataType(DataType.STRING)))); docType.addField(new Field("map_struct", new MapDataType(DataType.STRING, myStruct))); docType.addField(new Field("singlepos_field", PositionDataType.INSTANCE)); docType.addField(new Field("multipos_field", new ArrayDataType(PositionDataType.INSTANCE))); types.registerDocumentType(docType); } private static DocumentUpdate deSerializeDocumentUpdate(String jsonDoc, String docId) { final InputStream rawDoc = new ByteArrayInputStream(Utf8.toBytes(jsonDoc)); JsonReader reader = new JsonReader(types, rawDoc, parserFactory); return (DocumentUpdate) reader.readSingleDocument(DocumentParser.SupportedOperation.UPDATE, docId); } private static String serializeDocumentUpdate(DocumentUpdate update) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DocumentUpdateJsonSerializer serializer = new DocumentUpdateJsonSerializer(outputStream); serializer.serialize(update); try { return new String(outputStream.toByteArray(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } private static void deSerializeAndSerializeJsonAndMatch(String jsonDoc) { jsonDoc = jsonDoc.replaceFirst("DOCUMENT_ID", DEFAULT_DOCUMENT_ID); DocumentUpdate update = deSerializeDocumentUpdate(jsonDoc, DEFAULT_DOCUMENT_ID); assertJsonEquals(serializeDocumentUpdate(update), jsonDoc); } @Test public void testArithmeticUpdate() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'int_field': {", " 'increment': 3.0", " },", " 'float_field': {", " 'decrement': 1.5", " },", " 'double_field': {", " 'divide': 3.2", " },", " 'byte_field': {", " 'multiply': 2.0", " }", " }", "}" )); } @Test public void testAssignSimpleTypes() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'int_field': {", " 'assign': 42", " },", " 'float_field': {", " 'assign': 32.45", " },", " 'double_field': {", " 'assign': 45.93", " },", " 'string_field': {", " 'assign': \"My favorite string\"", " },", " 'byte_field': {", " 'assign': 127", " }", " }", "}" )); } @Test public void testAssignWeightedSet() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'int_set': {", " 'assign': {", " '123': 456,", " '789': 101112", " }", " },", " 'string_set': {", " 'assign': {", " 'meow': 218478,", " 'slurp': 2123", " }", " }", " }", "}" )); } @Test public void testAddUpdate() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'int_array': {", " 'add': [", " 123,", " 456,", " 789", " ]", " },", " 'string_array': {", " 'add': [", " 'bjarne',", " 'andrei',", " 'rich'", " ]", " }", " }", "}" )); } @Test public void testRemoveUpdate() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'int_array': {", " 'remove': [", " 123,", " 789", " ]", " },", " 'string_array': {", " 'remove': [", " 'bjarne',", " 'rich'", " ]", " }", " }", "}" )); } @Test public void testMatchUpdateArithmetic() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'int_array': {", " 'match': {", " 'element': 456,", " 'multiply': 8.0", " }", " }", " }", "}" )); } @Test public void testMatchUpdateAssign() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'string_array': {", " 'match': {", " 'element': 3,", " 'assign': 'kjeks'", " }", " }", " }", "}" )); } @Test public void testAssignTensor() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'tensor_field': {", " 'assign': {", " 'cells': [", " { 'address': { 'x': 'a', 'y': 'b' }, 'value': 2.0 },", " { 'address': { 'x': 'c', 'y': 'b' }, 'value': 3.0 }", " ]", " }", " }", " }", "}" )); } @Test public void reference_field_id_can_be_update_assigned_non_empty_id() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'reference_field': {", " 'assign': 'id:ns:target_doctype::foo'", " }", " }", "}" )); } @Test public void reference_field_id_can_be_update_assigned_empty_id() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'reference_field': {", " 'assign': ''", " }", " }", "}" )); } @Test public void testAssignPredicate() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'predicate_field': {", " 'assign': 'foo in [bar]'", " }", " }", "}" )); } @Test public void testAssignRaw() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'raw_field': {", " 'assign': 'caf86f4uutaoxfysmf7anj01xl6sv3ps'", " }", " }", "}" )); } @Test public void testAssignMap() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'string_map': {", " 'assign': { ", " 'conversion gel': 'deadly',", " 'repulsion gel': 'safe',", " 'propulsion gel': 'insufficient data'", " }", " }", " }", "}" )); } @Test public void testSimultaneousFieldsAndFieldPathsUpdate() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'singlepos_field': {", " 'assign': 'N60.222333;E10.12'", " },", " 'deep_map{my_field}': {", " 'assign': {", " 'my_key': 'my value',", " 'new_key': 'new value'", " }", " }", " }", "}" )); } @Test public void testAssignFieldPathUpdate() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'deep_map{my_field}': {", " 'assign': {", " 'my_key': 'my value',", " 'new_key': 'new value'", " }", " },", " 'map_struct{my_key}': {", " 'assign': {", " 'my_string_field': 'Some string',", " 'my_int_field': 5", " }", " },", " 'map_struct{my_key}.my_int_field': {", " 'assign': 10", " }", " }", "}" )); } @Test public void testRemoveFieldPathUpdate() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'int_array[5]': {", " 'remove': 0", " }", " }", "}" )); } @Test public void testAddFieldPathUpdate() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'map_array{my_value}': {", " 'add': ['some', 'fancy', 'strings']", " }", " }", "}" )); } @Test public void testArithmeticFieldPathUpdate() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'map_struct{my_key}.my_int_field': {", " 'increment': 5.0", " },", " 'int_array[10]': {", " 'divide': 3.0", " }", " }", "}" )); } @Test public void testMultipleOperationsOnSingleFieldPath() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'map_struct{my_key}': {", " 'assign': {", " 'my_string_field': 'Some string'", " },", " 'remove': 0", " }", " }", "}" )); } @Test public void testAssignSinglePos() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'singlepos_field': {", " 'assign': 'N60.222333;E10.12'", " }", " }", "}" )); } @Test public void testAssignMultiPos() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'multipos_field': {", " 'assign': [ 'N0.0;E0.0', 'S1.1;W1.1', 'N10.2;W122.2' ]", " }", " }", "}" )); } @Test public void testClearField() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'fields': {", " 'int_field': {", " 'assign': null", " },", " 'string_field': {", " 'assign': null", " }", " }", "}" )); } @Test public void testCreateIfNotExistTrue() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'create': true,", " 'fields': {", " 'int_field': {", " 'assign': 42", " }", " }", "}" )); } @Test public void testCreateIfNotExistFalse() { deSerializeAndSerializeJsonAndMatch(inputJson( "{", " 'update': 'DOCUMENT_ID',", " 'create': false,", " 'fields': {", " 'int_field': {", " 'assign': 42", " }", " }", "}" )); } }
9235ca9a181748074c40abfa6e9c92d39229038e
8,881
java
Java
drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieModule.java
tteofili/drools
4131eaa70b35a2e64d4a720979fa47d6c67800da
[ "Apache-2.0" ]
5
2016-07-31T17:00:18.000Z
2022-01-11T04:34:29.000Z
drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieModule.java
tteofili/drools
4131eaa70b35a2e64d4a720979fa47d6c67800da
[ "Apache-2.0" ]
1
2021-07-21T03:23:04.000Z
2021-07-21T03:23:04.000Z
drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieModule.java
tteofili/drools
4131eaa70b35a2e64d4a720979fa47d6c67800da
[ "Apache-2.0" ]
null
null
null
40.552511
161
0.739444
997,415
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.compiler.kie.builder.impl; import java.io.File; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.appformer.maven.support.DependencyFilter; import org.appformer.maven.support.PomModel; import org.drools.compiler.compiler.io.memory.MemoryFileSystem; import org.drools.compiler.kie.util.ChangeSetBuilder; import org.drools.compiler.kie.util.KieJarChangeSet; import org.drools.compiler.kproject.models.KieBaseModelImpl; import org.drools.compiler.kproject.models.KieModuleModelImpl; import org.drools.core.definitions.InternalKnowledgePackage; import org.drools.core.impl.InternalKnowledgeBase; import org.drools.core.io.internal.InternalResource; import org.drools.reflective.ResourceProvider; import org.drools.reflective.classloader.ProjectClassLoader; import org.kie.api.KieBaseConfiguration; import org.kie.api.builder.KieModule; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.Results; import org.kie.api.builder.model.KieBaseModel; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.definition.KiePackage; import org.kie.api.internal.utils.ServiceRegistry; import org.kie.api.io.ResourceConfiguration; import org.kie.internal.builder.CompositeKnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilderConfiguration; import org.kie.internal.builder.ResourceChangeSet; import org.kie.internal.utils.ClassLoaderResolver; import org.kie.internal.utils.NoDepsClassLoaderResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.drools.compiler.kie.builder.impl.KieBuilderImpl.buildKieModule; import static org.drools.compiler.kie.builder.impl.KieBuilderImpl.filterFileInKBase; import static org.drools.compiler.kie.builder.impl.KieBuilderImpl.setDefaultsforEmptyKieModule; import static org.drools.compiler.kproject.ReleaseIdImpl.adapt; import static org.drools.reflective.classloader.ProjectClassLoader.createProjectClassLoader; public interface InternalKieModule extends KieModule, Serializable { void cacheKnowledgeBuilderForKieBase(String kieBaseName, KnowledgeBuilder kbuilder); KnowledgeBuilder getKnowledgeBuilderForKieBase(String kieBaseName); Collection<KiePackage> getKnowledgePackagesForKieBase(String kieBaseName); InternalKnowledgePackage getPackage(String packageName); void cacheResultsForKieBase( String kieBaseName, Results results); Map<String, Results> getKnowledgeResultsCache(); KieModuleModel getKieModuleModel(); byte[] getBytes( ); boolean hasResource( String fileName ); InternalResource getResource( String fileName ); ResourceConfiguration getResourceConfiguration( String fileName ); Map<ReleaseId, InternalKieModule> getKieDependencies(); void addKieDependency(InternalKieModule dependency); Collection<ReleaseId> getJarDependencies(DependencyFilter filter); Collection<ReleaseId> getUnresolvedDependencies(); void setUnresolvedDependencies(Collection<ReleaseId> unresolvedDependencies); boolean isAvailable( final String pResourceName ); byte[] getBytes( final String pResourceName ); Collection<String> getFileNames(); File getFile(); ResourceProvider createResourceProvider(); Map<String, byte[]> getClassesMap(); boolean addResourceToCompiler(CompositeKnowledgeBuilder ckbuilder, KieBaseModel kieBaseModel, String fileName); boolean addResourceToCompiler(CompositeKnowledgeBuilder ckbuilder, KieBaseModel kieBaseModel, String fileName, ResourceChangeSet rcs); long getCreationTimestamp(); InputStream getPomAsStream(); PomModel getPomModel(); KnowledgeBuilderConfiguration getBuilderConfiguration( KieBaseModel kBaseModel, ClassLoader classLoader ); InternalKnowledgeBase createKieBase( KieBaseModelImpl kBaseModel, KieProject kieProject, ResultsImpl messages, KieBaseConfiguration conf ); ClassLoader getModuleClassLoader(); default ResultsImpl build() { ResultsImpl messages = new ResultsImpl(); buildKieModule(this, messages); return messages; } default KieJarChangeSet getChanges(InternalKieModule newKieModule) { return ChangeSetBuilder.build( this, newKieModule ); } default boolean isFileInKBase(KieBaseModel kieBase, String fileName) { return filterFileInKBase(this, kieBase, fileName, () -> getResource( fileName ), false); } default Runnable createKieBaseUpdater(KieBaseUpdateContext context) { return new KieBaseUpdater( context ); } default ProjectClassLoader createModuleClassLoader( ClassLoader parent ) { if( parent == null ) { ClassLoaderResolver resolver = ServiceRegistry.getInstance().get(ClassLoaderResolver.class); if (resolver==null) { resolver = new NoDepsClassLoaderResolver(); } parent = resolver.getClassLoader( this ); } return createProjectClassLoader( parent, createResourceProvider() ); } default CompilationCache getCompilationCache( String kbaseName) { return null; } default InternalKieModule cloneForIncrementalCompilation(ReleaseId releaseId, KieModuleModel kModuleModel, MemoryFileSystem newFs) { throw new UnsupportedOperationException(); } static InternalKieModule createKieModule(ReleaseId releaseId, File jar) { try (ZipFile zipFile = new ZipFile(jar)) { ZipEntry zipEntry = zipFile.getEntry(KieModuleModelImpl.KMODULE_JAR_PATH); if (zipEntry != null) { KieModuleModel kieModuleModel = KieModuleModelImpl.fromXML( zipFile.getInputStream( zipEntry ) ); setDefaultsforEmptyKieModule( kieModuleModel ); return kieModuleModel != null ? InternalKieModuleProvider.get( adapt( releaseId ), kieModuleModel, jar ) : null; } } catch (Exception e) { LocalLogger.logger.error(e.getMessage(), e); } return null; } default void updateKieModule(InternalKieModule newKM) { } class CompilationCache implements Serializable { private static final long serialVersionUID = 3812243055974412935L; // this is a { DIALECT -> ( RESOURCE, List<CompilationEntry> ) } cache protected final Map<String, Map<String, List<CompilationCacheEntry>>> compilationCache = new HashMap<String, Map<String, List<CompilationCacheEntry>>>(); public void addEntry(String dialect, String className, byte[] bytecode) { Map<String, List<CompilationCacheEntry>> resourceEntries = compilationCache.get(dialect); if( resourceEntries == null ) { resourceEntries = new HashMap<String, List<CompilationCacheEntry>>(); compilationCache.put(dialect, resourceEntries); } String key = className.contains("$") ? className.substring(0, className.indexOf('$') ) + ".class" : className; List<CompilationCacheEntry> bytes = resourceEntries.get(key); if( bytes == null ) { bytes = new ArrayList<CompilationCacheEntry>(); resourceEntries.put(key, bytes); } //System.out.println(String.format("Adding to in-memory cache: %s %s", key, className )); bytes.add(new CompilationCacheEntry(className, bytecode)); } public Map<String, List<CompilationCacheEntry>> getCacheForDialect(String dialect) { return compilationCache.get(dialect); } } class CompilationCacheEntry implements Serializable { private static final long serialVersionUID = 1423987159014688588L; public final String className; public final byte[] bytecode; public CompilationCacheEntry( String className, byte[] bytecode) { this.className = className; this.bytecode = bytecode; } } final class LocalLogger { private static final Logger logger = LoggerFactory.getLogger(InternalKieModule.class); } }
9235cab58e9f6453d9f51408ac08b573cca0255d
91
java
Java
hello-spring-boot/src/main/java/com/zachard/spring/boot/hello/controller/package-info.java
zachard/spring-boot-parent
eeebe0963ef5abc5dc3054540236d469ce4d288a
[ "Apache-2.0" ]
null
null
null
hello-spring-boot/src/main/java/com/zachard/spring/boot/hello/controller/package-info.java
zachard/spring-boot-parent
eeebe0963ef5abc5dc3054540236d469ce4d288a
[ "Apache-2.0" ]
null
null
null
hello-spring-boot/src/main/java/com/zachard/spring/boot/hello/controller/package-info.java
zachard/spring-boot-parent
eeebe0963ef5abc5dc3054540236d469ce4d288a
[ "Apache-2.0" ]
null
null
null
11.375
49
0.604396
997,416
/** * */ /** * @author richard * */ package com.zachard.spring.boot.hello.controller;
9235cac87d60e2be39721515bfc7043fb9b0b10f
1,150
java
Java
src/main/java/com/epam/brest/resource/impl/TxtFileResourceHandler.java
Brest-Java-Course-2021-2/Valentin-Kravchenko
b74408b5bca9ab931abe0eee2987f793aa374755
[ "Apache-2.0" ]
null
null
null
src/main/java/com/epam/brest/resource/impl/TxtFileResourceHandler.java
Brest-Java-Course-2021-2/Valentin-Kravchenko
b74408b5bca9ab931abe0eee2987f793aa374755
[ "Apache-2.0" ]
1
2021-10-10T15:08:00.000Z
2021-11-06T06:40:06.000Z
src/main/java/com/epam/brest/resource/impl/TxtFileResourceHandler.java
Brest-Java-Course-2021-2/Valentin-Kravchenko
b74408b5bca9ab931abe0eee2987f793aa374755
[ "Apache-2.0" ]
null
null
null
35.9375
108
0.591304
997,417
package com.epam.brest.resource.impl; import com.epam.brest.resource.ResourceHandler; import com.epam.brest.resource.ResourceUtils; import java.math.BigDecimal; import java.util.List; import java.util.NavigableMap; import java.util.TreeMap; import java.util.stream.Collectors; public class TxtFileResourceHandler implements ResourceHandler { @Override public NavigableMap<BigDecimal, BigDecimal> getMapPrice(String resourceFile) { return ResourceUtils.getStream(resourceFile) .filter(line -> !line.startsWith("#")) .map(line -> line.split("-")) .collect(Collectors.toMap(arr -> BigDecimal.valueOf(Double.parseDouble(arr[0])), arr -> BigDecimal.valueOf(Double.parseDouble(arr[1])), (oldValue, newValue) -> oldValue, TreeMap::new)); } @Override public List<String> getMessages(String resourceFile) { return ResourceUtils.getStream(resourceFile).toList(); } }
9235cb7efcfad60874aad4cf5dd1f794efb0e163
443
java
Java
src/main/java/com/cefet/compras/api/repositories/UsuarioRepository.java
odiloncorrea/api-compra
8ea9e333f8b2381e5f2763b1a8b421271a187b90
[ "MIT" ]
null
null
null
src/main/java/com/cefet/compras/api/repositories/UsuarioRepository.java
odiloncorrea/api-compra
8ea9e333f8b2381e5f2763b1a8b421271a187b90
[ "MIT" ]
null
null
null
src/main/java/com/cefet/compras/api/repositories/UsuarioRepository.java
odiloncorrea/api-compra
8ea9e333f8b2381e5f2763b1a8b421271a187b90
[ "MIT" ]
null
null
null
27.6875
74
0.832957
997,418
package com.cefet.compras.api.repositories; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.cefet.compras.api.entities.Usuario; @Repository public interface UsuarioRepository extends JpaRepository<Usuario, Long>{ Optional<Usuario> findByEmail(String email); Optional<Usuario> findUsuarioByEmailAndSenha(String email, String senha); }
9235cc26d1dd6e2527a7ab17deeaf5d1d345e6b9
5,498
java
Java
weblayer/browser/java/org/chromium/weblayer_private/DownloadCallbackProxy.java
sunlongbo/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
weblayer/browser/java/org/chromium/weblayer_private/DownloadCallbackProxy.java
sunlongbo/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
weblayer/browser/java/org/chromium/weblayer_private/DownloadCallbackProxy.java
sunlongbo/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
37.148649
98
0.689887
997,419
// Copyright 2019 The Chromium 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 org.chromium.weblayer_private; import android.Manifest.permission; import android.content.pm.PackageManager; import android.os.RemoteException; import android.webkit.ValueCallback; import org.chromium.base.ThreadUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; import org.chromium.ui.base.WindowAndroid; import org.chromium.url.GURL; import org.chromium.weblayer_private.interfaces.IDownloadCallbackClient; import org.chromium.weblayer_private.interfaces.ObjectWrapper; /** * Owns the c++ DownloadCallbackProxy class, which is responsible for forwarding all * DownloadDelegate delegate calls to this class, which in turn forwards to the * DownloadCallbackClient. */ @JNINamespace("weblayer") public final class DownloadCallbackProxy { private final ProfileImpl mProfile; private long mNativeDownloadCallbackProxy; private IDownloadCallbackClient mClient; DownloadCallbackProxy(ProfileImpl profile) { mProfile = profile; mNativeDownloadCallbackProxy = DownloadCallbackProxyJni.get().createDownloadCallbackProxy( this, profile.getNativeProfile()); } public void setClient(IDownloadCallbackClient client) { mClient = client; } public void destroy() { DownloadCallbackProxyJni.get().deleteDownloadCallbackProxy(mNativeDownloadCallbackProxy); mNativeDownloadCallbackProxy = 0; } @CalledByNative private boolean interceptDownload(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) throws RemoteException { if (mClient == null) { return false; } return mClient.interceptDownload( url, userAgent, contentDisposition, mimetype, contentLength); } @CalledByNative private void allowDownload(TabImpl tab, String url, String requestMethod, String requestInitiator, long callbackId) throws RemoteException { WindowAndroid window = tab.getBrowser().getWindowAndroid(); if (window.hasPermission(permission.WRITE_EXTERNAL_STORAGE)) { continueAllowDownload(url, requestMethod, requestInitiator, callbackId); return; } String[] requestPermissions = new String[] {permission.WRITE_EXTERNAL_STORAGE}; window.requestPermissions(requestPermissions, (permissions, grantResults) -> { if (grantResults.length == 0 || grantResults[0] == PackageManager.PERMISSION_DENIED) { DownloadCallbackProxyJni.get().allowDownload(callbackId, false); return; } try { continueAllowDownload(url, requestMethod, requestInitiator, callbackId); } catch (RemoteException e) { } }); } private void continueAllowDownload(String url, String requestMethod, String requestInitiator, long callbackId) throws RemoteException { if (mClient == null) { DownloadCallbackProxyJni.get().allowDownload(callbackId, true); return; } ValueCallback<Boolean> callback = new ValueCallback<Boolean>() { @Override public void onReceiveValue(Boolean result) { ThreadUtils.assertOnUiThread(); if (mNativeDownloadCallbackProxy == 0) { throw new IllegalStateException("Called after destroy()"); } DownloadCallbackProxyJni.get().allowDownload(callbackId, result); } }; mClient.allowDownload(url, requestMethod, requestInitiator, ObjectWrapper.wrap(callback)); } @CalledByNative private DownloadImpl createDownload( long nativeDownloadImpl, int id, boolean isTransient, GURL sourceUrl) { return new DownloadImpl(mProfile.getName(), mProfile.isIncognito(), mClient, nativeDownloadImpl, id, isTransient, sourceUrl); } @CalledByNative private void downloadStarted(DownloadImpl download) throws RemoteException { if (mClient != null) { mClient.downloadStarted(download.getClientDownload()); } download.downloadStarted(); } @CalledByNative private void downloadProgressChanged(DownloadImpl download) throws RemoteException { if (mClient != null) { mClient.downloadProgressChanged(download.getClientDownload()); } download.downloadProgressChanged(); } @CalledByNative private void downloadCompleted(DownloadImpl download) throws RemoteException { if (mClient != null) { mClient.downloadCompleted(download.getClientDownload()); } download.downloadCompleted(); } @CalledByNative private void downloadFailed(DownloadImpl download) throws RemoteException { if (mClient != null) { mClient.downloadFailed(download.getClientDownload()); } download.downloadFailed(); } @NativeMethods interface Natives { long createDownloadCallbackProxy(DownloadCallbackProxy proxy, long tab); void deleteDownloadCallbackProxy(long proxy); void allowDownload(long callbackId, boolean allow); } }
9235cdf2ccdc332c7a55463413ea89697d889049
32
java
Java
pulsar-client/src/test/kotlin/ai/platon/pulsar/client/package-info.java
platonai/pulsar
ea65b5e02c76d5c23e843bdae8f35095bf2ada67
[ "CC0-1.0" ]
117
2018-04-11T00:12:19.000Z
2022-03-11T20:20:41.000Z
pulsar-client/src/test/kotlin/ai/platon/pulsar/client/package-info.java
platonai/pulsar
ea65b5e02c76d5c23e843bdae8f35095bf2ada67
[ "CC0-1.0" ]
7
2019-11-19T15:13:57.000Z
2022-03-13T02:49:41.000Z
pulsar-client/src/test/kotlin/ai/platon/pulsar/client/package-info.java
platonai/pulsar
ea65b5e02c76d5c23e843bdae8f35095bf2ada67
[ "CC0-1.0" ]
35
2018-04-25T09:02:41.000Z
2021-08-07T11:58:42.000Z
32
32
0.84375
997,420
package ai.platon.pulsar.client;
9235cef8067323edaf159e23f7dd4915305e6eed
2,183
java
Java
src/main/java/net/imagej/ops/statistics/SumRealType.java
bnorthan/imagej-ops
defeee0eecc113b05685dcc6f0f475060ea1d943
[ "BSD-2-Clause" ]
null
null
null
src/main/java/net/imagej/ops/statistics/SumRealType.java
bnorthan/imagej-ops
defeee0eecc113b05685dcc6f0f475060ea1d943
[ "BSD-2-Clause" ]
null
null
null
src/main/java/net/imagej/ops/statistics/SumRealType.java
bnorthan/imagej-ops
defeee0eecc113b05685dcc6f0f475060ea1d943
[ "BSD-2-Clause" ]
null
null
null
40.425926
79
0.759505
997,421
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2014 Board of Regents of the University of * Wisconsin-Madison and University of Konstanz. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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 HOLDERS 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. * #L% */ package net.imagej.ops.statistics; import net.imagej.ops.AbstractStrictFunction; import net.imagej.ops.Op; import net.imagej.ops.Ops; import net.imglib2.type.numeric.RealType; import org.scijava.Priority; import org.scijava.plugin.Plugin; @Plugin(type = Op.class, name = Ops.Sum.NAME, priority = Priority.LOW_PRIORITY) public class SumRealType<T extends RealType<T>, V extends RealType<V>> extends AbstractStrictFunction<Iterable<T>, V> implements Sum<Iterable<T>, V> { @Override public V compute(final Iterable<T> input, final V output) { for (final T t : input) { output.setReal(output.getRealDouble() + t.getRealDouble()); } return output; } }
9235cf35553cd896d42ad09cc1ccc98e5ba775db
2,283
java
Java
src/main/java/com/neusoft/entity/vo/CustomerInfoVo.java
freedomhost/neucrm
89aa7b935cad7ea7be7068be26a842b2963d8ed6
[ "Apache-2.0" ]
null
null
null
src/main/java/com/neusoft/entity/vo/CustomerInfoVo.java
freedomhost/neucrm
89aa7b935cad7ea7be7068be26a842b2963d8ed6
[ "Apache-2.0" ]
null
null
null
src/main/java/com/neusoft/entity/vo/CustomerInfoVo.java
freedomhost/neucrm
89aa7b935cad7ea7be7068be26a842b2963d8ed6
[ "Apache-2.0" ]
null
null
null
15.22
53
0.585195
997,422
package com.neusoft.entity.vo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.io.Serializable; import java.math.BigDecimal; import java.time.LocalDateTime; /** * <p> * 客户信息 客户信息 * </p> * * @author CDHong * @since 2018-11-22 */ @Data @JsonInclude(JsonInclude.Include.NON_NULL)//无视NULL public class CustomerInfoVo implements Serializable { private Integer customerId; /** * 客户名称 客户名称 */ private String customerName; /** * 地区 地区 */ private String city; /** * 客户经理 客户经理 */ private String customerMgr; /** * 客户经理编号 客户经理编号 */ private BigDecimal customerMgrId; /** * 客户等级 客户等级 */ private String customerGrade; /** * 客户满意度 客户满意度 */ private String customerSatisfaction; /** * 客户信用度 客户信用度 */ private String customerCredit; /** * 地址 地址 */ private String address; /** * 邮政编码 邮政编码 */ private BigDecimal postalCode; /** * 电话 电话 */ private String phone; /** * 传真 传真 */ private String fax; /** * 网址 网址 */ private String ulr; /** * 营业执照注册号 营业执照注册号 */ private String businessLicense; /** * 法人 法人 */ private String juridicalPerson; /** * 注册资金 注册资金 */ private Double registeredCapital; /** * 年营业额 年营业额 */ private Double annualSales; /** * 开户银行 开户银行 */ private String depositBank; /** * 银行账号 银行账号 */ private String bankAccount; /** * 地税登记号 地税登记号 */ private String landTaxCode; /** * 国税登记号 国税登记号 */ private String centralTax; /** * 创建人 创建人 */ private String founder; /** * 创建人编号 创建人编号 */ private Integer foundId; /** * 创建时间 创建时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private LocalDateTime creationTime; }
9235cf49eb659d747bec053b28e094a9a1ad558c
6,787
java
Java
WebKIndex/src/main/java/Indexing/Newspapers/NewspapersRetriever.java
MKLab-ITI/KRISTINA
7d97b0f443468259af7aa2b7dcaab6458abdfa51
[ "Apache-2.0" ]
null
null
null
WebKIndex/src/main/java/Indexing/Newspapers/NewspapersRetriever.java
MKLab-ITI/KRISTINA
7d97b0f443468259af7aa2b7dcaab6458abdfa51
[ "Apache-2.0" ]
null
null
null
WebKIndex/src/main/java/Indexing/Newspapers/NewspapersRetriever.java
MKLab-ITI/KRISTINA
7d97b0f443468259af7aa2b7dcaab6458abdfa51
[ "Apache-2.0" ]
null
null
null
34.105528
139
0.626197
997,423
package Indexing.Newspapers; import Indexing.IndexCONSTANTS; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.pl.PolishAnalyzer; import org.apache.lucene.analysis.standard.ClassicAnalyzer; import org.apache.lucene.analysis.tr.TurkishAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexableField; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.*; import org.apache.lucene.search.similarities.DefaultSimilarity; import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Iterator; /** * Created by spyridons on 2/24/2017. */ public class NewspapersRetriever { Analyzer analyzer; Directory directory; IndexWriterConfig config; IndexWriter writer; String folderName; int NO_OF_RESULTS_QUERY = 1; /** * Constructor , creates File index in default directory ({@link IndexCONSTANTS#INDEX_PATH}).<br> * */ public NewspapersRetriever(String language){ analyzer = new ClassicAnalyzer(); if(language.equals("tr")) analyzer = new TurkishAnalyzer(); Path path= Paths.get(IndexCONSTANTS.NEWSPAPER_INDEX_PATH + language); try { directory = FSDirectory.open(path); } catch (IOException e) { e.printStackTrace(); } folderName=IndexCONSTANTS.NEWSPAPER_INDEX_PATH + language; try { config = new IndexWriterConfig(analyzer); config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND); writer = new IndexWriter(directory, config); writer.close(); writer = null; } catch (IOException e) { System.out.println("WebKIndex :: NewspapersRetriever() Could NOT create writer"); //e.printStackTrace(); } } /** * Open Index writer */ public void openWriter() { try { config = new IndexWriterConfig(analyzer); config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND); writer = new IndexWriter(directory, config); } catch (IOException e) { System.out.println("WebKIndex :: NewspapersRetriever.openWriter() Could NOT create writer"); e.printStackTrace(); } } /** * Close Index Writer */ public void closeWriter() { try { writer.close(); writer = null; } catch (IOException e) { System.out.println("WebKIndex :: NewspapersRetriever.closeWriter() Could NOT close writer"); e.printStackTrace(); } } /** * Close TextIndexHandler * * @return Nothing */ public void close(){ try { directory.close(); analyzer.close(); } catch (IOException e) { System.out.println("WebKIndex :: NewspapersRetriever.close() Could NOT close writer."); e.printStackTrace(); } } /** * If Index handling by TextIndexHandler is empty * * @return boolean. True if Empty. */ public boolean isEmpty(){ try { DirectoryReader reader = DirectoryReader.open(directory); if (reader.getDocCount(IndexCONSTANTS.FIELD_CONTENT) > 0){ reader.close(); return false; } reader.close(); } catch (IOException e) { System.out.println("WebKIndex :: NewspapersRetriever.isEmpty() Could NOT get Doc Count."); e.printStackTrace(); return true; } return true; } public String makeNewspaperQuery(String queryStr){ DirectoryReader reader = null; try { reader = DirectoryReader.open(directory); } catch (IOException e) { System.out.println("WebKIndex :: NewspapersRetriever.makeNewspaperQuery() Reader could NOT open directory"); e.printStackTrace(); } IndexSearcher searcher = new IndexSearcher(reader); Similarity similarityVS = new DefaultSimilarity(); //lucene default similarity is Vector Space searcher.setSimilarity(similarityVS); TopDocs candidate = null; BooleanQuery.Builder finalQuery = new BooleanQuery.Builder(); try { // query newspaper title QueryParser titleParser = new QueryParser(IndexCONSTANTS.FIELD_TITLE, analyzer); Query titleQuery = titleParser.parse(QueryParser.escape(queryStr)); finalQuery.add(titleQuery, BooleanClause.Occur.SHOULD); // query newspaper subtitle QueryParser subtitleParser = new QueryParser(IndexCONSTANTS.FIELD_SUBTITLE, analyzer); Query subtitleQuery = subtitleParser.parse(QueryParser.escape(queryStr)); finalQuery.add(subtitleQuery, BooleanClause.Occur.SHOULD); } catch (ParseException e) { System.out.println("WebKIndex :: RecipesRetriever.makeNewspaperQuery() Could NOT parse the queryString."); e.printStackTrace(); return null; } Query query = finalQuery.build(); try { candidate = searcher.search(query, NO_OF_RESULTS_QUERY); //candidate = searcher.search(query, reader.maxDoc()); } catch (IOException e) { System.out.println("WebKIndex :: RecipesRetriever.makeNewspaperQuery() Could NOT Search REcipes for query: " + queryStr); //e.printStackTrace(); return null; } String response=""; if (candidate.scoreDocs.length>0){ try { response = docToContent(searcher.doc(candidate.scoreDocs[0].doc)); } catch (IOException e) { System.out.println("WebKIndex :: RecipesRetriever.makeNewspaperQuery() Could NOT Get top document for query: " + queryStr); //e.printStackTrace(); } } return response; } private String docToContent(Document doc) { String content = ""; Iterator<IndexableField> iter = doc.iterator(); while (iter.hasNext()) { IndexableField temp = iter.next(); if (temp.name().equals(IndexCONSTANTS.FIELD_CONTENT)){ content = temp.stringValue(); } } return content; } }
9235d04ad03b791da90a56383ab5ec02662ca4d0
260
java
Java
src/com/github/darrmirr/fp/logger/LogEvent.java
DarrMirr/fp_cor
9da4a076c0e5c5ae03345f01c6d4ac8c5353b3e8
[ "MIT" ]
null
null
null
src/com/github/darrmirr/fp/logger/LogEvent.java
DarrMirr/fp_cor
9da4a076c0e5c5ae03345f01c6d4ac8c5353b3e8
[ "MIT" ]
null
null
null
src/com/github/darrmirr/fp/logger/LogEvent.java
DarrMirr/fp_cor
9da4a076c0e5c5ae03345f01c6d4ac8c5353b3e8
[ "MIT" ]
null
null
null
21.666667
58
0.642308
997,424
package com.github.darrmirr.fp.logger; public class LogEvent { public Logger.Level level; public String message; public LogEvent(Logger.Level level, String message) { this.level = level; this.message = message; } }
9235d0bd0e68e9c0c891cd116fdfb8bb7423c06f
502
java
Java
gmall-ums/src/main/java/com/atguigu/gmall/ums/service/UserAddressService.java
liuyawei-svg/gmall-0420
11948092aeac4a66e521d2148cdac51db5a0794f
[ "Apache-2.0" ]
null
null
null
gmall-ums/src/main/java/com/atguigu/gmall/ums/service/UserAddressService.java
liuyawei-svg/gmall-0420
11948092aeac4a66e521d2148cdac51db5a0794f
[ "Apache-2.0" ]
null
null
null
gmall-ums/src/main/java/com/atguigu/gmall/ums/service/UserAddressService.java
liuyawei-svg/gmall-0420
11948092aeac4a66e521d2148cdac51db5a0794f
[ "Apache-2.0" ]
null
null
null
22.863636
73
0.781312
997,425
package com.atguigu.gmall.ums.service; import com.baomidou.mybatisplus.extension.service.IService; import com.atguigu.gmall.common.bean.PageResultVo; import com.atguigu.gmall.common.bean.PageParamVo; import com.atguigu.gmall.ums.entity.UserAddressEntity; import java.util.Map; /** * 收货地址表 * * @author fengge * @email envkt@example.com * @date 2020-09-21 19:46:09 */ public interface UserAddressService extends IService<UserAddressEntity> { PageResultVo queryPage(PageParamVo paramVo); }
9235d0c16d3fb4953f0a3b376559b2fe126a282c
514
java
Java
core/src/test/java/io/basc/framework/test/TypeComparatorTest.java
wcnnkh/framework
841ea3950d8892dbcf57483a3bbdd1c2abe72f43
[ "Apache-2.0" ]
4
2021-12-30T09:59:47.000Z
2022-03-27T16:43:46.000Z
core/src/test/java/io/basc/framework/test/TypeComparatorTest.java
wcnnkh/scw
595790cfa656e39176ac022cf31deca3201cdb03
[ "Apache-2.0" ]
2
2021-03-30T14:05:58.000Z
2021-03-30T16:33:24.000Z
core/src/test/java/io/basc/framework/test/TypeComparatorTest.java
wcnnkh/framework
97debeee6915f47b42ea7df02e4807a0bda3d858
[ "Apache-2.0" ]
2
2022-01-14T13:58:37.000Z
2022-03-27T16:44:13.000Z
22.347826
70
0.725681
997,426
package io.basc.framework.test; import static org.junit.Assert.assertTrue; import java.util.TreeSet; import org.junit.Test; import io.basc.framework.util.comparator.TypeComparator; public class TypeComparatorTest { @Test public void test() { TreeSet<Class<?>> set = new TreeSet<Class<?>>(new TypeComparator()); set.add(Object.class); set.add(Integer.class); set.add(Number.class); System.out.println(set); assertTrue(set.first() == Integer.class); assertTrue(set.last() == Object.class); } }
9235d154e4277e5d2e5db31ea19b99057081af18
611
java
Java
src/commands/MINUS.java
vardhaan/SLOGO
99d18b51af9d8cd0732c566d6b071591b074c19e
[ "MIT" ]
null
null
null
src/commands/MINUS.java
vardhaan/SLOGO
99d18b51af9d8cd0732c566d6b071591b074c19e
[ "MIT" ]
null
null
null
src/commands/MINUS.java
vardhaan/SLOGO
99d18b51af9d8cd0732c566d6b071591b074c19e
[ "MIT" ]
null
null
null
14.547619
66
0.666121
997,427
/** * */ package commands; import exceptions.ParameterNotEnoughException; /** * @author Zhiyong * */ public class MINUS extends Command{ public MINUS(){ super(); expectedNumParameters = 1; } /* * set the return value */ @Override public void setReturnValue() throws ParameterNotEnoughException { if (parameters.size() == expectedNumParameters) { returnValue = -(parameters.get(0)); sendReturnToDependent(); } } /* * minus of the parameter */ @Override public double executeCommand() { double x = parameters.get(0); returnValue = -x ; return returnValue; } }
9235d1e09a0de186699ffb7ee0ec90a235cd68ac
3,234
java
Java
demos/theming-demo/src/main/java/org/pushingpixels/radiance/demo/theming/main/check/CardPanel.java
dpolivaev/radiance
89716f1bb195f64363160906b51e4f367ec16ca3
[ "BSD-3-Clause" ]
607
2018-05-23T19:11:22.000Z
2022-03-28T17:11:34.000Z
demos/theming-demo/src/main/java/org/pushingpixels/radiance/demo/theming/main/check/CardPanel.java
dpolivaev/radiance
89716f1bb195f64363160906b51e4f367ec16ca3
[ "BSD-3-Clause" ]
379
2018-05-23T18:52:03.000Z
2022-03-28T11:07:05.000Z
demos/theming-demo/src/main/java/org/pushingpixels/radiance/demo/theming/main/check/CardPanel.java
dpolivaev/radiance
89716f1bb195f64363160906b51e4f367ec16ca3
[ "BSD-3-Clause" ]
96
2018-05-26T04:53:09.000Z
2022-03-09T03:25:16.000Z
34.774194
80
0.723253
997,428
/* * Copyright (c) 2005-2021 Radiance Kirill Grouchnikov. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o 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. * * o Neither the name of the copyright holder 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 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.pushingpixels.radiance.demo.theming.main.check; import javax.swing.*; import java.awt.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; /** * Test application panel that test {@link CardLayout}. * * @author Kirill Grouchnikov */ public class CardPanel extends JPanel implements ItemListener { /** * Test panel with {@link CardLayout} */ JPanel cards; /** * ID for the button panel. */ final static String BUTTONPANEL = "JPanel with JButtons"; /** * ID for the text panel. */ final static String TEXTPANEL = "JPanel with JTextField"; /** * Creates a new panel. */ public CardPanel() { // Put the JComboBox in a JPanel to get a nicer look. JPanel comboBoxPane = new JPanel(); // use FlowLayout String[] comboBoxItems = { BUTTONPANEL, TEXTPANEL }; JComboBox<String> cb = new JComboBox<>(comboBoxItems); cb.setEditable(false); cb.addItemListener(this); comboBoxPane.add(cb); // Create the "cards". JPanel card1 = new JPanel(); card1.add(new JButton("Button 1")); card1.add(new JButton("Button 2")); card1.add(new JButton("Button 3")); JPanel card2 = new JPanel(); card2.add(new JTextField("TextField", 20)); // Create the panel that contains the "cards". cards = new JPanel(new CardLayout()); cards.add(card1, BUTTONPANEL); cards.add(card2, TEXTPANEL); this.add(comboBoxPane, BorderLayout.PAGE_START); this.add(cards, BorderLayout.CENTER); } public void itemStateChanged(ItemEvent evt) { CardLayout cl = (CardLayout) (cards.getLayout()); cl.show(cards, (String) evt.getItem()); } }
9235d2439c8228ea8452797ce088057cbe6e2708
170
java
Java
src/main/java/com/data/enums/mybatis/IEnumDesc.java
zhangweiheu/webapp
012edebca6b6d3cf3a13f3423ce8eed0b672f6fd
[ "Artistic-2.0" ]
null
null
null
src/main/java/com/data/enums/mybatis/IEnumDesc.java
zhangweiheu/webapp
012edebca6b6d3cf3a13f3423ce8eed0b672f6fd
[ "Artistic-2.0" ]
null
null
null
src/main/java/com/data/enums/mybatis/IEnumDesc.java
zhangweiheu/webapp
012edebca6b6d3cf3a13f3423ce8eed0b672f6fd
[ "Artistic-2.0" ]
null
null
null
11.333333
36
0.605882
997,429
/** * */ package com.data.enums.mybatis; /** * @author xianwen.tan * */ public interface IEnumDesc { /** 获取对枚举字段的描述,为统一解析枚举为字典提供支持 */ String getDesc(); }
9235d292136d847595ec6d70fc28de186b68c7eb
393
java
Java
src/main/java/Biometric/Utilities/FramesList.java
kajapa/fingerprints-master
466095c49d10233b7d35f535bfd8a42b0eff3693
[ "MIT" ]
null
null
null
src/main/java/Biometric/Utilities/FramesList.java
kajapa/fingerprints-master
466095c49d10233b7d35f535bfd8a42b0eff3693
[ "MIT" ]
null
null
null
src/main/java/Biometric/Utilities/FramesList.java
kajapa/fingerprints-master
466095c49d10233b7d35f535bfd8a42b0eff3693
[ "MIT" ]
null
null
null
20.684211
79
0.70229
997,430
/* * 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 Biometric.Utilities; import java.util.ArrayList; import java.util.List; /** * * @author Patryk */ public class FramesList { public List<double[]> Frames= new ArrayList<double []>(); }
9235d29d7ec478ea708aaed352aadbd3c3b735c3
1,681
java
Java
src/main/java/wraith/crushing_hammers/CustomToolMaterial.java
LordDeatHunter/CrushingHammers
6087dc6fc39f61eb2386fd485f0a0e05fa46b376
[ "MIT" ]
null
null
null
src/main/java/wraith/crushing_hammers/CustomToolMaterial.java
LordDeatHunter/CrushingHammers
6087dc6fc39f61eb2386fd485f0a0e05fa46b376
[ "MIT" ]
3
2021-02-09T06:52:35.000Z
2021-06-09T05:37:58.000Z
src/main/java/wraith/crushing_hammers/CustomToolMaterial.java
LordDeatHunter/CrushingHammers
6087dc6fc39f61eb2386fd485f0a0e05fa46b376
[ "MIT" ]
null
null
null
27.557377
169
0.706722
997,431
package wraith.crushing_hammers; import net.minecraft.item.Items; import net.minecraft.item.ToolMaterial; import net.minecraft.recipe.Ingredient; import net.minecraft.util.Lazy; import java.util.function.Supplier; public enum CustomToolMaterial implements ToolMaterial { GLASS(0, 8, 12.0F, 3.5F, 30, () -> { return Ingredient.ofItems(Items.GLASS); }); private final int miningLevel; private final int itemDurability; private final float miningSpeedMultiplier; private final float attackDamage; private final int enchantability; private final Lazy<Ingredient> repairIngredient; CustomToolMaterial(int miningLevel, int itemDurability, float miningSpeedMultiplier, float attackDamage, int enchantability, Supplier<Ingredient> repairIngredient) { this.miningLevel = miningLevel; this.itemDurability = itemDurability; this.miningSpeedMultiplier = miningSpeedMultiplier; this.attackDamage = attackDamage; this.enchantability = enchantability; this.repairIngredient = new Lazy<>(repairIngredient); } @Override public int getDurability() { return this.itemDurability; } @Override public float getMiningSpeedMultiplier() { return this.miningSpeedMultiplier; } @Override public float getAttackDamage() { return this.attackDamage; } @Override public int getMiningLevel() { return this.miningLevel; } @Override public int getEnchantability() { return this.enchantability; } @Override public Ingredient getRepairIngredient() { return this.repairIngredient.get(); } }
9235d2e85c059f136d15379e878b29cef653522b
3,260
java
Java
shio-app/src/main/java/com/viglet/shio/graphql/schema/object/type/sites/ShGraphQLOTObjectFromURL.java
openshio/shiohara
d86b34e3c4d33feb47154092af82d51ed4a04595
[ "Apache-2.0" ]
113
2019-05-23T21:02:58.000Z
2020-02-27T13:30:23.000Z
shio-app/src/main/java/com/viglet/shio/graphql/schema/object/type/sites/ShGraphQLOTObjectFromURL.java
openviglet/ocean
ccd729a88f25ef0af603a35a2de9259a80153583
[ "Apache-2.0" ]
198
2020-03-09T20:55:41.000Z
2022-03-30T04:35:16.000Z
shio-app/src/main/java/com/viglet/shio/graphql/schema/object/type/sites/ShGraphQLOTObjectFromURL.java
openviglet/ocean
ccd729a88f25ef0af603a35a2de9259a80153583
[ "Apache-2.0" ]
15
2019-09-05T12:37:47.000Z
2020-02-13T23:10:30.000Z
37.906977
108
0.783436
997,432
/* * Copyright (C) 2016-2020 the original author or authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.viglet.shio.graphql.schema.object.type.sites; import static graphql.Scalars.GraphQLID; import static graphql.Scalars.GraphQLString; import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition; import static graphql.schema.GraphQLObjectType.newObject; import static graphql.schema.GraphqlTypeComparatorRegistry.BY_NAME_REGISTRY; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.viglet.shio.graphql.ShGraphQLConstants; import com.viglet.shio.graphql.schema.query.type.sites.ShGraphQLQTObjectFromURL; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLObjectType.Builder; import graphql.scalars.ExtendedScalars; /** * GraphQL Object From URL Object Type. * * @author Alexandre Oliveira * @since 0.3.7 */ @Component public class ShGraphQLOTObjectFromURL { @Autowired private ShGraphQLQTObjectFromURL shGraphQLQTObjectFromURL; private GraphQLObjectType createWebSiteByURL() { Builder builder = newObject().name("ObjectFromURL").description("Object from Site URL"); this.createSiteURLObjectTypeFields(builder); return builder.comparatorRegistry(BY_NAME_REGISTRY).build(); } private void createSiteURLObjectTypeFields(Builder builder) { builder.field(newFieldDefinition().name(ShGraphQLConstants.ID).description("Identifier").type(GraphQLID)); builder.field( newFieldDefinition().name("type").description("Object Type").type(GraphQLString)); builder.field( newFieldDefinition().name("format").description("Format").type(GraphQLString)); builder.field( newFieldDefinition().name("locale").description("Locale").type(GraphQLString)); builder.field( newFieldDefinition().name("siteId").description("Site Id").type(GraphQLString)); builder.field( newFieldDefinition().name("siteName").description("Site Name").type(GraphQLString)); builder.field( newFieldDefinition().name("context").description("Context").type(GraphQLString)); builder.field( newFieldDefinition().name("content").description("Content").type(ExtendedScalars.Object)); builder.field( newFieldDefinition().name("pageLayout").description("Page Layout Name").type(GraphQLString)); } public void createObjectType(Builder queryTypeBuilder, graphql.schema.GraphQLCodeRegistry.Builder codeRegistryBuilder) { GraphQLObjectType graphQLObjectType = this.createWebSiteByURL(); shGraphQLQTObjectFromURL.createQueryType(queryTypeBuilder, codeRegistryBuilder, graphQLObjectType); } }
9235d49feacabe8982d373b7068e87d44bbd627f
1,415
java
Java
examples/cassandra-kubernetes/src/main/java/org/apache/camel/example/kubernetes/jkube/RowProcessor.java
CodeEmpire/camel-examples
3d962b23faeaee0d5cbca3e527428f605fd8c049
[ "Apache-2.0" ]
249
2020-02-05T09:45:20.000Z
2022-03-28T21:49:53.000Z
examples/camel-example-cassandra-kubernetes/src/main/java/org/apache/camel/example/kubernetes/jkube/RowProcessor.java
JavaZhoujl/camel-examples
ee4f4752c5c0fed53163ae18c6e50fa9f8236325
[ "Apache-2.0" ]
25
2020-02-12T13:41:32.000Z
2022-03-24T06:05:43.000Z
examples/camel-example-cassandra-kubernetes/src/main/java/org/apache/camel/example/kubernetes/jkube/RowProcessor.java
JavaZhoujl/camel-examples
ee4f4752c5c0fed53163ae18c6e50fa9f8236325
[ "Apache-2.0" ]
263
2020-02-06T03:24:30.000Z
2022-03-30T10:37:12.000Z
38.243243
82
0.740636
997,433
/* * 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.camel.example.kubernetes.jkube; import com.datastax.oss.driver.api.core.cql.Row; import org.apache.camel.Exchange; import org.apache.camel.Processor; import java.util.List; import java.util.stream.Collectors; public class RowProcessor implements Processor { @SuppressWarnings("unchecked") @Override public void process(Exchange exchange) { final List<Row> rows = exchange.getIn().getBody(List.class); exchange.getIn().setBody(rows.stream() .map(row -> String.format("%s-%s", row.getInt("id"), row.getString("name"))) .collect(Collectors.joining(",")) ); } }
9235d4c967acf7c46b53eb43549d010d08771b32
2,033
java
Java
microservice-modules/system-role/src/main/java/com/zhou/javakc/system/role/controller/RoleController.java
Liyingying0137/spring-cloud-javakc
c4d94d766b6f011b58b925d9acd5245cf86722ca
[ "MIT" ]
26
2019-10-17T06:51:07.000Z
2020-12-09T09:18:06.000Z
microservice-modules/system-role/src/main/java/com/zhou/javakc/system/role/controller/RoleController.java
Liyingying0137/spring-cloud-javakc
c4d94d766b6f011b58b925d9acd5245cf86722ca
[ "MIT" ]
null
null
null
microservice-modules/system-role/src/main/java/com/zhou/javakc/system/role/controller/RoleController.java
Liyingying0137/spring-cloud-javakc
c4d94d766b6f011b58b925d9acd5245cf86722ca
[ "MIT" ]
45
2019-10-17T07:57:55.000Z
2020-06-28T13:19:43.000Z
29.897059
96
0.693064
997,434
package com.zhou.javakc.system.role.controller; import com.zhou.javakc.component.data.entity.system.Role; import com.zhou.javakc.system.role.service.RoleService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author zhou * @version v0.0.1 * @date 2019-09-06 09:06 */ @Api(value = "系统管理-角色管理") @RestController @RequestMapping("system") public class RoleController { @Autowired private RoleService roleService; @ApiOperation(value="展示角色", notes="分页查询角色列表") @ApiImplicitParam(name = "entity", value = "角色详细实体Role", required = true, dataType = "Role") @PostMapping("role/query") public Page<Role> query(@RequestBody Role entity) { return roleService.findAll(entity); } @ApiOperation(value="展示角色", notes="获取全部角色列表") @GetMapping("role/query") public List<Role> query() { return roleService.findAll(); } @ApiOperation(value="添加角色", notes="根据Role对象创建角色") @ApiImplicitParam(name = "entity", value = "角色详细实体Role", required = true, dataType = "Role") @PostMapping("role") public Role save(@RequestBody Role entity) { return roleService.save(entity); } @ApiOperation(value="获取角色", notes="根据请求参数的roleId来获取角色详细信息") @ApiImplicitParam(name = "roleId", value = "角色主键ID", required = true, dataType = "String") @GetMapping("role/{roleId}") public Role load(@PathVariable String roleId) { return roleService.get(roleId); } @ApiOperation(value="删除角色", notes="根据请求参数的roleId来指定删除角色") @ApiImplicitParam(name = "roleId", value = "角色主键ID", required = true, dataType = "String") @DeleteMapping("role/{roleId}") public String delete(@PathVariable String roleId) { roleService.delete(roleId); return ""; } }
9235d4d0bdb1f5e2c04827ba20e652de3cb00188
1,617
java
Java
src/main/java/com/rbkmoney/dark/api/util/MathUtils.java
rbkmoney/dark-api
c58ef15b8e6777ca5d44d9e5eff268f6c2ab4389
[ "Apache-2.0" ]
3
2020-03-20T22:14:55.000Z
2021-01-25T15:58:57.000Z
src/main/java/com/rbkmoney/dark/api/util/MathUtils.java
rbkmoney/dark-api
c58ef15b8e6777ca5d44d9e5eff268f6c2ab4389
[ "Apache-2.0" ]
2
2020-10-28T12:33:51.000Z
2021-07-30T12:14:13.000Z
src/main/java/com/rbkmoney/dark/api/util/MathUtils.java
rbkmoney/dark-api
c58ef15b8e6777ca5d44d9e5eff268f6c2ab4389
[ "Apache-2.0" ]
3
2020-03-20T09:58:43.000Z
2021-12-07T09:07:52.000Z
36.75
104
0.698825
997,435
package com.rbkmoney.dark.api.util; import com.rbkmoney.cabi.base.Rational; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; @RequiredArgsConstructor(access = AccessLevel.NONE) public class MathUtils { public static Rational covertToRational(BigDecimal value) { BigInteger denominator = value.scale() > 0 ? BigInteger.TEN.pow(value.scale()) : BigInteger.ONE; BigInteger numerator = value.remainder(BigDecimal.ONE) .movePointRight(value.scale()).toBigInteger() .add(value.toBigInteger().multiply(denominator)); if (numerator.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) { throw new ArithmeticException("Too big numerator value: " + numerator); } if (denominator.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) { throw new ArithmeticException("Too big denominator value: " + denominator); } return new Rational(numerator.longValue(), denominator.longValue()); } public static BigDecimal convertFromRational(Rational rational) { return convertFromRational(rational, null); } public static BigDecimal convertFromRational(Rational rational, Integer scale) { BigDecimal numerator = BigDecimal.valueOf(rational.p); BigDecimal denominator = BigDecimal.valueOf(rational.q); if (scale != null) { return numerator.divide(denominator, scale, RoundingMode.HALF_UP); } return numerator.divide(denominator); } }
9235d5531557a3a8de108bd281438413de9ce080
1,931
java
Java
src/main/java/seedu/address/model/exercise/Calories.java
Nauman-S/tp
98e64ee519a76d21686a9c6d4261716cb1fe99c5
[ "MIT" ]
null
null
null
src/main/java/seedu/address/model/exercise/Calories.java
Nauman-S/tp
98e64ee519a76d21686a9c6d4261716cb1fe99c5
[ "MIT" ]
null
null
null
src/main/java/seedu/address/model/exercise/Calories.java
Nauman-S/tp
98e64ee519a76d21686a9c6d4261716cb1fe99c5
[ "MIT" ]
null
null
null
26.452055
102
0.607975
997,436
package seedu.address.model.exercise; import static seedu.address.commons.util.AppUtil.checkArgument; public class Calories { public static final String MESSAGE_CONSTRAINTS = "Calories should be at least 1 digit long, or must be an integer"; /* * The first character must not be a whitespace, * otherwise " " (a blank string) becomes a valid input. */ public static final String VALIDATION_REGEX = "\\d+"; public final String value; /** * Constructs a {@code Calories}. * * @param calories A valid input. */ public Calories(String calories) { if (calories == null) { value = "0"; } else { checkArgument(isValidCalories(calories), MESSAGE_CONSTRAINTS); value = calories; } } /** * Returns true if a given string is a valid input. */ public static boolean isValidCalories(String test) { return test.matches(VALIDATION_REGEX); } @Override public String toString() { return value; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof seedu.address.model.exercise.Calories // instanceof handles nulls && value.equals(((Calories) other).value)); // state check } @Override public int hashCode() { return value.hashCode(); } /** * Subtracts a {@code Calories}. * * @param calories A valid input. */ public Calories subtract(Calories calories) { Integer currentCalories = Integer.parseInt(value); Integer removedCalories = Integer.parseInt(calories.value); Integer newCalorie = currentCalories - removedCalories; if (newCalorie < 0) { newCalorie = 0; } return new Calories(String.valueOf(newCalorie)); } }
9235d5cc1290cdf11a89780cbf32a37f434144bb
1,617
java
Java
third_party/java/jopt-simple/src/test/java/joptsimple/RequiredArgumentOptionSpecEqualsHashCodeTest.java
pbekambo/bazel.0.5.1
843dc1c2bd76315e78cb03ee21bad4bbebe9e6ea
[ "Apache-2.0" ]
2
2019-08-17T15:26:51.000Z
2019-11-17T13:16:30.000Z
third_party/java/jopt-simple/src/test/java/joptsimple/RequiredArgumentOptionSpecEqualsHashCodeTest.java
pbekambo/bazel.0.5.1
843dc1c2bd76315e78cb03ee21bad4bbebe9e6ea
[ "Apache-2.0" ]
null
null
null
third_party/java/jopt-simple/src/test/java/joptsimple/RequiredArgumentOptionSpecEqualsHashCodeTest.java
pbekambo/bazel.0.5.1
843dc1c2bd76315e78cb03ee21bad4bbebe9e6ea
[ "Apache-2.0" ]
1
2019-08-11T19:15:28.000Z
2019-08-11T19:15:28.000Z
38.642857
93
0.769563
997,437
/* The MIT License Copyright (c) 2004-2015 Paul R. Holser, Jr. 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 joptsimple; /** * @author <a href="mailto:ychag@example.com">Paul Holser</a> */ public class RequiredArgumentOptionSpecEqualsHashCodeTest extends AbstractOptionSpecFixture { @Override protected RequiredArgumentOptionSpec<?> createEqualOptionSpecInstance() { return new RequiredArgumentOptionSpec<Void>( "a" ); } @Override protected RequiredArgumentOptionSpec<?> createNotEqualOptionSpecInstance() { return new RequiredArgumentOptionSpec<Void>( "b" ); } }
9235d602b634b93501639cac20f1e23330403a32
14,400
java
Java
moe/natj/natj/natj-ctests/src/test/java/c/tests/natjgen/FunctionsWithPrimitivesTest.java
ark100/multi-os-engine
f71d66a58b3d7e5eb2a68541480b7a0d88c7b908
[ "Apache-2.0" ]
3
2016-08-25T03:26:16.000Z
2017-04-23T11:42:36.000Z
moe/natj/natj/natj-ctests/src/test/java/c/tests/natjgen/FunctionsWithPrimitivesTest.java
ark100/multi-os-engine
f71d66a58b3d7e5eb2a68541480b7a0d88c7b908
[ "Apache-2.0" ]
1
2016-11-23T03:11:01.000Z
2016-11-23T03:11:01.000Z
moe/natj/natj/natj-ctests/src/test/java/c/tests/natjgen/FunctionsWithPrimitivesTest.java
ark100/multi-os-engine
f71d66a58b3d7e5eb2a68541480b7a0d88c7b908
[ "Apache-2.0" ]
7
2016-09-10T02:19:04.000Z
2021-07-29T17:19:41.000Z
29.875519
72
0.562778
997,438
/* Copyright 2014-2016 Intel Corporation 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 c.tests.natjgen; import org.moe.natj.general.ptr.*; import org.junit.Assert; import org.junit.Test; import java.util.Random; import static c.binding.c.Globals.*; public class FunctionsWithPrimitivesTest { private static final int COUNT = 10; private static final int COUNT_N = COUNT - 1; private static final Random random = new Random(); @Test public void testBool() { boolean a = NGBoolCreate(random.nextBoolean()); boolean b = NGBoolCreate(!a); Assert.assertTrue(NGBoolCompare(a, a)); Assert.assertTrue(NGBoolCompare(b, b)); Assert.assertFalse(NGBoolCompare(a, b)); Assert.assertFalse(NGBoolCompare(b, a)); } @Test public void testBoolPtr() { // Create a BoolPtr a = NGBoolCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { a.setValue(idx, random.nextBoolean()); } a.setValue(COUNT_N, true); // Create b & compare a with b BoolPtr b = NGBoolCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, random.nextBoolean()); } b.setValue(COUNT_N, false); Assert.assertFalse(NGBoolArrayCompare(a, b, COUNT)); // Update b & compare a with b for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, a.getValue(idx)); } b.setValue(COUNT_N, true); Assert.assertTrue(NGBoolArrayCompare(a, b, COUNT)); // Free a & b NGBoolArrayFree(a); NGBoolArrayFree(b); } @Test public void testBoolPtrPtr() { // Create a BoolPtr a = NGBoolCreateArray(COUNT); for (int idx = 0; idx < COUNT; ++idx) { a.setValue(idx, random.nextBoolean()); } // Create b & compare a with b Ptr<BoolPtr> b = NGBoolCreateArrayRef(a); Assert.assertTrue(NGBoolArrayRefCompare(b, a, COUNT)); // Free a & b NGBoolArrayFree(a); NGBoolArrayRefFree(b); } @Test public void testByte() { byte a = NGByteCreate((byte) random.nextInt()); byte b = NGByteCreate((byte) (a + 50)); Assert.assertTrue(NGByteCompare(a, a)); Assert.assertTrue(NGByteCompare(b, b)); Assert.assertFalse(NGByteCompare(a, b)); Assert.assertFalse(NGByteCompare(b, a)); } @Test public void testBytePtr() { // Create a BytePtr a = NGByteCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { a.setValue(idx, (byte) random.nextInt()); } a.setValue(COUNT_N, (byte) 1); // Create b & compare a with b BytePtr b = NGByteCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, (byte) random.nextInt()); } b.setValue(COUNT_N, (byte) 0); Assert.assertFalse(NGByteArrayCompare(a, b, COUNT)); // Update b & compare a with b for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, a.getValue(idx)); } b.setValue(COUNT_N, (byte) 1); Assert.assertTrue(NGByteArrayCompare(a, b, COUNT)); // Free a & b NGByteArrayFree(a); NGByteArrayFree(b); } @Test public void testBytePtrPtr() { // Create a BytePtr a = NGByteCreateArray(COUNT); for (int idx = 0; idx < COUNT; ++idx) { a.setValue(idx, (byte) random.nextInt()); } // Create b & compare a with b Ptr<BytePtr> b = NGByteCreateArrayRef(a); Assert.assertTrue(NGByteArrayRefCompare(b, a, COUNT)); // Free a & b NGByteArrayFree(a); NGByteArrayRefFree(b); } @Test public void testShort() { short a = NGShortCreate((short) random.nextInt()); short b = NGShortCreate((short) (a + 50)); Assert.assertTrue(NGShortCompare(a, a)); Assert.assertTrue(NGShortCompare(b, b)); Assert.assertFalse(NGShortCompare(a, b)); Assert.assertFalse(NGShortCompare(b, a)); } @Test public void testShortPtr() { // Create a ShortPtr a = NGShortCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { a.setValue(idx, (short) random.nextInt()); } a.setValue(COUNT_N, (short) 1); // Create b & compare a with b ShortPtr b = NGShortCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, (short) random.nextInt()); } b.setValue(COUNT_N, (short) 0); Assert.assertFalse(NGShortArrayCompare(a, b, COUNT)); // Update b & compare a with b for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, a.getValue(idx)); } b.setValue(COUNT_N, (short) 1); Assert.assertTrue(NGShortArrayCompare(a, b, COUNT)); // Free a & b NGShortArrayFree(a); NGShortArrayFree(b); } @Test public void testShortPtrPtr() { // Create a ShortPtr a = NGShortCreateArray(COUNT); for (int idx = 0; idx < COUNT; ++idx) { a.setValue(idx, (short) random.nextInt()); } // Create b & compare a with b Ptr<ShortPtr> b = NGShortCreateArrayRef(a); Assert.assertTrue(NGShortArrayRefCompare(b, a, COUNT)); // Free a & b NGShortArrayFree(a); NGShortArrayRefFree(b); } @Test public void testChar() { char a = NGCharCreate((char) random.nextInt()); char b = NGCharCreate((char) (a + 50 % 0xFF)); Assert.assertTrue(NGCharCompare(a, a)); Assert.assertTrue(NGCharCompare(b, b)); Assert.assertFalse(NGCharCompare(a, b)); Assert.assertFalse(NGCharCompare(b, a)); } @Test public void testCharPtr() { // Create a CharPtr a = NGCharCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { a.setValue(idx, (char) random.nextInt()); } a.setValue(COUNT_N, (char) 1); // Create b & compare a with b CharPtr b = NGCharCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, (char) random.nextInt()); } b.setValue(COUNT_N, (char) 0); Assert.assertFalse(NGCharArrayCompare(a, b, COUNT)); // Update b & compare a with b for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, a.getValue(idx)); } b.setValue(COUNT_N, (char) 1); Assert.assertTrue(NGCharArrayCompare(a, b, COUNT)); // Free a & b NGCharArrayFree(a); NGCharArrayFree(b); } @Test public void testCharPtrPtr() { // Create a CharPtr a = NGCharCreateArray(COUNT); for (int idx = 0; idx < COUNT; ++idx) { a.setValue(idx, (char) random.nextInt()); } // Create b & compare a with b Ptr<CharPtr> b = NGCharCreateArrayRef(a); Assert.assertTrue(NGCharArrayRefCompare(b, a, COUNT)); // Free a & b NGCharArrayFree(a); NGCharArrayRefFree(b); } @Test public void testInt() { int a = NGIntCreate(random.nextInt()); int b = NGIntCreate(a + 50); Assert.assertTrue(NGIntCompare(a, a)); Assert.assertTrue(NGIntCompare(b, b)); Assert.assertFalse(NGIntCompare(a, b)); Assert.assertFalse(NGIntCompare(b, a)); } @Test public void testIntPtr() { // Create a IntPtr a = NGIntCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { a.setValue(idx, random.nextInt()); } a.setValue(COUNT_N, 1); // Create b & compare a with b IntPtr b = NGIntCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, random.nextInt()); } b.setValue(COUNT_N, 0); Assert.assertFalse(NGIntArrayCompare(a, b, COUNT)); // Update b & compare a with b for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, a.getValue(idx)); } b.setValue(COUNT_N, 1); Assert.assertTrue(NGIntArrayCompare(a, b, COUNT)); // Free a & b NGIntArrayFree(a); NGIntArrayFree(b); } @Test public void testIntPtrPtr() { // Create a IntPtr a = NGIntCreateArray(COUNT); for (int idx = 0; idx < COUNT; ++idx) { a.setValue(idx, random.nextInt()); } // Create b & compare a with b Ptr<IntPtr> b = NGIntCreateArrayRef(a); Assert.assertTrue(NGIntArrayRefCompare(b, a, COUNT)); // Free a & b NGIntArrayFree(a); NGIntArrayRefFree(b); } @Test public void testLong() { long a = NGLongCreate(random.nextLong()); long b = NGLongCreate(a + 50); Assert.assertTrue(NGLongCompare(a, a)); Assert.assertTrue(NGLongCompare(b, b)); Assert.assertFalse(NGLongCompare(a, b)); Assert.assertFalse(NGLongCompare(b, a)); } @Test public void testLongPtr() { // Create a LongPtr a = NGLongCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { a.setValue(idx, random.nextLong()); } a.setValue(COUNT_N, 1); // Create b & compare a with b LongPtr b = NGLongCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, random.nextLong()); } b.setValue(COUNT_N, 0); Assert.assertFalse(NGLongArrayCompare(a, b, COUNT)); // Update b & compare a with b for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, a.getValue(idx)); } b.setValue(COUNT_N, 1); Assert.assertTrue(NGLongArrayCompare(a, b, COUNT)); // Free a & b NGLongArrayFree(a); NGLongArrayFree(b); } @Test public void testLongPtrPtr() { // Create a LongPtr a = NGLongCreateArray(COUNT); for (int idx = 0; idx < COUNT; ++idx) { a.setValue(idx, random.nextLong()); } // Create b & compare a with b Ptr<LongPtr> b = NGLongCreateArrayRef(a); Assert.assertTrue(NGLongArrayRefCompare(b, a, COUNT)); // Free a & b NGLongArrayFree(a); NGLongArrayRefFree(b); } @Test public void testFloat() { float a = NGFloatCreate(random.nextFloat()); float b = NGFloatCreate(a + 50); Assert.assertTrue(NGFloatCompare(a, a)); Assert.assertTrue(NGFloatCompare(b, b)); Assert.assertFalse(NGFloatCompare(a, b)); Assert.assertFalse(NGFloatCompare(b, a)); } @Test public void testFloatPtr() { // Create a FloatPtr a = NGFloatCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { a.setValue(idx, random.nextFloat()); } a.setValue(COUNT_N, 1); // Create b & compare a with b FloatPtr b = NGFloatCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, random.nextFloat()); } b.setValue(COUNT_N, 0); Assert.assertFalse(NGFloatArrayCompare(a, b, COUNT)); // Update b & compare a with b for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, a.getValue(idx)); } b.setValue(COUNT_N, 1); Assert.assertTrue(NGFloatArrayCompare(a, b, COUNT)); // Free a & b NGFloatArrayFree(a); NGFloatArrayFree(b); } @Test public void testFloatPtrPtr() { // Create a FloatPtr a = NGFloatCreateArray(COUNT); for (int idx = 0; idx < COUNT; ++idx) { a.setValue(idx, random.nextFloat()); } // Create b & compare a with b Ptr<FloatPtr> b = NGFloatCreateArrayRef(a); Assert.assertTrue(NGFloatArrayRefCompare(b, a, COUNT)); // Free a & b NGFloatArrayFree(a); NGFloatArrayRefFree(b); } @Test public void testDouble() { double a = NGDoubleCreate(random.nextDouble()); double b = NGDoubleCreate(a + 50); Assert.assertTrue(NGDoubleCompare(a, a)); Assert.assertTrue(NGDoubleCompare(b, b)); Assert.assertFalse(NGDoubleCompare(a, b)); Assert.assertFalse(NGDoubleCompare(b, a)); } @Test public void testDoublePtr() { // Create a DoublePtr a = NGDoubleCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { a.setValue(idx, random.nextDouble()); } a.setValue(COUNT_N, 1); // Create b & compare a with b DoublePtr b = NGDoubleCreateArray(COUNT); for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, random.nextDouble()); } b.setValue(COUNT_N, 0); Assert.assertFalse(NGDoubleArrayCompare(a, b, COUNT)); // Update b & compare a with b for (int idx = 0; idx < COUNT_N; ++idx) { b.setValue(idx, a.getValue(idx)); } b.setValue(COUNT_N, 1); Assert.assertTrue(NGDoubleArrayCompare(a, b, COUNT)); // Free a & b NGDoubleArrayFree(a); NGDoubleArrayFree(b); } @Test public void testDoublePtrPtr() { // Create a DoublePtr a = NGDoubleCreateArray(COUNT); for (int idx = 0; idx < COUNT; ++idx) { a.setValue(idx, random.nextDouble()); } // Create b & compare a with b Ptr<DoublePtr> b = NGDoubleCreateArrayRef(a); Assert.assertTrue(NGDoubleArrayRefCompare(b, a, COUNT)); // Free a & b NGDoubleArrayFree(a); NGDoubleArrayRefFree(b); } }
9235d60507afdae87a85c13d539ca35e8a8b4a00
81
java
Java
inject-test/src/test/java/org/example/factory/OutSource.java
dinject/dinject
9a816c44ec79eecca7b72df21d0c1e348f299ec4
[ "Apache-2.0" ]
33
2018-11-29T10:29:57.000Z
2020-08-24T17:51:30.000Z
inject-test/src/test/java/org/example/factory/OutSource.java
dinject/dinject
9a816c44ec79eecca7b72df21d0c1e348f299ec4
[ "Apache-2.0" ]
41
2018-11-22T09:16:16.000Z
2020-08-28T00:51:29.000Z
inject-test/src/test/java/org/example/factory/OutSource.java
kanuka/kanuka
b19bdbea98f3e57574033bd268931f7b40f38a58
[ "Apache-2.0" ]
1
2019-06-05T07:54:37.000Z
2019-06-05T07:54:37.000Z
11.571429
28
0.740741
997,439
package org.example.factory; public interface OutSource { String source(); }
9235d60f60b2097d0598a6d9bc2c2324cdf2cb7d
1,184
java
Java
ungiorno-web/src/main/java/it/smartcommunitylab/ungiorno/model/SchoolObject.java
smartcommunitylab/sco.infanziadigitales
dea1036ffb8f6d14f6da6290c4045f3d9a45112e
[ "Apache-2.0" ]
null
null
null
ungiorno-web/src/main/java/it/smartcommunitylab/ungiorno/model/SchoolObject.java
smartcommunitylab/sco.infanziadigitales
dea1036ffb8f6d14f6da6290c4045f3d9a45112e
[ "Apache-2.0" ]
69
2015-08-27T15:40:18.000Z
2021-12-09T20:28:02.000Z
ungiorno-web/src/main/java/it/smartcommunitylab/ungiorno/model/SchoolObject.java
smartcommunitylab/sco.infanziadigitales
dea1036ffb8f6d14f6da6290c4045f3d9a45112e
[ "Apache-2.0" ]
null
null
null
28.878049
80
0.615709
997,440
/******************************************************************************* * Copyright 2015 Fondazione Bruno Kessler * * 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 it.smartcommunitylab.ungiorno.model; /** * @author raman * */ public class SchoolObject { private String appId; private String schoolId; public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getSchoolId() { return schoolId; } public void setSchoolId(String schoolId) { this.schoolId = schoolId; } }
9235d66fd00b463a7623098f87a715e718108792
676
java
Java
src/main/java/br/com/zup/ecommerce/config/security/token/LoginRequest.java
christian-moura/orange-talents-07-template-ecommerce
b717206d383df7d23aae4ed1eb0f16b4b96abc3a
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/zup/ecommerce/config/security/token/LoginRequest.java
christian-moura/orange-talents-07-template-ecommerce
b717206d383df7d23aae4ed1eb0f16b4b96abc3a
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/zup/ecommerce/config/security/token/LoginRequest.java
christian-moura/orange-talents-07-template-ecommerce
b717206d383df7d23aae4ed1eb0f16b4b96abc3a
[ "Apache-2.0" ]
null
null
null
26
87
0.755917
997,441
package br.com.zup.ecommerce.config.security.token; import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import javax.validation.constraints.NotBlank; public class LoginRequest { @JsonProperty @NotBlank private String email; @JsonProperty @NotBlank private String senha; public LoginRequest(String email, String senha) { this.email = email; this.senha = senha; } public UsernamePasswordAuthenticationToken CredentialsAuthenticationToken() { return new UsernamePasswordAuthenticationToken(this.email, this.senha); } }
9235d737af48eed14face89a09462a15369c1f26
1,901
java
Java
src/test/java/com/keyword/automation/bill/warehouse/Test005_Warehouse_TestWholeCheckBill.java
Airpy/keyWordDrivenAutoTest
80c0222bcc937b27a8fc96f1e2ddf03db45031f6
[ "Apache-2.0" ]
null
null
null
src/test/java/com/keyword/automation/bill/warehouse/Test005_Warehouse_TestWholeCheckBill.java
Airpy/keyWordDrivenAutoTest
80c0222bcc937b27a8fc96f1e2ddf03db45031f6
[ "Apache-2.0" ]
null
null
null
src/test/java/com/keyword/automation/bill/warehouse/Test005_Warehouse_TestWholeCheckBill.java
Airpy/keyWordDrivenAutoTest
80c0222bcc937b27a8fc96f1e2ddf03db45031f6
[ "Apache-2.0" ]
null
null
null
30.174603
87
0.667017
997,442
package com.keyword.automation.bill.warehouse; import com.keyword.automation.action.BrowserKeyword; import com.keyword.automation.base.utils.LogUtils; import com.keyword.automation.bean.BillCell; import com.keyword.automation.bean.BillHeader; import com.keyword.automation.customer.BillKeyword; import com.keyword.automation.customer.LoginKeyword; import com.keyword.automation.customer.MenuKeyword; import com.keyword.automation.bean.BillWhole; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import java.util.ArrayList; import java.util.List; /** * 入口:销售-制作单据-销售订单<br/> * 主要测试功能: * 1、新增销售订单 * * @author Amio_ */ public class Test005_Warehouse_TestWholeCheckBill { private static List<BillCell> billCellList = new ArrayList<BillCell>(); private static BillHeader billHeader = new BillHeader("测试仓库", "刘振峰"); private static BillCell billCellA_BASE = new BillCell(0.0,5.0); private static BillCell billCellA_PKG = new BillCell("商品档案A", "箱", "10"); private static BillCell billCellB_BASE = new BillCell("商品档案B", "瓶", "10"); static { billCellList.add(billCellA_BASE); billCellList.add(billCellA_PKG); billCellList.add(billCellB_BASE); } private static BillWhole billWhole = new BillWhole(billHeader, billCellList, null); @Before public void setUp() { LogUtils.info("--------------------测试预处理:登录系统并跳转报损单界面--------------------"); LoginKeyword.loginSystem(); MenuKeyword.selectMenu("仓库", "报损单"); } @Test // 测试新增销售单 public void test_AddSaleBill() { LogUtils.info("--------------------测试添加报损单--------------------"); BillKeyword.addBill("报损单", billWhole); } @After public void tearDown() { LogUtils.info("--------------------测试后处理--------------------"); BrowserKeyword.browserQuit(); } }
9235d7d0ef1fc21c9717c2ec2576947cbdc96dbe
1,947
java
Java
java/com/example/android/inventory/data/InventoryDbHelper.java
aBluePawn/androdInventoryApp
398c067a45936c7e7e36383312828233f32b3c1b
[ "MIT" ]
null
null
null
java/com/example/android/inventory/data/InventoryDbHelper.java
aBluePawn/androdInventoryApp
398c067a45936c7e7e36383312828233f32b3c1b
[ "MIT" ]
null
null
null
java/com/example/android/inventory/data/InventoryDbHelper.java
aBluePawn/androdInventoryApp
398c067a45936c7e7e36383312828233f32b3c1b
[ "MIT" ]
null
null
null
41.425532
117
0.721623
997,443
package com.example.android.inventory.data; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class InventoryDbHelper extends SQLiteOpenHelper { //the name of the database public static final String DATABASE_NAME = "inventory.db"; //set the database version public static final int DATA_BASE_VERSION = 1; // set the string that we will use to create the table - columns and data type public final String SQL_CREATE_BOOKS_ENTRIES = "CREATE TABLE " + InventoryContract.BooksEntry.TABLE_NAME + " (" + InventoryContract.BooksEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + InventoryContract.BooksEntry.COLUMN_BOOKS_TITLE + " TEXT NOT NULL," + InventoryContract.BooksEntry.COLUMN_BOOKS_AUTHOR + " TEXT NOT NULL," + InventoryContract.BooksEntry.COLUMN_BOOKS_PAGES_COUNT + " INTEGER NOT NULL," + InventoryContract.BooksEntry.COLUMN_BOOKS_YEAR_PUBLISHED + " INTEGER NOT NULL," + InventoryContract.BooksEntry.COLUMN_BOOKS_QUANTITY + " INTEGER NOT NULL DEFAULT 0," + InventoryContract.BooksEntry.COLUMN_BOOKS_PRICE + " REAL NOT NULL DEFAULT 0," + InventoryContract.BooksEntry.COLUMN_BOOKS_IMAGE + " TEXT)"; public final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS" + InventoryContract.BooksEntry.TABLE_NAME; // constructor public InventoryDbHelper(Context context) { super(context, DATABASE_NAME, null, DATA_BASE_VERSION); } @Override public void onCreate(SQLiteDatabase database) { createTable(database); } @Override public void onUpgrade(SQLiteDatabase database, int i, int i1) { database.execSQL(SQL_DELETE_ENTRIES); createTable(database); } private void createTable(SQLiteDatabase database) { database.execSQL(SQL_CREATE_BOOKS_ENTRIES); } }
9235d809ff84ba677821b84df357dc0fb3166749
1,649
java
Java
src/main/java/net/kamradtfamily/springbootboilerplate/data/Sample.java
AlexRogalskiy/SpringBootBoilerplate
be058ba2547a54a1bc47eb1d5d536300448e1519
[ "MIT" ]
null
null
null
src/main/java/net/kamradtfamily/springbootboilerplate/data/Sample.java
AlexRogalskiy/SpringBootBoilerplate
be058ba2547a54a1bc47eb1d5d536300448e1519
[ "MIT" ]
1
2022-02-18T11:35:53.000Z
2022-02-18T11:36:04.000Z
src/main/java/net/kamradtfamily/springbootboilerplate/data/Sample.java
AlexRogalskiy/SpringBootBoilerplate
be058ba2547a54a1bc47eb1d5d536300448e1519
[ "MIT" ]
null
null
null
34.354167
80
0.729533
997,444
/* * The MIT License * * Copyright 2018 Randal Kamradt * * 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 net.kamradtfamily.springbootboilerplate.data; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.immutables.value.Value; /** * * @author randalkamradt */ @Value.Immutable @JsonDeserialize(as = ImmutableSample.class) public interface Sample { public static Sample build(String val1, String val2) { return ImmutableSample.builder() .val1(val1) .val2(val2) .build(); } String val1(); String val2(); }
9235d96d6a6d9ff9fec15ace4b9e70d7a1a918c7
355
java
Java
src/main/java/com/hl/bootssm/config/MessCodeConstant.java
GodGrounp/springboot
4150f55d153638253b4dd5a69e143657d32eff45
[ "Apache-2.0" ]
2
2017-11-29T02:34:17.000Z
2018-06-13T07:27:39.000Z
src/main/java/com/hl/bootssm/config/MessCodeConstant.java
GodGrounp/springboot
4150f55d153638253b4dd5a69e143657d32eff45
[ "Apache-2.0" ]
null
null
null
src/main/java/com/hl/bootssm/config/MessCodeConstant.java
GodGrounp/springboot
4150f55d153638253b4dd5a69e143657d32eff45
[ "Apache-2.0" ]
null
null
null
27.307692
87
0.726761
997,445
package com.hl.bootssm.config; /** * @author Static */ public final class MessCodeConstant { /** * 系统错误 */ public final static String ERROR_SYSTEM = "ERROR_SYSTEM"; public final static String SYSTEM_CLIENTID_ERROR = "SYSTEM_CLIENTID_ERROR"; public final static String ERROR_SYSTEM_PARAM_FORMAT = "ERROR_SYSTEM_PARAM_FORMAT"; }
9235db24f4870b9d79133619905545ddc8dccffb
1,422
java
Java
src/main/java/com/in28minutes/rest/webservices/restfulwebwervices/user/User.java
vineeshst/springboot-rest
da8a0b1598c45ea9b19ec97c2931bc7b89cc9585
[ "MIT" ]
null
null
null
src/main/java/com/in28minutes/rest/webservices/restfulwebwervices/user/User.java
vineeshst/springboot-rest
da8a0b1598c45ea9b19ec97c2931bc7b89cc9585
[ "MIT" ]
null
null
null
src/main/java/com/in28minutes/rest/webservices/restfulwebwervices/user/User.java
vineeshst/springboot-rest
da8a0b1598c45ea9b19ec97c2931bc7b89cc9585
[ "MIT" ]
null
null
null
23.7
71
0.600563
997,446
package com.in28minutes.rest.webservices.restfulwebwervices.user; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.Past; import javax.validation.constraints.Size; import java.util.Date; @ApiModel(description = "All details about the user. ") public class User { private Long id; @Size(min = 2, message = "Name should have at least 2 characters") @ApiModelProperty(notes = "Name should have at least 2 characters") private String name; @Past @ApiModelProperty(notes = "Birth date should be in the past") private Date birthDate; public User() { } public User(Long id, String name, Date birthDate) { this.id = id; this.name = name; this.birthDate = birthDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", birthDate=" + birthDate + '}'; } }
9235dfc0bc7e68dc741c5ed673ab7e193a2ea59d
197
java
Java
src/main/java/code/javaee/sample/petclinic/PetClinicApplication.java
naotsugu/javaee-petclinic
186858f8391a19c7b2ffacce2ccfcce954a44141
[ "Apache-2.0" ]
1
2018-11-07T22:32:31.000Z
2018-11-07T22:32:31.000Z
src/main/java/code/javaee/sample/petclinic/PetClinicApplication.java
naotsugu/javaee-petclinic
186858f8391a19c7b2ffacce2ccfcce954a44141
[ "Apache-2.0" ]
null
null
null
src/main/java/code/javaee/sample/petclinic/PetClinicApplication.java
naotsugu/javaee-petclinic
186858f8391a19c7b2ffacce2ccfcce954a44141
[ "Apache-2.0" ]
null
null
null
19.7
55
0.807107
997,447
package code.javaee.sample.petclinic; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; @ApplicationPath("/app") public class PetClinicApplication extends Application { }
9235dffc93fa35d1d99f09f84023664dc1ea83c1
4,926
java
Java
src/test/java/at/nonblocking/maven/nonsnapshot/NonSnapshotCommitMojoTest.java
nonblocking/nonsnapshot-maven-plugin
f882994683e63784fddf048049a36e66f555a320
[ "Apache-1.1" ]
11
2015-04-28T12:03:33.000Z
2020-06-04T19:13:35.000Z
src/test/java/at/nonblocking/maven/nonsnapshot/NonSnapshotCommitMojoTest.java
nonblocking/nonsnapshot-maven-plugin
f882994683e63784fddf048049a36e66f555a320
[ "Apache-1.1" ]
4
2016-06-27T14:57:07.000Z
2017-07-11T11:50:44.000Z
src/test/java/at/nonblocking/maven/nonsnapshot/NonSnapshotCommitMojoTest.java
nonblocking/nonsnapshot-maven-plugin
f882994683e63784fddf048049a36e66f555a320
[ "Apache-1.1" ]
9
2015-08-31T13:30:57.000Z
2021-04-28T01:07:22.000Z
42.834783
153
0.715185
997,448
package at.nonblocking.maven.nonsnapshot; import static junit.framework.Assert.*; import static org.mockito.Mockito.*; import java.io.File; import java.io.PrintWriter; import java.util.Arrays; import org.apache.maven.project.MavenProject; import org.junit.Before; import org.junit.Test; public class NonSnapshotCommitMojoTest { private NonSnapshotCommitMojo nonSnapshotMojo = new NonSnapshotCommitMojo(); private ModuleTraverser mockModuleTraverser = mock(ModuleTraverser.class); private DependencyTreeProcessor mockDependencyTreeProcessor = mock(DependencyTreeProcessor.class); private MavenPomHandler mockMavenPomHandler = mock(MavenPomHandler.class); private ScmHandler mockScmHandler = mock(ScmHandler.class); private UpstreamDependencyHandler mockUpstreamDependencyHandler = mock(UpstreamDependencyHandler.class); @Before public void setupMojo() { MavenProject mavenProject = new MavenProject(); mavenProject.setFile(new File("target/pom.xml")); this.nonSnapshotMojo.setMavenProject(mavenProject); this.nonSnapshotMojo.setScmUser("foo"); this.nonSnapshotMojo.setScmPassword("bar"); this.nonSnapshotMojo.setDeferPomCommit(false); this.nonSnapshotMojo.setModuleTraverser(this.mockModuleTraverser); this.nonSnapshotMojo.setDependencyTreeProcessor(this.mockDependencyTreeProcessor); this.nonSnapshotMojo.setMavenPomHandler(this.mockMavenPomHandler); this.nonSnapshotMojo.setScmHandler(this.mockScmHandler); this.nonSnapshotMojo.setUpstreamDependencyHandler(this.mockUpstreamDependencyHandler); } @Test public void testCommit() throws Exception { File pomFilesToCommit = new File("target/nonSnapshotDirtyModules.txt"); File pom1 = new File("target/pom.xml").getAbsoluteFile(); File pom2 = new File("target/test1/pom.xml").getAbsoluteFile(); File pom3 = new File("target/test2/pom.xml").getAbsoluteFile(); File pom4 = new File("test3/pom.xml").getAbsoluteFile(); PrintWriter writer = new PrintWriter(pomFilesToCommit); writer.write("." + System.getProperty("line.separator")); writer.write("test1" + System.getProperty("line.separator")); writer.write("test2" + System.getProperty("line.separator")); writer.write("../test3" + System.getProperty("line.separator")); writer.close(); this.nonSnapshotMojo.execute(); verify(this.mockScmHandler).commitFiles(Arrays.asList(pom1, pom2, pom3, pom4), "Nonsnapshot Plugin: Version of 4 modules updated"); assertFalse(pomFilesToCommit.exists()); } @Test public void testCommitIgnoreDuplicateEntries() throws Exception { File pomFilesToCommit = new File("target/nonSnapshotDirtyModules.txt"); File pom1 = new File("target/test1/pom.xml").getAbsoluteFile(); File pom2 = new File("target/test2/pom.xml").getAbsoluteFile(); File pom3 = new File("target/test3/pom.xml").getAbsoluteFile(); PrintWriter writer = new PrintWriter(pomFilesToCommit); writer.write("test1" + System.getProperty("line.separator")); writer.write("test2" + System.getProperty("line.separator")); writer.write("test3" + System.getProperty("line.separator")); writer.write("test2" + System.getProperty("line.separator")); writer.close(); this.nonSnapshotMojo.execute(); verify(this.mockScmHandler).commitFiles(Arrays.asList(pom1, pom2, pom3), "Nonsnapshot Plugin: Version of 3 modules updated"); assertFalse(pomFilesToCommit.exists()); } @Test public void testDontFailOnCommitTrue() throws Exception { File pomFilesToCommit = new File("target/nonSnapshotDirtyModules.txt"); File pom1 = new File("target/test1/pom.xml"); PrintWriter writer = new PrintWriter(pomFilesToCommit); writer.write(pom1.getPath() + System.getProperty("line.separator")); writer.close(); doThrow(new RuntimeException("test")).when(this.mockScmHandler).commitFiles(anyList(), eq("Nonsnapshot Plugin: Version of 1 artifacts updated")); this.nonSnapshotMojo.setDontFailOnCommit(true); this.nonSnapshotMojo.execute(); } @Test(expected = RuntimeException.class) public void testDontFailOnCommitFalse() throws Exception { File pomFilesToCommit = new File("target/nonSnapshotDirtyModules.txt"); File pom1 = new File("target/test1/pom.xml"); PrintWriter writer = new PrintWriter(pomFilesToCommit); writer.write(pom1.getPath() + System.getProperty("line.separator")); writer.close(); doThrow(new RuntimeException("test")).when(this.mockScmHandler).commitFiles(anyList(), eq("Nonsnapshot Plugin: Version of 1 modules updated")); this.nonSnapshotMojo.setDontFailOnCommit(false); this.nonSnapshotMojo.execute(); } }
9235e00d454a8dcef45d08214e290a73c4b9e38b
172
java
Java
blog-system/blog-service/src/main/java/com/nf/services/imp/NFArticleModule.java
ketoo/NFBlog
c6e087fdf81f53f5c71a4e80c8d95b2bb1a5b6f9
[ "Apache-2.0" ]
null
null
null
blog-system/blog-service/src/main/java/com/nf/services/imp/NFArticleModule.java
ketoo/NFBlog
c6e087fdf81f53f5c71a4e80c8d95b2bb1a5b6f9
[ "Apache-2.0" ]
null
null
null
blog-system/blog-service/src/main/java/com/nf/services/imp/NFArticleModule.java
ketoo/NFBlog
c6e087fdf81f53f5c71a4e80c8d95b2bb1a5b6f9
[ "Apache-2.0" ]
null
null
null
17.2
56
0.761628
997,449
package com.nf.services.imp; import com.nf.services.NFIArticleModule; /** * Created by James on 8/11/18. */ public class NFArticleModule implements NFIArticleModule {}
9235e1c953826507eefb23210bf6ced5dd3852b7
471
java
Java
main/src/main/java/me/dropead2/tab/listener/PlayerListener.java
Dropead2/TabList-API
30271ef5ee55a154deee18c07c53b6d9d19334d0
[ "MIT" ]
2
2021-09-03T02:44:42.000Z
2021-10-17T09:08:52.000Z
main/src/main/java/me/dropead2/tab/listener/PlayerListener.java
Dropead2/TabList-API
30271ef5ee55a154deee18c07c53b6d9d19334d0
[ "MIT" ]
null
null
null
main/src/main/java/me/dropead2/tab/listener/PlayerListener.java
Dropead2/TabList-API
30271ef5ee55a154deee18c07c53b6d9d19334d0
[ "MIT" ]
null
null
null
24.789474
51
0.787686
997,450
package me.dropead2.tab.listener; import lombok.RequiredArgsConstructor; import me.dropead2.tab.TabHandler; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; @RequiredArgsConstructor public class PlayerListener implements Listener { private final TabHandler handler; @EventHandler public void onJoin(PlayerJoinEvent event) { this.handler.sendUpdate(event.getPlayer()); } }
9235e25ab3343d2f04576a072a3ffbf0139b9b64
410
java
Java
src/main/java/redis/clients/jedis/exceptions/InvalidURIException.java
sebdehne/jedis
83af8c19fd360f299eae7c54d7fc14f2a6cb3f6d
[ "MIT" ]
8,456
2015-01-02T02:31:37.000Z
2020-10-20T06:57:17.000Z
src/main/java/redis/clients/jedis/exceptions/InvalidURIException.java
sebdehne/jedis
83af8c19fd360f299eae7c54d7fc14f2a6cb3f6d
[ "MIT" ]
1,550
2015-01-01T03:34:02.000Z
2020-10-15T05:21:13.000Z
src/main/java/redis/clients/jedis/exceptions/InvalidURIException.java
sebdehne/jedis
83af8c19fd360f299eae7c54d7fc14f2a6cb3f6d
[ "MIT" ]
3,198
2015-01-02T06:58:09.000Z
2020-10-20T10:41:07.000Z
21.578947
68
0.756098
997,451
package redis.clients.jedis.exceptions; public class InvalidURIException extends JedisException { private static final long serialVersionUID = -781691993326357802L; public InvalidURIException(String message) { super(message); } public InvalidURIException(Throwable cause) { super(cause); } public InvalidURIException(String message, Throwable cause) { super(message, cause); } }
9235e2c765d7d34e157deb71d0552b53f81ba8ee
2,252
java
Java
src/main/java/com/heqilin/util/model/Constants.java
hqlsoftware/javaweb-utils
e8ee55f5bf7799e46eedf8209c92044faffa1265
[ "Apache-2.0" ]
null
null
null
src/main/java/com/heqilin/util/model/Constants.java
hqlsoftware/javaweb-utils
e8ee55f5bf7799e46eedf8209c92044faffa1265
[ "Apache-2.0" ]
2
2020-03-04T22:34:26.000Z
2020-03-18T11:22:20.000Z
src/main/java/com/heqilin/util/model/Constants.java
richlin2004/myutils_java
e8ee55f5bf7799e46eedf8209c92044faffa1265
[ "Apache-2.0" ]
null
null
null
22.52
89
0.690941
997,452
package com.heqilin.util.model; import java.io.File; /** * 常量 * * @author heqilin * date: 2019-01-15 **/ public class Constants { //region 分隔符常量 public static final String POINT_STR = "."; public static final String BLANK_STR = ""; public static final String SPACE_STR = " "; public static final String NEWLINE_STR = "\n"; public static final String SYS_SEPARATOR = File.separator; public static final String FILE_SEPARATOR = "/"; public static final String BRACKET_LEFT = "["; public static final String BRACKET_RIGHT = "]"; public static final String UNDERLINE = "_"; public static final String MINUS_STR = "-"; //endregion //region 编码格式 public static final String UTF8 = "UTF-8"; //endregion //region 文件后缀 public static final String EXCEL_XLS = ".xls"; public static final String EXCEL_XLSX = ".xlsx"; public static final String IMAGE_PNG = "png"; public static final String IMAGE_JPG = "jpg"; public static final String FILE_ZIP = ".zip"; public static final String FILE_GZ = ".gz"; //endregion //region io流 public static final int BUFFER_1024 = 1024; public static final int BUFFER_512 = 512; public static final String USER_DIR = "user.dir"; //endregion //region tesseract for java语言字库 public static final String ENG = "eng"; public static final String CHI_SIM = "chi_sim"; //endregion //region opencv public static final String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; public static final String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; //endregion //region my.utils相关 public static final String MYUTILS_CONFIG_PROPERTIES_URL = "my.util.properties"; public static final String MYUTILS_CONFIG_PROPERTIES_URL_EHCACHE = "ehcache.xml"; //endregion //region cms相关 public static final String CACHE_SHOPPING_CART="my_shoppingcart"; public static final String CACHE_SMS_CODE="my_smscode"; public static final String CACHE_USER_INFO="my_userinfo"; public static final String CACHE_MANAGER_INFO="my_managerinfo"; public static final String CACHE_CAPTCHA_CODE="my_captchacode"; //endregion }
9235e2dabad433dc0528dfd83d1e72397c5f41c2
8,093
java
Java
src/main/java/org/apache/hadoop/hbase/client/MultiPut.java
winter-ict/LCIndex
601f5fffb9798f9e481a990ef083d8b930605c40
[ "Apache-2.0" ]
407
2015-01-05T09:53:33.000Z
2021-11-09T00:49:19.000Z
src/main/java/org/apache/hadoop/hbase/client/MultiPut.java
weimingdefeng/hindex
9aa98d80543f069208f651322c38029d35d694ac
[ "Apache-2.0" ]
8
2015-04-08T04:16:57.000Z
2022-02-28T09:42:00.000Z
src/main/java/org/apache/hadoop/hbase/client/MultiPut.java
weimingdefeng/hindex
9aa98d80543f069208f651322c38029d35d694ac
[ "Apache-2.0" ]
206
2015-01-04T08:00:27.000Z
2021-08-31T06:42:20.000Z
34.147679
95
0.643025
997,453
/* * Copyright 2010 The Apache Software Foundation * * 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.hadoop.hbase.client; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HServerAddress; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.Writable; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; /** * @deprecated Use MultiAction instead * Data type class for putting multiple regions worth of puts in one RPC. */ public class MultiPut extends Operation implements Writable { public HServerAddress address; // client code ONLY // TODO make this configurable public static final int DEFAULT_MAX_PUT_OUTPUT = 10; // map of regions to lists of puts for that region. public Map<byte[], List<Put> > puts = new TreeMap<byte[], List<Put>>(Bytes.BYTES_COMPARATOR); /** * Writable constructor only. */ public MultiPut() {} /** * MultiPut for putting multiple regions worth of puts in one RPC. * @param a address */ public MultiPut(HServerAddress a) { address = a; } public int size() { int size = 0; for( List<Put> l : puts.values()) { size += l.size(); } return size; } public void add(byte[] regionName, Put aPut) { List<Put> rsput = puts.get(regionName); if (rsput == null) { rsput = new ArrayList<Put>(); puts.put(regionName, rsput); } rsput.add(aPut); } public Collection<Put> allPuts() { List<Put> res = new ArrayList<Put>(); for ( List<Put> pp : puts.values() ) { res.addAll(pp); } return res; } /** * Compile the table and column family (i.e. schema) information * into a String. Useful for parsing and aggregation by debugging, * logging, and administration tools. * @return Map */ @Override public Map<String, Object> getFingerprint() { Map<String, Object> map = new HashMap<String, Object>(); // for extensibility, we have a map of table information that we will // populate with only family information for each table Map<String, Map> tableInfo = new HashMap<String, Map>(); map.put("tables", tableInfo); for (Map.Entry<byte[], List<Put>> entry : puts.entrySet()) { // our fingerprint only concerns itself with which families are touched, // not how many Puts touch them, so we use this Set to do just that. Set<String> familySet; try { // since the puts are stored by region, we may have already // recorded families for this region. if that is the case, // we want to add to the existing Set. if not, we make a new Set. String tableName = Bytes.toStringBinary( HRegionInfo.parseRegionName(entry.getKey())[0]); if (tableInfo.get(tableName) == null) { Map<String, Object> table = new HashMap<String, Object>(); familySet = new TreeSet<String>(); table.put("families", familySet); tableInfo.put(tableName, table); } else { familySet = (Set<String>) tableInfo.get(tableName).get("families"); } } catch (IOException ioe) { // in the case of parse error, default to labeling by region Map<String, Object> table = new HashMap<String, Object>(); familySet = new TreeSet<String>(); table.put("families", familySet); tableInfo.put(Bytes.toStringBinary(entry.getKey()), table); } // we now iterate through each Put and keep track of which families // are affected in this table. for (Put p : entry.getValue()) { for (byte[] fam : p.getFamilyMap().keySet()) { familySet.add(Bytes.toStringBinary(fam)); } } } return map; } /** * Compile the details beyond the scope of getFingerprint (mostly * toMap from the Puts) into a Map along with the fingerprinted * information. Useful for debugging, logging, and administration tools. * @param maxCols a limit on the number of columns output prior to truncation * @return Map */ @Override public Map<String, Object> toMap(int maxCols) { Map<String, Object> map = getFingerprint(); Map<String, Object> tableInfo = (Map<String, Object>) map.get("tables"); int putCount = 0; for (Map.Entry<byte[], List<Put>> entry : puts.entrySet()) { // If the limit has been hit for put output, just adjust our counter if (putCount >= DEFAULT_MAX_PUT_OUTPUT) { putCount += entry.getValue().size(); continue; } List<Put> regionPuts = entry.getValue(); List<Map<String, Object>> putSummaries = new ArrayList<Map<String, Object>>(); // find out how many of this region's puts we can add without busting // the maximum int regionPutsToAdd = regionPuts.size(); putCount += regionPutsToAdd; if (putCount > DEFAULT_MAX_PUT_OUTPUT) { regionPutsToAdd -= putCount - DEFAULT_MAX_PUT_OUTPUT; } for (Iterator<Put> iter = regionPuts.iterator(); regionPutsToAdd-- > 0;) { putSummaries.add(iter.next().toMap(maxCols)); } // attempt to extract the table name from the region name String tableName = ""; try { tableName = Bytes.toStringBinary( HRegionInfo.parseRegionName(entry.getKey())[0]); } catch (IOException ioe) { // in the case of parse error, default to labeling by region tableName = Bytes.toStringBinary(entry.getKey()); } // since the puts are stored by region, we may have already // recorded puts for this table. if that is the case, // we want to add to the existing List. if not, we place a new list // in the map Map<String, Object> table = (Map<String, Object>) tableInfo.get(tableName); if (table == null) { // in case the Put has changed since getFingerprint's map was built table = new HashMap<String, Object>(); tableInfo.put(tableName, table); table.put("puts", putSummaries); } else if (table.get("puts") == null) { table.put("puts", putSummaries); } else { ((List<Map<String, Object>>) table.get("puts")).addAll(putSummaries); } } map.put("totalPuts", putCount); return map; } @Override public void write(DataOutput out) throws IOException { out.writeInt(puts.size()); for( Map.Entry<byte[],List<Put>> e : puts.entrySet()) { Bytes.writeByteArray(out, e.getKey()); List<Put> ps = e.getValue(); out.writeInt(ps.size()); for( Put p : ps ) { p.write(out); } } } @Override public void readFields(DataInput in) throws IOException { puts.clear(); int mapSize = in.readInt(); for (int i = 0 ; i < mapSize; i++) { byte[] key = Bytes.readByteArray(in); int listSize = in.readInt(); List<Put> ps = new ArrayList<Put>(listSize); for ( int j = 0 ; j < listSize; j++ ) { Put put = new Put(); put.readFields(in); ps.add(put); } puts.put(key, ps); } } }
9235e3a2e44191f4eb58c1a4fea99112e7ec4b41
3,444
java
Java
dragonite-forwarder/src/main/java/com/vecsight/dragonite/forwarder/network/server/ForwarderMuxHandler.java
tobyxdd/dragonite-java
52fa76fb2a1d27cee4bfe2805644af92fe411b87
[ "Apache-2.0" ]
920
2017-10-21T22:33:33.000Z
2022-03-16T17:14:57.000Z
dragonite-forwarder/src/main/java/com/vecsight/dragonite/forwarder/network/server/ForwarderMuxHandler.java
tobyxdd/dragonite-java
52fa76fb2a1d27cee4bfe2805644af92fe411b87
[ "Apache-2.0" ]
35
2017-10-22T04:28:23.000Z
2020-03-16T13:28:32.000Z
dragonite-forwarder/src/main/java/com/vecsight/dragonite/forwarder/network/server/ForwarderMuxHandler.java
tobyxdd/dragonite-java
52fa76fb2a1d27cee4bfe2805644af92fe411b87
[ "Apache-2.0" ]
128
2017-10-22T01:03:54.000Z
2021-04-13T12:43:31.000Z
38.266667
166
0.590592
997,454
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.forwarder.network.server; import com.vecsight.dragonite.forwarder.misc.ForwarderGlobalConstants; import com.vecsight.dragonite.forwarder.network.Pipe; import com.vecsight.dragonite.mux.conn.MultiplexedConnection; import com.vecsight.dragonite.mux.conn.Multiplexer; import com.vecsight.dragonite.mux.exception.MultiplexerClosedException; import org.pmw.tinylog.Logger; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; public class ForwarderMuxHandler { private final Multiplexer multiplexer; private final String clientName; private final SocketAddress clientAddress; private final InetSocketAddress forwardingAddress; public ForwarderMuxHandler(final Multiplexer multiplexer, final String clientName, final SocketAddress clientAddress, final InetSocketAddress forwardingAddress) { this.multiplexer = multiplexer; this.clientName = clientName; this.clientAddress = clientAddress; this.forwardingAddress = forwardingAddress; } public void run() throws MultiplexerClosedException, InterruptedException { MultiplexedConnection multiplexedConnection; while ((multiplexedConnection = multiplexer.acceptConnection()) != null) { final MultiplexedConnection finalMuxConn = multiplexedConnection; Logger.debug("New connection by client \"{}\" ({})", clientName, clientAddress.toString()); try { final Socket tcpSocket = new Socket(forwardingAddress.getAddress(), forwardingAddress.getPort()); final Thread pipeFromRemoteThread = new Thread(() -> { final Pipe pipeFromRemotePipe = new Pipe(ForwarderGlobalConstants.PIPE_BUFFER_SIZE); try { pipeFromRemotePipe.pipe(finalMuxConn, tcpSocket.getOutputStream()); } catch (final Exception e) { Logger.debug(e, "Pipe closed"); } finally { try { tcpSocket.close(); } catch (final IOException ignored) { } finalMuxConn.close(); } }, "FS-R2L"); pipeFromRemoteThread.start(); final Thread pipeFromLocalThread = new Thread(() -> { final Pipe pipeFromLocalPipe = new Pipe(ForwarderGlobalConstants.PIPE_BUFFER_SIZE); try { pipeFromLocalPipe.pipe(tcpSocket.getInputStream(), finalMuxConn); } catch (final Exception e) { Logger.debug(e, "Pipe closed"); } finally { try { tcpSocket.close(); } catch (final IOException ignored) { } finalMuxConn.close(); } }, "FS-L2R"); pipeFromLocalThread.start(); } catch (final IOException e) { Logger.error(e, "Unable to establish local connection"); finalMuxConn.close(); } } } }